src/Controller/ManagerController.php line 607

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'=>14,'J'=>24,'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,
  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:L4')->setCellValue('A1', 'Informations clients');
  5429. $sheet->mergeCells('M1:O4')->setCellValue('M1', 'Informations cotations');
  5430. $sheet->mergeCells('P1:S4')->setCellValue('P1', 'Informations contrats ');
  5431. $sheet->mergeCells('T1:X4')->setCellValue('T1', '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' => 'Téléphone',
  5442. 'J5' => 'Email',
  5443. 'K5' => 'Code NAF',
  5444. 'L5' => 'Secteur client',
  5445. 'M5' => "Tenue de l'offre",
  5446. 'N5' => 'Note Ellipro',
  5447. 'O5' => 'Marge souhaitée POUR FLASH ',
  5448. 'P5' => 'Fournisseur actuel',
  5449. 'Q5' => 'Date de début de fourniture',
  5450. 'R5' => 'Date de fin de fourniture',
  5451. 'S5' => 'Nombre de mois à fournir',
  5452. 'T5' => 'PCE',
  5453. 'U5' => 'Adresse du site',
  5454. 'V5' => 'Profil',
  5455. 'W5' => "Tarif d'acheminement",
  5456. 'X5' => 'CAR (Mwh)',
  5457. ];
  5458. foreach ($labels as $cell => $text) {
  5459. [$col] = sscanf($cell, "%[A-Z]");
  5460. $sheet->mergeCells($col.'5:'.$col.'6');
  5461. $sheet->setCellValue($cell, $text);
  5462. }
  5463. // ---------- Styles ----------
  5464. $sheet->getStyle('A1:L4')->applyFromArray($boldCenter + $fillInfoClients + $mediumOutline);
  5465. $sheet->getStyle('M1:O4')->applyFromArray($boldCenter + $fillCotation + $mediumOutline);
  5466. $sheet->getStyle('P1:S4')->applyFromArray($boldCenter + $fillContrats + $mediumOutline);
  5467. $sheet->getStyle('T1:X4')->applyFromArray($boldCenter + $fillSites + $mediumOutline);
  5468. $sheet->getStyle('A5:X6')->applyFromArray($boldCenter + $fillHeader2 + $thinBorder);
  5469. $sheet->getStyle('A5:X6')->applyFromArray($mediumOutline);
  5470. $i = 7;
  5471. foreach ($cotation->getCotations() as $site) {
  5472. /** @var Cotation $site */
  5473. $sheet->getStyle('C' . $i)->getNumberFormat()->setFormatCode('0');
  5474. $sheet->getStyle('E' . $i)->getNumberFormat()->setFormatCode('0');
  5475. $sheet->getStyle('T' . $i)->getNumberFormat()->setFormatCode('0');
  5476. $sheet->setCellValue('A' . $i, $site->getName());
  5477. $sheet->setCellValue('B' . $i, $cotation->getCompanyName());
  5478. $sheet->setCellValue('C' . $i, $cotation->getSiret());
  5479. $sheet->setCellValue('D' . $i, $site->getCompanyName());
  5480. $sheet->setCellValue('E' . $i, $site->getSiret());
  5481. $sheet->setCellValue('F' . $i, $site->getFirstName() . ' ' . $site->getLastName());
  5482. $sheet->setCellValue('G' . $i, $site->getPosition());
  5483. $sheet->setCellValue('H' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
  5484. $sheet->setCellValue('I' . $i, $site->getPhone());
  5485. $sheet->setCellValue('J' . $i, $site->getEmail());
  5486. $sheet->setCellValue('K' . $i, $site->getApeCode());
  5487. $sheet->setCellValue('L' . $i, $site->getSector());
  5488. $sheet->setCellValue('M' . $i, $cotation->getTenueOffre());
  5489. $sheet->setCellValue('N' . $i, $site->getEliproNote());
  5490. $sheet->setCellValue('O' . $i, $site->getDesiredMargin());
  5491. $sheet->setCellValue('P' . $i, $site->getGasSupplier() ? $site->getGasSupplier()->getName() : "");
  5492. $sheet->setCellValue('Q' . $i, ($site->getGDesiredBegin())->format('Y-m-d'));
  5493. $sheet->setCellValue('R' . $i, ($site->getGDesiredEnd())->format('Y-m-d'));
  5494. $sheet->setCellValue('S' . $i, $site->getGNombreMois());
  5495. $sheet->setCellValue('T' . $i, $site->getGPce());
  5496. $sheet->setCellValue('U' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
  5497. $sheet->setCellValue('V' . $i, $site->getGProfil());
  5498. $sheet->setCellValue('W' . $i, $site->getGSegment());
  5499. $sheet->setCellValue('X' . $i, $site->getGCarMwh());
  5500. $i++;
  5501. }
  5502. $sheet->freezePane('A7');
  5503. $sheet->setSelectedCell("A7");
  5504. $writer = new Xlsx($spreadsheet);
  5505. $response = new StreamedResponse();
  5506. $response->setCallback(function () use ($writer) {
  5507. $writer->save('php://output');
  5508. });
  5509. $filenane = "excel-gaz_".$cotation->getCompanyName().'.xlsx';
  5510. $response->setStatusCode(200);
  5511. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5512. $response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
  5513. $response->headers->set('Cache-Control', 'max-age=0');
  5514. return $response;
  5515. }
  5516. /**
  5517. * @Route("/companies/{company}/cotations-multisites/{cotation}/offers", name="companies_cotations-multisites_offers")
  5518. */
  5519. public function companiesCotationsMultisitesOffersAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation)
  5520. {
  5521. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  5522. throw new NotFoundHttpException();
  5523. }
  5524. if (!$this->getUser()->getManager()->getAdmin()) {
  5525. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5526. throw new NotFoundHttpException();
  5527. }
  5528. }
  5529. $offersBySite = [];
  5530. foreach ($cotation->getCotations() as $site) {
  5531. $offers = [];
  5532. if ($cotation->getElectricity()) {
  5533. $offers = array_merge($offers, $em->getRepository(OfferElec::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
  5534. }
  5535. if ($cotation->getGas()) {
  5536. $offers = array_merge($offers, $em->getRepository(OfferGaz::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
  5537. }
  5538. $offersBySite[] = [
  5539. "site" => $site,
  5540. "offers" => $offers
  5541. ];
  5542. }
  5543. return $this->render("app/clients/cotations-multisites_offers.html.twig", [
  5544. "offersBySite" => $offersBySite,
  5545. "company" => $company,
  5546. "cotation" => $cotation,
  5547. ]);
  5548. }
  5549. /**
  5550. * @Route("/companies/{company}/cotations-multisites/{cotation}/offers/pdf", name="companies_cotations-multisites_offers_pdf")
  5551. */
  5552. public function companiesCotationsMultisitesOffersPdfAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, Pdf $knpSnappyPdf, OfferCalculatorService $offerCalculatorService)
  5553. {
  5554. if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
  5555. throw new NotFoundHttpException();
  5556. }
  5557. if (!$this->getUser()->getManager()->getAdmin()) {
  5558. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5559. throw new NotFoundHttpException();
  5560. }
  5561. }
  5562. $form = $this->createFormBuilder()->getForm();
  5563. if ($cotation->getElectricity()) {
  5564. $form->add("etude_solution_elec", ChoiceType::class, [
  5565. "expanded" => false,
  5566. "multiple" => false,
  5567. "choices" => [
  5568. "Prendre un prix unique composé de la totalité de ses droits d’ARENH" => "1",
  5569. "Prendre un prix unique composé d’un taux modéré de ses droits d'ARENH" => "2",
  5570. "Maintenir un prix unique composé d'un prix 100 % fixe" => "3",
  5571. "Prendre un horosaisonnalisé 100 % fixe (uniquement prix de marché)" => "4",
  5572. "Prendre un prix horosaisonnalisé composé d’un taux modéré de ses droits d'ARENH" => "5",
  5573. "Maintenir un prix horosaisonnalisé composé de la totalité de ses droits d’ARENH" => "6",
  5574. ],
  5575. "label" => "Choix de la solution ELEC",
  5576. ])
  5577. ->add("etude_commentaire_elec", TextType::class, [
  5578. "attr" => [
  5579. "placeholder" => ""
  5580. ],
  5581. "label" => "Commentaire ELEC",
  5582. "required" => false,
  5583. ]);
  5584. $form["etude_solution_elec"]->setData($cotation->getEtudeSolutionElec());
  5585. $form["etude_commentaire_elec"]->setData($cotation->getEtudeCommentaireElec());
  5586. }
  5587. if ($cotation->getGas()) {
  5588. $form->add("etude_solution_gaz", ChoiceType::class, [
  5589. "expanded" => false,
  5590. "multiple" => false,
  5591. "choices" => [
  5592. "Prendre un prix variable indexé sur le PEG" => "1",
  5593. "Maintenir un prix 100 % fixe" => "2",
  5594. ],
  5595. "label" => "Choix de la solution GAZ",
  5596. ])
  5597. ->add("etude_commentaire_gaz", TextType::class, [
  5598. "attr" => [
  5599. "placeholder" => ""
  5600. ],
  5601. "label" => "Commentaire GAZ",
  5602. "required" => false,
  5603. ]);
  5604. $form["etude_solution_gaz"]->setData($cotation->getEtudeSolutionGaz());
  5605. $form["etude_commentaire_gaz"]->setData($cotation->getEtudeCommentaireGaz());
  5606. }
  5607. $form->add("etude_type", ChoiceType::class, [
  5608. "expanded" => false,
  5609. "multiple" => false,
  5610. "choices" => [
  5611. "Site par site" => "1",
  5612. "Globale" => "2",
  5613. "Globale + Site par site" => "3",
  5614. ],
  5615. "label" => "Choix du type d'étude",
  5616. ]);
  5617. $sitesChoices = [
  5618. //"Tous" => "ALL",
  5619. ];
  5620. foreach ($cotation->getCotations() as $site) {
  5621. $sitesChoices[$site->getName()] = $site->getId();
  5622. }
  5623. $form->handleRequest($request);
  5624. if ($form->isSubmitted() && $form->isValid()) {
  5625. $offersElec = [];
  5626. $offersGas = [];
  5627. $cotationSite = [];
  5628. $supplierForSite = [
  5629. 'elec' => [],
  5630. 'gas' => [],
  5631. 'global' => [
  5632. 'consommationEstimation' => []
  5633. ]
  5634. ];
  5635. foreach ($sitesChoices as $siteName => $site) {
  5636. $cotationSiteElement = $em->getRepository(Cotation::class)->find($site);
  5637. if ($cotationSiteElement->getCotationMultisite() != $cotation) {
  5638. throw new BadRequestHttpException();
  5639. }
  5640. if ($cotationSiteElement->getElectricity()) {
  5641. $cotationSiteElement->setEtudeSolutionElec($form["etude_solution_elec"]->getData());
  5642. $cotationSiteElement->setEtudeCommentaireElec($form["etude_commentaire_elec"]->getData());
  5643. }
  5644. if ($cotationSiteElement->getGas()) {
  5645. $cotationSiteElement->setEtudeSolutionGaz($form["etude_solution_gaz"]->getData());
  5646. $cotationSiteElement->setEtudeCommentaireGaz($form["etude_commentaire_gaz"]->getData());
  5647. }
  5648. $em->flush();
  5649. $offerElecItem = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
  5650. $offersElec[$siteName] = $offerElecItem;
  5651. $offerGasItem = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
  5652. $offersGas[$siteName] = $offerGasItem;
  5653. //Create array with elec and gas key for supplier choice in a site or multiple site
  5654. foreach ($offersElec[$siteName] as $offer) {
  5655. $supplierName = $cotationSiteElement->getPreselectedOfferElec()?->getSupplier()->getName();
  5656. if (isset($supplierName)) {
  5657. //Re-create variable calculated in front twig in past
  5658. if ($offer->getCurrentOffer()) {
  5659. $supplierForSite['elec'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcElec($offer);
  5660. }
  5661. //Re-create variable calculated in front twig in past
  5662. if ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offer->getId()) {
  5663. $supplierForSite['elec'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcElec($offer);
  5664. }
  5665. // Get supplier infos to display in twig template like logo, name and description
  5666. $supplierForSite['elec'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferElec()->getSupplier();
  5667. }
  5668. }
  5669. //Create array with elec and gas key for supplier choice in a site or multiple site
  5670. foreach ($offersGas[$siteName] as $offer) {
  5671. $supplierName = $cotationSiteElement->getPreselectedOfferGaz()?->getSupplier()->getName();
  5672. if (isset($supplierName)) {
  5673. //Re-create variable calculated in front twig in past
  5674. if ($offer->getCurrentOffer()) {
  5675. $supplierForSite['gas'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcGaz($offer);
  5676. }
  5677. //Re-create variable calculated in front twig in past
  5678. if ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offer->getId()) {
  5679. $supplierForSite['gas'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcGaz($offer);
  5680. }
  5681. // Get supplier infos to display in twig template like logo, name and description
  5682. $supplierForSite['gas'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferGaz()->getSupplier();
  5683. }
  5684. }
  5685. $cotationSite[$siteName] = $cotationSiteElement;
  5686. foreach ($offerElecItem as $offerItem) {
  5687. $offerCalculated = $offerCalculatorService->calcElec($offerItem);
  5688. $keyGlobalResult = [
  5689. 'id',
  5690. 'htt_2024',
  5691. 'htt_2025',
  5692. 'htt_2026',
  5693. 'htt_2027',
  5694. 'htt_2028',
  5695. 'htt_2029',
  5696. 'ach_taxes_per_year',
  5697. 'moy_month',
  5698. 'total_ttc',
  5699. 'total_htt',
  5700. 'subscription',
  5701. 'capacite',
  5702. 'cee',
  5703. 'other_tax',
  5704. 'budget_before_ach',
  5705. 'acheminement',
  5706. 'cta',
  5707. 'cspe',
  5708. 'cspe_index',
  5709. 'total_ttc',
  5710. ];
  5711. if ($offerItem->getCurrentOffer()) {
  5712. $type = 'actualOffer';
  5713. } elseif ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offerItem->getId()) {
  5714. $type = 'currentOffer';
  5715. }
  5716. if (isset($type)) {
  5717. foreach ($keyGlobalResult as $key) {
  5718. if (!isset($supplierForSite['global'][$type][$key])) {
  5719. $supplierForSite['global'][$type][$key] = 0;
  5720. }
  5721. $supplierForSite['global'][$type][$key] += $offerCalculated[$key];
  5722. }
  5723. if ($type === 'actualOffer') {
  5724. $consommationKeyArray = [
  5725. 'carAdditional',
  5726. 'carAverage',
  5727. 'kvaAdditional',
  5728. 'kvaAverage'
  5729. ];
  5730. $consommationSubKeyArray = [
  5731. 'pointe',
  5732. 'hph',
  5733. 'hch',
  5734. 'hpe',
  5735. 'hce',
  5736. ];
  5737. foreach ($consommationKeyArray as $consommationKey) {
  5738. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
  5739. $supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
  5740. }
  5741. foreach ($consommationSubKeyArray as $consommationSubKey) {
  5742. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
  5743. $supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
  5744. }
  5745. }
  5746. }
  5747. $supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] += $cotationSiteElement->getEConsommationPointe();
  5748. $supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] += $cotationSiteElement->getEConsommationHph();
  5749. $supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] += $cotationSiteElement->getEConsommationHch();
  5750. $supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] += $cotationSiteElement->getEConsommationHpe();
  5751. $supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] += $cotationSiteElement->getEConsommationHce();
  5752. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] += $cotationSiteElement->getEPuissanceKvaPointe();
  5753. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] += $cotationSiteElement->getEPuissanceKvaHph();
  5754. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] += $cotationSiteElement->getEPuissanceKvaHch();
  5755. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] += $cotationSiteElement->getEPuissanceKvaHpe();
  5756. $supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] += $cotationSiteElement->getEPuissanceKvaHce();
  5757. }
  5758. $offerAnalysisAndDetailsKeyArray = [
  5759. 'pointe_price',
  5760. 'base_price',
  5761. 'hp_price',
  5762. 'hc_price',
  5763. 'hph_price',
  5764. 'hch_price',
  5765. 'hpe_price',
  5766. 'hce_price',
  5767. ];
  5768. foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
  5769. if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
  5770. if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
  5771. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
  5772. }
  5773. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
  5774. }
  5775. }
  5776. unset($type);
  5777. }
  5778. }
  5779. foreach ($offerGasItem as $offerItem) {
  5780. $offerCalculated = $offerCalculatorService->calcGaz($offerItem);
  5781. $keyGlobalResult = [
  5782. 'id',
  5783. 'htt_2024',
  5784. 'htt_2025',
  5785. 'htt_2026',
  5786. 'htt_2027',
  5787. 'htt_2028',
  5788. 'htt_2029',
  5789. 'ach_taxes_per_year',
  5790. 'moy_month',
  5791. 'total_ttc',
  5792. 'total_htt',
  5793. 'subscription',
  5794. 'cee',
  5795. 'other_tax',
  5796. 'budget_before_ach',
  5797. 'acheminement',
  5798. 'cta',
  5799. 'total_ttc',
  5800. 'fourniture',
  5801. 'budget_fourniture',
  5802. ];
  5803. if ($offerItem->getCurrentOffer()) {
  5804. $type = 'actualOffer';
  5805. } elseif ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offerItem->getId()) {
  5806. $type = 'currentOffer';
  5807. }
  5808. if (isset($type)) {
  5809. foreach ($keyGlobalResult as $key) {
  5810. if (!isset($supplierForSite['global'][$type][$key])) {
  5811. $supplierForSite['global'][$type][$key] = 0;
  5812. }
  5813. $supplierForSite['global'][$type][$key] += $offerCalculated[$key];
  5814. }
  5815. if ($type === 'actualOffer') {
  5816. $consommationKeyArray = [
  5817. 'carAdditional',
  5818. 'carAverage',
  5819. ];
  5820. $consommationSubKeyArray = [
  5821. 'total'
  5822. ];
  5823. foreach ($consommationKeyArray as $consommationKey) {
  5824. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
  5825. $supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
  5826. }
  5827. foreach ($consommationSubKeyArray as $consommationSubKey) {
  5828. if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
  5829. $supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
  5830. }
  5831. }
  5832. }
  5833. $supplierForSite['global']['consommationEstimation']['carAdditional']['total'] += $cotationSiteElement->getGCarMwh();
  5834. }
  5835. $offerAnalysisAndDetailsKeyArray = [
  5836. 'fourniture',
  5837. 'budget_fourniture',
  5838. ];
  5839. foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
  5840. if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
  5841. if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
  5842. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
  5843. }
  5844. $supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
  5845. }
  5846. }
  5847. unset($type);
  5848. }
  5849. }
  5850. }
  5851. if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['total'])) {
  5852. $supplierForSite['global']['consommationEstimation']['carAverage']['total'] = $supplierForSite['global']['consommationEstimation']['carAdditional']['total'] / count($sitesChoices);
  5853. }
  5854. $roundPrecision = 3;
  5855. if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'])) {
  5856. $supplierForSite['global']['consommationEstimation']['carAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
  5857. $supplierForSite['global']['consommationEstimation']['carAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] / count($sitesChoices), $roundPrecision);
  5858. $supplierForSite['global']['consommationEstimation']['carAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] / count($sitesChoices), $roundPrecision);
  5859. $supplierForSite['global']['consommationEstimation']['carAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
  5860. $supplierForSite['global']['consommationEstimation']['carAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] / count($sitesChoices), $roundPrecision);
  5861. $supplierForSite['global']['consommationEstimation']['kvaAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
  5862. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] / count($sitesChoices), $roundPrecision);
  5863. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] / count($sitesChoices), $roundPrecision);
  5864. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
  5865. $supplierForSite['global']['consommationEstimation']['kvaAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] / count($sitesChoices), $roundPrecision);
  5866. }
  5867. $html = $this->renderView('app/pdf/presentation-budget/section1.html.twig', [
  5868. "offersElec" => $offersElec,
  5869. "offersGas" => $offersGas,
  5870. 'cotation' => $cotationSite,
  5871. 'multisite' => true,
  5872. 'array_site' => $sitesChoices,
  5873. 'supplierChoiceForMultiSite' => $supplierForSite,
  5874. "etude_type" => $form['etude_type']->getData() ?? 0
  5875. ]);
  5876. $pdf = $knpSnappyPdf->getOutputFromHtml($html, array(
  5877. 'orientation' => 'landscape',
  5878. 'no-stop-slow-scripts' => true,
  5879. 'no-background' => false,
  5880. 'lowquality' => false,
  5881. 'page-height' => 340,
  5882. 'page-width' => 200,
  5883. 'encoding' => 'utf-8',
  5884. 'images' => true,
  5885. 'cookie' => array(),
  5886. 'dpi' => 300,
  5887. 'enable-external-links' => true,
  5888. 'enable-internal-links' => true,
  5889. 'margin-bottom' => 0
  5890. ));
  5891. return new Response($pdf,200,array(
  5892. 'Content-Type' => 'application/pdf',
  5893. 'Content-Disposition' => 'inline; filename="Flash-Presentation_budget.pdf"'
  5894. ));
  5895. /*
  5896. return new PdfResponse(
  5897. $knpSnappyPdf->getOutputFromHtml($html),
  5898. 'Flash-Presentation_budget.pdf'
  5899. );
  5900. */
  5901. }
  5902. return $this->render("app/clients/cotation_offers_pdf.html.twig", [
  5903. "form" => $form->createView(),
  5904. "cotation" => $cotation,
  5905. "multisite" => true,
  5906. ]);
  5907. }
  5908. /**
  5909. * @Route("/companies/{company}/contracts", name="companies_contracts")
  5910. */
  5911. public function companiesContractsAction(Request $request, EntityManagerInterface $em, Company $company)
  5912. {
  5913. if (!$this->getUser()->getManager()->getAdmin()) {
  5914. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5915. throw new NotFoundHttpException();
  5916. }
  5917. }
  5918. $contracts = $em->getRepository(Contract::class)->findBy(["company" => $company], ["expiryDate" => "DESC"]);
  5919. return $this->render("app/clients/contracts.html.twig", [
  5920. "company" => $company,
  5921. "contracts" => $contracts,
  5922. ]);
  5923. }
  5924. /**
  5925. * @Route("/companies/{company}/contracts/add", name="companies_contracts_add")
  5926. */
  5927. public function companiesContractsAddAction(Request $request, EntityManagerInterface $em, Company $company)
  5928. {
  5929. if (!$this->getUser()->getManager()->getAdmin()) {
  5930. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  5931. throw new NotFoundHttpException();
  5932. }
  5933. }
  5934. $contract = new Contract();
  5935. $contract->setCompany($company);
  5936. $form = $this->createForm(ContractType::class, $contract);
  5937. $form->add('contractType', EntityType::class, [
  5938. 'class' => \App\Entity\ContractType::class,
  5939. 'query_builder' => function (EntityRepository $er) {
  5940. return $er->createQueryBuilder('t')
  5941. ->where('t.active = TRUE')
  5942. ->orderBy('t.label', 'ASC');
  5943. },
  5944. 'choice_label' => 'label',
  5945. 'label' => 'Type de contrat',
  5946. 'required' => true,
  5947. 'mapped' => false,
  5948. ]);
  5949. $form["sepaIban"]->setData($company->getSepaIban());
  5950. $form["sepaBic"]->setData($company->getSepaBic());
  5951. $form->handleRequest($request);
  5952. if ($form->isSubmitted() && !$form->isValid()) {
  5953. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  5954. }
  5955. if ($form->isSubmitted() && $form->isValid()) {
  5956. $contract->setManager($this->getUser()->getManager());
  5957. $em->persist($contract);
  5958. $em->flush();
  5959. $file = $form['file']->getData();
  5960. if ($file) {
  5961. $extension = $file->guessExtension();
  5962. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5963. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5964. } else {
  5965. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5966. $file->move(
  5967. $this->getParameter('documents_contracts_directory'),
  5968. $fileName
  5969. );
  5970. $contract->setFile($fileName);
  5971. $em->flush();
  5972. }
  5973. }
  5974. $otherFile = $form['otherFile']->getData();
  5975. if ($otherFile) {
  5976. $extension = $otherFile->guessExtension();
  5977. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5978. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5979. } else {
  5980. $fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
  5981. $otherFile->move(
  5982. $this->getParameter('documents_contracts_directory'),
  5983. $fileName
  5984. );
  5985. $contract->setOtherFile($fileName);
  5986. $em->flush();
  5987. }
  5988. }
  5989. $rib = $form['ribFile']->getData();
  5990. if ($rib) {
  5991. $extension = $rib->guessExtension();
  5992. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  5993. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  5994. } else {
  5995. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  5996. $rib->move(
  5997. $this->getParameter('documents_contracts_directory'),
  5998. $fileName
  5999. );
  6000. $contract->setRibFile($fileName);
  6001. $em->flush();
  6002. }
  6003. }
  6004. if ($form['contractType']->getData()) {
  6005. switch ($form['contractType']->getData()->getId()) {
  6006. case 1:
  6007. $contract->setGas(true);
  6008. break;
  6009. case 2:
  6010. $contract->setElectricity(true);
  6011. break;
  6012. case 3:
  6013. //$contract->setGas(true);
  6014. //$contract->setElectricity(true);
  6015. break;
  6016. case 4:
  6017. $contract->setEngiePro(true);
  6018. break;
  6019. case 5:
  6020. $contract->setTelecom(true);
  6021. break;
  6022. case 6:
  6023. $contract->setPhotovoltaique(true);
  6024. break;
  6025. }
  6026. $em->flush();
  6027. }
  6028. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  6029. $contract->setSignDate(new \DateTime('now'));
  6030. $em->flush();
  6031. }
  6032. $this->get("session")->getFlashBag()->add("success", "Contrat ajouté avec succès");
  6033. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId(), "creation" => 1]);
  6034. }
  6035. return $this->render("app/clients/contracts_form.html.twig", [
  6036. "form" => $form->createView(),
  6037. "contract" => $contract,
  6038. "title" => "Ajouter un contrat",
  6039. ]);
  6040. }
  6041. /**
  6042. * @Route("/companies/{company}/contracts/{contract}/edit", name="companies_contracts_edit")
  6043. */
  6044. public function companiesContractsEditAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, YousignService $yousignService)
  6045. {
  6046. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6047. throw new NotFoundHttpException();
  6048. }
  6049. if (!$this->getUser()->getManager()->getAdmin()) {
  6050. if ($contract->getManager()->getId() != $this->getUser()->getManager()->getId() && !$contract->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6051. throw new NotFoundHttpException();
  6052. }
  6053. }
  6054. if (isset($_GET["proof"]) && $contract->getProcedureYousignId()) {
  6055. $zipBase64 = $yousignService->getProcedureProof($contract->getProcedureYousignId());
  6056. if ($zipBase64) {
  6057. $zip = base64_decode($zipBase64);
  6058. $response = new Response($zip);
  6059. $response->headers->set('Content-Type', 'application/zip');
  6060. $response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
  6061. $response->headers->set('Content-length', strlen($zip));
  6062. return $response;
  6063. }
  6064. }
  6065. if (isset($_GET["proof-other"]) && $contract->getOtherFileProcedureYousignId()) {
  6066. $zipBase64 = $yousignService->getProcedureProof($contract->getOtherFileProcedureYousignId());
  6067. if ($zipBase64) {
  6068. $zip = base64_decode($zipBase64);
  6069. $response = new Response($zip);
  6070. $response->headers->set('Content-Type', 'application/zip');
  6071. $response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
  6072. $response->headers->set('Content-length', strlen($zip));
  6073. return $response;
  6074. }
  6075. }
  6076. $form = $this->createForm(ContractType::class, $contract);
  6077. if ($this->getUser()->getManager()->getAdmin()) {
  6078. $form->add('manager', EntityType::class, [
  6079. "label" => "Commercial associé",
  6080. 'class' => Manager::class,
  6081. 'query_builder' => function (EntityRepository $er) {
  6082. return $er->createQueryBuilder('m')
  6083. ->leftJoin("m.account", "a")
  6084. ->where('a.enabled = true');
  6085. },
  6086. 'choice_label' => 'fullName',
  6087. 'attr' => [
  6088. "data-control" => "select2",
  6089. ],
  6090. "required" => false,
  6091. "mapped" => true,
  6092. ]);
  6093. $form["manager"]->setData($contract->getManager());
  6094. } elseif ($contract->getManager()->isSupervisedBy($this->getUser()->getManager()) || ($contract->getManager() === $this->getUser()->getManager())) {
  6095. $form->add('manager', EntityType::class, [
  6096. "label" => "Commercial associé",
  6097. 'class' => Manager::class,
  6098. 'query_builder' => function (EntityRepository $er) {
  6099. return $er->createQueryBuilder('m')
  6100. ->leftJoin("m.account", "a")
  6101. ->where('a.enabled = true')
  6102. ->andWhere('(:manager MEMBER OF m.supervisors OR :manager = m)')
  6103. ->setParameter('manager', $this->getUser()->getManager());
  6104. },
  6105. 'choice_label' => 'fullName',
  6106. 'attr' => [
  6107. "data-control" => "select2",
  6108. ],
  6109. "required" => false,
  6110. "mapped" => true,
  6111. ]);
  6112. $form["manager"]->setData($contract->getManager());
  6113. }
  6114. $form->handleRequest($request);
  6115. if ($form->isSubmitted() && !$form->isValid()) {
  6116. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6117. }
  6118. if ($form->isSubmitted() && $form->isValid()) {
  6119. $em->flush();
  6120. $file = $form['file']->getData();
  6121. if ($file) {
  6122. $extension = $file->guessExtension();
  6123. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6124. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6125. } else {
  6126. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6127. $file->move(
  6128. $this->getParameter('documents_contracts_directory'),
  6129. $fileName
  6130. );
  6131. $contract->setFile($fileName);
  6132. $em->flush();
  6133. }
  6134. }
  6135. $otherFile = $form['otherFile']->getData();
  6136. if ($otherFile) {
  6137. $extension = $otherFile->guessExtension();
  6138. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6139. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6140. } else {
  6141. $fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
  6142. $otherFile->move(
  6143. $this->getParameter('documents_contracts_directory'),
  6144. $fileName
  6145. );
  6146. $contract->setOtherFile($fileName);
  6147. $em->flush();
  6148. }
  6149. }
  6150. $rib = $form['ribFile']->getData();
  6151. if ($rib) {
  6152. $extension = $rib->guessExtension();
  6153. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6154. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6155. } else {
  6156. $fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6157. $rib->move(
  6158. $this->getParameter('documents_contracts_directory'),
  6159. $fileName
  6160. );
  6161. $contract->setRibFile($fileName);
  6162. $em->flush();
  6163. }
  6164. }
  6165. if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
  6166. $contract->setSignDate(new \DateTime('now'));
  6167. $em->flush();
  6168. }
  6169. $this->get("session")->getFlashBag()->add("success", "Contrat modifié avec succès");
  6170. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6171. }
  6172. if ($request->query->get("backFromDocusign") && $request->query->get("event") == "Send") {
  6173. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
  6174. }
  6175. $signMember = $this->getContractSignMember($contract);
  6176. $creationWorkflow = $request->query->get('creation') === '1';
  6177. return $this->render("app/clients/contracts_form.html.twig", [
  6178. "form" => $form->createView(),
  6179. "contract" => $contract,
  6180. "title" => "Modifier un contrat",
  6181. "signMember" => $signMember,
  6182. 'creation_workflow' => $creationWorkflow,
  6183. ]);
  6184. }
  6185. /**
  6186. * @Route("/companies/{company}/contracts/{contract}/resiliation-email", name="companies_contracts_resiliation-email")
  6187. */
  6188. public function companiesContractsResiliationEmailAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, SendEmailService $sendEmailService, Pdf $knpSnappyPdf)
  6189. {
  6190. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6191. throw new NotFoundHttpException();
  6192. }
  6193. if (!$this->getUser()->getManager()->getAdmin()) {
  6194. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6195. throw new NotFoundHttpException();
  6196. }
  6197. }
  6198. if (isset($_POST["file_elec_content"])) {
  6199. $contract->setResiliationElecEmailContent($_POST["file_elec_content"]);
  6200. $em->flush();
  6201. // Génération du PDF
  6202. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_elec_content"]);
  6203. // Email
  6204. $content = <<<EOD
  6205. Bonjour,<br/>
  6206. <br/>
  6207. Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture d'électricité actuel.<br/>
  6208. <br/>
  6209. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  6210. <br/>
  6211. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6212. 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/>
  6213. <br/>
  6214. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6215. EOD;
  6216. $sendEmailService->send(
  6217. "Flash Énergie: Lettre de changement de fournisseur Electricité",
  6218. $contract->getCompany()->getEmail(),
  6219. 'emails/flash_default.html.twig',
  6220. [
  6221. "title" => "Lettre de changement de fournisseur",
  6222. "content" => $content
  6223. ],
  6224. 'resiliation@flash-consulting.fr',
  6225. null,
  6226. [
  6227. [
  6228. "content" => $pdf,
  6229. "name" => "courrier_de_changement_fournisseur_elec.pdf",
  6230. "contentType" => "application/pdf"
  6231. ]
  6232. ]
  6233. );
  6234. $contract->setResiliationElecEmailSendDate(new \DateTime('now'));
  6235. $em->flush();
  6236. } elseif (isset($_POST["file_gas_content"])) {
  6237. $contract->setResiliationGasEmailContent($_POST["file_gas_content"]);
  6238. $em->flush();
  6239. // Génération du PDF
  6240. $pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_gas_content"]);
  6241. // Email
  6242. $content = <<<EOD
  6243. Bonjour,<br/>
  6244. <br/>
  6245. 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/>
  6246. <br/>
  6247. <i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
  6248. <br/>
  6249. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6250. 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/>
  6251. <br/>
  6252. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6253. EOD;
  6254. $sendEmailService->send(
  6255. "Flash Énergie: Lettre de changement de fournisseur Gaz",
  6256. $contract->getCompany()->getEmail(),
  6257. 'emails/flash_default.html.twig',
  6258. [
  6259. "title" => "Lettre de changement de fournisseur",
  6260. "content" => $content
  6261. ],
  6262. 'resiliation@flash-consulting.fr',
  6263. null,
  6264. [
  6265. [
  6266. "content" => $pdf,
  6267. "name" => "courrier_de_changement_fournisseur_gaz.pdf",
  6268. "contentType" => "application/pdf"
  6269. ]
  6270. ]
  6271. );
  6272. $contract->setResiliationGasEmailSendDate(new \DateTime('now'));
  6273. $em->flush();
  6274. } else {
  6275. $content = <<<EOD
  6276. Bonjour,<br/>
  6277. <br/>
  6278. Veuillez trouver ci-joint un modèle de courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat actuel.<br/>
  6279. <br/>
  6280. <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/>
  6281. <br/>
  6282. De plus, nous avons également inclus <b>un guide</b> (voir pièces jointes) pour remplir le formulaire correctement.<br/>
  6283. <br/>
  6284. Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
  6285. 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/>
  6286. <br/>
  6287. Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
  6288. EOD;
  6289. $sendEmailService->send(
  6290. "Flash Énergie: Lettre de changement de fournisseur et son guide",
  6291. $contract->getCompany()->getEmail(),
  6292. 'emails/flash_default.html.twig',
  6293. [
  6294. "title" => "Lettre de changement de fournisseur et son guide",
  6295. "content" => $content
  6296. ],
  6297. 'resiliation@flash-consulting.fr',
  6298. [
  6299. $this->getParameter('assets_directory')."Lettre de resiliation.docx",
  6300. $this->getParameter('assets_directory')."Guide pour remplir sa lettre de resiliation.docx",
  6301. ]
  6302. );
  6303. if (isset($_GET["elec"])) {
  6304. $contract->setResiliationElecEmailSendDate(new \DateTime('now'));
  6305. }
  6306. if (isset($_GET["gas"])) {
  6307. $contract->setResiliationGasEmailSendDate(new \DateTime('now'));
  6308. }
  6309. $em->flush();
  6310. }
  6311. $this->get("session")->getFlashBag()->add("success", "L'email de changement de fournisseur a bien été envoyé");
  6312. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6313. }
  6314. /**
  6315. * @Route("/companies/{company}/contracts/{contract}/delete", name="companies_contracts_delete")
  6316. */
  6317. public function companiesContractsDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6318. {
  6319. if (!$this->getUser()->getManager()->getAdmin()) {
  6320. throw new UnauthorizedHttpException("Admin only");
  6321. }
  6322. $contract->setOfferElec(null);
  6323. $contract->setOfferGaz(null);
  6324. $em->flush();
  6325. $em->remove($contract);
  6326. $em->flush();
  6327. $this->get("session")->getFlashBag()->add("success", "Contrat supprimée");
  6328. return $this->redirectToRoute("manager_contracts", ["pro" => 1]);
  6329. }
  6330. /**
  6331. * @Route("/companies/{company}/contracts/{contract}/file", name="companies_contracts_file")
  6332. */
  6333. public function companiesContractsFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6334. {
  6335. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6336. throw new NotFoundHttpException();
  6337. }
  6338. if (!$this->getUser()->getManager()->getAdmin()) {
  6339. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6340. throw new NotFoundHttpException();
  6341. }
  6342. }
  6343. if ($contract->getFile()) {
  6344. return $this->getContractFile($contract, $request->get('mergeRib'));
  6345. }
  6346. throw new NotFoundHttpException();
  6347. }
  6348. /**
  6349. * @Route("/companies/{company}/contracts/{contract}/other-file", name="companies_contracts_other_file")
  6350. */
  6351. public function companiesContractsOtherFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6352. {
  6353. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6354. throw new NotFoundHttpException();
  6355. }
  6356. if (!$this->getUser()->getManager()->getAdmin()) {
  6357. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6358. throw new NotFoundHttpException();
  6359. }
  6360. }
  6361. if ($contract->getOtherFile()) {
  6362. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
  6363. return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6364. }
  6365. throw new NotFoundHttpException();
  6366. }
  6367. /**
  6368. * @Route("/companies/{company}/contracts/{contract}/rib", name="companies_contracts_rib")
  6369. */
  6370. public function companiesContractsRibAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6371. {
  6372. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6373. throw new NotFoundHttpException();
  6374. }
  6375. if (!$this->getUser()->getManager()->getAdmin()) {
  6376. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6377. throw new NotFoundHttpException();
  6378. }
  6379. }
  6380. if ($contract->getRibFile()) {
  6381. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6382. return $this->file($filePath, $contract->getRibFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6383. }
  6384. throw new NotFoundHttpException();
  6385. }
  6386. /**
  6387. * @Route("/companies/{company}/contracts/{contract}/rib-delete", name="companies_contracts_rib-delete")
  6388. */
  6389. public function companiesContractsRibDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
  6390. {
  6391. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6392. throw new NotFoundHttpException();
  6393. }
  6394. if (!$this->getUser()->getManager()->getAdmin()) {
  6395. throw new NotFoundHttpException();
  6396. }
  6397. $contract->setRibFile(null);
  6398. $em->flush();
  6399. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6400. }
  6401. /**
  6402. * @Route("/companies/{company}/contracts/{contract}/sign", name="companies_contracts_sign")
  6403. */
  6404. public function companiesContractsSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
  6405. {
  6406. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6407. throw new NotFoundHttpException();
  6408. }
  6409. if (!$this->getUser()->getManager()->getAdmin()) {
  6410. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6411. throw new NotFoundHttpException();
  6412. }
  6413. }
  6414. if (!$contract->getFile()) {
  6415. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  6416. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6417. } else if (!$contract->getState() || $contract->getState()->getId() != 3) {
  6418. $this->get("session")->getFlashBag()->add("danger", "Le statut du contrat doit être: Contrat en attente de signature");
  6419. return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6420. } else {
  6421. return $this->sendContractFileToDocusign($contract, $docusignService, $em, true);
  6422. //return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6423. }
  6424. throw new NotFoundHttpException();
  6425. }
  6426. /**
  6427. * @Route("/companies/{company}/contracts/{contract}/other-file/sign", name="companies_contracts_other_file_sign")
  6428. */
  6429. public function companiesContractsOtherFileSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
  6430. {
  6431. if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
  6432. throw new NotFoundHttpException();
  6433. }
  6434. if (!$this->getUser()->getManager()->getAdmin()) {
  6435. if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6436. throw new NotFoundHttpException();
  6437. }
  6438. }
  6439. if (!$contract->getOtherFile()) {
  6440. $this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
  6441. $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6442. } else {
  6443. return $this->sendContractOtherFileToDocusign($contract, $docusignService, $em, true);
  6444. //return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
  6445. }
  6446. throw new NotFoundHttpException();
  6447. }
  6448. private function getContractFile(Contract $contract, $mergeRib)
  6449. {
  6450. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
  6451. if ($mergeRib && $contract->getRibFile()) {
  6452. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6453. if (file_exists($fileRib)) {
  6454. $pdf = new FPDI();
  6455. $pagecount = $pdf->setSourceFile($filePath);
  6456. for($i=0; $i<$pagecount; $i++){
  6457. $pdf->AddPage();
  6458. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6459. $pdf->useTemplate($tplidx);
  6460. }
  6461. $pagecount = $pdf->setSourceFile($fileRib);
  6462. for($i=0; $i<$pagecount; $i++){
  6463. $pdf->AddPage();
  6464. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6465. $pdf->useTemplate($tplidx);
  6466. }
  6467. return $this->file($pdf->Output($contract->getFile(), 'I'), $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6468. }
  6469. }
  6470. return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
  6471. }
  6472. public function sendContractFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded)
  6473. {
  6474. $fileName = $contract->getFile();
  6475. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
  6476. $signMember = $this->getContractSignMember($contract);
  6477. // Création de la procédure
  6478. $procedureSign = new ProcedureSign();
  6479. if ($contract->getCompany()) {
  6480. $procedureSign->setUser($contract->getCompany()->getUser());
  6481. } else if ($contract->getUser()) {
  6482. $procedureSign->setUser($contract->getUser());
  6483. }
  6484. $procedureSign->setFirstName($signMember["firstName"]);
  6485. $procedureSign->setLastName($signMember["lastName"]);
  6486. $procedureSign->setEmail($signMember["email"]);
  6487. $procedureSign->setPhone($signMember["phone"]);
  6488. $procedureSign->setCreationDate(new \DateTime('now'));
  6489. $procedureSign->setNameFile($fileName);
  6490. $procedureSign->setFilePath($filePath);
  6491. $content = [
  6492. "type" => "contract.file",
  6493. "id" => $contract->getId()
  6494. ];
  6495. $procedureSign->setContent(json_encode($content));
  6496. $em->persist($procedureSign);
  6497. $em->flush();
  6498. /*
  6499. $fileCertificate = $this->getParameter('documents_fc_certificate');
  6500. if (file_exists($fileCertificate)) {
  6501. $pdf = new FPDI();
  6502. $pagecount = $pdf->setSourceFile($filePath);
  6503. for($i=0; $i<$pagecount; $i++){
  6504. $pdf->AddPage();
  6505. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6506. $pdf->useTemplate($tplidx);
  6507. }
  6508. // add RIB
  6509. if ($contract->getRibFile()) {
  6510. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6511. if (file_exists($fileRib)) {
  6512. $pagecount = $pdf->setSourceFile($fileRib);
  6513. for ($i = 0; $i < $pagecount; $i++) {
  6514. $pdf->AddPage();
  6515. $tplidx = $pdf->importPage($i + 1, '/MediaBox');
  6516. $pdf->useTemplate($tplidx);
  6517. }
  6518. }
  6519. }
  6520. // add certificate
  6521. $pagecount = $pdf->setSourceFile($fileCertificate);
  6522. for($i=0; $i<$pagecount; $i++){
  6523. $pdf->AddPage();
  6524. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6525. $pdf->useTemplate($tplidx);
  6526. }
  6527. $pdf->Output($filePath, 'F');
  6528. }
  6529. */
  6530. // Lancement de la signature
  6531. $accessToken = $docusignService->getAccessToken();
  6532. if ($accessToken) {
  6533. try {
  6534. if ($embedded) {
  6535. $response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
  6536. $procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
  6537. $em->flush();
  6538. return $this->redirect($response["url"]);
  6539. } else {
  6540. $response = $docusignService->sendFile($accessToken, $procedureSign);
  6541. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  6542. $em->flush();
  6543. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
  6544. return true;
  6545. }
  6546. } catch (ApiException $e) {
  6547. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6548. }
  6549. } else {
  6550. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6551. }
  6552. return false;
  6553. }
  6554. public function sendContractOtherFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded=false)
  6555. {
  6556. $fileName = $contract->getOtherFile();
  6557. $filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
  6558. $signMember = $this->getContractSignMember($contract);
  6559. // Création de la procédure
  6560. $procedureSign = new ProcedureSign();
  6561. if ($contract->getCompany()) {
  6562. $procedureSign->setUser($contract->getCompany()->getUser());
  6563. } else if ($contract->getUser()) {
  6564. $procedureSign->setUser($contract->getUser());
  6565. }
  6566. $procedureSign->setFirstName($signMember["firstName"]);
  6567. $procedureSign->setLastName($signMember["lastName"]);
  6568. $procedureSign->setEmail($signMember["email"]);
  6569. $procedureSign->setPhone($signMember["phone"]);
  6570. $procedureSign->setCreationDate(new \DateTime('now'));
  6571. $procedureSign->setNameFile($fileName);
  6572. $procedureSign->setFilePath($filePath);
  6573. $content = [
  6574. "type" => "contract.other-file",
  6575. "id" => $contract->getId()
  6576. ];
  6577. $procedureSign->setContent(json_encode($content));
  6578. $em->persist($procedureSign);
  6579. $em->flush();
  6580. // Création de la position
  6581. /*
  6582. $yousignPosition = new YousignPosition();
  6583. $yousignPosition->setPosition("209,16,395,180");
  6584. $yousignPosition->setReason("Signé par ".$company->getUser()->getFirstName().' '.$company->getUser()->getLastName());
  6585. $fileCertificate = $this->getParameter('documents_fc_certificate');
  6586. if (file_exists($fileCertificate)) {
  6587. $pdf = new FPDI();
  6588. $pagecount = $pdf->setSourceFile($filePath);
  6589. for($i=0; $i<$pagecount; $i++){
  6590. $pdf->AddPage();
  6591. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6592. $pdf->useTemplate($tplidx);
  6593. }
  6594. // add RIB
  6595. if ($contract->getRibFile()) {
  6596. $fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
  6597. if (file_exists($fileRib)) {
  6598. $pagecount = $pdf->setSourceFile($fileRib);
  6599. for ($i = 0; $i < $pagecount; $i++) {
  6600. $pdf->AddPage();
  6601. $tplidx = $pdf->importPage($i + 1, '/MediaBox');
  6602. $pdf->useTemplate($tplidx);
  6603. }
  6604. }
  6605. }
  6606. // add certificate
  6607. $pagecount = $pdf->setSourceFile($fileCertificate);
  6608. for($i=0; $i<$pagecount; $i++){
  6609. $pdf->AddPage();
  6610. $tplidx = $pdf->importPage($i+1, '/MediaBox');
  6611. $pdf->useTemplate($tplidx);
  6612. }
  6613. $pdf->Output($filePath, 'F');
  6614. }
  6615. $pdf = new FPDI();
  6616. $pagecount = $pdf->setSourceFile($filePath);
  6617. $yousignPosition->setPage($pagecount);
  6618. */
  6619. $accessToken = $docusignService->getAccessToken();
  6620. if ($accessToken) {
  6621. try {
  6622. if ($embedded) {
  6623. $response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
  6624. $procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
  6625. $em->flush();
  6626. return $this->redirect($response["url"]);
  6627. } else {
  6628. $response = $docusignService->sendFile($accessToken, $procedureSign);
  6629. $procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
  6630. $em->flush();
  6631. $this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du fichier a été envoyé au client.");
  6632. return true;
  6633. }
  6634. } catch (ApiException $e) {
  6635. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6636. }
  6637. } else {
  6638. $this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
  6639. }
  6640. return false;
  6641. }
  6642. private function getContractSignMember(Contract $contrat)
  6643. {
  6644. if ($contrat->getCompany()) {
  6645. $firstName = $contrat->getCompany()->getUser()->getFirstName();
  6646. $lastName = $contrat->getCompany()->getUser()->getLastName();
  6647. $email = $contrat->getCompany()->getUser()->getEmail();
  6648. $phone = $contrat->getCompany()->getUser()->getPhone();
  6649. if ($contrat->getOfferElec() && $contrat->getOfferElec()->getCotation()) {
  6650. $firstName = $contrat->getOfferElec()->getCotation()->getFirstName();
  6651. $lastName = $contrat->getOfferElec()->getCotation()->getLastName();
  6652. $email = $contrat->getOfferElec()->getCotation()->getEmail();
  6653. $phone = $contrat->getOfferElec()->getCotation()->getPhone();
  6654. } else if ($contrat->getOfferGaz() && $contrat->getOfferGaz()->getCotation()) {
  6655. $firstName = $contrat->getOfferGaz()->getCotation()->getFirstName();
  6656. $lastName = $contrat->getOfferGaz()->getCotation()->getLastName();
  6657. $email = $contrat->getOfferGaz()->getCotation()->getEmail();
  6658. $phone = $contrat->getOfferGaz()->getCotation()->getPhone();
  6659. }
  6660. } else if ($contrat->getUser()) {
  6661. $firstName = $contrat->getUser()->getFirstName();
  6662. $lastName = $contrat->getUser()->getLastName();
  6663. $email = $contrat->getUser()->getEmail();
  6664. $phone = $contrat->getUser()->getPhone();
  6665. } else {
  6666. $firstName = "";
  6667. $lastName = "";
  6668. $email = "contact@flash-consulting.fr";
  6669. $phone = "";
  6670. }
  6671. return [
  6672. "firstName" => $firstName,
  6673. "lastName" => $lastName,
  6674. "email" => $email,
  6675. "phone" => $phone,
  6676. ];
  6677. }
  6678. /**
  6679. * @Route("/cotations", name="cotations")
  6680. */
  6681. public function cotationsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6682. {
  6683. $page = $request->get("page");
  6684. if (!is_numeric($page) || $page < 1) {
  6685. $page = 1;
  6686. }
  6687. $nbByPage = 20;
  6688. $keywords = null;
  6689. if ($request->get("search")) {
  6690. $terms = explode(" ", $request->get("search"));
  6691. if (count($terms)) {
  6692. $keywords = $terms;
  6693. }
  6694. }
  6695. if ($request->get("onlyInProgress")) {
  6696. if ($this->getUser()->getManager()->getAdmin()) {
  6697. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
  6698. } else {
  6699. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
  6700. }
  6701. $title = "Cotations monosites en cours";
  6702. } else {
  6703. if ($this->getUser()->getManager()->getAdmin()) {
  6704. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
  6705. } else {
  6706. $cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
  6707. }
  6708. $title = "Toutes les cotations monosites";
  6709. }
  6710. return $this->render("app/cotations/list.html.twig", [
  6711. "cotations_paginator" => $cotations_paginator,
  6712. "title" => $title,
  6713. ]);
  6714. }
  6715. /**
  6716. * @Route("/cotations-multisites", name="cotations-multisites")
  6717. */
  6718. public function cotationsMultisitesAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6719. {
  6720. $page = $request->get("page");
  6721. if (!is_numeric($page) || $page < 1) {
  6722. $page = 1;
  6723. }
  6724. $nbByPage = 20;
  6725. $keywords = null;
  6726. if ($request->get("search")) {
  6727. $terms = explode(" ", $request->get("search"));
  6728. if (count($terms)) {
  6729. $keywords = $terms;
  6730. }
  6731. }
  6732. if ($request->get("onlyInProgress")) {
  6733. if ($this->getUser()->getManager()->getAdmin()) {
  6734. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
  6735. } else {
  6736. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
  6737. }
  6738. $title = "Cotations multisites en cours";
  6739. } else {
  6740. if ($this->getUser()->getManager()->getAdmin()) {
  6741. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
  6742. } else {
  6743. $cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
  6744. }
  6745. $title = "Toutes les cotations multisites";
  6746. }
  6747. return $this->render("app/cotations-multisites/list.html.twig", [
  6748. "cotations_paginator" => $cotations_paginator,
  6749. "title" => $title,
  6750. ]);
  6751. }
  6752. /**
  6753. * @Route("/contracts", name="contracts")
  6754. */
  6755. public function contractsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
  6756. {
  6757. $page = $request->get("page");
  6758. if (!is_numeric($page) || $page < 1) {
  6759. $page = 1;
  6760. }
  6761. $nbByPage = 20;
  6762. $keywords = null;
  6763. if ($request->get("search")) {
  6764. $terms = explode(" ", $request->get("search"));
  6765. if (count($terms)) {
  6766. $keywords = $terms;
  6767. }
  6768. }
  6769. if ($request->get("particulier")) {
  6770. if ($this->getUser()->getManager()->getAdmin()) {
  6771. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, true, false);
  6772. } else {
  6773. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), true, false);
  6774. }
  6775. return $this->render("app/contracts/list.html.twig", [
  6776. "contracts_paginator" => $contracts_paginator,
  6777. "title" => "Contrats particuliers",
  6778. "pro" => false,
  6779. ]);
  6780. } elseif ($request->get("pro")) {
  6781. if ($this->getUser()->getManager()->getAdmin()) {
  6782. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true);
  6783. } else {
  6784. $contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), false, true);
  6785. }
  6786. return $this->render("app/contracts/list.html.twig", [
  6787. "contracts_paginator" => $contracts_paginator,
  6788. "title" => "Contrats professionnels",
  6789. "pro" => true,
  6790. ]);
  6791. }
  6792. throw new NotAcceptableHttpException();
  6793. }
  6794. /**
  6795. * @Route("/roadmaps", name="roadmaps")
  6796. */
  6797. public function roadmapsAction(Request $request, EntityManagerInterface $em)
  6798. {
  6799. $keywords = null;
  6800. if ($request->get("search")) {
  6801. $terms = explode(" ", $request->get("search"));
  6802. if (count($terms)) {
  6803. $keywords = $terms;
  6804. }
  6805. }
  6806. if ($request->get("onlyOpened")) {
  6807. if ($this->getUser()->getManager()->getAdmin()) {
  6808. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null, true);
  6809. } else {
  6810. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager(), true);
  6811. }
  6812. return $this->render("app/roadmaps/list.html.twig", [
  6813. "roadmaps" => $roadmaps,
  6814. "title" => "Feuilles de routes en cours",
  6815. ]);
  6816. } else {
  6817. if ($this->getUser()->getManager()->getAdmin()) {
  6818. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null);
  6819. } else {
  6820. $roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager());
  6821. }
  6822. return $this->render("app/roadmaps/list.html.twig", [
  6823. "roadmaps" => $roadmaps,
  6824. "title" => "Feuilles de routes",
  6825. ]);
  6826. }
  6827. }
  6828. /**
  6829. * @Route("/roadmaps/add", name="roadmaps_add")
  6830. */
  6831. public function roadmapsAddAction(Request $request, EntityManagerInterface $em)
  6832. {
  6833. $roadmap = new Roadmap();
  6834. $form = $this->createForm(RoadmapType::class, $roadmap);
  6835. $form->handleRequest($request);
  6836. if ($form->isSubmitted() && !$form->isValid()) {
  6837. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6838. }
  6839. if ($form->isSubmitted() && $form->isValid()) {
  6840. $roadmap->setCreationDate(new \DateTime("now"));
  6841. $roadmap->setManager($this->getUser()->getManager());
  6842. $em->persist($roadmap);
  6843. $em->flush();
  6844. $em->refresh($roadmap);
  6845. $file = $form['file']->getData();
  6846. if ($file) {
  6847. $extension = $file->guessExtension();
  6848. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6849. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6850. } else {
  6851. $fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6852. $file->move(
  6853. $this->getParameter('documents_justificatif_directory'),
  6854. $fileName
  6855. );
  6856. $roadmap->setFilePath($fileName);
  6857. $em->flush();
  6858. }
  6859. }
  6860. $this->get("session")->getFlashBag()->add("success", "Feuille de route ajoutée");
  6861. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6862. }
  6863. return $this->render("app/roadmaps/form.html.twig", [
  6864. "form" => $form->createView(),
  6865. "title" => "Ajouter une feuille de route",
  6866. "roadmap" => null,
  6867. ]);
  6868. }
  6869. /**
  6870. * @Route("/roadmaps/{id}/edit", name="roadmaps_edit")
  6871. */
  6872. public function roadmapEditAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6873. {
  6874. if (!$this->getUser()->getManager()->getAdmin()) {
  6875. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6876. throw new NotFoundHttpException();
  6877. }
  6878. }
  6879. if ($roadmap->getArchived()) {
  6880. throw new BadRequestHttpException("Archived");
  6881. }
  6882. $form = $this->createForm(RoadmapType::class, $roadmap);
  6883. $form->handleRequest($request);
  6884. if ($form->isSubmitted() && !$form->isValid()) {
  6885. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  6886. }
  6887. if ($form->isSubmitted() && $form->isValid()) {
  6888. $em->flush();
  6889. $file = $form['file']->getData();
  6890. if ($file) {
  6891. $extension = $file->guessExtension();
  6892. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  6893. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  6894. } else {
  6895. $fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
  6896. $file->move(
  6897. $this->getParameter('documents_justificatif_directory'),
  6898. $fileName
  6899. );
  6900. $roadmap->setFilePath($fileName);
  6901. $em->flush();
  6902. }
  6903. }
  6904. $this->get("session")->getFlashBag()->add("success", "Feuille de route modifiée");
  6905. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6906. }
  6907. return $this->render("app/roadmaps/form.html.twig", [
  6908. "form" => $form->createView(),
  6909. "title" => "Modifier une feuille de route",
  6910. "roadmap" => $roadmap,
  6911. ]);
  6912. }
  6913. /**
  6914. * @Route("/roadmaps/{id}/file", name="roadmaps_file")
  6915. */
  6916. public function roadmapFileAction(Request $request, Roadmap $roadmap)
  6917. {
  6918. if (!$this->getUser()->getManager()->getAdmin()) {
  6919. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6920. throw new NotFoundHttpException();
  6921. }
  6922. }
  6923. if ($roadmap->getFilePath()) {
  6924. $filePath = $this->getParameter('documents_justificatif_directory') . $roadmap->getFilePath();
  6925. return $this->file($filePath, $roadmap->getFilePath(), ResponseHeaderBag::DISPOSITION_INLINE);
  6926. }
  6927. throw new NotFoundHttpException();
  6928. }
  6929. /**
  6930. * @Route("/roadmaps/{id}/file-delete", name="roadmaps_file-delete")
  6931. */
  6932. public function roadmapFileDeleteAction(Request $request, Roadmap $roadmap, EntityManagerInterface $em)
  6933. {
  6934. if (!$this->getUser()->getManager()->getAdmin()) {
  6935. throw new NotFoundHttpException();
  6936. }
  6937. $roadmap->setFilePath(null);
  6938. $em->flush();
  6939. return $this->redirectToRoute("manager_roadmaps_edit", ["id" => $roadmap->getId()]);
  6940. }
  6941. /**
  6942. * @Route("/roadmaps/{id}/delete", name="roadmaps_delete")
  6943. */
  6944. public function roadmapDeleteAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6945. {
  6946. if (!$this->getUser()->getManager()->getAdmin()) {
  6947. throw new UnauthorizedHttpException("Admin only");
  6948. }
  6949. $em->remove($roadmap);
  6950. $em->flush();
  6951. $this->get("session")->getFlashBag()->add("success", "Feuille de route supprimée");
  6952. return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
  6953. }
  6954. /**
  6955. * @Route("/roadmaps/{id}/convert", name="roadmaps_convert")
  6956. */
  6957. public function roadmapConvertAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
  6958. {
  6959. if (!$this->getUser()->getManager()->getAdmin()) {
  6960. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6961. throw new NotFoundHttpException();
  6962. }
  6963. }
  6964. if ($roadmap->getArchived()) {
  6965. throw new BadRequestHttpException("Archived");
  6966. }
  6967. // On cherche les clients pro similaires
  6968. $keywords = explode(" ", $roadmap->getCompanyName());
  6969. $keywords[] = $roadmap->getLastName();
  6970. if ($this->getUser()->getManager()->getAdmin()) {
  6971. $users = $em->getRepository(User::class)->searchForTerms($keywords, null, false, true);
  6972. } else {
  6973. $users = $em->getRepository(User::class)->searchForTerms($keywords, $this->getUser()->getManager(), false, true);
  6974. }
  6975. return $this->render("app/roadmaps/convert.html.twig", [
  6976. "roadmap" => $roadmap,
  6977. "users" => $users,
  6978. ]);
  6979. }
  6980. /**
  6981. * @Route("/roadmaps/{id}/convert/{company}", name="roadmaps_convert_to_company")
  6982. * @ParamConverter("roadmap", options={"id" = "id"})
  6983. * @ParamConverter("company", options={"id" = "company"})
  6984. */
  6985. public function roadmapConvertUserAction(Roadmap $roadmap, Company $company, Request $request, EntityManagerInterface $em)
  6986. {
  6987. if (!$this->getUser()->getManager()->getAdmin()) {
  6988. if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  6989. throw new NotFoundHttpException();
  6990. }
  6991. }
  6992. if ($roadmap->getArchived()) {
  6993. throw new BadRequestHttpException("Archived");
  6994. }
  6995. $roadmap->setArchived(true);
  6996. $roadmap->setCompany($company);
  6997. if ($roadmap->getContractType()->getId() == 4) {
  6998. // Engie PRO
  6999. $this->roadmapEngieProToContract(
  7000. $roadmap,
  7001. $company,
  7002. true,
  7003. "",
  7004. null,
  7005. "",
  7006. new \DateTime('now'),
  7007. null,
  7008. "",
  7009. true,
  7010. "",
  7011. null,
  7012. "",
  7013. new \DateTime('now'),
  7014. null,
  7015. "",
  7016. $em
  7017. );
  7018. }
  7019. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 5) {
  7020. $this->roadmapTelecomToContract(
  7021. $roadmap,
  7022. $company,
  7023. "",
  7024. "",
  7025. false,
  7026. "",
  7027. $em
  7028. );
  7029. }
  7030. if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 6) {
  7031. $this->roadmapPhotovoltaiqueToContract(
  7032. $roadmap,
  7033. $company,
  7034. "",
  7035. "",
  7036. "",
  7037. "",
  7038. "",
  7039. false,
  7040. $em
  7041. );
  7042. }
  7043. $em->flush();
  7044. $this->get("session")->getFlashBag()->add("success", "Feuille de route convertie");
  7045. return $this->redirectToRoute("manager_roadmaps");
  7046. }
  7047. /**
  7048. * @Route("/documents", name="documents")
  7049. */
  7050. public function documentsAction(Request $request, EntityManagerInterface $em)
  7051. {
  7052. if (!$this->getUser()->getManager()->getAdmin()) {
  7053. throw new NotFoundHttpException();
  7054. }
  7055. $keywords = null;
  7056. if ($request->get("search")) {
  7057. $terms = explode(" ", $request->get("search"));
  7058. if (count($terms)) {
  7059. $keywords = $terms;
  7060. }
  7061. }
  7062. $documents = $em->getRepository(Document::class)->searchForTerms($keywords);
  7063. return $this->render("app/documents/list.html.twig", [
  7064. "documents" => $documents,
  7065. ]);
  7066. }
  7067. /**
  7068. * @Route("/documents/add", name="documents_add")
  7069. */
  7070. public function documentsAddAction(Request $request, EntityManagerInterface $em)
  7071. {
  7072. if (!$this->getUser()->getManager()->getAdmin()) {
  7073. throw new NotFoundHttpException();
  7074. }
  7075. $document = new Document();
  7076. $form = $this->createForm(DocumentType::class, $document);
  7077. $form->handleRequest($request);
  7078. if ($form->isSubmitted() && !$form->isValid()) {
  7079. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7080. }
  7081. if ($form->isSubmitted() && $form->isValid()) {
  7082. $file = $form['file']->getData();
  7083. if ($file) {
  7084. $extension = $file->guessExtension();
  7085. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
  7086. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7087. } else {
  7088. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  7089. $relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
  7090. $relativePathFile = str_replace('/', '', $relativePathFile);
  7091. $file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
  7092. $document->setPath('/uploads/documents/' . $relativePathFile);
  7093. $document->setCreationDate(new \DateTime("now"));
  7094. $document->setVisible(true);
  7095. $document->setManager($this->getUser()->getManager());
  7096. $em->persist($document);
  7097. $em->flush();
  7098. $this->get("session")->getFlashBag()->add("success", "Document ajouté");
  7099. }
  7100. } else {
  7101. $this->get("session")->getFlashBag()->add("danger", "Impossible de télécharger ce document");
  7102. }
  7103. return $this->redirectToRoute("manager_documents");
  7104. }
  7105. return $this->render("app/documents/form.html.twig", [
  7106. "form" => $form->createView(),
  7107. "title" => "Ajouter un document à la boîte à outils"
  7108. ]);
  7109. }
  7110. /**
  7111. * @Route("/documents/{id}/edit", name="documents_edit")
  7112. */
  7113. public function documentsEditAction(Document $document, Request $request, EntityManagerInterface $em)
  7114. {
  7115. if (!$this->getUser()->getManager()->getAdmin()) {
  7116. throw new NotFoundHttpException();
  7117. }
  7118. $form = $this->createForm(DocumentType::class, $document);
  7119. $form->add('creationDate', DateType::class, [
  7120. "label" => "Date de publication",
  7121. 'widget' => 'single_text',
  7122. 'html5' => true,
  7123. ]);
  7124. $form->handleRequest($request);
  7125. if ($form->isSubmitted() && !$form->isValid()) {
  7126. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7127. }
  7128. if ($form->isSubmitted() && $form->isValid()) {
  7129. $file = $form['file']->getData();
  7130. if ($file) {
  7131. $extension = $file->guessExtension();
  7132. if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
  7133. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7134. } else {
  7135. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  7136. $relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
  7137. $relativePathFile = str_replace('/', '', $relativePathFile);
  7138. $file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
  7139. $document->setPath('/uploads/documents/' . $relativePathFile);
  7140. }
  7141. }
  7142. $em->flush();
  7143. $this->get("session")->getFlashBag()->add("success", "Document modifié");
  7144. return $this->redirectToRoute("manager_documents");
  7145. }
  7146. return $this->render("app/documents/form.html.twig", [
  7147. "form" => $form->createView(),
  7148. "title" => "Modifier un document"
  7149. ]);
  7150. }
  7151. /**
  7152. * @Route("/documents/{id}/activate", name="documents_activate")
  7153. */
  7154. public function documentsActivateAction(Document $document, Request $request, EntityManagerInterface $em)
  7155. {
  7156. if (!$this->getUser()->getManager()->getAdmin()) {
  7157. throw new NotFoundHttpException();
  7158. }
  7159. $document->setVisible(true);
  7160. $em->flush();
  7161. $this->get("session")->getFlashBag()->add("success", "Document activé");
  7162. return $this->redirectToRoute("manager_documents");
  7163. }
  7164. /**
  7165. * @Route("/documents/{id}/desactivate", name="documents_desactivate")
  7166. */
  7167. public function documentsDesactivateAction(Document $document, Request $request, EntityManagerInterface $em)
  7168. {
  7169. if (!$this->getUser()->getManager()->getAdmin()) {
  7170. throw new NotFoundHttpException();
  7171. }
  7172. $document->setVisible(false);
  7173. $em->flush();
  7174. $this->get("session")->getFlashBag()->add("success", "Document désactivé");
  7175. return $this->redirectToRoute("manager_documents");
  7176. }
  7177. /**
  7178. * @Route("/documents/{id}/delete", name="documents_delete")
  7179. */
  7180. public function documentsDeleteAction(Document $document, Request $request, EntityManagerInterface $em)
  7181. {
  7182. if (!$this->getUser()->getManager()->getAdmin()) {
  7183. throw new NotFoundHttpException();
  7184. }
  7185. $em->remove($document);
  7186. $em->flush();
  7187. $this->get("session")->getFlashBag()->add("success", "Document supprimé");
  7188. return $this->redirectToRoute("manager_documents");
  7189. }
  7190. /**
  7191. * @Route("/managers", name="managers")
  7192. */
  7193. public function managersAction(Request $request, EntityManagerInterface $em)
  7194. {
  7195. if (!$this->getUser()->getManager()->getAdmin()) {
  7196. throw new NotFoundHttpException();
  7197. }
  7198. $accounts = $em->getRepository(Account::class)->findManagers();
  7199. return $this->render("app/managers/list.html.twig", [
  7200. "accounts" => $accounts,
  7201. ]);
  7202. }
  7203. /**
  7204. * @Route("/managers/add", name="managers_add")
  7205. */
  7206. public function managersAddAction(Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
  7207. {
  7208. if (!$this->getUser()->getManager()->getAdmin()) {
  7209. throw new NotFoundHttpException();
  7210. }
  7211. $manager = new Manager();
  7212. $form = $this->createForm(ManagerType::class, $manager);
  7213. $form->handleRequest($request);
  7214. if ($form->isSubmitted() && !$form->isValid()) {
  7215. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7216. }
  7217. if ($form->isSubmitted() && $form->isValid()) {
  7218. $error = false;
  7219. $accountEmail = $form["account_email"]->getData();
  7220. if (filter_var($accountEmail, FILTER_VALIDATE_EMAIL)) {
  7221. $other_account = $em->getRepository(Account::class)->findOneBy(['email' => $accountEmail]);
  7222. if ($other_account) {
  7223. $error = true;
  7224. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
  7225. }
  7226. } else {
  7227. $error = true;
  7228. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
  7229. }
  7230. if (!$error) {
  7231. $em->persist($manager);
  7232. $em->flush();
  7233. $account = new Account();
  7234. $account->setEmail($accountEmail);
  7235. $account->setEnabled($form["enabled"]->getData());
  7236. $account->setManager($manager);
  7237. $salt = md5(uniqid());
  7238. $pwd = $form['password']->getData();
  7239. $account->setSalt($salt);
  7240. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  7241. $account->setPassword($enc_pwd);
  7242. $account->setRegistrationDate(new \DateTime('now'));
  7243. $em->persist($account);
  7244. $em->flush();
  7245. $this->get('session')->getFlashBag()->add('success', 'Utilisateur créé avec succès');
  7246. return $this->redirectToRoute('manager_managers');
  7247. }
  7248. }
  7249. return $this->render('app/managers/form.html.twig', [
  7250. 'form' => $form->createView(),
  7251. 'title' => "Ajouter un utilisateur",
  7252. ]);
  7253. }
  7254. /**
  7255. * @Route("/managers/{id}/edit", name="managers_edit")
  7256. */
  7257. public function managersEditAction(Account $account, Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
  7258. {
  7259. if (!$this->getUser()->getManager()->getAdmin()) {
  7260. throw new NotFoundHttpException();
  7261. }
  7262. if (!$account->getManager()) {
  7263. throw new BadRequestHttpException();
  7264. }
  7265. $r_email = $account->getEmail();
  7266. $form = $this->createForm(ManagerType::class, $account->getManager());
  7267. $form["account_email"]->setData($account->getEmail());
  7268. $form["enabled"]->setData($account->getEnabled());
  7269. $form->handleRequest($request);
  7270. if ($form->isSubmitted() && !$form->isValid()) {
  7271. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7272. }
  7273. if ($form->isSubmitted() && $form->isValid()) {
  7274. $error = false;
  7275. $newEmail = $form["account_email"]->getData();
  7276. if ($r_email != $newEmail) {
  7277. if (filter_var($account->getEmail(), FILTER_VALIDATE_EMAIL)) {
  7278. $other_account = $em->getRepository(Account::class)->findOneBy(['email' => $newEmail]);
  7279. if ($other_account && $other_account->getId() != $account->getId()) {
  7280. $error = true;
  7281. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
  7282. }
  7283. } else {
  7284. $error = true;
  7285. $this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
  7286. }
  7287. }
  7288. if (!$error) {
  7289. $account->setEmail($newEmail);
  7290. $account->setEnabled($form["enabled"]->getData());
  7291. $em->flush();
  7292. if ($form['password']->getData()) {
  7293. $salt = md5(uniqid());
  7294. $pwd = $form['password']->getData();
  7295. $account->setSalt($salt);
  7296. $enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
  7297. $account->setPassword($enc_pwd);
  7298. $em->flush();
  7299. }
  7300. $this->get('session')->getFlashBag()->add('success', 'Utilisateur modifié avec succès');
  7301. return $this->redirectToRoute('manager_managers_edit', ["id" => $account->getId()]);
  7302. }
  7303. }
  7304. return $this->render('app/managers/form.html.twig', [
  7305. 'form' => $form->createView(),
  7306. 'title' => "Modifier un utilisateur",
  7307. ]);
  7308. }
  7309. /**
  7310. * @Route("/flash-energie/notification", name="managers_flash-energie_notification")
  7311. */
  7312. public function managersFlashEnergieNotificationAction(Request $request, EntityManagerInterface $em)
  7313. {
  7314. if (!$this->getUser()->getManager()->getAdmin()) {
  7315. throw new NotFoundHttpException();
  7316. }
  7317. $form = $this->createFormBuilder()
  7318. ->add('title', TextType::class, [
  7319. 'attr' => [
  7320. 'placeholder' => 'Titre',
  7321. ],
  7322. 'label' => 'Titre de la notification',
  7323. 'required' => true,
  7324. 'mapped' => false,
  7325. ])
  7326. ->add('message', TextType::class, [
  7327. 'attr' => [
  7328. 'placeholder' => 'Message',
  7329. ],
  7330. 'label' => 'Message de la notification',
  7331. 'required' => true,
  7332. 'mapped' => false,
  7333. ])
  7334. ->add('sendAfter', DateTimeType::class, [
  7335. 'attr' => [
  7336. 'placeholder' => 'Date d\'envoi',
  7337. ],
  7338. 'label' => 'Date et heure d\'envoi',
  7339. 'required' => false,
  7340. 'mapped' => false,
  7341. ])->getForm();
  7342. $form->handleRequest($request);
  7343. if ($form->isSubmitted() && !$form->isValid()) {
  7344. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7345. }
  7346. if ($form->isSubmitted() && $form->isValid()) {
  7347. $title = $form['title']->getData();
  7348. $message = $form['message']->getData();
  7349. $sendAfter = $form['sendAfter']->getData();
  7350. $devices = $em->getRepository(Device::class)->findAll();
  7351. foreach ($devices as $device) {
  7352. $notification = new Notification();
  7353. $notification->setTitle($title);
  7354. $notification->setMessage($message);
  7355. $notification->setDevice($device);
  7356. if ($sendAfter) {
  7357. $notification->setSendAfter($sendAfter);
  7358. }
  7359. $em->persist($notification);
  7360. }
  7361. $em->flush();
  7362. $this->get('session')->getFlashBag()->add('success', 'L\'envoi de la notification a bien été programmé');
  7363. }
  7364. return $this->render('app/flash-energie/notifications/form.html.twig', [
  7365. 'form' => $form->createView(),
  7366. ]);
  7367. }
  7368. /**
  7369. * @Route("/flash-energie/offers-individual", name="managers_flash-energie_offers-individual")
  7370. */
  7371. public function managersFlashEnergieOffersIndividualAction(Request $request, EntityManagerInterface $em)
  7372. {
  7373. if (!$this->getUser()->getManager()->getAdmin()) {
  7374. throw new NotFoundHttpException();
  7375. }
  7376. $form = $this->createFormBuilder()
  7377. ->add('emplacement1', EntityType::class, [
  7378. "class" => OfferIndividual::class,
  7379. "label" => "Choix 1",
  7380. "required" => false,
  7381. 'query_builder' => function (EntityRepository $er) {
  7382. $qb = $er->createQueryBuilder('o');
  7383. $qb->where('o.type = \'ELEC\'');
  7384. return $qb;
  7385. },
  7386. 'choice_label' => function($offerInd) {
  7387. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7388. },
  7389. ])
  7390. ->add('emplacement2', EntityType::class, [
  7391. "class" => OfferIndividual::class,
  7392. "label" => "Choix 2",
  7393. "required" => false,
  7394. 'query_builder' => function (EntityRepository $er) {
  7395. $qb = $er->createQueryBuilder('o');
  7396. $qb->where('o.type = \'ELEC\'');
  7397. return $qb;
  7398. },
  7399. 'choice_label' => function($offerInd) {
  7400. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7401. },
  7402. ])
  7403. ->add('emplacement3', EntityType::class, [
  7404. "class" => OfferIndividual::class,
  7405. "label" => "Choix 3",
  7406. "required" => false,
  7407. 'query_builder' => function (EntityRepository $er) {
  7408. $qb = $er->createQueryBuilder('o');
  7409. $qb->where('o.type = \'ELEC\'');
  7410. return $qb;
  7411. },
  7412. 'choice_label' => function($offerInd) {
  7413. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7414. },
  7415. ])
  7416. ->add('emplacement4', EntityType::class, [
  7417. "class" => OfferIndividual::class,
  7418. "label" => "Choix 4",
  7419. "required" => false,
  7420. 'query_builder' => function (EntityRepository $er) {
  7421. $qb = $er->createQueryBuilder('o');
  7422. $qb->where('o.type = \'ELEC\'');
  7423. return $qb;
  7424. },
  7425. 'choice_label' => function($offerInd) {
  7426. return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
  7427. },
  7428. ])
  7429. ->getForm();
  7430. $form['emplacement1']->setData($this->findOfferIndividuelByEmplacement("1", $em));
  7431. $form['emplacement2']->setData($this->findOfferIndividuelByEmplacement("2", $em));
  7432. $form['emplacement3']->setData($this->findOfferIndividuelByEmplacement("3", $em));
  7433. $form['emplacement4']->setData($this->findOfferIndividuelByEmplacement("4", $em));
  7434. $form->handleRequest($request);
  7435. if ($form->isSubmitted() && $form->isValid()) {
  7436. $emplacement1 = $form['emplacement1']->getData();
  7437. $this->setOfferIndividualEmplacement($emplacement1, "1", $em);
  7438. $emplacement2 = $form['emplacement2']->getData();
  7439. $this->setOfferIndividualEmplacement($emplacement2, "2", $em);
  7440. $emplacement3 = $form['emplacement3']->getData();
  7441. $this->setOfferIndividualEmplacement($emplacement3, "3", $em);
  7442. $emplacement4 = $form['emplacement4']->getData();
  7443. $this->setOfferIndividualEmplacement($emplacement4, "4", $em);
  7444. }
  7445. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7446. $offersGaz = $em->getRepository(OfferIndividual::class)->findBy(["type" => "GAZ"]);
  7447. $offersDual = $em->getRepository(OfferIndividual::class)->findBy(["type" => "DUAL"]);
  7448. return $this->render('app/flash-energie/offers-individual/list.html.twig', [
  7449. 'offersElec' => $offersElec,
  7450. 'offersGaz' => $offersGaz,
  7451. 'offersDual' => $offersDual,
  7452. 'form' => $form->createView(),
  7453. ]);
  7454. }
  7455. private function setOfferIndividualEmplacement(?OfferIndividual $offerIndividual, ?string $emplacement, EntityManagerInterface $em): void
  7456. {
  7457. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7458. foreach ($offersElec as $offer) {
  7459. $emplacements = explode(';', $offer->getEmplacements());
  7460. if ($offerIndividual) {
  7461. if ($offer->getId() == $offerIndividual->getId()) {
  7462. if (!in_array($emplacement, $emplacements)) {
  7463. $emplacements[] = $emplacement;
  7464. }
  7465. } else {
  7466. if (in_array($emplacement, $emplacements)) {
  7467. $emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
  7468. return $value !== $emplacement;
  7469. });
  7470. $emplacements = array_values($emplacements);
  7471. }
  7472. }
  7473. } else {
  7474. if (in_array($emplacement, $emplacements)) {
  7475. $emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
  7476. return $value !== $emplacement;
  7477. });
  7478. $emplacements = array_values($emplacements);
  7479. }
  7480. }
  7481. $offer->setEmplacements(implode(";", $emplacements));
  7482. }
  7483. $em->flush();
  7484. }
  7485. private function findOfferIndividuelByEmplacement(string $emplacement, EntityManagerInterface $em)
  7486. {
  7487. $offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
  7488. foreach ($offersElec as $offer) {
  7489. $emplacements = explode(';', $offer->getEmplacements());
  7490. if (in_array($emplacement, $emplacements)) {
  7491. return $offer;
  7492. }
  7493. }
  7494. return null;
  7495. }
  7496. /**
  7497. * @Route("/flash-energie/offers-individual/add", name="managers_flash-energie_offers-individual_add")
  7498. */
  7499. public function managersFlashEnergieOffersIndividualAddAction(Request $request, EntityManagerInterface $em)
  7500. {
  7501. if (!$this->getUser()->getManager()->getAdmin()) {
  7502. throw new NotFoundHttpException();
  7503. }
  7504. $offer = new OfferIndividual();
  7505. $form = $this->createForm(OfferIndividualType::class, $offer);
  7506. $form->handleRequest($request);
  7507. if ($form->isSubmitted() && !$form->isValid()) {
  7508. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7509. }
  7510. if ($form->isSubmitted() && $form->isValid()) {
  7511. $offer->setCreationDate(new \DateTime('now'));
  7512. $em->persist($offer);
  7513. $em->flush();
  7514. $this->get('session')->getFlashBag()->add('success', 'Offre ajoutée avec succès');
  7515. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7516. }
  7517. return $this->render('app/flash-energie/offers-individual/form.html.twig', [
  7518. 'offer' => $offer,
  7519. 'form' => $form->createView(),
  7520. ]);
  7521. }
  7522. /**
  7523. * @Route("/flash-energie/offers-individual/{id}/edit", name="managers_flash-energie_offers-individual_edit")
  7524. */
  7525. public function managersFlashEnergieOffersIndividualEditAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7526. {
  7527. if (!$this->getUser()->getManager()->getAdmin()) {
  7528. throw new NotFoundHttpException();
  7529. }
  7530. $form = $this->createForm(OfferIndividualType::class, $offer);
  7531. $form->handleRequest($request);
  7532. if ($form->isSubmitted() && !$form->isValid()) {
  7533. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7534. }
  7535. if ($form->isSubmitted() && $form->isValid()) {
  7536. $em->flush();
  7537. $this->get('session')->getFlashBag()->add('success', 'Offre modifiée avec succès');
  7538. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7539. }
  7540. return $this->render('app/flash-energie/offers-individual/form.html.twig', [
  7541. 'offer' => $offer,
  7542. 'form' => $form->createView(),
  7543. ]);
  7544. }
  7545. /**
  7546. * @Route("/flash-energie/offers-individual/{id}/active", name="managers_flash-energie_offers-individual_active")
  7547. */
  7548. public function managersFlashEnergieOffersIndividualActiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7549. {
  7550. if (!$this->getUser()->getManager()->getAdmin()) {
  7551. throw new NotFoundHttpException();
  7552. }
  7553. $offersByType = $em->getRepository(OfferIndividual::class)->findBy(["type" => $offer->getType()]);
  7554. foreach ($offersByType as $offer2) {
  7555. $offer2->setActive(false);
  7556. }
  7557. $offer->setActive(true);
  7558. $em->flush();
  7559. $this->get('session')->getFlashBag()->add('success', 'Offre activée avec succès');
  7560. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7561. }
  7562. /**
  7563. * @Route("/flash-energie/offers-individual/{id}/deactive", name="managers_flash-energie_offers-individual_deactive")
  7564. */
  7565. public function managersFlashEnergieOffersIndividualDeactiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
  7566. {
  7567. if (!$this->getUser()->getManager()->getAdmin()) {
  7568. throw new NotFoundHttpException();
  7569. }
  7570. $offer->setActive(false);
  7571. $em->flush();
  7572. $this->get('session')->getFlashBag()->add('success', 'Offre désactivée avec succès');
  7573. return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
  7574. }
  7575. /**
  7576. * @Route("/docusign/connexion-api", name="managers_docusign_connexion-api")
  7577. */
  7578. public function managersDocusignConnexionApiAction(Request $request, DocusignService $docusignService)
  7579. {
  7580. if (!$this->getUser()->getManager()->getAdmin()) {
  7581. throw new NotFoundHttpException();
  7582. }
  7583. $connected = false;
  7584. $accessToken = $docusignService->getAccessToken();
  7585. if ($accessToken) {
  7586. $connected = true;
  7587. }
  7588. $form = $this->createFormBuilder()
  7589. ->add("email", TextType::class, [
  7590. 'label' => "Adresse e-mail",
  7591. 'required' => true,
  7592. ])
  7593. ->add("file", FileType::class, [
  7594. 'label' => "Fichier à signer",
  7595. 'required' => true,
  7596. ])
  7597. ->getForm();
  7598. $form->handleRequest($request);
  7599. if ($form->isSubmitted() && $form->isValid()) {
  7600. if ($accessToken) {
  7601. try {
  7602. $file = $form->get("file")->getData();
  7603. $procedureSign = new ProcedureSign();
  7604. $procedureSign->setFirstName("Test");
  7605. $procedureSign->setLastName("Flash");
  7606. $procedureSign->setEmail($form->get("email")->getData());
  7607. $procedureSign->setPhone("0600000000");
  7608. $procedureSign->setCreationDate(new \DateTime('now'));
  7609. $procedureSign->setNameFile($file->getClientOriginalName());
  7610. $procedureSign->setFilePath($file->getPathname());
  7611. $response = $docusignService->sendFile($accessToken, $procedureSign);
  7612. $this->get('session')->getFlashBag()->add('success', 'Document envoyé pour signature, réf: '.$response->getEnvelopeId());
  7613. } catch (ApiException $e) {
  7614. $this->get('session')->getFlashBag()->add('danger', 'L\'envoi a echoué');
  7615. var_dump($e);
  7616. }
  7617. }
  7618. }
  7619. return $this->render('app/docusign/connexion-api.html.twig', [
  7620. "connected" => $connected,
  7621. "authorizationURL" => $docusignService->getAuthorizationURL(),
  7622. "form" => $form->createView(),
  7623. ]);
  7624. }
  7625. /**
  7626. * @Route("/actions", name="actions")
  7627. */
  7628. public function managersActionsAction()
  7629. {
  7630. if (!$this->getUser()->getManager()->getAdmin()) {
  7631. throw new NotFoundHttpException();
  7632. }
  7633. return $this->render('app/actions/index.html.twig', [
  7634. ]);
  7635. }
  7636. /**
  7637. * @Route("/actions/affect-unaffected-cotations", name="actions_affect-unaffected-cotations")
  7638. */
  7639. public function managersActionsAffectUnaffectedCotationsAction(EntityManagerInterface $em)
  7640. {
  7641. if (!$this->getUser()->getManager()->getAdmin()) {
  7642. throw new NotFoundHttpException();
  7643. }
  7644. $unaffectedCotations = $em->getRepository(Cotation::class)->findBy(["manager" => null]);
  7645. $affected = 0;
  7646. foreach ($unaffectedCotations as $cotation) {
  7647. if ($cotation->getCompany() && $cotation->getCompany()->getUser() && $cotation->getCompany()->getUser()->getManager()) {
  7648. $cotation->setManager($cotation->getCompany()->getUser()->getManager());
  7649. $affected++;
  7650. }
  7651. }
  7652. $em->flush();
  7653. $this->get('session')->getFlashBag()->add('success', $affected.' cotation(s) affectée(s).');
  7654. return $this->redirectToRoute('manager_actions');
  7655. }
  7656. /**
  7657. * @Route("/actions/affect-unaffected-contracts", name="actions_affect-unaffected-contracts")
  7658. */
  7659. public function managersActionsAffectUnaffectedContractsAction(EntityManagerInterface $em)
  7660. {
  7661. if (!$this->getUser()->getManager()->getAdmin()) {
  7662. throw new NotFoundHttpException();
  7663. }
  7664. $unaffectedContracts = $em->getRepository(Contract::class)->findBy(["manager" => null]);
  7665. $affected = 0;
  7666. foreach ($unaffectedContracts as $contract) {
  7667. if ($contract->getCompany() && $contract->getCompany()->getUser() && $contract->getCompany()->getUser()->getManager()) {
  7668. $contract->setManager($contract->getCompany()->getUser()->getManager());
  7669. $affected++;
  7670. }
  7671. }
  7672. $em->flush();
  7673. $this->get('session')->getFlashBag()->add('success', $affected.' contrat(s) affecté(s).');
  7674. return $this->redirectToRoute('manager_actions');
  7675. }
  7676. /**
  7677. * @Route("/cotation-document/{id}/file", name="cotation-document_file")
  7678. */
  7679. public function cotationDocumentFileAction(Request $request, EntityManagerInterface $em, CotationDocument $cotationDocument)
  7680. {
  7681. if (!$this->getUser()->getManager()->getAdmin()) {
  7682. if ($cotationDocument->getCotation()->getCompany()->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$cotationDocument->getCotation()->getCompany()->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
  7683. throw new NotFoundHttpException();
  7684. }
  7685. }
  7686. if ($cotationDocument->getPath()) {
  7687. $filePath = $this->getParameter('documents_justificatif_directory') . $cotationDocument->getPath();
  7688. return $this->file($filePath, $cotationDocument->getPath(), ResponseHeaderBag::DISPOSITION_INLINE);
  7689. }
  7690. throw new NotFoundHttpException();
  7691. }
  7692. /**
  7693. * @Route("/test-template", name="managers_test-template")
  7694. */
  7695. public function managersTestTemplateAction(Request $request, EntityManagerInterface $em, YousignService $yousignService)
  7696. {
  7697. if (!$this->getUser()->getManager()->getAdmin()) {
  7698. throw new NotFoundHttpException();
  7699. }
  7700. $form = $this->createFormBuilder()
  7701. ->add('supplier', EntityType::class, [
  7702. "class" => Supplier::class,
  7703. "label" => "Fournisseur",
  7704. "placeholder" => "Fournisseur",
  7705. "required" => true,
  7706. 'mapped' => false,
  7707. ])
  7708. ->add('file', FileType::class, [
  7709. "label" => "Fichier",
  7710. "required" => true,
  7711. 'mapped' => false,
  7712. ])
  7713. ->add('email', EmailType::class, [
  7714. 'attr' => [
  7715. 'placeholder' => 'Email',
  7716. ],
  7717. "data" => "david@slapp.me",
  7718. 'label' => 'Destinataire (email)',
  7719. 'required' => true,
  7720. 'mapped' => false,
  7721. ])
  7722. ->add('sepaIban', TextType::class, [
  7723. "label" => "IBAN",
  7724. "data" => "FR7611315000011234567890138",
  7725. "attr" => [
  7726. "placeholder" => "FR",
  7727. ],
  7728. "required" => false,
  7729. ])
  7730. ->add('sepaBic', TextType::class, [
  7731. "label" => "BIC",
  7732. "data" => "INGBFR18XXX",
  7733. "attr" => [
  7734. "placeholder" => "",
  7735. ],
  7736. "required" => false,
  7737. ])->getForm();
  7738. $form->handleRequest($request);
  7739. if ($form->isSubmitted() && !$form->isValid()) {
  7740. $this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
  7741. }
  7742. if ($form->isSubmitted() && $form->isValid()) {
  7743. $supplier = $form['supplier']->getData();
  7744. $file = $form['file']->getData();
  7745. $email = $form['email']->getData();
  7746. $sepaIban = $form['sepaIban']->getData();
  7747. $sepaBic = $form['sepaBic']->getData();
  7748. $extension = $file->guessExtension();
  7749. if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
  7750. $this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
  7751. return $this->render('app/test_template.html.twig', [
  7752. 'form' => $form->createView(),
  7753. ]);
  7754. }
  7755. $fileName = "test-template_" . md5(uniqid()) . '.' . $extension;
  7756. $file->move(
  7757. $this->getParameter('documents_justificatif_directory'),
  7758. $fileName
  7759. );
  7760. $filePath = $this->getParameter('documents_justificatif_directory').$fileName;
  7761. $cotation = $em->getRepository(Cotation::class)->find(26);
  7762. $company = $cotation->getCompany();
  7763. // Création de la procédure
  7764. $procedureSign = new ProcedureSign();
  7765. $procedureSign->setUser($cotation->getUser());
  7766. $procedureSign->setFirstName($cotation->getFirstName());
  7767. $procedureSign->setLastName($cotation->getLastName());
  7768. $procedureSign->setEmail($email);
  7769. $procedureSign->setPhone("0604176553");
  7770. $procedureSign->setCreationDate(new \DateTime('now'));
  7771. $procedureSign->setNameFile($fileName);
  7772. $procedureSign->setFilePath($filePath);
  7773. $content = [
  7774. "type" => "cotation.test",
  7775. "id" => $cotation->getId()
  7776. ];
  7777. $procedureSign->setContent(json_encode($content));
  7778. $em->persist($procedureSign);
  7779. $em->flush();
  7780. // Création de la position
  7781. $yousignPosition = new YousignPosition();
  7782. $yousignPosition->setReason("Signé par ".$cotation->getFirstName().' '.$cotation->getLastName());
  7783. $contract = new Contract();
  7784. $contract->setCompany($company);
  7785. $contract->setSepaBic($sepaBic);
  7786. $contract->setSepaIban($sepaIban);
  7787. $contract->setCity("Toulouse");
  7788. $contract->setPdlNumber("1234565432");
  7789. $contract->setElectricity(true);
  7790. $pdf = $yousignService->applyTemplate($yousignPosition, $filePath, $supplier->getCodeTemplate(), $contract);
  7791. // Lancement de la signature
  7792. /* $startSign = $yousignService->startSign($procedureSign, $yousignPosition);
  7793. if ($startSign) {
  7794. $this->get('session')->getFlashBag()->add('success', 'Top, c\'est envoyé !');
  7795. }*/
  7796. $pdf->Output($fileName,'I');
  7797. }
  7798. return $this->render('app/test_template.html.twig', [
  7799. 'form' => $form->createView(),
  7800. ]);
  7801. }
  7802. private function newContratForCompany(Company $company, EntityManagerInterface $em): Contract
  7803. {
  7804. $contract = new Contract();
  7805. $contract->setUser($company->getUser());
  7806. $contract->setCompany($company);
  7807. $contract->setAddress($company->getAddress());
  7808. $contract->setAddress2($company->getAddress2());
  7809. $contract->setZipCode($company->getZipCode());
  7810. $contract->setCity($company->getZipCode());
  7811. $contract->setManager($this->getUser()->getManager());
  7812. $contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
  7813. $contract->setState($contratStateEnAttenteClient);
  7814. return $contract;
  7815. }
  7816. private function roadmapEngieProToContract(
  7817. Roadmap $roadmap,
  7818. Company $company,
  7819. ?bool $elec,
  7820. ?string $powerSubscribed,
  7821. ?SituationGasElec $eSituation,
  7822. ?string $eSegment,
  7823. \DateTime $eCommitmentDate,
  7824. ?int $eDuree,
  7825. ?string $eOptEnergieVerte,
  7826. ?bool $gas,
  7827. ?string $quantityConsumed,
  7828. ?SituationGasElec $gSituation,
  7829. ?string $gSegment,
  7830. \DateTime $gCommitmentDate,
  7831. ?int $gDuree,
  7832. ?string $gOptEnergieVerte,
  7833. EntityManagerInterface $em)
  7834. {
  7835. $twoContracts = ($elec && $gas && $eCommitmentDate != $gCommitmentDate);
  7836. $contract = $this->newContratForCompany($company, $em);
  7837. $contract->setEngiePro(true);
  7838. if ($elec) {
  7839. $contract->setElectricity(true);
  7840. $contract->setPdlNumber($company->getPdlNumber());
  7841. $contract->setSubscribedKvaPower($powerSubscribed);
  7842. $contract->setElectricitySituation($eSituation);
  7843. $contract->setEffectiveDate($eCommitmentDate);
  7844. if ($eDuree && $eDuree > 0) {
  7845. $expiryDate = clone $eCommitmentDate;
  7846. $expiryDate->modify('+ '.$eDuree.' years');
  7847. $contract->setExpiryDate($expiryDate);
  7848. }
  7849. $contract->setEngieProESegment($eSegment);
  7850. $contract->setEngieProEOptEnergieVerte($eOptEnergieVerte);
  7851. }
  7852. if ($gas && $twoContracts) {
  7853. $em->persist($contract);
  7854. $em->flush();
  7855. $contract = $this->newContratForCompany($company, $em);
  7856. $contract->setEngiePro(true);
  7857. $contract->setEffectiveDate($gCommitmentDate);
  7858. if ($gDuree && $gDuree > 0) {
  7859. $expiryDate = clone $gCommitmentDate;
  7860. $expiryDate->modify('+ '.$gDuree.' years');
  7861. $contract->setExpiryDate($expiryDate);
  7862. }
  7863. }
  7864. if ($gas) {
  7865. $contract->setGas(true);
  7866. $contract->setPceNumber($company->getPceNumber());
  7867. $contract->setGasSituation($gSituation);
  7868. $contract->setGasMeterReadingM3($quantityConsumed);
  7869. $contract->setEngieProGSegment($gSegment);
  7870. $contract->setEngieProGOptEnergieVerte($gOptEnergieVerte);
  7871. }
  7872. $em->persist($contract);
  7873. $em->flush();
  7874. }
  7875. private function roadmapTelecomToContract(
  7876. Roadmap $roadmap,
  7877. Company $company,
  7878. ?string $offer,
  7879. ?string $duration,
  7880. ?bool $optionPremium,
  7881. ?string $rio,
  7882. EntityManagerInterface $em)
  7883. {
  7884. $contract = $this->newContratForCompany($company, $em);
  7885. $contract->setTelecom(true);
  7886. $contract->setTelecomOffer($offer);
  7887. $contract->setTelecomDuration($duration);
  7888. $contract->setTelecomOptionPremium($optionPremium);
  7889. $contract->setTelecomRio($rio);
  7890. $em->persist($contract);
  7891. $em->flush();
  7892. }
  7893. private function roadmapPhotovoltaiqueToContract(
  7894. Roadmap $roadmap,
  7895. Company $company,
  7896. ?string $buildintType,
  7897. ?string $buildingYear,
  7898. ?string $surface,
  7899. ?string $exposition,
  7900. ?string $mainMaterial,
  7901. ?bool $recentWork,
  7902. EntityManagerInterface $em)
  7903. {
  7904. $contract = $this->newContratForCompany($company, $em);
  7905. $contract->setPhotovoltaique(true);
  7906. $contract->setPhotovBuildingType($buildintType);
  7907. $contract->setPhotovBuildingYear($buildingYear);
  7908. $contract->setPhotovSurface($surface);
  7909. $contract->setPhotovExposition($exposition);
  7910. $contract->setPhotovMainMaterial($mainMaterial);
  7911. $contract->setPhotovRecentWork($recentWork);
  7912. $em->persist($contract);
  7913. $em->flush();
  7914. }
  7915. }