<?php
namespace App\EventSubscriber\Doctrine;
use App\Enum\ActivityLogCategoryEnum;
use App\Enum\DiscountCodeTypeEnum;
use App\Enum\HeadQuartersEnum;
use App\Enum\LegalRepresentativeQualityTypeEnum;
use App\Enum\OrganizationStatusEnum;
use App\Enum\OrganizationStatusImmatriculationEnum;
use App\Enum\OrganizationStatusPayedEnum;
use App\Enum\OrganizationStatusTransfertEnum;
use App\Enum\OrganizationTracFinEnum;
use App\Enum\PersonTypeEnum;
use App\Repository\SubscriptionRepository;
use App\Service\LeadUtils;
use App\Service\LetterFilesService;
use App\Service\OrganizationUtils;
use App\Service\SegmentAPI;
use App\Service\SubscriptionUtils;
use App\Traits\SentryNotifyTrait;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Evo\Domain\Billing\BillingReportInterface;
use Evo\Infrastructure\Mapper\Organization\OrganizationMapper;
use Evo\Infrastructure\MappingORM\ActivityLog;
use Evo\Infrastructure\MappingORM\DiscountCode;
use Evo\Infrastructure\MappingORM\Organization;
use Evo\Infrastructure\MappingORM\PostalAddress;
use Evo\Infrastructure\MappingORM\Service;
use Evo\Infrastructure\MappingORM\Store;
use Evo\Infrastructure\MappingORM\Subscription;
use Evo\Infrastructure\MappingORM\User;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
class OrganizationSubscriber implements EventSubscriber
{
use SentryNotifyTrait;
public const SERVICE_NAME = '[ ORGANIZATION SUBSCRIBER ] :: ';
public const LR_POST_ROUTE_NAME = 'api_legal_representatives_post_collection';
public const UNLINK_LR_FROM_ORGA_ROUTE_NAME = 'app_legal_representative_unlink_organization';
private RequestStack $requestStack;
private SegmentAPI $segment;
private EntityManagerInterface $em;
private OrganizationUtils $organizationUtils;
private LetterFilesService $letterFilesService;
private LeadUtils $leadUtils;
private SessionInterface $session;
private Security $security;
private SubscriptionUtils $subscriptionUtils;
private TranslatorInterface $translator;
private BillingReportInterface $billingReport;
public function __construct(
RequestStack $requestStack,
SegmentAPI $segmentAPI,
SessionInterface $session,
LeadUtils $leadUtils,
LetterFilesService $letterFilesService,
OrganizationUtils $organizationUtils,
EntityManagerInterface $em,
SubscriptionUtils $subscriptionUtils,
TranslatorInterface $translator,
Security $security,
BillingReportInterface $billingReport
) {
$this->requestStack = $requestStack;
$this->organizationUtils = $organizationUtils;
$this->leadUtils = $leadUtils;
$this->segment = $segmentAPI;
$this->session = $session;
$this->letterFilesService = $letterFilesService;
$this->em = $em;
$this->security = $security;
$this->subscriptionUtils = $subscriptionUtils;
$this->translator = $translator;
$this->billingReport = $billingReport;
}
public function getSubscribedEvents(): array
{
return [
'prePersist',
'postPersist',
'preUpdate',
'postUpdate',
'preRemove',
];
}
public function preRemove(LifecycleEventArgs $args): void
{
/** @var Organization $entity */
$entity = $args->getObject();
if (!$entity instanceof Organization) {
return;
}
$dataLogs = [
'id' => $entity->getId(),
'legalName' => $entity->getLegalName() ?? '',
];
if (!is_null($this->security->getUser())) {
/** @var User $user */
$user = $this->security->getUser();
$dataLogs['Deleted by'] = $user->getUsername() ?? 'N/A';
}
$this->sendSentryMessage(self::SERVICE_NAME.'Suppression Organization '.json_encode($dataLogs, JSON_THROW_ON_ERROR));
}
public function postPersist(LifecycleEventArgs $args): void
{
/** @var Organization $entity */
$entity = $args->getObject();
if (!$entity instanceof Organization) {
return;
}
$this->em = $args->getObjectManager();
$this->setForwardingAddress($entity);
if (null !== $entity->getStore()) {
$this->setAddress($entity);
} else {
$entity->getSubscriptions()->map(function (Subscription $subscription) {
$subscription->removeServiceByType(Service::STORE_ADDITION);
});
}
try {
$this->organizationUtils->generateDocs($entity);
} catch (ORMException $e) {
$this->captureSentryException($e);
}
if (OrganizationStatusEnum::NEW === $entity->getStatus()) {
$this->leadUtils->changeStatus($entity);
}
$this->segment->trackNewOrganization($entity);
$this->segment->getCompanyID($entity);
$this->segment->trackOrganizationStatus($entity);
$this->segment->trackOrganizationReferral($entity);
}
public function setAddress(Organization $entity): void
{
if (null !== $entity->getStore()) {
$address = new PostalAddress();
$orgaAdress = $entity->getStore()->getPostalAddress();
$address->setAddressCountry($orgaAdress->getAddressCountry())
->setAddressLocality($orgaAdress->getAddressLocality())
->setAddressRegion($orgaAdress->getAddressRegion())
->setPostalCode($orgaAdress->getPostalCode())
->setStreetAddress($orgaAdress->getStreetAddress());
$entity->setAddress($address);
$this->em->persist($entity);
$this->em->flush();
$this->segment->identifyCompanyDomiciliationAddress($entity);
} else {
$entity->getSubscriptions()->map(function (Subscription $subscription) {
$subscription->removeServiceByType(Service::STORE_ADDITION);
});
}
}
public function setForwardingAddress($entity)
{
if (!$entity->getForwardingAddress()) {
$lr = $entity->getLegalRepresentatives();
$lrAddress = null;
foreach ($lr as $legalRepresentative) {
if (in_array(
$legalRepresentative->getQuality(),
[LegalRepresentativeQualityTypeEnum::CHAIRMAN, LegalRepresentativeQualityTypeEnum::MANAGER]
)) {
if ($legalRepresentative->getPerson() && PersonTypeEnum::PHYSICAL == $legalRepresentative->getPerson()->getType()) {
$lrAddress = $legalRepresentative->getPerson()->getAddress();
} else {
$physicalLR = $this->organizationUtils->getFirstPhysicalLR($legalRepresentative);
if ($physicalLR) {
$lrAddress = $physicalLR->getPerson()->getAddress();
}
}
}
}
if ($lrAddress) {
$fa = new PostalAddress();
$fa->setStreetAddress($lrAddress->getStreetAddress());
$fa->setPostalCode($lrAddress->getPostalCode());
$fa->setAddressLocality($lrAddress->getAddressLocality());
$fa->setAddressCountry($lrAddress->getAddressCountry());
$entity->setForwardingAddress($fa);
$this->em->persist($entity);
$this->em->flush();
}
}
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if (!$entity instanceof Organization) {
return;
}
$this->em = $args->getObjectManager();
if (null === $entity->getCreatedAt()) {
$entity->setCreatedAt(new \DateTime());
}
if ($entity->getIsNewImmatriculation()) {
$entity->setStatusImmatriculation(OrganizationStatusImmatriculationEnum::NEW);
}
if ($entity->getIsNewTransfert()) {
$entity->setStatusTransfert(OrganizationStatusTransfertEnum::NEW);
}
if (!$entity->getIsNewDomiciliation()) {
$entity->setStatus(null);
}
if (!$entity->getUniqId()) {
$entity->setUniqId(uniqid());
}
if ($entity->getUsers()) {
/** @var User $user */
$user = $entity->getUsers()[0];
$entity->setTelephone($user->getPhoneNumber());
$entity->setEmail($user->getEmail());
}
if (null !== $entity->getPrescriberSource()) {
$this->segment->identifyCompanySourcePrescriber($entity);
}
if (null !== $entity->getEncryptedParentId()) {
$decryptedParentID = str_replace('DIGIPAR', '', $entity->getEncryptedParentId());
$parentOrganization = $this->em->getRepository(Organization::class)->findOneBy(['id' => $decryptedParentID]);
if (null !== $parentOrganization) {
$entity->setReferralSource($parentOrganization);
$entity->setIsReferralProcessFinished(false);
}
}
$invoiceToken = hash('sha512', uniqid());
$entity->setInvoiceToken($invoiceToken);
$this->segment->identifyLegalStatus($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
/** @var Organization $entity */
$entity = $args->getObject();
if (!$entity instanceof Organization) {
return;
}
$this->em = $args->getEntityManager();
$changeset = $args->getEntityChangeSet();
if (isset($changeset['isAuthorizedDebit'])) {
$this->segment->identifyUpdateAuthorizationDebit($entity);
}
if (1 == count($changeset) && isset($changeset['invoiceToken'])) {
return;
}
if (1 === count($changeset) && isset($changeset['isAuthorizedDebit'])) {
return;
}
if (1 === count($changeset) && isset($changeset['historyNavTunnel'])) {
return;
}
if (1 === count($changeset) && isset($changeset['isInvalidPhoneNumber'])) {
return;
}
if (1 === count($changeset) && isset($changeset['isInvalidEmail'])) {
return;
}
if (isset($changeset['status']) && OrganizationTracFinEnum::WARNING_DOC != $entity->getTracFin()) {
switch ($changeset['status'][1]) {
case OrganizationStatusEnum::NEW:
case OrganizationStatusEnum::NEW_PAYMENT:
case OrganizationStatusEnum::LOST:
case OrganizationStatusEnum::CANCELLED:
case OrganizationStatusEnum::DELETED:
$entity->setTracFin(null);
break;
case OrganizationStatusEnum::DOCS_MISSING:
case OrganizationStatusEnum::DOCS_EXPIRED:
$entity->setTracFin(OrganizationTracFinEnum::INCOMPLETE_DOC);
break;
case OrganizationStatusEnum::OK:
case OrganizationStatusEnum::PRE_CANCELLATION:
$entity->setTracFin(OrganizationTracFinEnum::COMPLETE_DOC);
break;
default:
$entity->setTracFin(null);
}
}
if (isset($changeset['mandatID']) && (null !== $changeset['mandatID'][1])) {
$entity->setReasonRIBInactive(null);
}
if (isset($changeset['statusInvoicePayed']) && (OrganizationStatusPayedEnum::UNPAID !== $changeset['statusInvoicePayed'][1])) {
$entity->setReasonUnpaid(null);
$entity->setDateMaxUnpaid(null);
}
if (isset($changeset['statusInvoicePayed']) && OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][1]) {
$this->segment->identifyGocardlessUrl($entity);
}
if (isset($changeset['telephone'])) {
$entity->setIsInvalidPhoneNumber(false);
}
if (isset($changeset['email'])) {
$entity->setIsInvalidEmail(false);
}
if (isset($changeset['store'])) {
/** @var Store $store */
$store = $changeset['store'][1];
if (
$store && $store->getPostalAddress() &&
HeadQuartersEnum::CONTRACT_DOMICILIATION === $entity->getHeadQuartersAddressType()
) {
$entity->setAddress($store->getPostalAddress());
}
}
if (
isset($changeset['isNewImmatriculation']) &&
true === $changeset['isNewImmatriculation'][1] &&
!$entity->getStatusImmatriculation()
) {
$entity->setStatusImmatriculation(OrganizationStatusImmatriculationEnum::NEW);
}
if (
isset($changeset['status']) &&
OrganizationStatusEnum::LOST === $changeset['status'][0] &&
OrganizationStatusEnum::NEW === $changeset['status'][1]
) {
$entity->setCreatedAt(new \DateTime());
}
if (isset($changeset['statusInvoicePayed']) && OrganizationStatusPayedEnum::NO_INVOICES === $changeset['statusInvoicePayed'][0]) {
$this->segment->identifyInvoiceToken($entity);
}
/*
* Check domiciliation status automatically.
*/
if (!isset($changeset['isSurveillance'])) {
$status = $this->organizationUtils->checkStatusDomiciliation($entity);
}
if (isset($changeset['isNewDomiciliation'])) {
if (false === $changeset['isNewDomiciliation'][1]) {
if (!$entity->getIsNewDomiciliation()) {
$entity->setStatus(null);
}
} elseif (true === $changeset['isNewDomiciliation'][1] && null === $entity->getStatus() && (!isset($status) || !$status)) {
$status = OrganizationStatusEnum::NEW;
}
}
if (isset($changeset['status'])) {
$changedStatus = $changeset['status'];
if ((OrganizationStatusEnum::DELETED === $changedStatus[1]) && !$this->security->isGranted('ROLE_SUPER_ADMIN')) {
$entity->setStatus($changedStatus[0]);
return;
}
if (
$this->security->getToken() &&
($this->security->isGranted('ROLE_SUPER_ADMIN')
|| ($this->security->isGranted('ROLE_ADMIN') && in_array($changeset['status'][1], [OrganizationStatusEnum::LOST, OrganizationStatusEnum::PRE_CANCELLATION, OrganizationStatusEnum::CANCELLED])))
) {
$status = $changeset['status'][1];
}
}
if (isset($status) && $status) {
$entity->setStatus($status);
}
if (isset($changeset['isPrescriber']) && true === $changeset['isPrescriber'][1]) {
$entity->setPrescriber($entity);
}
if (isset($changeset['legalStatus'])) {
$this->segment->identifyLegalStatus($entity);
}
if (isset($changeset['prescriberSource'])) {
$this->segment->identifyCompanySourcePrescriber($entity);
}
if ($entity->getUsers()) {
$user = $entity->getUsers()[0];
$entity->setTelephone($user->getPhoneNumber());
$entity->setEmail($user->getEmail());
}
/*
* Set status PRE_CANCELLATION to CANCELLED
*/
if (OrganizationStatusEnum::PRE_CANCELLATION === $entity->getStatus() && null !== $entity->getTerminationDate()) {
$now = date('Y-m-d');
$deadline = $entity->getTerminationDate()->format('Y-m-d');
if ($deadline <= $now) {
$entity->setStatus(OrganizationStatusEnum::CANCELLED);
}
}
$this->segment->identifyOrganization($entity, $args->getEntityChangeSet());
}
/**
* @throws OptimisticLockException
* @throws GuzzleException
* @throws ORMException
*/
public function postUpdate(LifecycleEventArgs $args): void
{
/** @var Organization $entity */
$entity = $args->getObject();
if (!$entity instanceof Organization) {
return;
}
if ($this->session->has('locked')) {
$this->session->remove('locked');
}
$uow = $this->em->getUnitOfWork();
$uow->computeChangeSets();
$changeset = $uow->getEntityChangeSet($entity);
if (1 === (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['historyNavTunnel'])) {
return;
}
if (1 === (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['isAuthorizedDebit'])) {
return;
}
$subscription = SubscriptionUtils::getDomSubscription($entity);
if (null !== $subscription && (isset($changeset['statusInvoicePayed']) || isset($changeset['dateMaxUnpaid']))) {
if (isset($changeset['statusInvoicePayed'])) {
$isUnpaid = (OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][1]);
} elseif (isset($changeset['dateMaxUnpaid'])) {
$isUnpaid = (OrganizationStatusPayedEnum::UNPAID === $entity->getStatusInvoicePayed());
} else {
$isUnpaid = false;
}
$hasBlockedService = $this->subscriptionUtils->checkIfServiceShouldBeBlocked($subscription, $isUnpaid);
$this->subscriptionUtils->updateSubscriptionBlockedService($subscription, $hasBlockedService);
}
$isRegularise = false;
$issetStatusInvoicePayed = isset($changeset['statusInvoicePayed']);
if (isset($changeset['status']) || $issetStatusInvoicePayed || isset($changeset['dateMaxUnpaid']) || isset($changeset['statusImmatriculation']) || isset($changeset['statusTransfert'])) {
if ($issetStatusInvoicePayed && OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][0]) {
$isRegularise = true;
}
$this->segment->trackOrganizationStatus($entity, $isRegularise);
}
if (
in_array($entity->getStatus(), [
OrganizationStatusEnum::NEW_PAYMENT,
OrganizationStatusEnum::DOCS_MISSING,
OrganizationStatusEnum::OK,
]) &&
!$entity->getIsReferralProcessFinished() &&
isset($changeset['status'])
) {
$this->segment->trackOrganizationReferral($entity);
}
// create activity log after creating legal representative
$request = $this->requestStack->getCurrentRequest();
$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
$impersonatorUser = $token->getOriginalToken()->getUser();
}
$activityLogUser = $request instanceof Request ? $impersonatorUser ?? $this->security->getUser() : null;
if (isset($changeset['discountCode']) && $changeset['discountCode'][1]) {
try {
/** @var DiscountCode $discountCode */
$discountCode = $changeset['discountCode'][1];
$discountType = DiscountCodeTypeEnum::SUBSCRIPTION_DISCOUNT === $discountCode->getType() ? 'remise abonnement' : 'remise facture';
$discountActivityLog = ActivityLog::create(
$activityLogUser,
'NOTE_PROMO',
'Code promo',
ActivityLogCategoryEnum::COMMERCIAL_GESTURE,
[],
$entity,
null,
'Utilisation du code promo '.$discountCode->getPromoCode().' de type '.$discountType
);
$this->em->persist($discountActivityLog);
$this->em->flush();
} catch (\Exception $e) {
$this->captureSentryException($e);
}
}
if (
isset($changeset['status']) &&
OrganizationStatusEnum::PRE_CANCELLATION !== $changeset['status'][0] &&
(OrganizationStatusEnum::CANCELLED === $changeset['status'][1] || OrganizationStatusEnum::LOST === $changeset['status'][1])
) {
$entity->setTerminationDate(new \DateTime());
$this->em->persist($entity);
$this->em->flush();
}
if (
isset($changeset['status']) && OrganizationStatusEnum::NEW_PAYMENT === $changeset['status'][0] && OrganizationStatusEnum::DOCS_MISSING === $changeset['status'][1] &&
!$this->organizationUtils->hasLetterWelcome($entity)
) {
/* Création courrier de bienvenu * */
if ('test' !== getenv('APP_ENV')) {
$this->letterFilesService->generateLetterWelcome($entity);
}
}
if (isset($changeset['status'])) {
try {
$oldStatus = null !== $changeset['status'][0] ? $this->translator->trans(OrganizationStatusEnum::getReadableValue($changeset['status'][0])) : '-';
$newStatus = null !== $changeset['status'][1] ? $this->translator->trans(OrganizationStatusEnum::getReadableValue($changeset['status'][1])) : '-';
$activityLogChangeSet = [
'statut' => [
$oldStatus => $newStatus,
],
];
$orgaActivityLog = ActivityLog::create(
$activityLogUser,
'CREATION',
'Modification de statut domiciliation',
ActivityLogCategoryEnum::STATUS_CHANGE,
$activityLogChangeSet,
$entity,
null,
null
);
$this->em->persist($orgaActivityLog);
$this->em->flush();
} catch (\Exception $exception) {
$this->captureSentryException($exception);
}
}
if (isset($changeset['bal'])) {
$this->segment->identifyBalCompany($entity);
}
if (isset($changeset['alternateName'], $changeset['SIRET'], $changeset['sigle'])) {
$this->segment->identifySIRET($entity);
}
if (isset($changeset['store'])) {
if (HeadQuartersEnum::POSTAL_DOMICILIATION !== $entity->getHeadQuartersAddressType()) {
$this->setAddress($entity);
}
$subscription = SubscriptionUtils::getDomSubscription($entity);
if (null !== $subscription) {
$this->subscriptionUtils->addStoreAdditionStoreForDom($subscription);
}
}
if (OrganizationStatusEnum::DELETED === $entity->getStatus()) {
return;
}
if (isset($changeset['notificationPreference'])) {
$this->segment->trackNotificationPreference($entity->getNotificationPreference(), $entity);
}
if (1 == (is_countable($changeset) ? count($changeset) : 0) && isset($changeset['invoiceToken'])) {
return;
}
if (
isset($changeset['status']) ||
isset($changeset['bal']) ||
isset($changeset['statusImmatriculation']) ||
isset($changeset['statusTransfert']) ||
isset($changeset['statusInvoicePayed']) ||
isset($changeset['legalName'])
) {
$this->organizationUtils->updateInfoFrontApp($entity);
}
if (
isset($changeset['statusInvoicePayed']) &&
OrganizationStatusPayedEnum::UNPAID === $changeset['statusInvoicePayed'][0] &&
OrganizationStatusPayedEnum::PAID === $changeset['statusInvoicePayed'][1] && false === $entity->getIsAuthorizedDebit()
) {
$entity->setIsAuthorizedDebit(true);
$this->em->persist($entity);
$this->em->flush();
}
if (null !== $this->requestStack->getCurrentRequest() && empty($this->requestStack->getCurrentRequest()->get('organizationPreUpdated'))) {
$this->requestStack->getCurrentRequest()->query->set('organizationPreUpdated', true);
$status = $entity->getStatus();
if (OrganizationStatusEnum::CANCELLED == $status) {
$this->organizationUtils->statusChangedActions($status, $entity, true);
}
}
$this->setForwardingAddress($entity);
$isGenerateContract = false;
$notGenerateContractKey = [
'status',
'mandatID',
'statusImmatriculation',
'statusTransfert',
'haveAccountant',
'iban',
'referenceGocardless',
];
if (array_intersect_key(array_flip($notGenerateContractKey), $changeset)) {
$isGenerateContract = false;
}
$generateContractKey = [
'store',
'address',
'domiciliationStartDate',
'SIRET',
'headQuartersAddressType',
'legalStatus',
'legalName',
];
if (array_intersect_key(array_flip($generateContractKey), $changeset)) {
$isGenerateContract = true;
}
// generate contract for lr add and remove
if (null !== $this->requestStack->getCurrentRequest()) {
$route = $this->requestStack->getCurrentRequest()->attributes->get('_route');
if (
in_array($route, [self::LR_POST_ROUTE_NAME, self::UNLINK_LR_FROM_ORGA_ROUTE_NAME])
&& 0 === count($changeset)
) {
$isGenerateContract = true;
}
}
$this->organizationUtils->generateDocs($entity, $isGenerateContract);
if (in_array($entity->getStatus(), [OrganizationStatusEnum::CANCELLED, OrganizationStatusEnum::PRE_CANCELLATION, OrganizationStatusEnum::NEW], true)) {
$this->organizationUtils->statusChangedActions($entity->getStatus(), $entity, true);
}
if (isset($changeset['forwardingFrequency'])) {
$this->segment->trackUpdateForwardingAddress($entity);
}
if (isset($changeset['status']) && OrganizationStatusEnum::LOST === $changeset['status'][1]) {
$this->organizationUtils->statusChangedActions(OrganizationStatusEnum::LOST, $entity, true);
}
if (isset($changeset['status']) && OrganizationStatusEnum::NEW_PAYMENT === $changeset['status'][1]) {
$this->segment->identifyGocardlessUrl($entity);
}
if (
isset($changeset['status']) &&
OrganizationStatusEnum::OK === $changeset['status'][1]
) {
$entity->setIsReferralProcessFinished(true);
$this->em->persist($entity);
$this->em->flush();
}
if (isset($changeset['SIRET']) || isset($changeset['status'])) {
$this->organizationUtils->updateSurveillance($entity, $changeset['SIRET'] ?? null);
}
if (
isset($changeset['status']) &&
null !== $subscription
) {
if (in_array(
$entity->getStatus(),
[OrganizationStatusEnum::DOCS_MISSING, OrganizationStatusEnum::DOCS_EXPIRED]
)) {
$hasAllRequiredDocumentToPassToOKStatus = $this->organizationUtils->hasAllRequiredDocumentToPassToOKStatus($entity);
$hasOneDocumentNotApproved = $this->organizationUtils->hasAllDocumentsUploadedButAtLeastOneRefused($entity);
$newStatus = $changeset['status'][1];
$this->subscriptionUtils->updateSubscriptionRecoveryDelay($newStatus, $subscription, $hasOneDocumentNotApproved, $hasAllRequiredDocumentToPassToOKStatus);
} else {
try {
$subscription->setDocumentRecoveryDelay(null);
$this->em->persist($subscription);
$this->em->flush();
} catch (\Exception $e) {
$this->captureSentryException($e);
}
}
/** @var SubscriptionRepository $subscriptionRepository */
$subscriptionRepository = $this->em->getRepository(Subscription::class);
$subscriptionStatus = SubscriptionUtils::isActiveSubscription($subscription);
$subscriptionRepository->updateSubscriptionStatus($subscription, $subscriptionStatus);
}
if (
isset($changeset['isNewDomiciliation']) ||
isset($changeset['isNewImmatriculation']) ||
isset($changeset['isNewTransfert'])
) {
$this->segment->trackFlag($entity);
}
if (!in_array($entity->getStatus(), [
OrganizationStatusEnum::CANCELLED,
OrganizationStatusEnum::PRE_CANCELLATION,
OrganizationStatusEnum::LOST,
])) {
$this->em->getRepository(Organization::class)->update(
$entity,
[
'terminationDate' => null,
'terminationReason' => null,
'terminationReasonOther' => null,
]
);
}
}
private function updateOrCreateCustomerForBillingReport(Organization $entity): void
{
$data = OrganizationMapper::mapForBillingReport($entity);
$response = $this->billingReport->customers()->update(
(string) $entity->getId(),
$data
);
if (Response::HTTP_NOT_FOUND === $response->getStatusCode()) {
$this->billingReport->customers()->create(
$data
);
}
}
}