src/Controller/ManagerController.php line 7813

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Account;
  4. use App\Entity\Company;
  5. use App\Entity\Contract;
  6. use App\Entity\ContractState;
  7. use App\Entity\Cotation;
  8. use App\Entity\CotationDocument;
  9. use App\Entity\CotationMultisite;
  10. use App\Entity\CotationState;
  11. use App\Entity\Device;
  12. use App\Entity\Document;
  13. use App\Entity\Manager;
  14. use App\Entity\Notification;
  15. use App\Entity\OfferElec;
  16. use App\Entity\OfferGaz;
  17. use App\Entity\OfferIndividual;
  18. use App\Entity\ProcedureSign;
  19. use App\Entity\Roadmap;
  20. use App\Entity\SituationGasElec;
  21. use App\Entity\Supplier;
  22. use App\Entity\User;
  23. use App\Form\CompanyType;
  24. use App\Form\ContractType;
  25. use App\Form\CotationMultisiteType;
  26. use App\Form\CotationType;
  27. use App\Form\DocumentType;
  28. use App\Form\ManagerType;
  29. use App\Form\OfferElecType;
  30. use App\Form\OfferGazType;
  31. use App\Form\OfferIndividualType;
  32. use App\Form\RoadmapType;
  33. use App\Form\SupplierType;
  34. use App\Form\UserType;
  35. use App\Repository\CompanyRepository;
  36. use App\Resources\YousignPosition;
  37. use App\Security\PasswordEncoder;
  38. use App\Form\AccountType;
  39. use App\Service\DocusignService;
  40. use App\Service\EllisphereService;
  41. use App\Service\EnedisService;
  42. use App\Service\OfferCalculatorService;
  43. use App\Service\SendEmailService;
  44. use App\Service\TurpeCalculatorService;
  45. use App\Service\YousignService;
  46. use Doctrine\DBAL\Exception\DriverException;
  47. use Doctrine\ORM\EntityManagerInterface;
  48. use Doctrine\ORM\EntityRepository;
  49. use DocuSign\eSign\Client\ApiException;
  50. use Knp\Component\Pager\PaginatorInterface;
  51. use Knp\Snappy\Pdf;
  52. use PhpOffice\PhpSpreadsheet\Reader\Exception;
  53. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  54. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  55. use PhpOffice\PhpSpreadsheet\Style\Border;
  56. use PhpOffice\PhpSpreadsheet\Style\Fill;
  57. use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
  58. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  59. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  60. use setasign\Fpdi\Tcpdf\Fpdi;
  61. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  62. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  63. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  64. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  65. use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
  66. use Symfony\Component\Form\Extension\Core\Type\DateType;
  67. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  68. use Symfony\Component\Form\Extension\Core\Type\FileType;
  69. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  70. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  71. use Symfony\Component\Form\Extension\Core\Type\TextType;
  72. use Symfony\Component\HttpFoundation\File\UploadedFile;
  73. use Symfony\Component\HttpFoundation\JsonResponse;
  74. use Symfony\Component\HttpFoundation\Request;
  75. use Symfony\Component\HttpFoundation\Response;
  76. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  77. use Symfony\Component\HttpFoundation\StreamedResponse;
  78. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  79. use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
  80. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  81. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  82. use Symfony\Component\HttpKernel\KernelInterface;
  83. use Symfony\Component\Routing\Annotation\Route;
  84. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  85. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  86. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  87. use TCPDF;
  88. /**
  89. * Class ManagerController
  90. * @package App\Controller
  91. *
  92. * @Route("/manager", name="manager_")
  93. */
  94. class ManagerController extends AbstractController
  95. {
  96. /**
  97. * @Route("", name="homepage")
  98. */
  99. public function indexAction(Request $request, EntityManagerInterface $em)
  100. {
  101. setlocale(LC_ALL, 'fr_FR');
  102. if ($this->getUser()->getManager()->getAdmin()) {
  103. $contracts = $em->getRepository(Contract::class)->findByExpiryDateBeforeOneYear(null, 15);
  104. } else {
  105. $contracts = $em->getRepository(Contract::class)->findByExpiryDateBeforeOneYear($this->getUser()->getManager(), 15);
  106. }
  107. $documents = $em->getRepository(Document::class)->findBy(["visible" => true], ["creationDate" => "DESC"]);
  108. // Chart
  109. $now = new \DateTime('now');
  110. $x_labels = [utf8_encode(strftime("%b", $now->getTimestamp()))];
  111. for ($i=0; $i < 5; $i++) {
  112. $m = $now->modify('-1 month');
  113. $x_labels[] = utf8_encode(strftime("%b", $m->getTimestamp()));
  114. }
  115. $x_labels = array_reverse($x_labels);
  116. $now = new \DateTime('now');
  117. if ($this->getUser()->getManager()->getAdmin()) {
  118. $q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"));
  119. $y_ca = [$q["ca"] ?: 0];
  120. $y_nb = [$q["nb"] ?: 0];
  121. } else {
  122. $q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"), $this->getUser()->getManager());
  123. $y_ca = [$q["ca"] ?: 0];
  124. $y_nb = [$q["nb"] ?: 0];
  125. }
  126. for ($i=0; $i < 5; $i++) {
  127. $m = $now->modify('-1 month');
  128. if ($this->getUser()->getManager()->getAdmin()) {
  129. $q = $em->getRepository(Contract::class)->getCa($m->format("m"), $now->format("Y"));
  130. $y_ca[] = $q["ca"] ?: 0;
  131. $y_nb[] = $q["nb"] ?: 0;
  132. } else {
  133. $q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"), $this->getUser()->getManager());
  134. $y_ca[] = $q["ca"] ?: 0;
  135. $y_nb[] = $q["nb"] ?: 0;
  136. }
  137. }
  138. $y_ca = array_reverse($y_ca);
  139. $y_nb = array_reverse($y_nb);
  140. $now = new \DateTime('now');
  141. return $this->render("app/dashboard.html.twig", [
  142. 'contracts' => $contracts,
  143. 'documents' => $documents,
  144. 'month_string' => strftime("%B %Y", $now->getTimestamp()),
  145. 'x_labels' => $x_labels,
  146. "y_ca" => $y_ca,
  147. "y_nb" => $y_nb,
  148. ]);
  149. }
  150. /**
  151. * @Route("/account", name="account")
  152. */
  153. public function accountAction(Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
  154. {
  155. $account = $this->getUser();
  156. $r_email = $account->getEmail();
  157. $form = $this->createForm(AccountType::class, $account);
  158. $form["firstName"]->setData($account->getManager()->getFirstName());
  159. $form["lastName"]->setData($account->getManager()->getLastName());
  160. $form2 = $this->createFormBuilder()
  161. ->add('password', RepeatedType::class, array(
  162. 'type' => PasswordType::class,
  163. 'invalid_message' => 'Les mot de passe ne sont pas identiques',
  164. 'first_options' => array(
  165. 'attr' => array(
  166. 'placeholder' => 'Nouveau mot de passe'
  167. ),
  168. 'label' => "Nouveau mot de passe"
  169. ),
  170. 'second_options' => array('attr' => array('placeholder' => 'Confirmez le mot de passe'), 'label' => "Confirmez le mot de passe"),
  171. 'label' => false,
  172. 'mapped' => false
  173. ))->getForm();
  174. $form->handleRequest($request);
  175. $form2->handleRequest($request);
  176. if ($form->isSubmitted() && !$form->isValid()) {
  177. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  178. }
  179. if ($form->isSubmitted() && $form->isValid()) {
  180. $error = false;
  181. if ($r_email != $account->getEmail()) {
  182. if (filter_var($account->getEmail(), FILTER_VALIDATE_EMAIL)) {
  183. $other_account = $em->getRepository(Account::class)->findOneBy(['email' => $account->getEmail()]);
  184. if ($other_account && $other_account->getId() != $account->getId()) {
  185. $error = true;
  186. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
  187. }
  188. } else {
  189. $error = true;
  190. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
  191. }
  192. }
  193. if (!$error) {
  194. $account->getManager()->setFirstName($form['firstName']->getData());
  195. $account->getManager()->setLastName($form['lastName']->getData());
  196. $em->flush();
  197. $oldToken = $this->get('security.token_storage')->getToken();
  198. $token = new UsernamePasswordToken(
  199. $account, //user object with updated username
  200. null,
  201. $oldToken->getProviderKey(),
  202. $oldToken->getRoles()
  203. );
  204. $this->get('security.token_storage')->setToken($token);
  205. $this->get('session')->getFlashBag()->add('success', 'Profil mis à jour avec succès');
  206. return $this->redirectToRoute('manager_account');
  207. }
  208. }
  209. if ($form2->isSubmitted() && $form2->isValid()) {
  210. $salt = md5(uniqid());
  211. $pwd = $form2['password']->getData();
  212. $account->setSalt($salt);
  213. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  214. $account->setPassword($enc_pwd);
  215. $em->flush();
  216. $this->get('session')->getFlashBag()->add('success', 'Mot de passe mis à jour');
  217. return $this->redirectToRoute('manager_account');
  218. }
  219. return $this->render('app/account.html.twig', [
  220. 'form' => $form->createView(),
  221. 'form2' => $form2->createView(),
  222. ]);
  223. }
  224. /**
  225. * @Route("/suppliers", name="suppliers")
  226. */
  227. public function suppliersAction(Request $request, EntityManagerInterface $em)
  228. {
  229. if (!$this->getUser()->getManager()->getAdmin()) {
  230. throw new UnauthorizedHttpException("Not admin");
  231. }
  232. $suppliers = $em->getRepository(Supplier::class)->findAll();
  233. return $this->render("app/suppliers/list.html.twig", [
  234. "suppliers" => $suppliers
  235. ]);
  236. }
  237. /**
  238. * @Route("/suppliers/add", name="suppliers_add")
  239. */
  240. public function suppliersAddAction(Request $request, EntityManagerInterface $em)
  241. {
  242. if (!$this->getUser()->getManager()->getAdmin()) {
  243. throw new UnauthorizedHttpException("Not admin");
  244. }
  245. $supplier = new Supplier();
  246. $supplier->setGas(true);
  247. $supplier->setElectricity(true);
  248. $form = $this->createForm(SupplierType::class, $supplier);
  249. $form->handleRequest($request);
  250. if ($form->isSubmitted() && !$form->isValid()) {
  251. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  252. }
  253. if ($form->isSubmitted() && $form->isValid()) {
  254. $em->persist($supplier);
  255. $em->flush();
  256. $logo = $form['logo']->getData();
  257. if ($logo) {
  258. $extension = $logo->guessExtension();
  259. if (!$extension || !in_array($extension, ["png", "jpeg", "jpg", "gif", "svg"])) {
  260. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le logo");
  261. } else {
  262. $fileName = $supplier->getId() . "_" . md5(uniqid()) . '.' . $extension;
  263. $logo->move(
  264. $this->getParameter('documents_logos_directory'),
  265. $fileName
  266. );
  267. $supplier->setLogo($fileName);
  268. $em->flush();
  269. }
  270. }
  271. $this->get("session")->getFlashBag()->add("success", "Nouveau fournisseur ajouté");
  272. return $this->redirectToRoute("manager_suppliers");
  273. }
  274. return $this->render("app/suppliers/form.html.twig", [
  275. "form" => $form->createView(),
  276. "title" => "Ajouter un fournisseur",
  277. ]);
  278. }
  279. /**
  280. * @Route("/suppliers/{supplier}/edit", name="suppliers_edit")
  281. */
  282. public function suppliersEditAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
  283. {
  284. if (!$this->getUser()->getManager()->getAdmin()) {
  285. throw new UnauthorizedHttpException("Not admin");
  286. }
  287. $form = $this->createForm(SupplierType::class, $supplier);
  288. $form->handleRequest($request);
  289. if ($form->isSubmitted() && !$form->isValid()) {
  290. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  291. }
  292. if ($form->isSubmitted() && $form->isValid()) {
  293. $em->flush();
  294. $logo = $form['logo']->getData();
  295. if ($logo) {
  296. $extension = $logo->guessExtension();
  297. if (!$extension || !in_array($extension, ["png", "jpeg", "jpg", "gif", "svg"])) {
  298. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le logo");
  299. } else {
  300. $fileName = $supplier->getId() . "_" . md5(uniqid()) . '.' . $extension;
  301. $logo->move(
  302. $this->getParameter('documents_logos_directory'),
  303. $fileName
  304. );
  305. $supplier->setLogo($fileName);
  306. $em->flush();
  307. }
  308. }
  309. $this->get("session")->getFlashBag()->add("success", "Fournisseur mis à jour");
  310. return $this->redirectToRoute("manager_suppliers");
  311. }
  312. return $this->render("app/suppliers/form.html.twig", [
  313. "form" => $form->createView(),
  314. "title" => "Modifier un fournisseur",
  315. ]);
  316. }
  317. /**
  318. * @Route("/suppliers/{supplier}/active", name="suppliers_active")
  319. */
  320. public function suppliersActiveAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
  321. {
  322. if (!$this->getUser()->getManager()->getAdmin()) {
  323. throw new UnauthorizedHttpException("Not admin");
  324. }
  325. $supplier->setActive(true);
  326. $em->flush();
  327. $this->get("session")->getFlashBag()->add("success", "Fournisseur activé");
  328. return $this->redirectToRoute("manager_suppliers");
  329. }
  330. /**
  331. * @Route("/suppliers/{supplier}/deactive", name="suppliers_deactive")
  332. */
  333. public function suppliersDeactiveAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
  334. {
  335. if (!$this->getUser()->getManager()->getAdmin()) {
  336. throw new UnauthorizedHttpException("Not admin");
  337. }
  338. $supplier->setActive(false);
  339. $em->flush();
  340. $this->get("session")->getFlashBag()->add("success", "Fournisseur désactivé");
  341. return $this->redirectToRoute("manager_suppliers");
  342. }
  343. /**
  344. * @Route("/suppliers/{supplier}/delete", name="suppliers_delete")
  345. */
  346. public function suppliersDeleteAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
  347. {
  348. if (!$this->getUser()->getManager()->getAdmin()) {
  349. throw new UnauthorizedHttpException("Not admin");
  350. }
  351. // On vérifie que le fournisseur n'est pas associé à un contrat, une cotation ou une offre
  352. $contrats = $em->getRepository(Contract::class)->findBy(['supplier' => $supplier]);
  353. if ($contrats && count($contrats) > 0) {
  354. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des contrats.");
  355. return $this->redirectToRoute("manager_suppliers");
  356. }
  357. $cotations = $em->getRepository(Cotation::class)->findBy(['desiredSupplier' => $supplier]);
  358. if ($cotations && count($cotations) > 0) {
  359. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
  360. return $this->redirectToRoute("manager_suppliers");
  361. }
  362. $cotations = $em->getRepository(Cotation::class)->findBy(['eDesiredSuppliers' => $supplier]);
  363. if ($cotations && count($cotations) > 0) {
  364. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
  365. return $this->redirectToRoute("manager_suppliers");
  366. }
  367. $cotations = $em->getRepository(Cotation::class)->findBy(['gDesiredSuppliers' => $supplier]);
  368. if ($cotations && count($cotations) > 0) {
  369. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
  370. return $this->redirectToRoute("manager_suppliers");
  371. }
  372. $cotations = $em->getRepository(Cotation::class)->findBy(['electricitySupplier' => $supplier]);
  373. if ($cotations && count($cotations) > 0) {
  374. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
  375. return $this->redirectToRoute("manager_suppliers");
  376. }
  377. $cotations = $em->getRepository(Cotation::class)->findBy(['gasSupplier' => $supplier]);
  378. if ($cotations && count($cotations) > 0) {
  379. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
  380. return $this->redirectToRoute("manager_suppliers");
  381. }
  382. $offersElec = $em->getRepository(OfferElec::class)->findBy(['supplier' => $supplier]);
  383. if ($offersElec && count($offersElec) > 0) {
  384. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des offres.");
  385. return $this->redirectToRoute("manager_suppliers");
  386. }
  387. $offersGaz = $em->getRepository(OfferGaz::class)->findBy(['supplier' => $supplier]);
  388. if ($offersGaz && count($offersGaz) > 0) {
  389. $this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des offres.");
  390. return $this->redirectToRoute("manager_suppliers");
  391. }
  392. try {
  393. $em->remove($supplier);
  394. $em->flush();
  395. $this->get("session")->getFlashBag()->add("success", "Fournisseur supprimé");
  396. } catch (\Exception $e) {
  397. $this->get("session")->getFlashBag()->add("danger", "Impossible de supprimer ce fournisseur.");
  398. }
  399. return $this->redirectToRoute("manager_suppliers");
  400. }
  401. /**
  402. * @Route("/clients", name="clients")
  403. */
  404. public function clientsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  405. {
  406. $page = $request->get("page");
  407. if (!is_numeric($page) || $page < 1) {
  408. $page = 1;
  409. }
  410. $nbByPage = 20;
  411. $keywords = null;
  412. if ($request->get("search")) {
  413. $terms = explode(" ", $request->get("search"));
  414. if (count($terms)) {
  415. $keywords = $terms;
  416. }
  417. }
  418. if ($request->get("particulier")) {
  419. if ($request->get("export") && $this->getUser()->getManager()->getAdmin()) {
  420. $response = new StreamedResponse();
  421. $users_export = $em->getRepository(User::class)->searchForTerms($keywords, null, true, false);
  422. $response->setCallback(function () use ($users_export) {
  423. $handle = fopen('php://output', 'w+');
  424. fputcsv($handle, [], ';');
  425. foreach ($users_export as $user) {
  426. $data = array(
  427. utf8_decode($user->getEmail()),
  428. );
  429. fputcsv($handle, $data, ';');
  430. }
  431. fclose($handle);
  432. });
  433. $response->setStatusCode(200);
  434. $response->headers->set('Content-Encoding', 'UTF-8');
  435. $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
  436. $response->headers->set('Content-Disposition', 'attachment; filename="export_particulier.csv"');
  437. return $response;
  438. }
  439. if ($this->getUser()->getManager()->getAdmin()) {
  440. $users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, true, false);
  441. } else {
  442. $users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), true, false);
  443. }
  444. return $this->render("app/clients/list.html.twig", [
  445. "users_paginator" => $users_paginator,
  446. "title" => "Clients particuliers",
  447. "pro" => false,
  448. ]);
  449. } elseif ($request->get("pro")) {
  450. if ($request->get("export") && $this->getUser()->getManager()->getAdmin()) {
  451. $response = new StreamedResponse();
  452. $users_export = $em->getRepository(User::class)->searchForTerms($keywords, null, false, true);
  453. $response->setCallback(function () use ($users_export) {
  454. $handle = fopen('php://output', 'w+');
  455. fputcsv($handle, [], ';');
  456. foreach ($users_export as $user) {
  457. $data = array(
  458. utf8_decode($user->getEmail()),
  459. );
  460. fputcsv($handle, $data, ';');
  461. }
  462. fclose($handle);
  463. });
  464. $response->setStatusCode(200);
  465. $response->headers->set('Content-Encoding', 'UTF-8');
  466. $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
  467. $response->headers->set('Content-Disposition', 'attachment; filename="export_pro.csv"');
  468. return $response;
  469. }
  470. $title = "Clients professionnels";
  471. if ($request->get("onlyNotValidated") && $this->getUser()->getManager()->getAdmin()) {
  472. $users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true, true);
  473. $title = "Clients professionnels à valider";
  474. } else {
  475. if ($this->getUser()->getManager()->getAdmin()) {
  476. $users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true);
  477. } else {
  478. $users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), false, true);
  479. }
  480. }
  481. return $this->render("app/clients/list.html.twig", [
  482. "users_paginator" => $users_paginator,
  483. "title" => $title,
  484. "pro" => true,
  485. "onlyNotValidated" => (bool) $request->get("onlyNotValidated"),
  486. ]);
  487. }
  488. throw new NotAcceptableHttpException();
  489. }
  490. /**
  491. * @Route("/clients/archive", name="clients_archive")
  492. */
  493. public function clientsArchiveAction(Request $request, EntityManagerInterface $em)
  494. {
  495. if (!$this->getUser()->getManager()->getAdmin()) {
  496. throw new UnauthorizedHttpException("Not admin");
  497. }
  498. $clientsId = $request->get("clientsId");
  499. if (!$clientsId) {
  500. throw new BadRequestHttpException("Missing clientsId.");
  501. }
  502. foreach (explode(";",$clientsId) as $clientId) {
  503. $user = $em->getRepository(User::class)->find($clientId);
  504. if ($user) {
  505. $user->setArchived(true);
  506. }
  507. }
  508. $em->flush();
  509. $this->get("session")->getFlashBag()->add("success", "Clients archivés avec succès");
  510. $from = $request->get("from");
  511. if ($from) {
  512. return $this->redirect($from);
  513. }
  514. return $this->redirectToRoute("manager_clients", ["pro" => 1]);
  515. }
  516. /**
  517. * @Route("/clients/add", name="clients_add")
  518. */
  519. public function clientsAddAction(Request $request, EntityManagerInterface $em)
  520. {
  521. if ($request->get("particulier")) {
  522. $user = new User();
  523. $user->setGas(true);
  524. $user->setElectricity(true);
  525. $form = $this->createForm(UserType::class, $user);
  526. if ($this->getUser()->getManager()->getAdmin()) {
  527. $form->add('manager', EntityType::class, [
  528. "label" => "Commercial associé",
  529. 'class' => Manager::class,
  530. 'query_builder' => function (EntityRepository $er) {
  531. return $er->createQueryBuilder('m')
  532. ->leftJoin("m.account", "a")
  533. ->where('a.enabled = true');
  534. },
  535. 'choice_label' => 'fullName',
  536. 'attr' => [
  537. "data-control" => "select2",
  538. ],
  539. "required" => false,
  540. "mapped" => true,
  541. ]);
  542. }
  543. $form->handleRequest($request);
  544. if ($form->isSubmitted() && !$form->isValid()) {
  545. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  546. }
  547. if ($form->isSubmitted() && $form->isValid()) {
  548. $user->setCreationDate(new \DateTime("now"));
  549. $user->setManager($this->getUser()->getManager());
  550. $user->setPro(false);
  551. $em->persist($user);
  552. $em->flush();
  553. $this->get("session")->getFlashBag()->add("success", "Nouveau client ajouté");
  554. return $this->redirectToRoute("manager_clients_edit", ["user" => $user->getId()]);
  555. }
  556. return $this->render("app/clients/form.html.twig", [
  557. "form" => $form->createView(),
  558. "title" => "Ajouter un client",
  559. ]);
  560. } elseif ($request->get("pro")) {
  561. $company = new Company();
  562. $roadmap = null;
  563. if ($request->get("roadmap")) {
  564. $roadmap = $em->getRepository(Roadmap::class)->find($request->get("roadmap"));
  565. if ($roadmap) {
  566. if (!$this->getUser()->getManager()->getAdmin()) {
  567. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId()) {
  568. $roadmap = null;
  569. }
  570. }
  571. if ($roadmap->getArchived()) {
  572. $roadmap = null;
  573. }
  574. }
  575. }
  576. $form = $this->createForm(CompanyType::class, $company);
  577. if ($roadmap) {
  578. $company->setName($roadmap->getCompanyName());
  579. $company->setSiret($roadmap->getSiret());
  580. $company->setPhone($roadmap->getPhone());
  581. $company->setEmail($roadmap->getEmail());
  582. $company->setCity($roadmap->getSector());
  583. // Engie PRO
  584. if ($roadmap->getContractType()->getId() == 4) {
  585. $form->add('powerSubscribed', TextType::class, [
  586. "label" => "Puissance souscrite (kVA)",
  587. "attr" => [
  588. "placeholder" => "Puissance souscrite",
  589. ],
  590. "mapped" => false,
  591. "required" => false,
  592. ])
  593. ->add('eSituation', EntityType::class, [
  594. "label" => "Situation",
  595. 'class' => SituationGasElec::class,
  596. 'query_builder' => function (EntityRepository $er) {
  597. return $er->createQueryBuilder('s')
  598. ->where('s.electricity = true');
  599. },
  600. 'choice_label' => 'libelle',
  601. "mapped" => false,
  602. "required" => false,
  603. ])
  604. ->add('eSegment', ChoiceType::class, [
  605. "label" => "Segment",
  606. "placeholder" => "Segment",
  607. "choices" => [
  608. "C1" => "C1",
  609. "C2" => "C2",
  610. "C3" => "C3",
  611. "C4" => "C4",
  612. "C5" => "C5",
  613. ],
  614. "mapped" => false,
  615. "required" => false,
  616. ])
  617. ->add('eDuree', ChoiceType::class, [
  618. "label" => "Durée",
  619. "placeholder" => "Durée",
  620. "choices" => [
  621. "1 an" => "1",
  622. "2 ans" => "2",
  623. "3 ans" => "3",
  624. "Sans engagement" => "0",
  625. ],
  626. "mapped" => false,
  627. "required" => false,
  628. ])
  629. ->add('eCommitmentDate', DateType::class, [
  630. "label" => "Date de début d'engagement",
  631. 'data' => new \DateTime(),
  632. 'widget' => 'single_text',
  633. 'html5' => true,
  634. "mapped" => false,
  635. "required" => false,
  636. ])
  637. ->add('eOptEnergieVerte', ChoiceType::class, [
  638. "label" => "Option: Énergie verte",
  639. "placeholder" => "Énergie verte",
  640. "choices" => [
  641. "Oui" => "100",
  642. "Non" => "0",
  643. ],
  644. "mapped" => false,
  645. "required" => false,
  646. ])
  647. ->add('quantityConsumed', ChoiceType::class, [
  648. "label" => "Quantité consommée",
  649. 'choices' => [
  650. "0-6MWH" => "0-6MWH",
  651. "6-30MWH" => "6-30MWH",
  652. "30-50MWH" => "30-50MWH",
  653. "50-100MWH" => "50-100MWH",
  654. "100-200MWH" => "100-200MWH",
  655. ">200MWH" => ">200MWH",
  656. ],
  657. "mapped" => false,
  658. "required" => false,
  659. ])
  660. ->add('gSituation', EntityType::class, [
  661. "label" => "Situation",
  662. 'class' => SituationGasElec::class,
  663. 'query_builder' => function (EntityRepository $er) {
  664. return $er->createQueryBuilder('s')
  665. ->where('s.gas = true');
  666. },
  667. 'choice_label' => 'libelle',
  668. "mapped" => false,
  669. "required" => false,
  670. ])
  671. ->add('gSegment', ChoiceType::class, [
  672. "label" => "Segment",
  673. "placeholder" => "Segment",
  674. "choices" => [
  675. "P1 (jusqu'à 5999 kWh)" => "P1",
  676. "P2 (de 6000 à 29 999 kWh)" => "P2",
  677. "P3 (plus de 30 000 kWh)" => "P3",
  678. ],
  679. "mapped" => false,
  680. "required" => false,
  681. ])
  682. ->add('gDuree', ChoiceType::class, [
  683. "label" => "Durée",
  684. "placeholder" => "Durée",
  685. "choices" => [
  686. "1 an" => "1",
  687. "2 ans" => "2",
  688. "3 ans" => "3",
  689. "Sans engagement" => "0",
  690. ],
  691. "mapped" => false,
  692. "required" => false,
  693. ])
  694. ->add('gCommitmentDate', DateType::class, [
  695. "label" => "Date de début d'engagement",
  696. 'data' => new \DateTime(),
  697. 'widget' => 'single_text',
  698. 'html5' => true,
  699. "mapped" => false,
  700. "required" => false,
  701. ])
  702. ->add('gOptEnergieVerte', ChoiceType::class, [
  703. "label" => "Option: Énergie verte",
  704. "placeholder" => "Énergie verte",
  705. "choices" => [
  706. "Oui" => "100",
  707. "Non" => "0",
  708. ],
  709. "mapped" => false,
  710. "required" => false,
  711. ])
  712. ;
  713. }
  714. // TELECOM
  715. if ($roadmap->getContractType()->getId() == 5) {
  716. $form->add('offer', ChoiceType::class, [
  717. "label" => "Offre",
  718. "placeholder" => "Offre",
  719. "choices" => [
  720. "FREEBOX PRO" => "FREEBOX PRO",
  721. "FREEBOX PRO + FORFAIT MOBILE FREE PRO" => "FREEBOX PRO + FORFAIT MOBILE FREE PRO",
  722. ],
  723. "mapped" => false,
  724. "required" => false,
  725. ])
  726. ->add('duree', ChoiceType::class, [
  727. "label" => "Durée d'engagement",
  728. "placeholder" => "Durée d'engagement",
  729. "choices" => [
  730. "24 mois" => "24",
  731. "36 mois" => "36",
  732. ],
  733. "mapped" => false,
  734. "required" => false,
  735. ])
  736. ->add('optionPremium', CheckboxType::class, [
  737. "label" => "Option premium",
  738. "mapped" => false,
  739. "required" => false,
  740. ])
  741. ->add('rio', TextType::class, [
  742. "label" => "RIO (si option mobile et demande de transfert)",
  743. "attr" => [
  744. "placeholder" => "RIO",
  745. ],
  746. "mapped" => false,
  747. "required" => false,
  748. ])
  749. ;
  750. }
  751. // PHOTOVOLTAIQUE
  752. if ($roadmap->getContractType()->getId() == 6) {
  753. $form->add('buildingType', TextType::class, [
  754. "label" => "Type de bâtisse",
  755. "attr" => [
  756. "placeholder" => "Type de bâtisse",
  757. ],
  758. "mapped" => false,
  759. "required" => false,
  760. ])
  761. ->add('buildingYear', TextType::class, [
  762. "label" => "Année de construction",
  763. "attr" => [
  764. "placeholder" => "Année de construction",
  765. ],
  766. "mapped" => false,
  767. "required" => false,
  768. ])
  769. ->add('surface', TextType::class, [
  770. "label" => "Surface",
  771. "attr" => [
  772. "placeholder" => "Surface",
  773. ],
  774. "mapped" => false,
  775. "required" => false,
  776. ])
  777. ->add('exposition', TextType::class, [
  778. "label" => "Exposition",
  779. "attr" => [
  780. "placeholder" => "Exposition",
  781. ],
  782. "mapped" => false,
  783. "required" => false,
  784. ])
  785. ->add('mainMaterial', TextType::class, [
  786. "label" => "Matière principale",
  787. "attr" => [
  788. "placeholder" => "Matière principale",
  789. ],
  790. "mapped" => false,
  791. "required" => false,
  792. ])
  793. ->add('recentWork', CheckboxType::class, [
  794. "label" => "Travaux récents",
  795. "mapped" => false,
  796. "required" => false,
  797. ])
  798. ;
  799. }
  800. }
  801. if ($roadmap) {
  802. $form->get("firstName")->setData($roadmap->getFirstName());
  803. $form->get("lastName")->setData($roadmap->getLastName());
  804. $form->get("phone")->setData($roadmap->getPhone());
  805. $form->get("email")->setData($roadmap->getEmail());
  806. $form->get("name")->setData($roadmap->getCompanyName());
  807. $form->get("siret")->setData($roadmap->getSiret());
  808. $form->get("city")->setData($roadmap->getSector());
  809. $form->get("position")->setData($roadmap->getPosition());
  810. }
  811. $form->handleRequest($request);
  812. if ($form->isSubmitted() && !$form->isValid()) {
  813. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  814. }
  815. if ($form->isSubmitted() && $form->isValid()) {
  816. $user = new User();
  817. $user->setFirstName($form["firstName"]->getData());
  818. $user->setLastName($form["lastName"]->getData());
  819. $user->setPosition($form["position"]->getData());
  820. $user->setStepInProcess($form["stepInProcess"]->getData());
  821. $user->setComment($form["comment"]->getData());
  822. $user->setPhone($company->getPhone());
  823. $user->setEmail($company->getEmail());
  824. $user->setCreationDate(new \DateTime("now"));
  825. $user->setManager($this->getUser()->getManager());
  826. $user->setPro(true);
  827. $company->setUser($user);
  828. $em->persist($company);
  829. $em->persist($user);
  830. $em->flush();
  831. if ($roadmap) {
  832. $roadmap->setArchived(true);
  833. $roadmap->setCompany($company);
  834. $em->flush();
  835. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 4) {
  836. $this->roadmapEngieProToContract(
  837. $roadmap,
  838. $company,
  839. $form->get("electricity")->getData(),
  840. $form->get("powerSubscribed")->getData(),
  841. $form->get("eSituation")->getData(),
  842. $form->get("eSegment")->getData(),
  843. $form->get("eCommitmentDate")->getData(),
  844. intval($form->get("eDuree")->getData()),
  845. $form->get("eOptEnergieVerte")->getData(),
  846. $form->get("gas")->getData(),
  847. $form->get("quantityConsumed")->getData(),
  848. $form->get("gSituation")->getData(),
  849. $form->get("gSegment")->getData(),
  850. $form->get("gCommitmentDate")->getData(),
  851. intval($form->get("gDuree")->getData()),
  852. $form->get("gOptEnergieVerte")->getData(),
  853. $em
  854. );
  855. }
  856. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 5) {
  857. $this->roadmapTelecomToContract(
  858. $roadmap,
  859. $company,
  860. $form->get("offer")->getData(),
  861. $form->get("duree")->getData(),
  862. $form->get("optionPremium")->getData(),
  863. $form->get("rio")->getData(),
  864. $em
  865. );
  866. }
  867. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 6) {
  868. $this->roadmapPhotovoltaiqueToContract(
  869. $roadmap,
  870. $company,
  871. $form->get("buildingType")->getData(),
  872. $form->get("buildingYear")->getData(),
  873. $form->get("surface")->getData(),
  874. $form->get("exposition")->getData(),
  875. $form->get("mainMaterial")->getData(),
  876. $form->get("recentWork")->getData(),
  877. $em
  878. );
  879. }
  880. }
  881. $fileJustificatif = $form['justificatif']->getData();
  882. if ($fileJustificatif) {
  883. $extension = $fileJustificatif->guessExtension();
  884. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  885. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le justificati");
  886. } else {
  887. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  888. $fileJustificatif->move(
  889. $this->getParameter('documents_justificatif_directory'),
  890. $fileName
  891. );
  892. $company->setJustificatif($fileName);
  893. $em->flush();
  894. }
  895. }
  896. $fileFactElec = $form['factElec']->getData();
  897. if ($fileFactElec) {
  898. $extension = $fileFactElec->guessExtension();
  899. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  900. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
  901. } else {
  902. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  903. $fileFactElec->move(
  904. $this->getParameter('documents_justificatif_directory'),
  905. $fileName
  906. );
  907. $company->setFactElec($fileName);
  908. $em->flush();
  909. }
  910. }
  911. $fileFactGas = $form['factGas']->getData();
  912. if ($fileFactGas) {
  913. $extension = $fileFactGas->guessExtension();
  914. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  915. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
  916. } else {
  917. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  918. $fileFactGas->move(
  919. $this->getParameter('documents_justificatif_directory'),
  920. $fileName
  921. );
  922. $company->setFactGas($fileName);
  923. $em->flush();
  924. }
  925. }
  926. $fileLiaseFiscale = $form['liasseFiscale']->getData();
  927. if ($fileLiaseFiscale) {
  928. $extension = $fileLiaseFiscale->guessExtension();
  929. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  930. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
  931. } else {
  932. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  933. $fileLiaseFiscale->move(
  934. $this->getParameter('documents_justificatif_directory'),
  935. $fileName
  936. );
  937. $company->setLiasseFiscale($fileName);
  938. $em->flush();
  939. }
  940. }
  941. $fileSgeElec = $form['sgeElec']->getData();
  942. if ($fileSgeElec) {
  943. $extension = $fileSgeElec->guessExtension();
  944. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  945. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
  946. } else {
  947. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  948. $fileSgeElec->move(
  949. $this->getParameter('documents_justificatif_directory'),
  950. $fileName
  951. );
  952. $company->setSgeElec($fileName);
  953. $em->flush();
  954. }
  955. }
  956. $fileOmegaGas = $form['omegaGas']->getData();
  957. if ($fileOmegaGas) {
  958. $extension = $fileOmegaGas->guessExtension();
  959. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  960. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
  961. } else {
  962. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  963. $fileOmegaGas->move(
  964. $this->getParameter('documents_justificatif_directory'),
  965. $fileName
  966. );
  967. $company->setOmegaGas($fileName);
  968. $em->flush();
  969. }
  970. }
  971. $fileExcelMultisite = $form['excelMultisite']->getData();
  972. if ($fileExcelMultisite) {
  973. $extension = $fileExcelMultisite->guessExtension();
  974. if (!$extension || !in_array($extension, ["csv", "xls", "xlsx"])) {
  975. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour l'excel multisite");
  976. } else {
  977. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  978. $fileExcelMultisite->move(
  979. $this->getParameter('documents_justificatif_directory'),
  980. $fileName
  981. );
  982. $company->setExcelMultisite($fileName);
  983. $em->flush();
  984. }
  985. }
  986. $this->get("session")->getFlashBag()->add("success", "Nouveau client ajouté.");
  987. return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
  988. }
  989. return $this->render("app/clients/form_pro.html.twig", [
  990. "form" => $form->createView(),
  991. "title" => "Ajouter un client",
  992. "company" => $company,
  993. "roadmap" => $roadmap,
  994. ]);
  995. }
  996. throw new NotAcceptableHttpException();
  997. }
  998. /**
  999. * @Route("/clients/{user}/edit", name="clients_edit")
  1000. */
  1001. public function clientsEditAction(Request $request, EntityManagerInterface $em, User $user)
  1002. {
  1003. if (!$this->getUser()->getManager()->getAdmin()) {
  1004. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1005. throw new NotFoundHttpException();
  1006. }
  1007. }
  1008. $form = $this->createForm(UserType::class, $user);
  1009. if ($this->getUser()->getManager()->getAdmin()) {
  1010. $form->add('manager', EntityType::class, [
  1011. "label" => "Commercial associé",
  1012. 'class' => Manager::class,
  1013. 'query_builder' => function (EntityRepository $er) {
  1014. return $er->createQueryBuilder('m')
  1015. ->leftJoin("m.account", "a")
  1016. ->where('a.enabled = true');
  1017. },
  1018. 'choice_label' => 'fullName',
  1019. 'attr' => [
  1020. "data-control" => "select2",
  1021. ],
  1022. "required" => false,
  1023. "mapped" => true,
  1024. ]);
  1025. }
  1026. $form->handleRequest($request);
  1027. if ($form->isSubmitted() && !$form->isValid()) {
  1028. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  1029. }
  1030. if ($form->isSubmitted() && $form->isValid()) {
  1031. $em->flush();
  1032. $this->get("session")->getFlashBag()->add("success", "Client mis à jour");
  1033. return $this->redirectToRoute("manager_clients_edit", ["user" => $user->getId()]);
  1034. }
  1035. $cotations = $em->getRepository(Cotation::class)->findBy(["user" => $user], ["creationDate" => "DESC"], 3);
  1036. return $this->render("app/clients/form.html.twig", [
  1037. "form" => $form->createView(),
  1038. "user" => $user,
  1039. "cotations" => $cotations,
  1040. "title" => "Modifier un client",
  1041. ]);
  1042. }
  1043. /**
  1044. * @Route("/clients/{user}/cotations", name="clients_cotations")
  1045. */
  1046. public function clientsCotationsAction(Request $request, EntityManagerInterface $em, User $user)
  1047. {
  1048. if (!$this->getUser()->getManager()->getAdmin()) {
  1049. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1050. throw new NotFoundHttpException();
  1051. }
  1052. }
  1053. $cotations = $em->getRepository(Cotation::class)->findBy(["user" => $user, 'cotationMultisite' => null], ["creationDate" => "DESC"]);
  1054. return $this->render("app/clients/cotations.html.twig", [
  1055. "user" => $user,
  1056. "cotations" => $cotations,
  1057. ]);
  1058. }
  1059. /**
  1060. * @Route("/clients/{user}/cotations/add", name="clients_cotations_add")
  1061. */
  1062. public function clientsCotationsAddAction(Request $request, EntityManagerInterface $em, User $user)
  1063. {
  1064. if (!$this->getUser()->getManager()->getAdmin()) {
  1065. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1066. throw new NotFoundHttpException();
  1067. }
  1068. }
  1069. $cotation = new Cotation();
  1070. $cotation->setUser($user);
  1071. $cotation->setManager($this->getUser()->getManager());
  1072. $cotation->setFirstName($user->getFirstName());
  1073. $cotation->setLastName($user->getLastName());
  1074. $cotation->setAddress($user->getAddress());
  1075. $cotation->setAddress2($user->getAddress2());
  1076. $cotation->setZipCode($user->getZipCode());
  1077. $cotation->setCity($user->getCity());
  1078. $cotation->setBillingAddress($user->getAddress());
  1079. $cotation->setBillingAddress2($user->getAddress2());
  1080. $cotation->setBillingZipCode($user->getZipCode());
  1081. $cotation->setBillingCity($user->getCity());
  1082. $cotation->setPhone($user->getPhone());
  1083. $cotation->setEmail($user->getEmail());
  1084. $cotation->setEPdl($user->getPdlNumber());
  1085. $cotation->setGPce($user->getPceNumber());
  1086. $form = $this->createForm(CotationType::class, $cotation);
  1087. $form->handleRequest($request);
  1088. if ($form->isSubmitted() && !$form->isValid()) {
  1089. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  1090. }
  1091. if ($form->isSubmitted() && $form->isValid()) {
  1092. $state = $em->getRepository(CotationState::class)->find(1);
  1093. $cotation->setState($state);
  1094. $cotation->setCreationDate(new \DateTime("now"));
  1095. $em->persist($cotation);
  1096. $em->flush();
  1097. $this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
  1098. return $this->redirectToRoute("manager_clients_cotations", ["user" => $user->getId()]);
  1099. }
  1100. return $this->render("app/clients/cotation_form.html.twig", [
  1101. "form" => $form->createView(),
  1102. "cotation" => $cotation,
  1103. ]);
  1104. }
  1105. /**
  1106. * @Route("/clients/{user}/contracts/add", name="clients_contracts_add")
  1107. */
  1108. public function clientsContractsAddAction(Request $request, EntityManagerInterface $em, User $user)
  1109. {
  1110. if (!$this->getUser()->getManager()->getAdmin()) {
  1111. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1112. throw new NotFoundHttpException();
  1113. }
  1114. }
  1115. $contract = new Contract();
  1116. $contract->setUser($user);
  1117. $form = $this->createForm(ContractType::class, $contract);
  1118. $contractPart = $em->getRepository(\App\Entity\ContractType::class)->find(7);
  1119. $form->add('contractType', EntityType::class, [
  1120. 'class' => \App\Entity\ContractType::class,
  1121. 'query_builder' => function (EntityRepository $er) {
  1122. return $er->createQueryBuilder('t')
  1123. ->where('t.active = TRUE')
  1124. ->andWhere('t.id = 7')
  1125. ->orderBy('t.label', 'ASC');
  1126. },
  1127. 'data' => $contractPart,
  1128. 'choice_label' => 'label',
  1129. 'label' => 'Type de contrat',
  1130. 'required' => true,
  1131. 'mapped' => false,
  1132. ]);
  1133. $form->handleRequest($request);
  1134. if ($form->isSubmitted() && !$form->isValid()) {
  1135. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  1136. }
  1137. if ($form->isSubmitted() && $form->isValid()) {
  1138. $contract->setManager($this->getUser()->getManager());
  1139. $stateWaitSupplier = $em->getRepository(ContractState::class)->findOneBy(['id' => 7]);
  1140. $contract->setState($stateWaitSupplier);
  1141. $em->persist($contract);
  1142. $em->flush();
  1143. $file = $form['file']->getData();
  1144. if ($file) {
  1145. $extension = $file->guessExtension();
  1146. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1147. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1148. } else {
  1149. $fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1150. $file->move(
  1151. $this->getParameter('documents_contracts_directory'),
  1152. $fileName
  1153. );
  1154. $contract->setFile($fileName);
  1155. $em->flush();
  1156. }
  1157. }
  1158. $otherFile = $form['otherFile']->getData();
  1159. if ($otherFile) {
  1160. $extension = $otherFile->guessExtension();
  1161. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1162. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1163. } else {
  1164. $fileName = $user->getId() . "_" . $otherFile->getClientOriginalName();
  1165. $otherFile->move(
  1166. $this->getParameter('documents_contracts_directory'),
  1167. $fileName
  1168. );
  1169. $contract->setOtherFile($fileName);
  1170. $em->flush();
  1171. }
  1172. }
  1173. $rib = $form['ribFile']->getData();
  1174. if ($rib) {
  1175. $extension = $rib->guessExtension();
  1176. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1177. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1178. } else {
  1179. $fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1180. $rib->move(
  1181. $this->getParameter('documents_contracts_directory'),
  1182. $fileName
  1183. );
  1184. $contract->setRibFile($fileName);
  1185. $em->flush();
  1186. }
  1187. }
  1188. /*
  1189. if ($form['contractType']->getData()) {
  1190. switch ($form['contractType']->getData()->getId()) {
  1191. case 1:
  1192. $contract->setGas(true);
  1193. break;
  1194. case 2:
  1195. $contract->setElectricity(true);
  1196. break;
  1197. case 3:
  1198. $contract->setGas(true);
  1199. $contract->setElectricity(true);
  1200. break;
  1201. case 4:
  1202. $contract->setEngiePro(true);
  1203. break;
  1204. case 5:
  1205. $contract->setTelecom(true);
  1206. break;
  1207. case 6:
  1208. $contract->setPhotovoltaique(true);
  1209. break;
  1210. }
  1211. $em->flush();
  1212. }
  1213. */
  1214. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  1215. $contract->setSignDate(new \DateTime('now'));
  1216. $em->flush();
  1217. }
  1218. $this->get("session")->getFlashBag()->add("success", "Contrat ajouté avec succès");
  1219. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId(), "creation" => 1]);
  1220. }
  1221. return $this->render("app/clients/contracts_form.html.twig", [
  1222. "form" => $form->createView(),
  1223. "contract" => $contract,
  1224. "title" => "Ajouter un contrat",
  1225. ]);
  1226. }
  1227. /**
  1228. * @Route("/clients/{user}/contracts/{contract}/edit", name="clients_contracts_edit")
  1229. */
  1230. public function clientsContractsEditAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1231. {
  1232. if (!$this->getUser()->getManager()->getAdmin()) {
  1233. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1234. throw new NotFoundHttpException();
  1235. }
  1236. }
  1237. $form = $this->createForm(ContractType::class, $contract);
  1238. if ($this->getUser()->getManager()->getAdmin()) {
  1239. $form->add('manager', EntityType::class, [
  1240. "label" => "Commercial associé",
  1241. 'class' => Manager::class,
  1242. 'query_builder' => function (EntityRepository $er) {
  1243. return $er->createQueryBuilder('m')
  1244. ->leftJoin("m.account", "a")
  1245. ->where('a.enabled = true');
  1246. },
  1247. 'choice_label' => 'fullName',
  1248. 'attr' => [
  1249. "data-control" => "select2",
  1250. ],
  1251. "required" => false,
  1252. "mapped" => false,
  1253. ]);
  1254. $form["manager"]->setData($contract->getManager());
  1255. } elseif ($contract->getManager()->isSupervisedBy($this->getUser()->getManager()) || ($contract->getManager() === $this->getUser()->getManager())) {
  1256. $form->add('manager', EntityType::class, [
  1257. "label" => "Commercial associé",
  1258. 'class' => Manager::class,
  1259. 'query_builder' => function (EntityRepository $er) {
  1260. return $er->createQueryBuilder('m')
  1261. ->leftJoin("m.account", "a")
  1262. ->where('a.enabled = true')
  1263. ->andWhere('(:manager MEMBER OF m.supervisors OR :manager = m)')
  1264. ->setParameter('manager', $this->getUser()->getManager());
  1265. },
  1266. 'choice_label' => 'fullName',
  1267. 'attr' => [
  1268. "data-control" => "select2",
  1269. ],
  1270. "required" => false,
  1271. "mapped" => true,
  1272. ]);
  1273. $form["manager"]->setData($contract->getManager());
  1274. }
  1275. $form->handleRequest($request);
  1276. if ($form->isSubmitted() && !$form->isValid()) {
  1277. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  1278. }
  1279. if ($form->isSubmitted() && $form->isValid()) {
  1280. if ($form->get("manager")) {
  1281. $contract->setManager($form->get("manager")->getData());
  1282. }
  1283. $em->persist($contract);
  1284. $em->flush();
  1285. $file = $form['file']->getData();
  1286. if ($file) {
  1287. $extension = $file->guessExtension();
  1288. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1289. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1290. } else {
  1291. $fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1292. $file->move(
  1293. $this->getParameter('documents_contracts_directory'),
  1294. $fileName
  1295. );
  1296. $contract->setFile($fileName);
  1297. $em->flush();
  1298. }
  1299. }
  1300. $otherFile = $form['otherFile']->getData();
  1301. if ($otherFile) {
  1302. $extension = $otherFile->guessExtension();
  1303. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1304. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1305. } else {
  1306. $fileName = $user->getId() . "_" . $otherFile->getClientOriginalName();
  1307. $otherFile->move(
  1308. $this->getParameter('documents_contracts_directory'),
  1309. $fileName
  1310. );
  1311. $contract->setOtherFile($fileName);
  1312. $em->flush();
  1313. }
  1314. }
  1315. $rib = $form['ribFile']->getData();
  1316. if ($rib) {
  1317. $extension = $rib->guessExtension();
  1318. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  1319. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  1320. } else {
  1321. $fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1322. $rib->move(
  1323. $this->getParameter('documents_contracts_directory'),
  1324. $fileName
  1325. );
  1326. $contract->setRibFile($fileName);
  1327. $em->flush();
  1328. }
  1329. }
  1330. /*
  1331. if ($form['contractType']->getData()) {
  1332. switch ($form['contractType']->getData()->getId()) {
  1333. case 1:
  1334. $contract->setGas(true);
  1335. break;
  1336. case 2:
  1337. $contract->setElectricity(true);
  1338. break;
  1339. case 3:
  1340. $contract->setGas(true);
  1341. $contract->setElectricity(true);
  1342. break;
  1343. case 4:
  1344. $contract->setEngiePro(true);
  1345. break;
  1346. case 5:
  1347. $contract->setTelecom(true);
  1348. break;
  1349. case 6:
  1350. $contract->setPhotovoltaique(true);
  1351. break;
  1352. }
  1353. $em->flush();
  1354. }
  1355. */
  1356. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  1357. $contract->setSignDate(new \DateTime('now'));
  1358. $em->flush();
  1359. }
  1360. $this->get("session")->getFlashBag()->add("success", "Contrat modifié avec succès");
  1361. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1362. }
  1363. $creationWorkflow = $request->query->get('creation') === '1';
  1364. return $this->render("app/clients/contracts_form.html.twig", [
  1365. "form" => $form->createView(),
  1366. "contract" => $contract,
  1367. "title" => "Modifier un contrat",
  1368. 'creation_workflow' => $creationWorkflow,
  1369. ]);
  1370. }
  1371. /**
  1372. * @Route("/clients/{user}/contracts/{contract}/delete", name="clients_contracts_delete")
  1373. */
  1374. public function clientsContractsDeleteAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1375. {
  1376. if (!$this->getUser()->getManager()->getAdmin()) {
  1377. throw new UnauthorizedHttpException("Admin only");
  1378. }
  1379. $contract->setOfferElec(null);
  1380. $contract->setOfferGaz(null);
  1381. $em->flush();
  1382. $em->remove($contract);
  1383. $em->flush();
  1384. $this->get("session")->getFlashBag()->add("success", "Contrat supprimée");
  1385. return $this->redirectToRoute("manager_contracts", ["particulier" => 1]);
  1386. }
  1387. /**
  1388. * @Route("/clients/{user}/contracts/{contract}/file", name="clients_contracts_file")
  1389. */
  1390. public function clientsContractsFileAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1391. {
  1392. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1393. throw new NotFoundHttpException();
  1394. }
  1395. if (!$this->getUser()->getManager()->getAdmin()) {
  1396. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1397. throw new NotFoundHttpException();
  1398. }
  1399. }
  1400. if ($contract->getFile()) {
  1401. return $this->getContractFile($contract, $request->get('mergeRib'));
  1402. }
  1403. throw new NotFoundHttpException();
  1404. }
  1405. /**
  1406. * @Route("/clients/{user}/contracts/{contract}/other-file", name="clients_contracts_other_file")
  1407. */
  1408. public function clientsContractsOtherFileAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1409. {
  1410. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1411. throw new NotFoundHttpException();
  1412. }
  1413. if (!$this->getUser()->getManager()->getAdmin()) {
  1414. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1415. throw new NotFoundHttpException();
  1416. }
  1417. }
  1418. if ($contract->getOtherFile()) {
  1419. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
  1420. return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  1421. }
  1422. throw new NotFoundHttpException();
  1423. }
  1424. /**
  1425. * @Route("/clients/{user}/contracts/{contract}/rib", name="clients_contracts_rib")
  1426. */
  1427. public function clientsContractsRibAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1428. {
  1429. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1430. throw new NotFoundHttpException();
  1431. }
  1432. if (!$this->getUser()->getManager()->getAdmin()) {
  1433. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1434. throw new NotFoundHttpException();
  1435. }
  1436. }
  1437. if ($contract->getRibFile()) {
  1438. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  1439. return $this->file($filePath, $contract->getRibFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  1440. }
  1441. throw new NotFoundHttpException();
  1442. }
  1443. /**
  1444. * @Route("/clients/{user}/contracts/{contract}/rib-delete", name="clients_contracts_rib-delete")
  1445. */
  1446. public function clientsContractsRibDeleteAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
  1447. {
  1448. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1449. throw new NotFoundHttpException();
  1450. }
  1451. if (!$this->getUser()->getManager()->getAdmin()) {
  1452. throw new NotFoundHttpException();
  1453. }
  1454. $contract->setRibFile(null);
  1455. $em->flush();
  1456. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1457. }
  1458. /**
  1459. * @Route("/clients/{user}/contracts/{contract}/sign", name="clients_contracts_sign")
  1460. */
  1461. public function clientsContractsSignAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract, DocusignService $docusignService)
  1462. {
  1463. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1464. throw new NotFoundHttpException();
  1465. }
  1466. if (!$this->getUser()->getManager()->getAdmin()) {
  1467. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1468. throw new NotFoundHttpException();
  1469. }
  1470. }
  1471. if (!$contract->getFile()) {
  1472. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  1473. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1474. } else if (!$contract->getState() || $contract->getState()->getId() != 3) {
  1475. $this->get("session")->getFlashBag()->add("danger", "Le statut du contrat doit être: Contrat en attente de signature");
  1476. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1477. } else {
  1478. return $this->sendContractFileToDocusign($contract, $docusignService, $em, $request->query->get("embedded"));
  1479. //return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1480. }
  1481. throw new NotFoundHttpException();
  1482. }
  1483. /**
  1484. * @Route("/clients/{user}/contracts/{contract}/other-file/sign", name="clients_contracts_other_file_sign")
  1485. */
  1486. public function clientsContractsOtherFileSignAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract, DocusignService $docusignService)
  1487. {
  1488. if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
  1489. throw new NotFoundHttpException();
  1490. }
  1491. if (!$this->getUser()->getManager()->getAdmin()) {
  1492. if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1493. throw new NotFoundHttpException();
  1494. }
  1495. }
  1496. if (!$contract->getOtherFile()) {
  1497. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  1498. return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1499. } else {
  1500. return $this->sendContractOtherFileToDocusign($contract, $docusignService, $em, true);
  1501. //return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
  1502. }
  1503. throw new NotFoundHttpException();
  1504. }
  1505. /**
  1506. * @Route("/companies/validate", name="companies_validate_group")
  1507. */
  1508. public function companiesValidateGroupAction(Request $request, EntityManagerInterface $em)
  1509. {
  1510. if (!$this->getUser()->getManager()->getAdmin()) {
  1511. throw new UnauthorizedHttpException("Not admin");
  1512. }
  1513. $companiesId = $request->get("companiesId");
  1514. if (!$companiesId) {
  1515. throw new BadRequestHttpException("Missing companiesId.");
  1516. }
  1517. foreach (explode(";",$companiesId) as $companyId) {
  1518. $company = $em->getRepository(Company::class)->find($companyId);
  1519. if ($company) {
  1520. $company->setValidated(true);
  1521. }
  1522. }
  1523. $em->flush();
  1524. $this->get("session")->getFlashBag()->add("success", "Clients validés avec succès");
  1525. return $this->redirectToRoute("manager_clients", ["pro" => 1, "onlyNotValidated" => 1]);
  1526. }
  1527. /**
  1528. * @Route("/companies/{company}/edit", name="companies_edit")
  1529. */
  1530. public function companiesEditAction(Request $request, EntityManagerInterface $em, Company $company, CompanyRepository $companyRepository)
  1531. {
  1532. if (!$this->getUser()->getManager()->getAdmin()) {
  1533. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1534. throw new NotFoundHttpException();
  1535. }
  1536. }
  1537. $form = $this->createForm(CompanyType::class, $company);
  1538. if ($this->getUser()->getManager()->getAdmin()) {
  1539. $form->add('manager', EntityType::class, [
  1540. "label" => "Commercial associé",
  1541. 'class' => Manager::class,
  1542. 'query_builder' => function (EntityRepository $er) {
  1543. return $er->createQueryBuilder('m')
  1544. ->leftJoin("m.account", "a")
  1545. ->where('a.enabled = true');
  1546. },
  1547. 'choice_label' => 'fullName',
  1548. 'attr' => [
  1549. "data-control" => "select2",
  1550. ],
  1551. "required" => false,
  1552. "mapped" => false,
  1553. ]);
  1554. $form["manager"]->setData($company->getUser()->getManager());
  1555. }
  1556. $form["firstName"]->setData($company->getUser()->getFirstName());
  1557. $form["lastName"]->setData($company->getUser()->getLastName());
  1558. $form["position"]->setData($company->getUser()->getPosition());
  1559. $form["stepInProcess"]->setData($company->getUser()->getStepInProcess());
  1560. $form["comment"]->setData($company->getUser()->getComment());
  1561. $form->handleRequest($request);
  1562. if ($form->isSubmitted() && !$form->isValid()) {
  1563. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  1564. }
  1565. if ($form->isSubmitted() && $form->isValid()) {
  1566. $company->getUser()->setFirstName($form["firstName"]->getData());
  1567. $company->getUser()->setLastName($form["lastName"]->getData());
  1568. $company->getUser()->setPosition($form["position"]->getData());
  1569. $company->getUser()->setPhone($company->getPhone());
  1570. $company->getUser()->setEmail($company->getEmail());
  1571. $company->getUser()->setStepInProcess($form["stepInProcess"]->getData());
  1572. $company->getUser()->setComment($form["comment"]->getData());
  1573. if ($this->getUser()->getManager()->getAdmin()) {
  1574. $company->getUser()->setManager($form["manager"]->getData());
  1575. }
  1576. $em->flush();
  1577. $fileJustificatif = $form['justificatif']->getData();
  1578. if ($fileJustificatif) {
  1579. $extension = $fileJustificatif->guessExtension();
  1580. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1581. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le justificati");
  1582. } else {
  1583. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1584. $fileJustificatif->move(
  1585. $this->getParameter('documents_justificatif_directory'),
  1586. $fileName
  1587. );
  1588. $company->setJustificatif($fileName);
  1589. $em->flush();
  1590. }
  1591. }
  1592. $fileFactElec = $form['factElec']->getData();
  1593. if ($fileFactElec) {
  1594. $extension = $fileFactElec->guessExtension();
  1595. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1596. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
  1597. } else {
  1598. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1599. $fileFactElec->move(
  1600. $this->getParameter('documents_justificatif_directory'),
  1601. $fileName
  1602. );
  1603. $company->setFactElec($fileName);
  1604. $em->flush();
  1605. }
  1606. }
  1607. $fileFactGas = $form['factGas']->getData();
  1608. if ($fileFactGas) {
  1609. $extension = $fileFactGas->guessExtension();
  1610. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1611. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
  1612. } else {
  1613. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1614. $fileFactGas->move(
  1615. $this->getParameter('documents_justificatif_directory'),
  1616. $fileName
  1617. );
  1618. $company->setFactGas($fileName);
  1619. $em->flush();
  1620. }
  1621. }
  1622. $fileLiaseFiscale = $form['liasseFiscale']->getData();
  1623. if ($fileLiaseFiscale) {
  1624. $extension = $fileLiaseFiscale->guessExtension();
  1625. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1626. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
  1627. } else {
  1628. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1629. $fileLiaseFiscale->move(
  1630. $this->getParameter('documents_justificatif_directory'),
  1631. $fileName
  1632. );
  1633. $company->setLiasseFiscale($fileName);
  1634. $em->flush();
  1635. }
  1636. }
  1637. $fileSgeElec = $form['sgeElec']->getData();
  1638. if ($fileSgeElec) {
  1639. $extension = $fileSgeElec->guessExtension();
  1640. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1641. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
  1642. } else {
  1643. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1644. $fileSgeElec->move(
  1645. $this->getParameter('documents_justificatif_directory'),
  1646. $fileName
  1647. );
  1648. $company->setSgeElec($fileName);
  1649. $em->flush();
  1650. }
  1651. }
  1652. $fileOmegaGas = $form['omegaGas']->getData();
  1653. if ($fileOmegaGas) {
  1654. $extension = $fileOmegaGas->guessExtension();
  1655. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  1656. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
  1657. } else {
  1658. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1659. $fileOmegaGas->move(
  1660. $this->getParameter('documents_justificatif_directory'),
  1661. $fileName
  1662. );
  1663. $company->setOmegaGas($fileName);
  1664. $em->flush();
  1665. }
  1666. }
  1667. $fileExcelMultisite = $form['excelMultisite']->getData();
  1668. if ($fileExcelMultisite) {
  1669. $extension = $fileExcelMultisite->guessExtension();
  1670. if (!$extension || !in_array($extension, ["csv", "xls", "xlsx"])) {
  1671. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour l'excel multisite");
  1672. } else {
  1673. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  1674. $fileExcelMultisite->move(
  1675. $this->getParameter('documents_justificatif_directory'),
  1676. $fileName
  1677. );
  1678. $company->setExcelMultisite($fileName);
  1679. $em->flush();
  1680. }
  1681. }
  1682. $this->get("session")->getFlashBag()->add("success", "Client mis à jour");
  1683. return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
  1684. }
  1685. $cotations = $em->getRepository(Cotation::class)->findBy(["company" => $company, 'cotationMultisite' => null], ["creationDate" => "DESC"], 3);
  1686. $cotationsMultisite = $em->getRepository(CotationMultisite::class)->findBy(["company" => $company], ["creationDate" => "DESC"], 3);
  1687. $contracts = $em->getRepository(Contract::class)->findBy(["company" => $company], ["effectiveDate" => "DESC"], 3);
  1688. return $this->render("app/clients/form_pro.html.twig", [
  1689. "form" => $form->createView(),
  1690. "company" => $company,
  1691. "cotations" => $cotations,
  1692. "cotationsMultisite" => $cotationsMultisite,
  1693. "contracts" => $contracts,
  1694. "title" => "Modifier un client",
  1695. "siretAlreadyExist" => $companyRepository->existCompaniesWithSameSiretAndDifferentId($company->getId(), $company->getSiret())
  1696. ]);
  1697. }
  1698. /**
  1699. * @Route("/companies/{company}/justificatif", name="companies_justificatif")
  1700. */
  1701. public function companiesJustificatifAction(Request $request, EntityManagerInterface $em, Company $company)
  1702. {
  1703. if (!$this->getUser()->getManager()->getAdmin()) {
  1704. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1705. throw new NotFoundHttpException();
  1706. }
  1707. }
  1708. if ($company->getJustificatif()) {
  1709. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getJustificatif();
  1710. return $this->file($filePath, $company->getJustificatif(), ResponseHeaderBag::DISPOSITION_INLINE);
  1711. }
  1712. throw new NotFoundHttpException();
  1713. }
  1714. /**
  1715. * @Route("/companies/{company}/justificatif-delete", name="companies_justificatif-delete")
  1716. */
  1717. public function companiesJustificatifDeleteAction(Request $request, EntityManagerInterface $em, Company $company)
  1718. {
  1719. if (!$this->getUser()->getManager()->getAdmin()) {
  1720. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1721. throw new NotFoundHttpException();
  1722. }
  1723. }
  1724. $company->setJustificatif(null);
  1725. $em->flush();
  1726. return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
  1727. }
  1728. /**
  1729. * @Route("/companies/{company}/fact-elec", name="companies_fact-elec")
  1730. */
  1731. public function companiesFactElecction(Request $request, EntityManagerInterface $em, Company $company)
  1732. {
  1733. if (!$this->getUser()->getManager()->getAdmin()) {
  1734. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1735. throw new NotFoundHttpException();
  1736. }
  1737. }
  1738. if ($company->getFactElec()) {
  1739. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getFactElec();
  1740. return $this->file($filePath, $company->getFactElec(), ResponseHeaderBag::DISPOSITION_INLINE);
  1741. }
  1742. throw new NotFoundHttpException();
  1743. }
  1744. /**
  1745. * @Route("/companies/{company}/fact-gas", name="companies_fact-gas")
  1746. */
  1747. public function companiesFactGasAction(Request $request, EntityManagerInterface $em, Company $company)
  1748. {
  1749. if (!$this->getUser()->getManager()->getAdmin()) {
  1750. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1751. throw new NotFoundHttpException();
  1752. }
  1753. }
  1754. if ($company->getFactGas()) {
  1755. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getFactGas();
  1756. return $this->file($filePath, $company->getFactGas(), ResponseHeaderBag::DISPOSITION_INLINE);
  1757. }
  1758. throw new NotFoundHttpException();
  1759. }
  1760. /**
  1761. * @Route("/companies/{company}/liasse-fiscale", name="companies_liasse-fiscale")
  1762. */
  1763. public function companiesLiasseFiscaleAction(Request $request, EntityManagerInterface $em, Company $company)
  1764. {
  1765. if (!$this->getUser()->getManager()->getAdmin()) {
  1766. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1767. throw new NotFoundHttpException();
  1768. }
  1769. }
  1770. if ($company->getLiasseFiscale()) {
  1771. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getLiasseFiscale();
  1772. return $this->file($filePath, $company->getLiasseFiscale(), ResponseHeaderBag::DISPOSITION_INLINE);
  1773. }
  1774. throw new NotFoundHttpException();
  1775. }
  1776. /**
  1777. * @Route("/companies/{company}/liasse-fiscale-delete", name="companies_liasse-fiscale-delete")
  1778. */
  1779. public function companiesLiasseFiscaleDeleteAction(Request $request, EntityManagerInterface $em, Company $company)
  1780. {
  1781. if (!$this->getUser()->getManager()->getAdmin()) {
  1782. throw new NotFoundHttpException();
  1783. }
  1784. $company->setLiasseFiscale(null);
  1785. $em->flush();
  1786. return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
  1787. }
  1788. /**
  1789. * @Route("/companies/{company}/sge-elec", name="companies_sge-elec")
  1790. */
  1791. public function companiesSgeElecAction(Request $request, EntityManagerInterface $em, Company $company)
  1792. {
  1793. if (!$this->getUser()->getManager()->getAdmin()) {
  1794. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1795. throw new NotFoundHttpException();
  1796. }
  1797. }
  1798. if ($company->getSgeElec()) {
  1799. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getSgeElec();
  1800. return $this->file($filePath, $company->getSgeElec(), ResponseHeaderBag::DISPOSITION_INLINE);
  1801. }
  1802. throw new NotFoundHttpException();
  1803. }
  1804. /**
  1805. * @Route("/companies/{company}/omega-gas", name="companies_omega-gas")
  1806. */
  1807. public function companiesOmegaGasAction(Request $request, EntityManagerInterface $em, Company $company)
  1808. {
  1809. if (!$this->getUser()->getManager()->getAdmin()) {
  1810. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1811. throw new NotFoundHttpException();
  1812. }
  1813. }
  1814. if ($company->getOmegaGas()) {
  1815. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getOmegaGas();
  1816. return $this->file($filePath, $company->getOmegaGas(), ResponseHeaderBag::DISPOSITION_INLINE);
  1817. }
  1818. throw new NotFoundHttpException();
  1819. }
  1820. /**
  1821. * @Route("/companies/{company}/excel-multisite", name="companies_excel-multisite")
  1822. */
  1823. public function companiesExcelMultisiteAction(Request $request, EntityManagerInterface $em, Company $company)
  1824. {
  1825. if (!$this->getUser()->getManager()->getAdmin()) {
  1826. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1827. throw new NotFoundHttpException();
  1828. }
  1829. }
  1830. if ($company->getExcelMultisite()) {
  1831. $filePath = $this->getParameter('documents_justificatif_directory') . $company->getExcelMultisite();
  1832. return $this->file($filePath, $company->getExcelMultisite(), ResponseHeaderBag::DISPOSITION_INLINE);
  1833. }
  1834. throw new NotFoundHttpException();
  1835. }
  1836. /**
  1837. * @Route("/companies/{company}/ellipro", name="companies_ellipro")
  1838. */
  1839. public function companiesElliproAction(Request $request, Company $company, EllisphereService $ellisphereService)
  1840. {
  1841. if (!$this->getUser()->getManager()->getAdmin()) {
  1842. throw new NotFoundHttpException();
  1843. }
  1844. if (!$company->getSiret()) {
  1845. return new JsonResponse([
  1846. "success" => false,
  1847. "message" => "Siret non renseigné pour ce client"
  1848. ]);
  1849. }
  1850. $data = $ellisphereService->getNoteElliPro($company->getSiret());
  1851. if ($data) {
  1852. return new JsonResponse([
  1853. "success" => true,
  1854. "data" => $data
  1855. ]);
  1856. } else {
  1857. return new JsonResponse([
  1858. "success" => false,
  1859. "message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
  1860. ]);
  1861. }
  1862. }
  1863. /**
  1864. * @Route("/companies/{company}/cotations", name="companies_cotations")
  1865. */
  1866. public function companiesCotationsAction(Request $request, EntityManagerInterface $em, Company $company)
  1867. {
  1868. if (!$this->getUser()->getManager()->getAdmin()) {
  1869. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1870. throw new NotFoundHttpException();
  1871. }
  1872. }
  1873. $cotations = $em->getRepository(Cotation::class)->findBy(["company" => $company, 'cotationMultisite' => null], ["creationDate" => "DESC"]);
  1874. return $this->render("app/clients/cotations.html.twig", [
  1875. "company" => $company,
  1876. "cotations" => $cotations,
  1877. ]);
  1878. }
  1879. /**
  1880. * @Route("/companies/{company}/cotations-multisites", name="companies_cotations-multisites")
  1881. */
  1882. public function companiesCotationsMultisitesAction(Request $request, EntityManagerInterface $em, Company $company)
  1883. {
  1884. if (!$this->getUser()->getManager()->getAdmin()) {
  1885. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1886. throw new NotFoundHttpException();
  1887. }
  1888. }
  1889. $cotations = $em->getRepository(CotationMultisite::class)->findBy(["company" => $company], ["creationDate" => "DESC"]);
  1890. return $this->render("app/clients/cotations-multisites.html.twig", [
  1891. "company" => $company,
  1892. "cotations" => $cotations,
  1893. ]);
  1894. }
  1895. /**
  1896. * @Route("/companies/{company}/validate", name="companies_validate")
  1897. */
  1898. public function companiesValidateAction(Request $request, EntityManagerInterface $em, Company $company)
  1899. {
  1900. if (!$this->getUser()->getManager()->getAdmin()) {
  1901. throw new UnauthorizedHttpException("Only for admins");
  1902. }
  1903. $company->setValidated(true);
  1904. $em->flush();
  1905. $this->get("session")->getFlashBag()->add("success", "Client accepté");
  1906. return $this->redirectToRoute("manager_clients", ["pro"=> 1, "onlyNotValidated"=> 1]);
  1907. }
  1908. /**
  1909. * @Route("/companies/{company}/fe-invitation", name="companies_fe_invitation")
  1910. */
  1911. public function companiesFeInvitationAction(Request $request, EntityManagerInterface $em, Company $company, SendEmailService $sendEmailService)
  1912. {
  1913. if (!$this->getUser()->getManager()->getAdmin()) {
  1914. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1915. throw new NotFoundHttpException();
  1916. }
  1917. }
  1918. if ($company->getUser()->getAccount()) {
  1919. throw new BadRequestHttpException("Already Flash Energie User");
  1920. }
  1921. $user = $company->getUser();
  1922. $feToken = hash("sha256", uniqid());
  1923. $user->setFeInvitationToken($feToken);
  1924. $user->setFeInvitationDate(new \DateTime('now'));
  1925. $em->flush();
  1926. $url = $this->generateUrl("default_flash_energie_token", ["token" => $feToken], UrlGeneratorInterface::ABSOLUTE_URL);
  1927. $content = <<<EOD
  1928. <br/>
  1929. Merci de compter parmi nos clients !<br/>
  1930. Afin de vous faciliter la gestion de vos contrats d'énergies, nous avons créé l'application Flash Énergie. Votre conseiller vous invite à rejoindre l'application afin de suivre vos contrats et de gérer vos données.
  1931. <br/>
  1932. <br/>
  1933. Téléchargez dès maintenant l'application Flash Energie ici.<br/>
  1934. Ensuite, cliquez sur ce lien depuis votre smartphone pour vous inscrire depuis l'application:<br/>
  1935. <a href="$url">$url</a>
  1936. EOD;
  1937. $sendEmailService->send(
  1938. "Flash Énergie vous invite à rejoindre l'application Flash Énergie",
  1939. "david@slapp.me",
  1940. 'emails/flash_default.html.twig',
  1941. [
  1942. "title" => "Suivez vos contrats avec l'application Flash Énergie",
  1943. "content" => $content
  1944. ]
  1945. );
  1946. $this->get("session")->getFlashBag()->add("success", "Invitation envoyée avec succès");
  1947. return $this->redirectToRoute("manager_companies_edit", ["company"=> $company->getId()]);
  1948. }
  1949. /**
  1950. * @Route("/companies/{company}/cotations/add", name="companies_cotations_add")
  1951. */
  1952. public function companiesCotationsAddAction(Request $request, EntityManagerInterface $em, Company $company, DocusignService $docusignService)
  1953. {
  1954. if (!$this->getUser()->getManager()->getAdmin()) {
  1955. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  1956. throw new NotFoundHttpException();
  1957. }
  1958. }
  1959. $cotation = new Cotation();
  1960. $cotation->setCompany($company);
  1961. $cotation->setManager($this->getUser()->getManager());
  1962. $cotation->setSiret($company->getSiret());
  1963. //Demande du 2 octobre du client
  1964. $cotation->setCompanyName($company->getName());
  1965. $cotation->setApeCode($company->getApeCode());
  1966. $cotation->setSector($company->getSector());
  1967. $cotation->setPhone($company->getPhone());
  1968. $cotation->setEmail($company->getEmail());
  1969. /*
  1970. $cotation->setFirstName($company->getUser()->getFirstName());
  1971. $cotation->setLastName($company->getUser()->getLastName());
  1972. $cotation->setAddress($company->getAddress());
  1973. $cotation->setAddress2($company->getAddress2());
  1974. $cotation->setZipCode($company->getZipCode());
  1975. $cotation->setCity($company->getCity());
  1976. $cotation->setBillingAddress($company->getAddress());
  1977. $cotation->setBillingAddress2($company->getAddress2());
  1978. $cotation->setBillingZipCode($company->getZipCode());
  1979. $cotation->setBillingCity($company->getCity());
  1980. $cotation->setEPdl($company->getPdlNumber());
  1981. $cotation->setGPce($company->getPceNumber());
  1982. $cotation->setCreditsafeNote($company->getCreditsafeNote());
  1983. $cotation->setEliproNote($company->getEliproNote());
  1984. */
  1985. $form = $this->createForm(CotationType::class, $cotation);
  1986. $form["firstName"]->setData($company->getUser()->getFirstName());
  1987. $form["lastName"]->setData($company->getUser()->getLastName());
  1988. $form["position"]->setData($company->getUser()->getPosition());
  1989. $form["sepaIban"]->setData($company->getSepaIban());
  1990. $form["sepaBic"]->setData($company->getSepaBic());
  1991. if (!$cotation->isAcdValid()) {
  1992. $signatureAvailable = true;
  1993. if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
  1994. $signatureAvailable = false;
  1995. }
  1996. if ($signatureAvailable) {
  1997. $form->add('enableDocusign', CheckboxType::class, [
  1998. "label" => "Envoyer la signature électronique de l'ACD",
  1999. "required" => false,
  2000. "mapped" => false,
  2001. ]);
  2002. } else {
  2003. $form->add('enableDocusign', CheckboxType::class, [
  2004. "label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
  2005. "data" => true,
  2006. "disabled" => true,
  2007. "required" => false,
  2008. "mapped" => false,
  2009. ]);
  2010. }
  2011. }
  2012. $form->handleRequest($request);
  2013. if ($form->isSubmitted() && !$form->isValid()) {
  2014. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  2015. }
  2016. if ($form->isSubmitted() && $form->isValid()) {
  2017. $state = $em->getRepository(CotationState::class)->find(1);
  2018. $cotation->setState($state);
  2019. $cotation->setCreationDate(new \DateTime("now"));
  2020. $em->persist($cotation);
  2021. $em->flush();
  2022. // Ancienne facture
  2023. if ($form->get('oldInvoice')->getData()) {
  2024. $fileOldInvoice = $form->get('oldInvoice')->getData();
  2025. if ($fileOldInvoice != NULL) {
  2026. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
  2027. $fileOldInvoice->move(
  2028. $this->getParameter('documents_justificatif_directory'),
  2029. $fileName
  2030. );
  2031. $cotation->setOldInvoice($fileName);
  2032. }
  2033. } else {
  2034. if ($cotation->getCompany()->getJustificatif()) {
  2035. $filePathFrom = $this->getParameter('documents_justificatif_directory') . $cotation->getCompany()->getJustificatif();
  2036. $path_parts = pathinfo($filePathFrom);
  2037. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $path_parts['extension'];
  2038. copy($filePathFrom, $this->getParameter('documents_justificatif_directory') . $fileName);
  2039. $cotation->setOldInvoice($fileName);
  2040. }
  2041. }
  2042. $em->flush();
  2043. $fileFactElec = $form['factElec']->getData();
  2044. if ($fileFactElec) {
  2045. $extension = $fileFactElec->guessExtension();
  2046. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2047. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
  2048. } else {
  2049. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2050. $fileFactElec->move(
  2051. $this->getParameter('documents_justificatif_directory'),
  2052. $fileName
  2053. );
  2054. $cotation->setFactElec($fileName);
  2055. $em->flush();
  2056. }
  2057. }
  2058. $fileFactGas = $form['factGas']->getData();
  2059. if ($fileFactGas) {
  2060. $extension = $fileFactGas->guessExtension();
  2061. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2062. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
  2063. } else {
  2064. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2065. $fileFactGas->move(
  2066. $this->getParameter('documents_justificatif_directory'),
  2067. $fileName
  2068. );
  2069. $cotation->setFactGas($fileName);
  2070. $em->flush();
  2071. }
  2072. }
  2073. $fileLiaseFiscale = $form['liasseFiscale']->getData();
  2074. if ($fileLiaseFiscale) {
  2075. $extension = $fileLiaseFiscale->guessExtension();
  2076. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2077. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
  2078. } else {
  2079. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2080. $fileLiaseFiscale->move(
  2081. $this->getParameter('documents_justificatif_directory'),
  2082. $fileName
  2083. );
  2084. $cotation->setLiasseFiscale($fileName);
  2085. $em->flush();
  2086. }
  2087. }
  2088. $fileSgeElec = $form['sgeElec']->getData();
  2089. if ($fileSgeElec) {
  2090. $extension = $fileSgeElec->guessExtension();
  2091. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2092. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
  2093. } else {
  2094. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2095. $fileSgeElec->move(
  2096. $this->getParameter('documents_justificatif_directory'),
  2097. $fileName
  2098. );
  2099. $cotation->setSgeElec($fileName);
  2100. $em->flush();
  2101. }
  2102. }
  2103. $fileOmegaGas = $form['omegaGas']->getData();
  2104. if ($fileOmegaGas) {
  2105. $extension = $fileOmegaGas->guessExtension();
  2106. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2107. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
  2108. } else {
  2109. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2110. $fileOmegaGas->move(
  2111. $this->getParameter('documents_justificatif_directory'),
  2112. $fileName
  2113. );
  2114. $cotation->setOmegaGas($fileName);
  2115. $em->flush();
  2116. }
  2117. }
  2118. // Other documents
  2119. $otherDocuments = $form['otherDocuments']->getData();
  2120. foreach ($otherDocuments as $key => $cotationDocument) {
  2121. $cotationDocument->setCotation($cotation);
  2122. $file = $form['otherDocuments'][$key]["file"]->getData();
  2123. if ($file) {
  2124. $extension = $file->guessExtension();
  2125. if ($extension && in_array($extension, ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "pptx"])) {
  2126. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2127. $file->move(
  2128. $this->getParameter('documents_justificatif_directory'),
  2129. $fileName
  2130. );
  2131. $cotationDocument->setPath($fileName);
  2132. }
  2133. }
  2134. $em->flush();
  2135. }
  2136. // Signature électronique de l'ACD
  2137. if ($form->get('enableDocusign')->getData()) {
  2138. // Lancement de la signature
  2139. $startSign = null;
  2140. if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
  2141. $startSign = $this::sendAcdToDocusign($cotation, $company, $docusignService, $em);
  2142. } else {
  2143. $this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
  2144. }
  2145. if (!$startSign) {
  2146. $this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
  2147. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  2148. } else {
  2149. $this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée. Le mail pour la signature électronique de l'ACD a été envoyé au client.");
  2150. }
  2151. } else {
  2152. $this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
  2153. }
  2154. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2155. }
  2156. return $this->render("app/clients/cotation_form.html.twig", [
  2157. "form" => $form->createView(),
  2158. "cotation" => $cotation,
  2159. ]);
  2160. }
  2161. /**
  2162. * @Route("/companies/{company}/cotations/{cotation}/ellipro", name="companies_cotations_ellipro")
  2163. */
  2164. public function companiesCotationElliproAction(Request $request, Company $company, Cotation $cotation, EllisphereService $ellisphereService)
  2165. {
  2166. if (!$cotation->getSiret()) {
  2167. return new JsonResponse([
  2168. "success" => false,
  2169. "message" => "Siret non renseigné pour cette cotation"
  2170. ]);
  2171. }
  2172. $data = $ellisphereService->getNoteElliPro($cotation->getSiret());
  2173. if ($data) {
  2174. return new JsonResponse([
  2175. "success" => true,
  2176. "data" => $data
  2177. ]);
  2178. } else {
  2179. return new JsonResponse([
  2180. "success" => false,
  2181. "message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
  2182. ]);
  2183. }
  2184. }
  2185. /**
  2186. * @Route("/companies/{company}/cotations/{cotation}/send-acd", name="companies_cotations_send_acd")
  2187. */
  2188. public function companiesCotationsSendAcdAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, DocusignService $docusignService)
  2189. {
  2190. if (!$this->getUser()->getManager()->getAdmin()) {
  2191. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2192. throw new NotFoundHttpException();
  2193. }
  2194. }
  2195. if ($cotation->isAcdValid()) {
  2196. $this->get("session")->getFlashBag()->add("danger", "L'ACD a déjà été renseigné pour cette cotation.");
  2197. } else {
  2198. // Lancement de la signature
  2199. $startSign = null;
  2200. if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
  2201. $startSign = $this::sendAcdToDocusign($cotation, $company, $docusignService, $em);
  2202. } else {
  2203. $this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
  2204. }
  2205. if (!$startSign) {
  2206. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  2207. } else {
  2208. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
  2209. }
  2210. }
  2211. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2212. }
  2213. private function sendAcdToYouSign(Cotation $cotation, Company $company, $yousignService, $em)
  2214. {
  2215. // Génération de l'ACD
  2216. $pdf = $this->generateACDv2($cotation);
  2217. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  2218. $filePath = $this->getParameter('documents_acd_directory').$fileName;
  2219. $pdf->Output($filePath, 'F');
  2220. // Création de la procédure
  2221. $procedureSign = new ProcedureSign();
  2222. $procedureSign->setUser($company->getUser());
  2223. $procedureSign->setFirstName($cotation->getFirstName());
  2224. $procedureSign->setLastName($cotation->getLastName());
  2225. $procedureSign->setEmail($cotation->getEmail());
  2226. $procedureSign->setPhone($cotation->getPhone());
  2227. $procedureSign->setCreationDate(new \DateTime('now'));
  2228. $procedureSign->setNameFile($fileName);
  2229. $procedureSign->setFilePath($filePath);
  2230. $content = [
  2231. "type" => "cotation.acd",
  2232. "id" => $cotation->getId()
  2233. ];
  2234. $procedureSign->setContent(json_encode($content));
  2235. $em->persist($procedureSign);
  2236. $em->flush();
  2237. // Création de la position
  2238. $yousignPosition = new YousignPosition();
  2239. $yousignPosition->setReason("Signé par ".$cotation->getFirstName().' '.$cotation->getLastName());
  2240. // Lancement de la signature
  2241. return $yousignService->startSign($procedureSign, $yousignPosition);
  2242. }
  2243. private function sendAcdToDocusign(Cotation $cotation, Company $company, $docusignService, $em)
  2244. {
  2245. // Génération de l'ACD
  2246. $pdf = $this->generateACDv2($cotation);
  2247. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  2248. $filePath = $this->getParameter('documents_acd_directory').$fileName;
  2249. $pdf->Output($filePath, 'F');
  2250. // Création de la procédure
  2251. $procedureSign = new ProcedureSign();
  2252. $procedureSign->setUser($company->getUser());
  2253. $procedureSign->setFirstName($cotation->getFirstName());
  2254. $procedureSign->setLastName($cotation->getLastName());
  2255. $procedureSign->setEmail($cotation->getEmail());
  2256. $procedureSign->setPhone($cotation->getPhone());
  2257. $procedureSign->setCreationDate(new \DateTime('now'));
  2258. $procedureSign->setNameFile($fileName);
  2259. $procedureSign->setFilePath($filePath);
  2260. $content = [
  2261. "type" => "cotation.acd",
  2262. "id" => $cotation->getId()
  2263. ];
  2264. $procedureSign->setContent(json_encode($content));
  2265. $em->persist($procedureSign);
  2266. $em->flush();
  2267. $accessToken = $docusignService->getAccessToken();
  2268. if ($accessToken) {
  2269. try {
  2270. $response = $docusignService->sendFile($accessToken, $procedureSign);
  2271. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  2272. $em->flush();
  2273. return true;
  2274. } catch (\Exception $e) {
  2275. $this->get("session")->getFlashBag()->add("danger", "Une erreur est survenue lors de l'envoi de l'ACD pour signature. Veuillez vérifier le format de l'email et du numéro de téléphone.");
  2276. return false;
  2277. }
  2278. }
  2279. return false;
  2280. }
  2281. private function sendAcdMultisiteToDocusign(CotationMultisite $cotation, Company $company, $docusignService, $em)
  2282. {
  2283. // Génération de l'ACD
  2284. $pdf = $this->generateACDMultisite($cotation);
  2285. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
  2286. $filePath = $this->getParameter('documents_acd_directory').$fileName;
  2287. $pdf->Output($filePath, 'F');
  2288. // Création de la procédure
  2289. $procedureSign = new ProcedureSign();
  2290. $procedureSign->setUser($company->getUser());
  2291. $procedureSign->setFirstName($cotation->getFirstName());
  2292. $procedureSign->setLastName($cotation->getLastName());
  2293. $procedureSign->setEmail($cotation->getEmail());
  2294. $procedureSign->setPhone($cotation->getPhone());
  2295. $procedureSign->setCreationDate(new \DateTime('now'));
  2296. $procedureSign->setNameFile($fileName);
  2297. $procedureSign->setFilePath($filePath);
  2298. $content = [
  2299. "type" => "cotation-multisite.acd",
  2300. "id" => $cotation->getId()
  2301. ];
  2302. $procedureSign->setContent(json_encode($content));
  2303. $em->persist($procedureSign);
  2304. $em->flush();
  2305. $accessToken = $docusignService->getAccessToken();
  2306. if ($accessToken) {
  2307. try {
  2308. $response = $docusignService->sendFile($accessToken, $procedureSign);
  2309. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  2310. $em->flush();
  2311. return true;
  2312. } catch (\Exception $e) {
  2313. $this->get("session")->getFlashBag()->add("danger", "Une erreur est survenue lors de l'envoi de l'ACD pour signature. Veuillez vérifier le format de l'email et du numéro de téléphone.");
  2314. return false;
  2315. }
  2316. }
  2317. return false;
  2318. }
  2319. /**
  2320. * @Route("/companies/{company}/cotations/{cotation}/edit", name="companies_cotations_edit")
  2321. */
  2322. public function companiesCotationsEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2323. {
  2324. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2325. throw new NotFoundHttpException();
  2326. }
  2327. if (!$this->getUser()->getManager()->getAdmin()) {
  2328. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2329. throw new NotFoundHttpException();
  2330. }
  2331. }
  2332. if ($cotation->getCotationMultisite()) {
  2333. throw new NotFoundHttpException();
  2334. }
  2335. if ($cotation->getState()->getId() == 6) { // Terminée
  2336. //throw new NotFoundHttpException();
  2337. }
  2338. $form = $this->createForm(CotationType::class, $cotation);
  2339. if ($cotation->getCompany()->getValidated()) {
  2340. $form->add('acdFileUpload', FileType::class, [
  2341. 'attr' => [
  2342. 'placeholder' => 'Importer le fichier ACD'
  2343. ],
  2344. 'label' => 'Importer le fichier ACD',
  2345. 'required' => false,
  2346. 'mapped' => false
  2347. ]);
  2348. if ($this->getUser()->getManager()->getAdmin()) {
  2349. if (!$cotation->getElectricityDataFile() && $cotation->getElectricity()) {
  2350. $form->add('electricityDataFileUpload', FileType::class, [
  2351. 'attr' => [
  2352. 'placeholder' => 'Importer le fichier de données Enedis'
  2353. ],
  2354. 'label' => 'Importer le fichier de données Enedis',
  2355. 'required' => false,
  2356. 'mapped' => false
  2357. ]);
  2358. }
  2359. if (!$cotation->getGasDataFile() && $cotation->getGas()) {
  2360. $form->add('gasDataFileUpload', FileType::class, [
  2361. 'attr' => [
  2362. 'placeholder' => 'Importer le fichier de données GRDF'
  2363. ],
  2364. 'label' => 'Importer le fichier de données GRDF',
  2365. 'required' => false,
  2366. 'mapped' => false
  2367. ]);
  2368. }
  2369. }
  2370. }
  2371. $form->handleRequest($request);
  2372. if ($form->isSubmitted() && !$form->isValid()) {
  2373. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  2374. }
  2375. if ($form->isSubmitted() && $form->isValid()) {
  2376. $cotation->setEditDate(new \DateTime("now"));
  2377. $em->flush();
  2378. if ($form->get('oldInvoice')->getData()) {
  2379. $fileOldInvoice = $form->get('oldInvoice')->getData();
  2380. if ($fileOldInvoice != NULL) {
  2381. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
  2382. $fileOldInvoice->move(
  2383. $this->getParameter('documents_justificatif_directory'),
  2384. $fileName
  2385. );
  2386. $cotation->setOldInvoice($fileName);
  2387. }
  2388. }
  2389. $fileFactElec = $form['factElec']->getData();
  2390. if ($fileFactElec) {
  2391. $extension = $fileFactElec->guessExtension();
  2392. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2393. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
  2394. } else {
  2395. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2396. $fileFactElec->move(
  2397. $this->getParameter('documents_justificatif_directory'),
  2398. $fileName
  2399. );
  2400. $cotation->setFactElec($fileName);
  2401. $em->flush();
  2402. }
  2403. }
  2404. $fileFactGas = $form['factGas']->getData();
  2405. if ($fileFactGas) {
  2406. $extension = $fileFactGas->guessExtension();
  2407. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2408. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
  2409. } else {
  2410. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2411. $fileFactGas->move(
  2412. $this->getParameter('documents_justificatif_directory'),
  2413. $fileName
  2414. );
  2415. $cotation->setFactGas($fileName);
  2416. $em->flush();
  2417. }
  2418. }
  2419. $fileLiaseFiscale = $form['liasseFiscale']->getData();
  2420. if ($fileLiaseFiscale) {
  2421. $extension = $fileLiaseFiscale->guessExtension();
  2422. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2423. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
  2424. } else {
  2425. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2426. $fileLiaseFiscale->move(
  2427. $this->getParameter('documents_justificatif_directory'),
  2428. $fileName
  2429. );
  2430. $cotation->setLiasseFiscale($fileName);
  2431. $em->flush();
  2432. }
  2433. }
  2434. $fileSgeElec = $form['sgeElec']->getData();
  2435. if ($fileSgeElec) {
  2436. $extension = $fileSgeElec->guessExtension();
  2437. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2438. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
  2439. } else {
  2440. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2441. $fileSgeElec->move(
  2442. $this->getParameter('documents_justificatif_directory'),
  2443. $fileName
  2444. );
  2445. $cotation->setSgeElec($fileName);
  2446. $em->flush();
  2447. }
  2448. }
  2449. $fileOmegaGas = $form['omegaGas']->getData();
  2450. if ($fileOmegaGas) {
  2451. $extension = $fileOmegaGas->guessExtension();
  2452. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  2453. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
  2454. } else {
  2455. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2456. $fileOmegaGas->move(
  2457. $this->getParameter('documents_justificatif_directory'),
  2458. $fileName
  2459. );
  2460. $cotation->setOmegaGas($fileName);
  2461. $em->flush();
  2462. }
  2463. }
  2464. if ($form->has('acdFileUpload')) {
  2465. /**
  2466. * @var UploadedFile $fileAcd
  2467. */
  2468. $fileAcd = $form->get('acdFileUpload')->getData();
  2469. if ($fileAcd != NULL) {
  2470. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileAcd->guessExtension();
  2471. $fileAcd->move(
  2472. $this->getParameter('documents_acd_directory'),
  2473. $fileName
  2474. );
  2475. $cotation->setAcdFile($fileName);
  2476. $cotation->setAcdSignDate(new \DateTime('now'));
  2477. $em->flush();
  2478. }
  2479. }
  2480. if (!$cotation->getElectricityDataFile() && $form->has('electricityDataFileUpload')) {
  2481. /**
  2482. * @var UploadedFile $fileData
  2483. */
  2484. $fileData = $form->get('electricityDataFileUpload')->getData();
  2485. if ($fileData != NULL) {
  2486. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  2487. try {
  2488. $spreadsheet = $reader->load($fileData->getRealPath());
  2489. $sheet = $spreadsheet->setActiveSheetIndex(0);
  2490. $cotation->setENombreMois($sheet->getCell("E9")->getValue());
  2491. $cotation->setEFormuleAcheminement($sheet->getCell("E12")->getValue());
  2492. $cotation->setECarMwh($sheet->getCell("E13")->getValue());
  2493. $cotation->setEConsommationPointe($sheet->getCell("E14")->getValue());
  2494. $cotation->setEConsommationHph($sheet->getCell("E15")->getValue());
  2495. $cotation->setEConsommationHch($sheet->getCell("E16")->getValue());
  2496. $cotation->setEConsommationHpe($sheet->getCell("E17")->getValue());
  2497. $cotation->setEConsommationHce($sheet->getCell("E18")->getValue());
  2498. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileData->guessExtension();
  2499. $fileData->move(
  2500. $this->getParameter('documents_electricity_directory'),
  2501. $fileName
  2502. );
  2503. $cotation->setElectricityDataFile($fileName);
  2504. $em->flush();
  2505. } catch (Exception|DriverException $e) {
  2506. $this->get("session")->getFlashBag()->add("danger", "Impossible de charger le fichier Enedis");
  2507. }
  2508. }
  2509. }
  2510. if (!$cotation->getGasDataFile() && $form->has('gasDataFileUpload')) {
  2511. /**
  2512. * @var UploadedFile $fileData
  2513. */
  2514. $fileData = $form->get('gasDataFileUpload')->getData();
  2515. if ($fileData != NULL) {
  2516. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  2517. try {
  2518. $spreadsheet = $reader->load($fileData->getRealPath());
  2519. $sheet = $spreadsheet->setActiveSheetIndex(0);
  2520. $cotation->setGNombreMois($sheet->getCell("E9")->getValue());
  2521. $cotation->setGCarMwh($sheet->getCell("E12")->getValue());
  2522. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileData->guessExtension();
  2523. $fileData->move(
  2524. $this->getParameter('documents_gas_directory'),
  2525. $fileName
  2526. );
  2527. $cotation->setGasDataFile($fileName);
  2528. $em->flush();
  2529. } catch (Exception|DriverException $e) {
  2530. $this->get("session")->getFlashBag()->add("danger", "Impossible de charger le fichier GRDF");
  2531. }
  2532. }
  2533. }
  2534. // Cotation status
  2535. if ($cotation->getState()->getId() != 5) {
  2536. if (
  2537. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getGasDataFile()))
  2538. &&
  2539. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getElectricityDataFile()))
  2540. ) {
  2541. $newState = $em->getRepository(CotationState::class)->find(4);
  2542. $cotation->setState($newState);
  2543. } else if ($cotation->getAcdFile()) {
  2544. $newState = $em->getRepository(CotationState::class)->find(3);
  2545. $cotation->setState($newState);
  2546. } else {
  2547. $newState = $em->getRepository(CotationState::class)->find(2);
  2548. $cotation->setState($newState);
  2549. }
  2550. }
  2551. // Other documents
  2552. $otherDocuments = $form['otherDocuments']->getData();
  2553. foreach ($otherDocuments as $key => $cotationDocument) {
  2554. $cotationDocument->setCotation($cotation);
  2555. $file = $form['otherDocuments'][$key]["file"]->getData();
  2556. if ($file) {
  2557. $extension = $file->guessExtension();
  2558. if ($extension && in_array($extension, ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "pptx"])) {
  2559. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  2560. $file->move(
  2561. $this->getParameter('documents_justificatif_directory'),
  2562. $fileName
  2563. );
  2564. $cotationDocument->setPath($fileName);
  2565. }
  2566. }
  2567. $em->flush();
  2568. }
  2569. $this->get("session")->getFlashBag()->add("success", "Demande de cotation mise à jour");
  2570. //return $this->redirectToRoute("manager_companies_cotations", ["company" => $company->getId()]);
  2571. if (!$cotation->getPricingSentDate() && !($cotation->isAcdValid() && ($cotation->getFactElec() || $cotation->getFactGas()))) {
  2572. $this->get("session")->getFlashBag()->add("info", "Rappel: pour pouvoir notifier le pricing, il faut une ACD valide et la facture elec/gaz enregistrée.");
  2573. }
  2574. if ($cotation->getAcdFile() && $cotation->getElectricityDataFile() && $cotation->getGasDataFile()) {
  2575. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2576. }
  2577. // else retour formulaire
  2578. return $this->redirectToRoute('manager_companies_cotations_edit', ['company' => $company->getId(), 'cotation' => $cotation->getId()]);
  2579. }
  2580. return $this->render("app/clients/cotation_form.html.twig", [
  2581. "form" => $form->createView(),
  2582. "cotation" => $cotation,
  2583. ]);
  2584. }
  2585. /**
  2586. * @Route("/companies/{company}/cotations/{cotation}/old-invoice", name="companies_cotations_old_invoice")
  2587. */
  2588. public function cotationOldInvoiceAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2589. {
  2590. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2591. throw new NotFoundHttpException();
  2592. }
  2593. if (!$this->getUser()->getManager()->getAdmin()) {
  2594. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2595. throw new NotFoundHttpException();
  2596. }
  2597. }
  2598. if ($cotation->getOldInvoice()) {
  2599. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getOldInvoice();
  2600. return $this->file($filePath, $cotation->getOldInvoice(), ResponseHeaderBag::DISPOSITION_INLINE);
  2601. }
  2602. throw new NotFoundHttpException();
  2603. }
  2604. /**
  2605. * @Route("/companies/{company}/cotations/{cotation}/old-invoice-delete", name="companies_cotations_old_invoice-delete")
  2606. */
  2607. public function cotationOldInvoiceDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2608. {
  2609. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2610. throw new NotFoundHttpException();
  2611. }
  2612. if (!$this->getUser()->getManager()->getAdmin()) {
  2613. throw new NotFoundHttpException();
  2614. }
  2615. $cotation->setOldInvoice(null);
  2616. $em->flush();
  2617. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2618. }
  2619. /**
  2620. * @Route("/companies/{company}/cotations/{cotation}/fact-elec", name="companies_cotations_fact-elec")
  2621. */
  2622. public function cotationFactElecAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2623. {
  2624. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2625. throw new NotFoundHttpException();
  2626. }
  2627. if (!$this->getUser()->getManager()->getAdmin()) {
  2628. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2629. throw new NotFoundHttpException();
  2630. }
  2631. }
  2632. if ($cotation->getFactElec()) {
  2633. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getFactElec();
  2634. return $this->file($filePath, $cotation->getFactElec(), ResponseHeaderBag::DISPOSITION_INLINE);
  2635. }
  2636. throw new NotFoundHttpException();
  2637. }
  2638. /**
  2639. * @Route("/companies/{company}/cotations/{cotation}/fact-elec-delete", name="companies_cotations_fact-elec-delete")
  2640. */
  2641. public function cotationFactElecDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2642. {
  2643. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2644. throw new NotFoundHttpException();
  2645. }
  2646. if (!$this->getUser()->getManager()->getAdmin()) {
  2647. throw new NotFoundHttpException();
  2648. }
  2649. $cotation->setFactElec(null);
  2650. $em->flush();
  2651. if ($cotation->getCotationMultisite()) {
  2652. return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  2653. } else {
  2654. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2655. }
  2656. }
  2657. /**
  2658. * @Route("/companies/{company}/cotations/{cotation}/fact-gas", name="companies_cotations_fact-gas")
  2659. */
  2660. public function cotationFactGasAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2661. {
  2662. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2663. throw new NotFoundHttpException();
  2664. }
  2665. if (!$this->getUser()->getManager()->getAdmin()) {
  2666. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2667. throw new NotFoundHttpException();
  2668. }
  2669. }
  2670. if ($cotation->getFactGas()) {
  2671. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getFactGas();
  2672. return $this->file($filePath, $cotation->getFactGas(), ResponseHeaderBag::DISPOSITION_INLINE);
  2673. }
  2674. throw new NotFoundHttpException();
  2675. }
  2676. /**
  2677. * @Route("/companies/{company}/cotations/{cotation}/fact-gas-delete", name="companies_cotations_fact-gas-delete")
  2678. */
  2679. public function cotationFactGasDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2680. {
  2681. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2682. throw new NotFoundHttpException();
  2683. }
  2684. if (!$this->getUser()->getManager()->getAdmin()) {
  2685. throw new NotFoundHttpException();
  2686. }
  2687. $cotation->setFactGas(null);
  2688. $em->flush();
  2689. if ($cotation->getCotationMultisite()) {
  2690. return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  2691. } else {
  2692. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2693. }
  2694. }
  2695. /**
  2696. * @Route("/companies/{company}/cotations/{cotation}/liasse-fiscale", name="companies_cotations_liasse-fiscale")
  2697. */
  2698. public function cotationLiasseFiscaleAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2699. {
  2700. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2701. throw new NotFoundHttpException();
  2702. }
  2703. if (!$this->getUser()->getManager()->getAdmin()) {
  2704. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2705. throw new NotFoundHttpException();
  2706. }
  2707. }
  2708. if ($cotation->getLiasseFiscale()) {
  2709. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getLiasseFiscale();
  2710. return $this->file($filePath, $cotation->getLiasseFiscale(), ResponseHeaderBag::DISPOSITION_INLINE);
  2711. }
  2712. throw new NotFoundHttpException();
  2713. }
  2714. /**
  2715. * @Route("/companies/{company}/cotations/{cotation}/liasse-fiscale-delete", name="companies_cotations_liasse-fiscale-delete")
  2716. */
  2717. public function cotationLiasseFiscaleDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2718. {
  2719. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2720. throw new NotFoundHttpException();
  2721. }
  2722. if (!$this->getUser()->getManager()->getAdmin()) {
  2723. throw new NotFoundHttpException();
  2724. }
  2725. $cotation->setLiasseFiscale(null);
  2726. $em->flush();
  2727. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2728. }
  2729. /**
  2730. * @Route("/companies/{company}/cotations/{cotation}/sge-elec", name="companies_cotations_sge-elec")
  2731. */
  2732. public function cotationSgeElecAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2733. {
  2734. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2735. throw new NotFoundHttpException();
  2736. }
  2737. if (!$this->getUser()->getManager()->getAdmin()) {
  2738. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2739. throw new NotFoundHttpException();
  2740. }
  2741. }
  2742. if ($cotation->getSgeElec()) {
  2743. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getSgeElec();
  2744. return $this->file($filePath, $cotation->getSgeElec(), ResponseHeaderBag::DISPOSITION_INLINE);
  2745. }
  2746. throw new NotFoundHttpException();
  2747. }
  2748. /**
  2749. * @Route("/companies/{company}/cotations/{cotation}/sge-elec-delete", name="companies_cotations_sge-elec-delete")
  2750. */
  2751. public function cotationSgeElecDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2752. {
  2753. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2754. throw new NotFoundHttpException();
  2755. }
  2756. if (!$this->getUser()->getManager()->getAdmin()) {
  2757. throw new NotFoundHttpException();
  2758. }
  2759. $cotation->setSgeElec(null);
  2760. $em->flush();
  2761. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2762. }
  2763. /**
  2764. * @Route("/companies/{company}/cotations/{cotation}/omega-gas", name="companies_cotations_omega-gas")
  2765. */
  2766. public function cotationOmegaGasAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2767. {
  2768. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2769. throw new NotFoundHttpException();
  2770. }
  2771. if (!$this->getUser()->getManager()->getAdmin()) {
  2772. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2773. throw new NotFoundHttpException();
  2774. }
  2775. }
  2776. if ($cotation->getOmegaGas()) {
  2777. $filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getOmegaGas();
  2778. return $this->file($filePath, $cotation->getOmegaGas(), ResponseHeaderBag::DISPOSITION_INLINE);
  2779. }
  2780. throw new NotFoundHttpException();
  2781. }
  2782. /**
  2783. * @Route("/companies/{company}/cotations/{cotation}/omega-gas-delete", name="companies_cotations_omega-gas-delete")
  2784. */
  2785. public function cotationOmegaGasDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2786. {
  2787. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2788. throw new NotFoundHttpException();
  2789. }
  2790. if (!$this->getUser()->getManager()->getAdmin()) {
  2791. throw new NotFoundHttpException();
  2792. }
  2793. $cotation->setOmegaGas(null);
  2794. $em->flush();
  2795. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  2796. }
  2797. /**
  2798. * @Route("/companies/{company}/cotations/{cotation}/delete", name="companies_cotations_delete")
  2799. */
  2800. public function companiesCotationsDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2801. {
  2802. if (!$this->getUser()->getManager()->getAdmin()) {
  2803. throw new UnauthorizedHttpException("Admin only");
  2804. }
  2805. $cotation->setPreselectedOfferElec(null);
  2806. $cotation->setPreselectedOfferGaz(null);
  2807. $cotation->setSelectedOfferElec(null);
  2808. $cotation->setSelectedOfferGaz(null);
  2809. $em->flush();
  2810. $offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation]);
  2811. if ($offersElec) {
  2812. foreach ($offersElec as $offerElec) {
  2813. $em->remove($offerElec);
  2814. }
  2815. }
  2816. $em->flush();
  2817. $offersGaz = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation]);
  2818. if ($offersGaz) {
  2819. foreach ($offersGaz as $offerGaz) {
  2820. $em->remove($offerGaz);
  2821. }
  2822. }
  2823. $em->flush();
  2824. $em->remove($cotation);
  2825. $em->flush();
  2826. $this->get("session")->getFlashBag()->add("success", "Cotation supprimée");
  2827. return $this->redirectToRoute("manager_cotations", ["onlyInProgress" => 1]);
  2828. }
  2829. /**
  2830. * @Route("/companies/{company}/cotations/{cotation}/acd", name="companies_cotations_acd")
  2831. */
  2832. public function companiesCotationsAcdAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  2833. {
  2834. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2835. throw new NotFoundHttpException();
  2836. }
  2837. if (!$this->getUser()->getManager()->getAdmin()) {
  2838. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2839. throw new NotFoundHttpException();
  2840. }
  2841. }
  2842. if ($cotation->getAcdFile()) {
  2843. $filePath = $this->getParameter('documents_acd_directory') . $cotation->getAcdFile();
  2844. return $this->file($filePath, $cotation->getAcdFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  2845. }
  2846. if ($cotation->getState()->getId() == 1) {
  2847. $newState = $em->getRepository(CotationState::class)->find(2);
  2848. $cotation->setState($newState);
  2849. $em->flush();
  2850. }
  2851. $pdf = $this->generateACDv2($cotation);
  2852. $filename = "ACD";
  2853. return $pdf->Output($filename.".pdf",'I');
  2854. }
  2855. private function generateACD(Cotation $cotation): TCPDF
  2856. {
  2857. $pdf = new TCPDF();
  2858. $pdf->SetPrintHeader(false);
  2859. $pdf->SetAuthor('Flash Énergie');
  2860. $pdf->SetTitle("ACD");
  2861. $pdf->setMargins(10,5,10);
  2862. $pdf->AddPage();
  2863. $html = $this->renderView('app/pdf/acd.html.twig', [
  2864. 'cotation' => $cotation,
  2865. ]);
  2866. $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2867. $pdf->StartTransform();
  2868. $pdf->Rotate(90, 3, 68);
  2869. $pdf->writeHTMLCell($w = 0, $h = 0, $x = 5, $y = 68, '<span style="font-size: 10px;"><i>A remplir par le client</i></span>', $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2870. $pdf->StopTransform();
  2871. $pdf->StartTransform();
  2872. $pdf->Rotate(90, 3, 140);
  2873. $pdf->writeHTMLCell($w = 0, $h = 0, $x = 5, $y = 140, '<span style="font-size: 10px;"><i>A remplir par le consultant</i></span>', $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2874. $pdf->StopTransform();
  2875. return $pdf;
  2876. }
  2877. private function generateACDv2(Cotation $cotation): TCPDF
  2878. {
  2879. $pdf = new TCPDF();
  2880. $pdf->SetPrintHeader(false);
  2881. $pdf->SetAuthor('Flash Énergie');
  2882. $pdf->SetTitle("ACD");
  2883. $pdf->setMargins(10,5,10);
  2884. $pdf->AddPage();
  2885. $html = $this->renderView('app/pdf/acdv2.html.twig', [
  2886. 'cotation' => $cotation,
  2887. ]);
  2888. $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2889. $pdf->StartTransform();
  2890. $pdf->Rotate(90, 3, 68);
  2891. $pdf->writeHTMLCell($w = 0, $h = 0, $x = -20, $y = 68, '<span style="font-size: 10px;"><i>Signataire du présent document</i></span>', $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2892. $pdf->StopTransform();
  2893. return $pdf;
  2894. }
  2895. private function generateACDMultisite(CotationMultisite $cotation): TCPDF
  2896. {
  2897. $pdf = new TCPDF();
  2898. $pdf->SetPrintHeader(false);
  2899. $pdf->SetAuthor('Flash Énergie');
  2900. $pdf->SetTitle("ACD");
  2901. $pdf->setMargins(10,5,10);
  2902. $pdf->AddPage();
  2903. $html = $this->renderView('app/pdf/acdv2.html.twig', [
  2904. 'cotation' => $cotation,
  2905. ]);
  2906. $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2907. $pdf->StartTransform();
  2908. $pdf->Rotate(90, 3, 68);
  2909. $pdf->writeHTMLCell($w = 0, $h = 0, $x = -20, $y = 68, '<span style="font-size: 10px;"><i>Signataire du présent document</i></span>', $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
  2910. $pdf->StopTransform();
  2911. $pdf->AddPage();
  2912. $pdf->setFontSize(14);
  2913. $pdf->Cell(0, 10, 'ANNEXE', 0, 1, 'C');
  2914. $pdf->Ln(10);
  2915. $pdf->SetX(58);
  2916. $table = '<table border="1" cellpadding="4" cellspacing="0" width="95mm">
  2917. <thead>
  2918. <tr style="font-weight: bold; text-align: center;">
  2919. <th>'.($cotation->getElectricity() ? 'PDL' : 'PCE').'</th>
  2920. </tr>
  2921. </thead>
  2922. <tbody>';
  2923. if ($cotation->getElectricity()) {
  2924. foreach ($cotation->getCotations() as $cotationSite) {
  2925. $table .= '<tr><td height="20">' . $cotationSite->getEPdl() . '</td></tr>';
  2926. }
  2927. }
  2928. if ($cotation->getGas()) {
  2929. foreach ($cotation->getCotations() as $cotationSite) {
  2930. $table .= '<tr><td height="20">'.$cotationSite->getGPce().'</td></tr>';
  2931. }
  2932. }
  2933. $table .= '</tbody></table>';
  2934. $pdf->setFontSize(10);
  2935. $pdf->writeHTML($table, true, false, false, false, '');
  2936. $pdf->writeHTML(
  2937. '<table style="position: fixed; bottom: 10mm;">
  2938. <tr>
  2939. <td></td>
  2940. <td style="width: 50%;">
  2941. <table style="border: 0.75px solid black;" cellpadding="6">
  2942. <tr><td style="font-size: 8px;"><i>Cachet de l’entreprise + signature</i></td></tr>
  2943. <tr><td style="font-size: 8px;">_Date:</td></tr>
  2944. <tr><td style="height: 2.5cm; font-size: 8px;">_Signature</td></tr>
  2945. </table>
  2946. </td>
  2947. </tr>
  2948. </table>', true, false, false, false, '');
  2949. return $pdf;
  2950. }
  2951. /**
  2952. * @Route("/companies/{company}/cotations/{cotation}/resiliation-email", name="companies_cotations_resiliation-email")
  2953. */
  2954. public function companiesCotationsResiliationEmailAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, SendEmailService $sendEmailService, Pdf $knpSnappyPdf)
  2955. {
  2956. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  2957. throw new NotFoundHttpException();
  2958. }
  2959. if (!$this->getUser()->getManager()->getAdmin()) {
  2960. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  2961. throw new NotFoundHttpException();
  2962. }
  2963. }
  2964. if (!$cotation->getAcdFile()) {
  2965. throw new BadRequestHttpException();
  2966. }
  2967. if (isset($_POST["file_elec_content"])) {
  2968. $cotation->setResiliationElecEmailContent($_POST["file_elec_content"]);
  2969. $em->flush();
  2970. // Génération du PDF
  2971. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_elec_content"]);
  2972. // Email
  2973. $content = <<<EOD
  2974. Bonjour,<br/>
  2975. <br/>
  2976. Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture d'électricité actuel.<br/>
  2977. <br/>
  2978. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  2979. <br/>
  2980. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  2981. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  2982. <br/>
  2983. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  2984. EOD;
  2985. $sendEmailService->send(
  2986. "Flash Énergie: Lettre de changement de fournisseur Electricité",
  2987. $cotation->getEmail(),
  2988. 'emails/flash_default.html.twig',
  2989. [
  2990. "title" => "Lettre de changement de fournisseur",
  2991. "content" => $content
  2992. ],
  2993. 'resiliation@flash-consulting.fr',
  2994. null,
  2995. [
  2996. [
  2997. "content" => $pdf,
  2998. "name" => "courrier_de_changement_fournisseur_elec.pdf",
  2999. "contentType" => "application/pdf"
  3000. ]
  3001. ]
  3002. );
  3003. $cotation->setResiliationElecEmailSendDate(new \DateTime('now'));
  3004. $em->flush();
  3005. } elseif (isset($_POST["file_gas_content"])) {
  3006. $cotation->setResiliationGasEmailContent($_POST["file_gas_content"]);
  3007. $em->flush();
  3008. // Génération du PDF
  3009. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_gas_content"]);
  3010. // Email
  3011. $content = <<<EOD
  3012. Bonjour,<br/>
  3013. <br/>
  3014. Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture de gaz naturel actuel.<br/>
  3015. <br/>
  3016. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  3017. <br/>
  3018. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  3019. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  3020. <br/>
  3021. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  3022. EOD;
  3023. $sendEmailService->send(
  3024. "Flash Énergie: Lettre de changement de fournisseur Gaz",
  3025. $cotation->getEmail(),
  3026. 'emails/flash_default.html.twig',
  3027. [
  3028. "title" => "Lettre de changement de fournisseur",
  3029. "content" => $content
  3030. ],
  3031. 'resiliation@flash-consulting.fr',
  3032. null,
  3033. [
  3034. [
  3035. "content" => $pdf,
  3036. "name" => "courrier_de_changement_fournisseur_gaz.pdf",
  3037. "contentType" => "application/pdf"
  3038. ]
  3039. ]
  3040. );
  3041. $cotation->setResiliationGasEmailSendDate(new \DateTime('now'));
  3042. $em->flush();
  3043. } else {
  3044. $content = <<<EOD
  3045. Bonjour,<br/>
  3046. <br/>
  3047. Veuillez trouver ci-joint un modèle de courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat actuel.<br/>
  3048. <br/>
  3049. <i>Ce modèle est conçu pour vous aider à formaliser votre demande de résiliation conformément aux conditions de votre fournisseur d'énergie.</i><br/>
  3050. <br/>
  3051. De plus, nous avons également inclus <b>un guide</b> (voir pièces jointes) pour remplir le formulaire correctement.<br/>
  3052. <br/>
  3053. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  3054. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  3055. <br/>
  3056. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  3057. EOD;
  3058. $sendEmailService->send(
  3059. "Flash Énergie: Lettre de changement de fournisseur et son guide",
  3060. $cotation->getEmail(),
  3061. 'emails/flash_default.html.twig',
  3062. [
  3063. "title" => "Lettre de changement de fournisseur et son guide",
  3064. "content" => $content
  3065. ],
  3066. 'resiliation@flash-consulting.fr',
  3067. [
  3068. $this->getParameter('assets_directory')."Lettre de resiliation.docx",
  3069. $this->getParameter('assets_directory')."Guide pour remplir sa lettre de resiliation.docx",
  3070. ]
  3071. );
  3072. if (isset($_GET["elec"])) {
  3073. $cotation->setResiliationElecEmailSendDate(new \DateTime('now'));
  3074. }
  3075. if (isset($_GET["gas"])) {
  3076. $cotation->setResiliationGasEmailSendDate(new \DateTime('now'));
  3077. }
  3078. $em->flush();
  3079. }
  3080. $this->get("session")->getFlashBag()->add("success", "L'email de changement de fournisseur a bien été envoyé");
  3081. return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  3082. }
  3083. /**
  3084. * @Route("/companies/{company}/cotations/{cotation}/enedis", name="companies_cotations_enedis")
  3085. */
  3086. public function companiesCotationsEnedisAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
  3087. {
  3088. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3089. throw new NotFoundHttpException();
  3090. }
  3091. if (!$this->getUser()->getManager()->getAdmin()) {
  3092. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3093. throw new NotFoundHttpException();
  3094. }
  3095. }
  3096. $spreadsheet = new Spreadsheet();
  3097. $sheet = $spreadsheet->getActiveSheet();
  3098. $sheet->setTitle("Demande de Cotation");
  3099. $sheet->getProtection()->setSheet(true);
  3100. $spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
  3101. //HEADER
  3102. $sheet->setCellValue('A2', 'Demande de Cotation');
  3103. $sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
  3104. $sheet->getStyle("A2")->getAlignment()->setVertical("center");
  3105. $sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
  3106. $sheet->getStyle("A2")->getFont()->setBold(true);
  3107. $sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
  3108. $sheet->mergeCells("A2:E3");
  3109. $sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
  3110. $sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
  3111. $sheet->getColumnDimension("A")->setWidth(40);
  3112. $sheet->getColumnDimension("B")->setWidth(40);
  3113. $sheet->getColumnDimension("C")->setWidth(3);
  3114. $sheet->getColumnDimension("D")->setWidth(40);
  3115. $sheet->getColumnDimension("E")->setWidth(40);
  3116. //DONNEES CLIENT
  3117. $sheet->setCellValue('A5', 'Données client');
  3118. $sheet->setCellValue('A6', 'Raison sociale');
  3119. $sheet->setCellValue('A7', 'Titulaire');
  3120. $sheet->setCellValue('A8', 'SIRET du titulaire');
  3121. $sheet->setCellValue('A9', 'Payeur');
  3122. $sheet->setCellValue('A10', 'SIRET du payeur');
  3123. $sheet->setCellValue('A11', 'Prénom');
  3124. $sheet->setCellValue('A12', 'Nom');
  3125. $sheet->setCellValue('A13', 'Fonction');
  3126. $sheet->setCellValue('A14', 'Adresse de consommation');
  3127. $sheet->setCellValue('A16', 'Adresse facturation');
  3128. $sheet->setCellValue('A18', 'Téléphone');
  3129. $sheet->setCellValue('A19', 'Email');
  3130. $sheet->setCellValue('A20', 'Secteur client');
  3131. $sheet->setCellValue('A21', 'Activité APE/NAF');
  3132. $sheet->setCellValue('A22', 'Note ELIPRO');
  3133. $sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3134. $sheet->mergeCells("A5:B5");
  3135. $sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
  3136. $sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3137. $sheet->getStyle("A5:B22")->getAlignment()->setVertical('center');
  3138. $sheet->getStyle("A5:B22")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3139. for ($i = 6; $i <= 22; $i++) {
  3140. $sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3141. $sheet->getStyle('A'.$i)->getFont()->setBold(true);
  3142. $sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3143. //$sheet->getStyle('B'.$i)->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3144. $sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
  3145. }
  3146. $sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
  3147. $sheet->getStyle('B10')->getNumberFormat()->setFormatCode('0');
  3148. $sheet->mergeCells("A14:A15");
  3149. $sheet->mergeCells("B14:B15");
  3150. $sheet->mergeCells("A16:A17");
  3151. $sheet->mergeCells("B16:B17");
  3152. $sheet->getStyle('B14')->getAlignment()->setWrapText(true);
  3153. $sheet->getStyle('B16')->getAlignment()->setWrapText(true);
  3154. $sheet->getStyle('A6:A22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
  3155. $sheet->getStyle('B6:B22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3156. $sheet->setCellValue('B6', $cotation->getCompanyName());
  3157. $sheet->setCellValue('B7', $cotation->getCompanyName());
  3158. $sheet->setCellValue('B8', $cotation->getSiret());
  3159. // Payeur
  3160. // Siret du payeur
  3161. $sheet->setCellValue('B11', $cotation->getFirstName());
  3162. $sheet->setCellValue('B12', $cotation->getLastName());
  3163. $sheet->setCellValue('B13', $cotation->getPosition());
  3164. $sheet->setCellValue('B14', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
  3165. $sheet->setCellValue('B16', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
  3166. $sheet->setCellValue('B18', $cotation->getPhone());
  3167. $sheet->setCellValue('B19', $cotation->getEmail());
  3168. $sheet->setCellValue('B20', $cotation->getSector() ?: ($cotation->getCompany()? $cotation->getCompany()->getSector():""));
  3169. $sheet->setCellValue('B21', $cotation->getApeCode() ?: ($cotation->getCompany()?($cotation->getCompany()->getApeCode()):""));
  3170. $sheet->setCellValue('B22', $cotation->getEliproNote() ?: ($cotation->getCompany()?($cotation->getCompany()->getEliproNote()):""));
  3171. //ENEDIS
  3172. $sheet->setCellValue('D5', 'Données consommation électricité');
  3173. $sheet->setCellValue('D6', 'Fournisseur actuel');
  3174. $sheet->setCellValue('D7', 'Début de fourniture souhaitée');
  3175. $sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
  3176. $sheet->setCellValue('D9', 'Nombre de mois à fournir');
  3177. $sheet->setCellValue('D10', 'PDL');
  3178. $sheet->setCellValue('D11', 'Segment');
  3179. $sheet->setCellValue('D12', 'Formule acheminement(facultatif)');
  3180. $sheet->setCellValue('D13', 'CAR (MWh)');
  3181. $sheet->setCellValue('D14', 'Consommation Pointe');
  3182. $sheet->setCellValue('D15', 'Consommation HPH');
  3183. $sheet->setCellValue('D16', 'Consommation HCH');
  3184. $sheet->setCellValue('D17', 'Consommation HPE');
  3185. $sheet->setCellValue('D18', 'Consommation HCE');
  3186. $sheet->setCellValue('D19', 'Puissance souscrites (Kva)');
  3187. $sheet->setCellValue('D20', 'Pointe');
  3188. $sheet->setCellValue('D21', 'HPH');
  3189. $sheet->setCellValue('D22', 'HCH');
  3190. $sheet->setCellValue('D23', 'HPE');
  3191. $sheet->setCellValue('D24', 'HCE');
  3192. $sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3193. $sheet->mergeCells("D5:E5");
  3194. $sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3195. $sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3196. $sheet->getStyle("D5:E24")->getAlignment()->setVertical('center');
  3197. $sheet->getStyle("D5:E24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3198. for ($i = 6; $i <= 24; $i++) {
  3199. $sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3200. $sheet->getStyle('D'.$i)->getFont()->setBold(true);
  3201. $sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3202. $sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
  3203. }
  3204. $sheet->mergeCells("D19:E19");
  3205. $sheet->getStyle('D19:E19')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3206. $sheet->getStyle('D6:D18')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3207. $sheet->getStyle('D20:D24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3208. $sheet->getStyle('E6:E8')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3209. $sheet->getStyle('E10:E11')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3210. $sheet->getStyle('E20:E24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3211. //$sheet->getStyle('E6:E8')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3212. //$sheet->getStyle('E10:E11')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3213. //$sheet->getStyle('E20:E24')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3214. $sheet->setCellValue('E6', $cotation->getElectricitySupplier()?$cotation->getElectricitySupplier()->getName():"");
  3215. $sheet->setCellValue('E7', $cotation->getEDesiredBegin()?$cotation->getEDesiredBegin()->format("d/m/Y"):"");
  3216. $sheet->setCellValue('E8', $cotation->getEDesiredEnd()?$cotation->getEDesiredEnd()->format("d/m/Y"):"");
  3217. $sheet->setCellValue('E9', $cotation->getENombreMois());
  3218. $sheet->setCellValue('E10', $cotation->getEPdl());
  3219. $sheet->setCellValue('E11', $cotation->getESegment());
  3220. $sheet->setCellValue('E12', $cotation->getEFormuleAcheminement());
  3221. $sheet->setCellValue('E13', $cotation->getECarMwh());
  3222. $sheet->setCellValue('E14', $cotation->getEConsommationPointe());
  3223. $sheet->setCellValue('E15', $cotation->getEConsommationHph());
  3224. $sheet->setCellValue('E16', $cotation->getEConsommationHch());
  3225. $sheet->setCellValue('E17', $cotation->getEConsommationHpe());
  3226. $sheet->setCellValue('E18', $cotation->getEConsommationHce());
  3227. $sheet->setCellValue('E20', $cotation->getEPuissanceKvaPointe());
  3228. $sheet->setCellValue('E21', $cotation->getEPuissanceKvaHph());
  3229. $sheet->setCellValue('E22', $cotation->getEPuissanceKvaHch());
  3230. $sheet->setCellValue('E23', $cotation->getEPuissanceKvaHpe());
  3231. $sheet->setCellValue('E24', $cotation->getEPuissanceKvaHce());
  3232. //END
  3233. $sheet->getRowDimension("2")->setRowHeight(18);
  3234. $sheet->getRowDimension("3")->setRowHeight(18);
  3235. $sheet->getRowDimension("5")->setRowHeight(26);
  3236. $sheet->getRowDimension("6")->setRowHeight(26);
  3237. $sheet->getRowDimension("7")->setRowHeight(26);
  3238. $sheet->getRowDimension("8")->setRowHeight(26);
  3239. $sheet->getRowDimension("9")->setRowHeight(26);
  3240. $sheet->getRowDimension("10")->setRowHeight(26);
  3241. $sheet->getRowDimension("11")->setRowHeight(26);
  3242. $sheet->getRowDimension("12")->setRowHeight(26);
  3243. $sheet->getRowDimension("13")->setRowHeight(26);
  3244. $sheet->getRowDimension("14")->setRowHeight(26);
  3245. $sheet->getRowDimension("15")->setRowHeight(26);
  3246. $sheet->getRowDimension("16")->setRowHeight(26);
  3247. $sheet->getRowDimension("17")->setRowHeight(26);
  3248. $sheet->getRowDimension("18")->setRowHeight(26);
  3249. $sheet->getRowDimension("19")->setRowHeight(26);
  3250. $sheet->getRowDimension("20")->setRowHeight(26);
  3251. $sheet->getRowDimension("21")->setRowHeight(26);
  3252. $sheet->getRowDimension("22")->setRowHeight(26);
  3253. $sheet->getRowDimension("23")->setRowHeight(26);
  3254. $sheet->getRowDimension("24")->setRowHeight(26);
  3255. $drawingLogo = new Drawing();
  3256. $drawingLogo->setName('Logo');
  3257. $drawingLogo->setDescription('Logo');
  3258. $drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
  3259. $drawingLogo->setCoordinates('A2');
  3260. $drawingLogo->setHeight(36);
  3261. $drawingLogo->setOffsetY(6);
  3262. $drawingLogo->setOffsetX(12);
  3263. $drawingLogo->setWorksheet($sheet);
  3264. $drawingData = new Drawing();
  3265. $drawingData->setName('Logo Data');
  3266. $drawingData->setDescription('Logo Data');
  3267. $drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/enedis.png');
  3268. $drawingData->setCoordinates('E5');
  3269. $drawingData->setHeight(26);
  3270. $drawingData->setOffsetY(4);
  3271. $drawingData->setOffsetX(12);
  3272. $drawingData->setWorksheet($sheet);
  3273. $sheet->setSelectedCell("A1");
  3274. $writer = new Xlsx($spreadsheet);
  3275. $response = new StreamedResponse();
  3276. $response->setCallback(function () use ($writer) {
  3277. $writer->save('php://output');
  3278. });
  3279. $filenane = "enedis_".$cotation->getCompanyName().'.xlsx';
  3280. $response->setStatusCode(200);
  3281. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3282. $response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
  3283. $response->headers->set('Cache-Control', 'max-age=0');
  3284. return $response;
  3285. }
  3286. /**
  3287. * @Route("/companies/{company}/cotations/{cotation}/grdf", name="companies_cotations_grdf")
  3288. */
  3289. public function companiesCotationsGrdfAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
  3290. {
  3291. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3292. throw new NotFoundHttpException();
  3293. }
  3294. if (!$this->getUser()->getManager()->getAdmin()) {
  3295. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3296. throw new NotFoundHttpException();
  3297. }
  3298. }
  3299. $spreadsheet = new Spreadsheet();
  3300. $sheet = $spreadsheet->getActiveSheet();
  3301. $sheet->setTitle("Demande de Cotation");
  3302. $sheet->getProtection()->setSheet(true);
  3303. $spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
  3304. //HEADER
  3305. $sheet->setCellValue('A2', 'Demande de Cotation');
  3306. $sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
  3307. $sheet->getStyle("A2")->getAlignment()->setVertical("center");
  3308. $sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
  3309. $sheet->getStyle("A2")->getFont()->setBold(true);
  3310. $sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
  3311. $sheet->mergeCells("A2:E3");
  3312. $sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
  3313. $sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
  3314. $sheet->getColumnDimension("A")->setWidth(40);
  3315. $sheet->getColumnDimension("B")->setWidth(40);
  3316. $sheet->getColumnDimension("C")->setWidth(3);
  3317. $sheet->getColumnDimension("D")->setWidth(40);
  3318. $sheet->getColumnDimension("E")->setWidth(40);
  3319. //DONNEES CLIENT
  3320. $sheet->setCellValue('A5', 'Données client');
  3321. $sheet->setCellValue('A6', 'Raison sociale');
  3322. $sheet->setCellValue('A7', 'Titulaire');
  3323. $sheet->setCellValue('A8', 'SIRET du titulaire');
  3324. $sheet->setCellValue('A9', 'Payeur');
  3325. $sheet->setCellValue('A10', 'SIRET du payeur');
  3326. $sheet->setCellValue('A11', 'Prénom');
  3327. $sheet->setCellValue('A12', 'Nom');
  3328. $sheet->setCellValue('A13', 'Fonction');
  3329. $sheet->setCellValue('A14', 'Adresse de consommation');
  3330. $sheet->setCellValue('A16', 'Adresse facturation');
  3331. $sheet->setCellValue('A18', 'Téléphone');
  3332. $sheet->setCellValue('A19', 'Email');
  3333. $sheet->setCellValue('A20', 'Secteur client');
  3334. $sheet->setCellValue('A21', 'Activité APE/NAF');
  3335. $sheet->setCellValue('A22', 'Note Elipro');
  3336. $sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3337. $sheet->mergeCells("A5:B5");
  3338. $sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
  3339. $sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3340. $sheet->getStyle("A5:B22")->getAlignment()->setVertical('center');
  3341. $sheet->getStyle("A5:B22")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3342. for ($i = 6; $i <= 22; $i++) {
  3343. $sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3344. $sheet->getStyle('A'.$i)->getFont()->setBold(true);
  3345. $sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3346. //$sheet->getStyle('B'.$i)->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3347. $sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
  3348. }
  3349. $sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
  3350. $sheet->getStyle('B10')->getNumberFormat()->setFormatCode('0');
  3351. $sheet->mergeCells("A14:A15");
  3352. $sheet->mergeCells("B14:B15");
  3353. $sheet->mergeCells("A16:A17");
  3354. $sheet->mergeCells("B16:B17");
  3355. $sheet->getStyle('B14')->getAlignment()->setWrapText(true);
  3356. $sheet->getStyle('B16')->getAlignment()->setWrapText(true);
  3357. $sheet->getStyle('A6:A22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
  3358. $sheet->getStyle('B6:B22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3359. $sheet->setCellValue('B6', $cotation->getCompanyName());
  3360. $sheet->setCellValue('B7', $cotation->getCompanyName());
  3361. $sheet->setCellValue('B8', $cotation->getSiret());
  3362. // Payeur
  3363. // Siret payeur
  3364. $sheet->setCellValue('B11', $cotation->getFirstName());
  3365. $sheet->setCellValue('B12', $cotation->getLastName());
  3366. $sheet->setCellValue('B13', $cotation->getPosition());
  3367. $sheet->setCellValue('B14', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
  3368. $sheet->setCellValue('B16', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
  3369. $sheet->setCellValue('B18', $cotation->getPhone());
  3370. $sheet->setCellValue('B19', $cotation->getEmail());
  3371. $sheet->setCellValue('B20', $cotation->getSector() ?: ($cotation->getCompany()?$cotation->getCompany()->getSector():""));
  3372. $sheet->setCellValue('B21', $cotation->getApeCode() ?: ($cotation->getCompany()?($cotation->getCompany()->getApeCode()):""));
  3373. $sheet->setCellValue('B22', $cotation->getEliproNote() ?: ($cotation->getCompany()?($cotation->getCompany()->getEliproNote()):""));
  3374. //GRDF
  3375. $sheet->setCellValue('D5', 'Données consommation Gaz');
  3376. $sheet->setCellValue('D6', 'Fournisseur actuel');
  3377. $sheet->setCellValue('D7', 'Début de fourniture souhaitée');
  3378. $sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
  3379. $sheet->setCellValue('D9', 'Nombre de mois à fournir');
  3380. $sheet->setCellValue('D10', 'PCE');
  3381. $sheet->setCellValue('D11', 'Segment');
  3382. $sheet->setCellValue('D12', 'CAR (MWh)');
  3383. $sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3384. $sheet->mergeCells("D5:E5");
  3385. $sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3386. $sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3387. $sheet->getStyle("D5:E12")->getAlignment()->setVertical('center');
  3388. $sheet->getStyle("D5:E12")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3389. for ($i = 6; $i <= 12; $i++) {
  3390. $sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3391. $sheet->getStyle('D'.$i)->getFont()->setBold(true);
  3392. $sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3393. $sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
  3394. }
  3395. $sheet->getStyle('D6:D12')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3396. $sheet->getStyle('E6:E8')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3397. $sheet->getStyle('E10:E11')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
  3398. //$sheet->getStyle('E6:E8')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3399. //$sheet->getStyle('E10:E11')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
  3400. $sheet->setCellValue('E6', $cotation->getGasSupplier()?$cotation->getGasSupplier()->getName():"");
  3401. $sheet->setCellValue('E7', $cotation->getGDesiredBegin()?$cotation->getGDesiredBegin()->format("d/m/Y"):"");
  3402. $sheet->setCellValue('E8', $cotation->getGDesiredEnd()?$cotation->getGDesiredEnd()->format("d/m/Y"):"");
  3403. $sheet->setCellValue('E9', $cotation->getGNombreMois());
  3404. $sheet->setCellValue('E10', $cotation->getGPce());
  3405. $sheet->setCellValue('E11', $cotation->getGSegment());
  3406. $sheet->setCellValue('E12', $cotation->getGCarMwh());
  3407. //END
  3408. $sheet->getRowDimension("2")->setRowHeight(18);
  3409. $sheet->getRowDimension("3")->setRowHeight(18);
  3410. $sheet->getRowDimension("5")->setRowHeight(26);
  3411. $sheet->getRowDimension("6")->setRowHeight(26);
  3412. $sheet->getRowDimension("7")->setRowHeight(26);
  3413. $sheet->getRowDimension("8")->setRowHeight(26);
  3414. $sheet->getRowDimension("9")->setRowHeight(26);
  3415. $sheet->getRowDimension("10")->setRowHeight(26);
  3416. $sheet->getRowDimension("11")->setRowHeight(26);
  3417. $sheet->getRowDimension("12")->setRowHeight(26);
  3418. $sheet->getRowDimension("13")->setRowHeight(26);
  3419. $sheet->getRowDimension("14")->setRowHeight(26);
  3420. $sheet->getRowDimension("15")->setRowHeight(26);
  3421. $sheet->getRowDimension("16")->setRowHeight(26);
  3422. $sheet->getRowDimension("17")->setRowHeight(26);
  3423. $sheet->getRowDimension("18")->setRowHeight(26);
  3424. $sheet->getRowDimension("19")->setRowHeight(26);
  3425. $sheet->getRowDimension("20")->setRowHeight(26);
  3426. $sheet->getRowDimension("21")->setRowHeight(26);
  3427. $sheet->getRowDimension("22")->setRowHeight(26);
  3428. $sheet->getRowDimension("23")->setRowHeight(26);
  3429. $sheet->getRowDimension("24")->setRowHeight(26);
  3430. $drawingLogo = new Drawing();
  3431. $drawingLogo->setName('Logo');
  3432. $drawingLogo->setDescription('Logo');
  3433. $drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
  3434. $drawingLogo->setCoordinates('A2');
  3435. $drawingLogo->setHeight(36);
  3436. $drawingLogo->setOffsetY(6);
  3437. $drawingLogo->setOffsetX(12);
  3438. $drawingLogo->setWorksheet($sheet);
  3439. $drawingData = new Drawing();
  3440. $drawingData->setName('Logo Data');
  3441. $drawingData->setDescription('Logo Data');
  3442. $drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/grdf.png');
  3443. $drawingData->setCoordinates('E5');
  3444. $drawingData->setHeight(26);
  3445. $drawingData->setOffsetY(4);
  3446. $drawingData->setOffsetX(12);
  3447. $drawingData->setWorksheet($sheet);
  3448. $sheet->setSelectedCell("A1");
  3449. $writer = new Xlsx($spreadsheet);
  3450. $response = new StreamedResponse();
  3451. $response->setCallback(function () use ($writer) {
  3452. $writer->save('php://output');
  3453. });
  3454. $filenane = "grdf_".$cotation->getCompanyName().'.xlsx';
  3455. $response->setStatusCode(200);
  3456. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3457. $response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
  3458. $response->headers->set('Cache-Control', 'max-age=0');
  3459. return $response;
  3460. }
  3461. /**
  3462. * @Route("/companies/{company}/cotations/{cotation}/review", name="companies_cotations_review")
  3463. */
  3464. public function companiesCotationsReviewAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
  3465. {
  3466. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3467. throw new NotFoundHttpException();
  3468. }
  3469. if (!$this->getUser()->getManager()->getAdmin()) {
  3470. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3471. throw new NotFoundHttpException();
  3472. }
  3473. }
  3474. $spreadsheet = new Spreadsheet();
  3475. $sheet = $spreadsheet->getActiveSheet();
  3476. $sheet->setTitle("Cotation");
  3477. $sheet->getProtection()->setSheet(true);
  3478. $spreadsheet->getDefaultStyle()->getProtection()->setLocked(true);
  3479. //HEADER
  3480. $sheet->setCellValue('A2', 'Cotation');
  3481. $sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
  3482. $sheet->getStyle("A2")->getAlignment()->setVertical("center");
  3483. $sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
  3484. $sheet->getStyle("A2")->getFont()->setBold(true);
  3485. $sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
  3486. if ($cotation->getElectricity() && $cotation->getGas()) {
  3487. $sheet->mergeCells("A2:H3");
  3488. $sheet->getStyle('A2:H3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
  3489. $sheet->getStyle('A2:H3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
  3490. } else {
  3491. $sheet->mergeCells("A2:E3");
  3492. $sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
  3493. $sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
  3494. }
  3495. $sheet->getColumnDimension("A")->setWidth(40);
  3496. $sheet->getColumnDimension("B")->setWidth(40);
  3497. $sheet->getColumnDimension("C")->setWidth(3);
  3498. $sheet->getColumnDimension("D")->setWidth(40);
  3499. $sheet->getColumnDimension("E")->setWidth(40);
  3500. if ($cotation->getElectricity() && $cotation->getGas()) {
  3501. $sheet->getColumnDimension("F")->setWidth(3);
  3502. $sheet->getColumnDimension("G")->setWidth(40);
  3503. $sheet->getColumnDimension("H")->setWidth(40);
  3504. }
  3505. //DONNEES CLIENT
  3506. $sheet->setCellValue('A5', 'Données client');
  3507. $sheet->setCellValue('A6', 'Raison sociale');
  3508. $sheet->setCellValue('A7', 'Nom du site');
  3509. $sheet->setCellValue('A8', 'SIRET');
  3510. $sheet->setCellValue('A9', 'Prénom');
  3511. $sheet->setCellValue('A10', 'Nom');
  3512. $sheet->setCellValue('A11', 'Fonction');
  3513. $sheet->setCellValue('A12', 'Adresse');
  3514. $sheet->setCellValue('A14', 'Adresse facturation');
  3515. $sheet->setCellValue('A16', 'Téléphone');
  3516. $sheet->setCellValue('A17', 'Email');
  3517. $sheet->setCellValue('A18', 'Secteur client');
  3518. $sheet->setCellValue('A19', 'Activité APE/NAF');
  3519. $sheet->setCellValue('A20', 'Tenue de l\'offre en jours');
  3520. $sheet->setCellValue('A21', 'Date du RDV client');
  3521. $sheet->setCellValue('A22', 'Ellipro (note sur 10) / 40/100 Créditsafe');
  3522. $sheet->setCellValue('A23', 'Tarif unique/ horosaisonnalité, Arenh(%) ...');
  3523. $sheet->setCellValue('A24', 'Marge souhaitée POUR flash Énergie');
  3524. $sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3525. $sheet->mergeCells("A5:B5");
  3526. $sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
  3527. $sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3528. $sheet->getStyle("A5:B24")->getAlignment()->setVertical('center');
  3529. $sheet->getStyle("A5:B24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3530. for ($i = 6; $i <= 24; $i++) {
  3531. $sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3532. $sheet->getStyle('A'.$i)->getFont()->setBold(true);
  3533. $sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3534. $sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
  3535. }
  3536. $sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
  3537. $sheet->mergeCells("A12:A13");
  3538. $sheet->mergeCells("B12:B13");
  3539. $sheet->mergeCells("A14:A15");
  3540. $sheet->mergeCells("B14:B15");
  3541. $sheet->getStyle('B12')->getAlignment()->setWrapText(true);
  3542. $sheet->getStyle('B14')->getAlignment()->setWrapText(true);
  3543. $sheet->getStyle('A6:A24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
  3544. $sheet->setCellValue('B6', $cotation->getCompanyName());
  3545. $sheet->setCellValue('B7', $cotation->getPlaceName());
  3546. $sheet->setCellValue('B8', $cotation->getSiret());
  3547. $sheet->setCellValue('B9', $cotation->getFirstName());
  3548. $sheet->setCellValue('B10', $cotation->getLastName());
  3549. $sheet->setCellValue('B11', $cotation->getPosition());
  3550. $sheet->setCellValue('B12', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
  3551. $sheet->setCellValue('B14', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
  3552. $sheet->setCellValue('B16', $cotation->getPhone());
  3553. $sheet->setCellValue('B17', $cotation->getEmail());
  3554. $sheet->setCellValue('B18', $cotation->getCompany()?$cotation->getCompany()->getSector():"");
  3555. $sheet->setCellValue('B19', $cotation->getCompany()?($cotation->getCompany()->getApeCode()):"");
  3556. $sheet->setCellValue('B20', '1 à 2 de validité du contrat');
  3557. $sheet->setCellValue('B21', $cotation->getAppointmentDate()?$cotation->getAppointmentDate()->format("d/m/Y"):"");
  3558. $sheet->setCellValue('B22', $cotation->getCreditsafeNote());
  3559. $sheet->setCellValue('B23', $cotation->getTarifType());
  3560. $sheet->setCellValue('B24', $cotation->getDesiredMargin());
  3561. if ($cotation->getElectricity()) {
  3562. //ENEDIS
  3563. $sheet->setCellValue('D5', 'Données consommation électricité');
  3564. $sheet->setCellValue('D6', 'Fournisseur actuel');
  3565. $sheet->setCellValue('D7', 'Début de fourniture souhaitée');
  3566. $sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
  3567. $sheet->setCellValue('D9', 'Nombre de mois à fournir');
  3568. $sheet->setCellValue('D10', 'RAE');
  3569. $sheet->setCellValue('D11', 'Segment');
  3570. $sheet->setCellValue('D12', 'Formule acheminement(facultatif)');
  3571. $sheet->setCellValue('D13', 'CAR (MWh)');
  3572. $sheet->setCellValue('D14', 'Consommation Pointe');
  3573. $sheet->setCellValue('D15', 'Consommation HPH');
  3574. $sheet->setCellValue('D16', 'Consommation HCH');
  3575. $sheet->setCellValue('D17', 'Consommation HPE');
  3576. $sheet->setCellValue('D18', 'Consommation HCE');
  3577. $sheet->setCellValue('D19', 'Puissance souscrites (Kva)');
  3578. $sheet->setCellValue('D20', 'Pointe');
  3579. $sheet->setCellValue('D21', 'HPH');
  3580. $sheet->setCellValue('D22', 'HCH');
  3581. $sheet->setCellValue('D23', 'HPE');
  3582. $sheet->setCellValue('D24', 'HCE');
  3583. $sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3584. $sheet->mergeCells("D5:E5");
  3585. $sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3586. $sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3587. $sheet->getStyle("D5:E24")->getAlignment()->setVertical('center');
  3588. $sheet->getStyle("D5:E24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3589. for ($i = 6; $i <= 24; $i++) {
  3590. $sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3591. $sheet->getStyle('D'.$i)->getFont()->setBold(true);
  3592. $sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3593. $sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
  3594. }
  3595. $sheet->mergeCells("D19:E19");
  3596. $sheet->getStyle('D19:E19')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3597. $sheet->getStyle('D6:D18')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3598. $sheet->getStyle('D20:D24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3599. $sheet->setCellValue('E6', $cotation->getElectricitySupplier()?$cotation->getElectricitySupplier()->getName():"");
  3600. $sheet->setCellValue('E7', $cotation->getEDesiredBegin()?$cotation->getEDesiredBegin()->format("d/m/Y"):"");
  3601. $sheet->setCellValue('E8', $cotation->getEDesiredEnd()?$cotation->getEDesiredEnd()->format("d/m/Y"):"");
  3602. $sheet->setCellValue('E9', $cotation->getENombreMois());
  3603. $sheet->setCellValue('E10', $cotation->getERae());
  3604. $sheet->setCellValue('E11', $cotation->getESegment());
  3605. $sheet->setCellValue('E12', $cotation->getEFormuleAcheminement());
  3606. $sheet->setCellValue('E13', $cotation->getECarMwh());
  3607. $sheet->setCellValue('E14', $cotation->getEConsommationPointe());
  3608. $sheet->setCellValue('E15', $cotation->getEConsommationHph());
  3609. $sheet->setCellValue('E16', $cotation->getEConsommationHch());
  3610. $sheet->setCellValue('E17', $cotation->getEConsommationHpe());
  3611. $sheet->setCellValue('E18', $cotation->getEConsommationHce());
  3612. $sheet->setCellValue('E20', $cotation->getEPuissanceKvaPointe());
  3613. $sheet->setCellValue('E21', $cotation->getEPuissanceKvaHph());
  3614. $sheet->setCellValue('E22', $cotation->getEPuissanceKvaHch());
  3615. $sheet->setCellValue('E23', $cotation->getEPuissanceKvaHpe());
  3616. $sheet->setCellValue('E24', $cotation->getEPuissanceKvaHce());
  3617. $drawingData = new Drawing();
  3618. $drawingData->setName('Logo Data');
  3619. $drawingData->setDescription('Logo Data');
  3620. $drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/enedis.png');
  3621. $drawingData->setCoordinates('E5');
  3622. $drawingData->setHeight(26);
  3623. $drawingData->setOffsetY(4);
  3624. $drawingData->setOffsetX(12);
  3625. $drawingData->setWorksheet($sheet);
  3626. }
  3627. if ($cotation->getGas()) {
  3628. $beginLetter = "D";
  3629. $endLetter = "E";
  3630. if ($cotation->getElectricity()) {
  3631. $beginLetter = "G";
  3632. $endLetter = "H";
  3633. }
  3634. //GRDF
  3635. $sheet->setCellValue($beginLetter.'5', 'Données consommation Gaz');
  3636. $sheet->setCellValue($beginLetter.'6', 'Fournisseur actuel');
  3637. $sheet->setCellValue($beginLetter.'7', 'Début de fourniture souhaitée');
  3638. $sheet->setCellValue($beginLetter.'8', 'Fin de la fourniture souhaitée');
  3639. $sheet->setCellValue($beginLetter.'9', 'Nombre de mois à fournir');
  3640. $sheet->setCellValue($beginLetter.'10', 'PCE');
  3641. $sheet->setCellValue($beginLetter.'11', 'Segment');
  3642. $sheet->setCellValue($beginLetter.'12', 'CAR (MWh)');
  3643. $sheet->getStyle($beginLetter.'5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
  3644. $sheet->mergeCells($beginLetter."5:".$endLetter."5");
  3645. $sheet->getStyle($beginLetter.'$5:'.$endLetter.'5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
  3646. $sheet->getStyle($beginLetter.'$5:'.$endLetter.'5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3647. $sheet->getStyle($beginLetter."5:".$endLetter."12")->getAlignment()->setVertical('center');
  3648. $sheet->getStyle($beginLetter."5:".$endLetter."12")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
  3649. for ($i = 6; $i <= 12; $i++) {
  3650. $sheet->getStyle($beginLetter.''.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3651. $sheet->getStyle($beginLetter.''.$i)->getFont()->setBold(true);
  3652. $sheet->getStyle($endLetter.''.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
  3653. $sheet->getStyle($endLetter.''.$i)->getAlignment()->setHorizontal('left');
  3654. }
  3655. $sheet->getStyle($beginLetter.'6:'.$beginLetter.'12')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
  3656. $sheet->setCellValue($endLetter.'6', $cotation->getGasSupplier()?$cotation->getGasSupplier()->getName():"");
  3657. $sheet->setCellValue($endLetter.'7', $cotation->getGDesiredBegin()?$cotation->getGDesiredBegin()->format("d/m/Y"):"");
  3658. $sheet->setCellValue($endLetter.'8', $cotation->getGDesiredEnd()?$cotation->getGDesiredEnd()->format("d/m/Y"):"");
  3659. $sheet->setCellValue($endLetter.'9', $cotation->getGNombreMois());
  3660. $sheet->setCellValue($endLetter.'10', $cotation->getGPce());
  3661. $sheet->setCellValue($endLetter.'11', $cotation->getGSegment());
  3662. $sheet->setCellValue($endLetter.'12', $cotation->getGCarMwh());
  3663. $drawingData = new Drawing();
  3664. $drawingData->setName('Logo Data');
  3665. $drawingData->setDescription('Logo Data');
  3666. $drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/grdf.png');
  3667. $drawingData->setCoordinates($endLetter.'5');
  3668. $drawingData->setHeight(26);
  3669. $drawingData->setOffsetY(4);
  3670. $drawingData->setOffsetX(12);
  3671. $drawingData->setWorksheet($sheet);
  3672. }
  3673. //END
  3674. $sheet->getRowDimension("2")->setRowHeight(18);
  3675. $sheet->getRowDimension("3")->setRowHeight(18);
  3676. $sheet->getRowDimension("5")->setRowHeight(26);
  3677. $sheet->getRowDimension("6")->setRowHeight(26);
  3678. $sheet->getRowDimension("7")->setRowHeight(26);
  3679. $sheet->getRowDimension("8")->setRowHeight(26);
  3680. $sheet->getRowDimension("9")->setRowHeight(26);
  3681. $sheet->getRowDimension("10")->setRowHeight(26);
  3682. $sheet->getRowDimension("11")->setRowHeight(26);
  3683. $sheet->getRowDimension("12")->setRowHeight(26);
  3684. $sheet->getRowDimension("13")->setRowHeight(26);
  3685. $sheet->getRowDimension("14")->setRowHeight(26);
  3686. $sheet->getRowDimension("15")->setRowHeight(26);
  3687. $sheet->getRowDimension("16")->setRowHeight(26);
  3688. $sheet->getRowDimension("17")->setRowHeight(26);
  3689. $sheet->getRowDimension("18")->setRowHeight(26);
  3690. $sheet->getRowDimension("19")->setRowHeight(26);
  3691. $sheet->getRowDimension("20")->setRowHeight(26);
  3692. $sheet->getRowDimension("21")->setRowHeight(26);
  3693. $sheet->getRowDimension("22")->setRowHeight(26);
  3694. $sheet->getRowDimension("23")->setRowHeight(26);
  3695. $sheet->getRowDimension("24")->setRowHeight(26);
  3696. $drawingLogo = new Drawing();
  3697. $drawingLogo->setName('Logo');
  3698. $drawingLogo->setDescription('Logo');
  3699. $drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
  3700. $drawingLogo->setCoordinates('A2');
  3701. $drawingLogo->setHeight(36);
  3702. $drawingLogo->setOffsetY(6);
  3703. $drawingLogo->setOffsetX(12);
  3704. $drawingLogo->setWorksheet($sheet);
  3705. $sheet->setSelectedCell("A1");
  3706. $writer = new Xlsx($spreadsheet);
  3707. $response = new StreamedResponse();
  3708. $response->setCallback(function () use ($writer) {
  3709. $writer->save('php://output');
  3710. });
  3711. $response->setStatusCode(200);
  3712. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3713. $response->headers->set('Content-Disposition', 'attachment;filename="enedis.xlsx"');
  3714. $response->headers->set('Cache-Control', 'max-age=0');
  3715. return $response;
  3716. }
  3717. /**
  3718. * @Route("/companies/{company}/cotations/{cotationId}/notif-princing", name="companies_cotations_notif-princing")
  3719. */
  3720. public function companiesCotationsNotifPricingAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, int $cotationId, SendEmailService $sendEmailService)
  3721. {
  3722. $cotation = $em->getRepository(Cotation::class)->find($cotationId);
  3723. if (!$cotation) {
  3724. $cotation = $em->getRepository(CotationMultisite::class)->find($cotationId);
  3725. }
  3726. if (!$cotation) {
  3727. throw new RouteNotFoundException();
  3728. }
  3729. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3730. throw new NotFoundHttpException();
  3731. }
  3732. if (!$this->getUser()->getManager()->getAdmin()) {
  3733. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3734. throw new NotFoundHttpException();
  3735. }
  3736. }
  3737. $raisonSociale = $cotation->getCompanyName();
  3738. $siret = $cotation->getSiret();
  3739. $content = <<<EOD
  3740. Raison Sociale : $raisonSociale
  3741. <br/>
  3742. Siret : $siret
  3743. <br/>
  3744. EOD;
  3745. if ($cotation instanceof CotationMultisite) {
  3746. foreach ($cotation as $cotationItem) {
  3747. if ($cotation->getElectricity()) {
  3748. $fournisseurElec = $cotationItem->getElecDesiredSuppliersToString();
  3749. $debutFournitureElec = $cotationItem->getEDesiredBegin() ? $cotationItem->getEDesiredBegin()->format('d/m/Y') : '';
  3750. $finFournitureElec = $cotationItem->getEDesiredEnd() ? $cotationItem->getEDesiredEnd()->format('d/m/Y') : '';
  3751. $pdl = $cotationItem->getEPdl();
  3752. $content .= <<<EOD
  3753. Fournisseur(s) souhaité(s) ELEC : $fournisseurElec
  3754. <br/>
  3755. Début de fourniture ELEC : $debutFournitureElec
  3756. <br/>
  3757. Fin de fourniture ELEC : $finFournitureElec
  3758. <br/>
  3759. PDL : $pdl
  3760. <br/>
  3761. EOD;
  3762. }
  3763. if ($cotationItem->getGas()) {
  3764. $fournisseurGaz = $cotationItem->getGasDesiredSuppliersToString();
  3765. $debutFournitureGaz = $cotationItem->getGDesiredBegin() ? $cotationItem->getGDesiredBegin()->format('d/m/Y') : '';
  3766. $finFournitureGaz = $cotationItem->getGDesiredEnd() ? $cotationItem->getGDesiredEnd()->format('d/m/Y') : '';
  3767. $pce = $cotationItem->getGPce();
  3768. $content .= <<<EOD
  3769. Fournisseur(s) souhaité(s) GAZ : $fournisseurGaz
  3770. <br/>
  3771. Début de fourniture GAZ : $debutFournitureGaz
  3772. <br/>
  3773. Fin de fourniture GAZ : $finFournitureGaz
  3774. <br/>
  3775. PCE : $pce
  3776. <br/>
  3777. EOD;
  3778. }
  3779. }
  3780. } else {
  3781. if ($cotation->getElectricity()) {
  3782. $fournisseurElec = $cotation->getElecDesiredSuppliersToString();
  3783. $debutFournitureElec = $cotation->getEDesiredBegin() ? $cotation->getEDesiredBegin()->format('d/m/Y') : '';
  3784. $finFournitureElec = $cotation->getEDesiredEnd() ? $cotation->getEDesiredEnd()->format('d/m/Y') : '';
  3785. $pdl = $cotation->getEPdl();
  3786. $content .= <<<EOD
  3787. Fournisseur(s) souhaité(s) ELEC : $fournisseurElec
  3788. <br/>
  3789. Début de fourniture ELEC : $debutFournitureElec
  3790. <br/>
  3791. Fin de fourniture ELEC : $finFournitureElec
  3792. <br/>
  3793. PDL : $pdl
  3794. <br/>
  3795. EOD;
  3796. }
  3797. if ($cotation->getGas()) {
  3798. $fournisseurGaz = $cotation->getGasDesiredSuppliersToString();
  3799. $debutFournitureGaz = $cotation->getGDesiredBegin() ? $cotation->getGDesiredBegin()->format('d/m/Y') : '';
  3800. $finFournitureGaz = $cotation->getGDesiredEnd() ? $cotation->getGDesiredEnd()->format('d/m/Y') : '';
  3801. $pce = $cotation->getGPce();
  3802. $content .= <<<EOD
  3803. Fournisseur(s) souhaité(s) GAZ : $fournisseurGaz
  3804. <br/>
  3805. Début de fourniture GAZ : $debutFournitureGaz
  3806. <br/>
  3807. Fin de fourniture GAZ : $finFournitureGaz
  3808. <br/>
  3809. PCE : $pce
  3810. <br/>
  3811. EOD;
  3812. }
  3813. }
  3814. $dateEtHeureRdv = $cotation->getAppointmentDate() ? $cotation->getAppointmentDate()->format('d/m/Y H:i') : '';
  3815. $commercial = $cotation->getManager() ? $cotation->getManager()->getFirstName().' '.$cotation->getManager()->getLastName() : '';
  3816. $content .= <<<EOD
  3817. Date et heure de RDV : $dateEtHeureRdv
  3818. <br/>
  3819. Commercial : $commercial
  3820. <br/>
  3821. EOD;
  3822. $sendEmailService->send(
  3823. "Demande de cotation - ".$raisonSociale,
  3824. $this->getUser()->getManager()->getReferentPricing(),
  3825. 'emails/flash_default.html.twig',
  3826. [
  3827. "title" => "Demande de cotation - ".$raisonSociale,
  3828. "content" => $content
  3829. ]
  3830. );
  3831. $cotation->setPricingSentDate(new \DateTime('now'));
  3832. $em->flush();
  3833. $this->get('session')->getFlashBag()->add("success", "Notification envoyée à pricing");
  3834. return $this->redirectToRoute(($cotation instanceof CotationMultisite) ? "manager_companies_cotations-multisites_edit" : "manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  3835. }
  3836. /**
  3837. * @Route("/companies/{company}/cotations/{cotation}/turpe", name="companies_cotations_turpe")
  3838. */
  3839. public function companiesCotationsTurpeAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, TurpeCalculatorService $turpeCalculatorService)
  3840. {
  3841. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3842. throw new NotFoundHttpException();
  3843. }
  3844. if (!$this->getUser()->getManager()->getAdmin()) {
  3845. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3846. throw new NotFoundHttpException();
  3847. }
  3848. }
  3849. $isLongueUtilisation = false;
  3850. if ($request->get("isLongueUtilisation") && $request->get("isLongueUtilisation") == "true") {
  3851. $isLongueUtilisation = true;
  3852. }
  3853. $turpe = $turpeCalculatorService->calc($cotation, $isLongueUtilisation);
  3854. return new Response($turpe,200);
  3855. }
  3856. /**
  3857. * @Route("/companies/{company}/cotations/{cotation}/enedis-car", name="companies_cotations_enedis-car")
  3858. */
  3859. public function companiesCotationsEnedisCarAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
  3860. {
  3861. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3862. throw new NotFoundHttpException();
  3863. }
  3864. if (!$cotation->getEPdl()) {
  3865. return new JsonResponse([
  3866. "success" => false,
  3867. "message" => "PDL non renseigné pour cette cotation"
  3868. ]);
  3869. }
  3870. $data = $enedisService->getCar($cotation->getEPdl());
  3871. if ($data) {
  3872. return new JsonResponse([
  3873. "success" => true,
  3874. "data" => $data
  3875. ]);
  3876. } else {
  3877. return new JsonResponse([
  3878. "success" => false,
  3879. "message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
  3880. ]);
  3881. }
  3882. }
  3883. /**
  3884. * @Route("/companies/{company}/cotations/{cotation}/enedis-donnees-contractuelles", name="companies_cotations_enedis-donnees-contractuelles")
  3885. */
  3886. public function companiesCotationsEnedisDonneesContractuellesAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
  3887. {
  3888. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3889. throw new NotFoundHttpException();
  3890. }
  3891. if (!$cotation->getEPdl()) {
  3892. return new JsonResponse([
  3893. "success" => false,
  3894. "message" => "PDL non renseigné pour cette cotation"
  3895. ]);
  3896. }
  3897. $data = $enedisService->getDonneesContractuelles($cotation->getEPdl());
  3898. if ($data) {
  3899. return new JsonResponse([
  3900. "success" => true,
  3901. "data" => $data
  3902. ]);
  3903. } else {
  3904. return new JsonResponse([
  3905. "success" => false,
  3906. "message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
  3907. ]);
  3908. }
  3909. }
  3910. /**
  3911. * @Route("/companies/{company}/cotations/{cotation}/enedis-address", name="companies_cotations_enedis-address")
  3912. */
  3913. public function companiesCotationsEnedisAddressAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
  3914. {
  3915. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3916. throw new NotFoundHttpException();
  3917. }
  3918. if (!$cotation->getEPdl()) {
  3919. return new JsonResponse([
  3920. "success" => false,
  3921. "message" => "PDL non renseigné pour cette cotation"
  3922. ]);
  3923. }
  3924. $data = $enedisService->getDonneesContractuelles($cotation->getEPdl(), true);
  3925. if ($data) {
  3926. return new JsonResponse([
  3927. "success" => true,
  3928. "data" => $data
  3929. ]);
  3930. } else {
  3931. return new JsonResponse([
  3932. "success" => false,
  3933. "message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
  3934. ]);
  3935. }
  3936. }
  3937. /**
  3938. * @Route("/companies/{company}/cotations/{cotation}/enedis-depassements", name="companies_cotations_enedis-depassements")
  3939. */
  3940. public function companiesCotationsEnedisDepassementsAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
  3941. {
  3942. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3943. throw new NotFoundHttpException();
  3944. }
  3945. if (!$cotation->getEPdl()) {
  3946. return new JsonResponse([
  3947. "success" => false,
  3948. "message" => "PDL non renseigné pour cette cotation"
  3949. ]);
  3950. }
  3951. $data = $enedisService->getDonneesDepassements($cotation->getEPdl());
  3952. if ($data) {
  3953. return new JsonResponse([
  3954. "success" => true,
  3955. "data" => $data
  3956. ]);
  3957. } else {
  3958. return new JsonResponse([
  3959. "success" => false,
  3960. "message" => "Une erreur est survenue lors de la récupération des données de dépassements ENEDIS."
  3961. ]);
  3962. }
  3963. }
  3964. /**
  3965. * @Route("/companies/{company}/cotations/{cotation}/offers", name="companies_cotations_offers")
  3966. */
  3967. public function companiesCotationsOffersAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  3968. {
  3969. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3970. throw new NotFoundHttpException();
  3971. }
  3972. if (!$this->getUser()->getManager()->getAdmin()) {
  3973. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3974. throw new NotFoundHttpException();
  3975. }
  3976. }
  3977. $offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation], ["currentOffer" => "DESC"]);
  3978. $offersGas = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation], ["currentOffer" => "DESC"]);
  3979. return $this->render("app/clients/cotations_offers.html.twig", [
  3980. "offersElec" => $offersElec,
  3981. "offersGas" => $offersGas,
  3982. "company" => $company,
  3983. "cotation" => $cotation,
  3984. ]);
  3985. }
  3986. /**
  3987. * @Route("/companies/{company}/cotations/{cotation}/offers/pdf", name="companies_cotations_offers_pdf")
  3988. */
  3989. public function companiesCotationsOffersPdfAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, Pdf $knpSnappyPdf)
  3990. {
  3991. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  3992. throw new NotFoundHttpException();
  3993. }
  3994. if (!$this->getUser()->getManager()->getAdmin()) {
  3995. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  3996. throw new NotFoundHttpException();
  3997. }
  3998. }
  3999. $form = $this->createFormBuilder()->getForm();
  4000. if ($cotation->getElectricity()) {
  4001. $form->add("etude_solution_elec", ChoiceType::class, [
  4002. "expanded" => false,
  4003. "multiple" => false,
  4004. "choices" => [
  4005. "Prendre un prix unique composé de la totalité de ses droits d’ARENH" => "1",
  4006. "Prendre un prix unique composé d’un taux modéré de ses droits d'ARENH" => "2",
  4007. "Maintenir un prix unique composé d'un prix 100 % fixe" => "3",
  4008. "Prendre un horosaisonnalisé 100 % fixe (uniquement prix de marché)" => "4",
  4009. "Prendre un prix horosaisonnalisé composé d’un taux modéré de ses droits d'ARENH" => "5",
  4010. "Maintenir un prix horosaisonnalisé composé de la totalité de ses droits d’ARENH" => "6",
  4011. ],
  4012. "label" => "Choix de la solution ELEC",
  4013. ])
  4014. ->add("etude_commentaire_elec", TextType::class, [
  4015. "attr" => [
  4016. "placeholder" => ""
  4017. ],
  4018. "label" => "Commentaire ELEC",
  4019. "required" => false,
  4020. ]);
  4021. $form["etude_solution_elec"]->setData($cotation->getEtudeSolutionElec());
  4022. $form["etude_commentaire_elec"]->setData($cotation->getEtudeCommentaireElec());
  4023. }
  4024. if ($cotation->getGas()) {
  4025. $form->add("etude_solution_gaz", ChoiceType::class, [
  4026. "expanded" => false,
  4027. "multiple" => false,
  4028. "choices" => [
  4029. "Prendre un prix variable indexé sur le PEG" => "1",
  4030. "Maintenir un prix 100 % fixe" => "2",
  4031. ],
  4032. "label" => "Choix de la solution GAZ",
  4033. ])
  4034. ->add("etude_commentaire_gaz", TextType::class, [
  4035. "attr" => [
  4036. "placeholder" => ""
  4037. ],
  4038. "label" => "Commentaire GAZ",
  4039. "required" => false,
  4040. ]);
  4041. $form["etude_solution_gaz"]->setData($cotation->getEtudeSolutionGaz());
  4042. $form["etude_commentaire_gaz"]->setData($cotation->getEtudeCommentaireGaz());
  4043. }
  4044. $form->handleRequest($request);
  4045. if ($form->isSubmitted() && $form->isValid()) {
  4046. if ($cotation->getElectricity()) {
  4047. $cotation->setEtudeSolutionElec($form["etude_solution_elec"]->getData());
  4048. $cotation->setEtudeCommentaireElec($form["etude_commentaire_elec"]->getData());
  4049. }
  4050. if ($cotation->getGas()) {
  4051. $cotation->setEtudeSolutionGaz($form["etude_solution_gaz"]->getData());
  4052. $cotation->setEtudeCommentaireGaz($form["etude_commentaire_gaz"]->getData());
  4053. }
  4054. $em->flush();
  4055. $offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation, "displayed" => true], ["currentOffer" => "DESC"]);
  4056. $offersGas = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation, "displayed" => true], ["currentOffer" => "DESC"]);
  4057. $html = $this->renderView('app/pdf/presentation-budget/section1.html.twig', array(
  4058. "offersElec" => $offersElec,
  4059. "offersGas" => $offersGas,
  4060. 'cotation' => $cotation,
  4061. 'multisite' => false,
  4062. ));
  4063. $pdf = $knpSnappyPdf->getOutputFromHtml($html, array(
  4064. 'orientation' => 'landscape',
  4065. 'no-stop-slow-scripts' => true,
  4066. 'no-background' => false,
  4067. 'lowquality' => false,
  4068. 'page-height' => 340,
  4069. 'page-width' => 200,
  4070. 'encoding' => 'utf-8',
  4071. 'images' => true,
  4072. 'cookie' => array(),
  4073. 'dpi' => 300,
  4074. 'enable-external-links' => true,
  4075. 'enable-internal-links' => true,
  4076. 'margin-bottom' => 0
  4077. ));
  4078. return new Response($pdf,200,array(
  4079. 'Content-Type' => 'application/pdf',
  4080. 'Content-Disposition' => 'inline; filename="Flash-Presentation_budget.pdf"'
  4081. ));
  4082. /*
  4083. return new PdfResponse(
  4084. $knpSnappyPdf->getOutputFromHtml($html),
  4085. 'Flash-Presentation_budget.pdf'
  4086. );
  4087. */
  4088. }
  4089. return $this->render("app/clients/cotation_offers_pdf.html.twig", [
  4090. "form" => $form->createView(),
  4091. "cotation" => $cotation,
  4092. "multisite" => false,
  4093. ]);
  4094. }
  4095. /**
  4096. * @Route("/companies/{company}/cotations/{cotation}/offers/add", name="companies_cotations_offers_add")
  4097. */
  4098. public function companiesCotationsOffersAddAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
  4099. {
  4100. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4101. throw new NotFoundHttpException();
  4102. }
  4103. if (!$this->getUser()->getManager()->getAdmin()) {
  4104. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4105. throw new NotFoundHttpException();
  4106. }
  4107. }
  4108. if ($request->get("elec")) {
  4109. if (!$cotation->getElectricity() || $cotation->getSelectedOfferElec() != null) {
  4110. throw new BadRequestHttpException();
  4111. }
  4112. $offer = new OfferElec();
  4113. if ($cotation->getCotationMultisite() && $request->get("duplicate")) {
  4114. $duplicateOffer = $em->getRepository(OfferElec::class)->find($request->get("duplicate"));
  4115. if ($duplicateOffer && $cotation->getCotationMultisite() === $duplicateOffer->getCotation()->getCotationMultisite()) {
  4116. $offer = clone $duplicateOffer;
  4117. }
  4118. }
  4119. $offer->setCotation($cotation);
  4120. $form = $this->createForm(OfferElecType::class, $offer);
  4121. $title = "Ajouter une offre Electricité";
  4122. $type = "elec";
  4123. } else {
  4124. if (!$cotation->getGas() || $cotation->getSelectedOfferGaz() != null) {
  4125. throw new BadRequestHttpException();
  4126. }
  4127. $offer = new OfferGaz();
  4128. if ($cotation->getCotationMultisite() && $request->get("duplicate")) {
  4129. $duplicateOffer = $em->getRepository(OfferGaz::class)->find($request->get("duplicate"));
  4130. if ($duplicateOffer && $cotation->getCotationMultisite() === $duplicateOffer->getCotation()->getCotationMultisite()) {
  4131. $offer = clone $duplicateOffer;
  4132. }
  4133. }
  4134. $offer->setCotation($cotation);
  4135. $form = $this->createForm(OfferGazType::class, $offer);
  4136. $title = "Ajouter une offre Gaz";
  4137. $type = "gas";
  4138. }
  4139. $form->handleRequest($request);
  4140. if ($form->isSubmitted() && !$form->isValid()) {
  4141. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  4142. }
  4143. if ($form->isSubmitted() && $form->isValid()) {
  4144. $em->persist($offer);
  4145. $em->flush();
  4146. $file = $form['file']->getData();
  4147. if ($file) {
  4148. $extension = $file->guessExtension();
  4149. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  4150. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  4151. } else {
  4152. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4153. $file->move(
  4154. $this->getParameter('documents_offers_directory'),
  4155. $fileName
  4156. );
  4157. $offer->setFile($fileName);
  4158. $em->flush();
  4159. }
  4160. }
  4161. $this->get("session")->getFlashBag()->add("success", "Offre fournisseur ajoutée");
  4162. if ($cotation->getCotationMultisite()) {
  4163. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4164. } else {
  4165. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4166. }
  4167. }
  4168. return $this->render("app/clients/cotation_offer_form.html.twig", [
  4169. "form" => $form->createView(),
  4170. "offer" => $offer,
  4171. "title" => $title,
  4172. "type" => $type,
  4173. ]);
  4174. }
  4175. /**
  4176. * @Route("/companies/{company}/cotations/{cotation}/offers/add-file", name="companies_cotations_offers_add-file")
  4177. */
  4178. public function companiesCotationsOffersAddFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, DocusignService $docusignService)
  4179. {
  4180. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4181. throw new NotFoundHttpException();
  4182. }
  4183. if (!$this->getUser()->getManager()->getAdmin()) {
  4184. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4185. throw new NotFoundHttpException();
  4186. }
  4187. }
  4188. $form = $this->createFormBuilder()
  4189. ->add('supplier', EntityType::class, [
  4190. "class" => Supplier::class,
  4191. "label" => "Fournisseur de l'offre",
  4192. "placeholder" => "Fournisseur de l'offre",
  4193. "required" => true,
  4194. 'query_builder' => function (EntityRepository $er) {
  4195. $qb = $er->createQueryBuilder('s');
  4196. $qb->where('s.active = true');
  4197. return $qb;
  4198. },
  4199. ])
  4200. ->add('file', FileType::class, [
  4201. 'attr' => [
  4202. 'accept' => '.pdf, .doc, .docx',
  4203. 'placeholder' => 'Importer l\'offre ou le contrat'
  4204. ],
  4205. 'label' => 'Document',
  4206. 'required' => false,
  4207. 'mapped' => false,
  4208. ])->getForm();
  4209. $signatureAvailable = true;
  4210. if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
  4211. $signatureAvailable = false;
  4212. }
  4213. if ($signatureAvailable) {
  4214. $form->add('enableDocusign', CheckboxType::class, [
  4215. "label" => "Envoyer la signature électronique de l'offre",
  4216. "required" => false,
  4217. "mapped" => false,
  4218. ]);
  4219. } else {
  4220. $form->add('enableDocusign', CheckboxType::class, [
  4221. "label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
  4222. "data" => true,
  4223. "disabled" => true,
  4224. "required" => false,
  4225. "mapped" => false,
  4226. ]);
  4227. }
  4228. if ($request->get("elec")) {
  4229. if (!$cotation->getElectricity() || $cotation->getSelectedOfferElec() != null) {
  4230. throw new BadRequestHttpException();
  4231. }
  4232. $offer = new OfferElec();
  4233. $offer->setCotation($cotation);
  4234. $title = "Ajouter le contrat Electricité";
  4235. $type = "elec";
  4236. } else {
  4237. if (!$cotation->getGas() || $cotation->getSelectedOfferGaz() != null) {
  4238. throw new BadRequestHttpException();
  4239. }
  4240. $offer = new OfferGaz();
  4241. $offer->setCotation($cotation);
  4242. $title = "Ajouter le contrat Gaz";
  4243. $type = "gas";
  4244. }
  4245. $form->handleRequest($request);
  4246. if ($form->isSubmitted() && !$form->isValid()) {
  4247. $this->get('session')->getFlashBag()->add('danger', 'Veuillez indiquer un fichier valide. Les extensions autorisées sont .pdf, .doc, .docx');
  4248. }
  4249. if ($form->isSubmitted() && $form->isValid()) {
  4250. $supplier = $form['supplier']->getData();
  4251. $offer->setSupplier($supplier);
  4252. $file = $form['file']->getData();
  4253. if ($file) {
  4254. $extension = $file->guessExtension();
  4255. if ($extension && in_array($extension, ["pdf", "doc", "docx"])) {
  4256. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4257. $file->move(
  4258. $this->getParameter('documents_offers_directory'),
  4259. $fileName
  4260. );
  4261. $offer->setFile($fileName);
  4262. $em->persist($offer);
  4263. $em->flush();
  4264. // Signature électronique de l'offre
  4265. if ($form->get('enableDocusign')->getData()) {
  4266. $filePath = $this->getParameter('documents_offers_directory').$fileName;
  4267. // Création de la procédure
  4268. $procedureSign = new ProcedureSign();
  4269. $procedureSign->setUser($company->getUser());
  4270. $procedureSign->setFirstName($cotation->getFirstName());
  4271. $procedureSign->setLastName($cotation->getLastName());
  4272. $procedureSign->setEmail($cotation->getEmail());
  4273. $procedureSign->setPhone($cotation->getPhone());
  4274. $procedureSign->setCreationDate(new \DateTime('now'));
  4275. $procedureSign->setNameFile($fileName);
  4276. $procedureSign->setFilePath($filePath);
  4277. $content = [
  4278. "type" => "cotation.offer",
  4279. "nrj" => $request->get("elec") ? "elec" : "gaz",
  4280. "id" => $offer->getId()
  4281. ];
  4282. $procedureSign->setContent(json_encode($content));
  4283. $em->persist($procedureSign);
  4284. $em->flush();
  4285. /*$fileCertificate = $this->getParameter('documents_fc_certificate');
  4286. if (file_exists($fileCertificate)) {
  4287. $pdf = new FPDI();
  4288. $pagecount = $pdf->setSourceFile($filePath);
  4289. for($i=0; $i<$pagecount; $i++){
  4290. $pdf->AddPage();
  4291. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  4292. $pdf->useTemplate($tplidx);
  4293. }
  4294. // add certificate
  4295. $pagecount = $pdf->setSourceFile($fileCertificate);
  4296. for($i=0; $i<$pagecount; $i++){
  4297. $pdf->AddPage();
  4298. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  4299. $pdf->useTemplate($tplidx);
  4300. }
  4301. $pdf->Output($filePath, 'F');
  4302. }*/
  4303. // Lancement de la signature
  4304. $accessToken = $docusignService->getAccessToken();
  4305. if ($accessToken) {
  4306. try {
  4307. $response = $docusignService->sendFile($accessToken, $procedureSign);
  4308. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  4309. $em->flush();
  4310. $this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté. Le mail pour la signature électronique de l'offre a été envoyé au client.");
  4311. } catch (ApiException $e) {
  4312. $this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté.");
  4313. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  4314. }
  4315. } else {
  4316. $this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté.");
  4317. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  4318. }
  4319. } else {
  4320. $this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté. Vous devez l'envoyer pour signature au client.");
  4321. }
  4322. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4323. } else {
  4324. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  4325. }
  4326. } else {
  4327. $this->get("session")->getFlashBag()->add("danger", "Fichier introuvable ou incorrect.");
  4328. }
  4329. }
  4330. return $this->render("app/clients/cotation_offer_contract_form.html.twig", [
  4331. "form" => $form->createView(),
  4332. "offer" => $offer,
  4333. "title" => $title,
  4334. "type" => $type,
  4335. ]);
  4336. }
  4337. /**
  4338. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/preselect", name="companies_cotations_offers_elec_preselect")
  4339. */
  4340. public function companiesCotationsOffersElecPreselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4341. {
  4342. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4343. throw new NotFoundHttpException();
  4344. }
  4345. if (!$this->getUser()->getManager()->getAdmin()) {
  4346. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4347. throw new NotFoundHttpException();
  4348. }
  4349. }
  4350. if ($offer->getCotation()->getId() != $cotation->getId()) {
  4351. throw new NotFoundHttpException();
  4352. }
  4353. if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
  4354. throw new BadRequestHttpException();
  4355. }
  4356. $cotation->setPreselectedOfferElec($offer);
  4357. $em->flush();
  4358. $this->get("session")->getFlashBag()->add("success", "Offre éléctricité présélectionnée.");
  4359. if ($cotation->getCotationMultisite()) {
  4360. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4361. } else {
  4362. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4363. }
  4364. }
  4365. /**
  4366. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/deselect", name="companies_cotations_offers_elec_deselect")
  4367. */
  4368. public function companiesCotationsOffersElecDeselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4369. {
  4370. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4371. throw new NotFoundHttpException();
  4372. }
  4373. if (!$this->getUser()->getManager()->getAdmin()) {
  4374. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4375. throw new NotFoundHttpException();
  4376. }
  4377. }
  4378. $cotation->setPreselectedOfferElec(null);
  4379. $em->flush();
  4380. $this->get("session")->getFlashBag()->add("success", "Offre éléctricité désélectionnée.");
  4381. if ($cotation->getCotationMultisite()) {
  4382. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4383. } else {
  4384. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4385. }
  4386. }
  4387. /**
  4388. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/choose", name="companies_cotations_offers_elec_choose")
  4389. */
  4390. public function companiesCotationsOffersElecChooseAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4391. {
  4392. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4393. throw new NotFoundHttpException();
  4394. }
  4395. if (!$this->getUser()->getManager()->getAdmin()) {
  4396. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4397. throw new NotFoundHttpException();
  4398. }
  4399. }
  4400. if ($offer->getCotation()->getId() != $cotation->getId()) {
  4401. throw new NotFoundHttpException();
  4402. }
  4403. if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
  4404. throw new BadRequestHttpException();
  4405. }
  4406. $cotation->setSelectedOfferElec($offer);
  4407. $em->flush();
  4408. // Mise à jour du state
  4409. if (
  4410. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
  4411. &&
  4412. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
  4413. ) {
  4414. $stateTerminee = $em->getRepository(CotationState::class)->find(6);
  4415. $cotation->setState($stateTerminee);
  4416. $em->flush();
  4417. }
  4418. // Edition du contrat
  4419. $contract = new Contract();
  4420. $contract->setUser($cotation->getUser());
  4421. $contract->setCompany($cotation->getCompany());
  4422. $contract->setElectricity(true);
  4423. $contract->setElectricitySituation($cotation->getElectricitySituation());
  4424. $contract->setSupplier($offer->getSupplier());
  4425. $contract->setAddress($cotation->getAddress());
  4426. $contract->setAddress2($cotation->getAddress2());
  4427. $contract->setZipCode($cotation->getZipCode());
  4428. $contract->setCity($cotation->getCity());
  4429. $contract->setPdlNumber($cotation->getEPdl());
  4430. $contract->setOfferElec($offer);
  4431. $contract->setSepaIban($cotation->getSepaIban());
  4432. $contract->setSepaBic($cotation->getSepaBic());
  4433. $contract->setManager($cotation->getManager());
  4434. $contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
  4435. $contract->setState($contratStateEnAttenteClient);
  4436. if ($offer->getFile()) {
  4437. $filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
  4438. copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
  4439. $contract->setFile($offer->getFile());
  4440. }
  4441. $em->persist($contract);
  4442. $em->flush();
  4443. $this->get("session")->getFlashBag()->add("success", "Offre éléctricité sélectionnée. Le contrat a été édité.");
  4444. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  4445. }
  4446. /**
  4447. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/preselect", name="companies_cotations_offers_gas_preselect")
  4448. */
  4449. public function companiesCotationsOffersGasPreselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4450. {
  4451. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4452. throw new NotFoundHttpException();
  4453. }
  4454. if (!$this->getUser()->getManager()->getAdmin()) {
  4455. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4456. throw new NotFoundHttpException();
  4457. }
  4458. }
  4459. if ($offer->getCotation()->getId() != $cotation->getId()) {
  4460. throw new NotFoundHttpException();
  4461. }
  4462. if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
  4463. throw new BadRequestHttpException();
  4464. }
  4465. $cotation->setPreselectedOfferGaz($offer);
  4466. $em->flush();
  4467. $this->get("session")->getFlashBag()->add("success", "Offre gaz présélectionnée.");
  4468. if ($cotation->getCotationMultisite()) {
  4469. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4470. } else {
  4471. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4472. }
  4473. }
  4474. /**
  4475. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/deselect", name="companies_cotations_offers_gas_deselect")
  4476. */
  4477. public function companiesCotationsOffersGasDeselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4478. {
  4479. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4480. throw new NotFoundHttpException();
  4481. }
  4482. if (!$this->getUser()->getManager()->getAdmin()) {
  4483. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4484. throw new NotFoundHttpException();
  4485. }
  4486. }
  4487. $cotation->setPreselectedOfferGaz(null);
  4488. $em->flush();
  4489. $this->get("session")->getFlashBag()->add("success", "Offre gaz désélectionnée.");
  4490. if ($cotation->getCotationMultisite()) {
  4491. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4492. } else {
  4493. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4494. }
  4495. }
  4496. /**
  4497. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/choose", name="companies_cotations_offers_gas_choose")
  4498. */
  4499. public function companiesCotationsOffersGasChooseAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4500. {
  4501. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4502. throw new NotFoundHttpException();
  4503. }
  4504. if (!$this->getUser()->getManager()->getAdmin()) {
  4505. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4506. throw new NotFoundHttpException();
  4507. }
  4508. }
  4509. if ($offer->getCotation()->getId() != $cotation->getId()) {
  4510. throw new NotFoundHttpException();
  4511. }
  4512. if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
  4513. throw new BadRequestHttpException();
  4514. }
  4515. $cotation->setSelectedOfferGaz($offer);
  4516. $em->flush();
  4517. // Mise à jour du state
  4518. if (
  4519. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
  4520. &&
  4521. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
  4522. ) {
  4523. $stateTerminee = $em->getRepository(CotationState::class)->find(6);
  4524. $cotation->setState($stateTerminee);
  4525. $em->flush();
  4526. }
  4527. // Edition du contrat
  4528. $contract = new Contract();
  4529. $contract->setUser($cotation->getUser());
  4530. $contract->setCompany($cotation->getCompany());
  4531. $contract->setGas(true);
  4532. $contract->setGasSituation($cotation->getElectricitySituation());
  4533. $contract->setSupplier($offer->getSupplier());
  4534. $contract->setAddress($cotation->getAddress());
  4535. $contract->setAddress2($cotation->getAddress2());
  4536. $contract->setZipCode($cotation->getZipCode());
  4537. $contract->setCity($cotation->getCity());
  4538. $contract->setPceNumber($cotation->getGPce());
  4539. $contract->setOfferGaz($offer);
  4540. $contract->setManager($cotation->getManager());
  4541. $contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
  4542. $contract->setState($contratStateEnAttenteClient);
  4543. if ($offer->getFile()) {
  4544. $filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
  4545. copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
  4546. $contract->setFile($offer->getFile());
  4547. }
  4548. $em->persist($contract);
  4549. $em->flush();
  4550. $this->get("session")->getFlashBag()->add("success", "Offre gaz sélectionnée. Le contrat a été édité.");
  4551. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  4552. }
  4553. /**
  4554. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/edit", name="companies_cotations_offers_elec_edit")
  4555. */
  4556. public function companiesCotationsOffersElecEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4557. {
  4558. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4559. throw new NotFoundHttpException();
  4560. }
  4561. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4562. throw new NotFoundHttpException();
  4563. }
  4564. if (!$this->getUser()->getManager()->getAdmin()) {
  4565. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4566. throw new NotFoundHttpException();
  4567. }
  4568. }
  4569. $form = $this->createForm(OfferElecType::class, $offer);
  4570. $form->handleRequest($request);
  4571. if ($form->isSubmitted() && !$form->isValid()) {
  4572. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  4573. }
  4574. if ($form->isSubmitted() && $form->isValid()) {
  4575. $em->flush();
  4576. $file = $form['file']->getData();
  4577. if ($file) {
  4578. $extension = $file->guessExtension();
  4579. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  4580. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  4581. } else {
  4582. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4583. $file->move(
  4584. $this->getParameter('documents_offers_directory'),
  4585. $fileName
  4586. );
  4587. $offer->setFile($fileName);
  4588. $em->flush();
  4589. }
  4590. }
  4591. $this->get("session")->getFlashBag()->add("success", "Offre fournisseur mise à jour");
  4592. if ($cotation->getCotationMultisite()) {
  4593. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4594. } else {
  4595. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4596. }
  4597. }
  4598. return $this->render("app/clients/cotation_offer_form.html.twig", [
  4599. "form" => $form->createView(),
  4600. "offer" => $offer,
  4601. "title" => "Modifier une offre Electricité",
  4602. "type" => "elec",
  4603. ]);
  4604. }
  4605. /**
  4606. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/edit", name="companies_cotations_offers_gas_edit")
  4607. */
  4608. public function companiesCotationsOffersGasEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4609. {
  4610. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4611. throw new NotFoundHttpException();
  4612. }
  4613. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4614. throw new NotFoundHttpException();
  4615. }
  4616. if (!$this->getUser()->getManager()->getAdmin()) {
  4617. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4618. throw new NotFoundHttpException();
  4619. }
  4620. }
  4621. $form = $this->createForm(OfferGazType::class, $offer);
  4622. $form->handleRequest($request);
  4623. if ($form->isSubmitted() && !$form->isValid()) {
  4624. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  4625. }
  4626. if ($form->isSubmitted() && $form->isValid()) {
  4627. $em->flush();
  4628. $file = $form['file']->getData();
  4629. if ($file) {
  4630. $extension = $file->guessExtension();
  4631. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  4632. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  4633. } else {
  4634. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4635. $file->move(
  4636. $this->getParameter('documents_offers_directory'),
  4637. $fileName
  4638. );
  4639. $offer->setFile($fileName);
  4640. $em->flush();
  4641. }
  4642. }
  4643. $this->get("session")->getFlashBag()->add("success", "Offre fournisseur mise à jour");
  4644. if ($cotation->getCotationMultisite()) {
  4645. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4646. } else {
  4647. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4648. }
  4649. }
  4650. return $this->render("app/clients/cotation_offer_form.html.twig", [
  4651. "form" => $form->createView(),
  4652. "offer" => $offer,
  4653. "title" => "Modifier une offre Gaz",
  4654. "type" => "gas",
  4655. ]);
  4656. }
  4657. /**
  4658. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/file", name="companies_cotations_offers_elec_file")
  4659. */
  4660. public function companiesCotationsOffersElecFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4661. {
  4662. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4663. throw new NotFoundHttpException();
  4664. }
  4665. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4666. throw new NotFoundHttpException();
  4667. }
  4668. if (!$this->getUser()->getManager()->getAdmin()) {
  4669. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4670. throw new NotFoundHttpException();
  4671. }
  4672. }
  4673. if ($offer->getFile()) {
  4674. $filePath = $this->getParameter('documents_offers_directory') . $offer->getFile();
  4675. return $this->file($filePath, $offer->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  4676. }
  4677. throw new NotFoundHttpException();
  4678. }
  4679. /**
  4680. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/file-delete", name="companies_cotations_offers_elec_file-delete")
  4681. */
  4682. public function companiesCotationsOffersElecFileDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4683. {
  4684. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4685. throw new NotFoundHttpException();
  4686. }
  4687. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4688. throw new NotFoundHttpException();
  4689. }
  4690. if (!$this->getUser()->getManager()->getAdmin()) {
  4691. throw new NotFoundHttpException();
  4692. }
  4693. $offer->setFile(null);
  4694. $em->flush();
  4695. return $this->redirectToRoute("manager_companies_cotations_offers_elec_edit", ["company" => $company->getId(), "cotation" => $cotation->getId(), "offer" => $offer->getId()]);
  4696. }
  4697. /**
  4698. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/hide", name="companies_cotations_offers_elec_hide")
  4699. */
  4700. public function companiesCotationsOffersElecHideAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4701. {
  4702. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4703. throw new NotFoundHttpException();
  4704. }
  4705. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4706. throw new NotFoundHttpException();
  4707. }
  4708. if (!$this->getUser()->getManager()->getAdmin()) {
  4709. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4710. throw new NotFoundHttpException();
  4711. }
  4712. }
  4713. $offer->setDisplayed(false);
  4714. $em->flush();
  4715. $this->get("session")->getFlashBag()->add("success", "Offre masquée");
  4716. if ($cotation->getCotationMultisite()) {
  4717. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4718. } else {
  4719. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4720. }
  4721. }
  4722. /**
  4723. * @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/display", name="companies_cotations_offers_elec_display")
  4724. */
  4725. public function companiesCotationsOffersElecDisplayAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
  4726. {
  4727. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4728. throw new NotFoundHttpException();
  4729. }
  4730. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4731. throw new NotFoundHttpException();
  4732. }
  4733. if (!$this->getUser()->getManager()->getAdmin()) {
  4734. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4735. throw new NotFoundHttpException();
  4736. }
  4737. }
  4738. $offer->setDisplayed(true);
  4739. $em->flush();
  4740. $this->get("session")->getFlashBag()->add("success", "Offre démasquée");
  4741. if ($cotation->getCotationMultisite()) {
  4742. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4743. } else {
  4744. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4745. }
  4746. }
  4747. /**
  4748. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/file", name="companies_cotations_offers_gas_file")
  4749. */
  4750. public function companiesCotationsOffersGasFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4751. {
  4752. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4753. throw new NotFoundHttpException();
  4754. }
  4755. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4756. throw new NotFoundHttpException();
  4757. }
  4758. if (!$this->getUser()->getManager()->getAdmin()) {
  4759. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4760. throw new NotFoundHttpException();
  4761. }
  4762. }
  4763. if ($offer->getFile()) {
  4764. $filePath = $this->getParameter('documents_offers_directory') . $offer->getFile();
  4765. return $this->file($filePath, $offer->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  4766. }
  4767. throw new NotFoundHttpException();
  4768. }
  4769. /**
  4770. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/file-delete", name="companies_cotations_offers_gas_file-delete")
  4771. */
  4772. public function companiesCotationsOffersGasFileDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4773. {
  4774. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4775. throw new NotFoundHttpException();
  4776. }
  4777. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4778. throw new NotFoundHttpException();
  4779. }
  4780. if (!$this->getUser()->getManager()->getAdmin()) {
  4781. throw new NotFoundHttpException();
  4782. }
  4783. $offer->setFile(null);
  4784. $em->flush();
  4785. return $this->redirectToRoute("manager_companies_cotations_offers_elec_edit", ["company" => $company->getId(), "cotation" => $cotation->getId(), "offer" => $offer->getId()]);
  4786. }
  4787. /**
  4788. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/hide", name="companies_cotations_offers_gas_hide")
  4789. */
  4790. public function companiesCotationsOffersGasHideAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4791. {
  4792. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4793. throw new NotFoundHttpException();
  4794. }
  4795. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4796. throw new NotFoundHttpException();
  4797. }
  4798. if (!$this->getUser()->getManager()->getAdmin()) {
  4799. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4800. throw new NotFoundHttpException();
  4801. }
  4802. }
  4803. $offer->setDisplayed(false);
  4804. $em->flush();
  4805. $this->get("session")->getFlashBag()->add("success", "Offre masquée");
  4806. if ($cotation->getCotationMultisite()) {
  4807. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4808. } else {
  4809. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4810. }
  4811. }
  4812. /**
  4813. * @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/display", name="companies_cotations_offers_gas_display")
  4814. */
  4815. public function companiesCotationsOffersGasDisplayAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
  4816. {
  4817. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4818. throw new NotFoundHttpException();
  4819. }
  4820. if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
  4821. throw new NotFoundHttpException();
  4822. }
  4823. if (!$this->getUser()->getManager()->getAdmin()) {
  4824. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4825. throw new NotFoundHttpException();
  4826. }
  4827. }
  4828. $offer->setDisplayed(true);
  4829. $em->flush();
  4830. $this->get("session")->getFlashBag()->add("success", "Offre démasquée");
  4831. if ($cotation->getCotationMultisite()) {
  4832. return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
  4833. } else {
  4834. return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4835. }
  4836. }
  4837. /**
  4838. * @Route("/companies/{company}/cotations-multisites/add", name="companies_cotations-multisites_add")
  4839. */
  4840. public function companiesCotationsMultisitesAddAction(Request $request, EntityManagerInterface $em, Company $company)
  4841. {
  4842. if (!$this->getUser()->getManager()->getAdmin()) {
  4843. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4844. throw new NotFoundHttpException();
  4845. }
  4846. }
  4847. $cotation = new CotationMultisite();
  4848. $cotation->setCompany($company);
  4849. $cotation->setManager($this->getUser()->getManager());
  4850. $cotation->setSiret($company->getSiret());
  4851. $cotation->setCompanyName($company->getName());
  4852. $cotation->setFirstName($company->getUser()->getFirstName());
  4853. $cotation->setLastName($company->getUser()->getLastName());
  4854. $cotation->setPosition($company->getUser()->getPosition());
  4855. $cotation->setPhone($company->getPhone());
  4856. $cotation->setEmail($company->getEmail());
  4857. $cotation->setApeCode($company->getApeCode());
  4858. $cotation->setSector($company->getSector());
  4859. $form = $this->createForm(CotationMultisiteType::class, $cotation);
  4860. $form->add('type', ChoiceType::class, [
  4861. "label" => "Type d'énergie",
  4862. "choices" => [
  4863. "Elec" => "Elec",
  4864. "Gaz" => "Gaz",
  4865. ],
  4866. "required" => true,
  4867. "mapped" => false,
  4868. ]);
  4869. $form->handleRequest($request);
  4870. if ($form->isSubmitted() && !$form->isValid()) {
  4871. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  4872. }
  4873. if ($form->isSubmitted() && $form->isValid()) {
  4874. $state = $em->getRepository(CotationState::class)->find(1);
  4875. $cotation->setState($state);
  4876. $cotation->setCreationDate(new \DateTime("now"));
  4877. $type = $form->get('type')->getData();
  4878. if ($type == "Elec") {
  4879. $cotation->setElectricity(true);
  4880. }
  4881. if ($type == "Gaz") {
  4882. $cotation->setGas(true);
  4883. }
  4884. $em->persist($cotation);
  4885. $em->flush();
  4886. return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  4887. }
  4888. return $this->render("app/clients/cotation-multisite_form.html.twig", [
  4889. "form" => $form->createView(),
  4890. "cotation" => $cotation,
  4891. ]);
  4892. }
  4893. /**
  4894. * @Route("/companies/{company}/cotations-multisites/{cotation}/edit", name="companies_cotations-multisites_edit")
  4895. */
  4896. public function companiesCotationsMultisitesEditAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, DocusignService $docusignService)
  4897. {
  4898. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  4899. throw new NotFoundHttpException();
  4900. }
  4901. if (!$this->getUser()->getManager()->getAdmin()) {
  4902. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  4903. throw new NotFoundHttpException();
  4904. }
  4905. }
  4906. $form = $this->createForm(CotationMultisiteType::class, $cotation);
  4907. $signatureAvailable = true;
  4908. if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
  4909. $signatureAvailable = false;
  4910. }
  4911. if ($signatureAvailable) {
  4912. $form->add('enableDocusign', CheckboxType::class, [
  4913. "label" => "Envoyer la signature électronique de l'ACD",
  4914. "required" => false,
  4915. "mapped" => false,
  4916. ]);
  4917. } else {
  4918. $form->add('enableDocusign', CheckboxType::class, [
  4919. "label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
  4920. "data" => true,
  4921. "disabled" => true,
  4922. "required" => false,
  4923. "mapped" => false,
  4924. ]);
  4925. }
  4926. if ($cotation->getCompany()->getValidated()) {
  4927. $form->add('acdFileUpload', FileType::class, [
  4928. 'attr' => [
  4929. 'placeholder' => 'Importer le fichier ACD'
  4930. ],
  4931. 'label' => 'Importer le fichier ACD',
  4932. 'required' => false,
  4933. 'mapped' => false
  4934. ]);
  4935. }
  4936. $form->handleRequest($request);
  4937. if ($form->isSubmitted() && !$form->isValid()) {
  4938. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  4939. }
  4940. if ($form->isSubmitted() && $form->isValid()) {
  4941. $cotation->setEditDate(new \DateTime("now"));
  4942. $em->flush();
  4943. if ($form->get('oldInvoice')->getData()) {
  4944. $fileOldInvoice = $form->get('oldInvoice')->getData();
  4945. if ($fileOldInvoice != NULL) {
  4946. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
  4947. $fileOldInvoice->move(
  4948. $this->getParameter('documents_justificatif_directory'),
  4949. $fileName
  4950. );
  4951. $cotation->setOldInvoice($fileName);
  4952. }
  4953. }
  4954. $cotationSites = $form['cotations']->getData();
  4955. foreach ($cotationSites as $key => $cotationSite) {
  4956. $cotationSite->setManager($cotation->getManager());
  4957. $cotationSite->setCompany($cotation->getCompany());
  4958. $fileFactElec = $form['cotations'][$key]["factElec"]->getData();
  4959. if ($fileFactElec) {
  4960. $extension = $fileFactElec->guessExtension();
  4961. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  4962. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
  4963. } else {
  4964. $fileName = $cotation->getId() . "_" . $cotationSite->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4965. $fileFactElec->move(
  4966. $this->getParameter('documents_justificatif_directory'),
  4967. $fileName
  4968. );
  4969. $cotationSite->setFactElec($fileName);
  4970. $em->flush();
  4971. }
  4972. }
  4973. $fileFactGas = $form['cotations'][$key]["factGas"]->getData();
  4974. if ($fileFactGas) {
  4975. $extension = $fileFactGas->guessExtension();
  4976. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  4977. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
  4978. } else {
  4979. $fileName = $cotation->getId() . "_" . $cotationSite->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4980. $fileFactGas->move(
  4981. $this->getParameter('documents_justificatif_directory'),
  4982. $fileName
  4983. );
  4984. $cotationSite->setFactGas($fileName);
  4985. $em->flush();
  4986. }
  4987. }
  4988. }
  4989. $fileLiaseFiscale = $form['liasseFiscale']->getData();
  4990. if ($fileLiaseFiscale) {
  4991. $extension = $fileLiaseFiscale->guessExtension();
  4992. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  4993. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
  4994. } else {
  4995. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  4996. $fileLiaseFiscale->move(
  4997. $this->getParameter('documents_justificatif_directory'),
  4998. $fileName
  4999. );
  5000. $cotation->setLiasseFiscale($fileName);
  5001. $em->flush();
  5002. }
  5003. }
  5004. $fileSgeElec = $form['sgeElec']->getData();
  5005. if ($fileSgeElec) {
  5006. $extension = $fileSgeElec->guessExtension();
  5007. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  5008. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
  5009. } else {
  5010. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5011. $fileSgeElec->move(
  5012. $this->getParameter('documents_justificatif_directory'),
  5013. $fileName
  5014. );
  5015. $cotation->setSgeElec($fileName);
  5016. $em->flush();
  5017. }
  5018. }
  5019. $fileOmegaGas = $form['omegaGas']->getData();
  5020. if ($fileOmegaGas) {
  5021. $extension = $fileOmegaGas->guessExtension();
  5022. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
  5023. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
  5024. } else {
  5025. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5026. $fileOmegaGas->move(
  5027. $this->getParameter('documents_justificatif_directory'),
  5028. $fileName
  5029. );
  5030. $cotation->setOmegaGas($fileName);
  5031. $em->flush();
  5032. }
  5033. }
  5034. if ($form->has('acdFileUpload')) {
  5035. $fileAcd = $form->get('acdFileUpload')->getData();
  5036. if ($fileAcd != NULL) {
  5037. $fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileAcd->guessExtension();
  5038. $fileAcd->move(
  5039. $this->getParameter('documents_acd_directory'),
  5040. $fileName
  5041. );
  5042. $cotation->setAcdFile($fileName);
  5043. $cotation->setAcdSignDate(new \DateTime('now'));
  5044. $em->flush();
  5045. }
  5046. }
  5047. // Signature électronique de l'ACD
  5048. if ($form->has('enableDocusign') && $form->get('enableDocusign')->getData()) {
  5049. // Lancement de la signature
  5050. $startSign = null;
  5051. if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
  5052. $startSign = $this::sendAcdMultisiteToDocusign($cotation, $company, $docusignService, $em);
  5053. } else {
  5054. $this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
  5055. }
  5056. if (!$startSign) {
  5057. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  5058. } else {
  5059. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
  5060. }
  5061. }
  5062. // Cotation status
  5063. if ($cotation->getState()->getId() != 5) {
  5064. if (
  5065. (!$cotation->getGas() || ($cotation->getGas() && $cotation->getOmegaGas()))
  5066. &&
  5067. (!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSgeElec()))
  5068. ) {
  5069. $newState = $em->getRepository(CotationState::class)->find(4);
  5070. $cotation->setState($newState);
  5071. } else if ($cotation->getAcdFile()) {
  5072. $newState = $em->getRepository(CotationState::class)->find(3);
  5073. $cotation->setState($newState);
  5074. } else {
  5075. $newState = $em->getRepository(CotationState::class)->find(2);
  5076. $cotation->setState($newState);
  5077. }
  5078. }
  5079. $this->get("session")->getFlashBag()->add("success", "Demande de cotation mise à jour");
  5080. return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  5081. }
  5082. return $this->render("app/clients/cotation-multisite_form.html.twig", [
  5083. "form" => $form->createView(),
  5084. "cotation" => $cotation,
  5085. ]);
  5086. }
  5087. /**
  5088. * @Route("/companies/{company}/cotations-multisites/{cotation}/ellipro", name="companies_cotations-multisites_ellipro")
  5089. */
  5090. public function companiesCotationMultisiteElliproAction(Request $request, Company $company, CotationMultisite $cotation, EllisphereService $ellisphereService)
  5091. {
  5092. if (!$cotation->getSiret()) {
  5093. return new JsonResponse([
  5094. "success" => false,
  5095. "message" => "Siret non renseigné pour cette cotation"
  5096. ]);
  5097. }
  5098. $data = $ellisphereService->getNoteElliPro($cotation->getSiret());
  5099. if ($data) {
  5100. return new JsonResponse([
  5101. "success" => true,
  5102. "data" => $data
  5103. ]);
  5104. } else {
  5105. return new JsonResponse([
  5106. "success" => false,
  5107. "message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
  5108. ]);
  5109. }
  5110. }
  5111. /**
  5112. * @Route("/companies/{company}/cotations-multisites/{cotation}/acd", name="companies_cotations-multisites_acd")
  5113. */
  5114. public function companiesCotationsMultisitesAcdAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation)
  5115. {
  5116. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  5117. throw new NotFoundHttpException();
  5118. }
  5119. if (!$this->getUser()->getManager()->getAdmin()) {
  5120. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5121. throw new NotFoundHttpException();
  5122. }
  5123. }
  5124. if ($cotation->getAcdFile()) {
  5125. $filePath = $this->getParameter('documents_acd_directory') . $cotation->getAcdFile();
  5126. return $this->file($filePath, $cotation->getAcdFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  5127. }
  5128. if ($cotation->getState()->getId() == 1) {
  5129. $newState = $em->getRepository(CotationState::class)->find(2);
  5130. $cotation->setState($newState);
  5131. $em->flush();
  5132. }
  5133. $pdf = $this->generateACDMultisite($cotation);
  5134. $filename = "ACD";
  5135. return $pdf->Output($filename.".pdf",'I');
  5136. }
  5137. /**
  5138. * @Route("/companies/{company}/cotations-multisites/{cotation}/send-acd", name="companies_cotations-multisites_send_acd")
  5139. */
  5140. public function companiesCotationsMultisiteSendAcdAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, DocusignService $docusignService)
  5141. {
  5142. if (!$this->getUser()->getManager()->getAdmin()) {
  5143. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5144. throw new NotFoundHttpException();
  5145. }
  5146. }
  5147. if ($cotation->isAcdValid()) {
  5148. $this->get("session")->getFlashBag()->add("danger", "L'ACD a déjà été renseigné pour cette cotation.");
  5149. } else {
  5150. // Lancement de la signature
  5151. $startSign = null;
  5152. if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
  5153. $startSign = $this::sendAcdMultisiteToDocusign($cotation, $company, $docusignService, $em);
  5154. } else {
  5155. $this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
  5156. }
  5157. if (!$startSign) {
  5158. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  5159. } else {
  5160. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
  5161. }
  5162. }
  5163. return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
  5164. }
  5165. /**
  5166. * @Route("/companies/{company}/cotations-multisites/{cotation}/excel-elec", name="companies_cotations-multisites_excel-elec")
  5167. */
  5168. public function companiesCotationsMultisiteExcelElecAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, CotationMultisite $cotation)
  5169. {
  5170. if (!$this->getUser()->getManager()->getAdmin()) {
  5171. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5172. throw new NotFoundHttpException();
  5173. }
  5174. }
  5175. $spreadsheet = new Spreadsheet();
  5176. $sheet = $spreadsheet->getActiveSheet();
  5177. $sheet->setTitle("Cotation Multisite ELEC");
  5178. $sheet->getProtection()->setSheet(true);
  5179. $spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
  5180. //HEADER
  5181. // ---------- Helpers ----------
  5182. $thinBorder = [
  5183. 'borders' => [
  5184. 'allBorders' => ['borderStyle' => Border::BORDER_THIN],
  5185. ],
  5186. ];
  5187. $mediumOutline = [
  5188. 'borders' => [
  5189. 'outline' => ['borderStyle' => Border::BORDER_MEDIUM],
  5190. ],
  5191. ];
  5192. $centerWrap = [
  5193. 'alignment' => [
  5194. 'horizontal' => Alignment::HORIZONTAL_CENTER,
  5195. 'vertical' => Alignment::VERTICAL_CENTER,
  5196. 'wrapText' => true,
  5197. ],
  5198. ];
  5199. $boldCenter = [
  5200. 'font' => ['bold' => true, 'size' => 10],
  5201. ] + $centerWrap;
  5202. $normalCenter = [
  5203. 'font' => ['bold' => false, 'size' => 10],
  5204. ] + $centerWrap;
  5205. $fill = function(string $hex) {
  5206. return [
  5207. 'fill' => [
  5208. 'fillType' => Fill::FILL_SOLID,
  5209. 'startColor' => ['rgb' => ltrim($hex, '#')],
  5210. ],
  5211. ];
  5212. };
  5213. $fillInfoClients = $fill('#FCE4D6'); // A1:L4
  5214. $fillCotation = $fill('#E2EFDA'); // M1:P4
  5215. $fillContrats = $fill('#FFF2CC'); // Q1:T4
  5216. $fillSites = $fill('#DDEBF7'); // U1:AI3
  5217. $fillSousTitreBlue = $fill('#BDD7EE'); // Y4:AC4 (Puissances)
  5218. $fillSousTitreGrn = $fill('#C6E0B4'); // AD4:AI4 (Consommations MWh)
  5219. $fillHeader2 = $fill('#B4C6E7'); // Lignes 5-6 (libellés colonnes)
  5220. // ---------- Largeurs de colonnes ----------
  5221. $widths = [
  5222. 'A'=>15,'B'=>15,'C'=>16,'D'=>15,'E'=>16,'F'=>16,'G'=>12,'H'=>22,'I'=>22,'J'=>14,'K'=>12,'L'=>16,
  5223. 'M'=>18,'N'=>14,'O'=>28,'P'=>24,'Q'=>18,'R'=>16,'S'=>16,'T'=>18,
  5224. 'U'=>24,'V'=>30,'W'=>14,'X'=>20,
  5225. // blocs Y..AI
  5226. 'Y'=>10,'Z'=>10,'AA'=>10,'AB'=>10,'AC'=>10,
  5227. 'AD'=>10,'AE'=>10,'AF'=>10,'AG'=>10,'AH'=>10,'AI'=>10, 'AJ'=>10
  5228. ];
  5229. foreach ($widths as $col => $w) {
  5230. $sheet->getColumnDimension($col)->setWidth($w);
  5231. }
  5232. // ---------- Hauteurs de ligne ----------
  5233. $sheet->getRowDimension(1)->setRowHeight(24);
  5234. $sheet->getRowDimension(2)->setRowHeight(18);
  5235. $sheet->getRowDimension(3)->setRowHeight(18);
  5236. $sheet->getRowDimension(4)->setRowHeight(22);
  5237. $sheet->getRowDimension(5)->setRowHeight(22);
  5238. $sheet->getRowDimension(6)->setRowHeight(22);
  5239. // ---------- Contenu & fusions ----------
  5240. $sheet->mergeCells('A1:L4')->setCellValue('A1', 'Informations clients');
  5241. $sheet->mergeCells('M1:P4')->setCellValue('M1', 'Informations cotations');
  5242. $sheet->mergeCells('Q1:T4')->setCellValue('Q1', 'Informations contrats ');
  5243. $sheet->mergeCells('U1:AI3')->setCellValue('U1', 'Informations sites ');
  5244. $sheet->mergeCells('Y4:AC4')->setCellValue('Y4', 'Puissances');
  5245. $sheet->mergeCells('AD4:AI4')->setCellValue('AD4', 'Consommations MWh');
  5246. // Ligne 5 (labels de colonnes, fusionnées avec ligne 6)
  5247. $labels = [
  5248. 'A5' => 'Nom du Site',
  5249. 'B5' => 'Titulaire',
  5250. 'C5' => 'SIRET Titulaire',
  5251. 'D5' => 'Payeur',
  5252. 'E5' => 'SIRET Payeur',
  5253. 'F5' => 'Nom Prénom',
  5254. 'G5' => 'Fonction',
  5255. 'H5' => 'Adresse de facturation',
  5256. 'I5' => 'Téléphone',
  5257. 'J5' => 'Email',
  5258. 'K5' => 'Code NAF',
  5259. 'L5' => 'Secteur client',
  5260. 'M5' => "Tenue de l'offre",
  5261. 'N5' => 'Note Ellipro',
  5262. 'O5' => 'Tarif unique/ horosaisonnalité, Arenh(%) …',
  5263. 'P5' => 'Marge souhaitée POUR FLASH ',
  5264. 'Q5' => 'Fournisseur actuel',
  5265. 'R5' => 'Date de début de fourniture',
  5266. 'S5' => 'Date de fin de fourniture',
  5267. 'T5' => 'Nombre de mois à fournir',
  5268. 'U5' => 'RAE',
  5269. 'V5' => 'Adresse du site',
  5270. 'W5' => 'Segment',
  5271. 'X5' => 'Formule acheminement',
  5272. // Bloc Puissances
  5273. 'Y5' => 'POINTE',
  5274. 'Z5' => 'HPC',
  5275. 'AA5' => 'HCH',
  5276. 'AB5' => 'HPE',
  5277. 'AC5' => 'HCE',
  5278. // Bloc Consommations MWh
  5279. 'AD5' => 'POINTE',
  5280. 'AE5' => 'HPC',
  5281. 'AF5' => 'HCH',
  5282. 'AG5' => 'HPE',
  5283. 'AH5' => 'HCE',
  5284. 'AI5' => 'CAR',
  5285. ];
  5286. foreach ($labels as $cell => $text) {
  5287. // Fusion 5-6
  5288. [$col] = sscanf($cell, "%[A-Z]");
  5289. $sheet->mergeCells($col.'5:'.$col.'6');
  5290. $sheet->setCellValue($cell, $text);
  5291. }
  5292. // ---------- Styles ----------
  5293. $sheet->getStyle('A1:L4')->applyFromArray($boldCenter + $fillInfoClients + $mediumOutline);
  5294. $sheet->getStyle('M1:P4')->applyFromArray($boldCenter + $fillCotation + $mediumOutline);
  5295. $sheet->getStyle('Q1:T4')->applyFromArray($boldCenter + $fillContrats + $mediumOutline);
  5296. $sheet->getStyle('U1:AI3')->applyFromArray($boldCenter + $fillSites + $mediumOutline);
  5297. $sheet->getStyle('Y4:AC4')->applyFromArray($normalCenter + $fillSousTitreBlue + $mediumOutline);
  5298. $sheet->getStyle('AD4:AI4')->applyFromArray($normalCenter + $fillSousTitreGrn + $mediumOutline);
  5299. $sheet->getStyle('A5:AI6')->applyFromArray($boldCenter + $fillHeader2 + $thinBorder);
  5300. $sheet->getStyle('A5:X6')->applyFromArray($mediumOutline);
  5301. $sheet->getStyle('Y4:AC6')->applyFromArray($mediumOutline);
  5302. $sheet->getStyle('AD4:AI6')->applyFromArray($mediumOutline);
  5303. $i = 7;
  5304. foreach ($cotation->getCotations() as $site) {
  5305. /** @var Cotation $site */
  5306. $sheet->getStyle('C' . $i)->getNumberFormat()->setFormatCode('0');
  5307. $sheet->getStyle('E' . $i)->getNumberFormat()->setFormatCode('0');
  5308. $sheet->getStyle('U' . $i)->getNumberFormat()->setFormatCode('0');
  5309. $sheet->setCellValue('A' . $i, $site->getName());
  5310. $sheet->setCellValue('B' . $i, $cotation->getCompanyName());
  5311. $sheet->setCellValue('C' . $i, $cotation->getSiret());
  5312. $sheet->setCellValue('D' . $i, $site->getCompanyName());
  5313. $sheet->setCellValue('E' . $i, $site->getSiret());
  5314. $sheet->setCellValue('F' . $i, $site->getFirstName() . ' ' . $site->getLastName());
  5315. $sheet->setCellValue('G' . $i, $site->getPosition());
  5316. $sheet->setCellValue('H' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
  5317. $sheet->setCellValue('I' . $i, $site->getPhone());
  5318. $sheet->setCellValue('J' . $i, $site->getEmail());
  5319. $sheet->setCellValue('K' . $i, $site->getApeCode());
  5320. $sheet->setCellValue('L' . $i, $site->getSector());
  5321. $sheet->setCellValue('M' . $i, $cotation->getTenueOffre());
  5322. $sheet->setCellValue('N' . $i, $site->getEliproNote());
  5323. $sheet->setCellValue('O' . $i, $site->getTarifType());
  5324. $sheet->setCellValue('P' . $i, $site->getDesiredMargin());
  5325. $sheet->setCellValue('Q' . $i, $site->getElectricitySupplier() ? $site->getElectricitySupplier()->getName() : "");
  5326. $sheet->setCellValue('R' . $i, ($site->getEDesiredBegin())->format('Y-m-d'));
  5327. $sheet->setCellValue('S' . $i, ($site->getEDesiredEnd())->format('Y-m-d'));
  5328. $sheet->setCellValue('T' . $i, $site->getENombreMois());
  5329. $sheet->setCellValue('U' . $i, $site->getEPdl());
  5330. $sheet->setCellValue('V' . $i, $site->getEAddress() . ' ' . $site->getEAddress2() . ' ' . $site->getEZipCode() . ' ' . $site->getECity());
  5331. $sheet->setCellValue('W' . $i, $site->getESegment());
  5332. $sheet->setCellValue('X' . $i, $site->getEFormuleAcheminement());
  5333. $sheet->setCellValue('Y' . $i, $site->getEPuissanceKvaPointe());
  5334. $sheet->setCellValue('Z' . $i, $site->getEPuissanceKvaHph());
  5335. $sheet->setCellValue('AA' . $i, $site->getEPuissanceKvaHch());
  5336. $sheet->setCellValue('AB' . $i, $site->getEPuissanceKvaHpe());
  5337. $sheet->setCellValue('AC' . $i, $site->getEPuissanceKvaHce());
  5338. $sheet->setCellValue('AD' . $i, $site->getEConsommationPointe());
  5339. $sheet->setCellValue('AE' . $i, $site->getEConsommationHph());
  5340. $sheet->setCellValue('AF' . $i, $site->getEConsommationHch());
  5341. $sheet->setCellValue('AG' . $i, $site->getEConsommationHpe());
  5342. $sheet->setCellValue('AH' . $i, $site->getEConsommationHce());
  5343. $sheet->setCellValue('AI' . $i, $site->getEConsommationPointe()+$site->getEConsommationHph()+$site->getEConsommationHch()+$site->getEConsommationHpe()+$site->getEConsommationHce());
  5344. $i++;
  5345. }
  5346. $sheet->freezePane('A7');
  5347. $sheet->setSelectedCell("A7");
  5348. $writer = new Xlsx($spreadsheet);
  5349. $response = new StreamedResponse();
  5350. $response->setCallback(function () use ($writer) {
  5351. $writer->save('php://output');
  5352. });
  5353. $filenane = "excel-elec_".$cotation->getCompanyName().'.xlsx';
  5354. $response->setStatusCode(200);
  5355. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5356. $response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
  5357. $response->headers->set('Cache-Control', 'max-age=0');
  5358. return $response;
  5359. }
  5360. /**
  5361. * @Route("/companies/{company}/cotations-multisites/{cotation}/excel-gaz", name="companies_cotations-multisites_excel-gaz")
  5362. */
  5363. public function companiesCotationsMultisiteExcelGazAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, CotationMultisite $cotation)
  5364. {
  5365. if (!$this->getUser()->getManager()->getAdmin()) {
  5366. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5367. throw new NotFoundHttpException();
  5368. }
  5369. }
  5370. $spreadsheet = new Spreadsheet();
  5371. $sheet = $spreadsheet->getActiveSheet();
  5372. $sheet->setTitle("Cotation Multisite GAZ");
  5373. $sheet->getProtection()->setSheet(true);
  5374. $spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
  5375. //HEADER
  5376. // ---------- Helpers ----------
  5377. $thinBorder = [
  5378. 'borders' => [
  5379. 'allBorders' => ['borderStyle' => Border::BORDER_THIN],
  5380. ],
  5381. ];
  5382. $mediumOutline = [
  5383. 'borders' => [
  5384. 'outline' => ['borderStyle' => Border::BORDER_MEDIUM],
  5385. ],
  5386. ];
  5387. $centerWrap = [
  5388. 'alignment' => [
  5389. 'horizontal' => Alignment::HORIZONTAL_CENTER,
  5390. 'vertical' => Alignment::VERTICAL_CENTER,
  5391. 'wrapText' => true,
  5392. ],
  5393. ];
  5394. $boldCenter = [
  5395. 'font' => ['bold' => true, 'size' => 10],
  5396. ] + $centerWrap;
  5397. $normalCenter = [
  5398. 'font' => ['bold' => false, 'size' => 10],
  5399. ] + $centerWrap;
  5400. $fill = function(string $hex) {
  5401. return [
  5402. 'fill' => [
  5403. 'fillType' => Fill::FILL_SOLID,
  5404. 'startColor' => ['rgb' => ltrim($hex, '#')],
  5405. ],
  5406. ];
  5407. };
  5408. $fillInfoClients = $fill('#FCE4D6'); // A1:L4
  5409. $fillCotation = $fill('#E2EFDA'); // M1:O4
  5410. $fillContrats = $fill('#FFF2CC'); // P1:S4
  5411. $fillSites = $fill('#DDEBF7'); // T1:X4
  5412. $fillHeader2 = $fill('#B4C6E7'); // Lignes 5-6 (libellés colonnes)
  5413. $widths = [
  5414. 'A'=>15,'B'=>15,'C'=>16,'D'=>15,'E'=>16,'F'=>16,'G'=>12,'H'=>22,'I'=>22,'J'=>14,'K'=>12,'L'=>16,
  5415. 'M'=>18,'N'=>14,'O'=>24,'P'=>18,'Q'=>20,'R'=>22,'S'=>23,'T'=>15,
  5416. 'U'=>24,'V'=>12,'W'=>18,'X'=>12, 'Y' => 12
  5417. ];
  5418. foreach ($widths as $col => $w) {
  5419. $sheet->getColumnDimension($col)->setWidth($w);
  5420. }
  5421. $sheet->getRowDimension(1)->setRowHeight(24);
  5422. $sheet->getRowDimension(2)->setRowHeight(18);
  5423. $sheet->getRowDimension(3)->setRowHeight(18);
  5424. $sheet->getRowDimension(4)->setRowHeight(22);
  5425. $sheet->getRowDimension(5)->setRowHeight(22);
  5426. $sheet->getRowDimension(6)->setRowHeight(22);
  5427. // ---------- Groupes & fusions ----------
  5428. $sheet->mergeCells('A1:M4')->setCellValue('A1', 'Informations clients');
  5429. $sheet->mergeCells('N1:P4')->setCellValue('N1', 'Informations cotations');
  5430. $sheet->mergeCells('Q1:T4')->setCellValue('Q1', 'Informations contrats ');
  5431. $sheet->mergeCells('U1:Y4')->setCellValue('U1', 'Informations sites ');
  5432. $labels = [
  5433. 'A5' => 'Nom du Site',
  5434. 'B5' => 'Titulaire',
  5435. 'C5' => 'SIRET Titulaire',
  5436. 'D5' => 'Payeur',
  5437. 'E5' => 'SIRET Payeur',
  5438. 'F5' => 'Nom Prénom',
  5439. 'G5' => 'Fonction',
  5440. 'H5' => 'Adresse de facturation',
  5441. 'I5' => 'Adresse de consommation',
  5442. 'J5' => 'Téléphone',
  5443. 'K5' => 'Email',
  5444. 'L5' => 'Code NAF',
  5445. 'M5' => 'Secteur client',
  5446. 'N5' => "Tenue de l'offre",
  5447. 'O5' => 'Note Ellipro',
  5448. 'P5' => 'Marge souhaitée POUR FLASH ',
  5449. 'Q5' => 'Fournisseur actuel',
  5450. 'R5' => 'Date de début de fourniture',
  5451. 'S5' => 'Date de fin de fourniture',
  5452. 'T5' => 'Nombre de mois à fournir',
  5453. 'U5' => 'PCE',
  5454. 'V5' => 'Adresse du site',
  5455. 'W5' => 'Profil',
  5456. 'X5' => "Tarif d'acheminement",
  5457. 'Y5' => 'CAR (Mwh)',
  5458. ];
  5459. foreach ($labels as $cell => $text) {
  5460. [$col] = sscanf($cell, "%[A-Z]");
  5461. $sheet->mergeCells($col.'5:'.$col.'6');
  5462. $sheet->setCellValue($cell, $text);
  5463. }
  5464. // ---------- Styles ----------
  5465. $sheet->getStyle('A1:M4')->applyFromArray($boldCenter + $fillInfoClients + $mediumOutline);
  5466. $sheet->getStyle('N1:P4')->applyFromArray($boldCenter + $fillCotation + $mediumOutline);
  5467. $sheet->getStyle('Q1:T4')->applyFromArray($boldCenter + $fillContrats + $mediumOutline);
  5468. $sheet->getStyle('U1:Y4')->applyFromArray($boldCenter + $fillSites + $mediumOutline);
  5469. $sheet->getStyle('A5:Y6')->applyFromArray($boldCenter + $fillHeader2 + $thinBorder);
  5470. $sheet->getStyle('A5:Y6')->applyFromArray($mediumOutline);
  5471. $i = 7;
  5472. foreach ($cotation->getCotations() as $site) {
  5473. /** @var Cotation $site */
  5474. $sheet->getStyle('C' . $i)->getNumberFormat()->setFormatCode('0');
  5475. $sheet->getStyle('E' . $i)->getNumberFormat()->setFormatCode('0');
  5476. $sheet->getStyle('T' . $i)->getNumberFormat()->setFormatCode('0');
  5477. $sheet->setCellValue('A' . $i, $site->getName());
  5478. $sheet->setCellValue('B' . $i, $cotation->getCompanyName());
  5479. $sheet->setCellValue('C' . $i, $cotation->getSiret());
  5480. $sheet->setCellValue('D' . $i, $site->getCompanyName());
  5481. $sheet->setCellValue('E' . $i, $site->getSiret());
  5482. $sheet->setCellValue('F' . $i, $site->getFirstName() . ' ' . $site->getLastName());
  5483. $sheet->setCellValue('G' . $i, $site->getPosition());
  5484. $sheet->setCellValue('H' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
  5485. $sheet->setCellValue('I' . $i, $site->getGAddress() . ' ' . $site->getGAddress2() . ' ' . $site->getGZipCode() . ' ' . $site->getGCity());
  5486. $sheet->setCellValue('J' . $i, $site->getPhone());
  5487. $sheet->setCellValue('K' . $i, $site->getEmail());
  5488. $sheet->setCellValue('L' . $i, $site->getApeCode());
  5489. $sheet->setCellValue('M' . $i, $site->getSector());
  5490. $sheet->setCellValue('N' . $i, $cotation->getTenueOffre());
  5491. $sheet->setCellValue('O' . $i, $site->getEliproNote());
  5492. $sheet->setCellValue('P' . $i, $cotation->getDesiredMargin());
  5493. $sheet->setCellValue('Q' . $i, $site->getGasSupplier() ? $site->getGasSupplier()->getName() : "");
  5494. $sheet->setCellValue('R' . $i, $site->getGDesiredBegin());
  5495. $sheet->setCellValue('S' . $i, $site->getGDesiredEnd());
  5496. $sheet->setCellValue('T' . $i, $site->getGNombreMois());
  5497. $sheet->setCellValue('U' . $i, $site->getGPce());
  5498. $sheet->setCellValue('V' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
  5499. $sheet->setCellValue('W' . $i, $site->getGProfil());
  5500. $sheet->setCellValue('X' . $i, $site->getGSegment());
  5501. $sheet->setCellValue('Y' . $i, $site->getGCarMwh());
  5502. $i++;
  5503. }
  5504. $sheet->freezePane('A7');
  5505. $sheet->setSelectedCell("A7");
  5506. $writer = new Xlsx($spreadsheet);
  5507. $response = new StreamedResponse();
  5508. $response->setCallback(function () use ($writer) {
  5509. $writer->save('php://output');
  5510. });
  5511. $filenane = "excel-gaz_".$cotation->getCompanyName().'.xlsx';
  5512. $response->setStatusCode(200);
  5513. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5514. $response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
  5515. $response->headers->set('Cache-Control', 'max-age=0');
  5516. return $response;
  5517. }
  5518. /**
  5519. * @Route("/companies/{company}/cotations-multisites/{cotation}/offers", name="companies_cotations-multisites_offers")
  5520. */
  5521. public function companiesCotationsMultisitesOffersAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation)
  5522. {
  5523. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  5524. throw new NotFoundHttpException();
  5525. }
  5526. if (!$this->getUser()->getManager()->getAdmin()) {
  5527. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5528. throw new NotFoundHttpException();
  5529. }
  5530. }
  5531. $offersBySite = [];
  5532. foreach ($cotation->getCotations() as $site) {
  5533. $offers = [];
  5534. if ($cotation->getElectricity()) {
  5535. $offers = array_merge($offers, $em->getRepository(OfferElec::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
  5536. }
  5537. if ($cotation->getGas()) {
  5538. $offers = array_merge($offers, $em->getRepository(OfferGaz::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
  5539. }
  5540. $offersBySite[] = [
  5541. "site" => $site,
  5542. "offers" => $offers
  5543. ];
  5544. }
  5545. return $this->render("app/clients/cotations-multisites_offers.html.twig", [
  5546. "offersBySite" => $offersBySite,
  5547. "company" => $company,
  5548. "cotation" => $cotation,
  5549. ]);
  5550. }
  5551. /**
  5552. * @Route("/companies/{company}/cotations-multisites/{cotation}/offers/pdf", name="companies_cotations-multisites_offers_pdf")
  5553. */
  5554. public function companiesCotationsMultisitesOffersPdfAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, Pdf $knpSnappyPdf, OfferCalculatorService $offerCalculatorService)
  5555. {
  5556. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  5557. throw new NotFoundHttpException();
  5558. }
  5559. if (!$this->getUser()->getManager()->getAdmin()) {
  5560. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5561. throw new NotFoundHttpException();
  5562. }
  5563. }
  5564. $form = $this->createFormBuilder()->getForm();
  5565. if ($cotation->getElectricity()) {
  5566. $form->add("etude_solution_elec", ChoiceType::class, [
  5567. "expanded" => false,
  5568. "multiple" => false,
  5569. "choices" => [
  5570. "Prendre un prix unique composé de la totalité de ses droits d’ARENH" => "1",
  5571. "Prendre un prix unique composé d’un taux modéré de ses droits d'ARENH" => "2",
  5572. "Maintenir un prix unique composé d'un prix 100 % fixe" => "3",
  5573. "Prendre un horosaisonnalisé 100 % fixe (uniquement prix de marché)" => "4",
  5574. "Prendre un prix horosaisonnalisé composé d’un taux modéré de ses droits d'ARENH" => "5",
  5575. "Maintenir un prix horosaisonnalisé composé de la totalité de ses droits d’ARENH" => "6",
  5576. ],
  5577. "label" => "Choix de la solution ELEC",
  5578. ])
  5579. ->add("etude_commentaire_elec", TextType::class, [
  5580. "attr" => [
  5581. "placeholder" => ""
  5582. ],
  5583. "label" => "Commentaire ELEC",
  5584. "required" => false,
  5585. ]);
  5586. $form["etude_solution_elec"]->setData($cotation->getEtudeSolutionElec());
  5587. $form["etude_commentaire_elec"]->setData($cotation->getEtudeCommentaireElec());
  5588. }
  5589. if ($cotation->getGas()) {
  5590. $form->add("etude_solution_gaz", ChoiceType::class, [
  5591. "expanded" => false,
  5592. "multiple" => false,
  5593. "choices" => [
  5594. "Prendre un prix variable indexé sur le PEG" => "1",
  5595. "Maintenir un prix 100 % fixe" => "2",
  5596. ],
  5597. "label" => "Choix de la solution GAZ",
  5598. ])
  5599. ->add("etude_commentaire_gaz", TextType::class, [
  5600. "attr" => [
  5601. "placeholder" => ""
  5602. ],
  5603. "label" => "Commentaire GAZ",
  5604. "required" => false,
  5605. ]);
  5606. $form["etude_solution_gaz"]->setData($cotation->getEtudeSolutionGaz());
  5607. $form["etude_commentaire_gaz"]->setData($cotation->getEtudeCommentaireGaz());
  5608. }
  5609. $form->add("etude_type", ChoiceType::class, [
  5610. "expanded" => false,
  5611. "multiple" => false,
  5612. "choices" => [
  5613. "Site par site" => "1",
  5614. "Globale" => "2",
  5615. "Globale + Site par site" => "3",
  5616. ],
  5617. "label" => "Choix du type d'étude",
  5618. ]);
  5619. $sitesChoices = [
  5620. //"Tous" => "ALL",
  5621. ];
  5622. foreach ($cotation->getCotations() as $site) {
  5623. $sitesChoices[$site->getName()] = $site->getId();
  5624. }
  5625. $form->handleRequest($request);
  5626. if ($form->isSubmitted() && $form->isValid()) {
  5627. $offersElec = [];
  5628. $offersGas = [];
  5629. $cotationSite = [];
  5630. $supplierForSite = [
  5631. 'elec' => [],
  5632. 'gas' => [],
  5633. 'global' => [
  5634. 'consommationEstimation' => []
  5635. ]
  5636. ];
  5637. foreach ($sitesChoices as $siteName => $site) {
  5638. $cotationSiteElement = $em->getRepository(Cotation::class)->find($site);
  5639. if ($cotationSiteElement->getCotationMultisite() != $cotation) {
  5640. throw new BadRequestHttpException();
  5641. }
  5642. if ($cotationSiteElement->getElectricity()) {
  5643. $cotationSiteElement->setEtudeSolutionElec($form["etude_solution_elec"]->getData());
  5644. $cotationSiteElement->setEtudeCommentaireElec($form["etude_commentaire_elec"]->getData());
  5645. }
  5646. if ($cotationSiteElement->getGas()) {
  5647. $cotationSiteElement->setEtudeSolutionGaz($form["etude_solution_gaz"]->getData());
  5648. $cotationSiteElement->setEtudeCommentaireGaz($form["etude_commentaire_gaz"]->getData());
  5649. }
  5650. $em->flush();
  5651. $offerElecItem = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
  5652. $offersElec[$siteName] = $offerElecItem;
  5653. $offerGasItem = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
  5654. $offersGas[$siteName] = $offerGasItem;
  5655. //Create array with elec and gas key for supplier choice in a site or multiple site
  5656. foreach ($offersElec[$siteName] as $offer) {
  5657. $supplierName = $cotationSiteElement->getPreselectedOfferElec()?->getSupplier()->getName();
  5658. if (isset($supplierName)) {
  5659. //Re-create variable calculated in front twig in past
  5660. if ($offer->getCurrentOffer()) {
  5661. $supplierForSite['elec'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcElec($offer);
  5662. }
  5663. //Re-create variable calculated in front twig in past
  5664. if ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offer->getId()) {
  5665. $supplierForSite['elec'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcElec($offer);
  5666. }
  5667. // Get supplier infos to display in twig template like logo, name and description
  5668. $supplierForSite['elec'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferElec()->getSupplier();
  5669. }
  5670. }
  5671. //Create array with elec and gas key for supplier choice in a site or multiple site
  5672. foreach ($offersGas[$siteName] as $offer) {
  5673. $supplierName = $cotationSiteElement->getPreselectedOfferGaz()?->getSupplier()->getName();
  5674. if (isset($supplierName)) {
  5675. //Re-create variable calculated in front twig in past
  5676. if ($offer->getCurrentOffer()) {
  5677. $supplierForSite['gas'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcGaz($offer);
  5678. }
  5679. //Re-create variable calculated in front twig in past
  5680. if ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offer->getId()) {
  5681. $supplierForSite['gas'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcGaz($offer);
  5682. }
  5683. // Get supplier infos to display in twig template like logo, name and description
  5684. $supplierForSite['gas'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferGaz()->getSupplier();
  5685. }
  5686. }
  5687. $cotationSite[$siteName] = $cotationSiteElement;
  5688. foreach ($offerElecItem as $offerItem) {
  5689. $offerCalculated = $offerCalculatorService->calcElec($offerItem);
  5690. $keyGlobalResult = [
  5691. 'id',
  5692. 'htt_2024',
  5693. 'htt_2025',
  5694. 'htt_2026',
  5695. 'htt_2027',
  5696. 'htt_2028',
  5697. 'htt_2029',
  5698. 'ach_taxes_per_year',
  5699. 'moy_month',
  5700. 'total_ttc',
  5701. 'total_htt',
  5702. 'subscription',
  5703. 'capacite',
  5704. 'cee',
  5705. 'other_tax',
  5706. 'budget_before_ach',
  5707. 'acheminement',
  5708. 'cta',
  5709. 'cspe',
  5710. 'cspe_index',
  5711. 'total_ttc',
  5712. ];
  5713. if ($offerItem->getCurrentOffer()) {
  5714. $type = 'actualOffer';
  5715. } elseif ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offerItem->getId()) {
  5716. $type = 'currentOffer';
  5717. }
  5718. if (isset($type)) {
  5719. foreach ($keyGlobalResult as $key) {
  5720. if (!isset($supplierForSite['global'][$type][$key])) {
  5721. $supplierForSite['global'][$type][$key] = 0;
  5722. }
  5723. $supplierForSite['global'][$type][$key] += $offerCalculated[$key];
  5724. }
  5725. if ($type === 'actualOffer') {
  5726. $consommationKeyArray = [
  5727. 'carAdditional',
  5728. 'carAverage',
  5729. 'kvaAdditional',
  5730. 'kvaAverage'
  5731. ];
  5732. $consommationSubKeyArray = [
  5733. 'pointe',
  5734. 'hph',
  5735. 'hch',
  5736. 'hpe',
  5737. 'hce',
  5738. ];
  5739. foreach ($consommationKeyArray as $consommationKey) {
  5740. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
  5741. $supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
  5742. }
  5743. foreach ($consommationSubKeyArray as $consommationSubKey) {
  5744. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
  5745. $supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
  5746. }
  5747. }
  5748. }
  5749. $supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] += $cotationSiteElement->getEConsommationPointe();
  5750. $supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] += $cotationSiteElement->getEConsommationHph();
  5751. $supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] += $cotationSiteElement->getEConsommationHch();
  5752. $supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] += $cotationSiteElement->getEConsommationHpe();
  5753. $supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] += $cotationSiteElement->getEConsommationHce();
  5754. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] += $cotationSiteElement->getEPuissanceKvaPointe();
  5755. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] += $cotationSiteElement->getEPuissanceKvaHph();
  5756. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] += $cotationSiteElement->getEPuissanceKvaHch();
  5757. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] += $cotationSiteElement->getEPuissanceKvaHpe();
  5758. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] += $cotationSiteElement->getEPuissanceKvaHce();
  5759. }
  5760. $offerAnalysisAndDetailsKeyArray = [
  5761. 'pointe_price',
  5762. 'base_price',
  5763. 'hp_price',
  5764. 'hc_price',
  5765. 'hph_price',
  5766. 'hch_price',
  5767. 'hpe_price',
  5768. 'hce_price',
  5769. ];
  5770. foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
  5771. if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
  5772. if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
  5773. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
  5774. }
  5775. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
  5776. }
  5777. }
  5778. unset($type);
  5779. }
  5780. }
  5781. foreach ($offerGasItem as $offerItem) {
  5782. $offerCalculated = $offerCalculatorService->calcGaz($offerItem);
  5783. $keyGlobalResult = [
  5784. 'id',
  5785. 'htt_2024',
  5786. 'htt_2025',
  5787. 'htt_2026',
  5788. 'htt_2027',
  5789. 'htt_2028',
  5790. 'htt_2029',
  5791. 'ach_taxes_per_year',
  5792. 'moy_month',
  5793. 'total_ttc',
  5794. 'total_htt',
  5795. 'subscription',
  5796. 'cee',
  5797. 'other_tax',
  5798. 'budget_before_ach',
  5799. 'acheminement',
  5800. 'cta',
  5801. 'total_ttc',
  5802. 'fourniture',
  5803. 'budget_fourniture',
  5804. ];
  5805. if ($offerItem->getCurrentOffer()) {
  5806. $type = 'actualOffer';
  5807. } elseif ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offerItem->getId()) {
  5808. $type = 'currentOffer';
  5809. }
  5810. if (isset($type)) {
  5811. foreach ($keyGlobalResult as $key) {
  5812. if (!isset($supplierForSite['global'][$type][$key])) {
  5813. $supplierForSite['global'][$type][$key] = 0;
  5814. }
  5815. $supplierForSite['global'][$type][$key] += $offerCalculated[$key];
  5816. }
  5817. if ($type === 'actualOffer') {
  5818. $consommationKeyArray = [
  5819. 'carAdditional',
  5820. 'carAverage',
  5821. ];
  5822. $consommationSubKeyArray = [
  5823. 'total'
  5824. ];
  5825. foreach ($consommationKeyArray as $consommationKey) {
  5826. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
  5827. $supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
  5828. }
  5829. foreach ($consommationSubKeyArray as $consommationSubKey) {
  5830. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
  5831. $supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
  5832. }
  5833. }
  5834. }
  5835. $supplierForSite['global']['consommationEstimation']['carAdditional']['total'] += $cotationSiteElement->getGCarMwh();
  5836. }
  5837. $offerAnalysisAndDetailsKeyArray = [
  5838. 'fourniture',
  5839. 'budget_fourniture',
  5840. ];
  5841. foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
  5842. if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
  5843. if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
  5844. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
  5845. }
  5846. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
  5847. }
  5848. }
  5849. unset($type);
  5850. }
  5851. }
  5852. }
  5853. if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['total'])) {
  5854. $supplierForSite['global']['consommationEstimation']['carAverage']['total'] = $supplierForSite['global']['consommationEstimation']['carAdditional']['total'] / count($sitesChoices);
  5855. }
  5856. $roundPrecision = 3;
  5857. if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'])) {
  5858. $supplierForSite['global']['consommationEstimation']['carAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
  5859. $supplierForSite['global']['consommationEstimation']['carAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] / count($sitesChoices), $roundPrecision);
  5860. $supplierForSite['global']['consommationEstimation']['carAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] / count($sitesChoices), $roundPrecision);
  5861. $supplierForSite['global']['consommationEstimation']['carAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
  5862. $supplierForSite['global']['consommationEstimation']['carAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] / count($sitesChoices), $roundPrecision);
  5863. $supplierForSite['global']['consommationEstimation']['kvaAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
  5864. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] / count($sitesChoices), $roundPrecision);
  5865. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] / count($sitesChoices), $roundPrecision);
  5866. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
  5867. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] / count($sitesChoices), $roundPrecision);
  5868. }
  5869. $html = $this->renderView('app/pdf/presentation-budget/section1.html.twig', [
  5870. "offersElec" => $offersElec,
  5871. "offersGas" => $offersGas,
  5872. 'cotation' => $cotationSite,
  5873. 'multisite' => true,
  5874. 'array_site' => $sitesChoices,
  5875. 'supplierChoiceForMultiSite' => $supplierForSite,
  5876. "etude_type" => $form['etude_type']->getData() ?? 0
  5877. ]);
  5878. $pdf = $knpSnappyPdf->getOutputFromHtml($html, array(
  5879. 'orientation' => 'landscape',
  5880. 'no-stop-slow-scripts' => true,
  5881. 'no-background' => false,
  5882. 'lowquality' => false,
  5883. 'page-height' => 340,
  5884. 'page-width' => 200,
  5885. 'encoding' => 'utf-8',
  5886. 'images' => true,
  5887. 'cookie' => array(),
  5888. 'dpi' => 300,
  5889. 'enable-external-links' => true,
  5890. 'enable-internal-links' => true,
  5891. 'margin-bottom' => 0
  5892. ));
  5893. return new Response($pdf,200,array(
  5894. 'Content-Type' => 'application/pdf',
  5895. 'Content-Disposition' => 'inline; filename="Flash-Presentation_budget.pdf"'
  5896. ));
  5897. /*
  5898. return new PdfResponse(
  5899. $knpSnappyPdf->getOutputFromHtml($html),
  5900. 'Flash-Presentation_budget.pdf'
  5901. );
  5902. */
  5903. }
  5904. return $this->render("app/clients/cotation_offers_pdf.html.twig", [
  5905. "form" => $form->createView(),
  5906. "cotation" => $cotation,
  5907. "multisite" => true,
  5908. ]);
  5909. }
  5910. /**
  5911. * @Route("/companies/{company}/contracts", name="companies_contracts")
  5912. */
  5913. public function companiesContractsAction(Request $request, EntityManagerInterface $em, Company $company)
  5914. {
  5915. if (!$this->getUser()->getManager()->getAdmin()) {
  5916. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5917. throw new NotFoundHttpException();
  5918. }
  5919. }
  5920. $contracts = $em->getRepository(Contract::class)->findBy(["company" => $company], ["expiryDate" => "DESC"]);
  5921. return $this->render("app/clients/contracts.html.twig", [
  5922. "company" => $company,
  5923. "contracts" => $contracts,
  5924. ]);
  5925. }
  5926. /**
  5927. * @Route("/companies/{company}/contracts/add", name="companies_contracts_add")
  5928. */
  5929. public function companiesContractsAddAction(Request $request, EntityManagerInterface $em, Company $company)
  5930. {
  5931. if (!$this->getUser()->getManager()->getAdmin()) {
  5932. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5933. throw new NotFoundHttpException();
  5934. }
  5935. }
  5936. $contract = new Contract();
  5937. $contract->setCompany($company);
  5938. $form = $this->createForm(ContractType::class, $contract);
  5939. $form->add('contractType', EntityType::class, [
  5940. 'class' => \App\Entity\ContractType::class,
  5941. 'query_builder' => function (EntityRepository $er) {
  5942. return $er->createQueryBuilder('t')
  5943. ->where('t.active = TRUE')
  5944. ->orderBy('t.label', 'ASC');
  5945. },
  5946. 'choice_label' => 'label',
  5947. 'label' => 'Type de contrat',
  5948. 'required' => true,
  5949. 'mapped' => false,
  5950. ]);
  5951. $form["sepaIban"]->setData($company->getSepaIban());
  5952. $form["sepaBic"]->setData($company->getSepaBic());
  5953. $form->handleRequest($request);
  5954. if ($form->isSubmitted() && !$form->isValid()) {
  5955. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  5956. }
  5957. if ($form->isSubmitted() && $form->isValid()) {
  5958. $contract->setManager($this->getUser()->getManager());
  5959. $em->persist($contract);
  5960. $em->flush();
  5961. $file = $form['file']->getData();
  5962. if ($file) {
  5963. $extension = $file->guessExtension();
  5964. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5965. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5966. } else {
  5967. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5968. $file->move(
  5969. $this->getParameter('documents_contracts_directory'),
  5970. $fileName
  5971. );
  5972. $contract->setFile($fileName);
  5973. $em->flush();
  5974. }
  5975. }
  5976. $otherFile = $form['otherFile']->getData();
  5977. if ($otherFile) {
  5978. $extension = $otherFile->guessExtension();
  5979. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5980. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5981. } else {
  5982. $fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
  5983. $otherFile->move(
  5984. $this->getParameter('documents_contracts_directory'),
  5985. $fileName
  5986. );
  5987. $contract->setOtherFile($fileName);
  5988. $em->flush();
  5989. }
  5990. }
  5991. $rib = $form['ribFile']->getData();
  5992. if ($rib) {
  5993. $extension = $rib->guessExtension();
  5994. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5995. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5996. } else {
  5997. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5998. $rib->move(
  5999. $this->getParameter('documents_contracts_directory'),
  6000. $fileName
  6001. );
  6002. $contract->setRibFile($fileName);
  6003. $em->flush();
  6004. }
  6005. }
  6006. if ($form['contractType']->getData()) {
  6007. switch ($form['contractType']->getData()->getId()) {
  6008. case 1:
  6009. $contract->setGas(true);
  6010. break;
  6011. case 2:
  6012. $contract->setElectricity(true);
  6013. break;
  6014. case 3:
  6015. //$contract->setGas(true);
  6016. //$contract->setElectricity(true);
  6017. break;
  6018. case 4:
  6019. $contract->setEngiePro(true);
  6020. break;
  6021. case 5:
  6022. $contract->setTelecom(true);
  6023. break;
  6024. case 6:
  6025. $contract->setPhotovoltaique(true);
  6026. break;
  6027. }
  6028. $em->flush();
  6029. }
  6030. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  6031. $contract->setSignDate(new \DateTime('now'));
  6032. $em->flush();
  6033. }
  6034. $this->get("session")->getFlashBag()->add("success", "Contrat ajouté avec succès");
  6035. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId(), "creation" => 1]);
  6036. }
  6037. return $this->render("app/clients/contracts_form.html.twig", [
  6038. "form" => $form->createView(),
  6039. "contract" => $contract,
  6040. "title" => "Ajouter un contrat",
  6041. ]);
  6042. }
  6043. /**
  6044. * @Route("/companies/{company}/contracts/{contract}/edit", name="companies_contracts_edit")
  6045. */
  6046. public function companiesContractsEditAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, YousignService $yousignService)
  6047. {
  6048. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6049. throw new NotFoundHttpException();
  6050. }
  6051. if (!$this->getUser()->getManager()->getAdmin()) {
  6052. if ($contract->getManager()->getId() != $this->getUser()->getManager()->getId() && !$contract->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6053. throw new NotFoundHttpException();
  6054. }
  6055. }
  6056. if (isset($_GET["proof"]) && $contract->getProcedureYousignId()) {
  6057. $zipBase64 = $yousignService->getProcedureProof($contract->getProcedureYousignId());
  6058. if ($zipBase64) {
  6059. $zip = base64_decode($zipBase64);
  6060. $response = new Response($zip);
  6061. $response->headers->set('Content-Type', 'application/zip');
  6062. $response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
  6063. $response->headers->set('Content-length', strlen($zip));
  6064. return $response;
  6065. }
  6066. }
  6067. if (isset($_GET["proof-other"]) && $contract->getOtherFileProcedureYousignId()) {
  6068. $zipBase64 = $yousignService->getProcedureProof($contract->getOtherFileProcedureYousignId());
  6069. if ($zipBase64) {
  6070. $zip = base64_decode($zipBase64);
  6071. $response = new Response($zip);
  6072. $response->headers->set('Content-Type', 'application/zip');
  6073. $response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
  6074. $response->headers->set('Content-length', strlen($zip));
  6075. return $response;
  6076. }
  6077. }
  6078. $form = $this->createForm(ContractType::class, $contract);
  6079. if ($this->getUser()->getManager()->getAdmin()) {
  6080. $form->add('manager', EntityType::class, [
  6081. "label" => "Commercial associé",
  6082. 'class' => Manager::class,
  6083. 'query_builder' => function (EntityRepository $er) {
  6084. return $er->createQueryBuilder('m')
  6085. ->leftJoin("m.account", "a")
  6086. ->where('a.enabled = true');
  6087. },
  6088. 'choice_label' => 'fullName',
  6089. 'attr' => [
  6090. "data-control" => "select2",
  6091. ],
  6092. "required" => false,
  6093. "mapped" => true,
  6094. ]);
  6095. $form["manager"]->setData($contract->getManager());
  6096. } elseif ($contract->getManager()->isSupervisedBy($this->getUser()->getManager()) || ($contract->getManager() === $this->getUser()->getManager())) {
  6097. $form->add('manager', EntityType::class, [
  6098. "label" => "Commercial associé",
  6099. 'class' => Manager::class,
  6100. 'query_builder' => function (EntityRepository $er) {
  6101. return $er->createQueryBuilder('m')
  6102. ->leftJoin("m.account", "a")
  6103. ->where('a.enabled = true')
  6104. ->andWhere('(:manager MEMBER OF m.supervisors OR :manager = m)')
  6105. ->setParameter('manager', $this->getUser()->getManager());
  6106. },
  6107. 'choice_label' => 'fullName',
  6108. 'attr' => [
  6109. "data-control" => "select2",
  6110. ],
  6111. "required" => false,
  6112. "mapped" => true,
  6113. ]);
  6114. $form["manager"]->setData($contract->getManager());
  6115. }
  6116. $form->handleRequest($request);
  6117. if ($form->isSubmitted() && !$form->isValid()) {
  6118. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6119. }
  6120. if ($form->isSubmitted() && $form->isValid()) {
  6121. $em->flush();
  6122. $file = $form['file']->getData();
  6123. if ($file) {
  6124. $extension = $file->guessExtension();
  6125. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6126. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6127. } else {
  6128. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6129. $file->move(
  6130. $this->getParameter('documents_contracts_directory'),
  6131. $fileName
  6132. );
  6133. $contract->setFile($fileName);
  6134. $em->flush();
  6135. }
  6136. }
  6137. $otherFile = $form['otherFile']->getData();
  6138. if ($otherFile) {
  6139. $extension = $otherFile->guessExtension();
  6140. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6141. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6142. } else {
  6143. $fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
  6144. $otherFile->move(
  6145. $this->getParameter('documents_contracts_directory'),
  6146. $fileName
  6147. );
  6148. $contract->setOtherFile($fileName);
  6149. $em->flush();
  6150. }
  6151. }
  6152. $rib = $form['ribFile']->getData();
  6153. if ($rib) {
  6154. $extension = $rib->guessExtension();
  6155. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6156. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6157. } else {
  6158. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6159. $rib->move(
  6160. $this->getParameter('documents_contracts_directory'),
  6161. $fileName
  6162. );
  6163. $contract->setRibFile($fileName);
  6164. $em->flush();
  6165. }
  6166. }
  6167. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  6168. $contract->setSignDate(new \DateTime('now'));
  6169. $em->flush();
  6170. }
  6171. $this->get("session")->getFlashBag()->add("success", "Contrat modifié avec succès");
  6172. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6173. }
  6174. if ($request->query->get("backFromDocusign") && $request->query->get("event") == "Send") {
  6175. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
  6176. }
  6177. $signMember = $this->getContractSignMember($contract);
  6178. $creationWorkflow = $request->query->get('creation') === '1';
  6179. return $this->render("app/clients/contracts_form.html.twig", [
  6180. "form" => $form->createView(),
  6181. "contract" => $contract,
  6182. "title" => "Modifier un contrat",
  6183. "signMember" => $signMember,
  6184. 'creation_workflow' => $creationWorkflow,
  6185. ]);
  6186. }
  6187. /**
  6188. * @Route("/companies/{company}/contracts/{contract}/resiliation-email", name="companies_contracts_resiliation-email")
  6189. */
  6190. public function companiesContractsResiliationEmailAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, SendEmailService $sendEmailService, Pdf $knpSnappyPdf)
  6191. {
  6192. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6193. throw new NotFoundHttpException();
  6194. }
  6195. if (!$this->getUser()->getManager()->getAdmin()) {
  6196. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6197. throw new NotFoundHttpException();
  6198. }
  6199. }
  6200. if (isset($_POST["file_elec_content"])) {
  6201. $contract->setResiliationElecEmailContent($_POST["file_elec_content"]);
  6202. $em->flush();
  6203. // Génération du PDF
  6204. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_elec_content"]);
  6205. // Email
  6206. $content = <<<EOD
  6207. Bonjour,<br/>
  6208. <br/>
  6209. Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture d'électricité actuel.<br/>
  6210. <br/>
  6211. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  6212. <br/>
  6213. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6214. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  6215. <br/>
  6216. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6217. EOD;
  6218. $sendEmailService->send(
  6219. "Flash Énergie: Lettre de changement de fournisseur Electricité",
  6220. $contract->getCompany()->getEmail(),
  6221. 'emails/flash_default.html.twig',
  6222. [
  6223. "title" => "Lettre de changement de fournisseur",
  6224. "content" => $content
  6225. ],
  6226. 'resiliation@flash-consulting.fr',
  6227. null,
  6228. [
  6229. [
  6230. "content" => $pdf,
  6231. "name" => "courrier_de_changement_fournisseur_elec.pdf",
  6232. "contentType" => "application/pdf"
  6233. ]
  6234. ]
  6235. );
  6236. $contract->setResiliationElecEmailSendDate(new \DateTime('now'));
  6237. $em->flush();
  6238. } elseif (isset($_POST["file_gas_content"])) {
  6239. $contract->setResiliationGasEmailContent($_POST["file_gas_content"]);
  6240. $em->flush();
  6241. // Génération du PDF
  6242. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_gas_content"]);
  6243. // Email
  6244. $content = <<<EOD
  6245. Bonjour,<br/>
  6246. <br/>
  6247. Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture de gaz naturel actuel.<br/>
  6248. <br/>
  6249. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  6250. <br/>
  6251. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6252. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  6253. <br/>
  6254. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6255. EOD;
  6256. $sendEmailService->send(
  6257. "Flash Énergie: Lettre de changement de fournisseur Gaz",
  6258. $contract->getCompany()->getEmail(),
  6259. 'emails/flash_default.html.twig',
  6260. [
  6261. "title" => "Lettre de changement de fournisseur",
  6262. "content" => $content
  6263. ],
  6264. 'resiliation@flash-consulting.fr',
  6265. null,
  6266. [
  6267. [
  6268. "content" => $pdf,
  6269. "name" => "courrier_de_changement_fournisseur_gaz.pdf",
  6270. "contentType" => "application/pdf"
  6271. ]
  6272. ]
  6273. );
  6274. $contract->setResiliationGasEmailSendDate(new \DateTime('now'));
  6275. $em->flush();
  6276. } else {
  6277. $content = <<<EOD
  6278. Bonjour,<br/>
  6279. <br/>
  6280. Veuillez trouver ci-joint un modèle de courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat actuel.<br/>
  6281. <br/>
  6282. <i>Ce modèle est conçu pour vous aider à formaliser votre demande de résiliation conformément aux conditions de votre fournisseur d'énergie.</i><br/>
  6283. <br/>
  6284. De plus, nous avons également inclus <b>un guide</b> (voir pièces jointes) pour remplir le formulaire correctement.<br/>
  6285. <br/>
  6286. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6287. Cette démarche vous assurera une confirmation officielle de sa bonne réception. Il est impératif que vous gardiez une copie du courrier et que vous conserviez l'accusé de réception du recommandé.<br/>
  6288. <br/>
  6289. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6290. EOD;
  6291. $sendEmailService->send(
  6292. "Flash Énergie: Lettre de changement de fournisseur et son guide",
  6293. $contract->getCompany()->getEmail(),
  6294. 'emails/flash_default.html.twig',
  6295. [
  6296. "title" => "Lettre de changement de fournisseur et son guide",
  6297. "content" => $content
  6298. ],
  6299. 'resiliation@flash-consulting.fr',
  6300. [
  6301. $this->getParameter('assets_directory')."Lettre de resiliation.docx",
  6302. $this->getParameter('assets_directory')."Guide pour remplir sa lettre de resiliation.docx",
  6303. ]
  6304. );
  6305. if (isset($_GET["elec"])) {
  6306. $contract->setResiliationElecEmailSendDate(new \DateTime('now'));
  6307. }
  6308. if (isset($_GET["gas"])) {
  6309. $contract->setResiliationGasEmailSendDate(new \DateTime('now'));
  6310. }
  6311. $em->flush();
  6312. }
  6313. $this->get("session")->getFlashBag()->add("success", "L'email de changement de fournisseur a bien été envoyé");
  6314. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6315. }
  6316. /**
  6317. * @Route("/companies/{company}/contracts/{contract}/delete", name="companies_contracts_delete")
  6318. */
  6319. public function companiesContractsDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6320. {
  6321. if (!$this->getUser()->getManager()->getAdmin()) {
  6322. throw new UnauthorizedHttpException("Admin only");
  6323. }
  6324. $contract->setOfferElec(null);
  6325. $contract->setOfferGaz(null);
  6326. $em->flush();
  6327. $em->remove($contract);
  6328. $em->flush();
  6329. $this->get("session")->getFlashBag()->add("success", "Contrat supprimée");
  6330. return $this->redirectToRoute("manager_contracts", ["pro" => 1]);
  6331. }
  6332. /**
  6333. * @Route("/companies/{company}/contracts/{contract}/file", name="companies_contracts_file")
  6334. */
  6335. public function companiesContractsFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6336. {
  6337. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6338. throw new NotFoundHttpException();
  6339. }
  6340. if (!$this->getUser()->getManager()->getAdmin()) {
  6341. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6342. throw new NotFoundHttpException();
  6343. }
  6344. }
  6345. if ($contract->getFile()) {
  6346. return $this->getContractFile($contract, $request->get('mergeRib'));
  6347. }
  6348. throw new NotFoundHttpException();
  6349. }
  6350. /**
  6351. * @Route("/companies/{company}/contracts/{contract}/other-file", name="companies_contracts_other_file")
  6352. */
  6353. public function companiesContractsOtherFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6354. {
  6355. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6356. throw new NotFoundHttpException();
  6357. }
  6358. if (!$this->getUser()->getManager()->getAdmin()) {
  6359. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6360. throw new NotFoundHttpException();
  6361. }
  6362. }
  6363. if ($contract->getOtherFile()) {
  6364. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
  6365. return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6366. }
  6367. throw new NotFoundHttpException();
  6368. }
  6369. /**
  6370. * @Route("/companies/{company}/contracts/{contract}/rib", name="companies_contracts_rib")
  6371. */
  6372. public function companiesContractsRibAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6373. {
  6374. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6375. throw new NotFoundHttpException();
  6376. }
  6377. if (!$this->getUser()->getManager()->getAdmin()) {
  6378. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6379. throw new NotFoundHttpException();
  6380. }
  6381. }
  6382. if ($contract->getRibFile()) {
  6383. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6384. return $this->file($filePath, $contract->getRibFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6385. }
  6386. throw new NotFoundHttpException();
  6387. }
  6388. /**
  6389. * @Route("/companies/{company}/contracts/{contract}/rib-delete", name="companies_contracts_rib-delete")
  6390. */
  6391. public function companiesContractsRibDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6392. {
  6393. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6394. throw new NotFoundHttpException();
  6395. }
  6396. if (!$this->getUser()->getManager()->getAdmin()) {
  6397. throw new NotFoundHttpException();
  6398. }
  6399. $contract->setRibFile(null);
  6400. $em->flush();
  6401. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6402. }
  6403. /**
  6404. * @Route("/companies/{company}/contracts/{contract}/sign", name="companies_contracts_sign")
  6405. */
  6406. public function companiesContractsSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
  6407. {
  6408. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6409. throw new NotFoundHttpException();
  6410. }
  6411. if (!$this->getUser()->getManager()->getAdmin()) {
  6412. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6413. throw new NotFoundHttpException();
  6414. }
  6415. }
  6416. if (!$contract->getFile()) {
  6417. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  6418. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6419. } else if (!$contract->getState() || $contract->getState()->getId() != 3) {
  6420. $this->get("session")->getFlashBag()->add("danger", "Le statut du contrat doit être: Contrat en attente de signature");
  6421. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6422. } else {
  6423. return $this->sendContractFileToDocusign($contract, $docusignService, $em, true);
  6424. //return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6425. }
  6426. throw new NotFoundHttpException();
  6427. }
  6428. /**
  6429. * @Route("/companies/{company}/contracts/{contract}/other-file/sign", name="companies_contracts_other_file_sign")
  6430. */
  6431. public function companiesContractsOtherFileSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
  6432. {
  6433. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6434. throw new NotFoundHttpException();
  6435. }
  6436. if (!$this->getUser()->getManager()->getAdmin()) {
  6437. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6438. throw new NotFoundHttpException();
  6439. }
  6440. }
  6441. if (!$contract->getOtherFile()) {
  6442. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  6443. $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6444. } else {
  6445. return $this->sendContractOtherFileToDocusign($contract, $docusignService, $em, true);
  6446. //return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6447. }
  6448. throw new NotFoundHttpException();
  6449. }
  6450. private function getContractFile(Contract $contract, $mergeRib)
  6451. {
  6452. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
  6453. if ($mergeRib && $contract->getRibFile()) {
  6454. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6455. if (file_exists($fileRib)) {
  6456. $pdf = new FPDI();
  6457. $pagecount = $pdf->setSourceFile($filePath);
  6458. for($i=0; $i<$pagecount; $i++){
  6459. $pdf->AddPage();
  6460. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6461. $pdf->useTemplate($tplidx);
  6462. }
  6463. $pagecount = $pdf->setSourceFile($fileRib);
  6464. for($i=0; $i<$pagecount; $i++){
  6465. $pdf->AddPage();
  6466. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6467. $pdf->useTemplate($tplidx);
  6468. }
  6469. return $this->file($pdf->Output($contract->getFile(), 'I'), $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6470. }
  6471. }
  6472. return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6473. }
  6474. public function sendContractFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded)
  6475. {
  6476. $fileName = $contract->getFile();
  6477. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
  6478. $signMember = $this->getContractSignMember($contract);
  6479. // Création de la procédure
  6480. $procedureSign = new ProcedureSign();
  6481. if ($contract->getCompany()) {
  6482. $procedureSign->setUser($contract->getCompany()->getUser());
  6483. } else if ($contract->getUser()) {
  6484. $procedureSign->setUser($contract->getUser());
  6485. }
  6486. $procedureSign->setFirstName($signMember["firstName"]);
  6487. $procedureSign->setLastName($signMember["lastName"]);
  6488. $procedureSign->setEmail($signMember["email"]);
  6489. $procedureSign->setPhone($signMember["phone"]);
  6490. $procedureSign->setCreationDate(new \DateTime('now'));
  6491. $procedureSign->setNameFile($fileName);
  6492. $procedureSign->setFilePath($filePath);
  6493. $content = [
  6494. "type" => "contract.file",
  6495. "id" => $contract->getId()
  6496. ];
  6497. $procedureSign->setContent(json_encode($content));
  6498. $em->persist($procedureSign);
  6499. $em->flush();
  6500. /*
  6501. $fileCertificate = $this->getParameter('documents_fc_certificate');
  6502. if (file_exists($fileCertificate)) {
  6503. $pdf = new FPDI();
  6504. $pagecount = $pdf->setSourceFile($filePath);
  6505. for($i=0; $i<$pagecount; $i++){
  6506. $pdf->AddPage();
  6507. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6508. $pdf->useTemplate($tplidx);
  6509. }
  6510. // add RIB
  6511. if ($contract->getRibFile()) {
  6512. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6513. if (file_exists($fileRib)) {
  6514. $pagecount = $pdf->setSourceFile($fileRib);
  6515. for ($i = 0; $i < $pagecount; $i++) {
  6516. $pdf->AddPage();
  6517. $tplidx = $pdf->importPage($i + 1, '/MediaBox');
  6518. $pdf->useTemplate($tplidx);
  6519. }
  6520. }
  6521. }
  6522. // add certificate
  6523. $pagecount = $pdf->setSourceFile($fileCertificate);
  6524. for($i=0; $i<$pagecount; $i++){
  6525. $pdf->AddPage();
  6526. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6527. $pdf->useTemplate($tplidx);
  6528. }
  6529. $pdf->Output($filePath, 'F');
  6530. }
  6531. */
  6532. // Lancement de la signature
  6533. $accessToken = $docusignService->getAccessToken();
  6534. if ($accessToken) {
  6535. try {
  6536. if ($embedded) {
  6537. $response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
  6538. $procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
  6539. $em->flush();
  6540. return $this->redirect($response["url"]);
  6541. } else {
  6542. $response = $docusignService->sendFile($accessToken, $procedureSign);
  6543. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  6544. $em->flush();
  6545. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
  6546. return true;
  6547. }
  6548. } catch (ApiException $e) {
  6549. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6550. }
  6551. } else {
  6552. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6553. }
  6554. return false;
  6555. }
  6556. public function sendContractOtherFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded=false)
  6557. {
  6558. $fileName = $contract->getOtherFile();
  6559. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
  6560. $signMember = $this->getContractSignMember($contract);
  6561. // Création de la procédure
  6562. $procedureSign = new ProcedureSign();
  6563. if ($contract->getCompany()) {
  6564. $procedureSign->setUser($contract->getCompany()->getUser());
  6565. } else if ($contract->getUser()) {
  6566. $procedureSign->setUser($contract->getUser());
  6567. }
  6568. $procedureSign->setFirstName($signMember["firstName"]);
  6569. $procedureSign->setLastName($signMember["lastName"]);
  6570. $procedureSign->setEmail($signMember["email"]);
  6571. $procedureSign->setPhone($signMember["phone"]);
  6572. $procedureSign->setCreationDate(new \DateTime('now'));
  6573. $procedureSign->setNameFile($fileName);
  6574. $procedureSign->setFilePath($filePath);
  6575. $content = [
  6576. "type" => "contract.other-file",
  6577. "id" => $contract->getId()
  6578. ];
  6579. $procedureSign->setContent(json_encode($content));
  6580. $em->persist($procedureSign);
  6581. $em->flush();
  6582. // Création de la position
  6583. /*
  6584. $yousignPosition = new YousignPosition();
  6585. $yousignPosition->setPosition("209,16,395,180");
  6586. $yousignPosition->setReason("Signé par ".$company->getUser()->getFirstName().' '.$company->getUser()->getLastName());
  6587. $fileCertificate = $this->getParameter('documents_fc_certificate');
  6588. if (file_exists($fileCertificate)) {
  6589. $pdf = new FPDI();
  6590. $pagecount = $pdf->setSourceFile($filePath);
  6591. for($i=0; $i<$pagecount; $i++){
  6592. $pdf->AddPage();
  6593. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6594. $pdf->useTemplate($tplidx);
  6595. }
  6596. // add RIB
  6597. if ($contract->getRibFile()) {
  6598. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6599. if (file_exists($fileRib)) {
  6600. $pagecount = $pdf->setSourceFile($fileRib);
  6601. for ($i = 0; $i < $pagecount; $i++) {
  6602. $pdf->AddPage();
  6603. $tplidx = $pdf->importPage($i + 1, '/MediaBox');
  6604. $pdf->useTemplate($tplidx);
  6605. }
  6606. }
  6607. }
  6608. // add certificate
  6609. $pagecount = $pdf->setSourceFile($fileCertificate);
  6610. for($i=0; $i<$pagecount; $i++){
  6611. $pdf->AddPage();
  6612. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6613. $pdf->useTemplate($tplidx);
  6614. }
  6615. $pdf->Output($filePath, 'F');
  6616. }
  6617. $pdf = new FPDI();
  6618. $pagecount = $pdf->setSourceFile($filePath);
  6619. $yousignPosition->setPage($pagecount);
  6620. */
  6621. $accessToken = $docusignService->getAccessToken();
  6622. if ($accessToken) {
  6623. try {
  6624. if ($embedded) {
  6625. $response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
  6626. $procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
  6627. $em->flush();
  6628. return $this->redirect($response["url"]);
  6629. } else {
  6630. $response = $docusignService->sendFile($accessToken, $procedureSign);
  6631. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  6632. $em->flush();
  6633. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du fichier a été envoyé au client.");
  6634. return true;
  6635. }
  6636. } catch (ApiException $e) {
  6637. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6638. }
  6639. } else {
  6640. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6641. }
  6642. return false;
  6643. }
  6644. private function getContractSignMember(Contract $contrat)
  6645. {
  6646. if ($contrat->getCompany()) {
  6647. $firstName = $contrat->getCompany()->getUser()->getFirstName();
  6648. $lastName = $contrat->getCompany()->getUser()->getLastName();
  6649. $email = $contrat->getCompany()->getUser()->getEmail();
  6650. $phone = $contrat->getCompany()->getUser()->getPhone();
  6651. if ($contrat->getOfferElec() && $contrat->getOfferElec()->getCotation()) {
  6652. $firstName = $contrat->getOfferElec()->getCotation()->getFirstName();
  6653. $lastName = $contrat->getOfferElec()->getCotation()->getLastName();
  6654. $email = $contrat->getOfferElec()->getCotation()->getEmail();
  6655. $phone = $contrat->getOfferElec()->getCotation()->getPhone();
  6656. } else if ($contrat->getOfferGaz() && $contrat->getOfferGaz()->getCotation()) {
  6657. $firstName = $contrat->getOfferGaz()->getCotation()->getFirstName();
  6658. $lastName = $contrat->getOfferGaz()->getCotation()->getLastName();
  6659. $email = $contrat->getOfferGaz()->getCotation()->getEmail();
  6660. $phone = $contrat->getOfferGaz()->getCotation()->getPhone();
  6661. }
  6662. } else if ($contrat->getUser()) {
  6663. $firstName = $contrat->getUser()->getFirstName();
  6664. $lastName = $contrat->getUser()->getLastName();
  6665. $email = $contrat->getUser()->getEmail();
  6666. $phone = $contrat->getUser()->getPhone();
  6667. } else {
  6668. $firstName = "";
  6669. $lastName = "";
  6670. $email = "contact@flash-consulting.fr";
  6671. $phone = "";
  6672. }
  6673. return [
  6674. "firstName" => $firstName,
  6675. "lastName" => $lastName,
  6676. "email" => $email,
  6677. "phone" => $phone,
  6678. ];
  6679. }
  6680. /**
  6681. * @Route("/cotations", name="cotations")
  6682. */
  6683. public function cotationsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6684. {
  6685. $page = $request->get("page");
  6686. if (!is_numeric($page) || $page < 1) {
  6687. $page = 1;
  6688. }
  6689. $nbByPage = 20;
  6690. $keywords = null;
  6691. if ($request->get("search")) {
  6692. $terms = explode(" ", $request->get("search"));
  6693. if (count($terms)) {
  6694. $keywords = $terms;
  6695. }
  6696. }
  6697. if ($request->get("onlyInProgress")) {
  6698. if ($this->getUser()->getManager()->getAdmin()) {
  6699. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
  6700. } else {
  6701. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
  6702. }
  6703. $title = "Cotations monosites en cours";
  6704. } else {
  6705. if ($this->getUser()->getManager()->getAdmin()) {
  6706. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
  6707. } else {
  6708. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
  6709. }
  6710. $title = "Toutes les cotations monosites";
  6711. }
  6712. return $this->render("app/cotations/list.html.twig", [
  6713. "cotations_paginator" => $cotations_paginator,
  6714. "title" => $title,
  6715. ]);
  6716. }
  6717. /**
  6718. * @Route("/cotations-multisites", name="cotations-multisites")
  6719. */
  6720. public function cotationsMultisitesAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6721. {
  6722. $page = $request->get("page");
  6723. if (!is_numeric($page) || $page < 1) {
  6724. $page = 1;
  6725. }
  6726. $nbByPage = 20;
  6727. $keywords = null;
  6728. if ($request->get("search")) {
  6729. $terms = explode(" ", $request->get("search"));
  6730. if (count($terms)) {
  6731. $keywords = $terms;
  6732. }
  6733. }
  6734. if ($request->get("onlyInProgress")) {
  6735. if ($this->getUser()->getManager()->getAdmin()) {
  6736. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
  6737. } else {
  6738. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
  6739. }
  6740. $title = "Cotations multisites en cours";
  6741. } else {
  6742. if ($this->getUser()->getManager()->getAdmin()) {
  6743. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
  6744. } else {
  6745. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
  6746. }
  6747. $title = "Toutes les cotations multisites";
  6748. }
  6749. return $this->render("app/cotations-multisites/list.html.twig", [
  6750. "cotations_paginator" => $cotations_paginator,
  6751. "title" => $title,
  6752. ]);
  6753. }
  6754. /**
  6755. * @Route("/contracts", name="contracts")
  6756. */
  6757. public function contractsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6758. {
  6759. $page = $request->get("page");
  6760. if (!is_numeric($page) || $page < 1) {
  6761. $page = 1;
  6762. }
  6763. $nbByPage = 20;
  6764. $keywords = null;
  6765. if ($request->get("search")) {
  6766. $terms = explode(" ", $request->get("search"));
  6767. if (count($terms)) {
  6768. $keywords = $terms;
  6769. }
  6770. }
  6771. if ($request->get("particulier")) {
  6772. if ($this->getUser()->getManager()->getAdmin()) {
  6773. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, true, false);
  6774. } else {
  6775. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), true, false);
  6776. }
  6777. return $this->render("app/contracts/list.html.twig", [
  6778. "contracts_paginator" => $contracts_paginator,
  6779. "title" => "Contrats particuliers",
  6780. "pro" => false,
  6781. ]);
  6782. } elseif ($request->get("pro")) {
  6783. if ($this->getUser()->getManager()->getAdmin()) {
  6784. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true);
  6785. } else {
  6786. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), false, true);
  6787. }
  6788. return $this->render("app/contracts/list.html.twig", [
  6789. "contracts_paginator" => $contracts_paginator,
  6790. "title" => "Contrats professionnels",
  6791. "pro" => true,
  6792. ]);
  6793. }
  6794. throw new NotAcceptableHttpException();
  6795. }
  6796. /**
  6797. * @Route("/roadmaps", name="roadmaps")
  6798. */
  6799. public function roadmapsAction(Request $request, EntityManagerInterface $em)
  6800. {
  6801. $keywords = null;
  6802. if ($request->get("search")) {
  6803. $terms = explode(" ", $request->get("search"));
  6804. if (count($terms)) {
  6805. $keywords = $terms;
  6806. }
  6807. }
  6808. if ($request->get("onlyOpened")) {
  6809. if ($this->getUser()->getManager()->getAdmin()) {
  6810. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null, true);
  6811. } else {
  6812. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager(), true);
  6813. }
  6814. return $this->render("app/roadmaps/list.html.twig", [
  6815. "roadmaps" => $roadmaps,
  6816. "title" => "Feuilles de routes en cours",
  6817. ]);
  6818. } else {
  6819. if ($this->getUser()->getManager()->getAdmin()) {
  6820. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null);
  6821. } else {
  6822. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager());
  6823. }
  6824. return $this->render("app/roadmaps/list.html.twig", [
  6825. "roadmaps" => $roadmaps,
  6826. "title" => "Feuilles de routes",
  6827. ]);
  6828. }
  6829. }
  6830. /**
  6831. * @Route("/roadmaps/add", name="roadmaps_add")
  6832. */
  6833. public function roadmapsAddAction(Request $request, EntityManagerInterface $em)
  6834. {
  6835. $roadmap = new Roadmap();
  6836. $form = $this->createForm(RoadmapType::class, $roadmap);
  6837. $form->handleRequest($request);
  6838. if ($form->isSubmitted() && !$form->isValid()) {
  6839. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6840. }
  6841. if ($form->isSubmitted() && $form->isValid()) {
  6842. $roadmap->setCreationDate(new \DateTime("now"));
  6843. $roadmap->setManager($this->getUser()->getManager());
  6844. $em->persist($roadmap);
  6845. $em->flush();
  6846. $em->refresh($roadmap);
  6847. $file = $form['file']->getData();
  6848. if ($file) {
  6849. $extension = $file->guessExtension();
  6850. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6851. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6852. } else {
  6853. $fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6854. $file->move(
  6855. $this->getParameter('documents_justificatif_directory'),
  6856. $fileName
  6857. );
  6858. $roadmap->setFilePath($fileName);
  6859. $em->flush();
  6860. }
  6861. }
  6862. $this->get("session")->getFlashBag()->add("success", "Feuille de route ajoutée");
  6863. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6864. }
  6865. return $this->render("app/roadmaps/form.html.twig", [
  6866. "form" => $form->createView(),
  6867. "title" => "Ajouter une feuille de route",
  6868. "roadmap" => null,
  6869. ]);
  6870. }
  6871. /**
  6872. * @Route("/roadmaps/{id}/edit", name="roadmaps_edit")
  6873. */
  6874. public function roadmapEditAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6875. {
  6876. if (!$this->getUser()->getManager()->getAdmin()) {
  6877. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6878. throw new NotFoundHttpException();
  6879. }
  6880. }
  6881. if ($roadmap->getArchived()) {
  6882. throw new BadRequestHttpException("Archived");
  6883. }
  6884. $form = $this->createForm(RoadmapType::class, $roadmap);
  6885. $form->handleRequest($request);
  6886. if ($form->isSubmitted() && !$form->isValid()) {
  6887. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6888. }
  6889. if ($form->isSubmitted() && $form->isValid()) {
  6890. $em->flush();
  6891. $file = $form['file']->getData();
  6892. if ($file) {
  6893. $extension = $file->guessExtension();
  6894. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6895. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6896. } else {
  6897. $fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6898. $file->move(
  6899. $this->getParameter('documents_justificatif_directory'),
  6900. $fileName
  6901. );
  6902. $roadmap->setFilePath($fileName);
  6903. $em->flush();
  6904. }
  6905. }
  6906. $this->get("session")->getFlashBag()->add("success", "Feuille de route modifiée");
  6907. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6908. }
  6909. return $this->render("app/roadmaps/form.html.twig", [
  6910. "form" => $form->createView(),
  6911. "title" => "Modifier une feuille de route",
  6912. "roadmap" => $roadmap,
  6913. ]);
  6914. }
  6915. /**
  6916. * @Route("/roadmaps/{id}/file", name="roadmaps_file")
  6917. */
  6918. public function roadmapFileAction(Request $request, Roadmap $roadmap)
  6919. {
  6920. if (!$this->getUser()->getManager()->getAdmin()) {
  6921. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6922. throw new NotFoundHttpException();
  6923. }
  6924. }
  6925. if ($roadmap->getFilePath()) {
  6926. $filePath = $this->getParameter('documents_justificatif_directory') . $roadmap->getFilePath();
  6927. return $this->file($filePath, $roadmap->getFilePath(), ResponseHeaderBag::DISPOSITION_INLINE);
  6928. }
  6929. throw new NotFoundHttpException();
  6930. }
  6931. /**
  6932. * @Route("/roadmaps/{id}/file-delete", name="roadmaps_file-delete")
  6933. */
  6934. public function roadmapFileDeleteAction(Request $request, Roadmap $roadmap, EntityManagerInterface $em)
  6935. {
  6936. if (!$this->getUser()->getManager()->getAdmin()) {
  6937. throw new NotFoundHttpException();
  6938. }
  6939. $roadmap->setFilePath(null);
  6940. $em->flush();
  6941. return $this->redirectToRoute("manager_roadmaps_edit", ["id" => $roadmap->getId()]);
  6942. }
  6943. /**
  6944. * @Route("/roadmaps/{id}/delete", name="roadmaps_delete")
  6945. */
  6946. public function roadmapDeleteAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6947. {
  6948. if (!$this->getUser()->getManager()->getAdmin()) {
  6949. throw new UnauthorizedHttpException("Admin only");
  6950. }
  6951. $em->remove($roadmap);
  6952. $em->flush();
  6953. $this->get("session")->getFlashBag()->add("success", "Feuille de route supprimée");
  6954. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6955. }
  6956. /**
  6957. * @Route("/roadmaps/{id}/convert", name="roadmaps_convert")
  6958. */
  6959. public function roadmapConvertAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6960. {
  6961. if (!$this->getUser()->getManager()->getAdmin()) {
  6962. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6963. throw new NotFoundHttpException();
  6964. }
  6965. }
  6966. if ($roadmap->getArchived()) {
  6967. throw new BadRequestHttpException("Archived");
  6968. }
  6969. // On cherche les clients pro similaires
  6970. $keywords = explode(" ", $roadmap->getCompanyName());
  6971. $keywords[] = $roadmap->getLastName();
  6972. if ($this->getUser()->getManager()->getAdmin()) {
  6973. $users = $em->getRepository(User::class)->searchForTerms($keywords, null, false, true);
  6974. } else {
  6975. $users = $em->getRepository(User::class)->searchForTerms($keywords, $this->getUser()->getManager(), false, true);
  6976. }
  6977. return $this->render("app/roadmaps/convert.html.twig", [
  6978. "roadmap" => $roadmap,
  6979. "users" => $users,
  6980. ]);
  6981. }
  6982. /**
  6983. * @Route("/roadmaps/{id}/convert/{company}", name="roadmaps_convert_to_company")
  6984. * @ParamConverter("roadmap", options={"id" = "id"})
  6985. * @ParamConverter("company", options={"id" = "company"})
  6986. */
  6987. public function roadmapConvertUserAction(Roadmap $roadmap, Company $company, Request $request, EntityManagerInterface $em)
  6988. {
  6989. if (!$this->getUser()->getManager()->getAdmin()) {
  6990. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6991. throw new NotFoundHttpException();
  6992. }
  6993. }
  6994. if ($roadmap->getArchived()) {
  6995. throw new BadRequestHttpException("Archived");
  6996. }
  6997. $roadmap->setArchived(true);
  6998. $roadmap->setCompany($company);
  6999. if ($roadmap->getContractType()->getId() == 4) {
  7000. // Engie PRO
  7001. $this->roadmapEngieProToContract(
  7002. $roadmap,
  7003. $company,
  7004. true,
  7005. "",
  7006. null,
  7007. "",
  7008. new \DateTime('now'),
  7009. null,
  7010. "",
  7011. true,
  7012. "",
  7013. null,
  7014. "",
  7015. new \DateTime('now'),
  7016. null,
  7017. "",
  7018. $em
  7019. );
  7020. }
  7021. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 5) {
  7022. $this->roadmapTelecomToContract(
  7023. $roadmap,
  7024. $company,
  7025. "",
  7026. "",
  7027. false,
  7028. "",
  7029. $em
  7030. );
  7031. }
  7032. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 6) {
  7033. $this->roadmapPhotovoltaiqueToContract(
  7034. $roadmap,
  7035. $company,
  7036. "",
  7037. "",
  7038. "",
  7039. "",
  7040. "",
  7041. false,
  7042. $em
  7043. );
  7044. }
  7045. $em->flush();
  7046. $this->get("session")->getFlashBag()->add("success", "Feuille de route convertie");
  7047. return $this->redirectToRoute("manager_roadmaps");
  7048. }
  7049. /**
  7050. * @Route("/documents", name="documents")
  7051. */
  7052. public function documentsAction(Request $request, EntityManagerInterface $em)
  7053. {
  7054. if (!$this->getUser()->getManager()->getAdmin()) {
  7055. throw new NotFoundHttpException();
  7056. }
  7057. $keywords = null;
  7058. if ($request->get("search")) {
  7059. $terms = explode(" ", $request->get("search"));
  7060. if (count($terms)) {
  7061. $keywords = $terms;
  7062. }
  7063. }
  7064. $documents = $em->getRepository(Document::class)->searchForTerms($keywords);
  7065. return $this->render("app/documents/list.html.twig", [
  7066. "documents" => $documents,
  7067. ]);
  7068. }
  7069. /**
  7070. * @Route("/documents/add", name="documents_add")
  7071. */
  7072. public function documentsAddAction(Request $request, EntityManagerInterface $em)
  7073. {
  7074. if (!$this->getUser()->getManager()->getAdmin()) {
  7075. throw new NotFoundHttpException();
  7076. }
  7077. $document = new Document();
  7078. $form = $this->createForm(DocumentType::class, $document);
  7079. $form->handleRequest($request);
  7080. if ($form->isSubmitted() && !$form->isValid()) {
  7081. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7082. }
  7083. if ($form->isSubmitted() && $form->isValid()) {
  7084. $file = $form['file']->getData();
  7085. if ($file) {
  7086. $extension = $file->guessExtension();
  7087. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
  7088. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7089. } else {
  7090. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  7091. $relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
  7092. $relativePathFile = str_replace('/', '', $relativePathFile);
  7093. $file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
  7094. $document->setPath('/uploads/documents/' . $relativePathFile);
  7095. $document->setCreationDate(new \DateTime("now"));
  7096. $document->setVisible(true);
  7097. $document->setManager($this->getUser()->getManager());
  7098. $em->persist($document);
  7099. $em->flush();
  7100. $this->get("session")->getFlashBag()->add("success", "Document ajouté");
  7101. }
  7102. } else {
  7103. $this->get("session")->getFlashBag()->add("danger", "Impossible de télécharger ce document");
  7104. }
  7105. return $this->redirectToRoute("manager_documents");
  7106. }
  7107. return $this->render("app/documents/form.html.twig", [
  7108. "form" => $form->createView(),
  7109. "title" => "Ajouter un document à la boîte à outils"
  7110. ]);
  7111. }
  7112. /**
  7113. * @Route("/documents/{id}/edit", name="documents_edit")
  7114. */
  7115. public function documentsEditAction(Document $document, Request $request, EntityManagerInterface $em)
  7116. {
  7117. if (!$this->getUser()->getManager()->getAdmin()) {
  7118. throw new NotFoundHttpException();
  7119. }
  7120. $form = $this->createForm(DocumentType::class, $document);
  7121. $form->add('creationDate', DateType::class, [
  7122. "label" => "Date de publication",
  7123. 'widget' => 'single_text',
  7124. 'html5' => true,
  7125. ]);
  7126. $form->handleRequest($request);
  7127. if ($form->isSubmitted() && !$form->isValid()) {
  7128. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7129. }
  7130. if ($form->isSubmitted() && $form->isValid()) {
  7131. $file = $form['file']->getData();
  7132. if ($file) {
  7133. $extension = $file->guessExtension();
  7134. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
  7135. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7136. } else {
  7137. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  7138. $relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
  7139. $relativePathFile = str_replace('/', '', $relativePathFile);
  7140. $file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
  7141. $document->setPath('/uploads/documents/' . $relativePathFile);
  7142. }
  7143. }
  7144. $em->flush();
  7145. $this->get("session")->getFlashBag()->add("success", "Document modifié");
  7146. return $this->redirectToRoute("manager_documents");
  7147. }
  7148. return $this->render("app/documents/form.html.twig", [
  7149. "form" => $form->createView(),
  7150. "title" => "Modifier un document"
  7151. ]);
  7152. }
  7153. /**
  7154. * @Route("/documents/{id}/activate", name="documents_activate")
  7155. */
  7156. public function documentsActivateAction(Document $document, Request $request, EntityManagerInterface $em)
  7157. {
  7158. if (!$this->getUser()->getManager()->getAdmin()) {
  7159. throw new NotFoundHttpException();
  7160. }
  7161. $document->setVisible(true);
  7162. $em->flush();
  7163. $this->get("session")->getFlashBag()->add("success", "Document activé");
  7164. return $this->redirectToRoute("manager_documents");
  7165. }
  7166. /**
  7167. * @Route("/documents/{id}/desactivate", name="documents_desactivate")
  7168. */
  7169. public function documentsDesactivateAction(Document $document, Request $request, EntityManagerInterface $em)
  7170. {
  7171. if (!$this->getUser()->getManager()->getAdmin()) {
  7172. throw new NotFoundHttpException();
  7173. }
  7174. $document->setVisible(false);
  7175. $em->flush();
  7176. $this->get("session")->getFlashBag()->add("success", "Document désactivé");
  7177. return $this->redirectToRoute("manager_documents");
  7178. }
  7179. /**
  7180. * @Route("/documents/{id}/delete", name="documents_delete")
  7181. */
  7182. public function documentsDeleteAction(Document $document, Request $request, EntityManagerInterface $em)
  7183. {
  7184. if (!$this->getUser()->getManager()->getAdmin()) {
  7185. throw new NotFoundHttpException();
  7186. }
  7187. $em->remove($document);
  7188. $em->flush();
  7189. $this->get("session")->getFlashBag()->add("success", "Document supprimé");
  7190. return $this->redirectToRoute("manager_documents");
  7191. }
  7192. /**
  7193. * @Route("/managers", name="managers")
  7194. */
  7195. public function managersAction(Request $request, EntityManagerInterface $em)
  7196. {
  7197. if (!$this->getUser()->getManager()->getAdmin()) {
  7198. throw new NotFoundHttpException();
  7199. }
  7200. $accounts = $em->getRepository(Account::class)->findManagers();
  7201. return $this->render("app/managers/list.html.twig", [
  7202. "accounts" => $accounts,
  7203. ]);
  7204. }
  7205. /**
  7206. * @Route("/managers/add", name="managers_add")
  7207. */
  7208. public function managersAddAction(Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
  7209. {
  7210. if (!$this->getUser()->getManager()->getAdmin()) {
  7211. throw new NotFoundHttpException();
  7212. }
  7213. $manager = new Manager();
  7214. $form = $this->createForm(ManagerType::class, $manager);
  7215. $form->handleRequest($request);
  7216. if ($form->isSubmitted() && !$form->isValid()) {
  7217. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7218. }
  7219. if ($form->isSubmitted() && $form->isValid()) {
  7220. $error = false;
  7221. $accountEmail = $form["account_email"]->getData();
  7222. if (filter_var($accountEmail, FILTER_VALIDATE_EMAIL)) {
  7223. $other_account = $em->getRepository(Account::class)->findOneBy(['email' => $accountEmail]);
  7224. if ($other_account) {
  7225. $error = true;
  7226. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
  7227. }
  7228. } else {
  7229. $error = true;
  7230. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
  7231. }
  7232. if (!$error) {
  7233. $em->persist($manager);
  7234. $em->flush();
  7235. $account = new Account();
  7236. $account->setEmail($accountEmail);
  7237. $account->setEnabled($form["enabled"]->getData());
  7238. $account->setManager($manager);
  7239. $salt = md5(uniqid());
  7240. $pwd = $form['password']->getData();
  7241. $account->setSalt($salt);
  7242. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  7243. $account->setPassword($enc_pwd);
  7244. $account->setRegistrationDate(new \DateTime('now'));
  7245. $em->persist($account);
  7246. $em->flush();
  7247. $this->get('session')->getFlashBag()->add('success', 'Utilisateur créé avec succès');
  7248. return $this->redirectToRoute('manager_managers');
  7249. }
  7250. }
  7251. return $this->render('app/managers/form.html.twig', [
  7252. 'form' => $form->createView(),
  7253. 'title' => "Ajouter un utilisateur",
  7254. ]);
  7255. }
  7256. /**
  7257. * @Route("/managers/{id}/edit", name="managers_edit")
  7258. */
  7259. public function managersEditAction(Account $account, Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
  7260. {
  7261. if (!$this->getUser()->getManager()->getAdmin()) {
  7262. throw new NotFoundHttpException();
  7263. }
  7264. if (!$account->getManager()) {
  7265. throw new BadRequestHttpException();
  7266. }
  7267. $r_email = $account->getEmail();
  7268. $form = $this->createForm(ManagerType::class, $account->getManager());
  7269. $form["account_email"]->setData($account->getEmail());
  7270. $form["enabled"]->setData($account->getEnabled());
  7271. $form->handleRequest($request);
  7272. if ($form->isSubmitted() && !$form->isValid()) {
  7273. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7274. }
  7275. if ($form->isSubmitted() && $form->isValid()) {
  7276. $error = false;
  7277. $newEmail = $form["account_email"]->getData();
  7278. if ($r_email != $newEmail) {
  7279. if (filter_var($account->getEmail(), FILTER_VALIDATE_EMAIL)) {
  7280. $other_account = $em->getRepository(Account::class)->findOneBy(['email' => $newEmail]);
  7281. if ($other_account && $other_account->getId() != $account->getId()) {
  7282. $error = true;
  7283. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
  7284. }
  7285. } else {
  7286. $error = true;
  7287. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
  7288. }
  7289. }
  7290. if (!$error) {
  7291. $account->setEmail($newEmail);
  7292. $account->setEnabled($form["enabled"]->getData());
  7293. $em->flush();
  7294. if ($form['password']->getData()) {
  7295. $salt = md5(uniqid());
  7296. $pwd = $form['password']->getData();
  7297. $account->setSalt($salt);
  7298. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  7299. $account->setPassword($enc_pwd);
  7300. $em->flush();
  7301. }
  7302. $this->get('session')->getFlashBag()->add('success', 'Utilisateur modifié avec succès');
  7303. return $this->redirectToRoute('manager_managers_edit', ["id" => $account->getId()]);
  7304. }
  7305. }
  7306. return $this->render('app/managers/form.html.twig', [
  7307. 'form' => $form->createView(),
  7308. 'title' => "Modifier un utilisateur",
  7309. ]);
  7310. }
  7311. /**
  7312. * @Route("/flash-energie/notification", name="managers_flash-energie_notification")
  7313. */
  7314. public function managersFlashEnergieNotificationAction(Request $request, EntityManagerInterface $em)
  7315. {
  7316. if (!$this->getUser()->getManager()->getAdmin()) {
  7317. throw new NotFoundHttpException();
  7318. }
  7319. $form = $this->createFormBuilder()
  7320. ->add('title', TextType::class, [
  7321. 'attr' => [
  7322. 'placeholder' => 'Titre',
  7323. ],
  7324. 'label' => 'Titre de la notification',
  7325. 'required' => true,
  7326. 'mapped' => false,
  7327. ])
  7328. ->add('message', TextType::class, [
  7329. 'attr' => [
  7330. 'placeholder' => 'Message',
  7331. ],
  7332. 'label' => 'Message de la notification',
  7333. 'required' => true,
  7334. 'mapped' => false,
  7335. ])
  7336. ->add('sendAfter', DateTimeType::class, [
  7337. 'attr' => [
  7338. 'placeholder' => 'Date d\'envoi',
  7339. ],
  7340. 'label' => 'Date et heure d\'envoi',
  7341. 'required' => false,
  7342. 'mapped' => false,
  7343. ])->getForm();
  7344. $form->handleRequest($request);
  7345. if ($form->isSubmitted() && !$form->isValid()) {
  7346. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7347. }
  7348. if ($form->isSubmitted() && $form->isValid()) {
  7349. $title = $form['title']->getData();
  7350. $message = $form['message']->getData();
  7351. $sendAfter = $form['sendAfter']->getData();
  7352. $devices = $em->getRepository(Device::class)->findAll();
  7353. foreach ($devices as $device) {
  7354. $notification = new Notification();
  7355. $notification->setTitle($title);
  7356. $notification->setMessage($message);
  7357. $notification->setDevice($device);
  7358. if ($sendAfter) {
  7359. $notification->setSendAfter($sendAfter);
  7360. }
  7361. $em->persist($notification);
  7362. }
  7363. $em->flush();
  7364. $this->get('session')->getFlashBag()->add('success', 'L\'envoi de la notification a bien été programmé');
  7365. }
  7366. return $this->render('app/flash-energie/notifications/form.html.twig', [
  7367. 'form' => $form->createView(),
  7368. ]);
  7369. }
  7370. /**
  7371. * @Route("/flash-energie/offers-individual", name="managers_flash-energie_offers-individual")
  7372. */
  7373. public function managersFlashEnergieOffersIndividualAction(Request $request, EntityManagerInterface $em)
  7374. {
  7375. if (!$this->getUser()->getManager()->getAdmin()) {
  7376. throw new NotFoundHttpException();
  7377. }
  7378. $form = $this->createFormBuilder()
  7379. ->add('emplacement1', EntityType::class, [
  7380. "class" => OfferIndividual::class,
  7381. "label" => "Choix 1",
  7382. "required" => false,
  7383. 'query_builder' => function (EntityRepository $er) {
  7384. $qb = $er->createQueryBuilder('o');
  7385. $qb->where('o.type = \'ELEC\'');
  7386. return $qb;
  7387. },
  7388. 'choice_label' => function($offerInd) {
  7389. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7390. },
  7391. ])
  7392. ->add('emplacement2', EntityType::class, [
  7393. "class" => OfferIndividual::class,
  7394. "label" => "Choix 2",
  7395. "required" => false,
  7396. 'query_builder' => function (EntityRepository $er) {
  7397. $qb = $er->createQueryBuilder('o');
  7398. $qb->where('o.type = \'ELEC\'');
  7399. return $qb;
  7400. },
  7401. 'choice_label' => function($offerInd) {
  7402. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7403. },
  7404. ])
  7405. ->add('emplacement3', EntityType::class, [
  7406. "class" => OfferIndividual::class,
  7407. "label" => "Choix 3",
  7408. "required" => false,
  7409. 'query_builder' => function (EntityRepository $er) {
  7410. $qb = $er->createQueryBuilder('o');
  7411. $qb->where('o.type = \'ELEC\'');
  7412. return $qb;
  7413. },
  7414. 'choice_label' => function($offerInd) {
  7415. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7416. },
  7417. ])
  7418. ->add('emplacement4', EntityType::class, [
  7419. "class" => OfferIndividual::class,
  7420. "label" => "Choix 4",
  7421. "required" => false,
  7422. 'query_builder' => function (EntityRepository $er) {
  7423. $qb = $er->createQueryBuilder('o');
  7424. $qb->where('o.type = \'ELEC\'');
  7425. return $qb;
  7426. },
  7427. 'choice_label' => function($offerInd) {
  7428. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7429. },
  7430. ])
  7431. ->getForm();
  7432. $form['emplacement1']->setData($this->findOfferIndividuelByEmplacement("1", $em));
  7433. $form['emplacement2']->setData($this->findOfferIndividuelByEmplacement("2", $em));
  7434. $form['emplacement3']->setData($this->findOfferIndividuelByEmplacement("3", $em));
  7435. $form['emplacement4']->setData($this->findOfferIndividuelByEmplacement("4", $em));
  7436. $form->handleRequest($request);
  7437. if ($form->isSubmitted() && $form->isValid()) {
  7438. $emplacement1 = $form['emplacement1']->getData();
  7439. $this->setOfferIndividualEmplacement($emplacement1, "1", $em);
  7440. $emplacement2 = $form['emplacement2']->getData();
  7441. $this->setOfferIndividualEmplacement($emplacement2, "2", $em);
  7442. $emplacement3 = $form['emplacement3']->getData();
  7443. $this->setOfferIndividualEmplacement($emplacement3, "3", $em);
  7444. $emplacement4 = $form['emplacement4']->getData();
  7445. $this->setOfferIndividualEmplacement($emplacement4, "4", $em);
  7446. }
  7447. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7448. $offersGaz = $em->getRepository(OfferIndividual::class)->findBy(["type" => "GAZ"]);
  7449. $offersDual = $em->getRepository(OfferIndividual::class)->findBy(["type" => "DUAL"]);
  7450. return $this->render('app/flash-energie/offers-individual/list.html.twig', [
  7451. 'offersElec' => $offersElec,
  7452. 'offersGaz' => $offersGaz,
  7453. 'offersDual' => $offersDual,
  7454. 'form' => $form->createView(),
  7455. ]);
  7456. }
  7457. private function setOfferIndividualEmplacement(?OfferIndividual $offerIndividual, ?string $emplacement, EntityManagerInterface $em): void
  7458. {
  7459. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7460. foreach ($offersElec as $offer) {
  7461. $emplacements = explode(';', $offer->getEmplacements());
  7462. if ($offerIndividual) {
  7463. if ($offer->getId() == $offerIndividual->getId()) {
  7464. if (!in_array($emplacement, $emplacements)) {
  7465. $emplacements[] = $emplacement;
  7466. }
  7467. } else {
  7468. if (in_array($emplacement, $emplacements)) {
  7469. $emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
  7470. return $value !== $emplacement;
  7471. });
  7472. $emplacements = array_values($emplacements);
  7473. }
  7474. }
  7475. } else {
  7476. if (in_array($emplacement, $emplacements)) {
  7477. $emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
  7478. return $value !== $emplacement;
  7479. });
  7480. $emplacements = array_values($emplacements);
  7481. }
  7482. }
  7483. $offer->setEmplacements(implode(";", $emplacements));
  7484. }
  7485. $em->flush();
  7486. }
  7487. private function findOfferIndividuelByEmplacement(string $emplacement, EntityManagerInterface $em)
  7488. {
  7489. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7490. foreach ($offersElec as $offer) {
  7491. $emplacements = explode(';', $offer->getEmplacements());
  7492. if (in_array($emplacement, $emplacements)) {
  7493. return $offer;
  7494. }
  7495. }
  7496. return null;
  7497. }
  7498. /**
  7499. * @Route("/flash-energie/offers-individual/add", name="managers_flash-energie_offers-individual_add")
  7500. */
  7501. public function managersFlashEnergieOffersIndividualAddAction(Request $request, EntityManagerInterface $em)
  7502. {
  7503. if (!$this->getUser()->getManager()->getAdmin()) {
  7504. throw new NotFoundHttpException();
  7505. }
  7506. $offer = new OfferIndividual();
  7507. $form = $this->createForm(OfferIndividualType::class, $offer);
  7508. $form->handleRequest($request);
  7509. if ($form->isSubmitted() && !$form->isValid()) {
  7510. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7511. }
  7512. if ($form->isSubmitted() && $form->isValid()) {
  7513. $offer->setCreationDate(new \DateTime('now'));
  7514. $em->persist($offer);
  7515. $em->flush();
  7516. $this->get('session')->getFlashBag()->add('success', 'Offre ajoutée avec succès');
  7517. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7518. }
  7519. return $this->render('app/flash-energie/offers-individual/form.html.twig', [
  7520. 'offer' => $offer,
  7521. 'form' => $form->createView(),
  7522. ]);
  7523. }
  7524. /**
  7525. * @Route("/flash-energie/offers-individual/{id}/edit", name="managers_flash-energie_offers-individual_edit")
  7526. */
  7527. public function managersFlashEnergieOffersIndividualEditAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7528. {
  7529. if (!$this->getUser()->getManager()->getAdmin()) {
  7530. throw new NotFoundHttpException();
  7531. }
  7532. $form = $this->createForm(OfferIndividualType::class, $offer);
  7533. $form->handleRequest($request);
  7534. if ($form->isSubmitted() && !$form->isValid()) {
  7535. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7536. }
  7537. if ($form->isSubmitted() && $form->isValid()) {
  7538. $em->flush();
  7539. $this->get('session')->getFlashBag()->add('success', 'Offre modifiée avec succès');
  7540. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7541. }
  7542. return $this->render('app/flash-energie/offers-individual/form.html.twig', [
  7543. 'offer' => $offer,
  7544. 'form' => $form->createView(),
  7545. ]);
  7546. }
  7547. /**
  7548. * @Route("/flash-energie/offers-individual/{id}/active", name="managers_flash-energie_offers-individual_active")
  7549. */
  7550. public function managersFlashEnergieOffersIndividualActiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7551. {
  7552. if (!$this->getUser()->getManager()->getAdmin()) {
  7553. throw new NotFoundHttpException();
  7554. }
  7555. $offersByType = $em->getRepository(OfferIndividual::class)->findBy(["type" => $offer->getType()]);
  7556. foreach ($offersByType as $offer2) {
  7557. $offer2->setActive(false);
  7558. }
  7559. $offer->setActive(true);
  7560. $em->flush();
  7561. $this->get('session')->getFlashBag()->add('success', 'Offre activée avec succès');
  7562. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7563. }
  7564. /**
  7565. * @Route("/flash-energie/offers-individual/{id}/deactive", name="managers_flash-energie_offers-individual_deactive")
  7566. */
  7567. public function managersFlashEnergieOffersIndividualDeactiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7568. {
  7569. if (!$this->getUser()->getManager()->getAdmin()) {
  7570. throw new NotFoundHttpException();
  7571. }
  7572. $offer->setActive(false);
  7573. $em->flush();
  7574. $this->get('session')->getFlashBag()->add('success', 'Offre désactivée avec succès');
  7575. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7576. }
  7577. /**
  7578. * @Route("/docusign/connexion-api", name="managers_docusign_connexion-api")
  7579. */
  7580. public function managersDocusignConnexionApiAction(Request $request, DocusignService $docusignService)
  7581. {
  7582. if (!$this->getUser()->getManager()->getAdmin()) {
  7583. throw new NotFoundHttpException();
  7584. }
  7585. $connected = false;
  7586. $accessToken = $docusignService->getAccessToken();
  7587. if ($accessToken) {
  7588. $connected = true;
  7589. }
  7590. $form = $this->createFormBuilder()
  7591. ->add("email", TextType::class, [
  7592. 'label' => "Adresse e-mail",
  7593. 'required' => true,
  7594. ])
  7595. ->add("file", FileType::class, [
  7596. 'label' => "Fichier à signer",
  7597. 'required' => true,
  7598. ])
  7599. ->getForm();
  7600. $form->handleRequest($request);
  7601. if ($form->isSubmitted() && $form->isValid()) {
  7602. if ($accessToken) {
  7603. try {
  7604. $file = $form->get("file")->getData();
  7605. $procedureSign = new ProcedureSign();
  7606. $procedureSign->setFirstName("Test");
  7607. $procedureSign->setLastName("Flash");
  7608. $procedureSign->setEmail($form->get("email")->getData());
  7609. $procedureSign->setPhone("0600000000");
  7610. $procedureSign->setCreationDate(new \DateTime('now'));
  7611. $procedureSign->setNameFile($file->getClientOriginalName());
  7612. $procedureSign->setFilePath($file->getPathname());
  7613. $response = $docusignService->sendFile($accessToken, $procedureSign);
  7614. $this->get('session')->getFlashBag()->add('success', 'Document envoyé pour signature, réf: '.$response->getEnvelopeId());
  7615. } catch (ApiException $e) {
  7616. $this->get('session')->getFlashBag()->add('danger', 'L\'envoi a echoué');
  7617. var_dump($e);
  7618. }
  7619. }
  7620. }
  7621. return $this->render('app/docusign/connexion-api.html.twig', [
  7622. "connected" => $connected,
  7623. "authorizationURL" => $docusignService->getAuthorizationURL(),
  7624. "form" => $form->createView(),
  7625. ]);
  7626. }
  7627. /**
  7628. * @Route("/actions", name="actions")
  7629. */
  7630. public function managersActionsAction()
  7631. {
  7632. if (!$this->getUser()->getManager()->getAdmin()) {
  7633. throw new NotFoundHttpException();
  7634. }
  7635. return $this->render('app/actions/index.html.twig', [
  7636. ]);
  7637. }
  7638. /**
  7639. * @Route("/actions/affect-unaffected-cotations", name="actions_affect-unaffected-cotations")
  7640. */
  7641. public function managersActionsAffectUnaffectedCotationsAction(EntityManagerInterface $em)
  7642. {
  7643. if (!$this->getUser()->getManager()->getAdmin()) {
  7644. throw new NotFoundHttpException();
  7645. }
  7646. $unaffectedCotations = $em->getRepository(Cotation::class)->findBy(["manager" => null]);
  7647. $affected = 0;
  7648. foreach ($unaffectedCotations as $cotation) {
  7649. if ($cotation->getCompany() && $cotation->getCompany()->getUser() && $cotation->getCompany()->getUser()->getManager()) {
  7650. $cotation->setManager($cotation->getCompany()->getUser()->getManager());
  7651. $affected++;
  7652. }
  7653. }
  7654. $em->flush();
  7655. $this->get('session')->getFlashBag()->add('success', $affected.' cotation(s) affectée(s).');
  7656. return $this->redirectToRoute('manager_actions');
  7657. }
  7658. /**
  7659. * @Route("/actions/affect-unaffected-contracts", name="actions_affect-unaffected-contracts")
  7660. */
  7661. public function managersActionsAffectUnaffectedContractsAction(EntityManagerInterface $em)
  7662. {
  7663. if (!$this->getUser()->getManager()->getAdmin()) {
  7664. throw new NotFoundHttpException();
  7665. }
  7666. $unaffectedContracts = $em->getRepository(Contract::class)->findBy(["manager" => null]);
  7667. $affected = 0;
  7668. foreach ($unaffectedContracts as $contract) {
  7669. if ($contract->getCompany() && $contract->getCompany()->getUser() && $contract->getCompany()->getUser()->getManager()) {
  7670. $contract->setManager($contract->getCompany()->getUser()->getManager());
  7671. $affected++;
  7672. }
  7673. }
  7674. $em->flush();
  7675. $this->get('session')->getFlashBag()->add('success', $affected.' contrat(s) affecté(s).');
  7676. return $this->redirectToRoute('manager_actions');
  7677. }
  7678. /**
  7679. * @Route("/cotation-document/{id}/file", name="cotation-document_file")
  7680. */
  7681. public function cotationDocumentFileAction(Request $request, EntityManagerInterface $em, CotationDocument $cotationDocument)
  7682. {
  7683. if (!$this->getUser()->getManager()->getAdmin()) {
  7684. if ($cotationDocument->getCotation()->getCompany()->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$cotationDocument->getCotation()->getCompany()->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  7685. throw new NotFoundHttpException();
  7686. }
  7687. }
  7688. if ($cotationDocument->getPath()) {
  7689. $filePath = $this->getParameter('documents_justificatif_directory') . $cotationDocument->getPath();
  7690. return $this->file($filePath, $cotationDocument->getPath(), ResponseHeaderBag::DISPOSITION_INLINE);
  7691. }
  7692. throw new NotFoundHttpException();
  7693. }
  7694. /**
  7695. * @Route("/test-template", name="managers_test-template")
  7696. */
  7697. public function managersTestTemplateAction(Request $request, EntityManagerInterface $em, YousignService $yousignService)
  7698. {
  7699. if (!$this->getUser()->getManager()->getAdmin()) {
  7700. throw new NotFoundHttpException();
  7701. }
  7702. $form = $this->createFormBuilder()
  7703. ->add('supplier', EntityType::class, [
  7704. "class" => Supplier::class,
  7705. "label" => "Fournisseur",
  7706. "placeholder" => "Fournisseur",
  7707. "required" => true,
  7708. 'mapped' => false,
  7709. ])
  7710. ->add('file', FileType::class, [
  7711. "label" => "Fichier",
  7712. "required" => true,
  7713. 'mapped' => false,
  7714. ])
  7715. ->add('email', EmailType::class, [
  7716. 'attr' => [
  7717. 'placeholder' => 'Email',
  7718. ],
  7719. "data" => "david@slapp.me",
  7720. 'label' => 'Destinataire (email)',
  7721. 'required' => true,
  7722. 'mapped' => false,
  7723. ])
  7724. ->add('sepaIban', TextType::class, [
  7725. "label" => "IBAN",
  7726. "data" => "FR7611315000011234567890138",
  7727. "attr" => [
  7728. "placeholder" => "FR",
  7729. ],
  7730. "required" => false,
  7731. ])
  7732. ->add('sepaBic', TextType::class, [
  7733. "label" => "BIC",
  7734. "data" => "INGBFR18XXX",
  7735. "attr" => [
  7736. "placeholder" => "",
  7737. ],
  7738. "required" => false,
  7739. ])->getForm();
  7740. $form->handleRequest($request);
  7741. if ($form->isSubmitted() && !$form->isValid()) {
  7742. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7743. }
  7744. if ($form->isSubmitted() && $form->isValid()) {
  7745. $supplier = $form['supplier']->getData();
  7746. $file = $form['file']->getData();
  7747. $email = $form['email']->getData();
  7748. $sepaIban = $form['sepaIban']->getData();
  7749. $sepaBic = $form['sepaBic']->getData();
  7750. $extension = $file->guessExtension();
  7751. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  7752. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7753. return $this->render('app/test_template.html.twig', [
  7754. 'form' => $form->createView(),
  7755. ]);
  7756. }
  7757. $fileName = "test-template_" . md5(uniqid()) . '.' . $extension;
  7758. $file->move(
  7759. $this->getParameter('documents_justificatif_directory'),
  7760. $fileName
  7761. );
  7762. $filePath = $this->getParameter('documents_justificatif_directory').$fileName;
  7763. $cotation = $em->getRepository(Cotation::class)->find(26);
  7764. $company = $cotation->getCompany();
  7765. // Création de la procédure
  7766. $procedureSign = new ProcedureSign();
  7767. $procedureSign->setUser($cotation->getUser());
  7768. $procedureSign->setFirstName($cotation->getFirstName());
  7769. $procedureSign->setLastName($cotation->getLastName());
  7770. $procedureSign->setEmail($email);
  7771. $procedureSign->setPhone("0604176553");
  7772. $procedureSign->setCreationDate(new \DateTime('now'));
  7773. $procedureSign->setNameFile($fileName);
  7774. $procedureSign->setFilePath($filePath);
  7775. $content = [
  7776. "type" => "cotation.test",
  7777. "id" => $cotation->getId()
  7778. ];
  7779. $procedureSign->setContent(json_encode($content));
  7780. $em->persist($procedureSign);
  7781. $em->flush();
  7782. // Création de la position
  7783. $yousignPosition = new YousignPosition();
  7784. $yousignPosition->setReason("Signé par ".$cotation->getFirstName().' '.$cotation->getLastName());
  7785. $contract = new Contract();
  7786. $contract->setCompany($company);
  7787. $contract->setSepaBic($sepaBic);
  7788. $contract->setSepaIban($sepaIban);
  7789. $contract->setCity("Toulouse");
  7790. $contract->setPdlNumber("1234565432");
  7791. $contract->setElectricity(true);
  7792. $pdf = $yousignService->applyTemplate($yousignPosition, $filePath, $supplier->getCodeTemplate(), $contract);
  7793. // Lancement de la signature
  7794. /* $startSign = $yousignService->startSign($procedureSign, $yousignPosition);
  7795. if ($startSign) {
  7796. $this->get('session')->getFlashBag()->add('success', 'Top, c\'est envoyé !');
  7797. }*/
  7798. $pdf->Output($fileName,'I');
  7799. }
  7800. return $this->render('app/test_template.html.twig', [
  7801. 'form' => $form->createView(),
  7802. ]);
  7803. }
  7804. private function newContratForCompany(Company $company, EntityManagerInterface $em): Contract
  7805. {
  7806. $contract = new Contract();
  7807. $contract->setUser($company->getUser());
  7808. $contract->setCompany($company);
  7809. $contract->setAddress($company->getAddress());
  7810. $contract->setAddress2($company->getAddress2());
  7811. $contract->setZipCode($company->getZipCode());
  7812. $contract->setCity($company->getZipCode());
  7813. $contract->setManager($this->getUser()->getManager());
  7814. $contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
  7815. $contract->setState($contratStateEnAttenteClient);
  7816. return $contract;
  7817. }
  7818. private function roadmapEngieProToContract(
  7819. Roadmap $roadmap,
  7820. Company $company,
  7821. ?bool $elec,
  7822. ?string $powerSubscribed,
  7823. ?SituationGasElec $eSituation,
  7824. ?string $eSegment,
  7825. \DateTime $eCommitmentDate,
  7826. ?int $eDuree,
  7827. ?string $eOptEnergieVerte,
  7828. ?bool $gas,
  7829. ?string $quantityConsumed,
  7830. ?SituationGasElec $gSituation,
  7831. ?string $gSegment,
  7832. \DateTime $gCommitmentDate,
  7833. ?int $gDuree,
  7834. ?string $gOptEnergieVerte,
  7835. EntityManagerInterface $em)
  7836. {
  7837. $twoContracts = ($elec && $gas && $eCommitmentDate != $gCommitmentDate);
  7838. $contract = $this->newContratForCompany($company, $em);
  7839. $contract->setEngiePro(true);
  7840. if ($elec) {
  7841. $contract->setElectricity(true);
  7842. $contract->setPdlNumber($company->getPdlNumber());
  7843. $contract->setSubscribedKvaPower($powerSubscribed);
  7844. $contract->setElectricitySituation($eSituation);
  7845. $contract->setEffectiveDate($eCommitmentDate);
  7846. if ($eDuree && $eDuree > 0) {
  7847. $expiryDate = clone $eCommitmentDate;
  7848. $expiryDate->modify('+ '.$eDuree.' years');
  7849. $contract->setExpiryDate($expiryDate);
  7850. }
  7851. $contract->setEngieProESegment($eSegment);
  7852. $contract->setEngieProEOptEnergieVerte($eOptEnergieVerte);
  7853. }
  7854. if ($gas && $twoContracts) {
  7855. $em->persist($contract);
  7856. $em->flush();
  7857. $contract = $this->newContratForCompany($company, $em);
  7858. $contract->setEngiePro(true);
  7859. $contract->setEffectiveDate($gCommitmentDate);
  7860. if ($gDuree && $gDuree > 0) {
  7861. $expiryDate = clone $gCommitmentDate;
  7862. $expiryDate->modify('+ '.$gDuree.' years');
  7863. $contract->setExpiryDate($expiryDate);
  7864. }
  7865. }
  7866. if ($gas) {
  7867. $contract->setGas(true);
  7868. $contract->setPceNumber($company->getPceNumber());
  7869. $contract->setGasSituation($gSituation);
  7870. $contract->setGasMeterReadingM3($quantityConsumed);
  7871. $contract->setEngieProGSegment($gSegment);
  7872. $contract->setEngieProGOptEnergieVerte($gOptEnergieVerte);
  7873. }
  7874. $em->persist($contract);
  7875. $em->flush();
  7876. }
  7877. private function roadmapTelecomToContract(
  7878. Roadmap $roadmap,
  7879. Company $company,
  7880. ?string $offer,
  7881. ?string $duration,
  7882. ?bool $optionPremium,
  7883. ?string $rio,
  7884. EntityManagerInterface $em)
  7885. {
  7886. $contract = $this->newContratForCompany($company, $em);
  7887. $contract->setTelecom(true);
  7888. $contract->setTelecomOffer($offer);
  7889. $contract->setTelecomDuration($duration);
  7890. $contract->setTelecomOptionPremium($optionPremium);
  7891. $contract->setTelecomRio($rio);
  7892. $em->persist($contract);
  7893. $em->flush();
  7894. }
  7895. private function roadmapPhotovoltaiqueToContract(
  7896. Roadmap $roadmap,
  7897. Company $company,
  7898. ?string $buildintType,
  7899. ?string $buildingYear,
  7900. ?string $surface,
  7901. ?string $exposition,
  7902. ?string $mainMaterial,
  7903. ?bool $recentWork,
  7904. EntityManagerInterface $em)
  7905. {
  7906. $contract = $this->newContratForCompany($company, $em);
  7907. $contract->setPhotovoltaique(true);
  7908. $contract->setPhotovBuildingType($buildintType);
  7909. $contract->setPhotovBuildingYear($buildingYear);
  7910. $contract->setPhotovSurface($surface);
  7911. $contract->setPhotovExposition($exposition);
  7912. $contract->setPhotovMainMaterial($mainMaterial);
  7913. $contract->setPhotovRecentWork($recentWork);
  7914. $em->persist($contract);
  7915. $em->flush();
  7916. }
  7917. }