ShopService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Shop;
  4. use App\ApiResources\Organization\OrganizationCreationRequest;
  5. use App\ApiResources\Shop\NewStructureArtistPremiumTrialRequest;
  6. use App\Entity\Organization\Organization;
  7. use App\Entity\Shop\ShopRequest;
  8. use App\Enum\Access\AccessIdsEnum;
  9. use App\Enum\Organization\SettingsProductEnum;
  10. use App\Enum\Shop\ShopRequestStatus;
  11. use App\Enum\Shop\ShopRequestType;
  12. use App\Message\Message\Shop\NewStructureArtistPremiumTrial;
  13. use App\Service\Mailer\Mailer;
  14. use App\Service\Mailer\Model\Shop\NewStructureArtistPremium\ConfirmationToRepresentativeModel;
  15. use App\Service\Mailer\Model\Shop\NewStructureArtistPremium\NotificationToSalesAdminModel;
  16. use App\Service\Mailer\Model\Shop\TokenValidationModel;
  17. use App\Service\Organization\OrganizationFactory;
  18. use App\Service\Utils\DatesUtils;
  19. use App\Service\Utils\UrlBuilder;
  20. use Doctrine\DBAL\Exception;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Doctrine\ORM\Exception\ORMException;
  23. use Doctrine\ORM\OptimisticLockException;
  24. use libphonenumber\PhoneNumberUtil;
  25. use Psr\Log\LoggerInterface;
  26. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  27. use Symfony\Component\Messenger\Exception\ExceptionInterface;
  28. use Symfony\Component\Messenger\MessageBusInterface;
  29. use Symfony\Component\Serializer\SerializerInterface;
  30. use Symfony\Component\Uid\Uuid;
  31. /**
  32. * Service for managing shop requests.
  33. *
  34. * This service handles various shop-related operations.
  35. * It provides functionality for:
  36. * - Registering new shop requests
  37. * - Validating and processing shop requests
  38. * - Creating organizations based on trial requests
  39. * - Starting premium trials for organizations
  40. * - Generating subdomains from structure names
  41. */
  42. class ShopService
  43. {
  44. protected PhoneNumberUtil $phoneNumberUtil;
  45. public function __construct(
  46. private EntityManagerInterface $entityManager,
  47. private Mailer $mailer,
  48. private string $publicBaseUrl,
  49. private string $publicAdminBaseUrl,
  50. private OrganizationFactory $organizationFactory,
  51. private SerializerInterface $serializer,
  52. private LoggerInterface $logger,
  53. private MessageBusInterface $messageBus,
  54. private Trial $trial,
  55. private string $faqUrl,
  56. private readonly string $softwareWebsiteUrl,
  57. ) {
  58. $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
  59. }
  60. /**
  61. * A new shop request has been submitted.
  62. * Register the request, and send the validation link by email.
  63. *
  64. * @param array<string, mixed> $data
  65. *
  66. * @throws TransportExceptionInterface
  67. */
  68. public function registerNewShopRequest(ShopRequestType $type, array $data): ShopRequest
  69. {
  70. $this->controlShopRequestData($type, $data);
  71. $request = $this->createRequest($type, $data);
  72. $this->sendRequestValidationLink($request);
  73. return $request;
  74. }
  75. /**
  76. * Validate the shop request based on its type.
  77. * For NEW_STRUCTURE_ARTIST_PREMIUM_TRIAL, check if the organization already exists.
  78. * For other types, throw an error.
  79. *
  80. * @param array<string, mixed> $data
  81. */
  82. protected function controlShopRequestData(ShopRequestType $type, array $data): void
  83. {
  84. // @phpstan-ignore-next-line identical.alwaysTrue
  85. if ($type === ShopRequestType::NEW_STRUCTURE_ARTIST_PREMIUM_TRIAL) {
  86. $this->validateNewStructureArtistPremiumTrialRequest($data);
  87. } else {
  88. throw new \RuntimeException('request type not supported');
  89. }
  90. }
  91. /**
  92. * Validate the request and dispatch the appropriate job based on the request type.
  93. *
  94. * @throws \RuntimeException|ExceptionInterface
  95. */
  96. public function processShopRequest(ShopRequest $shopRequest): void
  97. {
  98. // Dispatch appropriate job based on request type
  99. switch ($shopRequest->getType()->value) {
  100. case ShopRequestType::NEW_STRUCTURE_ARTIST_PREMIUM_TRIAL->value:
  101. $this->messageBus->dispatch(
  102. new NewStructureArtistPremiumTrial($shopRequest->getToken())
  103. );
  104. break;
  105. default:
  106. throw new \RuntimeException('request type not supported');
  107. }
  108. $shopRequest->setStatus(ShopRequestStatus::VALIDATED);
  109. $this->entityManager->persist($shopRequest);
  110. $this->entityManager->flush();
  111. }
  112. /**
  113. * Create and persist a new ShopRequest entity.
  114. *
  115. * @param array<string, mixed> $data
  116. */
  117. protected function createRequest(ShopRequestType $type, array $data): ShopRequest
  118. {
  119. $shopRequest = new ShopRequest();
  120. $shopRequest->setToken(Uuid::v4()->toRfc4122());
  121. $shopRequest->setType($type);
  122. $shopRequest->setData($data);
  123. $this->entityManager->persist($shopRequest);
  124. $this->entityManager->flush();
  125. return $shopRequest;
  126. }
  127. /**
  128. * Send validation email with link.
  129. *
  130. * @throws TransportExceptionInterface
  131. */
  132. protected function sendRequestValidationLink(ShopRequest $shopRequest): void
  133. {
  134. $validationUrl = UrlBuilder::concat(
  135. $this->softwareWebsiteUrl,
  136. ['/shop/try/validation'],
  137. ['token' => $shopRequest->getToken()]
  138. );
  139. $data = $shopRequest->getData();
  140. $model = new TokenValidationModel();
  141. $model
  142. ->setToken($shopRequest->getToken())
  143. ->setRepresentativeEmail($data['representativeEmail'] ?? '')
  144. ->setRepresentativeFirstName($data['representativeFirstName'] ?? '')
  145. ->setRepresentativeLastName($data['representativeLastName'] ?? '')
  146. ->setStructureName($data['structureName'] ?? '')
  147. ->setValidationUrl($validationUrl)
  148. ->setSenderId(AccessIdsEnum::ADMIN_2IOPENSERVICE->value);
  149. $this->mailer->main($model);
  150. $shopRequest->setStatus(ShopRequestStatus::ACTIVATION_LINK_SENT);
  151. $this->entityManager->persist($shopRequest);
  152. $this->entityManager->flush();
  153. }
  154. /**
  155. * Handles the processing of a new structure artist premium trial request.
  156. *
  157. * @param string $token The token identifying the shop request
  158. *
  159. * @throws Exception
  160. * @throws \JsonException
  161. * @throws ORMException
  162. * @throws OptimisticLockException
  163. */
  164. public function handleNewStructureArtistPremiumTrialRequest(string $token): void
  165. {
  166. // Retrieve the ShopRequest entity using its token
  167. $shopRequest = $this->entityManager->find(ShopRequest::class, $token);
  168. if (!$shopRequest) {
  169. $this->logger->error('Cannot find ShopRequest with token: '.$token);
  170. return;
  171. }
  172. // Convert the stored JSON data to a NewStructureArtistPremiumTrialRequest object
  173. $data = $shopRequest->getData();
  174. $trialRequest = $this->serializer->deserialize(
  175. json_encode($data),
  176. NewStructureArtistPremiumTrialRequest::class,
  177. 'json'
  178. );
  179. $organization = $this->createOrganization($trialRequest);
  180. // Set the admin account password
  181. $this->organizationFactory->setAdminAccountPassword($organization, $trialRequest->getPassword());
  182. // Start the artist premium trial
  183. $this->trial->startArtistPremiumTrialForNewStructure($organization, $trialRequest);
  184. // Send email to sales administration
  185. $this->sendMailToSalesAdministration($trialRequest);
  186. // Send email to representative
  187. $this->sendConfirmationMailToRepresentative($trialRequest);
  188. $this->logger->info('Successfully processed NewStructureArtistPremiumTrial for token: '.$token);
  189. }
  190. /**
  191. * Creates a new organization based on a trial request.
  192. *
  193. * @param NewStructureArtistPremiumTrialRequest $trialRequest The trial request containing organization data
  194. *
  195. * @return Organization The created organization
  196. */
  197. protected function createOrganization(NewStructureArtistPremiumTrialRequest $trialRequest): Organization
  198. {
  199. // Generate an OrganizationCreationRequest object
  200. $organizationCreationRequest = $this->createOrganizationCreationRequestFromTrialRequest($trialRequest);
  201. // Create the organization
  202. return $this->organizationFactory->create($organizationCreationRequest);
  203. }
  204. /**
  205. * Vérifie la validité d'une requête d'essai artist premium pour une nouvelle structure.
  206. */
  207. protected function validateNewStructureArtistPremiumTrialRequest(
  208. array $data,
  209. ): void {
  210. $trialRequestObj = $this->serializer->deserialize(
  211. json_encode($data),
  212. NewStructureArtistPremiumTrialRequest::class,
  213. 'json'
  214. );
  215. // Validate phone number
  216. if (!$this->phoneNumberUtil->isPossibleNumber($trialRequestObj->getRepresentativePhone())) {
  217. throw new \RuntimeException('Invalid phone number');
  218. }
  219. // Check if organization already exists
  220. $organizationCreationRequest = $this->createOrganizationCreationRequestFromTrialRequest($trialRequestObj);
  221. $this->organizationFactory->interruptIfOrganizationExists($organizationCreationRequest);
  222. }
  223. /**
  224. * Creates an OrganizationCreationRequest from a NewStructureArtistPremiumTrialRequest.
  225. *
  226. * @param NewStructureArtistPremiumTrialRequest $trialRequest The trial request containing organization data
  227. *
  228. * @return OrganizationCreationRequest The created organization creation request
  229. *
  230. * @throws \Exception
  231. */
  232. protected function createOrganizationCreationRequestFromTrialRequest(
  233. NewStructureArtistPremiumTrialRequest $trialRequest,
  234. ): OrganizationCreationRequest {
  235. $organizationCreationRequest = new OrganizationCreationRequest();
  236. $organizationCreationRequest->setName($trialRequest->getStructureName());
  237. $organizationCreationRequest->setStreetAddress1($trialRequest->getAddress());
  238. $organizationCreationRequest->setStreetAddress2($trialRequest->getAddressComplement());
  239. $organizationCreationRequest->setPostalCode($trialRequest->getPostalCode());
  240. $organizationCreationRequest->setCity($trialRequest->getCity());
  241. $organizationCreationRequest->setEmail($trialRequest->getStructureEmail());
  242. $organizationCreationRequest->setPrincipalType($trialRequest->getStructureType());
  243. $organizationCreationRequest->setLegalStatus($trialRequest->getLegalStatus());
  244. $organizationCreationRequest->setSiretNumber($trialRequest->getSiren());
  245. $organizationCreationRequest->setPhoneNumber($trialRequest->getRepresentativePhone());
  246. $organizationCreationRequest->setSubdomain($trialRequest->getStructureIdentifier());
  247. $organizationCreationRequest->setSendConfirmationEmailAt($trialRequest->getRepresentativeEmail());
  248. // Set default values
  249. $organizationCreationRequest->setProduct(SettingsProductEnum::FREEMIUM);
  250. $organizationCreationRequest->setCreateWebsite(false);
  251. $organizationCreationRequest->setClient(false);
  252. $organizationCreationRequest->setCreationDate(DatesUtils::new());
  253. return $organizationCreationRequest;
  254. }
  255. /**
  256. * Envoie un email à l'administration des ventes pour informer d'une nouvelle demande d'essai artist premium.
  257. *
  258. * @param NewStructureArtistPremiumTrialRequest $trialRequest La demande d'essai
  259. *
  260. * @throws TransportExceptionInterface
  261. */
  262. protected function sendMailToSalesAdministration(NewStructureArtistPremiumTrialRequest $trialRequest): void
  263. {
  264. // Create the email model
  265. $model = new NotificationToSalesAdminModel();
  266. $model
  267. ->setTrialRequest($trialRequest)
  268. ->setSenderId(AccessIdsEnum::ADMIN_2IOPENSERVICE->value);
  269. // Send the email to the sales administration
  270. $this->mailer->main($model);
  271. }
  272. /**
  273. * Envoie un email au représentant pour l'informer que sa demande d'essai artist premium a été validée
  274. * et lui fournir un lien pour créer son compte et accéder au logiciel.
  275. *
  276. * @param NewStructureArtistPremiumTrialRequest $trialRequest La demande d'essai
  277. *
  278. * @throws TransportExceptionInterface
  279. */
  280. protected function sendConfirmationMailToRepresentative(
  281. NewStructureArtistPremiumTrialRequest $trialRequest,
  282. ): void
  283. {
  284. // Create the admin username
  285. $adminUsername = 'admin' . $trialRequest->getStructureIdentifier();
  286. // Create the admin login URL
  287. $adminLoginUrl = UrlBuilder::concat($this->publicAdminBaseUrl, ['#/login/']);
  288. // Create the email model
  289. $model = new ConfirmationToRepresentativeModel();
  290. $model
  291. ->setTrialRequest($trialRequest)
  292. ->setAccountCreationUrl(UrlBuilder::concat($this->publicBaseUrl, ['/account/create']))
  293. ->setFaqUrl($this->faqUrl)
  294. ->setAdminUsername($adminUsername)
  295. ->setAdminLoginUrl($adminLoginUrl)
  296. ->setSenderId(AccessIdsEnum::ADMIN_2IOPENSERVICE->value);
  297. // Send the email to the representative
  298. $this->mailer->main($model);
  299. }
  300. }