src/EventSubscriber/Doctrine/OrganizationSubscriber.php line 480

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Doctrine;
  3. use App\Enum\ActivityLogCategoryEnum;
  4. use App\Enum\DiscountCodeTypeEnum;
  5. use App\Enum\HeadQuartersEnum;
  6. use App\Enum\LegalRepresentativeQualityTypeEnum;
  7. use App\Enum\OrganizationStatusEnum;
  8. use App\Enum\OrganizationStatusImmatriculationEnum;
  9. use App\Enum\OrganizationStatusPayedEnum;
  10. use App\Enum\OrganizationStatusTransfertEnum;
  11. use App\Enum\OrganizationTracFinEnum;
  12. use App\Enum\PersonTypeEnum;
  13. use App\Repository\SubscriptionRepository;
  14. use App\Service\LeadUtils;
  15. use App\Service\LetterFilesService;
  16. use App\Service\OrganizationUtils;
  17. use App\Service\SegmentAPI;
  18. use App\Service\SubscriptionUtils;
  19. use App\Traits\SentryNotifyTrait;
  20. use Doctrine\Common\EventSubscriber;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Doctrine\ORM\Event\PreUpdateEventArgs;
  23. use Doctrine\ORM\OptimisticLockException;
  24. use Doctrine\ORM\ORMException;
  25. use Doctrine\Persistence\Event\LifecycleEventArgs;
  26. use Evo\Domain\Billing\BillingReportInterface;
  27. use Evo\Infrastructure\Mapper\Organization\OrganizationMapper;
  28. use Evo\Infrastructure\MappingORM\ActivityLog;
  29. use Evo\Infrastructure\MappingORM\DiscountCode;
  30. use Evo\Infrastructure\MappingORM\Organization;
  31. use Evo\Infrastructure\MappingORM\PostalAddress;
  32. use Evo\Infrastructure\MappingORM\Service;
  33. use Evo\Infrastructure\MappingORM\Store;
  34. use Evo\Infrastructure\MappingORM\Subscription;
  35. use Evo\Infrastructure\MappingORM\User;
  36. use GuzzleHttp\Exception\GuzzleException;
  37. use Symfony\Component\HttpFoundation\Request;
  38. use Symfony\Component\HttpFoundation\RequestStack;
  39. use Symfony\Component\HttpFoundation\Response;
  40. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  41. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  42. use Symfony\Component\Security\Core\Security;
  43. use Symfony\Contracts\Translation\TranslatorInterface;
  44. class OrganizationSubscriber implements EventSubscriber
  45. {
  46.     use SentryNotifyTrait;
  47.     public const SERVICE_NAME '[ ORGANIZATION SUBSCRIBER ] :: ';
  48.     public const LR_POST_ROUTE_NAME 'api_legal_representatives_post_collection';
  49.     public const UNLINK_LR_FROM_ORGA_ROUTE_NAME 'app_legal_representative_unlink_organization';
  50.     private RequestStack $requestStack;
  51.     private SegmentAPI $segment;
  52.     private EntityManagerInterface $em;
  53.     private OrganizationUtils $organizationUtils;
  54.     private LetterFilesService $letterFilesService;
  55.     private LeadUtils $leadUtils;
  56.     private SessionInterface $session;
  57.     private Security $security;
  58.     private SubscriptionUtils $subscriptionUtils;
  59.     private TranslatorInterface $translator;
  60.     private BillingReportInterface $billingReport;
  61.     public function __construct(
  62.         RequestStack $requestStack,
  63.         SegmentAPI $segmentAPI,
  64.         SessionInterface $session,
  65.         LeadUtils $leadUtils,
  66.         LetterFilesService $letterFilesService,
  67.         OrganizationUtils $organizationUtils,
  68.         EntityManagerInterface $em,
  69.         SubscriptionUtils $subscriptionUtils,
  70.         TranslatorInterface $translator,
  71.         Security $security,
  72.         BillingReportInterface $billingReport
  73.     ) {
  74.         $this->requestStack $requestStack;
  75.         $this->organizationUtils $organizationUtils;
  76.         $this->leadUtils $leadUtils;
  77.         $this->segment $segmentAPI;
  78.         $this->session $session;
  79.         $this->letterFilesService $letterFilesService;
  80.         $this->em $em;
  81.         $this->security $security;
  82.         $this->subscriptionUtils $subscriptionUtils;
  83.         $this->translator $translator;
  84.         $this->billingReport $billingReport;
  85.     }
  86.     public function getSubscribedEvents(): array
  87.     {
  88.         return [
  89.             'prePersist',
  90.             'postPersist',
  91.             'preUpdate',
  92.             'postUpdate',
  93.             'preRemove',
  94.         ];
  95.     }
  96.     public function preRemove(LifecycleEventArgs $args): void
  97.     {
  98.         /** @var Organization $entity */
  99.         $entity $args->getObject();
  100.         if (!$entity instanceof Organization) {
  101.             return;
  102.         }
  103.         $dataLogs = [
  104.             'id' => $entity->getId(),
  105.             'legalName' => $entity->getLegalName() ?? '',
  106.         ];
  107.         if (!is_null($this->security->getUser())) {
  108.             /** @var User $user */
  109.             $user $this->security->getUser();
  110.             $dataLogs['Deleted by'] = $user->getUsername() ?? 'N/A';
  111.         }
  112.         $this->sendSentryMessage(self::SERVICE_NAME.'Suppression Organization '.json_encode($dataLogsJSON_THROW_ON_ERROR));
  113.     }
  114.     public function postPersist(LifecycleEventArgs $args): void
  115.     {
  116.         /** @var Organization $entity */
  117.         $entity $args->getObject();
  118.         if (!$entity instanceof Organization) {
  119.             return;
  120.         }
  121.         $this->em $args->getObjectManager();
  122.         $this->setForwardingAddress($entity);
  123.         if (null !== $entity->getStore()) {
  124.             $this->setAddress($entity);
  125.         } else {
  126.             $entity->getSubscriptions()->map(function (Subscription $subscription) {
  127.                 $subscription->removeServiceByType(Service::STORE_ADDITION);
  128.             });
  129.         }
  130.         try {
  131.             $this->organizationUtils->generateDocs($entity);
  132.         } catch (ORMException $e) {
  133.             $this->captureSentryException($e);
  134.         }
  135.         if (OrganizationStatusEnum::NEW === $entity->getStatus()) {
  136.             $this->leadUtils->changeStatus($entity);
  137.         }
  138.         $this->segment->trackNewOrganization($entity);
  139.         $this->segment->getCompanyID($entity);
  140.         $this->segment->trackOrganizationStatus($entity);
  141.         $this->segment->trackOrganizationReferral($entity);
  142.     }
  143.     public function setAddress(Organization $entity): void
  144.     {
  145.         if (null !== $entity->getStore()) {
  146.             $address = new PostalAddress();
  147.             $orgaAdress $entity->getStore()->getPostalAddress();
  148.             $address->setAddressCountry($orgaAdress->getAddressCountry())
  149.                 ->setAddressLocality($orgaAdress->getAddressLocality())
  150.                 ->setAddressRegion($orgaAdress->getAddressRegion())
  151.                 ->setPostalCode($orgaAdress->getPostalCode())
  152.                 ->setStreetAddress($orgaAdress->getStreetAddress());
  153.             $entity->setAddress($address);
  154.             $this->em->persist($entity);
  155.             $this->em->flush();
  156.             $this->segment->identifyCompanyDomiciliationAddress($entity);
  157.         } else {
  158.             $entity->getSubscriptions()->map(function (Subscription $subscription) {
  159.                 $subscription->removeServiceByType(Service::STORE_ADDITION);
  160.             });
  161.         }
  162.     }
  163.     public function setForwardingAddress($entity)
  164.     {
  165.         if (!$entity->getForwardingAddress()) {
  166.             $lr $entity->getLegalRepresentatives();
  167.             $lrAddress null;
  168.             foreach ($lr as $legalRepresentative) {
  169.                 if (in_array(
  170.                     $legalRepresentative->getQuality(),
  171.                     [LegalRepresentativeQualityTypeEnum::CHAIRMANLegalRepresentativeQualityTypeEnum::MANAGER]
  172.                 )) {
  173.                     if ($legalRepresentative->getPerson() && PersonTypeEnum::PHYSICAL == $legalRepresentative->getPerson()->getType()) {
  174.                         $lrAddress $legalRepresentative->getPerson()->getAddress();
  175.                     } else {
  176.                         $physicalLR $this->organizationUtils->getFirstPhysicalLR($legalRepresentative);
  177.                         if ($physicalLR) {
  178.                             $lrAddress $physicalLR->getPerson()->getAddress();
  179.                         }
  180.                     }
  181.                 }
  182.             }
  183.             if ($lrAddress) {
  184.                 $fa = new PostalAddress();
  185.                 $fa->setStreetAddress($lrAddress->getStreetAddress());
  186.                 $fa->setPostalCode($lrAddress->getPostalCode());
  187.                 $fa->setAddressLocality($lrAddress->getAddressLocality());
  188.                 $fa->setAddressCountry($lrAddress->getAddressCountry());
  189.                 $entity->setForwardingAddress($fa);
  190.                 $this->em->persist($entity);
  191.                 $this->em->flush();
  192.             }
  193.         }
  194.     }
  195.     public function prePersist(LifecycleEventArgs $args)
  196.     {
  197.         $entity $args->getObject();
  198.         if (!$entity instanceof Organization) {
  199.             return;
  200.         }
  201.         $this->em $args->getObjectManager();
  202.         if (null === $entity->getCreatedAt()) {
  203.             $entity->setCreatedAt(new \DateTime());
  204.         }
  205.         if ($entity->getIsNewImmatriculation()) {
  206.             $entity->setStatusImmatriculation(OrganizationStatusImmatriculationEnum::NEW);
  207.         }
  208.         if ($entity->getIsNewTransfert()) {
  209.             $entity->setStatusTransfert(OrganizationStatusTransfertEnum::NEW);
  210.         }
  211.         if (!$entity->getIsNewDomiciliation()) {
  212.             $entity->setStatus(null);
  213.         }
  214.         if (!$entity->getUniqId()) {
  215.             $entity->setUniqId(uniqid());
  216.         }
  217.         if ($entity->getUsers()) {
  218.             /** @var User $user */
  219.             $user $entity->getUsers()[0];
  220.             $entity->setTelephone($user->getPhoneNumber());
  221.             $entity->setEmail($user->getEmail());
  222.         }
  223.         if (null !== $entity->getPrescriberSource()) {
  224.             $this->segment->identifyCompanySourcePrescriber($entity);
  225.         }
  226.         if (null !== $entity->getEncryptedParentId()) {
  227.             $decryptedParentID str_replace('DIGIPAR'''$entity->getEncryptedParentId());
  228.             $parentOrganization $this->em->getRepository(Organization::class)->findOneBy(['id' => $decryptedParentID]);
  229.             if (null !== $parentOrganization) {
  230.                 $entity->setReferralSource($parentOrganization);
  231.                 $entity->setIsReferralProcessFinished(false);
  232.             }
  233.         }
  234.         $invoiceToken hash('sha512'uniqid());
  235.         $entity->setInvoiceToken($invoiceToken);
  236.         $this->segment->identifyLegalStatus($entity);
  237.     }
  238.     public function preUpdate(PreUpdateEventArgs $args)
  239.     {
  240.         /** @var Organization $entity */
  241.         $entity $args->getObject();
  242.         if (!$entity instanceof Organization) {
  243.             return;
  244.         }
  245.         $this->em $args->getEntityManager();
  246.         $changeset $args->getEntityChangeSet();
  247.         if (isset($changeset['isAuthorizedDebit'])) {
  248.             $this->segment->identifyUpdateAuthorizationDebit($entity);
  249.         }
  250.         if (== count($changeset) && isset($changeset['invoiceToken'])) {
  251.             return;
  252.         }
  253.         if (=== count($changeset) && isset($changeset['isAuthorizedDebit'])) {
  254.             return;
  255.         }
  256.         if (=== count($changeset) && isset($changeset['historyNavTunnel'])) {
  257.             return;
  258.         }
  259.         if (=== count($changeset) && isset($changeset['isInvalidPhoneNumber'])) {
  260.             return;
  261.         }
  262.         if (=== count($changeset) && isset($changeset['isInvalidEmail'])) {
  263.             return;
  264.         }
  265.         if (isset($changeset['status']) && OrganizationTracFinEnum::WARNING_DOC != $entity->getTracFin()) {
  266.             switch ($changeset['status'][1]) {
  267.                 case OrganizationStatusEnum::NEW:
  268.                 case OrganizationStatusEnum::NEW_PAYMENT:
  269.                 case OrganizationStatusEnum::LOST:
  270.                 case OrganizationStatusEnum::CANCELLED:
  271.                 case OrganizationStatusEnum::DELETED:
  272.                     $entity->setTracFin(null);
  273.                     break;
  274.                 case OrganizationStatusEnum::DOCS_MISSING:
  275.                 case OrganizationStatusEnum::DOCS_EXPIRED:
  276.                     $entity->setTracFin(OrganizationTracFinEnum::INCOMPLETE_DOC);
  277.                     break;
  278.                 case OrganizationStatusEnum::OK:
  279.                 case OrganizationStatusEnum::PRE_CANCELLATION:
  280.                     $entity->setTracFin(OrganizationTracFinEnum::COMPLETE_DOC);
  281.                     break;
  282.                 default:
  283.                     $entity->setTracFin(null);
  284.             }
  285.         }
  286.         if (isset($changeset['mandatID']) && (null !== $changeset['mandatID'][1])) {
  287.             $entity->setReasonRIBInactive(null);
  288.         }
  289.         if (isset($changeset['statusInvoicePayed']) && (OrganizationStatusPayedEnum::UNPAID !== $changeset['statusInvoicePayed'][1])) {
  290.             $entity->setReasonUnpaid(null);
  291.             $entity->setDateMaxUnpaid(null);
  292.         }
  293.         if (isset($changeset['statusInvoicePayed']) && OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][1]) {
  294.             $this->segment->identifyGocardlessUrl($entity);
  295.         }
  296.         if (isset($changeset['telephone'])) {
  297.             $entity->setIsInvalidPhoneNumber(false);
  298.         }
  299.         if (isset($changeset['email'])) {
  300.             $entity->setIsInvalidEmail(false);
  301.         }
  302.         if (isset($changeset['store'])) {
  303.             /** @var Store $store */
  304.             $store $changeset['store'][1];
  305.             if (
  306.                 $store && $store->getPostalAddress() &&
  307.                 HeadQuartersEnum::CONTRACT_DOMICILIATION === $entity->getHeadQuartersAddressType()
  308.             ) {
  309.                 $entity->setAddress($store->getPostalAddress());
  310.             }
  311.         }
  312.         if (
  313.             isset($changeset['isNewImmatriculation']) &&
  314.             true === $changeset['isNewImmatriculation'][1] &&
  315.             !$entity->getStatusImmatriculation()
  316.         ) {
  317.             $entity->setStatusImmatriculation(OrganizationStatusImmatriculationEnum::NEW);
  318.         }
  319.         if (
  320.             isset($changeset['status']) &&
  321.             OrganizationStatusEnum::LOST === $changeset['status'][0] &&
  322.             OrganizationStatusEnum::NEW === $changeset['status'][1]
  323.         ) {
  324.             $entity->setCreatedAt(new \DateTime());
  325.         }
  326.         if (isset($changeset['statusInvoicePayed']) && OrganizationStatusPayedEnum::NO_INVOICES === $changeset['statusInvoicePayed'][0]) {
  327.             $this->segment->identifyInvoiceToken($entity);
  328.         }
  329.         /*
  330.          * Check domiciliation status automatically.
  331.          */
  332.         if (!isset($changeset['isSurveillance'])) {
  333.             $status $this->organizationUtils->checkStatusDomiciliation($entity);
  334.         }
  335.         if (isset($changeset['isNewDomiciliation'])) {
  336.             if (false === $changeset['isNewDomiciliation'][1]) {
  337.                 if (!$entity->getIsNewDomiciliation()) {
  338.                     $entity->setStatus(null);
  339.                 }
  340.             } elseif (true === $changeset['isNewDomiciliation'][1] && null === $entity->getStatus() && (!isset($status) || !$status)) {
  341.                 $status OrganizationStatusEnum::NEW;
  342.             }
  343.         }
  344.         if (isset($changeset['status'])) {
  345.             $changedStatus $changeset['status'];
  346.             if ((OrganizationStatusEnum::DELETED === $changedStatus[1]) && !$this->security->isGranted('ROLE_SUPER_ADMIN')) {
  347.                 $entity->setStatus($changedStatus[0]);
  348.                 return;
  349.             }
  350.             if (
  351.                 $this->security->getToken() &&
  352.                 ($this->security->isGranted('ROLE_SUPER_ADMIN')
  353.                     || ($this->security->isGranted('ROLE_ADMIN') && in_array($changeset['status'][1], [OrganizationStatusEnum::LOSTOrganizationStatusEnum::PRE_CANCELLATIONOrganizationStatusEnum::CANCELLED])))
  354.             ) {
  355.                 $status $changeset['status'][1];
  356.             }
  357.         }
  358.         if (isset($status) && $status) {
  359.             $entity->setStatus($status);
  360.         }
  361.         if (isset($changeset['isPrescriber']) && true === $changeset['isPrescriber'][1]) {
  362.             $entity->setPrescriber($entity);
  363.         }
  364.         if (isset($changeset['legalStatus'])) {
  365.             $this->segment->identifyLegalStatus($entity);
  366.         }
  367.         if (isset($changeset['prescriberSource'])) {
  368.             $this->segment->identifyCompanySourcePrescriber($entity);
  369.         }
  370.         if ($entity->getUsers()) {
  371.             $user $entity->getUsers()[0];
  372.             $entity->setTelephone($user->getPhoneNumber());
  373.             $entity->setEmail($user->getEmail());
  374.         }
  375.         /*
  376.          * Set status PRE_CANCELLATION to CANCELLED
  377.          */
  378.         if (OrganizationStatusEnum::PRE_CANCELLATION === $entity->getStatus() && null !== $entity->getTerminationDate()) {
  379.             $now date('Y-m-d');
  380.             $deadline $entity->getTerminationDate()->format('Y-m-d');
  381.             if ($deadline <= $now) {
  382.                 $entity->setStatus(OrganizationStatusEnum::CANCELLED);
  383.             }
  384.         }
  385.         $this->segment->identifyOrganization($entity$args->getEntityChangeSet());
  386.     }
  387.     /**
  388.      * @throws OptimisticLockException
  389.      * @throws GuzzleException
  390.      * @throws ORMException
  391.      */
  392.     public function postUpdate(LifecycleEventArgs $args): void
  393.     {
  394.         /** @var Organization $entity */
  395.         $entity $args->getObject();
  396.         if (!$entity instanceof Organization) {
  397.             return;
  398.         }
  399.         if ($this->session->has('locked')) {
  400.             $this->session->remove('locked');
  401.         }
  402.         $uow $this->em->getUnitOfWork();
  403.         $uow->computeChangeSets();
  404.         $changeset $uow->getEntityChangeSet($entity);
  405.         if (=== (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['historyNavTunnel'])) {
  406.             return;
  407.         }
  408.         if (=== (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['isAuthorizedDebit'])) {
  409.             return;
  410.         }
  411.         $subscription SubscriptionUtils::getDomSubscription($entity);
  412.         if (null !== $subscription && (isset($changeset['statusInvoicePayed']) || isset($changeset['dateMaxUnpaid']))) {
  413.             if (isset($changeset['statusInvoicePayed'])) {
  414.                 $isUnpaid = (OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][1]);
  415.             } elseif (isset($changeset['dateMaxUnpaid'])) {
  416.                 $isUnpaid = (OrganizationStatusPayedEnum::UNPAID === $entity->getStatusInvoicePayed());
  417.             } else {
  418.                 $isUnpaid false;
  419.             }
  420.             $hasBlockedService $this->subscriptionUtils->checkIfServiceShouldBeBlocked($subscription$isUnpaid);
  421.             $this->subscriptionUtils->updateSubscriptionBlockedService($subscription$hasBlockedService);
  422.         }
  423.         $isRegularise false;
  424.         $issetStatusInvoicePayed = isset($changeset['statusInvoicePayed']);
  425.         if (isset($changeset['status']) || $issetStatusInvoicePayed || isset($changeset['dateMaxUnpaid']) || isset($changeset['statusImmatriculation']) || isset($changeset['statusTransfert'])) {
  426.             if ($issetStatusInvoicePayed && OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][0]) {
  427.                 $isRegularise true;
  428.             }
  429.             $this->segment->trackOrganizationStatus($entity$isRegularise);
  430.         }
  431.         if (
  432.             in_array($entity->getStatus(), [
  433.                 OrganizationStatusEnum::NEW_PAYMENT,
  434.                 OrganizationStatusEnum::DOCS_MISSING,
  435.                 OrganizationStatusEnum::OK,
  436.             ]) &&
  437.             !$entity->getIsReferralProcessFinished() &&
  438.             isset($changeset['status'])
  439.         ) {
  440.             $this->segment->trackOrganizationReferral($entity);
  441.         }
  442.         // create activity log after creating legal representative
  443.         $request $this->requestStack->getCurrentRequest();
  444.         $token $this->security->getToken();
  445.         if ($token instanceof SwitchUserToken) {
  446.             $impersonatorUser $token->getOriginalToken()->getUser();
  447.         }
  448.         $activityLogUser $request instanceof Request $impersonatorUser ?? $this->security->getUser() : null;
  449.         if (isset($changeset['discountCode']) && $changeset['discountCode'][1]) {
  450.             try {
  451.                 /** @var DiscountCode $discountCode */
  452.                 $discountCode $changeset['discountCode'][1];
  453.                 $discountType DiscountCodeTypeEnum::SUBSCRIPTION_DISCOUNT === $discountCode->getType() ? 'remise abonnement' 'remise facture';
  454.                 $discountActivityLog ActivityLog::create(
  455.                     $activityLogUser,
  456.                     'NOTE_PROMO',
  457.                     'Code promo',
  458.                     ActivityLogCategoryEnum::COMMERCIAL_GESTURE,
  459.                     [],
  460.                     $entity,
  461.                     null,
  462.                     'Utilisation du code promo '.$discountCode->getPromoCode().' de type '.$discountType
  463.                 );
  464.                 $this->em->persist($discountActivityLog);
  465.                 $this->em->flush();
  466.             } catch (\Exception $e) {
  467.                 $this->captureSentryException($e);
  468.             }
  469.         }
  470.         if (
  471.             isset($changeset['status']) &&
  472.             OrganizationStatusEnum::PRE_CANCELLATION !== $changeset['status'][0] &&
  473.             (OrganizationStatusEnum::CANCELLED === $changeset['status'][1] || OrganizationStatusEnum::LOST === $changeset['status'][1])
  474.         ) {
  475.             $entity->setTerminationDate(new \DateTime());
  476.             $this->em->persist($entity);
  477.             $this->em->flush();
  478.         }
  479.         if (
  480.             isset($changeset['status']) && OrganizationStatusEnum::NEW_PAYMENT === $changeset['status'][0] && OrganizationStatusEnum::DOCS_MISSING === $changeset['status'][1] &&
  481.             !$this->organizationUtils->hasLetterWelcome($entity)
  482.         ) {
  483.             /*  Création courrier de bienvenu * */
  484.             if ('test' !== getenv('APP_ENV')) {
  485.                 $this->letterFilesService->generateLetterWelcome($entity);
  486.             }
  487.         }
  488.         if (isset($changeset['status'])) {
  489.             try {
  490.                 $oldStatus null !== $changeset['status'][0] ? $this->translator->trans(OrganizationStatusEnum::getReadableValue($changeset['status'][0])) : '-';
  491.                 $newStatus null !== $changeset['status'][1] ? $this->translator->trans(OrganizationStatusEnum::getReadableValue($changeset['status'][1])) : '-';
  492.                 $activityLogChangeSet = [
  493.                     'statut' => [
  494.                         $oldStatus => $newStatus,
  495.                     ],
  496.                 ];
  497.                 $orgaActivityLog ActivityLog::create(
  498.                     $activityLogUser,
  499.                     'CREATION',
  500.                     'Modification de statut domiciliation',
  501.                     ActivityLogCategoryEnum::STATUS_CHANGE,
  502.                     $activityLogChangeSet,
  503.                     $entity,
  504.                     null,
  505.                     null
  506.                 );
  507.                 $this->em->persist($orgaActivityLog);
  508.                 $this->em->flush();
  509.             } catch (\Exception $exception) {
  510.                 $this->captureSentryException($exception);
  511.             }
  512.         }
  513.         if (isset($changeset['bal'])) {
  514.             $this->segment->identifyBalCompany($entity);
  515.         }
  516.         if (isset($changeset['alternateName'], $changeset['SIRET'], $changeset['sigle'])) {
  517.             $this->segment->identifySIRET($entity);
  518.         }
  519.         if (isset($changeset['store'])) {
  520.             if (HeadQuartersEnum::POSTAL_DOMICILIATION !== $entity->getHeadQuartersAddressType()) {
  521.                 $this->setAddress($entity);
  522.             }
  523.             $subscription SubscriptionUtils::getDomSubscription($entity);
  524.             if (null !== $subscription) {
  525.                 $this->subscriptionUtils->addStoreAdditionStoreForDom($subscription);
  526.             }
  527.         }
  528.         if (OrganizationStatusEnum::DELETED === $entity->getStatus()) {
  529.             return;
  530.         }
  531.         if (isset($changeset['notificationPreference'])) {
  532.             $this->segment->trackNotificationPreference($entity->getNotificationPreference(), $entity);
  533.         }
  534.         if (== (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['invoiceToken'])) {
  535.             return;
  536.         }
  537.         if (
  538.             isset($changeset['status']) ||
  539.             isset($changeset['bal']) ||
  540.             isset($changeset['statusImmatriculation']) ||
  541.             isset($changeset['statusTransfert']) ||
  542.             isset($changeset['statusInvoicePayed']) ||
  543.             isset($changeset['legalName'])
  544.         ) {
  545.             $this->organizationUtils->updateInfoFrontApp($entity);
  546.         }
  547.         if (
  548.             isset($changeset['statusInvoicePayed']) &&
  549.             OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][0] &&
  550.             OrganizationStatusPayedEnum::PAID === $changeset['statusInvoicePayed'][1] && false === $entity->getIsAuthorizedDebit()
  551.         ) {
  552.             $entity->setIsAuthorizedDebit(true);
  553.             $this->em->persist($entity);
  554.             $this->em->flush();
  555.         }
  556.         if (null !== $this->requestStack->getCurrentRequest() && empty($this->requestStack->getCurrentRequest()->get('organizationPreUpdated'))) {
  557.             $this->requestStack->getCurrentRequest()->query->set('organizationPreUpdated'true);
  558.             $status $entity->getStatus();
  559.             if (OrganizationStatusEnum::CANCELLED == $status) {
  560.                 $this->organizationUtils->statusChangedActions($status$entitytrue);
  561.             }
  562.         }
  563.         $this->setForwardingAddress($entity);
  564.         $isGenerateContract false;
  565.         $notGenerateContractKey = [
  566.             'status',
  567.             'mandatID',
  568.             'statusImmatriculation',
  569.             'statusTransfert',
  570.             'haveAccountant',
  571.             'iban',
  572.             'referenceGocardless',
  573.         ];
  574.         if (array_intersect_key(array_flip($notGenerateContractKey), $changeset)) {
  575.             $isGenerateContract false;
  576.         }
  577.         $generateContractKey = [
  578.             'store',
  579.             'address',
  580.             'domiciliationStartDate',
  581.             'SIRET',
  582.             'headQuartersAddressType',
  583.             'legalStatus',
  584.             'legalName',
  585.         ];
  586.         if (array_intersect_key(array_flip($generateContractKey), $changeset)) {
  587.             $isGenerateContract true;
  588.         }
  589.         // generate contract for lr add and remove
  590.         if (null !== $this->requestStack->getCurrentRequest()) {
  591.             $route $this->requestStack->getCurrentRequest()->attributes->get('_route');
  592.             if (
  593.                 in_array($route, [self::LR_POST_ROUTE_NAMEself::UNLINK_LR_FROM_ORGA_ROUTE_NAME])
  594.                 && === count($changeset)
  595.             ) {
  596.                 $isGenerateContract true;
  597.             }
  598.         }
  599.         $this->organizationUtils->generateDocs($entity$isGenerateContract);
  600.         if (in_array($entity->getStatus(), [OrganizationStatusEnum::CANCELLEDOrganizationStatusEnum::PRE_CANCELLATIONOrganizationStatusEnum::NEW], true)) {
  601.             $this->organizationUtils->statusChangedActions($entity->getStatus(), $entitytrue);
  602.         }
  603.         if (isset($changeset['forwardingFrequency'])) {
  604.             $this->segment->trackUpdateForwardingAddress($entity);
  605.         }
  606.         if (isset($changeset['status']) && OrganizationStatusEnum::LOST === $changeset['status'][1]) {
  607.             $this->organizationUtils->statusChangedActions(OrganizationStatusEnum::LOST$entitytrue);
  608.         }
  609.         if (isset($changeset['status']) && OrganizationStatusEnum::NEW_PAYMENT === $changeset['status'][1]) {
  610.             $this->segment->identifyGocardlessUrl($entity);
  611.         }
  612.         if (
  613.             isset($changeset['status']) &&
  614.             OrganizationStatusEnum::OK === $changeset['status'][1]
  615.         ) {
  616.             $entity->setIsReferralProcessFinished(true);
  617.             $this->em->persist($entity);
  618.             $this->em->flush();
  619.         }
  620.         if (isset($changeset['SIRET']) || isset($changeset['status'])) {
  621.             $this->organizationUtils->updateSurveillance($entity$changeset['SIRET'] ?? null);
  622.         }
  623.         if (
  624.             isset($changeset['status']) &&
  625.             null !== $subscription
  626.         ) {
  627.             if (in_array(
  628.                 $entity->getStatus(),
  629.                 [OrganizationStatusEnum::DOCS_MISSINGOrganizationStatusEnum::DOCS_EXPIRED]
  630.             )) {
  631.                 $hasAllRequiredDocumentToPassToOKStatus $this->organizationUtils->hasAllRequiredDocumentToPassToOKStatus($entity);
  632.                 $hasOneDocumentNotApproved $this->organizationUtils->hasAllDocumentsUploadedButAtLeastOneRefused($entity);
  633.                 $newStatus $changeset['status'][1];
  634.                 $this->subscriptionUtils->updateSubscriptionRecoveryDelay($newStatus$subscription$hasOneDocumentNotApproved$hasAllRequiredDocumentToPassToOKStatus);
  635.             } else {
  636.                 try {
  637.                     $subscription->setDocumentRecoveryDelay(null);
  638.                     $this->em->persist($subscription);
  639.                     $this->em->flush();
  640.                 } catch (\Exception $e) {
  641.                     $this->captureSentryException($e);
  642.                 }
  643.             }
  644.             /** @var SubscriptionRepository $subscriptionRepository */
  645.             $subscriptionRepository $this->em->getRepository(Subscription::class);
  646.             $subscriptionStatus SubscriptionUtils::isActiveSubscription($subscription);
  647.             $subscriptionRepository->updateSubscriptionStatus($subscription$subscriptionStatus);
  648.         }
  649.         if (
  650.             isset($changeset['isNewDomiciliation']) ||
  651.             isset($changeset['isNewImmatriculation']) ||
  652.             isset($changeset['isNewTransfert'])
  653.         ) {
  654.             $this->segment->trackFlag($entity);
  655.         }
  656.         if (!in_array($entity->getStatus(), [
  657.             OrganizationStatusEnum::CANCELLED,
  658.             OrganizationStatusEnum::PRE_CANCELLATION,
  659.             OrganizationStatusEnum::LOST,
  660.         ])) {
  661.             $this->em->getRepository(Organization::class)->update(
  662.                 $entity,
  663.                 [
  664.                     'terminationDate' => null,
  665.                     'terminationReason' => null,
  666.                     'terminationReasonOther' => null,
  667.                 ]
  668.             );
  669.         }
  670.     }
  671.     private function updateOrCreateCustomerForBillingReport(Organization $entity): void
  672.     {
  673.         $data OrganizationMapper::mapForBillingReport($entity);
  674.         $response $this->billingReport->customers()->update(
  675.             (string) $entity->getId(),
  676.             $data
  677.         );
  678.         if (Response::HTTP_NOT_FOUND === $response->getStatusCode()) {
  679.             $this->billingReport->customers()->create(
  680.                 $data
  681.             );
  682.         }
  683.     }
  684. }