src/Controller/DefaultController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Account;
  4. use App\Entity\Contract;
  5. use App\Entity\ContractState;
  6. use App\Entity\Cotation;
  7. use App\Entity\CotationMultisite;
  8. use App\Entity\CotationState;
  9. use App\Entity\InseeNaf;
  10. use App\Entity\OfferElec;
  11. use App\Entity\OfferGaz;
  12. use App\Entity\ProcedureSign;
  13. use App\Security\PasswordEncoder;
  14. use App\Service\DocusignService;
  15. use App\Service\PappersService;
  16. use App\Service\SendEmailService;
  17. use App\Service\YousignService;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use PieGraph;
  20. use PiePlot;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  23. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  24. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  25. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. use Symfony\Component\Routing\Annotation\Route;
  32. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  33. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  34. /**
  35. * Class DefaultController
  36. * @package App\Controller
  37. *
  38. * @Route("/", name="default_")
  39. */
  40. class DefaultController extends AbstractController
  41. {
  42. /**
  43. * @Route("/", name="homepage")
  44. */
  45. public function indexAction(Request $request)
  46. {
  47. if ($this->getUser()) {
  48. if ($this->isGranted("ROLE_MANAGER")) {
  49. return $this->redirectToRoute("manager_homepage");
  50. }
  51. }
  52. return $this->redirectToRoute("default_login");
  53. }
  54. /**
  55. * @Route(
  56. * path="/login",
  57. * name="login"
  58. * )
  59. *
  60. * @return Response
  61. */
  62. public function loginAction(Request $request, PasswordEncoder $passwordEncoder, EventDispatcherInterface $eventDispatcher)
  63. {
  64. $form = $this->createFormBuilder()
  65. ->add("username", EmailType::class, [
  66. "attr" => [
  67. "placeholder" => "Adresse mail"
  68. ],
  69. "label" => "Adresse mail",
  70. ])
  71. ->add("password", PasswordType::class, [
  72. "attr" => [
  73. "placeholder" => "Mot de passe"
  74. ],
  75. "label" => "Mot de passe",
  76. ])->getForm();
  77. $form->handleRequest($request);
  78. if ($form->isSubmitted() && $form->isValid()) {
  79. $username = $form['username']->getData();
  80. $password = $form['password']->getData();
  81. $account = $this->getDoctrine()->getRepository(Account::class)->findOneBy(['email' => $username]);
  82. if ($account) {
  83. $isValid = $passwordEncoder->isPasswordValid($account->getPassword(), $password, $account->getSalt());
  84. if ($isValid) {
  85. if ($account->getEnabled()) {
  86. $session = $this->get('session');
  87. $firewall = 'main';
  88. $token = new UsernamePasswordToken($account, null, $firewall, $account->getRoles());
  89. $this->get('security.token_storage')->setToken($token);
  90. $session->set('_security_' . $firewall, serialize($token));
  91. //$event = new InteractiveLoginEvent($request, $token);
  92. //$eventDispatcher->dispatch('security.interactive_login', $event);
  93. return $this->redirectToRoute('default_homepage');
  94. } else {
  95. $this->get("session")->getFlashBag()->add("danger", "Compte inactif");
  96. }
  97. } else {
  98. $this->get("session")->getFlashBag()->add("danger", "Identifiant ou mot de passe incorrect");
  99. }
  100. } else {
  101. $this->get("session")->getFlashBag()->add("danger", "Identifiant ou mot de passe incorrect");
  102. }
  103. }
  104. return $this->render('login.html.twig', [
  105. 'form' => $form->createView()
  106. ]);
  107. }
  108. /**
  109. * @Route(
  110. * path="/logout",
  111. * name="logout"
  112. * )
  113. */
  114. public function logoutAction()
  115. {
  116. $this->get('security.token_storage')->setToken(null);
  117. $this->get('session')->invalidate();
  118. return $this->redirectToRoute("default_login");
  119. }
  120. /**
  121. * @Route(
  122. * path="/forgot",
  123. * name="forgot_password"
  124. * )
  125. *
  126. * @param Request $request
  127. * @return Response
  128. */
  129. public function forgotPasswordAction(Request $request, SendEmailService $sendEmailService)
  130. {
  131. $form = $this->createFormBuilder()
  132. ->add('email', EmailType::class, array(
  133. 'attr' => array(
  134. 'placeholder' => 'Adresse mail',
  135. ),
  136. "label" => "Adresse mail",
  137. 'required' => true,
  138. ))
  139. ->getForm();
  140. $form->handleRequest($request);
  141. $error = null;
  142. if ($form->isSubmitted()) {
  143. if ($form->isValid()) {
  144. $data = $form->getData();
  145. $em = $this->getDoctrine()->getManager();
  146. $account = $em->getRepository(Account::class)->findOneBy(["email" => $data["email"]]);
  147. if ($account) {
  148. if ($account->getEnabled()) {
  149. $token = hash("sha256", uniqid());
  150. $account->setPasswordRequest($token);
  151. $account->setPasswordRequestDate(new \DateTime('now'));
  152. $em->flush();
  153. $link = $this->generateUrl("default_reset_password", ["email" => $account->getEmail(), "token" => $token], UrlGeneratorInterface::ABSOLUTE_URL);
  154. $content = <<<EOD
  155. <br/>
  156. Une demande de réinitialisation de mot de passe a été demandée pour votre compte Flash Énergie.<br/>
  157. <br/>
  158. Pour réinitialiser votre mot de passe, rendez-vous sur le lien suivant: <a href="$link">$link</a><br/>
  159. Ce lien est valable 24h.
  160. <br/>
  161. Si vous n'êtes pas à l'origine de ce changement, veuillez contacter en urgence votre responsable.<br/>
  162. EOD;
  163. $sendEmailService->send(
  164. "Flash Énergie: Demande de réinitialisation de mot de passe",
  165. $account->getEmail(),
  166. 'emails/flash_default.html.twig',
  167. [
  168. "title" => "Demande de réinitialisation de mot de passe",
  169. "content" => $content
  170. ]
  171. );
  172. $this->get('session')->getFlashBag()->add("success", "Un mail contenant un lien de réinitialisation a été envoyé à l'adresse indiquée. Ce lien est valide pendant 24h.");
  173. return $this->redirectToRoute("default_login");
  174. } else {
  175. $this->get('session')->getFlashBag()->add("warning", "Votre compte n'est pas actif");
  176. }
  177. } else {
  178. $this->get('session')->getFlashBag()->add("danger", "Aucun compte trouvé avec cette adresse");
  179. }
  180. } else {
  181. $this->get('session')->getFlashBag()->add("warning", "Merci de saisir une adresse mail valide");
  182. }
  183. }
  184. return $this->render('forgot_password.html.twig', [
  185. "form" => $form->createView(),
  186. ]);
  187. }
  188. /**
  189. * @Route(
  190. * path="/reset_password/{email}/{token}",
  191. * name="reset_password"
  192. * )
  193. *
  194. * @param Request $request
  195. * @return Response
  196. */
  197. public function reset_password(Request $request, PasswordEncoder $passwordEncoder, EntityManagerInterface $em)
  198. {
  199. $em = $this->getDoctrine()->getManager();
  200. $account = $em->getRepository(Account::class)->findOneBy(["email" => $request->get("email")]);
  201. if ($account) {
  202. if ($account->getPasswordRequest() && $account->getPasswordRequestDate()) {
  203. if ($account->getPasswordRequest() == $request->get("token")) {
  204. $now = new \DateTime('now');
  205. if ($now->getTimestamp() - $account->getPasswordRequestDate()->getTimestamp() < 86400) {
  206. $label_attr = [
  207. "class" => "font-size-h6 font-weight-bolder text-dark",
  208. ];
  209. $input_attr = [
  210. "class" => "form-control h-auto py-5 px-6 border-0 rounded-lg font-size-h6 step4-view-form-field"
  211. ];
  212. $form = $this->createFormBuilder(null, [])
  213. ->add("password", RepeatedType::class, [
  214. 'type' => PasswordType::class,
  215. 'first_options' => [
  216. "attr" => $input_attr,
  217. "label" => "Mot de passe",
  218. "label_attr" => $label_attr
  219. ],
  220. 'second_options' => [
  221. "attr" => $input_attr,
  222. "label" => "Confirmer le mot de passe",
  223. "label_attr" => $label_attr
  224. ]
  225. ])
  226. ->getForm();
  227. $form->handleRequest($request);
  228. if ($form->isSubmitted() && $form->isValid()) {
  229. $salt = md5(uniqid());
  230. $pwd = $form['password']->getData();
  231. $account->setSalt($salt);
  232. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  233. $account->setPassword($enc_pwd);
  234. $account->setPasswordRequest(null);
  235. $account->setPasswordRequestDate(null);
  236. $em->flush();
  237. $this->get('session')->getFlashBag()->add("success", "Votre mot de passe a été réinitialisé, vous pouvez maintenant vous connecter à votre espace.");
  238. return $this->redirectToRoute("default_login");
  239. }
  240. return $this->render("reset_password.html.twig", [
  241. 'form' => $form->createView()
  242. ]);
  243. } else {
  244. throw new NotFoundHttpException("Cette URL n'est plus valide");
  245. }
  246. } else {
  247. throw new NotFoundHttpException("Cette URL n'est pas valide");
  248. }
  249. }
  250. }
  251. throw new NotFoundHttpException();
  252. }
  253. /**
  254. * @Route(
  255. * path="/yousignevent",
  256. * name="yousignevent"
  257. * )
  258. *
  259. * @param Request $request
  260. * @return Response
  261. */
  262. public function yousignEvent(Request $request, EntityManagerInterface $em, YousignService $yousignService, SendEmailService $sendEmailService)
  263. {
  264. $requestData = json_decode($request->getContent(), true);
  265. $eventName = $request->headers->get("X-Yousign-Event-Name");
  266. if (!$eventName) {
  267. error_log("Header X-Yousign-Event-Name not found.");
  268. throw new BadRequestHttpException("Header X-Yousign-Event-Name not found.");
  269. }
  270. $procedureId = $request->headers->get("X-Flash-Data-Header");
  271. if (!$procedureId) {
  272. error_log("Header X-Flash-Data-Header not found.");
  273. throw new BadRequestHttpException("Header X-Flash-Data-Header not found.");
  274. }
  275. $procedureSign = $em->getRepository(ProcedureSign::class)->find($procedureId);
  276. if (!$procedureSign) {
  277. error_log("ProcedureSign not found.");
  278. throw new BadRequestHttpException("ProcedureSign not found.");
  279. }
  280. switch ($eventName) {
  281. case "procedure.finished":
  282. // Traitement de l'évènement
  283. $procedureJson = json_decode($procedureSign->getContent());
  284. switch ($procedureJson->type) {
  285. case "cotation.acd":
  286. $cotation = $em->getRepository(Cotation::class)->find($procedureJson->id);
  287. $cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
  288. if ($cotation) {
  289. // Récupération du fichier signé
  290. $fileId = $requestData["procedure"]["files"][0]["id"];
  291. $fileContent = $yousignService->getFile($fileId);
  292. if ($fileContent) {
  293. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  294. file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
  295. $cotation->setAcdFile($fileName);
  296. }
  297. $cotation->setAcdSignDate(new \DateTime('now'));
  298. $cotation->setState($cotationStateAcd);
  299. $em->flush();
  300. if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
  301. $companyName = $cotation->getCompanyName();
  302. $content = <<<EOD
  303. <br/>
  304. L'ACD associé à la cotation de <b>$companyName</b> a été signé.<br/>
  305. Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
  306. <br/>
  307. Pricing Flash Énergie
  308. EOD;
  309. $sendEmailService->send(
  310. "CRM Flash Énergie: ACD signé",
  311. $cotation->getManager()->getEmail(),
  312. 'emails/flash_default.html.twig',
  313. [
  314. "title" => "Notification de signature de l'ACD",
  315. "content" => $content
  316. ]
  317. );
  318. }
  319. }
  320. break;
  321. case "cotation.offer":
  322. if ($procedureJson->nrj == "elec") {
  323. $offer = $em->getRepository(OfferElec::class)->find($procedureJson->id);
  324. } else {
  325. $offer = $em->getRepository(OfferGaz::class)->find($procedureJson->id);
  326. }
  327. if ($offer) {
  328. $cotation = $offer->getCotation();
  329. $company = $cotation->getCompany();
  330. // Récupération du fichier signé
  331. $fileId = $requestData["procedure"]["files"][0]["id"];
  332. $fileContent = $yousignService->getFile($fileId);
  333. if ($fileContent) {
  334. $fileName = $company->getId() . "_" . md5(uniqid()) . '.pdf';
  335. file_put_contents($this->getParameter('documents_offers_directory') . $fileName, $fileContent);
  336. $offer->setFile($fileName);
  337. $offer->setSignDate(new \DateTime('now'));
  338. $offer->setProcedureYousignId($requestData["procedure"]["id"]);
  339. }
  340. $em->flush();
  341. // Edition du contrat
  342. $contract = new Contract();
  343. $contract->setUser($cotation->getUser());
  344. $contract->setCompany($cotation->getCompany());
  345. $contract->setSupplier($offer->getSupplier());
  346. $contract->setAddress($cotation->getAddress());
  347. $contract->setAddress2($cotation->getAddress2());
  348. $contract->setZipCode($cotation->getZipCode());
  349. $contract->setCity($cotation->getCity());
  350. $contract->setManager($cotation->getManager());
  351. if ($procedureJson->nrj == "elec") {
  352. $contract->setPdlNumber($cotation->getEPdl());
  353. $contract->setOfferElec($offer);
  354. $contract->setElectricity(true);
  355. $contract->setElectricitySituation($cotation->getElectricitySituation());
  356. $cotation->setSelectedOfferElec($offer);
  357. } else {
  358. $contract->setPceNumber($cotation->getGPce());
  359. $contract->setOfferGaz($offer);
  360. $contract->setGas(true);
  361. $contract->setGasSituation($cotation->getElectricitySituation());
  362. $cotation->setSelectedOfferGaz($offer);
  363. }
  364. $contratStateEnAttenteFournisseur = $em->getRepository(ContractState::class)->find(7);
  365. $contract->setState($contratStateEnAttenteFournisseur);
  366. if ($offer->getFile()) {
  367. $filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
  368. copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
  369. $contract->setFile($offer->getFile());
  370. }
  371. $contract->setSignDate(new \DateTime('now'));
  372. $contract->setProcedureYousignId($requestData["procedure"]["id"]);
  373. $em->persist($contract);
  374. $em->flush();
  375. // Mise à jour du state
  376. if (
  377. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
  378. &&
  379. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
  380. ) {
  381. $stateTerminee = $em->getRepository(CotationState::class)->find(6);
  382. $cotation->setState($stateTerminee);
  383. $em->flush();
  384. }
  385. if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
  386. $companyName = $cotation->getCompanyName();
  387. $content = <<<EOD
  388. <br/>
  389. L'offre associée à la cotation de <b>$companyName</b> a été signé.<br/>
  390. Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
  391. <br/>
  392. Pricing Flash Énergie
  393. EOD;
  394. $sendEmailService->send(
  395. "CRM Flash Énergie: Offre signée",
  396. $cotation->getManager()->getEmail(),
  397. 'emails/flash_default.html.twig',
  398. [
  399. "title" => "Notification de signature de l'offre",
  400. "content" => $content
  401. ]
  402. );
  403. }
  404. }
  405. break;
  406. case "contract.file":
  407. $contract = $em->getRepository(Contract::class)->find($procedureJson->id);
  408. $contractStateAccepted = $em->getRepository(ContractState::class)->find(7);
  409. if ($contract) {
  410. // Récupération du fichier signé
  411. $fileId = $requestData["procedure"]["files"][0]["id"];
  412. $fileContent = $yousignService->getFile($fileId);
  413. if ($fileContent) {
  414. $fileName = $contract->getId() . "_" . md5(uniqid()) . '.pdf';
  415. file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
  416. $contract->setFile($fileName);
  417. }
  418. if ($contract->getState() && $contract->getState()->getId() == 3) {
  419. $contract->setState($contractStateAccepted);
  420. }
  421. $contract->setSignDate(new \DateTime('now'));
  422. $contract->setProcedureYousignId($procedureJson->id);
  423. $em->flush();
  424. if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
  425. $companyName = $contract->getCompany()->getName();
  426. $content = <<<EOD
  427. <br/>
  428. Le contrat de <b>$companyName</b> a été signé.<br/>
  429. <br/>
  430. Pricing Flash Énergie
  431. EOD;
  432. $sendEmailService->send(
  433. "CRM Flash Énergie: contrat signé",
  434. $contract->getManager()->getEmail(),
  435. 'emails/flash_default.html.twig',
  436. [
  437. "title" => "Notification de signature du contrat",
  438. "content" => $content
  439. ]
  440. );
  441. }
  442. }
  443. break;
  444. case "contract.other-file":
  445. $contract = $em->getRepository(Contract::class)->find($procedureJson->id);
  446. if ($contract) {
  447. // Récupération du fichier signé
  448. $fileId = $requestData["procedure"]["files"][0]["id"];
  449. $fileContent = $yousignService->getFile($fileId);
  450. if ($fileContent) {
  451. $fileName = $requestData["procedure"]["files"][0]["name"];
  452. file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
  453. $contract->setOtherFile($fileName);
  454. }
  455. $contract->setOtherFileSignDate(new \DateTime('now'));
  456. $contract->setOtherFileProcedureYousignId($procedureJson->id);
  457. $em->flush();
  458. if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
  459. $companyName = $contract->getCompany()->getName();
  460. $content = <<<EOD
  461. <br/>
  462. Un document associé au contrat de <b>$companyName</b> a été signé.<br/>
  463. <br/>
  464. Pricing Flash Énergie
  465. EOD;
  466. $sendEmailService->send(
  467. "CRM Flash Énergie: document signé",
  468. $contract->getManager()->getEmail(),
  469. 'emails/flash_default.html.twig',
  470. [
  471. "title" => "Notification de signature d'un document",
  472. "content" => $content
  473. ]
  474. );
  475. }
  476. }
  477. break;
  478. }
  479. $procedureSign->setSignDate(new \DateTime('now'));
  480. $em->flush();
  481. break;
  482. }
  483. return new Response("Success", 200);
  484. }
  485. /**
  486. * @Route(
  487. * path="/docusignconnect",
  488. * name="docusignconnect"
  489. * )
  490. *
  491. * @param Request $request
  492. * @return Response
  493. */
  494. public function docusignConnect(Request $request, EntityManagerInterface $em, DocusignService $docusignService, SendEmailService $sendEmailService)
  495. {
  496. //$hmacKey = "MaDBne1eSxgjvu3xJXrfG8KV8zhS3uISPSIP/76CYyg=";
  497. //$hmacKey = "Ed4gs/w9b2Ruhp4FhYDQ/todnR1Tzu3XxnZra24qJJ0=";
  498. $hmacKey = "DjXEsnc9rVIgrmp1hmxiC0HxmQgHjpizBKl+Afk4M8g=";
  499. $payload = file_get_contents('php://input');
  500. $signature = $request->headers->get("X-DocuSign-Signature-1");
  501. if ($docusignService::isValidHmac($hmacKey, $payload, $signature)) {
  502. $payload = json_decode($request->getContent(), true);
  503. $envelopeId = $payload["data"]["envelopeId"];
  504. $procedureSign = $em->getRepository(ProcedureSign::class)->findOneBy(["docusignEnvelopeId" => $envelopeId]);
  505. if (!$procedureSign) {
  506. //throw new BadRequestHttpException("ProcedureSign not found.");
  507. return new Response("ProcedureSign not found.", 200);
  508. }
  509. $accessToken = $docusignService->getAccessToken();
  510. switch ($payload["event"]) {
  511. case "envelope-completed":
  512. // Traitement de l'évènement
  513. $procedureJson = json_decode($procedureSign->getContent());
  514. switch ($procedureJson->type) {
  515. case "cotation.acd":
  516. $cotation = $em->getRepository(Cotation::class)->find($procedureJson->id);
  517. $cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
  518. if ($cotation) {
  519. // Récupération du fichier signé
  520. if ($accessToken) {
  521. $documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
  522. $fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
  523. if ($fileContent) {
  524. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  525. file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
  526. $cotation->setAcdFile($fileName);
  527. }
  528. }
  529. $cotation->setAcdSignDate(new \DateTime('now'));
  530. $cotation->setState($cotationStateAcd);
  531. $em->flush();
  532. if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
  533. $companyName = $cotation->getCompanyName();
  534. $content = <<<EOD
  535. <br/>
  536. L'ACD associé à la cotation monosite de <b>$companyName</b> a été signé.<br/>
  537. Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
  538. <br/>
  539. Pricing Flash Énergie
  540. EOD;
  541. $sendEmailService->send(
  542. "CRM Flash Énergie: ACD signé",
  543. $cotation->getManager()->getEmail(),
  544. 'emails/flash_default.html.twig',
  545. [
  546. "title" => "Notification de signature de l'ACD",
  547. "content" => $content
  548. ]
  549. );
  550. }
  551. }
  552. break;
  553. case "cotation.offer":
  554. if ($procedureJson->nrj == "elec") {
  555. $offer = $em->getRepository(OfferElec::class)->find($procedureJson->id);
  556. } else {
  557. $offer = $em->getRepository(OfferGaz::class)->find($procedureJson->id);
  558. }
  559. if ($offer) {
  560. $cotation = $offer->getCotation();
  561. $company = $cotation->getCompany();
  562. // Récupération du fichier signé
  563. if ($accessToken) {
  564. $documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
  565. $fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
  566. if ($fileContent) {
  567. $fileName = $company->getId() . "_" . md5(uniqid()) . '.pdf';
  568. file_put_contents($this->getParameter('documents_offers_directory') . $fileName, $fileContent);
  569. $offer->setFile($fileName);
  570. $offer->setSignDate(new \DateTime('now'));
  571. $offer->setDocusignEnvelopeId($envelopeId);
  572. }
  573. }
  574. $em->flush();
  575. // Edition du contrat
  576. $contract = new Contract();
  577. $contract->setUser($cotation->getUser());
  578. $contract->setCompany($cotation->getCompany());
  579. $contract->setSupplier($offer->getSupplier());
  580. $contract->setAddress($cotation->getAddress());
  581. $contract->setAddress2($cotation->getAddress2());
  582. $contract->setZipCode($cotation->getZipCode());
  583. $contract->setCity($cotation->getCity());
  584. $contract->setManager($cotation->getManager());
  585. if ($procedureJson->nrj == "elec") {
  586. $contract->setPdlNumber($cotation->getEPdl());
  587. $contract->setOfferElec($offer);
  588. $contract->setElectricity(true);
  589. $contract->setElectricitySituation($cotation->getElectricitySituation());
  590. $cotation->setSelectedOfferElec($offer);
  591. } else {
  592. $contract->setPceNumber($cotation->getGPce());
  593. $contract->setOfferGaz($offer);
  594. $contract->setGas(true);
  595. $contract->setGasSituation($cotation->getElectricitySituation());
  596. $cotation->setSelectedOfferGaz($offer);
  597. }
  598. $contratStateEnAttenteFournisseur = $em->getRepository(ContractState::class)->find(7);
  599. $contract->setState($contratStateEnAttenteFournisseur);
  600. if ($offer->getFile()) {
  601. $filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
  602. copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
  603. $contract->setFile($offer->getFile());
  604. }
  605. $contract->setSignDate(new \DateTime('now'));
  606. $contract->setDocusignEnvelopeId($envelopeId);
  607. $em->persist($contract);
  608. $em->flush();
  609. // Mise à jour du state
  610. if (
  611. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
  612. &&
  613. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
  614. ) {
  615. $stateTerminee = $em->getRepository(CotationState::class)->find(6);
  616. $cotation->setState($stateTerminee);
  617. $em->flush();
  618. }
  619. if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
  620. $companyName = $cotation->getCompanyName();
  621. $content = <<<EOD
  622. <br/>
  623. L'offre associée à la cotation de <b>$companyName</b> a été signé.<br/>
  624. Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
  625. <br/>
  626. Pricing Flash Énergie
  627. EOD;
  628. $sendEmailService->send(
  629. "CRM Flash Énergie: Offre signée",
  630. $cotation->getManager()->getEmail(),
  631. 'emails/flash_default.html.twig',
  632. [
  633. "title" => "Notification de signature de l'offre",
  634. "content" => $content
  635. ]
  636. );
  637. }
  638. }
  639. break;
  640. case "contract.file":
  641. $contract = $em->getRepository(Contract::class)->find($procedureJson->id);
  642. $contractStateAccepted = $em->getRepository(ContractState::class)->find(7);
  643. if ($contract) {
  644. // Récupération du fichier signé
  645. if ($accessToken) {
  646. $documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
  647. $fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
  648. if ($fileContent) {
  649. $fileName = $contract->getId() . "_" . md5(uniqid()) . '.pdf';
  650. file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
  651. $contract->setFile($fileName);
  652. }
  653. }
  654. if ($contract->getState() && $contract->getState()->getId() == 3) {
  655. $contract->setState($contractStateAccepted);
  656. }
  657. $contract->setSignDate(new \DateTime('now'));
  658. $contract->setDocusignEnvelopeId($envelopeId);
  659. $em->flush();
  660. if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
  661. $companyName = $contract->getCompany()->getName();
  662. $content = <<<EOD
  663. <br/>
  664. Le contrat de <b>$companyName</b> a été signé.<br/>
  665. <br/>
  666. Pricing Flash Énergie
  667. EOD;
  668. $sendEmailService->send(
  669. "CRM Flash Énergie: contrat signé",
  670. $contract->getManager()->getEmail(),
  671. 'emails/flash_default.html.twig',
  672. [
  673. "title" => "Notification de signature du contrat",
  674. "content" => $content
  675. ]
  676. );
  677. }
  678. }
  679. break;
  680. case "contract.other-file":
  681. $contract = $em->getRepository(Contract::class)->find($procedureJson->id);
  682. if ($contract) {
  683. // Récupération du fichier signé
  684. if ($accessToken) {
  685. $documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
  686. $fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
  687. if ($fileContent) {
  688. $fileName = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["name"];
  689. file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
  690. $contract->setOtherFile($fileName);
  691. }
  692. }
  693. $contract->setOtherFileSignDate(new \DateTime('now'));
  694. $contract->setOtherFileDocusignEnvelopeId($envelopeId);
  695. $em->flush();
  696. if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
  697. $companyName = $contract->getCompany()->getName();
  698. $content = <<<EOD
  699. <br/>
  700. Un document associé au contrat de <b>$companyName</b> a été signé.<br/>
  701. <br/>
  702. Pricing Flash Énergie
  703. EOD;
  704. $sendEmailService->send(
  705. "CRM Flash Énergie: document signé",
  706. $contract->getManager()->getEmail(),
  707. 'emails/flash_default.html.twig',
  708. [
  709. "title" => "Notification de signature d'un document",
  710. "content" => $content
  711. ]
  712. );
  713. }
  714. }
  715. break;
  716. case "cotation-multisite.acd":
  717. $cotation = $em->getRepository(CotationMultisite::class)->find($procedureJson->id);
  718. $cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
  719. if ($cotation) {
  720. // Récupération du fichier signé
  721. if ($accessToken) {
  722. $documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
  723. $fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
  724. if ($fileContent) {
  725. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  726. file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
  727. $cotation->setAcdFile($fileName);
  728. }
  729. }
  730. $cotation->setAcdSignDate(new \DateTime('now'));
  731. $cotation->setState($cotationStateAcd);
  732. $em->flush();
  733. if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
  734. $companyName = $cotation->getCompanyName();
  735. $content = <<<EOD
  736. <br/>
  737. L'ACD associé à la cotation multisite de <b>$companyName</b> a été signé.<br/>
  738. Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
  739. <br/>
  740. Pricing Flash Énergie
  741. EOD;
  742. $sendEmailService->send(
  743. "CRM Flash Énergie: ACD signé",
  744. $cotation->getManager()->getEmail(),
  745. 'emails/flash_default.html.twig',
  746. [
  747. "title" => "Notification de signature de l'ACD",
  748. "content" => $content
  749. ]
  750. );
  751. }
  752. }
  753. break;
  754. }
  755. $procedureSign->setSignDate(new \DateTime('now'));
  756. $em->flush();
  757. break;
  758. }
  759. } else {
  760. error_log("Bad HMAC verification.");
  761. throw new BadRequestHttpException("Bad HMAC verification.");
  762. }
  763. return new Response("Success", 200);
  764. }
  765. /**
  766. * @Route(
  767. * path="/fe-invitation/{token}",
  768. * name="flash_energie_token"
  769. * )
  770. *
  771. * @param Request $request
  772. * @return Response
  773. */
  774. public function FeInvitationToken(Request $request, EntityManagerInterface $em, $token)
  775. {
  776. return $this->redirect("flashenergie://invitation?token=" . $token, 301);
  777. }
  778. /**
  779. * @Route(
  780. * path="/fe-reset-password/{token}/{mail}",
  781. * name="flash_energie_reset_password_token"
  782. * )
  783. *
  784. * @param Request $request
  785. * @return Response
  786. */
  787. public function FeRestPasswordToken(Request $request, EntityManagerInterface $em, $token, $mail)
  788. {
  789. return $this->redirect("flashenergie://resetPassword?token=" . $token . "&email=" . $mail, 301);
  790. }
  791. /**
  792. * @Route(
  793. * path="/calculatrice-turpe/{id}",
  794. * name="calculatrice-turpe"
  795. * )
  796. *
  797. * @return Response
  798. */
  799. public function calculatriceTurpeAction(Cotation $cotation, Request $request)
  800. {
  801. return $this->render('app/cotations/calculatrice_turpe.html.twig', [
  802. "cotation" => $cotation,
  803. ]);
  804. }
  805. /**
  806. * @Route(
  807. * path="/graph-conso/{id}",
  808. * name="graph-conso"
  809. * )
  810. *
  811. */
  812. public function graphConsoAction(Cotation $cotation, Request $request)
  813. {
  814. require_once($_SERVER["DOCUMENT_ROOT"] . '../../assets/lib/jpgraph/jpgraph.php');
  815. require_once($_SERVER["DOCUMENT_ROOT"] . '../../assets/lib/jpgraph/jpgraph_pie.php');
  816. if ($cotation->getESegment() == "C5") {
  817. $data = array(
  818. $cotation->getEConsommationPointe(),
  819. $cotation->getEConsommationHph(),
  820. $cotation->getEConsommationHch(),
  821. );
  822. $labels = array(
  823. "Base: ".$cotation->getEConsommationPointe()." \n(%.1f%%)",
  824. "HP: ".$cotation->getEConsommationHph()." \n(%.1f%%)",
  825. "HC: ".$cotation->getEConsommationHch()." \n(%.1f%%)",
  826. );
  827. $legends = ['Base', 'HP', 'HC'];
  828. $aCols = 3;
  829. } else {
  830. $data = array(
  831. $cotation->getEConsommationPointe(),
  832. $cotation->getEConsommationHph(),
  833. $cotation->getEConsommationHch(),
  834. $cotation->getEConsommationHpe(),
  835. $cotation->getEConsommationHce()
  836. );
  837. $labels = array(
  838. "Pointe: ".$cotation->getEConsommationPointe()." \n(%.1f%%)",
  839. "HPH: ".$cotation->getEConsommationHph()." \n(%.1f%%)",
  840. "HCH: ".$cotation->getEConsommationHch()." \n(%.1f%%)",
  841. "HPE: ".$cotation->getEConsommationHpe()." \n(%.1f%%)",
  842. "HCE: ".$cotation->getEConsommationHce()." \n(%.1f%%)"
  843. );
  844. $legends = ['Pointe', 'HPH', 'HCH', 'HPE', 'HCE'];
  845. $aCols = 5;
  846. }
  847. // Create the Pie Graph.
  848. $graph = new PieGraph(300,250);
  849. // Set A title for the plot
  850. $graph->title->Set("CAR (MWh)");
  851. $graph->title->SetMargin(0);
  852. $graph->SetBox(true);
  853. $graph->legend->SetPos(0.5,0.97,'center','bottom');
  854. $graph->legend->SetColumns($aCols);
  855. // Create
  856. try {
  857. $p1 = new PiePlot($data);
  858. $p1->SetLegends($legends);
  859. $p1->SetLabels($labels);
  860. $p1->SetLabelPos(1);
  861. $graph->Add($p1);
  862. $p1->ShowBorder();
  863. $p1->SetColor('black');
  864. $p1->SetSliceColors(array('#ff5a78', '#ff9444', '#0099e3', '#ffc55a', '#17b8b7'));
  865. $graph->Stroke();
  866. } catch (\Exception $e) {
  867. return new Response("<img src='' />", 200);
  868. }
  869. }
  870. /**
  871. * @Route(
  872. * path="/external-api/pappers/search",
  873. * name="external-api_pappers_search"
  874. * )
  875. *
  876. */
  877. public function externalApiPappersSearchAction(PappersService $pappersService, Request $request)
  878. {
  879. return new JsonResponse($pappersService->searchCompany($request->get('q')));
  880. }
  881. /**
  882. * @Route(
  883. * path="/naf/search",
  884. * name="naf_search"
  885. * )
  886. *
  887. */
  888. public function nafSearchAction(Request $request, EntityManagerInterface $em)
  889. {
  890. $naf = $em->getRepository(InseeNaf::class)->findOneBy(["code" => strtoupper($request->get('code'))]);
  891. if ($naf) {
  892. return new JsonResponse([
  893. "success" => true,
  894. "code" => $naf->getCode(),
  895. "libelle" => $naf->getLibelle(),
  896. ]);
  897. }
  898. return new JsonResponse([
  899. "success" => false,
  900. ]);
  901. }
  902. }