ShopService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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\Organization\Subdomain;
  8. use App\Entity\Shop\ShopRequest;
  9. use App\Enum\Access\AccessIdsEnum;
  10. use App\Enum\Organization\SettingsProductEnum;
  11. use App\Enum\Shop\ShopRequestStatus;
  12. use App\Enum\Shop\ShopRequestType;
  13. use App\Message\Message\Shop\NewStructureArtistPremiumTrial;
  14. use App\Service\Dolibarr\DolibarrApiService;
  15. use App\Service\Dolibarr\DolibarrUtils;
  16. use App\Service\Mailer\Mailer;
  17. use App\Service\Mailer\Model\NewStructureArtistPremiumTrialRequestValidationModel;
  18. use App\Service\Organization\OrganizationFactory;
  19. use App\Service\Utils\DatesUtils;
  20. use App\Service\Utils\UrlBuilder;
  21. use Doctrine\DBAL\Exception;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use Doctrine\ORM\Exception\ORMException;
  24. use Doctrine\ORM\OptimisticLockException;
  25. use libphonenumber\PhoneNumberUtil;
  26. use Psr\Log\LoggerInterface;
  27. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  28. use Symfony\Component\Messenger\Exception\ExceptionInterface;
  29. use Symfony\Component\Messenger\MessageBusInterface;
  30. use Symfony\Component\Serializer\SerializerInterface;
  31. use Symfony\Component\Uid\Uuid;
  32. /**
  33. * Service for managing shop requests.
  34. *
  35. * This service handles various shop-related operations.
  36. * It provides functionality for:
  37. * - Registering new shop requests
  38. * - Validating and processing shop requests
  39. * - Creating organizations based on trial requests
  40. * - Starting premium trials for organizations
  41. * - Generating subdomains from structure names
  42. */
  43. class ShopService
  44. {
  45. protected PhoneNumberUtil $phoneNumberUtil;
  46. public function __construct(
  47. private EntityManagerInterface $entityManager,
  48. private Mailer $mailer,
  49. private string $publicBaseUrl,
  50. private OrganizationFactory $organizationFactory,
  51. private SerializerInterface $serializer,
  52. private LoggerInterface $logger,
  53. private MessageBusInterface $messageBus,
  54. private Trial $trial,
  55. ) {
  56. $this->phoneNumberUtil = PhoneNumberUtil::getInstance();
  57. }
  58. /**
  59. * A new shop request has been submitted.
  60. * Register the request, and send the validation link by email.
  61. *
  62. * @param array<string, mixed> $data
  63. *
  64. * @throws TransportExceptionInterface
  65. */
  66. public function registerNewShopRequest(ShopRequestType $type, array $data): ShopRequest
  67. {
  68. $this->controlShopRequestData($type, $data);
  69. $request = $this->createRequest($type, $data);
  70. $this->sendRequestValidationLink($request);
  71. return $request;
  72. }
  73. /**
  74. * Validate the shop request based on its type.
  75. * For NEW_STRUCTURE_ARTIST_PREMIUM_TRIAL, check if the organization already exists.
  76. * For other types, throw an error.
  77. *
  78. * @param array<string, mixed> $data
  79. */
  80. protected function controlShopRequestData(ShopRequestType $type, NewStructureArtistPremiumTrialRequest|array $data): void
  81. {
  82. // @phpstan-ignore-next-line identical.alwaysTrue
  83. if ($type === ShopRequestType::NEW_STRUCTURE_ARTIST_PREMIUM_TRIAL) {
  84. /** @var NewStructureArtistPremiumTrialRequest $request */
  85. $request = $data;
  86. $this->validateNewStructureArtistPremiumTrialRequest($request);
  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->publicBaseUrl,
  136. ['/api/public/shop/validate', $shopRequest->getToken()]
  137. );
  138. $data = $shopRequest->getData();
  139. $model = new NewStructureArtistPremiumTrialRequestValidationModel();
  140. $model
  141. ->setToken($shopRequest->getToken())
  142. ->setRepresentativeEmail($data['representativeEmail'] ?? '')
  143. ->setRepresentativeFirstName($data['representativeFirstName'] ?? '')
  144. ->setRepresentativeLastName($data['representativeLastName'] ?? '')
  145. ->setStructureName($data['structureName'] ?? '')
  146. ->setValidationUrl($validationUrl)
  147. ->setSenderId(AccessIdsEnum::ADMIN_2IOPENSERVICE->value);
  148. $this->mailer->main($model);
  149. $shopRequest->setStatus(ShopRequestStatus::ACTIVATION_LINK_SENT);
  150. $this->entityManager->persist($shopRequest);
  151. $this->entityManager->flush();
  152. }
  153. /**
  154. * Handles the processing of a new structure artist premium trial request.
  155. *
  156. * @param string $token The token identifying the shop request
  157. *
  158. * @throws Exception
  159. * @throws \JsonException
  160. * @throws ORMException
  161. * @throws OptimisticLockException
  162. */
  163. public function handleNewStructureArtistPremiumTrialRequest(string $token): void
  164. {
  165. // Retrieve the ShopRequest entity using its token
  166. $shopRequest = $this->entityManager->find(ShopRequest::class, $token);
  167. if (!$shopRequest) {
  168. $this->logger->error('Cannot find ShopRequest with token: '.$token);
  169. return;
  170. }
  171. // Convert the stored JSON data to a NewStructureArtistPremiumTrialRequest object
  172. $data = $shopRequest->getData();
  173. $trialRequest = $this->serializer->deserialize(
  174. json_encode($data),
  175. NewStructureArtistPremiumTrialRequest::class,
  176. 'json'
  177. );
  178. $organization = $this->createOrganization($trialRequest);
  179. // Start the artist premium trial
  180. $this->trial->startArtistPremiumTrialForNewStructure($organization, $trialRequest);
  181. $this->logger->info('Successfully processed NewStructureArtistPremiumTrial for token: '.$token);
  182. }
  183. /**
  184. * Creates a new organization based on a trial request.
  185. *
  186. * @param NewStructureArtistPremiumTrialRequest $trialRequest The trial request containing organization data
  187. *
  188. * @return Organization The created organization
  189. */
  190. protected function createOrganization(NewStructureArtistPremiumTrialRequest $trialRequest): Organization
  191. {
  192. // Generate an OrganizationCreationRequest object
  193. $organizationCreationRequest = $this->createOrganizationCreationRequestFromTrialRequest($trialRequest);
  194. // Create the organization
  195. return $this->organizationFactory->create($organizationCreationRequest);
  196. }
  197. /**
  198. * Vérifie la validité d'une requête d'essai artist premium pour une nouvelle structure.
  199. */
  200. protected function validateNewStructureArtistPremiumTrialRequest(
  201. NewStructureArtistPremiumTrialRequest $request,
  202. ): void {
  203. // Validate phone number
  204. if (!$this->phoneNumberUtil->isPossibleNumber($request->getRepresentativePhone())) {
  205. throw new \RuntimeException('Invalid phone number');
  206. }
  207. // Check if organization already exists
  208. $organizationCreationRequest = $this->createOrganizationCreationRequestFromTrialRequest($request, true);
  209. $this->organizationFactory->interruptIfOrganizationExists($organizationCreationRequest);
  210. }
  211. /**
  212. * Creates an OrganizationCreationRequest from a NewStructureArtistPremiumTrialRequest.
  213. *
  214. * @param NewStructureArtistPremiumTrialRequest $trialRequest The trial request containing organization data
  215. *
  216. * @return OrganizationCreationRequest The created organization creation request
  217. * @throws \Exception
  218. */
  219. protected function createOrganizationCreationRequestFromTrialRequest(
  220. NewStructureArtistPremiumTrialRequest $trialRequest,
  221. ): OrganizationCreationRequest {
  222. $organizationCreationRequest = new OrganizationCreationRequest();
  223. $organizationCreationRequest->setName($trialRequest->getStructureName());
  224. $organizationCreationRequest->setStreetAddress1($trialRequest->getAddress());
  225. $organizationCreationRequest->setStreetAddress2($trialRequest->getAddressComplement());
  226. $organizationCreationRequest->setPostalCode($trialRequest->getPostalCode());
  227. $organizationCreationRequest->setCity($trialRequest->getCity());
  228. $organizationCreationRequest->setEmail($trialRequest->getStructureEmail());
  229. $organizationCreationRequest->setPrincipalType($trialRequest->getStructureType());
  230. $organizationCreationRequest->setLegalStatus($trialRequest->getLegalStatus());
  231. $organizationCreationRequest->setSiretNumber($trialRequest->getSiren());
  232. $organizationCreationRequest->setPhoneNumber($trialRequest->getRepresentativePhone());
  233. $organizationCreationRequest->setSubdomain($trialRequest->getStructureIdentifier());
  234. // Set default values
  235. $organizationCreationRequest->setProduct(SettingsProductEnum::FREEMIUM);
  236. $organizationCreationRequest->setCreateWebsite(false);
  237. $organizationCreationRequest->setClient(false);
  238. $organizationCreationRequest->setCreationDate(DatesUtils::new());
  239. return $organizationCreationRequest;
  240. }
  241. }