src/Entity/Profile/Profile.php line 77

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by simpson <simpsonwork@gmail.com>
  4.  * Date: 2019-03-19
  5.  * Time: 15:36
  6.  */
  7. namespace App\Entity\Profile;
  8. use AngelGamez\TranslatableBundle\Entity\TranslatableValue;
  9. //use ApiPlatform\Core\Annotation\ApiProperty;
  10. use App\Entity\Account\Advertiser;
  11. use App\Entity\ApartmentsPricing;
  12. use App\Entity\ContainsDomainEvents;
  13. use App\Entity\Account\Customer;
  14. use App\Entity\DomainEventsRecorderTrait;
  15. use App\Entity\ExpressPricing;
  16. use App\Entity\IProvidesServices;
  17. use App\Entity\Location\City;
  18. use App\Entity\Location\MapCoordinate;
  19. use App\Entity\Location\Station;
  20. use App\Entity\Messengers;
  21. use App\Entity\PhoneCallRestrictions;
  22. use App\Entity\Profile\Comment\CommentByCustomer;
  23. use App\Entity\Profile\Confirmation\ModerationRequest;
  24. use App\Entity\Sales\Profile\AdBoardPlacement;
  25. use App\Entity\Sales\Profile\PlacementHiding;
  26. use App\Entity\Sales\Profile\TopPlacement;
  27. use App\Entity\Saloon\Saloon;
  28. use App\Entity\ProvidedServiceTrait;
  29. use App\Entity\TakeOutPricing;
  30. use App\Helper\TopCardTrait;
  31. use App\Repository\ProfileRepository;
  32. use Carbon\Carbon;
  33. use Carbon\CarbonImmutable;
  34. use Doctrine\Common\Collections\ArrayCollection;
  35. use Doctrine\Common\Collections\Collection;
  36. use Doctrine\ORM\Mapping as ORM;
  37. use Doctrine\ORM\Mapping\Index;
  38. //use ApiPlatform\Core\Annotation\ApiResource;
  39. //use ApiPlatform\Core\Annotation\ApiFilter;
  40. //use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
  41. //use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\RangeFilter;
  42. use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
  43. use Symfony\Component\Serializer\Annotation\Groups;
  44. use Gedmo\Mapping\Annotation as Gedmo;
  45. use App\Validator\Constraints\ValidPhoneForCountry as ValidPhoneForCountryAssert;
  46. use App\Validator\Constraints\PhoneNotBlack as PhoneNotBlackAssert;
  47. /**
  48.  * ApiResource(collectionOperations={"get"}, itemOperations={"get"}, normalizationContext={"groups"={"profile"}}, attributes={"pagination_client_enabled"=true, "pagination_client_items_per_page"=true})
  49.  * ApiFilter(SearchFilter::class, properties={"city": "exact", "providedServices": "exact"})
  50.  * ApiFilter(RangeFilter::class, properties={"personParameters.age", "personParameters.height", "personParameters.weight", "personParameters.breastSize", "apartmentsPricing.oneHourPrice"})
  51.  * @ValidPhoneForCountryAssert/ProtocolClass
  52.  * @PhoneNotBlackAssert/ProtocolClass
  53.  */
  54. #[Gedmo\SoftDeleteable(fieldName: "deletedAt", timeAware: true)]
  55. #[ORM\Table(name: 'profiles')]
  56. #[Index(name: 'idx_deleted_at', columns: ['deleted_at'])]
  57. #[Index(name: 'idx_created_at', columns: ['created_at'])]
  58. #[Index(name: 'idx_gender', columns: ['person_gender'])]
  59. #[Index(name: 'idx_apartments_one_hour_price', columns: ['apartments_one_hour_price'])]
  60. #[Index(name: 'idx_is_dummy', columns: ['is_dummy'])]
  61. #[Index(name: 'idx_city_deleted', columns: ['city_id', 'deleted_at'])]
  62. #[Index(name: 'idx_city_deleted_moderation', columns: ['city_id', 'deleted_at', 'moderation_status'])]
  63. #[Index(name: 'idx_city_masseur_deleted', columns: ['city_id', 'is_masseur', 'deleted_at'])]
  64. #[Index(name: 'idx_city_masseur_deleted_moderation', columns: ['city_id', 'is_masseur', 'deleted_at', 'moderation_status'])]
  65. #[Index(name: 'idx_city_deleted_gender', columns: ['city_id', 'deleted_at', 'person_gender'])]
  66. #[Index(name: 'idx_city_deleted_moderation_gender', columns: ['city_id', 'deleted_at', 'moderation_status', 'person_gender'])]
  67. #[Index(name: 'idx_city_masseur_deleted_gender', columns: ['city_id', 'is_masseur', 'deleted_at', 'person_gender'])]
  68. #[Index(name: 'idx_city_masseur_deleted_moderation_gender', columns: ['city_id', 'is_masseur', 'deleted_at', 'moderation_status', 'person_gender'])]
  69. #[Index(name: 'idx_saloon', columns: ['saloon_id'])]
  70. #[ORM\Entity(repositoryClass: ProfileRepository::class)]
  71. #[ORM\HasLifecycleCallbacks]
  72. class Profile implements ContainsDomainEvents, IProvidesServices
  73. {
  74.     use SoftDeleteableEntity;
  75.     use DomainEventsRecorderTrait;
  76.     use ProvidedServiceTrait;
  77.     use TopCardTrait;
  78.     const MODERATION_STATUS_NOT_PASSED = 0;
  79.     const MODERATION_STATUS_APPROVED = 1;
  80.     const MODERATION_STATUS_WAITING = 2;
  81.     const MODERATION_STATUS_REJECTED = 3;
  82.     #[ORM\Id]
  83.     #[ORM\Column(name: 'id', type: 'integer')]
  84.     #[ORM\GeneratedValue(strategy: 'AUTO')]
  85.     #[Groups(['preview', 'listing'])]
  86.     protected int $id;
  87.     #[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: true)]
  88.     #[ORM\ManyToOne(targetEntity: Advertiser::class, inversedBy: 'profiles')]
  89.     protected ?Advertiser $owner;
  90.     #[ORM\Column(name: 'is_dummy', type: 'boolean', options: ['default' => 0])]
  91.     protected bool $dummy = false;
  92.     /** @var TopPlacement[] */
  93.     #[ORM\OneToMany(targetEntity: TopPlacement::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  94.     protected Collection $topPlacements;
  95.     #[ORM\OneToOne(targetEntity: AdBoardPlacement::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  96.     protected ?AdBoardPlacement $adBoardPlacement = null;
  97.     #[ORM\OneToOne(targetEntity: PlacementHiding::class, mappedBy: 'profile', cascade: ['all'])]
  98.     protected ?PlacementHiding $placementHiding = null;
  99.     #[ORM\Column(name: 'uri_identity', type: 'string', length: 64)]
  100.     #[Groups(['preview', 'listing'])]
  101.     protected string $uriIdentity;
  102.     #[ORM\Column(name: 'name', type: 'translatable')]
  103.     #[Groups(['preview', 'listing'])]
  104.     protected TranslatableValue $name;
  105.     #[ORM\Column(name: 'description', type: 'translatable')]
  106.     #[Groups('preview')]
  107.     protected ?TranslatableValue $description = null;
  108.     #[ORM\Embedded(class: PersonParameters::class, columnPrefix: 'person_')]
  109.     #[Groups(['preview', 'listing'])]
  110.     protected PersonParameters $personParameters;
  111.     /** var ProfileService[] */
  112.     #[ORM\OneToMany(targetEntity: ProfileService::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  113.     #[ORM\Cache(usage: 'NONSTRICT_READ_WRITE', region: 'profiles')]
  114.     #[Groups(['preview', 'listing'])]
  115.     protected Collection $providedServices;
  116.     #[ORM\OneToMany(targetEntity: ProfileProvidedInventoryItem::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  117.     #[ORM\Cache(usage: 'NONSTRICT_READ_WRITE', region: 'profiles')]
  118.     #[Groups(['preview', 'listing'])]
  119.     protected Collection $providedInventoryItems;
  120.     /** @var int[] */
  121.     #[ORM\Column(name: 'client_types', type: 'simple_array', nullable: true)]
  122.     #[Groups('preview')]
  123.     protected ?array $clientTypes;
  124.     #[ORM\Column(name: 'phone_number', type: 'string', length: 24)]
  125.     #[Groups(['preview', 'listing'])]
  126.     protected string $phoneNumber;
  127.     #[ORM\Embedded(class: Messengers::class, columnPrefix: false)]
  128.     #[Groups(['preview', 'listing'])]
  129.     protected ?Messengers $messengers = null;
  130.     #[ORM\Embedded(class: PhoneCallRestrictions::class, columnPrefix: false)]
  131.     #[Groups('preview')]
  132.     protected ?PhoneCallRestrictions $phoneCallRestrictions = null;
  133.     #[ORM\Column(name: 'is_masseur', type: 'boolean')]
  134.     #[Groups(['preview', 'listing'])]
  135.     protected bool $masseur = false;
  136.     #[ORM\Embedded(class: ClientRestrictions::class, columnPrefix: false)]
  137.     #[Groups('preview')]
  138.     protected ?ClientRestrictions $clientRestrictions = null;
  139.     #[ORM\Embedded(class: ApartmentsPricing::class, columnPrefix: false)]
  140.     #[Groups('preview')]
  141.     protected ?ApartmentsPricing $apartmentsPricing = null;
  142.     #[ORM\Embedded(class: TakeOutPricing::class, columnPrefix: false)]
  143.     #[Groups('preview')]
  144.     protected ?TakeOutPricing $takeOutPricing = null;
  145.     #[ORM\Embedded(class: ExpressPricing::class, columnPrefix: false)]
  146.     #[Groups('preview')]
  147.     protected ?ExpressPricing $expressPricing = null;
  148.     #[ORM\Embedded(class: CarPricing::class, columnPrefix: false)]
  149.     #[Groups('preview')]
  150.     protected ?CarPricing $carPricing = null;
  151.     #[ORM\Column(name: 'extra_charge', type: 'integer', nullable: true)]
  152.     #[Groups('preview')]
  153.     protected ?int $extraCharge;
  154.     #[ORM\Column(name: 'prepayment', type: 'boolean', nullable: true)]
  155.     #[Groups('preview')]
  156.     protected ?bool $prepayment = null;
  157.     #[ORM\Column(name: 'prepayment_amount', type: 'integer', nullable: true)]
  158.     #[Groups('preview')]
  159.     protected ?int $prepaymentAmount = null;
  160.     #[ORM\Column(name: 'prepayment_comment', type: 'string', length: 512, nullable: true)]
  161.     #[Groups('preview')]
  162.     protected ?string $prepaymentComment = null;
  163.     /** @var Photo[] */
  164.     #[ORM\OneToMany(targetEntity: Photo::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  165.     #[Groups('preview')]
  166.     protected Collection $photos;
  167.     /** @var Selfie[] */
  168.     #[ORM\OneToMany(targetEntity: Selfie::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  169.     #[Groups('preview')]
  170.     protected Collection $selfies;
  171.     /** @var Video[] */
  172.     #[ORM\OneToMany(targetEntity: Video::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  173.     #[Groups('preview')]
  174.     protected Collection $videos;
  175.     #[ORM\OneToMany(targetEntity: FileProcessingTask::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  176.     protected Collection $processingFiles;
  177.     #[ORM\OneToOne(targetEntity: AdminApprovalPhoto::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  178.     protected ?AdminApprovalPhoto $adminApprovalPhoto = null;
  179.     #[ORM\OneToOne(targetEntity: Avatar::class, mappedBy: 'profile', cascade: ['all'], orphanRemoval: true)]
  180.     #[Groups(['preview', 'listing'])]
  181.     protected ?Avatar $avatar = null;
  182.     /** @var CommentByCustomer[] */
  183.     #[ORM\OneToMany(targetEntity: CommentByCustomer::class, mappedBy: 'profile')]
  184.     #[Groups('preview')]
  185.     protected Collection $comments;
  186.     #[ORM\Column(name: 'is_approved', type: 'boolean')]
  187.     #[Groups(['preview', 'listing'])]
  188.     protected bool $approved = false;
  189.     #[ORM\Column(name: 'moderation_status', type: 'integer')]
  190.     #[Groups('preview')]
  191.     protected int $moderationStatus = 0;
  192.     #[ORM\JoinColumn(name: 'city_id', referencedColumnName: 'id')]
  193.     #[ORM\ManyToOne(targetEntity: City::class)]
  194.     #[ORM\Cache(usage: 'NONSTRICT_READ_WRITE', region: 'profiles')]
  195.     #[Groups(['preview', 'listing'])]
  196.     protected City $city;
  197.     /** @var Station[] */
  198.     //, indexBy="id"
  199.     #[ORM\JoinTable(name: 'profile_stations')]
  200.     #[ORM\JoinColumn(name: 'profile_id', referencedColumnName: 'id')]
  201.     #[ORM\InverseJoinColumn(name: 'station_id', referencedColumnName: 'id')]
  202.     #[ORM\ManyToMany(targetEntity: Station::class)]
  203.     #[Groups(['preview', 'listing'])]
  204.     #[ORM\Cache(usage: 'NONSTRICT_READ_WRITE', region: 'profiles')]
  205.     protected Collection $stations;
  206.     #[ORM\Embedded(class: MapCoordinate::class, columnPrefix: false)] // ApiProperty()
  207.     #[Groups(['preview', 'listing'])]
  208.     protected ?MapCoordinate $mapCoordinate;
  209.     #[ORM\Column(name: 'created_at', type: 'datetimetz_immutable', nullable: true)]
  210.     #[Groups('preview')]
  211.     protected ?\DateTimeImmutable $createdAt;
  212.     #[Gedmo\Timestampable(on: "change", field: ["name", "description", "personParameters", "providedServices", "clientTypes", "phoneNumber", "messengers", "phoneCallrestrictions", "masseur", "clientRestrictions", "apartmentsPricing", "takeOutPricing", "expressPricing", "carPricing", "extraCharge", "prepayment", "prepaymentAmount", "prepaymentComment", "photos", "selfies", "videos", "avatar", "stations", "mapCoordinate"])]
  213.     #[ORM\Column(name: 'updated_at', type: 'datetimetz_immutable', nullable: true)]
  214.     #[Groups('preview')]
  215.     protected ?\DateTimeImmutable $updatedAt;
  216.     #[ORM\Column(name: 'inactivated_at', type: 'datetimetz_immutable', nullable: true)]
  217.     protected ?\DateTimeImmutable $inactivatedAt;
  218.     private bool $draft = false;
  219.     #[ORM\Column(name: 'seo', type: 'json', nullable: true)]
  220.     #[Groups(['preview', 'listing'])]
  221.     private ?array $seo = null;
  222.     #[ORM\ManyToOne(targetEntity: Station::class)]
  223.     #[ORM\JoinColumn(name: 'primary_station_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
  224.     #[Groups(['preview', 'listing'])]
  225.     #[ORM\Cache(usage: 'READ_ONLY')]
  226.     private ?Station $primaryStation = null;
  227.     #[ORM\ManyToOne(targetEntity: Saloon::class, inversedBy: 'profiles')]
  228.     #[ORM\JoinColumn(name: 'saloon_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
  229.     private ?Saloon $saloon = null;
  230.     #[ORM\Column(type: 'smallint', options: ['default' => 0])]
  231.     private int $deleteMode = 0;
  232.     protected function __construct(?\DateTimeImmutable $createdAt)
  233.     {
  234.         $this->draft = true;
  235.         $this->createdAt = $createdAt;
  236.         $this->photos = new ArrayCollection();
  237.         $this->selfies = new ArrayCollection();
  238.         $this->videos = new ArrayCollection();
  239.         $this->processingFiles = new ArrayCollection();
  240.         $this->comments = new ArrayCollection();
  241.         $this->topPlacements = new ArrayCollection();
  242.         $this->providedServices = new ArrayCollection();
  243.         $this->providedInventoryItems = new ArrayCollection();
  244.         $this->stations = new ArrayCollection();
  245.         $this->inactivatedAt = CarbonImmutable::now();
  246.     }
  247.     public static function draft(?\DateTimeImmutable $createdAt = null, ?bool $dummy = null): self
  248.     {
  249.         $profile = new static($createdAt);
  250.         if (null !== $dummy)
  251.             $profile->dummy = $dummy;
  252.         return $profile;
  253.     }
  254.     public static function create(string $uriIdentity, ?\DateTimeImmutable $createdAt = null): self
  255.     {
  256.         $profile = new static($createdAt);
  257.         $profile->defineUriIdentity($uriIdentity);
  258.         $profile->toggleMasseur(false);
  259.         return $profile;
  260.     }
  261.     public function defineUriIdentity(string $uriIdentity): void
  262.     {
  263.         if (!$this->isDraft()) {
  264.             throw new \DomainException('Profile is already created and can\'t change its URI.');
  265.         }
  266.         $this->uriIdentity = $uriIdentity;
  267.         $this->draft = false;
  268.     }
  269.     public function isDraft(): bool
  270.     {
  271.         return $this->draft;
  272.     }
  273.     public function toggleMasseur(bool $isMasseur): void
  274.     {
  275.         if ($this->masseur !== $isMasseur && (null !== $this->adBoardPlacement && false == $this->adBoardPlacement->getType()->isFree())) {
  276.             throw new \DomainException('Impossible to toggle profile type while it is displaying on adboard.');
  277.         }
  278.         $this->masseur = $isMasseur;
  279.     }
  280.     public static function createMasseur(string $uriIdentity, ?\DateTimeImmutable $createdAt = null): self
  281.     {
  282.         $profile = new static($createdAt);
  283.         $profile->defineUriIdentity($uriIdentity);
  284.         $profile->toggleMasseur(true);
  285.         return $profile;
  286.     }
  287.     public function isOwnedBy(Advertiser $account): bool
  288.     {
  289.         return $account->getId() === $this->owner->getId();
  290.     }
  291.     public function getId(): int
  292.     {
  293.         return $this->id;
  294.     }
  295.     public function setBio(TranslatableValue $name, TranslatableValue $description): void
  296.     {
  297.         $this->name = $name;
  298.         $this->description = $description;
  299.     }
  300.     public function setLocation(City $city, $stations, ?MapCoordinate $mapCoordinate): void
  301.     {
  302.         if (!$this->isDraft() && !$this->city->equals($city)) {
  303.             throw new \DomainException('City change for a saved profile is forbidden.');
  304.         }
  305.         $this->city = $city;
  306.         $this->changeStations($stations);
  307.         $this->normalizePrimaryStation();
  308.         $this->mapCoordinate = $mapCoordinate;
  309.     }
  310.     protected function changeStations($stations)
  311.     {
  312.         if (null === $stations)
  313.             return;
  314.         if (false === is_array($stations) && false === is_iterable($stations))
  315.             throw new \InvalidArgumentException('Stations list should be either an array or an ArrayCollection');
  316.         $stationsArray = is_iterable($stations) && !is_array($stations) ? iterator_to_array($stations) : $stations;
  317.         $stations = [];
  318.         foreach ($stationsArray as $station) {
  319.             $stations[$station->getId()] = $station;
  320.         }
  321.         $stationIds = array_map(function (Station $station): int {
  322.             return $station->getId();
  323.         }, $stations);
  324.         $existingStationIds = $this->stations->map(function (Station $station): int {
  325.             return $station->getId();
  326.         })->getValues();
  327.         $stationIdsToAdd = array_diff($stationIds, $existingStationIds);
  328.         $stationIdsToRemove = array_diff($existingStationIds, $stationIds);
  329.         foreach ($stationIdsToAdd as $stationId) {
  330.             $this->stations->add($stations[$stationId]);
  331.         }
  332.         foreach ($stationIdsToRemove as $stationId) {
  333.             $this->stations->remove($stationId);
  334.         }
  335.     }
  336.     public function normalizePrimaryStation(): void
  337.     {
  338.         if ($this->stations->isEmpty()) {
  339.             $this->primaryStation = null;
  340.             return;
  341.         }
  342.         if ($this->primaryStation === null || !$this->stations->contains($this->primaryStation)) {
  343.             $this->primaryStation = $this->stations->first();
  344.         }
  345.     }
  346.     public function setEnabledProvidedServices($services): void
  347.     {
  348.         if (null !== $services) {
  349.             if (is_array($services)) {
  350.                 $services = new ArrayCollection($services);
  351.             } elseif (!$services instanceof ArrayCollection) {
  352.                 if (is_iterable($services)) {
  353.                     $services = new ArrayCollection(iterator_to_array($services));
  354.                 } else {
  355.                     throw new \InvalidArgumentException('Services list should be either an array or an ArrayCollection');
  356.                 }
  357.             }
  358.             $this->providedServices = $services;
  359.         }
  360.     }
  361.     public function getProvidedInventoryItems(): Collection
  362.     {
  363.         return $this->providedInventoryItems;
  364.     }
  365.     public function getProvidedInventoryItemsGroupedByType(): array
  366.     {
  367.         $items = $this->providedInventoryItems->toArray();
  368.         usort(
  369.             $items,
  370.             function (ProfileProvidedInventoryItem $left, ProfileProvidedInventoryItem $right): int {
  371.                 return [
  372.                     ProfileInventoryItemType::getSortOrder($left->getItem()->getType()),
  373.                     $left->getItem()->getSort(),
  374.                     $left->getItem()->getId(),
  375.                 ] <=> [
  376.                     ProfileInventoryItemType::getSortOrder($right->getItem()->getType()),
  377.                     $right->getItem()->getSort(),
  378.                     $right->getItem()->getId(),
  379.                 ];
  380.             }
  381.         );
  382.         $groupedItems = [];
  383.         foreach ($items as $providedItem) {
  384.             $groupedItems[$providedItem->getItem()->getType()][] = $providedItem;
  385.         }
  386.         return $groupedItems;
  387.     }
  388.     public function removeProvidedInventoryItem(ProfileProvidedInventoryItem $providedItem): void
  389.     {
  390.         $this->providedInventoryItems->removeElement($providedItem);
  391.     }
  392.     public function provideInventoryItem(ProfileProvidedInventoryItem $providedItem): void
  393.     {
  394.         $existingSameItem = $this->providedInventoryItems->filter(
  395.             function (ProfileProvidedInventoryItem $existingProvidedItem) use ($providedItem): bool {
  396.                 return $existingProvidedItem->getItem()->getId() === $providedItem->getItem()->getId();
  397.             }
  398.         )->first();
  399.         if ($existingSameItem instanceof ProfileProvidedInventoryItem) {
  400.             $existingSameItem->updateComment($providedItem->getComment());
  401.             return;
  402.         }
  403.         $this->providedInventoryItems->add($providedItem);
  404.     }
  405.     public function setPhoneCallOptions(string $phoneNumber, ?PhoneCallRestrictions $restrictions, ?Messengers $messengers): void
  406.     {
  407.         $this->phoneNumber = $phoneNumber;
  408.         $this->phoneCallRestrictions = $restrictions;
  409.         $this->messengers = $messengers;
  410.     }
  411.     public function getSaloon(): ?Saloon
  412.     {
  413.         return $this->saloon;
  414.     }
  415.     public function attachToSaloon(?Saloon $saloon): void
  416.     {
  417.         $this->saloon = $saloon;
  418.     }
  419.     public function detachFromSaloon(): void
  420.     {
  421.         $this->attachToSaloon(null);
  422.     }
  423.     public function setPricing(?ApartmentsPricing $apartmentsPricing, ?TakeOutPricing $takeOutPricing, ?int $extraCharge, ?ExpressPricing $expressPricing = null, ?CarPricing $carPricing = null): void
  424.     {
  425.         $this->apartmentsPricing = $apartmentsPricing;
  426.         $this->takeOutPricing = $takeOutPricing;
  427.         $this->extraCharge = $extraCharge;
  428.         $this->expressPricing = $expressPricing;
  429.         $this->carPricing = $carPricing;
  430.     }
  431.     public function setPrepaymentOptions(?bool $prepayment, ?int $prepaymentAmount, ?string $prepaymentComment): void
  432.     {
  433.         $this->prepayment = $prepayment;
  434.         if ($prepayment !== true) {
  435.             $this->prepaymentAmount = null;
  436.             $this->prepaymentComment = null;
  437.             return;
  438.         }
  439.         $this->prepaymentAmount = $prepaymentAmount;
  440.         $this->prepaymentComment = $prepaymentComment;
  441.     }
  442.     public function isApproved(): bool
  443.     {
  444.         return $this->approved;
  445.     }
  446.     public function approve(): void
  447.     {
  448.         $this->approved = true;
  449.     }
  450.     public function unApprove(): void
  451.     {
  452.         $this->approved = false;
  453.     }
  454.     public function getOwner(): ?Advertiser
  455.     {
  456.         return $this->owner;
  457.     }
  458.     public function setOwner(Advertiser $owner): void
  459.     {
  460.         $this->owner = $owner;
  461.     }
  462.     public function hasOwner(): bool
  463.     {
  464.         return null !== $this->owner;
  465.     }
  466.     public function getTopPlacements(): Collection
  467.     {
  468.         return $this->topPlacements;
  469.     }
  470.     public function addTopPlacement(TopPlacement $topPlacement): void
  471.     {
  472.         $this->topPlacements->add($topPlacement);
  473.     }
  474.     public function getAdBoardPlacement(): ?AdBoardPlacement
  475.     {
  476.         return $this->adBoardPlacement;
  477.     }
  478.     public function setAdBoardPlacement(AdBoardPlacement $adBoardPlacement): void
  479.     {
  480.         $this->adBoardPlacement = $adBoardPlacement;
  481.     }
  482.     /**
  483.      * Анкета оплачена и выводится в общих списках на сайте
  484.      * или в ТОПе, то есть "АКТИВНА"
  485.      */
  486.     public function isActive(): bool
  487.     {
  488.         return null !== $this->adBoardPlacement || $this->hasRunningTopPlacement();
  489.     }
  490.     public function hasRunningTopPlacement(): bool
  491.     {
  492.         $now = new \DateTimeImmutable('now');
  493.         foreach ($this->topPlacements as /** @var TopPlacement $topPlacement */ $topPlacement) {
  494.             if ($topPlacement->getPlacedAt() <= $now && $now <= $topPlacement->getExpiresAt())
  495.                 return true;
  496.         }
  497.         return false;
  498.     }
  499.     public function getUriIdentity(): string
  500.     {
  501.         return $this->uriIdentity;
  502.     }
  503.     public function getName(): TranslatableValue
  504.     {
  505.         return $this->name;
  506.     }
  507.     public function getDescription(): ?TranslatableValue
  508.     {
  509.         return $this->description;
  510.     }
  511.     public function getPersonParameters(): PersonParameters
  512.     {
  513.         return $this->personParameters;
  514.     }
  515.     public function setPersonParameters(PersonParameters $personParameters): void
  516.     {
  517.         $this->personParameters = $personParameters;
  518.     }
  519.     public function getPhoneNumber(): string
  520.     {
  521.         return $this->phoneNumber;
  522.     }
  523.     //TODO return type
  524.     public function getPhoneCallRestrictions(): ?PhoneCallRestrictions
  525.     {
  526.         return $this->phoneCallRestrictions;
  527.     }
  528.     public function isMasseur(): bool
  529.     {
  530.         return $this->masseur;
  531.     }
  532.     //TODO return type
  533.     public function getClientRestrictions(): ?ClientRestrictions
  534.     {
  535.         return $this->clientRestrictions;
  536.     }
  537.     //TODO return type
  538.     public function setClientRestrictions(?ClientRestrictions $restrictions): void
  539.     {
  540.         $this->clientRestrictions = $restrictions;
  541.     }
  542.     //TODO return type
  543.     public function getApartmentsPricing(): ?ApartmentsPricing
  544.     {
  545.         return $this->apartmentsPricing;
  546.     }
  547.     public function getTakeOutPricing(): ?TakeOutPricing
  548.     {
  549.         return $this->takeOutPricing;
  550.     }
  551.     public function getExtraCharge(): ?int
  552.     {
  553.         return $this->extraCharge;
  554.     }
  555.     public function isPrepayment(): ?bool
  556.     {
  557.         return $this->prepayment;
  558.     }
  559.     public function isWithoutPrepayment(): bool
  560.     {
  561.         return $this->prepayment === false;
  562.     }
  563.     public function getPrepaymentAmount(): ?int
  564.     {
  565.         return $this->prepaymentAmount;
  566.     }
  567.     public function getPrepaymentComment(): ?string
  568.     {
  569.         return $this->prepaymentComment;
  570.     }
  571.     public function addPhoto(string $path, bool $isMain): Photo
  572.     {
  573.         $photos = $this->getPhotos();
  574.         $found = $photos->filter(function (Photo $photo) use ($path): bool {
  575.             return $path === $photo->getPath();
  576.         });
  577.         if (!$found->isEmpty())
  578.             return $found->first();
  579.         if (true === $isMain) {
  580.             $photos->forAll(function ($index, Photo $photo): true {
  581.                 $photo->unsetMain();
  582.                 return true;
  583.             });
  584.         }
  585.         $photo = new Photo($this, $path, $isMain);
  586.         $this->photos->add($photo);
  587.         return $photo;
  588.     }
  589.     /**
  590.      * @return Photo[]
  591.      */
  592.     public function getPhotos(): Collection
  593.     {
  594.         return $this->photos->filter(function ($mediaFile): bool {
  595.             return get_class($mediaFile) == Photo::class;
  596.         });
  597.     }
  598.     public function removePhoto(string $path): bool
  599.     {
  600.         foreach ($this->getPhotos() as $photo) {
  601.             if ($path === $photo->getPath()) {
  602.                 $this->photos->removeElement($photo);
  603.                 return true;
  604.             }
  605.         }
  606.         return false;
  607.     }
  608.     public function getMainPhotoOrFirstPhoto(): ?Photo
  609.     {
  610.         $photos = $this->getPhotos();
  611.         if ($photos->isEmpty()) {
  612.             return null;
  613.         }
  614.         $mainPhoto = $this->getMainPhoto();
  615.         if (null === $mainPhoto) {
  616.             $mainPhoto = $photos->first();
  617.         }
  618.         return $mainPhoto;
  619.     }
  620.     public function getMainPhoto(): ?Photo
  621.     {
  622.         $photos = $this->getPhotos();
  623.         if ($photos->isEmpty()) {
  624.             return null;
  625.         }
  626.         $mainPhoto = null;
  627.         $photos->forAll(function ($index, Photo $photo) use (&$mainPhoto): bool {
  628.             if ($photo->isMain()) {
  629.                 $mainPhoto = $photo;
  630.                 return false; // Stop the cycle
  631.             }
  632.             return true;
  633.         });
  634.         return $mainPhoto;
  635.     }
  636.     public function changeMainPhoto(string $path): void
  637.     {
  638.         $photos = $this->getPhotos();
  639.         $found = $photos->filter(function (Photo $photo) use ($path): bool {
  640.             return $path === $photo->getPath();
  641.         });
  642.         if ($found->isEmpty()) {
  643.             return;
  644.         }
  645.         $mainPhoto = $found->first();
  646.         $photos->forAll(function ($index, Photo $photo): true {
  647.             $photo->unsetMain();
  648.             return true;
  649.         });
  650.         $mainPhoto->setMain();
  651.     }
  652.     public function addSelfie(string $path): Selfie
  653.     {
  654.         $found = $this->getSelfies()->filter(function (Selfie $selfie) use ($path): bool {
  655.             return $path === $selfie->getPath();
  656.         });
  657.         if (!$found->isEmpty())
  658.             return $found->first();
  659.         $selfie = new Selfie($this, $path);
  660.         $this->selfies->add($selfie);
  661.         return $selfie;
  662.     }
  663.     /**
  664.      * @return Selfie[]
  665.      */
  666.     public function getSelfies(): Collection
  667.     {
  668.         return $this->selfies;
  669.     }
  670.     public function removeSelfie(string $path): bool
  671.     {
  672.         foreach ($this->getSelfies() as $selfie) {
  673.             if ($path === $selfie->getPath()) {
  674.                 $this->selfies->removeElement($selfie);
  675.                 return true;
  676.             }
  677.         }
  678.         return false;
  679.     }
  680.     public function getConfirmedVideos(): Collection
  681.     {
  682.         return $this->videos->filter(function ($mediaFile): bool {
  683.             if (!$mediaFile instanceof Video) {
  684.                 return false;
  685.             }
  686.             return $mediaFile->isConfirmed();
  687.         });
  688.     }
  689.     /**
  690.      * Храним только 1 видео для анкеты
  691.      */
  692.     public function addVideo(string $videoPath, ?string $posterPath = null): Video
  693.     {
  694.         $found = $this->getVideos()->filter(function (Video $video) use ($videoPath): bool {
  695.             return $videoPath === $video->getPath();
  696.         });
  697.         if (!$found->isEmpty())
  698.             return $found->first();
  699.         $video = new Video($this, $videoPath);
  700.         if (null !== $posterPath) {
  701.             $video->setPreviewPath($posterPath);
  702.         }
  703.         //теперь разрешаем много видео
  704.         //$this->videos->clear();
  705.         $this->videos->add($video);
  706.         return $video;
  707.     }
  708.     /**
  709.      * @return Video[]
  710.      */
  711.     public function getVideos(): Collection
  712.     {
  713.         return $this->videos->filter(function ($mediaFile): bool {
  714.             return ($mediaFile instanceof Video);
  715.         });
  716.     }
  717.     public function removeVideo(string $path): bool
  718.     {
  719.         foreach ($this->getVideos() as $video) {
  720.             if ($path === $video->getPath()) {
  721.                 $this->videos->removeElement($video);
  722.                 $this->photos->removeElement($video);
  723.                 return true;
  724.             }
  725.         }
  726.         return false;
  727.     }
  728.     /**
  729.      * Добавляет таск на обработку оригинала видео в подходящий формат
  730.      *
  731.      * @param string $path Путь к файлу оригинала относительно фс очередей
  732.      */
  733.     public function addRawVideo(string $path): FileProcessingTask
  734.     {
  735.         $file = new FileProcessingTask($this, $path);
  736.         $this->processingFiles->add($file);
  737.         return $file;
  738.     }
  739.     public function hasFilesInProcess(): bool
  740.     {
  741.         return $this->videosInProcess() > 0;
  742.     }
  743.     public function videosInProcess(): int
  744.     {
  745.         $inProcess = $this->processingFiles->filter(function (FileProcessingTask $task): bool {
  746.             return !$task->isCompleted();
  747.         });
  748.         return $inProcess->count();
  749.     }
  750.     public function isMediaProcessed(): bool
  751.     {
  752.         foreach ($this->videos as $video)
  753.             if (null === $video->getPreviewPath())
  754.                 return false;
  755.         return true;
  756.     }
  757.     public function getAvatar(): ?Avatar
  758.     {
  759.         return $this->avatar;
  760.     }
  761.     public function setAvatar(string $path): void
  762.     {
  763.         $this->avatar = new Avatar($this, $path);
  764.     }
  765.     public function removeAvatar(): bool
  766.     {
  767.         if (null == $this->avatar)
  768.             return false;
  769.         foreach ($this->photos as $photo) {
  770.             if ($this->avatar->getPath() === $photo->getPath()) {
  771.                 $this->photos->removeElement($photo);
  772.                 break;
  773.             }
  774.         }
  775.         $this->avatar = null;
  776.         return true;
  777.     }
  778.     /**
  779.      * @return CommentByCustomer[]
  780.      */
  781.     public function getComments(): Collection
  782.     {
  783.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  784.             return null == $comment->getParent();
  785.         });
  786.     }
  787.     /**
  788.      * @return CommentByCustomer[]
  789.      */
  790.     public function getCommentsOrderedByNotReplied(): array
  791.     {
  792.         $comments = $this->comments->filter(function (CommentByCustomer $comment): bool {
  793.             return null == $comment->getParent();
  794.         })->toArray();
  795.         usort($comments, function (CommentByCustomer $commentA, CommentByCustomer $commentB): int {
  796.             if ((null == $commentA->getLastCommentByAdvertiser() && null == $commentB->getLastCommentByAdvertiser())
  797.                 || (null != $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())) {
  798.                 if ($commentA->getCreatedAt() == $commentB->getCreatedAt())
  799.                     return $commentA->getId() > $commentB->getId() ? -1 : 1;
  800.                 else
  801.                     return $commentA->getCreatedAt() > $commentB->getCreatedAt() ? -1 : 1;
  802.             }
  803.             if (null == $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())
  804.                 return -1;
  805.             else
  806.                 return 1;
  807.         });
  808.         return $comments;
  809.     }
  810.     public function getCreatedAt(): ?\DateTimeImmutable
  811.     {
  812.         return $this->createdAt;
  813.     }
  814.     /**
  815.      * @return CommentByCustomer[]
  816.      */
  817.     public function getCommentsWithoutReply(): Collection
  818.     {
  819.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  820.             return null == $comment->getParent() && false == $comment->isCommentedByAdvertiser();
  821.         });
  822.     }
  823.     /**
  824.      * @return CommentByCustomer[]
  825.      */
  826.     public function getCommentsWithReply(): Collection
  827.     {
  828.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  829.             return null == $comment->getParent() && true == $comment->isCommentedByAdvertiser();
  830.         });
  831.     }
  832.     /**
  833.      * @return CommentByCustomer[]
  834.      */
  835.     public function getNewComments(): Collection
  836.     {
  837.         $weekAgo = CarbonImmutable::now()->sub('7 days');
  838.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  839.             return null == $comment->getParent()
  840.                 && (
  841.                     $comment->getCreatedAt() >= $weekAgo
  842.                     || null == $this->getCommentReply($comment)
  843.                 );
  844.         });
  845.     }
  846.     private function getCommentReply(CommentByCustomer $parent): ?CommentByCustomer
  847.     {
  848.         foreach ($this->comments as $comment)
  849.             if ($comment->getParent() == $parent)
  850.                 return $comment;
  851.         return null;
  852.     }
  853.     public function getOldComments(): Collection
  854.     {
  855.         $weekAgo = CarbonImmutable::now()->sub('7 days');
  856.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  857.             return null == $comment->getParent()
  858.                 && false == (
  859.                     $comment->getCreatedAt() >= $weekAgo
  860.                     || null == $this->getCommentReply($comment)
  861.                 );
  862.         });
  863.     }
  864.     public function getCommentFromUser(Customer $user): ?CommentByCustomer
  865.     {
  866.         foreach ($this->comments as $comment)
  867.             if (null == $comment->getParent() && null != $comment->getUser() && $user->getId() == $comment->getUser()->getId())
  868.                 return $comment;
  869.         return null;
  870.     }
  871.     //TODO return type
  872.     public function getCity(): City
  873.     {
  874.         return $this->city;
  875.     }
  876.     /**
  877.      * @return Station[]
  878.      */
  879.     public function getStations(): Collection
  880.     {
  881.         return $this->stations;
  882.     }
  883.     public function getMapCoordinate(): ?MapCoordinate
  884.     {
  885.         return $this->mapCoordinate;
  886.     }
  887.     public function getUpdatedAt(): ?\DateTimeImmutable
  888.     {
  889.         return $this->updatedAt;
  890.     }
  891.     public function setUpdatedAt(\DateTimeImmutable $updatedAt): void
  892.     {
  893.         $this->updatedAt = $updatedAt;
  894.     }
  895.     public function getModerationStatus(): int
  896.     {
  897.         return $this->moderationStatus;
  898.     }
  899.     public function setModerationStatus(int $status): void
  900.     {
  901.         if (self::MODERATION_STATUS_APPROVED === $status) {
  902.             throw new \RuntimeException(sprintf('Use %s::passModeration() method instead', static::class));
  903.         }
  904.         $validStatuses = [self::MODERATION_STATUS_NOT_PASSED, self::MODERATION_STATUS_APPROVED, self::MODERATION_STATUS_WAITING, self::MODERATION_STATUS_REJECTED];
  905.         if (false === array_search($status, $validStatuses))
  906.             throw new \LogicException('Trying to set an invalid moderation status');
  907.         $this->moderationStatus = $status;
  908.     }
  909.     public function isModerationPassed(): bool
  910.     {
  911.         return $this->moderationStatus == self::MODERATION_STATUS_APPROVED;
  912.     }
  913.     public function isModerationWaiting(): bool
  914.     {
  915.         return $this->moderationStatus == self::MODERATION_STATUS_WAITING;
  916.     }
  917.     public function isModerationRejected(): bool
  918.     {
  919.         return $this->moderationStatus == self::MODERATION_STATUS_REJECTED;
  920.     }
  921.     public function passModeration(?ModerationRequest $moderationRequest = null): void
  922.     {
  923.         $this->moderationStatus = self::MODERATION_STATUS_APPROVED;
  924.         $func = static function ($k, Photo|Video $file) use ($moderationRequest): bool {
  925.             if (!$file->isConfirmed()) {
  926.                 $file->passModeration($moderationRequest);
  927.             }
  928.             return true;
  929.         };
  930.         $this->videos->forAll($func);
  931.     }
  932.     public function delete(): void
  933.     {
  934.         $this->deletePlacementHiding();
  935.         $this->deleteFromAdBoard();
  936.         $now = new \DateTimeImmutable('now');
  937.         $toDelete = [];
  938.         foreach ($this->topPlacements as $topPlacement) {
  939.             if ($topPlacement->getExpiresAt() > $now)
  940.                 $toDelete[] = $topPlacement;
  941.         }
  942.         foreach ($toDelete as $topPlacement)
  943.             $this->topPlacements->removeElement($topPlacement);
  944.         $this->setDeletedAt(Carbon::now());
  945.     }
  946.     public function deletePlacementHiding(): void
  947.     {
  948.         $this->placementHiding = null;
  949.     }
  950.     public function deleteFromAdBoard(): void
  951.     {
  952.         $this->adBoardPlacement = null;
  953.     }
  954.     //TODO return type
  955.     public function undoDelete(): void
  956.     {
  957.         $this->setDeletedAt(); // will pass null by default
  958.     }
  959.     //TODO return type
  960.     public function deleteFromTopPlacement(): void
  961.     {
  962.         //здесь нужна логика отмены конретного размещения
  963. //        $this->topPlacement = null;
  964.     }
  965.     public function getExpressPricing(): ?ExpressPricing
  966.     {
  967.         return $this->expressPricing;
  968.     }
  969.     public function getCarPricing(): ?CarPricing
  970.     {
  971.         return $this->carPricing;
  972.     }
  973.     //TODO return type
  974.     /**
  975.      * @return int[]
  976.      */
  977.     public function getClientTypes(): array
  978.     {
  979.         return $this->clientTypes ?? [];
  980.     }
  981.     /**
  982.      * @param int[] $clientTypes
  983.      */
  984.     public function setClientTypes(array $clientTypes): void
  985.     {
  986.         $this->clientTypes = $clientTypes;
  987.     }
  988.     public function getMessengers(): ?Messengers
  989.     {
  990.         return $this->messengers;
  991.     }
  992.     public function getInactivatedAt(): ?\DateTimeImmutable
  993.     {
  994.         return $this->inactivatedAt;
  995.     }
  996.     public function setInactive(): void
  997.     {
  998.         $this->inactivatedAt = CarbonImmutable::now();
  999.     }
  1000.     public function undoInactive(): void
  1001.     {
  1002.         $this->inactivatedAt = null;
  1003.     }
  1004.     public function isHidden(): bool
  1005.     {
  1006.         return null !== $this->getPlacementHiding();
  1007.     }
  1008.     public function getPlacementHiding(): ?PlacementHiding
  1009.     {
  1010.         return $this->placementHiding;
  1011.     }
  1012.     public function setPlacementHiding(PlacementHiding $placementHiding): void
  1013.     {
  1014.         $this->placementHiding = $placementHiding;
  1015.     }
  1016.     public function hasSelfie(): bool
  1017.     {
  1018.         return $this->selfies->count() > 0;
  1019.     }
  1020.     public function hasVideo(): bool
  1021.     {
  1022.         return $this->videos->count() > 0;
  1023.     }
  1024.     public function isCommented(): bool
  1025.     {
  1026.         return $this->comments->count() > 0;
  1027.     }
  1028.     public function adminApprovalPhoto(): ?AdminApprovalPhoto
  1029.     {
  1030.         return $this->adminApprovalPhoto;
  1031.     }
  1032.     public function setAdminApprovalPhoto(?string $path): void
  1033.     {
  1034.         $this->adminApprovalPhoto = $path ? new AdminApprovalPhoto($this, $path) : null;
  1035.     }
  1036.     public function seo(): ?array
  1037.     {
  1038.         return $this->seo;
  1039.     }
  1040.     public function seoPhoneNumber(): ?string
  1041.     {
  1042.         return $this->seo['phone'] ?? null;
  1043.     }
  1044.     public function setSeoPhoneNumber(string $phoneNumber): void
  1045.     {
  1046.         if (null === $this->seo) {
  1047.             $this->seo = [];
  1048.         }
  1049.         $this->seo['phone'] = $phoneNumber;
  1050.     }
  1051.     public function getPrimaryStation(): ?Station
  1052.     {
  1053.         $station = $this->primaryStation ?? $this->getStations()->first();
  1054.         if (false === $station) {
  1055.             return null;
  1056.         }
  1057.         return $station;
  1058.     }
  1059.     public function setPrimaryStation(?Station $station): void
  1060.     {
  1061.         $this->primaryStation = $station;
  1062.         $this->normalizePrimaryStation();
  1063.     }
  1064.     public function getStationsSortedByPrimary(): array
  1065.     {
  1066.         $stations = $this->stations->toArray();
  1067.         if (!$this->primaryStation) {
  1068.             return $stations;
  1069.         }
  1070.         usort($stations, function (Station $a, Station $b) {
  1071.             if ($a->getId() === $this->primaryStation->getId()) return -1;
  1072.             if ($b->getId() === $this->primaryStation->getId()) return 1;
  1073.             return 0;
  1074.         });
  1075.         return $stations;
  1076.     }
  1077.     public function getDistricts(): array
  1078.     {
  1079.         $districts = [];
  1080.         $addedDistricts = [];
  1081.         foreach ($this->getStationsSortedByPrimary() as $station) {
  1082.             $district = $station->getDistrict();
  1083.             if (array_key_exists($district->getId(), $addedDistricts)) {
  1084.                 continue;
  1085.             }
  1086.             $districts[] = $district;
  1087.             $addedDistricts[$district->getId()] = true;
  1088.         }
  1089.         return $districts;
  1090.     }
  1091.     public function getDeleteMode(): int
  1092.     {
  1093.         return $this->deleteMode;
  1094.     }
  1095.     public function setDeleteMode(int $deleteMode): self
  1096.     {
  1097.         $this->deleteMode = $deleteMode;
  1098.         return $this;
  1099.     }
  1100.     public function isHardDeleted(): bool
  1101.     {
  1102.         return $this->deleteMode === 2;
  1103.     }
  1104. }