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.     /** @var Collection<int, ProfileName> */
  207.     #[ORM\JoinTable(name: 'profile_profile_names')]
  208.     #[ORM\JoinColumn(name: 'profile_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
  209.     #[ORM\InverseJoinColumn(name: 'profile_name_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
  210.     #[ORM\ManyToMany(targetEntity: ProfileName::class, inversedBy: 'profiles')]
  211.     protected Collection $profileNames;
  212.     #[ORM\Embedded(class: MapCoordinate::class, columnPrefix: false)] // ApiProperty()
  213.     #[Groups(['preview', 'listing'])]
  214.     protected ?MapCoordinate $mapCoordinate;
  215.     #[ORM\Column(name: 'created_at', type: 'datetimetz_immutable', nullable: true)]
  216.     #[Groups('preview')]
  217.     protected ?\DateTimeImmutable $createdAt;
  218.     #[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"])]
  219.     #[ORM\Column(name: 'updated_at', type: 'datetimetz_immutable', nullable: true)]
  220.     #[Groups('preview')]
  221.     protected ?\DateTimeImmutable $updatedAt;
  222.     #[ORM\Column(name: 'inactivated_at', type: 'datetimetz_immutable', nullable: true)]
  223.     protected ?\DateTimeImmutable $inactivatedAt;
  224.     private bool $draft = false;
  225.     #[ORM\Column(name: 'seo', type: 'json', nullable: true)]
  226.     #[Groups(['preview', 'listing'])]
  227.     private ?array $seo = null;
  228.     #[ORM\ManyToOne(targetEntity: Station::class)]
  229.     #[ORM\JoinColumn(name: 'primary_station_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
  230.     #[Groups(['preview', 'listing'])]
  231.     #[ORM\Cache(usage: 'READ_ONLY')]
  232.     private ?Station $primaryStation = null;
  233.     #[ORM\ManyToOne(targetEntity: Saloon::class, inversedBy: 'profiles')]
  234.     #[ORM\JoinColumn(name: 'saloon_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
  235.     private ?Saloon $saloon = null;
  236.     #[ORM\Column(type: 'smallint', options: ['default' => 0])]
  237.     private int $deleteMode = 0;
  238.     protected function __construct(?\DateTimeImmutable $createdAt)
  239.     {
  240.         $this->draft = true;
  241.         $this->createdAt = $createdAt;
  242.         $this->photos = new ArrayCollection();
  243.         $this->selfies = new ArrayCollection();
  244.         $this->videos = new ArrayCollection();
  245.         $this->processingFiles = new ArrayCollection();
  246.         $this->comments = new ArrayCollection();
  247.         $this->topPlacements = new ArrayCollection();
  248.         $this->providedServices = new ArrayCollection();
  249.         $this->providedInventoryItems = new ArrayCollection();
  250.         $this->stations = new ArrayCollection();
  251.         $this->profileNames = new ArrayCollection();
  252.         $this->inactivatedAt = CarbonImmutable::now();
  253.     }
  254.     public static function draft(?\DateTimeImmutable $createdAt = null, ?bool $dummy = null): self
  255.     {
  256.         $profile = new static($createdAt);
  257.         if (null !== $dummy)
  258.             $profile->dummy = $dummy;
  259.         return $profile;
  260.     }
  261.     public static function create(string $uriIdentity, ?\DateTimeImmutable $createdAt = null): self
  262.     {
  263.         $profile = new static($createdAt);
  264.         $profile->defineUriIdentity($uriIdentity);
  265.         $profile->toggleMasseur(false);
  266.         return $profile;
  267.     }
  268.     public function defineUriIdentity(string $uriIdentity): void
  269.     {
  270.         if (!$this->isDraft()) {
  271.             throw new \DomainException('Profile is already created and can\'t change its URI.');
  272.         }
  273.         $this->uriIdentity = $uriIdentity;
  274.         $this->draft = false;
  275.     }
  276.     public function isDraft(): bool
  277.     {
  278.         return $this->draft;
  279.     }
  280.     public function toggleMasseur(bool $isMasseur): void
  281.     {
  282.         if ($this->masseur !== $isMasseur && (null !== $this->adBoardPlacement && false == $this->adBoardPlacement->getType()->isFree())) {
  283.             throw new \DomainException('Impossible to toggle profile type while it is displaying on adboard.');
  284.         }
  285.         $this->masseur = $isMasseur;
  286.     }
  287.     public static function createMasseur(string $uriIdentity, ?\DateTimeImmutable $createdAt = null): self
  288.     {
  289.         $profile = new static($createdAt);
  290.         $profile->defineUriIdentity($uriIdentity);
  291.         $profile->toggleMasseur(true);
  292.         return $profile;
  293.     }
  294.     public function isOwnedBy(Advertiser $account): bool
  295.     {
  296.         return $account->getId() === $this->owner->getId();
  297.     }
  298.     public function getId(): int
  299.     {
  300.         return $this->id;
  301.     }
  302.     public function setBio(TranslatableValue $name, TranslatableValue $description): void
  303.     {
  304.         $this->name = $name;
  305.         $this->description = $description;
  306.     }
  307.     public function setLocation(City $city, $stations, ?MapCoordinate $mapCoordinate): void
  308.     {
  309.         if (!$this->isDraft() && !$this->city->equals($city)) {
  310.             throw new \DomainException('City change for a saved profile is forbidden.');
  311.         }
  312.         $this->city = $city;
  313.         $this->changeStations($stations);
  314.         $this->normalizePrimaryStation();
  315.         $this->mapCoordinate = $mapCoordinate;
  316.     }
  317.     protected function changeStations($stations)
  318.     {
  319.         if (null === $stations)
  320.             return;
  321.         if (false === is_array($stations) && false === is_iterable($stations))
  322.             throw new \InvalidArgumentException('Stations list should be either an array or an ArrayCollection');
  323.         $stationsArray = is_iterable($stations) && !is_array($stations) ? iterator_to_array($stations) : $stations;
  324.         $stations = [];
  325.         foreach ($stationsArray as $station) {
  326.             $stations[$station->getId()] = $station;
  327.         }
  328.         $stationIds = array_map(function (Station $station): int {
  329.             return $station->getId();
  330.         }, $stations);
  331.         $existingStationIds = $this->stations->map(function (Station $station): int {
  332.             return $station->getId();
  333.         })->getValues();
  334.         $stationIdsToAdd = array_diff($stationIds, $existingStationIds);
  335.         $stationIdsToRemove = array_diff($existingStationIds, $stationIds);
  336.         foreach ($stationIdsToAdd as $stationId) {
  337.             $this->stations->add($stations[$stationId]);
  338.         }
  339.         foreach ($stationIdsToRemove as $stationId) {
  340.             $this->stations->remove($stationId);
  341.         }
  342.     }
  343.     public function normalizePrimaryStation(): void
  344.     {
  345.         if ($this->stations->isEmpty()) {
  346.             $this->primaryStation = null;
  347.             return;
  348.         }
  349.         if ($this->primaryStation === null || !$this->stations->contains($this->primaryStation)) {
  350.             $this->primaryStation = $this->stations->first();
  351.         }
  352.     }
  353.     public function setEnabledProvidedServices($services): void
  354.     {
  355.         if (null !== $services) {
  356.             if (is_array($services)) {
  357.                 $services = new ArrayCollection($services);
  358.             } elseif (!$services instanceof ArrayCollection) {
  359.                 if (is_iterable($services)) {
  360.                     $services = new ArrayCollection(iterator_to_array($services));
  361.                 } else {
  362.                     throw new \InvalidArgumentException('Services list should be either an array or an ArrayCollection');
  363.                 }
  364.             }
  365.             $this->providedServices = $services;
  366.         }
  367.     }
  368.     public function getProvidedInventoryItems(): Collection
  369.     {
  370.         return $this->providedInventoryItems;
  371.     }
  372.     public function getProvidedInventoryItemsGroupedByType(): array
  373.     {
  374.         $items = $this->providedInventoryItems->toArray();
  375.         usort(
  376.             $items,
  377.             function (ProfileProvidedInventoryItem $left, ProfileProvidedInventoryItem $right): int {
  378.                 return [
  379.                     ProfileInventoryItemType::getSortOrder($left->getItem()->getType()),
  380.                     $left->getItem()->getSort(),
  381.                     $left->getItem()->getId(),
  382.                 ] <=> [
  383.                     ProfileInventoryItemType::getSortOrder($right->getItem()->getType()),
  384.                     $right->getItem()->getSort(),
  385.                     $right->getItem()->getId(),
  386.                 ];
  387.             }
  388.         );
  389.         $groupedItems = [];
  390.         foreach ($items as $providedItem) {
  391.             $groupedItems[$providedItem->getItem()->getType()][] = $providedItem;
  392.         }
  393.         return $groupedItems;
  394.     }
  395.     public function removeProvidedInventoryItem(ProfileProvidedInventoryItem $providedItem): void
  396.     {
  397.         $this->providedInventoryItems->removeElement($providedItem);
  398.     }
  399.     public function provideInventoryItem(ProfileProvidedInventoryItem $providedItem): void
  400.     {
  401.         $existingSameItem = $this->providedInventoryItems->filter(
  402.             function (ProfileProvidedInventoryItem $existingProvidedItem) use ($providedItem): bool {
  403.                 return $existingProvidedItem->getItem()->getId() === $providedItem->getItem()->getId();
  404.             }
  405.         )->first();
  406.         if ($existingSameItem instanceof ProfileProvidedInventoryItem) {
  407.             $existingSameItem->updateComment($providedItem->getComment());
  408.             return;
  409.         }
  410.         $this->providedInventoryItems->add($providedItem);
  411.     }
  412.     public function setPhoneCallOptions(string $phoneNumber, ?PhoneCallRestrictions $restrictions, ?Messengers $messengers): void
  413.     {
  414.         $this->phoneNumber = $phoneNumber;
  415.         $this->phoneCallRestrictions = $restrictions;
  416.         $this->messengers = $messengers;
  417.     }
  418.     public function getSaloon(): ?Saloon
  419.     {
  420.         return $this->saloon;
  421.     }
  422.     public function attachToSaloon(?Saloon $saloon): void
  423.     {
  424.         $this->saloon = $saloon;
  425.     }
  426.     public function detachFromSaloon(): void
  427.     {
  428.         $this->attachToSaloon(null);
  429.     }
  430.     public function setPricing(?ApartmentsPricing $apartmentsPricing, ?TakeOutPricing $takeOutPricing, ?int $extraCharge, ?ExpressPricing $expressPricing = null, ?CarPricing $carPricing = null): void
  431.     {
  432.         $this->apartmentsPricing = $apartmentsPricing;
  433.         $this->takeOutPricing = $takeOutPricing;
  434.         $this->extraCharge = $extraCharge;
  435.         $this->expressPricing = $expressPricing;
  436.         $this->carPricing = $carPricing;
  437.     }
  438.     public function setPrepaymentOptions(?bool $prepayment, ?int $prepaymentAmount, ?string $prepaymentComment): void
  439.     {
  440.         $this->prepayment = $prepayment;
  441.         if ($prepayment !== true) {
  442.             $this->prepaymentAmount = null;
  443.             $this->prepaymentComment = null;
  444.             return;
  445.         }
  446.         $this->prepaymentAmount = $prepaymentAmount;
  447.         $this->prepaymentComment = $prepaymentComment;
  448.     }
  449.     public function isApproved(): bool
  450.     {
  451.         return $this->approved;
  452.     }
  453.     public function approve(): void
  454.     {
  455.         $this->approved = true;
  456.     }
  457.     public function unApprove(): void
  458.     {
  459.         $this->approved = false;
  460.     }
  461.     public function getOwner(): ?Advertiser
  462.     {
  463.         return $this->owner;
  464.     }
  465.     public function setOwner(Advertiser $owner): void
  466.     {
  467.         $this->owner = $owner;
  468.     }
  469.     public function hasOwner(): bool
  470.     {
  471.         return null !== $this->owner;
  472.     }
  473.     public function getTopPlacements(): Collection
  474.     {
  475.         return $this->topPlacements;
  476.     }
  477.     public function addTopPlacement(TopPlacement $topPlacement): void
  478.     {
  479.         $this->topPlacements->add($topPlacement);
  480.     }
  481.     public function getAdBoardPlacement(): ?AdBoardPlacement
  482.     {
  483.         return $this->adBoardPlacement;
  484.     }
  485.     public function setAdBoardPlacement(AdBoardPlacement $adBoardPlacement): void
  486.     {
  487.         $this->adBoardPlacement = $adBoardPlacement;
  488.     }
  489.     /**
  490.      * Анкета оплачена и выводится в общих списках на сайте
  491.      * или в ТОПе, то есть "АКТИВНА"
  492.      */
  493.     public function isActive(): bool
  494.     {
  495.         return null !== $this->adBoardPlacement || $this->hasRunningTopPlacement();
  496.     }
  497.     public function hasRunningTopPlacement(): bool
  498.     {
  499.         $now = new \DateTimeImmutable('now');
  500.         foreach ($this->topPlacements as /** @var TopPlacement $topPlacement */ $topPlacement) {
  501.             if ($topPlacement->getPlacedAt() <= $now && $now <= $topPlacement->getExpiresAt())
  502.                 return true;
  503.         }
  504.         return false;
  505.     }
  506.     public function getUriIdentity(): string
  507.     {
  508.         return $this->uriIdentity;
  509.     }
  510.     public function getName(): TranslatableValue
  511.     {
  512.         return $this->name;
  513.     }
  514.     public function getDescription(): ?TranslatableValue
  515.     {
  516.         return $this->description;
  517.     }
  518.     public function getPersonParameters(): PersonParameters
  519.     {
  520.         return $this->personParameters;
  521.     }
  522.     public function setPersonParameters(PersonParameters $personParameters): void
  523.     {
  524.         $this->personParameters = $personParameters;
  525.     }
  526.     public function getPhoneNumber(): string
  527.     {
  528.         return $this->phoneNumber;
  529.     }
  530.     //TODO return type
  531.     public function getPhoneCallRestrictions(): ?PhoneCallRestrictions
  532.     {
  533.         return $this->phoneCallRestrictions;
  534.     }
  535.     public function isMasseur(): bool
  536.     {
  537.         return $this->masseur;
  538.     }
  539.     //TODO return type
  540.     public function getClientRestrictions(): ?ClientRestrictions
  541.     {
  542.         return $this->clientRestrictions;
  543.     }
  544.     //TODO return type
  545.     public function setClientRestrictions(?ClientRestrictions $restrictions): void
  546.     {
  547.         $this->clientRestrictions = $restrictions;
  548.     }
  549.     //TODO return type
  550.     public function getApartmentsPricing(): ?ApartmentsPricing
  551.     {
  552.         return $this->apartmentsPricing;
  553.     }
  554.     public function getTakeOutPricing(): ?TakeOutPricing
  555.     {
  556.         return $this->takeOutPricing;
  557.     }
  558.     public function getExtraCharge(): ?int
  559.     {
  560.         return $this->extraCharge;
  561.     }
  562.     public function isPrepayment(): ?bool
  563.     {
  564.         return $this->prepayment;
  565.     }
  566.     public function isWithoutPrepayment(): bool
  567.     {
  568.         return $this->prepayment === false;
  569.     }
  570.     public function getPrepaymentAmount(): ?int
  571.     {
  572.         return $this->prepaymentAmount;
  573.     }
  574.     public function getPrepaymentComment(): ?string
  575.     {
  576.         return $this->prepaymentComment;
  577.     }
  578.     public function addPhoto(string $path, bool $isMain): Photo
  579.     {
  580.         $photos = $this->getPhotos();
  581.         $found = $photos->filter(function (Photo $photo) use ($path): bool {
  582.             return $path === $photo->getPath();
  583.         });
  584.         if (!$found->isEmpty())
  585.             return $found->first();
  586.         if (true === $isMain) {
  587.             $photos->forAll(function ($index, Photo $photo): true {
  588.                 $photo->unsetMain();
  589.                 return true;
  590.             });
  591.         }
  592.         $photo = new Photo($this, $path, $isMain);
  593.         $this->photos->add($photo);
  594.         return $photo;
  595.     }
  596.     /**
  597.      * @return Photo[]
  598.      */
  599.     public function getPhotos(): Collection
  600.     {
  601.         return $this->photos->filter(function ($mediaFile): bool {
  602.             return get_class($mediaFile) == Photo::class;
  603.         });
  604.     }
  605.     public function removePhoto(string $path): bool
  606.     {
  607.         foreach ($this->getPhotos() as $photo) {
  608.             if ($path === $photo->getPath()) {
  609.                 $this->photos->removeElement($photo);
  610.                 return true;
  611.             }
  612.         }
  613.         return false;
  614.     }
  615.     public function getMainPhotoOrFirstPhoto(): ?Photo
  616.     {
  617.         $photos = $this->getPhotos();
  618.         if ($photos->isEmpty()) {
  619.             return null;
  620.         }
  621.         $mainPhoto = $this->getMainPhoto();
  622.         if (null === $mainPhoto) {
  623.             $mainPhoto = $photos->first();
  624.         }
  625.         return $mainPhoto;
  626.     }
  627.     public function getMainPhoto(): ?Photo
  628.     {
  629.         $photos = $this->getPhotos();
  630.         if ($photos->isEmpty()) {
  631.             return null;
  632.         }
  633.         $mainPhoto = null;
  634.         $photos->forAll(function ($index, Photo $photo) use (&$mainPhoto): bool {
  635.             if ($photo->isMain()) {
  636.                 $mainPhoto = $photo;
  637.                 return false; // Stop the cycle
  638.             }
  639.             return true;
  640.         });
  641.         return $mainPhoto;
  642.     }
  643.     public function changeMainPhoto(string $path): void
  644.     {
  645.         $photos = $this->getPhotos();
  646.         $found = $photos->filter(function (Photo $photo) use ($path): bool {
  647.             return $path === $photo->getPath();
  648.         });
  649.         if ($found->isEmpty()) {
  650.             return;
  651.         }
  652.         $mainPhoto = $found->first();
  653.         $photos->forAll(function ($index, Photo $photo): true {
  654.             $photo->unsetMain();
  655.             return true;
  656.         });
  657.         $mainPhoto->setMain();
  658.     }
  659.     public function addSelfie(string $path): Selfie
  660.     {
  661.         $found = $this->getSelfies()->filter(function (Selfie $selfie) use ($path): bool {
  662.             return $path === $selfie->getPath();
  663.         });
  664.         if (!$found->isEmpty())
  665.             return $found->first();
  666.         $selfie = new Selfie($this, $path);
  667.         $this->selfies->add($selfie);
  668.         return $selfie;
  669.     }
  670.     /**
  671.      * @return Selfie[]
  672.      */
  673.     public function getSelfies(): Collection
  674.     {
  675.         return $this->selfies;
  676.     }
  677.     public function removeSelfie(string $path): bool
  678.     {
  679.         foreach ($this->getSelfies() as $selfie) {
  680.             if ($path === $selfie->getPath()) {
  681.                 $this->selfies->removeElement($selfie);
  682.                 return true;
  683.             }
  684.         }
  685.         return false;
  686.     }
  687.     public function getConfirmedVideos(): Collection
  688.     {
  689.         return $this->videos->filter(function ($mediaFile): bool {
  690.             if (!$mediaFile instanceof Video) {
  691.                 return false;
  692.             }
  693.             return $mediaFile->isConfirmed();
  694.         });
  695.     }
  696.     /**
  697.      * Храним только 1 видео для анкеты
  698.      */
  699.     public function addVideo(string $videoPath, ?string $posterPath = null): Video
  700.     {
  701.         $found = $this->getVideos()->filter(function (Video $video) use ($videoPath): bool {
  702.             return $videoPath === $video->getPath();
  703.         });
  704.         if (!$found->isEmpty())
  705.             return $found->first();
  706.         $video = new Video($this, $videoPath);
  707.         if (null !== $posterPath) {
  708.             $video->setPreviewPath($posterPath);
  709.         }
  710.         //теперь разрешаем много видео
  711.         //$this->videos->clear();
  712.         $this->videos->add($video);
  713.         return $video;
  714.     }
  715.     /**
  716.      * @return Video[]
  717.      */
  718.     public function getVideos(): Collection
  719.     {
  720.         return $this->videos->filter(function ($mediaFile): bool {
  721.             return ($mediaFile instanceof Video);
  722.         });
  723.     }
  724.     public function removeVideo(string $path): bool
  725.     {
  726.         foreach ($this->getVideos() as $video) {
  727.             if ($path === $video->getPath()) {
  728.                 $this->videos->removeElement($video);
  729.                 $this->photos->removeElement($video);
  730.                 return true;
  731.             }
  732.         }
  733.         return false;
  734.     }
  735.     /**
  736.      * Добавляет таск на обработку оригинала видео в подходящий формат
  737.      *
  738.      * @param string $path Путь к файлу оригинала относительно фс очередей
  739.      */
  740.     public function addRawVideo(string $path): FileProcessingTask
  741.     {
  742.         $file = new FileProcessingTask($this, $path);
  743.         $this->processingFiles->add($file);
  744.         return $file;
  745.     }
  746.     public function hasFilesInProcess(): bool
  747.     {
  748.         return $this->videosInProcess() > 0;
  749.     }
  750.     public function videosInProcess(): int
  751.     {
  752.         $inProcess = $this->processingFiles->filter(function (FileProcessingTask $task): bool {
  753.             return !$task->isCompleted();
  754.         });
  755.         return $inProcess->count();
  756.     }
  757.     public function isMediaProcessed(): bool
  758.     {
  759.         foreach ($this->videos as $video)
  760.             if (null === $video->getPreviewPath())
  761.                 return false;
  762.         return true;
  763.     }
  764.     public function getAvatar(): ?Avatar
  765.     {
  766.         return $this->avatar;
  767.     }
  768.     public function setAvatar(string $path): void
  769.     {
  770.         $this->avatar = new Avatar($this, $path);
  771.     }
  772.     public function removeAvatar(): bool
  773.     {
  774.         if (null == $this->avatar)
  775.             return false;
  776.         foreach ($this->photos as $photo) {
  777.             if ($this->avatar->getPath() === $photo->getPath()) {
  778.                 $this->photos->removeElement($photo);
  779.                 break;
  780.             }
  781.         }
  782.         $this->avatar = null;
  783.         return true;
  784.     }
  785.     /**
  786.      * @return CommentByCustomer[]
  787.      */
  788.     public function getComments(): Collection
  789.     {
  790.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  791.             return null == $comment->getParent();
  792.         });
  793.     }
  794.     /**
  795.      * @return CommentByCustomer[]
  796.      */
  797.     public function getCommentsOrderedByNotReplied(): array
  798.     {
  799.         $comments = $this->comments->filter(function (CommentByCustomer $comment): bool {
  800.             return null == $comment->getParent();
  801.         })->toArray();
  802.         usort($comments, function (CommentByCustomer $commentA, CommentByCustomer $commentB): int {
  803.             if ((null == $commentA->getLastCommentByAdvertiser() && null == $commentB->getLastCommentByAdvertiser())
  804.                 || (null != $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())) {
  805.                 if ($commentA->getCreatedAt() == $commentB->getCreatedAt())
  806.                     return $commentA->getId() > $commentB->getId() ? -1 : 1;
  807.                 else
  808.                     return $commentA->getCreatedAt() > $commentB->getCreatedAt() ? -1 : 1;
  809.             }
  810.             if (null == $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())
  811.                 return -1;
  812.             else
  813.                 return 1;
  814.         });
  815.         return $comments;
  816.     }
  817.     public function getCreatedAt(): ?\DateTimeImmutable
  818.     {
  819.         return $this->createdAt;
  820.     }
  821.     /**
  822.      * @return CommentByCustomer[]
  823.      */
  824.     public function getCommentsWithoutReply(): Collection
  825.     {
  826.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  827.             return null == $comment->getParent() && false == $comment->isCommentedByAdvertiser();
  828.         });
  829.     }
  830.     /**
  831.      * @return CommentByCustomer[]
  832.      */
  833.     public function getCommentsWithReply(): Collection
  834.     {
  835.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  836.             return null == $comment->getParent() && true == $comment->isCommentedByAdvertiser();
  837.         });
  838.     }
  839.     /**
  840.      * @return CommentByCustomer[]
  841.      */
  842.     public function getNewComments(): Collection
  843.     {
  844.         $weekAgo = CarbonImmutable::now()->sub('7 days');
  845.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  846.             return null == $comment->getParent()
  847.                 && (
  848.                     $comment->getCreatedAt() >= $weekAgo
  849.                     || null == $this->getCommentReply($comment)
  850.                 );
  851.         });
  852.     }
  853.     private function getCommentReply(CommentByCustomer $parent): ?CommentByCustomer
  854.     {
  855.         foreach ($this->comments as $comment)
  856.             if ($comment->getParent() == $parent)
  857.                 return $comment;
  858.         return null;
  859.     }
  860.     public function getOldComments(): Collection
  861.     {
  862.         $weekAgo = CarbonImmutable::now()->sub('7 days');
  863.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  864.             return null == $comment->getParent()
  865.                 && false == (
  866.                     $comment->getCreatedAt() >= $weekAgo
  867.                     || null == $this->getCommentReply($comment)
  868.                 );
  869.         });
  870.     }
  871.     public function getCommentFromUser(Customer $user): ?CommentByCustomer
  872.     {
  873.         foreach ($this->comments as $comment)
  874.             if (null == $comment->getParent() && null != $comment->getUser() && $user->getId() == $comment->getUser()->getId())
  875.                 return $comment;
  876.         return null;
  877.     }
  878.     //TODO return type
  879.     public function getCity(): City
  880.     {
  881.         return $this->city;
  882.     }
  883.     /** @return Collection<int, ProfileName> */
  884.     public function getProfileNames(): Collection
  885.     {
  886.         return $this->profileNames;
  887.     }
  888.     /**
  889.      * @return Station[]
  890.      */
  891.     public function getStations(): Collection
  892.     {
  893.         return $this->stations;
  894.     }
  895.     public function getMapCoordinate(): ?MapCoordinate
  896.     {
  897.         return $this->mapCoordinate;
  898.     }
  899.     public function getUpdatedAt(): ?\DateTimeImmutable
  900.     {
  901.         return $this->updatedAt;
  902.     }
  903.     public function setUpdatedAt(\DateTimeImmutable $updatedAt): void
  904.     {
  905.         $this->updatedAt = $updatedAt;
  906.     }
  907.     public function getModerationStatus(): int
  908.     {
  909.         return $this->moderationStatus;
  910.     }
  911.     public function setModerationStatus(int $status): void
  912.     {
  913.         if (self::MODERATION_STATUS_APPROVED === $status) {
  914.             throw new \RuntimeException(sprintf('Use %s::passModeration() method instead', static::class));
  915.         }
  916.         $validStatuses = [self::MODERATION_STATUS_NOT_PASSED, self::MODERATION_STATUS_APPROVED, self::MODERATION_STATUS_WAITING, self::MODERATION_STATUS_REJECTED];
  917.         if (false === array_search($status, $validStatuses))
  918.             throw new \LogicException('Trying to set an invalid moderation status');
  919.         $this->moderationStatus = $status;
  920.     }
  921.     public function isModerationPassed(): bool
  922.     {
  923.         return $this->moderationStatus == self::MODERATION_STATUS_APPROVED;
  924.     }
  925.     public function isModerationWaiting(): bool
  926.     {
  927.         return $this->moderationStatus == self::MODERATION_STATUS_WAITING;
  928.     }
  929.     public function isModerationRejected(): bool
  930.     {
  931.         return $this->moderationStatus == self::MODERATION_STATUS_REJECTED;
  932.     }
  933.     public function passModeration(?ModerationRequest $moderationRequest = null): void
  934.     {
  935.         $this->moderationStatus = self::MODERATION_STATUS_APPROVED;
  936.         $func = static function ($k, Photo|Video $file) use ($moderationRequest): bool {
  937.             if (!$file->isConfirmed()) {
  938.                 $file->passModeration($moderationRequest);
  939.             }
  940.             return true;
  941.         };
  942.         $this->videos->forAll($func);
  943.     }
  944.     public function delete(): void
  945.     {
  946.         $this->deletePlacementHiding();
  947.         $this->deleteFromAdBoard();
  948.         $now = new \DateTimeImmutable('now');
  949.         $toDelete = [];
  950.         foreach ($this->topPlacements as $topPlacement) {
  951.             if ($topPlacement->getExpiresAt() > $now)
  952.                 $toDelete[] = $topPlacement;
  953.         }
  954.         foreach ($toDelete as $topPlacement)
  955.             $this->topPlacements->removeElement($topPlacement);
  956.         $this->setDeletedAt(Carbon::now());
  957.     }
  958.     public function deletePlacementHiding(): void
  959.     {
  960.         $this->placementHiding = null;
  961.     }
  962.     public function deleteFromAdBoard(): void
  963.     {
  964.         $this->adBoardPlacement = null;
  965.     }
  966.     //TODO return type
  967.     public function undoDelete(): void
  968.     {
  969.         $this->setDeletedAt(); // will pass null by default
  970.     }
  971.     //TODO return type
  972.     public function deleteFromTopPlacement(): void
  973.     {
  974.         //здесь нужна логика отмены конретного размещения
  975. //        $this->topPlacement = null;
  976.     }
  977.     public function getExpressPricing(): ?ExpressPricing
  978.     {
  979.         return $this->expressPricing;
  980.     }
  981.     public function getCarPricing(): ?CarPricing
  982.     {
  983.         return $this->carPricing;
  984.     }
  985.     //TODO return type
  986.     /**
  987.      * @return int[]
  988.      */
  989.     public function getClientTypes(): array
  990.     {
  991.         return $this->clientTypes ?? [];
  992.     }
  993.     /**
  994.      * @param int[] $clientTypes
  995.      */
  996.     public function setClientTypes(array $clientTypes): void
  997.     {
  998.         $this->clientTypes = $clientTypes;
  999.     }
  1000.     public function getMessengers(): ?Messengers
  1001.     {
  1002.         return $this->messengers;
  1003.     }
  1004.     public function getInactivatedAt(): ?\DateTimeImmutable
  1005.     {
  1006.         return $this->inactivatedAt;
  1007.     }
  1008.     public function setInactive(): void
  1009.     {
  1010.         $this->inactivatedAt = CarbonImmutable::now();
  1011.     }
  1012.     public function undoInactive(): void
  1013.     {
  1014.         $this->inactivatedAt = null;
  1015.     }
  1016.     public function isHidden(): bool
  1017.     {
  1018.         return null !== $this->getPlacementHiding();
  1019.     }
  1020.     public function getPlacementHiding(): ?PlacementHiding
  1021.     {
  1022.         return $this->placementHiding;
  1023.     }
  1024.     public function setPlacementHiding(PlacementHiding $placementHiding): void
  1025.     {
  1026.         $this->placementHiding = $placementHiding;
  1027.     }
  1028.     public function hasSelfie(): bool
  1029.     {
  1030.         return $this->selfies->count() > 0;
  1031.     }
  1032.     public function hasVideo(): bool
  1033.     {
  1034.         return $this->videos->count() > 0;
  1035.     }
  1036.     public function isCommented(): bool
  1037.     {
  1038.         return $this->comments->count() > 0;
  1039.     }
  1040.     public function adminApprovalPhoto(): ?AdminApprovalPhoto
  1041.     {
  1042.         return $this->adminApprovalPhoto;
  1043.     }
  1044.     public function setAdminApprovalPhoto(?string $path): void
  1045.     {
  1046.         $this->adminApprovalPhoto = $path ? new AdminApprovalPhoto($this, $path) : null;
  1047.     }
  1048.     public function seo(): ?array
  1049.     {
  1050.         return $this->seo;
  1051.     }
  1052.     public function seoPhoneNumber(): ?string
  1053.     {
  1054.         return $this->seo['phone'] ?? null;
  1055.     }
  1056.     public function setSeoPhoneNumber(string $phoneNumber): void
  1057.     {
  1058.         if (null === $this->seo) {
  1059.             $this->seo = [];
  1060.         }
  1061.         $this->seo['phone'] = $phoneNumber;
  1062.     }
  1063.     public function getPrimaryStation(): ?Station
  1064.     {
  1065.         $station = $this->primaryStation ?? $this->getStations()->first();
  1066.         if (false === $station) {
  1067.             return null;
  1068.         }
  1069.         return $station;
  1070.     }
  1071.     public function setPrimaryStation(?Station $station): void
  1072.     {
  1073.         $this->primaryStation = $station;
  1074.         $this->normalizePrimaryStation();
  1075.     }
  1076.     public function getStationsSortedByPrimary(): array
  1077.     {
  1078.         $stations = $this->stations->toArray();
  1079.         if (!$this->primaryStation) {
  1080.             return $stations;
  1081.         }
  1082.         usort($stations, function (Station $a, Station $b) {
  1083.             if ($a->getId() === $this->primaryStation->getId()) return -1;
  1084.             if ($b->getId() === $this->primaryStation->getId()) return 1;
  1085.             return 0;
  1086.         });
  1087.         return $stations;
  1088.     }
  1089.     public function getDistricts(): array
  1090.     {
  1091.         $districts = [];
  1092.         $addedDistricts = [];
  1093.         foreach ($this->getStationsSortedByPrimary() as $station) {
  1094.             $district = $station->getDistrict();
  1095.             if (array_key_exists($district->getId(), $addedDistricts)) {
  1096.                 continue;
  1097.             }
  1098.             $districts[] = $district;
  1099.             $addedDistricts[$district->getId()] = true;
  1100.         }
  1101.         return $districts;
  1102.     }
  1103.     public function getDeleteMode(): int
  1104.     {
  1105.         return $this->deleteMode;
  1106.     }
  1107.     public function setDeleteMode(int $deleteMode): self
  1108.     {
  1109.         $this->deleteMode = $deleteMode;
  1110.         return $this;
  1111.     }
  1112.     public function isHardDeleted(): bool
  1113.     {
  1114.         return $this->deleteMode === 2;
  1115.     }
  1116. }