<?php
namespace App\Controller;
use App\Entity\Account;
use App\Entity\Company;
use App\Entity\Contract;
use App\Entity\ContractState;
use App\Entity\Cotation;
use App\Entity\CotationDocument;
use App\Entity\CotationMultisite;
use App\Entity\CotationState;
use App\Entity\Device;
use App\Entity\Document;
use App\Entity\Manager;
use App\Entity\Notification;
use App\Entity\OfferElec;
use App\Entity\OfferGaz;
use App\Entity\OfferIndividual;
use App\Entity\ProcedureSign;
use App\Entity\Roadmap;
use App\Entity\SituationGasElec;
use App\Entity\Supplier;
use App\Entity\User;
use App\Form\CompanyType;
use App\Form\ContractType;
use App\Form\CotationMultisiteType;
use App\Form\CotationType;
use App\Form\DocumentType;
use App\Form\ManagerType;
use App\Form\OfferElecType;
use App\Form\OfferGazType;
use App\Form\OfferIndividualType;
use App\Form\RoadmapType;
use App\Form\SupplierType;
use App\Form\UserType;
use App\Repository\CompanyRepository;
use App\Resources\YousignPosition;
use App\Security\PasswordEncoder;
use App\Form\AccountType;
use App\Service\DocusignService;
use App\Service\EllisphereService;
use App\Service\EnedisService;
use App\Service\OfferCalculatorService;
use App\Service\SendEmailService;
use App\Service\TurpeCalculatorService;
use App\Service\YousignService;
use Doctrine\DBAL\Exception\DriverException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use DocuSign\eSign\Client\ApiException;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\Pdf;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use setasign\Fpdi\Tcpdf\Fpdi;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use TCPDF;
/**
* Class ManagerController
* @package App\Controller
*
* @Route("/manager", name="manager_")
*/
class ManagerController extends AbstractController
{
/**
* @Route("", name="homepage")
*/
public function indexAction(Request $request, EntityManagerInterface $em)
{
setlocale(LC_ALL, 'fr_FR');
if ($this->getUser()->getManager()->getAdmin()) {
$contracts = $em->getRepository(Contract::class)->findByExpiryDateBeforeOneYear(null, 15);
} else {
$contracts = $em->getRepository(Contract::class)->findByExpiryDateBeforeOneYear($this->getUser()->getManager(), 15);
}
$documents = $em->getRepository(Document::class)->findBy(["visible" => true], ["creationDate" => "DESC"]);
// Chart
$now = new \DateTime('now');
$x_labels = [utf8_encode(strftime("%b", $now->getTimestamp()))];
for ($i=0; $i < 5; $i++) {
$m = $now->modify('-1 month');
$x_labels[] = utf8_encode(strftime("%b", $m->getTimestamp()));
}
$x_labels = array_reverse($x_labels);
$now = new \DateTime('now');
if ($this->getUser()->getManager()->getAdmin()) {
$q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"));
$y_ca = [$q["ca"] ?: 0];
$y_nb = [$q["nb"] ?: 0];
} else {
$q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"), $this->getUser()->getManager());
$y_ca = [$q["ca"] ?: 0];
$y_nb = [$q["nb"] ?: 0];
}
for ($i=0; $i < 5; $i++) {
$m = $now->modify('-1 month');
if ($this->getUser()->getManager()->getAdmin()) {
$q = $em->getRepository(Contract::class)->getCa($m->format("m"), $now->format("Y"));
$y_ca[] = $q["ca"] ?: 0;
$y_nb[] = $q["nb"] ?: 0;
} else {
$q = $em->getRepository(Contract::class)->getCa($now->format("m"), $now->format("Y"), $this->getUser()->getManager());
$y_ca[] = $q["ca"] ?: 0;
$y_nb[] = $q["nb"] ?: 0;
}
}
$y_ca = array_reverse($y_ca);
$y_nb = array_reverse($y_nb);
$now = new \DateTime('now');
return $this->render("app/dashboard.html.twig", [
'contracts' => $contracts,
'documents' => $documents,
'month_string' => strftime("%B %Y", $now->getTimestamp()),
'x_labels' => $x_labels,
"y_ca" => $y_ca,
"y_nb" => $y_nb,
]);
}
/**
* @Route("/account", name="account")
*/
public function accountAction(Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
{
$account = $this->getUser();
$r_email = $account->getEmail();
$form = $this->createForm(AccountType::class, $account);
$form["firstName"]->setData($account->getManager()->getFirstName());
$form["lastName"]->setData($account->getManager()->getLastName());
$form2 = $this->createFormBuilder()
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'Les mot de passe ne sont pas identiques',
'first_options' => array(
'attr' => array(
'placeholder' => 'Nouveau mot de passe'
),
'label' => "Nouveau mot de passe"
),
'second_options' => array('attr' => array('placeholder' => 'Confirmez le mot de passe'), 'label' => "Confirmez le mot de passe"),
'label' => false,
'mapped' => false
))->getForm();
$form->handleRequest($request);
$form2->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$error = false;
if ($r_email != $account->getEmail()) {
if (filter_var($account->getEmail(), FILTER_VALIDATE_EMAIL)) {
$other_account = $em->getRepository(Account::class)->findOneBy(['email' => $account->getEmail()]);
if ($other_account && $other_account->getId() != $account->getId()) {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
}
} else {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
}
}
if (!$error) {
$account->getManager()->setFirstName($form['firstName']->getData());
$account->getManager()->setLastName($form['lastName']->getData());
$em->flush();
$oldToken = $this->get('security.token_storage')->getToken();
$token = new UsernamePasswordToken(
$account, //user object with updated username
null,
$oldToken->getProviderKey(),
$oldToken->getRoles()
);
$this->get('security.token_storage')->setToken($token);
$this->get('session')->getFlashBag()->add('success', 'Profil mis à jour avec succès');
return $this->redirectToRoute('manager_account');
}
}
if ($form2->isSubmitted() && $form2->isValid()) {
$salt = md5(uniqid());
$pwd = $form2['password']->getData();
$account->setSalt($salt);
$enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
$account->setPassword($enc_pwd);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Mot de passe mis à jour');
return $this->redirectToRoute('manager_account');
}
return $this->render('app/account.html.twig', [
'form' => $form->createView(),
'form2' => $form2->createView(),
]);
}
/**
* @Route("/suppliers", name="suppliers")
*/
public function suppliersAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$suppliers = $em->getRepository(Supplier::class)->findAll();
return $this->render("app/suppliers/list.html.twig", [
"suppliers" => $suppliers
]);
}
/**
* @Route("/suppliers/add", name="suppliers_add")
*/
public function suppliersAddAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$supplier = new Supplier();
$supplier->setGas(true);
$supplier->setElectricity(true);
$form = $this->createForm(SupplierType::class, $supplier);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($supplier);
$em->flush();
$logo = $form['logo']->getData();
if ($logo) {
$extension = $logo->guessExtension();
if (!$extension || !in_array($extension, ["png", "jpeg", "jpg", "gif", "svg"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le logo");
} else {
$fileName = $supplier->getId() . "_" . md5(uniqid()) . '.' . $extension;
$logo->move(
$this->getParameter('documents_logos_directory'),
$fileName
);
$supplier->setLogo($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Nouveau fournisseur ajouté");
return $this->redirectToRoute("manager_suppliers");
}
return $this->render("app/suppliers/form.html.twig", [
"form" => $form->createView(),
"title" => "Ajouter un fournisseur",
]);
}
/**
* @Route("/suppliers/{supplier}/edit", name="suppliers_edit")
*/
public function suppliersEditAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$form = $this->createForm(SupplierType::class, $supplier);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$logo = $form['logo']->getData();
if ($logo) {
$extension = $logo->guessExtension();
if (!$extension || !in_array($extension, ["png", "jpeg", "jpg", "gif", "svg"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le logo");
} else {
$fileName = $supplier->getId() . "_" . md5(uniqid()) . '.' . $extension;
$logo->move(
$this->getParameter('documents_logos_directory'),
$fileName
);
$supplier->setLogo($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Fournisseur mis à jour");
return $this->redirectToRoute("manager_suppliers");
}
return $this->render("app/suppliers/form.html.twig", [
"form" => $form->createView(),
"title" => "Modifier un fournisseur",
]);
}
/**
* @Route("/suppliers/{supplier}/active", name="suppliers_active")
*/
public function suppliersActiveAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$supplier->setActive(true);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Fournisseur activé");
return $this->redirectToRoute("manager_suppliers");
}
/**
* @Route("/suppliers/{supplier}/deactive", name="suppliers_deactive")
*/
public function suppliersDeactiveAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$supplier->setActive(false);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Fournisseur désactivé");
return $this->redirectToRoute("manager_suppliers");
}
/**
* @Route("/suppliers/{supplier}/delete", name="suppliers_delete")
*/
public function suppliersDeleteAction(Request $request, EntityManagerInterface $em, Supplier $supplier)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
// On vérifie que le fournisseur n'est pas associé à un contrat, une cotation ou une offre
$contrats = $em->getRepository(Contract::class)->findBy(['supplier' => $supplier]);
if ($contrats && count($contrats) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des contrats.");
return $this->redirectToRoute("manager_suppliers");
}
$cotations = $em->getRepository(Cotation::class)->findBy(['desiredSupplier' => $supplier]);
if ($cotations && count($cotations) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
return $this->redirectToRoute("manager_suppliers");
}
$cotations = $em->getRepository(Cotation::class)->findBy(['eDesiredSuppliers' => $supplier]);
if ($cotations && count($cotations) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
return $this->redirectToRoute("manager_suppliers");
}
$cotations = $em->getRepository(Cotation::class)->findBy(['gDesiredSuppliers' => $supplier]);
if ($cotations && count($cotations) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
return $this->redirectToRoute("manager_suppliers");
}
$cotations = $em->getRepository(Cotation::class)->findBy(['electricitySupplier' => $supplier]);
if ($cotations && count($cotations) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
return $this->redirectToRoute("manager_suppliers");
}
$cotations = $em->getRepository(Cotation::class)->findBy(['gasSupplier' => $supplier]);
if ($cotations && count($cotations) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des cotations.");
return $this->redirectToRoute("manager_suppliers");
}
$offersElec = $em->getRepository(OfferElec::class)->findBy(['supplier' => $supplier]);
if ($offersElec && count($offersElec) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des offres.");
return $this->redirectToRoute("manager_suppliers");
}
$offersGaz = $em->getRepository(OfferGaz::class)->findBy(['supplier' => $supplier]);
if ($offersGaz && count($offersGaz) > 0) {
$this->get("session")->getFlashBag()->add("danger", "Ce fournisseur est associé à des offres.");
return $this->redirectToRoute("manager_suppliers");
}
try {
$em->remove($supplier);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Fournisseur supprimé");
} catch (\Exception $e) {
$this->get("session")->getFlashBag()->add("danger", "Impossible de supprimer ce fournisseur.");
}
return $this->redirectToRoute("manager_suppliers");
}
/**
* @Route("/clients", name="clients")
*/
public function clientsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
{
$page = $request->get("page");
if (!is_numeric($page) || $page < 1) {
$page = 1;
}
$nbByPage = 20;
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
if ($request->get("particulier")) {
if ($request->get("export") && $this->getUser()->getManager()->getAdmin()) {
$response = new StreamedResponse();
$users_export = $em->getRepository(User::class)->searchForTerms($keywords, null, true, false);
$response->setCallback(function () use ($users_export) {
$handle = fopen('php://output', 'w+');
fputcsv($handle, [], ';');
foreach ($users_export as $user) {
$data = array(
utf8_decode($user->getEmail()),
);
fputcsv($handle, $data, ';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Encoding', 'UTF-8');
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="export_particulier.csv"');
return $response;
}
if ($this->getUser()->getManager()->getAdmin()) {
$users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, true, false);
} else {
$users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), true, false);
}
return $this->render("app/clients/list.html.twig", [
"users_paginator" => $users_paginator,
"title" => "Clients particuliers",
"pro" => false,
]);
} elseif ($request->get("pro")) {
if ($request->get("export") && $this->getUser()->getManager()->getAdmin()) {
$response = new StreamedResponse();
$users_export = $em->getRepository(User::class)->searchForTerms($keywords, null, false, true);
$response->setCallback(function () use ($users_export) {
$handle = fopen('php://output', 'w+');
fputcsv($handle, [], ';');
foreach ($users_export as $user) {
$data = array(
utf8_decode($user->getEmail()),
);
fputcsv($handle, $data, ';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Encoding', 'UTF-8');
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="export_pro.csv"');
return $response;
}
$title = "Clients professionnels";
if ($request->get("onlyNotValidated") && $this->getUser()->getManager()->getAdmin()) {
$users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true, true);
$title = "Clients professionnels à valider";
} else {
if ($this->getUser()->getManager()->getAdmin()) {
$users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true);
} else {
$users_paginator = $em->getRepository(User::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), false, true);
}
}
return $this->render("app/clients/list.html.twig", [
"users_paginator" => $users_paginator,
"title" => $title,
"pro" => true,
"onlyNotValidated" => (bool) $request->get("onlyNotValidated"),
]);
}
throw new NotAcceptableHttpException();
}
/**
* @Route("/clients/archive", name="clients_archive")
*/
public function clientsArchiveAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$clientsId = $request->get("clientsId");
if (!$clientsId) {
throw new BadRequestHttpException("Missing clientsId.");
}
foreach (explode(";",$clientsId) as $clientId) {
$user = $em->getRepository(User::class)->find($clientId);
if ($user) {
$user->setArchived(true);
}
}
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Clients archivés avec succès");
$from = $request->get("from");
if ($from) {
return $this->redirect($from);
}
return $this->redirectToRoute("manager_clients", ["pro" => 1]);
}
/**
* @Route("/clients/add", name="clients_add")
*/
public function clientsAddAction(Request $request, EntityManagerInterface $em)
{
if ($request->get("particulier")) {
$user = new User();
$user->setGas(true);
$user->setElectricity(true);
$form = $this->createForm(UserType::class, $user);
if ($this->getUser()->getManager()->getAdmin()) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true');
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => true,
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$user->setCreationDate(new \DateTime("now"));
$user->setManager($this->getUser()->getManager());
$user->setPro(false);
$em->persist($user);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Nouveau client ajouté");
return $this->redirectToRoute("manager_clients_edit", ["user" => $user->getId()]);
}
return $this->render("app/clients/form.html.twig", [
"form" => $form->createView(),
"title" => "Ajouter un client",
]);
} elseif ($request->get("pro")) {
$company = new Company();
$roadmap = null;
if ($request->get("roadmap")) {
$roadmap = $em->getRepository(Roadmap::class)->find($request->get("roadmap"));
if ($roadmap) {
if (!$this->getUser()->getManager()->getAdmin()) {
if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId()) {
$roadmap = null;
}
}
if ($roadmap->getArchived()) {
$roadmap = null;
}
}
}
$form = $this->createForm(CompanyType::class, $company);
if ($roadmap) {
$company->setName($roadmap->getCompanyName());
$company->setSiret($roadmap->getSiret());
$company->setPhone($roadmap->getPhone());
$company->setEmail($roadmap->getEmail());
$company->setCity($roadmap->getSector());
// Engie PRO
if ($roadmap->getContractType()->getId() == 4) {
$form->add('powerSubscribed', TextType::class, [
"label" => "Puissance souscrite (kVA)",
"attr" => [
"placeholder" => "Puissance souscrite",
],
"mapped" => false,
"required" => false,
])
->add('eSituation', EntityType::class, [
"label" => "Situation",
'class' => SituationGasElec::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('s')
->where('s.electricity = true');
},
'choice_label' => 'libelle',
"mapped" => false,
"required" => false,
])
->add('eSegment', ChoiceType::class, [
"label" => "Segment",
"placeholder" => "Segment",
"choices" => [
"C1" => "C1",
"C2" => "C2",
"C3" => "C3",
"C4" => "C4",
"C5" => "C5",
],
"mapped" => false,
"required" => false,
])
->add('eDuree', ChoiceType::class, [
"label" => "Durée",
"placeholder" => "Durée",
"choices" => [
"1 an" => "1",
"2 ans" => "2",
"3 ans" => "3",
"Sans engagement" => "0",
],
"mapped" => false,
"required" => false,
])
->add('eCommitmentDate', DateType::class, [
"label" => "Date de début d'engagement",
'data' => new \DateTime(),
'widget' => 'single_text',
'html5' => true,
"mapped" => false,
"required" => false,
])
->add('eOptEnergieVerte', ChoiceType::class, [
"label" => "Option: Énergie verte",
"placeholder" => "Énergie verte",
"choices" => [
"Oui" => "100",
"Non" => "0",
],
"mapped" => false,
"required" => false,
])
->add('quantityConsumed', ChoiceType::class, [
"label" => "Quantité consommée",
'choices' => [
"0-6MWH" => "0-6MWH",
"6-30MWH" => "6-30MWH",
"30-50MWH" => "30-50MWH",
"50-100MWH" => "50-100MWH",
"100-200MWH" => "100-200MWH",
">200MWH" => ">200MWH",
],
"mapped" => false,
"required" => false,
])
->add('gSituation', EntityType::class, [
"label" => "Situation",
'class' => SituationGasElec::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('s')
->where('s.gas = true');
},
'choice_label' => 'libelle',
"mapped" => false,
"required" => false,
])
->add('gSegment', ChoiceType::class, [
"label" => "Segment",
"placeholder" => "Segment",
"choices" => [
"P1 (jusqu'à 5999 kWh)" => "P1",
"P2 (de 6000 à 29 999 kWh)" => "P2",
"P3 (plus de 30 000 kWh)" => "P3",
],
"mapped" => false,
"required" => false,
])
->add('gDuree', ChoiceType::class, [
"label" => "Durée",
"placeholder" => "Durée",
"choices" => [
"1 an" => "1",
"2 ans" => "2",
"3 ans" => "3",
"Sans engagement" => "0",
],
"mapped" => false,
"required" => false,
])
->add('gCommitmentDate', DateType::class, [
"label" => "Date de début d'engagement",
'data' => new \DateTime(),
'widget' => 'single_text',
'html5' => true,
"mapped" => false,
"required" => false,
])
->add('gOptEnergieVerte', ChoiceType::class, [
"label" => "Option: Énergie verte",
"placeholder" => "Énergie verte",
"choices" => [
"Oui" => "100",
"Non" => "0",
],
"mapped" => false,
"required" => false,
])
;
}
// TELECOM
if ($roadmap->getContractType()->getId() == 5) {
$form->add('offer', ChoiceType::class, [
"label" => "Offre",
"placeholder" => "Offre",
"choices" => [
"FREEBOX PRO" => "FREEBOX PRO",
"FREEBOX PRO + FORFAIT MOBILE FREE PRO" => "FREEBOX PRO + FORFAIT MOBILE FREE PRO",
],
"mapped" => false,
"required" => false,
])
->add('duree', ChoiceType::class, [
"label" => "Durée d'engagement",
"placeholder" => "Durée d'engagement",
"choices" => [
"24 mois" => "24",
"36 mois" => "36",
],
"mapped" => false,
"required" => false,
])
->add('optionPremium', CheckboxType::class, [
"label" => "Option premium",
"mapped" => false,
"required" => false,
])
->add('rio', TextType::class, [
"label" => "RIO (si option mobile et demande de transfert)",
"attr" => [
"placeholder" => "RIO",
],
"mapped" => false,
"required" => false,
])
;
}
// PHOTOVOLTAIQUE
if ($roadmap->getContractType()->getId() == 6) {
$form->add('buildingType', TextType::class, [
"label" => "Type de bâtisse",
"attr" => [
"placeholder" => "Type de bâtisse",
],
"mapped" => false,
"required" => false,
])
->add('buildingYear', TextType::class, [
"label" => "Année de construction",
"attr" => [
"placeholder" => "Année de construction",
],
"mapped" => false,
"required" => false,
])
->add('surface', TextType::class, [
"label" => "Surface",
"attr" => [
"placeholder" => "Surface",
],
"mapped" => false,
"required" => false,
])
->add('exposition', TextType::class, [
"label" => "Exposition",
"attr" => [
"placeholder" => "Exposition",
],
"mapped" => false,
"required" => false,
])
->add('mainMaterial', TextType::class, [
"label" => "Matière principale",
"attr" => [
"placeholder" => "Matière principale",
],
"mapped" => false,
"required" => false,
])
->add('recentWork', CheckboxType::class, [
"label" => "Travaux récents",
"mapped" => false,
"required" => false,
])
;
}
}
if ($roadmap) {
$form->get("firstName")->setData($roadmap->getFirstName());
$form->get("lastName")->setData($roadmap->getLastName());
$form->get("phone")->setData($roadmap->getPhone());
$form->get("email")->setData($roadmap->getEmail());
$form->get("name")->setData($roadmap->getCompanyName());
$form->get("siret")->setData($roadmap->getSiret());
$form->get("city")->setData($roadmap->getSector());
$form->get("position")->setData($roadmap->getPosition());
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$user = new User();
$user->setFirstName($form["firstName"]->getData());
$user->setLastName($form["lastName"]->getData());
$user->setPosition($form["position"]->getData());
$user->setStepInProcess($form["stepInProcess"]->getData());
$user->setComment($form["comment"]->getData());
$user->setPhone($company->getPhone());
$user->setEmail($company->getEmail());
$user->setCreationDate(new \DateTime("now"));
$user->setManager($this->getUser()->getManager());
$user->setPro(true);
$company->setUser($user);
$em->persist($company);
$em->persist($user);
$em->flush();
if ($roadmap) {
$roadmap->setArchived(true);
$roadmap->setCompany($company);
$em->flush();
if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 4) {
$this->roadmapEngieProToContract(
$roadmap,
$company,
$form->get("electricity")->getData(),
$form->get("powerSubscribed")->getData(),
$form->get("eSituation")->getData(),
$form->get("eSegment")->getData(),
$form->get("eCommitmentDate")->getData(),
intval($form->get("eDuree")->getData()),
$form->get("eOptEnergieVerte")->getData(),
$form->get("gas")->getData(),
$form->get("quantityConsumed")->getData(),
$form->get("gSituation")->getData(),
$form->get("gSegment")->getData(),
$form->get("gCommitmentDate")->getData(),
intval($form->get("gDuree")->getData()),
$form->get("gOptEnergieVerte")->getData(),
$em
);
}
if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 5) {
$this->roadmapTelecomToContract(
$roadmap,
$company,
$form->get("offer")->getData(),
$form->get("duree")->getData(),
$form->get("optionPremium")->getData(),
$form->get("rio")->getData(),
$em
);
}
if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 6) {
$this->roadmapPhotovoltaiqueToContract(
$roadmap,
$company,
$form->get("buildingType")->getData(),
$form->get("buildingYear")->getData(),
$form->get("surface")->getData(),
$form->get("exposition")->getData(),
$form->get("mainMaterial")->getData(),
$form->get("recentWork")->getData(),
$em
);
}
}
$fileJustificatif = $form['justificatif']->getData();
if ($fileJustificatif) {
$extension = $fileJustificatif->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le justificati");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileJustificatif->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setJustificatif($fileName);
$em->flush();
}
}
$fileFactElec = $form['factElec']->getData();
if ($fileFactElec) {
$extension = $fileFactElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setFactElec($fileName);
$em->flush();
}
}
$fileFactGas = $form['factGas']->getData();
if ($fileFactGas) {
$extension = $fileFactGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setFactGas($fileName);
$em->flush();
}
}
$fileLiaseFiscale = $form['liasseFiscale']->getData();
if ($fileLiaseFiscale) {
$extension = $fileLiaseFiscale->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileLiaseFiscale->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setLiasseFiscale($fileName);
$em->flush();
}
}
$fileSgeElec = $form['sgeElec']->getData();
if ($fileSgeElec) {
$extension = $fileSgeElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileSgeElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setSgeElec($fileName);
$em->flush();
}
}
$fileOmegaGas = $form['omegaGas']->getData();
if ($fileOmegaGas) {
$extension = $fileOmegaGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileOmegaGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setOmegaGas($fileName);
$em->flush();
}
}
$fileExcelMultisite = $form['excelMultisite']->getData();
if ($fileExcelMultisite) {
$extension = $fileExcelMultisite->guessExtension();
if (!$extension || !in_array($extension, ["csv", "xls", "xlsx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour l'excel multisite");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileExcelMultisite->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setExcelMultisite($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Nouveau client ajouté.");
return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
}
return $this->render("app/clients/form_pro.html.twig", [
"form" => $form->createView(),
"title" => "Ajouter un client",
"company" => $company,
"roadmap" => $roadmap,
]);
}
throw new NotAcceptableHttpException();
}
/**
* @Route("/clients/{user}/edit", name="clients_edit")
*/
public function clientsEditAction(Request $request, EntityManagerInterface $em, User $user)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(UserType::class, $user);
if ($this->getUser()->getManager()->getAdmin()) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true');
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => true,
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Client mis à jour");
return $this->redirectToRoute("manager_clients_edit", ["user" => $user->getId()]);
}
$cotations = $em->getRepository(Cotation::class)->findBy(["user" => $user], ["creationDate" => "DESC"], 3);
return $this->render("app/clients/form.html.twig", [
"form" => $form->createView(),
"user" => $user,
"cotations" => $cotations,
"title" => "Modifier un client",
]);
}
/**
* @Route("/clients/{user}/cotations", name="clients_cotations")
*/
public function clientsCotationsAction(Request $request, EntityManagerInterface $em, User $user)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotations = $em->getRepository(Cotation::class)->findBy(["user" => $user, 'cotationMultisite' => null], ["creationDate" => "DESC"]);
return $this->render("app/clients/cotations.html.twig", [
"user" => $user,
"cotations" => $cotations,
]);
}
/**
* @Route("/clients/{user}/cotations/add", name="clients_cotations_add")
*/
public function clientsCotationsAddAction(Request $request, EntityManagerInterface $em, User $user)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotation = new Cotation();
$cotation->setUser($user);
$cotation->setManager($this->getUser()->getManager());
$cotation->setFirstName($user->getFirstName());
$cotation->setLastName($user->getLastName());
$cotation->setAddress($user->getAddress());
$cotation->setAddress2($user->getAddress2());
$cotation->setZipCode($user->getZipCode());
$cotation->setCity($user->getCity());
$cotation->setBillingAddress($user->getAddress());
$cotation->setBillingAddress2($user->getAddress2());
$cotation->setBillingZipCode($user->getZipCode());
$cotation->setBillingCity($user->getCity());
$cotation->setPhone($user->getPhone());
$cotation->setEmail($user->getEmail());
$cotation->setEPdl($user->getPdlNumber());
$cotation->setGPce($user->getPceNumber());
$form = $this->createForm(CotationType::class, $cotation);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$state = $em->getRepository(CotationState::class)->find(1);
$cotation->setState($state);
$cotation->setCreationDate(new \DateTime("now"));
$em->persist($cotation);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
return $this->redirectToRoute("manager_clients_cotations", ["user" => $user->getId()]);
}
return $this->render("app/clients/cotation_form.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
]);
}
/**
* @Route("/clients/{user}/contracts/add", name="clients_contracts_add")
*/
public function clientsContractsAddAction(Request $request, EntityManagerInterface $em, User $user)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$contract = new Contract();
$contract->setUser($user);
$form = $this->createForm(ContractType::class, $contract);
$contractPart = $em->getRepository(\App\Entity\ContractType::class)->find(7);
$form->add('contractType', EntityType::class, [
'class' => \App\Entity\ContractType::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('t')
->where('t.active = TRUE')
->andWhere('t.id = 7')
->orderBy('t.label', 'ASC');
},
'data' => $contractPart,
'choice_label' => 'label',
'label' => 'Type de contrat',
'required' => true,
'mapped' => false,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$contract->setManager($this->getUser()->getManager());
$stateWaitSupplier = $em->getRepository(ContractState::class)->findOneBy(['id' => 7]);
$contract->setState($stateWaitSupplier);
$em->persist($contract);
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setFile($fileName);
$em->flush();
}
}
$otherFile = $form['otherFile']->getData();
if ($otherFile) {
$extension = $otherFile->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . $otherFile->getClientOriginalName();
$otherFile->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setOtherFile($fileName);
$em->flush();
}
}
$rib = $form['ribFile']->getData();
if ($rib) {
$extension = $rib->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
$rib->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setRibFile($fileName);
$em->flush();
}
}
/*
if ($form['contractType']->getData()) {
switch ($form['contractType']->getData()->getId()) {
case 1:
$contract->setGas(true);
break;
case 2:
$contract->setElectricity(true);
break;
case 3:
$contract->setGas(true);
$contract->setElectricity(true);
break;
case 4:
$contract->setEngiePro(true);
break;
case 5:
$contract->setTelecom(true);
break;
case 6:
$contract->setPhotovoltaique(true);
break;
}
$em->flush();
}
*/
if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
$contract->setSignDate(new \DateTime('now'));
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "Contrat ajouté avec succès");
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId(), "creation" => 1]);
}
return $this->render("app/clients/contracts_form.html.twig", [
"form" => $form->createView(),
"contract" => $contract,
"title" => "Ajouter un contrat",
]);
}
/**
* @Route("/clients/{user}/contracts/{contract}/edit", name="clients_contracts_edit")
*/
public function clientsContractsEditAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(ContractType::class, $contract);
if ($this->getUser()->getManager()->getAdmin()) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true');
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => false,
]);
$form["manager"]->setData($contract->getManager());
} elseif ($contract->getManager()->isSupervisedBy($this->getUser()->getManager()) || ($contract->getManager() === $this->getUser()->getManager())) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true')
->andWhere('(:manager MEMBER OF m.supervisors OR :manager = m)')
->setParameter('manager', $this->getUser()->getManager());
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => true,
]);
$form["manager"]->setData($contract->getManager());
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
if ($form->get("manager")) {
$contract->setManager($form->get("manager")->getData());
}
$em->persist($contract);
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setFile($fileName);
$em->flush();
}
}
$otherFile = $form['otherFile']->getData();
if ($otherFile) {
$extension = $otherFile->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . $otherFile->getClientOriginalName();
$otherFile->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setOtherFile($fileName);
$em->flush();
}
}
$rib = $form['ribFile']->getData();
if ($rib) {
$extension = $rib->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $user->getId() . "_" . md5(uniqid()) . '.' . $extension;
$rib->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setRibFile($fileName);
$em->flush();
}
}
/*
if ($form['contractType']->getData()) {
switch ($form['contractType']->getData()->getId()) {
case 1:
$contract->setGas(true);
break;
case 2:
$contract->setElectricity(true);
break;
case 3:
$contract->setGas(true);
$contract->setElectricity(true);
break;
case 4:
$contract->setEngiePro(true);
break;
case 5:
$contract->setTelecom(true);
break;
case 6:
$contract->setPhotovoltaique(true);
break;
}
$em->flush();
}
*/
if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
$contract->setSignDate(new \DateTime('now'));
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "Contrat modifié avec succès");
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
}
$creationWorkflow = $request->query->get('creation') === '1';
return $this->render("app/clients/contracts_form.html.twig", [
"form" => $form->createView(),
"contract" => $contract,
"title" => "Modifier un contrat",
'creation_workflow' => $creationWorkflow,
]);
}
/**
* @Route("/clients/{user}/contracts/{contract}/delete", name="clients_contracts_delete")
*/
public function clientsContractsDeleteAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Admin only");
}
$contract->setOfferElec(null);
$contract->setOfferGaz(null);
$em->flush();
$em->remove($contract);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Contrat supprimée");
return $this->redirectToRoute("manager_contracts", ["particulier" => 1]);
}
/**
* @Route("/clients/{user}/contracts/{contract}/file", name="clients_contracts_file")
*/
public function clientsContractsFileAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getFile()) {
return $this->getContractFile($contract, $request->get('mergeRib'));
}
throw new NotFoundHttpException();
}
/**
* @Route("/clients/{user}/contracts/{contract}/other-file", name="clients_contracts_other_file")
*/
public function clientsContractsOtherFileAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getOtherFile()) {
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/clients/{user}/contracts/{contract}/rib", name="clients_contracts_rib")
*/
public function clientsContractsRibAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getRibFile()) {
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
return $this->file($filePath, $contract->getRibFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/clients/{user}/contracts/{contract}/rib-delete", name="clients_contracts_rib-delete")
*/
public function clientsContractsRibDeleteAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$contract->setRibFile(null);
$em->flush();
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
}
/**
* @Route("/clients/{user}/contracts/{contract}/sign", name="clients_contracts_sign")
*/
public function clientsContractsSignAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract, DocusignService $docusignService)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (!$contract->getFile()) {
$this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
} else if (!$contract->getState() || $contract->getState()->getId() != 3) {
$this->get("session")->getFlashBag()->add("danger", "Le statut du contrat doit être: Contrat en attente de signature");
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
} else {
return $this->sendContractFileToDocusign($contract, $docusignService, $em, $request->query->get("embedded"));
//return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
}
throw new NotFoundHttpException();
}
/**
* @Route("/clients/{user}/contracts/{contract}/other-file/sign", name="clients_contracts_other_file_sign")
*/
public function clientsContractsOtherFileSignAction(Request $request, EntityManagerInterface $em, User $user, Contract $contract, DocusignService $docusignService)
{
if (!$contract->getUser() || $contract->getUser()->getId() != $user->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($user->getManager()->getId() != $this->getUser()->getManager()->getId() && !$user->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (!$contract->getOtherFile()) {
$this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
} else {
return $this->sendContractOtherFileToDocusign($contract, $docusignService, $em, true);
//return $this->redirectToRoute("manager_clients_contracts_edit", ["user" => $user->getId(), "contract" => $contract->getId()]);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/validate", name="companies_validate_group")
*/
public function companiesValidateGroupAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Not admin");
}
$companiesId = $request->get("companiesId");
if (!$companiesId) {
throw new BadRequestHttpException("Missing companiesId.");
}
foreach (explode(";",$companiesId) as $companyId) {
$company = $em->getRepository(Company::class)->find($companyId);
if ($company) {
$company->setValidated(true);
}
}
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Clients validés avec succès");
return $this->redirectToRoute("manager_clients", ["pro" => 1, "onlyNotValidated" => 1]);
}
/**
* @Route("/companies/{company}/edit", name="companies_edit")
*/
public function companiesEditAction(Request $request, EntityManagerInterface $em, Company $company, CompanyRepository $companyRepository)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(CompanyType::class, $company);
if ($this->getUser()->getManager()->getAdmin()) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true');
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => false,
]);
$form["manager"]->setData($company->getUser()->getManager());
}
$form["firstName"]->setData($company->getUser()->getFirstName());
$form["lastName"]->setData($company->getUser()->getLastName());
$form["position"]->setData($company->getUser()->getPosition());
$form["stepInProcess"]->setData($company->getUser()->getStepInProcess());
$form["comment"]->setData($company->getUser()->getComment());
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$company->getUser()->setFirstName($form["firstName"]->getData());
$company->getUser()->setLastName($form["lastName"]->getData());
$company->getUser()->setPosition($form["position"]->getData());
$company->getUser()->setPhone($company->getPhone());
$company->getUser()->setEmail($company->getEmail());
$company->getUser()->setStepInProcess($form["stepInProcess"]->getData());
$company->getUser()->setComment($form["comment"]->getData());
if ($this->getUser()->getManager()->getAdmin()) {
$company->getUser()->setManager($form["manager"]->getData());
}
$em->flush();
$fileJustificatif = $form['justificatif']->getData();
if ($fileJustificatif) {
$extension = $fileJustificatif->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour le justificati");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileJustificatif->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setJustificatif($fileName);
$em->flush();
}
}
$fileFactElec = $form['factElec']->getData();
if ($fileFactElec) {
$extension = $fileFactElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setFactElec($fileName);
$em->flush();
}
}
$fileFactGas = $form['factGas']->getData();
if ($fileFactGas) {
$extension = $fileFactGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setFactGas($fileName);
$em->flush();
}
}
$fileLiaseFiscale = $form['liasseFiscale']->getData();
if ($fileLiaseFiscale) {
$extension = $fileLiaseFiscale->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileLiaseFiscale->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setLiasseFiscale($fileName);
$em->flush();
}
}
$fileSgeElec = $form['sgeElec']->getData();
if ($fileSgeElec) {
$extension = $fileSgeElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileSgeElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setSgeElec($fileName);
$em->flush();
}
}
$fileOmegaGas = $form['omegaGas']->getData();
if ($fileOmegaGas) {
$extension = $fileOmegaGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileOmegaGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setOmegaGas($fileName);
$em->flush();
}
}
$fileExcelMultisite = $form['excelMultisite']->getData();
if ($fileExcelMultisite) {
$extension = $fileExcelMultisite->guessExtension();
if (!$extension || !in_array($extension, ["csv", "xls", "xlsx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour l'excel multisite");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileExcelMultisite->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$company->setExcelMultisite($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Client mis à jour");
return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
}
$cotations = $em->getRepository(Cotation::class)->findBy(["company" => $company, 'cotationMultisite' => null], ["creationDate" => "DESC"], 3);
$cotationsMultisite = $em->getRepository(CotationMultisite::class)->findBy(["company" => $company], ["creationDate" => "DESC"], 3);
$contracts = $em->getRepository(Contract::class)->findBy(["company" => $company], ["effectiveDate" => "DESC"], 3);
return $this->render("app/clients/form_pro.html.twig", [
"form" => $form->createView(),
"company" => $company,
"cotations" => $cotations,
"cotationsMultisite" => $cotationsMultisite,
"contracts" => $contracts,
"title" => "Modifier un client",
"siretAlreadyExist" => $companyRepository->existCompaniesWithSameSiretAndDifferentId($company->getId(), $company->getSiret())
]);
}
/**
* @Route("/companies/{company}/justificatif", name="companies_justificatif")
*/
public function companiesJustificatifAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getJustificatif()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getJustificatif();
return $this->file($filePath, $company->getJustificatif(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/justificatif-delete", name="companies_justificatif-delete")
*/
public function companiesJustificatifDeleteAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$company->setJustificatif(null);
$em->flush();
return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
}
/**
* @Route("/companies/{company}/fact-elec", name="companies_fact-elec")
*/
public function companiesFactElecction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getFactElec()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getFactElec();
return $this->file($filePath, $company->getFactElec(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/fact-gas", name="companies_fact-gas")
*/
public function companiesFactGasAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getFactGas()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getFactGas();
return $this->file($filePath, $company->getFactGas(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/liasse-fiscale", name="companies_liasse-fiscale")
*/
public function companiesLiasseFiscaleAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getLiasseFiscale()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getLiasseFiscale();
return $this->file($filePath, $company->getLiasseFiscale(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/liasse-fiscale-delete", name="companies_liasse-fiscale-delete")
*/
public function companiesLiasseFiscaleDeleteAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$company->setLiasseFiscale(null);
$em->flush();
return $this->redirectToRoute("manager_companies_edit", ["company" => $company->getId()]);
}
/**
* @Route("/companies/{company}/sge-elec", name="companies_sge-elec")
*/
public function companiesSgeElecAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getSgeElec()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getSgeElec();
return $this->file($filePath, $company->getSgeElec(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/omega-gas", name="companies_omega-gas")
*/
public function companiesOmegaGasAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getOmegaGas()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getOmegaGas();
return $this->file($filePath, $company->getOmegaGas(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/excel-multisite", name="companies_excel-multisite")
*/
public function companiesExcelMultisiteAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getExcelMultisite()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $company->getExcelMultisite();
return $this->file($filePath, $company->getExcelMultisite(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/ellipro", name="companies_ellipro")
*/
public function companiesElliproAction(Request $request, Company $company, EllisphereService $ellisphereService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
if (!$company->getSiret()) {
return new JsonResponse([
"success" => false,
"message" => "Siret non renseigné pour ce client"
]);
}
$data = $ellisphereService->getNoteElliPro($company->getSiret());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations", name="companies_cotations")
*/
public function companiesCotationsAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotations = $em->getRepository(Cotation::class)->findBy(["company" => $company, 'cotationMultisite' => null], ["creationDate" => "DESC"]);
return $this->render("app/clients/cotations.html.twig", [
"company" => $company,
"cotations" => $cotations,
]);
}
/**
* @Route("/companies/{company}/cotations-multisites", name="companies_cotations-multisites")
*/
public function companiesCotationsMultisitesAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotations = $em->getRepository(CotationMultisite::class)->findBy(["company" => $company], ["creationDate" => "DESC"]);
return $this->render("app/clients/cotations-multisites.html.twig", [
"company" => $company,
"cotations" => $cotations,
]);
}
/**
* @Route("/companies/{company}/validate", name="companies_validate")
*/
public function companiesValidateAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Only for admins");
}
$company->setValidated(true);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Client accepté");
return $this->redirectToRoute("manager_clients", ["pro"=> 1, "onlyNotValidated"=> 1]);
}
/**
* @Route("/companies/{company}/fe-invitation", name="companies_fe_invitation")
*/
public function companiesFeInvitationAction(Request $request, EntityManagerInterface $em, Company $company, SendEmailService $sendEmailService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($company->getUser()->getAccount()) {
throw new BadRequestHttpException("Already Flash Energie User");
}
$user = $company->getUser();
$feToken = hash("sha256", uniqid());
$user->setFeInvitationToken($feToken);
$user->setFeInvitationDate(new \DateTime('now'));
$em->flush();
$url = $this->generateUrl("default_flash_energie_token", ["token" => $feToken], UrlGeneratorInterface::ABSOLUTE_URL);
$content = <<<EOD
<br/>
Merci de compter parmi nos clients !<br/>
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.
<br/>
<br/>
Téléchargez dès maintenant l'application Flash Energie ici.<br/>
Ensuite, cliquez sur ce lien depuis votre smartphone pour vous inscrire depuis l'application:<br/>
<a href="$url">$url</a>
EOD;
$sendEmailService->send(
"Flash Énergie vous invite à rejoindre l'application Flash Énergie",
"david@slapp.me",
'emails/flash_default.html.twig',
[
"title" => "Suivez vos contrats avec l'application Flash Énergie",
"content" => $content
]
);
$this->get("session")->getFlashBag()->add("success", "Invitation envoyée avec succès");
return $this->redirectToRoute("manager_companies_edit", ["company"=> $company->getId()]);
}
/**
* @Route("/companies/{company}/cotations/add", name="companies_cotations_add")
*/
public function companiesCotationsAddAction(Request $request, EntityManagerInterface $em, Company $company, DocusignService $docusignService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotation = new Cotation();
$cotation->setCompany($company);
$cotation->setManager($this->getUser()->getManager());
$cotation->setSiret($company->getSiret());
//Demande du 2 octobre du client
$cotation->setCompanyName($company->getName());
$cotation->setApeCode($company->getApeCode());
$cotation->setSector($company->getSector());
$cotation->setPhone($company->getPhone());
$cotation->setEmail($company->getEmail());
/*
$cotation->setFirstName($company->getUser()->getFirstName());
$cotation->setLastName($company->getUser()->getLastName());
$cotation->setAddress($company->getAddress());
$cotation->setAddress2($company->getAddress2());
$cotation->setZipCode($company->getZipCode());
$cotation->setCity($company->getCity());
$cotation->setBillingAddress($company->getAddress());
$cotation->setBillingAddress2($company->getAddress2());
$cotation->setBillingZipCode($company->getZipCode());
$cotation->setBillingCity($company->getCity());
$cotation->setEPdl($company->getPdlNumber());
$cotation->setGPce($company->getPceNumber());
$cotation->setCreditsafeNote($company->getCreditsafeNote());
$cotation->setEliproNote($company->getEliproNote());
*/
$form = $this->createForm(CotationType::class, $cotation);
$form["firstName"]->setData($company->getUser()->getFirstName());
$form["lastName"]->setData($company->getUser()->getLastName());
$form["position"]->setData($company->getUser()->getPosition());
$form["sepaIban"]->setData($company->getSepaIban());
$form["sepaBic"]->setData($company->getSepaBic());
if (!$cotation->isAcdValid()) {
$signatureAvailable = true;
if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
$signatureAvailable = false;
}
if ($signatureAvailable) {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "Envoyer la signature électronique de l'ACD",
"required" => false,
"mapped" => false,
]);
} else {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
"data" => true,
"disabled" => true,
"required" => false,
"mapped" => false,
]);
}
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$state = $em->getRepository(CotationState::class)->find(1);
$cotation->setState($state);
$cotation->setCreationDate(new \DateTime("now"));
$em->persist($cotation);
$em->flush();
// Ancienne facture
if ($form->get('oldInvoice')->getData()) {
$fileOldInvoice = $form->get('oldInvoice')->getData();
if ($fileOldInvoice != NULL) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
$fileOldInvoice->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOldInvoice($fileName);
}
} else {
if ($cotation->getCompany()->getJustificatif()) {
$filePathFrom = $this->getParameter('documents_justificatif_directory') . $cotation->getCompany()->getJustificatif();
$path_parts = pathinfo($filePathFrom);
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $path_parts['extension'];
copy($filePathFrom, $this->getParameter('documents_justificatif_directory') . $fileName);
$cotation->setOldInvoice($fileName);
}
}
$em->flush();
$fileFactElec = $form['factElec']->getData();
if ($fileFactElec) {
$extension = $fileFactElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setFactElec($fileName);
$em->flush();
}
}
$fileFactGas = $form['factGas']->getData();
if ($fileFactGas) {
$extension = $fileFactGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setFactGas($fileName);
$em->flush();
}
}
$fileLiaseFiscale = $form['liasseFiscale']->getData();
if ($fileLiaseFiscale) {
$extension = $fileLiaseFiscale->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileLiaseFiscale->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setLiasseFiscale($fileName);
$em->flush();
}
}
$fileSgeElec = $form['sgeElec']->getData();
if ($fileSgeElec) {
$extension = $fileSgeElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileSgeElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setSgeElec($fileName);
$em->flush();
}
}
$fileOmegaGas = $form['omegaGas']->getData();
if ($fileOmegaGas) {
$extension = $fileOmegaGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileOmegaGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOmegaGas($fileName);
$em->flush();
}
}
// Other documents
$otherDocuments = $form['otherDocuments']->getData();
foreach ($otherDocuments as $key => $cotationDocument) {
$cotationDocument->setCotation($cotation);
$file = $form['otherDocuments'][$key]["file"]->getData();
if ($file) {
$extension = $file->guessExtension();
if ($extension && in_array($extension, ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "pptx"])) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotationDocument->setPath($fileName);
}
}
$em->flush();
}
// Signature électronique de l'ACD
if ($form->get('enableDocusign')->getData()) {
// Lancement de la signature
$startSign = null;
if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
$startSign = $this::sendAcdToDocusign($cotation, $company, $docusignService, $em);
} else {
$this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
}
if (!$startSign) {
$this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
} else {
$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.");
}
} else {
$this->get("session")->getFlashBag()->add("success", "Nouvelle demande de cotation enregistrée");
}
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
return $this->render("app/clients/cotation_form.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/ellipro", name="companies_cotations_ellipro")
*/
public function companiesCotationElliproAction(Request $request, Company $company, Cotation $cotation, EllisphereService $ellisphereService)
{
if (!$cotation->getSiret()) {
return new JsonResponse([
"success" => false,
"message" => "Siret non renseigné pour cette cotation"
]);
}
$data = $ellisphereService->getNoteElliPro($cotation->getSiret());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/send-acd", name="companies_cotations_send_acd")
*/
public function companiesCotationsSendAcdAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, DocusignService $docusignService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->isAcdValid()) {
$this->get("session")->getFlashBag()->add("danger", "L'ACD a déjà été renseigné pour cette cotation.");
} else {
// Lancement de la signature
$startSign = null;
if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
$startSign = $this::sendAcdToDocusign($cotation, $company, $docusignService, $em);
} else {
$this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
}
if (!$startSign) {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
} else {
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
}
}
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
private function sendAcdToYouSign(Cotation $cotation, Company $company, $yousignService, $em)
{
// Génération de l'ACD
$pdf = $this->generateACDv2($cotation);
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
$filePath = $this->getParameter('documents_acd_directory').$fileName;
$pdf->Output($filePath, 'F');
// Création de la procédure
$procedureSign = new ProcedureSign();
$procedureSign->setUser($company->getUser());
$procedureSign->setFirstName($cotation->getFirstName());
$procedureSign->setLastName($cotation->getLastName());
$procedureSign->setEmail($cotation->getEmail());
$procedureSign->setPhone($cotation->getPhone());
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "cotation.acd",
"id" => $cotation->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
// Création de la position
$yousignPosition = new YousignPosition();
$yousignPosition->setReason("Signé par ".$cotation->getFirstName().' '.$cotation->getLastName());
// Lancement de la signature
return $yousignService->startSign($procedureSign, $yousignPosition);
}
private function sendAcdToDocusign(Cotation $cotation, Company $company, $docusignService, $em)
{
// Génération de l'ACD
$pdf = $this->generateACDv2($cotation);
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
$filePath = $this->getParameter('documents_acd_directory').$fileName;
$pdf->Output($filePath, 'F');
// Création de la procédure
$procedureSign = new ProcedureSign();
$procedureSign->setUser($company->getUser());
$procedureSign->setFirstName($cotation->getFirstName());
$procedureSign->setLastName($cotation->getLastName());
$procedureSign->setEmail($cotation->getEmail());
$procedureSign->setPhone($cotation->getPhone());
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "cotation.acd",
"id" => $cotation->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
try {
$response = $docusignService->sendFile($accessToken, $procedureSign);
$procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
$em->flush();
return true;
} catch (\Exception $e) {
$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.");
return false;
}
}
return false;
}
private function sendAcdMultisiteToDocusign(CotationMultisite $cotation, Company $company, $docusignService, $em)
{
// Génération de l'ACD
$pdf = $this->generateACDMultisite($cotation);
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
$filePath = $this->getParameter('documents_acd_directory').$fileName;
$pdf->Output($filePath, 'F');
// Création de la procédure
$procedureSign = new ProcedureSign();
$procedureSign->setUser($company->getUser());
$procedureSign->setFirstName($cotation->getFirstName());
$procedureSign->setLastName($cotation->getLastName());
$procedureSign->setEmail($cotation->getEmail());
$procedureSign->setPhone($cotation->getPhone());
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "cotation-multisite.acd",
"id" => $cotation->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
try {
$response = $docusignService->sendFile($accessToken, $procedureSign);
$procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
$em->flush();
return true;
} catch (\Exception $e) {
$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.");
return false;
}
}
return false;
}
/**
* @Route("/companies/{company}/cotations/{cotation}/edit", name="companies_cotations_edit")
*/
public function companiesCotationsEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getCotationMultisite()) {
throw new NotFoundHttpException();
}
if ($cotation->getState()->getId() == 6) { // Terminée
//throw new NotFoundHttpException();
}
$form = $this->createForm(CotationType::class, $cotation);
if ($cotation->getCompany()->getValidated()) {
$form->add('acdFileUpload', FileType::class, [
'attr' => [
'placeholder' => 'Importer le fichier ACD'
],
'label' => 'Importer le fichier ACD',
'required' => false,
'mapped' => false
]);
if ($this->getUser()->getManager()->getAdmin()) {
if (!$cotation->getElectricityDataFile() && $cotation->getElectricity()) {
$form->add('electricityDataFileUpload', FileType::class, [
'attr' => [
'placeholder' => 'Importer le fichier de données Enedis'
],
'label' => 'Importer le fichier de données Enedis',
'required' => false,
'mapped' => false
]);
}
if (!$cotation->getGasDataFile() && $cotation->getGas()) {
$form->add('gasDataFileUpload', FileType::class, [
'attr' => [
'placeholder' => 'Importer le fichier de données GRDF'
],
'label' => 'Importer le fichier de données GRDF',
'required' => false,
'mapped' => false
]);
}
}
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$cotation->setEditDate(new \DateTime("now"));
$em->flush();
if ($form->get('oldInvoice')->getData()) {
$fileOldInvoice = $form->get('oldInvoice')->getData();
if ($fileOldInvoice != NULL) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
$fileOldInvoice->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOldInvoice($fileName);
}
}
$fileFactElec = $form['factElec']->getData();
if ($fileFactElec) {
$extension = $fileFactElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setFactElec($fileName);
$em->flush();
}
}
$fileFactGas = $form['factGas']->getData();
if ($fileFactGas) {
$extension = $fileFactGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setFactGas($fileName);
$em->flush();
}
}
$fileLiaseFiscale = $form['liasseFiscale']->getData();
if ($fileLiaseFiscale) {
$extension = $fileLiaseFiscale->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileLiaseFiscale->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setLiasseFiscale($fileName);
$em->flush();
}
}
$fileSgeElec = $form['sgeElec']->getData();
if ($fileSgeElec) {
$extension = $fileSgeElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileSgeElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setSgeElec($fileName);
$em->flush();
}
}
$fileOmegaGas = $form['omegaGas']->getData();
if ($fileOmegaGas) {
$extension = $fileOmegaGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileOmegaGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOmegaGas($fileName);
$em->flush();
}
}
if ($form->has('acdFileUpload')) {
/**
* @var UploadedFile $fileAcd
*/
$fileAcd = $form->get('acdFileUpload')->getData();
if ($fileAcd != NULL) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileAcd->guessExtension();
$fileAcd->move(
$this->getParameter('documents_acd_directory'),
$fileName
);
$cotation->setAcdFile($fileName);
$cotation->setAcdSignDate(new \DateTime('now'));
$em->flush();
}
}
if (!$cotation->getElectricityDataFile() && $form->has('electricityDataFileUpload')) {
/**
* @var UploadedFile $fileData
*/
$fileData = $form->get('electricityDataFileUpload')->getData();
if ($fileData != NULL) {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
try {
$spreadsheet = $reader->load($fileData->getRealPath());
$sheet = $spreadsheet->setActiveSheetIndex(0);
$cotation->setENombreMois($sheet->getCell("E9")->getValue());
$cotation->setEFormuleAcheminement($sheet->getCell("E12")->getValue());
$cotation->setECarMwh($sheet->getCell("E13")->getValue());
$cotation->setEConsommationPointe($sheet->getCell("E14")->getValue());
$cotation->setEConsommationHph($sheet->getCell("E15")->getValue());
$cotation->setEConsommationHch($sheet->getCell("E16")->getValue());
$cotation->setEConsommationHpe($sheet->getCell("E17")->getValue());
$cotation->setEConsommationHce($sheet->getCell("E18")->getValue());
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileData->guessExtension();
$fileData->move(
$this->getParameter('documents_electricity_directory'),
$fileName
);
$cotation->setElectricityDataFile($fileName);
$em->flush();
} catch (Exception|DriverException $e) {
$this->get("session")->getFlashBag()->add("danger", "Impossible de charger le fichier Enedis");
}
}
}
if (!$cotation->getGasDataFile() && $form->has('gasDataFileUpload')) {
/**
* @var UploadedFile $fileData
*/
$fileData = $form->get('gasDataFileUpload')->getData();
if ($fileData != NULL) {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
try {
$spreadsheet = $reader->load($fileData->getRealPath());
$sheet = $spreadsheet->setActiveSheetIndex(0);
$cotation->setGNombreMois($sheet->getCell("E9")->getValue());
$cotation->setGCarMwh($sheet->getCell("E12")->getValue());
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileData->guessExtension();
$fileData->move(
$this->getParameter('documents_gas_directory'),
$fileName
);
$cotation->setGasDataFile($fileName);
$em->flush();
} catch (Exception|DriverException $e) {
$this->get("session")->getFlashBag()->add("danger", "Impossible de charger le fichier GRDF");
}
}
}
// Cotation status
if ($cotation->getState()->getId() != 5) {
if (
(!$cotation->getGas() || ($cotation->getGas() && $cotation->getGasDataFile()))
&&
(!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getElectricityDataFile()))
) {
$newState = $em->getRepository(CotationState::class)->find(4);
$cotation->setState($newState);
} else if ($cotation->getAcdFile()) {
$newState = $em->getRepository(CotationState::class)->find(3);
$cotation->setState($newState);
} else {
$newState = $em->getRepository(CotationState::class)->find(2);
$cotation->setState($newState);
}
}
// Other documents
$otherDocuments = $form['otherDocuments']->getData();
foreach ($otherDocuments as $key => $cotationDocument) {
$cotationDocument->setCotation($cotation);
$file = $form['otherDocuments'][$key]["file"]->getData();
if ($file) {
$extension = $file->guessExtension();
if ($extension && in_array($extension, ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "pptx"])) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotationDocument->setPath($fileName);
}
}
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "Demande de cotation mise à jour");
//return $this->redirectToRoute("manager_companies_cotations", ["company" => $company->getId()]);
if (!$cotation->getPricingSentDate() && !($cotation->isAcdValid() && ($cotation->getFactElec() || $cotation->getFactGas()))) {
$this->get("session")->getFlashBag()->add("info", "Rappel: pour pouvoir notifier le pricing, il faut une ACD valide et la facture elec/gaz enregistrée.");
}
if ($cotation->getAcdFile() && $cotation->getElectricityDataFile() && $cotation->getGasDataFile()) {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
// else retour formulaire
return $this->redirectToRoute('manager_companies_cotations_edit', ['company' => $company->getId(), 'cotation' => $cotation->getId()]);
}
return $this->render("app/clients/cotation_form.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/old-invoice", name="companies_cotations_old_invoice")
*/
public function cotationOldInvoiceAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getOldInvoice()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getOldInvoice();
return $this->file($filePath, $cotation->getOldInvoice(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/old-invoice-delete", name="companies_cotations_old_invoice-delete")
*/
public function cotationOldInvoiceDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setOldInvoice(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/fact-elec", name="companies_cotations_fact-elec")
*/
public function cotationFactElecAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getFactElec()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getFactElec();
return $this->file($filePath, $cotation->getFactElec(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/fact-elec-delete", name="companies_cotations_fact-elec-delete")
*/
public function cotationFactElecDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setFactElec(null);
$em->flush();
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/fact-gas", name="companies_cotations_fact-gas")
*/
public function cotationFactGasAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getFactGas()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getFactGas();
return $this->file($filePath, $cotation->getFactGas(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/fact-gas-delete", name="companies_cotations_fact-gas-delete")
*/
public function cotationFactGasDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setFactGas(null);
$em->flush();
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/liasse-fiscale", name="companies_cotations_liasse-fiscale")
*/
public function cotationLiasseFiscaleAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getLiasseFiscale()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getLiasseFiscale();
return $this->file($filePath, $cotation->getLiasseFiscale(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/liasse-fiscale-delete", name="companies_cotations_liasse-fiscale-delete")
*/
public function cotationLiasseFiscaleDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setLiasseFiscale(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/sge-elec", name="companies_cotations_sge-elec")
*/
public function cotationSgeElecAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getSgeElec()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getSgeElec();
return $this->file($filePath, $cotation->getSgeElec(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/sge-elec-delete", name="companies_cotations_sge-elec-delete")
*/
public function cotationSgeElecDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setSgeElec(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/omega-gas", name="companies_cotations_omega-gas")
*/
public function cotationOmegaGasAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getOmegaGas()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotation->getOmegaGas();
return $this->file($filePath, $cotation->getOmegaGas(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/omega-gas-delete", name="companies_cotations_omega-gas-delete")
*/
public function cotationOmegaGasDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$cotation->setOmegaGas(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/delete", name="companies_cotations_delete")
*/
public function companiesCotationsDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Admin only");
}
$cotation->setPreselectedOfferElec(null);
$cotation->setPreselectedOfferGaz(null);
$cotation->setSelectedOfferElec(null);
$cotation->setSelectedOfferGaz(null);
$em->flush();
$offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation]);
if ($offersElec) {
foreach ($offersElec as $offerElec) {
$em->remove($offerElec);
}
}
$em->flush();
$offersGaz = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation]);
if ($offersGaz) {
foreach ($offersGaz as $offerGaz) {
$em->remove($offerGaz);
}
}
$em->flush();
$em->remove($cotation);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Cotation supprimée");
return $this->redirectToRoute("manager_cotations", ["onlyInProgress" => 1]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/acd", name="companies_cotations_acd")
*/
public function companiesCotationsAcdAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getAcdFile()) {
$filePath = $this->getParameter('documents_acd_directory') . $cotation->getAcdFile();
return $this->file($filePath, $cotation->getAcdFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
if ($cotation->getState()->getId() == 1) {
$newState = $em->getRepository(CotationState::class)->find(2);
$cotation->setState($newState);
$em->flush();
}
$pdf = $this->generateACDv2($cotation);
$filename = "ACD";
return $pdf->Output($filename.".pdf",'I');
}
private function generateACD(Cotation $cotation): TCPDF
{
$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetAuthor('Flash Énergie');
$pdf->SetTitle("ACD");
$pdf->setMargins(10,5,10);
$pdf->AddPage();
$html = $this->renderView('app/pdf/acd.html.twig', [
'cotation' => $cotation,
]);
$pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
$pdf->StartTransform();
$pdf->Rotate(90, 3, 68);
$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);
$pdf->StopTransform();
$pdf->StartTransform();
$pdf->Rotate(90, 3, 140);
$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);
$pdf->StopTransform();
return $pdf;
}
private function generateACDv2(Cotation $cotation): TCPDF
{
$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetAuthor('Flash Énergie');
$pdf->SetTitle("ACD");
$pdf->setMargins(10,5,10);
$pdf->AddPage();
$html = $this->renderView('app/pdf/acdv2.html.twig', [
'cotation' => $cotation,
]);
$pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
$pdf->StartTransform();
$pdf->Rotate(90, 3, 68);
$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);
$pdf->StopTransform();
return $pdf;
}
private function generateACDMultisite(CotationMultisite $cotation): TCPDF
{
$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetAuthor('Flash Énergie');
$pdf->SetTitle("ACD");
$pdf->setMargins(10,5,10);
$pdf->AddPage();
$html = $this->renderView('app/pdf/acdv2.html.twig', [
'cotation' => $cotation,
]);
$pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true);
$pdf->StartTransform();
$pdf->Rotate(90, 3, 68);
$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);
$pdf->StopTransform();
$pdf->AddPage();
$pdf->setFontSize(14);
$pdf->Cell(0, 10, 'ANNEXE', 0, 1, 'C');
$pdf->Ln(10);
$pdf->SetX(58);
$table = '<table border="1" cellpadding="4" cellspacing="0" width="95mm">
<thead>
<tr style="font-weight: bold; text-align: center;">
<th>'.($cotation->getElectricity() ? 'PDL' : 'PCE').'</th>
</tr>
</thead>
<tbody>';
if ($cotation->getElectricity()) {
foreach ($cotation->getCotations() as $cotationSite) {
$table .= '<tr><td height="20">' . $cotationSite->getEPdl() . '</td></tr>';
}
}
if ($cotation->getGas()) {
foreach ($cotation->getCotations() as $cotationSite) {
$table .= '<tr><td height="20">'.$cotationSite->getGPce().'</td></tr>';
}
}
$table .= '</tbody></table>';
$pdf->setFontSize(10);
$pdf->writeHTML($table, true, false, false, false, '');
$pdf->writeHTML(
'<table style="position: fixed; bottom: 10mm;">
<tr>
<td></td>
<td style="width: 50%;">
<table style="border: 0.75px solid black;" cellpadding="6">
<tr><td style="font-size: 8px;"><i>Cachet de l’entreprise + signature</i></td></tr>
<tr><td style="font-size: 8px;">_Date:</td></tr>
<tr><td style="height: 2.5cm; font-size: 8px;">_Signature</td></tr>
</table>
</td>
</tr>
</table>', true, false, false, false, '');
return $pdf;
}
/**
* @Route("/companies/{company}/cotations/{cotation}/resiliation-email", name="companies_cotations_resiliation-email")
*/
public function companiesCotationsResiliationEmailAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, SendEmailService $sendEmailService, Pdf $knpSnappyPdf)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (!$cotation->getAcdFile()) {
throw new BadRequestHttpException();
}
if (isset($_POST["file_elec_content"])) {
$cotation->setResiliationElecEmailContent($_POST["file_elec_content"]);
$em->flush();
// Génération du PDF
$pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_elec_content"]);
// Email
$content = <<<EOD
Bonjour,<br/>
<br/>
Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture d'électricité actuel.<br/>
<br/>
<i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur Electricité",
$cotation->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur",
"content" => $content
],
'resiliation@flash-consulting.fr',
null,
[
[
"content" => $pdf,
"name" => "courrier_de_changement_fournisseur_elec.pdf",
"contentType" => "application/pdf"
]
]
);
$cotation->setResiliationElecEmailSendDate(new \DateTime('now'));
$em->flush();
} elseif (isset($_POST["file_gas_content"])) {
$cotation->setResiliationGasEmailContent($_POST["file_gas_content"]);
$em->flush();
// Génération du PDF
$pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_gas_content"]);
// Email
$content = <<<EOD
Bonjour,<br/>
<br/>
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/>
<br/>
<i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur Gaz",
$cotation->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur",
"content" => $content
],
'resiliation@flash-consulting.fr',
null,
[
[
"content" => $pdf,
"name" => "courrier_de_changement_fournisseur_gaz.pdf",
"contentType" => "application/pdf"
]
]
);
$cotation->setResiliationGasEmailSendDate(new \DateTime('now'));
$em->flush();
} else {
$content = <<<EOD
Bonjour,<br/>
<br/>
Veuillez trouver ci-joint un modèle de courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat actuel.<br/>
<br/>
<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/>
<br/>
De plus, nous avons également inclus <b>un guide</b> (voir pièces jointes) pour remplir le formulaire correctement.<br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur et son guide",
$cotation->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur et son guide",
"content" => $content
],
'resiliation@flash-consulting.fr',
[
$this->getParameter('assets_directory')."Lettre de resiliation.docx",
$this->getParameter('assets_directory')."Guide pour remplir sa lettre de resiliation.docx",
]
);
if (isset($_GET["elec"])) {
$cotation->setResiliationElecEmailSendDate(new \DateTime('now'));
}
if (isset($_GET["gas"])) {
$cotation->setResiliationGasEmailSendDate(new \DateTime('now'));
}
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "L'email de changement de fournisseur a bien été envoyé");
return $this->redirectToRoute("manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/enedis", name="companies_cotations_enedis")
*/
public function companiesCotationsEnedisAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Demande de Cotation");
$sheet->getProtection()->setSheet(true);
$spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
//HEADER
$sheet->setCellValue('A2', 'Demande de Cotation');
$sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
$sheet->getStyle("A2")->getAlignment()->setVertical("center");
$sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
$sheet->getStyle("A2")->getFont()->setBold(true);
$sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
$sheet->mergeCells("A2:E3");
$sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
$sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
$sheet->getColumnDimension("A")->setWidth(40);
$sheet->getColumnDimension("B")->setWidth(40);
$sheet->getColumnDimension("C")->setWidth(3);
$sheet->getColumnDimension("D")->setWidth(40);
$sheet->getColumnDimension("E")->setWidth(40);
//DONNEES CLIENT
$sheet->setCellValue('A5', 'Données client');
$sheet->setCellValue('A6', 'Raison sociale');
$sheet->setCellValue('A7', 'Titulaire');
$sheet->setCellValue('A8', 'SIRET du titulaire');
$sheet->setCellValue('A9', 'Payeur');
$sheet->setCellValue('A10', 'SIRET du payeur');
$sheet->setCellValue('A11', 'Prénom');
$sheet->setCellValue('A12', 'Nom');
$sheet->setCellValue('A13', 'Fonction');
$sheet->setCellValue('A14', 'Adresse de consommation');
$sheet->setCellValue('A16', 'Adresse facturation');
$sheet->setCellValue('A18', 'Téléphone');
$sheet->setCellValue('A19', 'Email');
$sheet->setCellValue('A20', 'Secteur client');
$sheet->setCellValue('A21', 'Activité APE/NAF');
$sheet->setCellValue('A22', 'Note ELIPRO');
$sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("A5:B5");
$sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
$sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("A5:B22")->getAlignment()->setVertical('center');
$sheet->getStyle("A5:B22")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 22; $i++) {
$sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('A'.$i)->getFont()->setBold(true);
$sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
//$sheet->getStyle('B'.$i)->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
$sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('B10')->getNumberFormat()->setFormatCode('0');
$sheet->mergeCells("A14:A15");
$sheet->mergeCells("B14:B15");
$sheet->mergeCells("A16:A17");
$sheet->mergeCells("B16:B17");
$sheet->getStyle('B14')->getAlignment()->setWrapText(true);
$sheet->getStyle('B16')->getAlignment()->setWrapText(true);
$sheet->getStyle('A6:A22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
$sheet->getStyle('B6:B22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
$sheet->setCellValue('B6', $cotation->getCompanyName());
$sheet->setCellValue('B7', $cotation->getCompanyName());
$sheet->setCellValue('B8', $cotation->getSiret());
// Payeur
// Siret du payeur
$sheet->setCellValue('B11', $cotation->getFirstName());
$sheet->setCellValue('B12', $cotation->getLastName());
$sheet->setCellValue('B13', $cotation->getPosition());
$sheet->setCellValue('B14', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
$sheet->setCellValue('B16', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
$sheet->setCellValue('B18', $cotation->getPhone());
$sheet->setCellValue('B19', $cotation->getEmail());
$sheet->setCellValue('B20', $cotation->getSector() ?: ($cotation->getCompany()? $cotation->getCompany()->getSector():""));
$sheet->setCellValue('B21', $cotation->getApeCode() ?: ($cotation->getCompany()?($cotation->getCompany()->getApeCode()):""));
$sheet->setCellValue('B22', $cotation->getEliproNote() ?: ($cotation->getCompany()?($cotation->getCompany()->getEliproNote()):""));
//ENEDIS
$sheet->setCellValue('D5', 'Données consommation électricité');
$sheet->setCellValue('D6', 'Fournisseur actuel');
$sheet->setCellValue('D7', 'Début de fourniture souhaitée');
$sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
$sheet->setCellValue('D9', 'Nombre de mois à fournir');
$sheet->setCellValue('D10', 'PDL');
$sheet->setCellValue('D11', 'Segment');
$sheet->setCellValue('D12', 'Formule acheminement(facultatif)');
$sheet->setCellValue('D13', 'CAR (MWh)');
$sheet->setCellValue('D14', 'Consommation Pointe');
$sheet->setCellValue('D15', 'Consommation HPH');
$sheet->setCellValue('D16', 'Consommation HCH');
$sheet->setCellValue('D17', 'Consommation HPE');
$sheet->setCellValue('D18', 'Consommation HCE');
$sheet->setCellValue('D19', 'Puissance souscrites (Kva)');
$sheet->setCellValue('D20', 'Pointe');
$sheet->setCellValue('D21', 'HPH');
$sheet->setCellValue('D22', 'HCH');
$sheet->setCellValue('D23', 'HPE');
$sheet->setCellValue('D24', 'HCE');
$sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("D5:E5");
$sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("D5:E24")->getAlignment()->setVertical('center');
$sheet->getStyle("D5:E24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 24; $i++) {
$sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('D'.$i)->getFont()->setBold(true);
$sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->mergeCells("D19:E19");
$sheet->getStyle('D19:E19')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle('D6:D18')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->getStyle('D20:D24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->getStyle('E6:E8')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
$sheet->getStyle('E10:E11')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
$sheet->getStyle('E20:E24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
//$sheet->getStyle('E6:E8')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
//$sheet->getStyle('E10:E11')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
//$sheet->getStyle('E20:E24')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
$sheet->setCellValue('E6', $cotation->getElectricitySupplier()?$cotation->getElectricitySupplier()->getName():"");
$sheet->setCellValue('E7', $cotation->getEDesiredBegin()?$cotation->getEDesiredBegin()->format("d/m/Y"):"");
$sheet->setCellValue('E8', $cotation->getEDesiredEnd()?$cotation->getEDesiredEnd()->format("d/m/Y"):"");
$sheet->setCellValue('E9', $cotation->getENombreMois());
$sheet->setCellValue('E10', $cotation->getEPdl());
$sheet->setCellValue('E11', $cotation->getESegment());
$sheet->setCellValue('E12', $cotation->getEFormuleAcheminement());
$sheet->setCellValue('E13', $cotation->getECarMwh());
$sheet->setCellValue('E14', $cotation->getEConsommationPointe());
$sheet->setCellValue('E15', $cotation->getEConsommationHph());
$sheet->setCellValue('E16', $cotation->getEConsommationHch());
$sheet->setCellValue('E17', $cotation->getEConsommationHpe());
$sheet->setCellValue('E18', $cotation->getEConsommationHce());
$sheet->setCellValue('E20', $cotation->getEPuissanceKvaPointe());
$sheet->setCellValue('E21', $cotation->getEPuissanceKvaHph());
$sheet->setCellValue('E22', $cotation->getEPuissanceKvaHch());
$sheet->setCellValue('E23', $cotation->getEPuissanceKvaHpe());
$sheet->setCellValue('E24', $cotation->getEPuissanceKvaHce());
//END
$sheet->getRowDimension("2")->setRowHeight(18);
$sheet->getRowDimension("3")->setRowHeight(18);
$sheet->getRowDimension("5")->setRowHeight(26);
$sheet->getRowDimension("6")->setRowHeight(26);
$sheet->getRowDimension("7")->setRowHeight(26);
$sheet->getRowDimension("8")->setRowHeight(26);
$sheet->getRowDimension("9")->setRowHeight(26);
$sheet->getRowDimension("10")->setRowHeight(26);
$sheet->getRowDimension("11")->setRowHeight(26);
$sheet->getRowDimension("12")->setRowHeight(26);
$sheet->getRowDimension("13")->setRowHeight(26);
$sheet->getRowDimension("14")->setRowHeight(26);
$sheet->getRowDimension("15")->setRowHeight(26);
$sheet->getRowDimension("16")->setRowHeight(26);
$sheet->getRowDimension("17")->setRowHeight(26);
$sheet->getRowDimension("18")->setRowHeight(26);
$sheet->getRowDimension("19")->setRowHeight(26);
$sheet->getRowDimension("20")->setRowHeight(26);
$sheet->getRowDimension("21")->setRowHeight(26);
$sheet->getRowDimension("22")->setRowHeight(26);
$sheet->getRowDimension("23")->setRowHeight(26);
$sheet->getRowDimension("24")->setRowHeight(26);
$drawingLogo = new Drawing();
$drawingLogo->setName('Logo');
$drawingLogo->setDescription('Logo');
$drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
$drawingLogo->setCoordinates('A2');
$drawingLogo->setHeight(36);
$drawingLogo->setOffsetY(6);
$drawingLogo->setOffsetX(12);
$drawingLogo->setWorksheet($sheet);
$drawingData = new Drawing();
$drawingData->setName('Logo Data');
$drawingData->setDescription('Logo Data');
$drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/enedis.png');
$drawingData->setCoordinates('E5');
$drawingData->setHeight(26);
$drawingData->setOffsetY(4);
$drawingData->setOffsetX(12);
$drawingData->setWorksheet($sheet);
$sheet->setSelectedCell("A1");
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse();
$response->setCallback(function () use ($writer) {
$writer->save('php://output');
});
$filenane = "enedis_".$cotation->getCompanyName().'.xlsx';
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/companies/{company}/cotations/{cotation}/grdf", name="companies_cotations_grdf")
*/
public function companiesCotationsGrdfAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Demande de Cotation");
$sheet->getProtection()->setSheet(true);
$spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
//HEADER
$sheet->setCellValue('A2', 'Demande de Cotation');
$sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
$sheet->getStyle("A2")->getAlignment()->setVertical("center");
$sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
$sheet->getStyle("A2")->getFont()->setBold(true);
$sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
$sheet->mergeCells("A2:E3");
$sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
$sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
$sheet->getColumnDimension("A")->setWidth(40);
$sheet->getColumnDimension("B")->setWidth(40);
$sheet->getColumnDimension("C")->setWidth(3);
$sheet->getColumnDimension("D")->setWidth(40);
$sheet->getColumnDimension("E")->setWidth(40);
//DONNEES CLIENT
$sheet->setCellValue('A5', 'Données client');
$sheet->setCellValue('A6', 'Raison sociale');
$sheet->setCellValue('A7', 'Titulaire');
$sheet->setCellValue('A8', 'SIRET du titulaire');
$sheet->setCellValue('A9', 'Payeur');
$sheet->setCellValue('A10', 'SIRET du payeur');
$sheet->setCellValue('A11', 'Prénom');
$sheet->setCellValue('A12', 'Nom');
$sheet->setCellValue('A13', 'Fonction');
$sheet->setCellValue('A14', 'Adresse de consommation');
$sheet->setCellValue('A16', 'Adresse facturation');
$sheet->setCellValue('A18', 'Téléphone');
$sheet->setCellValue('A19', 'Email');
$sheet->setCellValue('A20', 'Secteur client');
$sheet->setCellValue('A21', 'Activité APE/NAF');
$sheet->setCellValue('A22', 'Note Elipro');
$sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("A5:B5");
$sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
$sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("A5:B22")->getAlignment()->setVertical('center');
$sheet->getStyle("A5:B22")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 22; $i++) {
$sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('A'.$i)->getFont()->setBold(true);
$sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
//$sheet->getStyle('B'.$i)->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
$sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('B10')->getNumberFormat()->setFormatCode('0');
$sheet->mergeCells("A14:A15");
$sheet->mergeCells("B14:B15");
$sheet->mergeCells("A16:A17");
$sheet->mergeCells("B16:B17");
$sheet->getStyle('B14')->getAlignment()->setWrapText(true);
$sheet->getStyle('B16')->getAlignment()->setWrapText(true);
$sheet->getStyle('A6:A22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
$sheet->getStyle('B6:B22')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
$sheet->setCellValue('B6', $cotation->getCompanyName());
$sheet->setCellValue('B7', $cotation->getCompanyName());
$sheet->setCellValue('B8', $cotation->getSiret());
// Payeur
// Siret payeur
$sheet->setCellValue('B11', $cotation->getFirstName());
$sheet->setCellValue('B12', $cotation->getLastName());
$sheet->setCellValue('B13', $cotation->getPosition());
$sheet->setCellValue('B14', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
$sheet->setCellValue('B16', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
$sheet->setCellValue('B18', $cotation->getPhone());
$sheet->setCellValue('B19', $cotation->getEmail());
$sheet->setCellValue('B20', $cotation->getSector() ?: ($cotation->getCompany()?$cotation->getCompany()->getSector():""));
$sheet->setCellValue('B21', $cotation->getApeCode() ?: ($cotation->getCompany()?($cotation->getCompany()->getApeCode()):""));
$sheet->setCellValue('B22', $cotation->getEliproNote() ?: ($cotation->getCompany()?($cotation->getCompany()->getEliproNote()):""));
//GRDF
$sheet->setCellValue('D5', 'Données consommation Gaz');
$sheet->setCellValue('D6', 'Fournisseur actuel');
$sheet->setCellValue('D7', 'Début de fourniture souhaitée');
$sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
$sheet->setCellValue('D9', 'Nombre de mois à fournir');
$sheet->setCellValue('D10', 'PCE');
$sheet->setCellValue('D11', 'Segment');
$sheet->setCellValue('D12', 'CAR (MWh)');
$sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("D5:E5");
$sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("D5:E12")->getAlignment()->setVertical('center');
$sheet->getStyle("D5:E12")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 12; $i++) {
$sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('D'.$i)->getFont()->setBold(true);
$sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->getStyle('D6:D12')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->getStyle('E6:E8')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
$sheet->getStyle('E10:E11')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EBEBEB');
//$sheet->getStyle('E6:E8')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
//$sheet->getStyle('E10:E11')->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
$sheet->setCellValue('E6', $cotation->getGasSupplier()?$cotation->getGasSupplier()->getName():"");
$sheet->setCellValue('E7', $cotation->getGDesiredBegin()?$cotation->getGDesiredBegin()->format("d/m/Y"):"");
$sheet->setCellValue('E8', $cotation->getGDesiredEnd()?$cotation->getGDesiredEnd()->format("d/m/Y"):"");
$sheet->setCellValue('E9', $cotation->getGNombreMois());
$sheet->setCellValue('E10', $cotation->getGPce());
$sheet->setCellValue('E11', $cotation->getGSegment());
$sheet->setCellValue('E12', $cotation->getGCarMwh());
//END
$sheet->getRowDimension("2")->setRowHeight(18);
$sheet->getRowDimension("3")->setRowHeight(18);
$sheet->getRowDimension("5")->setRowHeight(26);
$sheet->getRowDimension("6")->setRowHeight(26);
$sheet->getRowDimension("7")->setRowHeight(26);
$sheet->getRowDimension("8")->setRowHeight(26);
$sheet->getRowDimension("9")->setRowHeight(26);
$sheet->getRowDimension("10")->setRowHeight(26);
$sheet->getRowDimension("11")->setRowHeight(26);
$sheet->getRowDimension("12")->setRowHeight(26);
$sheet->getRowDimension("13")->setRowHeight(26);
$sheet->getRowDimension("14")->setRowHeight(26);
$sheet->getRowDimension("15")->setRowHeight(26);
$sheet->getRowDimension("16")->setRowHeight(26);
$sheet->getRowDimension("17")->setRowHeight(26);
$sheet->getRowDimension("18")->setRowHeight(26);
$sheet->getRowDimension("19")->setRowHeight(26);
$sheet->getRowDimension("20")->setRowHeight(26);
$sheet->getRowDimension("21")->setRowHeight(26);
$sheet->getRowDimension("22")->setRowHeight(26);
$sheet->getRowDimension("23")->setRowHeight(26);
$sheet->getRowDimension("24")->setRowHeight(26);
$drawingLogo = new Drawing();
$drawingLogo->setName('Logo');
$drawingLogo->setDescription('Logo');
$drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
$drawingLogo->setCoordinates('A2');
$drawingLogo->setHeight(36);
$drawingLogo->setOffsetY(6);
$drawingLogo->setOffsetX(12);
$drawingLogo->setWorksheet($sheet);
$drawingData = new Drawing();
$drawingData->setName('Logo Data');
$drawingData->setDescription('Logo Data');
$drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/grdf.png');
$drawingData->setCoordinates('E5');
$drawingData->setHeight(26);
$drawingData->setOffsetY(4);
$drawingData->setOffsetX(12);
$drawingData->setWorksheet($sheet);
$sheet->setSelectedCell("A1");
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse();
$response->setCallback(function () use ($writer) {
$writer->save('php://output');
});
$filenane = "grdf_".$cotation->getCompanyName().'.xlsx';
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/companies/{company}/cotations/{cotation}/review", name="companies_cotations_review")
*/
public function companiesCotationsReviewAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Cotation");
$sheet->getProtection()->setSheet(true);
$spreadsheet->getDefaultStyle()->getProtection()->setLocked(true);
//HEADER
$sheet->setCellValue('A2', 'Cotation');
$sheet->getStyle('A2')->getFont()->setName("Arial")->setBold(true)->setSize(12);
$sheet->getStyle("A2")->getAlignment()->setVertical("center");
$sheet->getStyle("A2")->getAlignment()->setHorizontal("center");
$sheet->getStyle("A2")->getFont()->setBold(true);
$sheet->getStyle('A2')->getFont()->getColor()->setRGB('595959');
if ($cotation->getElectricity() && $cotation->getGas()) {
$sheet->mergeCells("A2:H3");
$sheet->getStyle('A2:H3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
$sheet->getStyle('A2:H3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
} else {
$sheet->mergeCells("A2:E3");
$sheet->getStyle('A2:E3')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D9D9D9');
$sheet->getStyle('A2:E3')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("757171");
}
$sheet->getColumnDimension("A")->setWidth(40);
$sheet->getColumnDimension("B")->setWidth(40);
$sheet->getColumnDimension("C")->setWidth(3);
$sheet->getColumnDimension("D")->setWidth(40);
$sheet->getColumnDimension("E")->setWidth(40);
if ($cotation->getElectricity() && $cotation->getGas()) {
$sheet->getColumnDimension("F")->setWidth(3);
$sheet->getColumnDimension("G")->setWidth(40);
$sheet->getColumnDimension("H")->setWidth(40);
}
//DONNEES CLIENT
$sheet->setCellValue('A5', 'Données client');
$sheet->setCellValue('A6', 'Raison sociale');
$sheet->setCellValue('A7', 'Nom du site');
$sheet->setCellValue('A8', 'SIRET');
$sheet->setCellValue('A9', 'Prénom');
$sheet->setCellValue('A10', 'Nom');
$sheet->setCellValue('A11', 'Fonction');
$sheet->setCellValue('A12', 'Adresse');
$sheet->setCellValue('A14', 'Adresse facturation');
$sheet->setCellValue('A16', 'Téléphone');
$sheet->setCellValue('A17', 'Email');
$sheet->setCellValue('A18', 'Secteur client');
$sheet->setCellValue('A19', 'Activité APE/NAF');
$sheet->setCellValue('A20', 'Tenue de l\'offre en jours');
$sheet->setCellValue('A21', 'Date du RDV client');
$sheet->setCellValue('A22', 'Ellipro (note sur 10) / 40/100 Créditsafe');
$sheet->setCellValue('A23', 'Tarif unique/ horosaisonnalité, Arenh(%) ...');
$sheet->setCellValue('A24', 'Marge souhaitée POUR flash Énergie');
$sheet->getStyle('A5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("A5:B5");
$sheet->getStyle('A5:B5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('92CDDC');
$sheet->getStyle('A5:B5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("A5:B24")->getAlignment()->setVertical('center');
$sheet->getStyle("A5:B24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 24; $i++) {
$sheet->getStyle('A'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('A'.$i)->getFont()->setBold(true);
$sheet->getStyle('B'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('B'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->getStyle('B8')->getNumberFormat()->setFormatCode('0');
$sheet->mergeCells("A12:A13");
$sheet->mergeCells("B12:B13");
$sheet->mergeCells("A14:A15");
$sheet->mergeCells("B14:B15");
$sheet->getStyle('B12')->getAlignment()->setWrapText(true);
$sheet->getStyle('B14')->getAlignment()->setWrapText(true);
$sheet->getStyle('A6:A24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('DAEEF3');
$sheet->setCellValue('B6', $cotation->getCompanyName());
$sheet->setCellValue('B7', $cotation->getPlaceName());
$sheet->setCellValue('B8', $cotation->getSiret());
$sheet->setCellValue('B9', $cotation->getFirstName());
$sheet->setCellValue('B10', $cotation->getLastName());
$sheet->setCellValue('B11', $cotation->getPosition());
$sheet->setCellValue('B12', $cotation->getAddress().(($cotation->getAddress2())?" ".$cotation->getAddress2():"")."\n".$cotation->getZipCode().", ".$cotation->getCity());
$sheet->setCellValue('B14', $cotation->getBillingAddress().(($cotation->getBillingAddress2())?" ".$cotation->getBillingAddress2():"")."\n".$cotation->getBillingZipCode().", ".$cotation->getBillingCity());
$sheet->setCellValue('B16', $cotation->getPhone());
$sheet->setCellValue('B17', $cotation->getEmail());
$sheet->setCellValue('B18', $cotation->getCompany()?$cotation->getCompany()->getSector():"");
$sheet->setCellValue('B19', $cotation->getCompany()?($cotation->getCompany()->getApeCode()):"");
$sheet->setCellValue('B20', '1 à 2 de validité du contrat');
$sheet->setCellValue('B21', $cotation->getAppointmentDate()?$cotation->getAppointmentDate()->format("d/m/Y"):"");
$sheet->setCellValue('B22', $cotation->getCreditsafeNote());
$sheet->setCellValue('B23', $cotation->getTarifType());
$sheet->setCellValue('B24', $cotation->getDesiredMargin());
if ($cotation->getElectricity()) {
//ENEDIS
$sheet->setCellValue('D5', 'Données consommation électricité');
$sheet->setCellValue('D6', 'Fournisseur actuel');
$sheet->setCellValue('D7', 'Début de fourniture souhaitée');
$sheet->setCellValue('D8', 'Fin de la fourniture souhaitée');
$sheet->setCellValue('D9', 'Nombre de mois à fournir');
$sheet->setCellValue('D10', 'RAE');
$sheet->setCellValue('D11', 'Segment');
$sheet->setCellValue('D12', 'Formule acheminement(facultatif)');
$sheet->setCellValue('D13', 'CAR (MWh)');
$sheet->setCellValue('D14', 'Consommation Pointe');
$sheet->setCellValue('D15', 'Consommation HPH');
$sheet->setCellValue('D16', 'Consommation HCH');
$sheet->setCellValue('D17', 'Consommation HPE');
$sheet->setCellValue('D18', 'Consommation HCE');
$sheet->setCellValue('D19', 'Puissance souscrites (Kva)');
$sheet->setCellValue('D20', 'Pointe');
$sheet->setCellValue('D21', 'HPH');
$sheet->setCellValue('D22', 'HCH');
$sheet->setCellValue('D23', 'HPE');
$sheet->setCellValue('D24', 'HCE');
$sheet->getStyle('D5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells("D5:E5");
$sheet->getStyle('D5:E5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle('D5:E5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle("D5:E24")->getAlignment()->setVertical('center');
$sheet->getStyle("D5:E24")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 24; $i++) {
$sheet->getStyle('D'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('D'.$i)->getFont()->setBold(true);
$sheet->getStyle('E'.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle('E'.$i)->getAlignment()->setHorizontal('left');
}
$sheet->mergeCells("D19:E19");
$sheet->getStyle('D19:E19')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle('D6:D18')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->getStyle('D20:D24')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->setCellValue('E6', $cotation->getElectricitySupplier()?$cotation->getElectricitySupplier()->getName():"");
$sheet->setCellValue('E7', $cotation->getEDesiredBegin()?$cotation->getEDesiredBegin()->format("d/m/Y"):"");
$sheet->setCellValue('E8', $cotation->getEDesiredEnd()?$cotation->getEDesiredEnd()->format("d/m/Y"):"");
$sheet->setCellValue('E9', $cotation->getENombreMois());
$sheet->setCellValue('E10', $cotation->getERae());
$sheet->setCellValue('E11', $cotation->getESegment());
$sheet->setCellValue('E12', $cotation->getEFormuleAcheminement());
$sheet->setCellValue('E13', $cotation->getECarMwh());
$sheet->setCellValue('E14', $cotation->getEConsommationPointe());
$sheet->setCellValue('E15', $cotation->getEConsommationHph());
$sheet->setCellValue('E16', $cotation->getEConsommationHch());
$sheet->setCellValue('E17', $cotation->getEConsommationHpe());
$sheet->setCellValue('E18', $cotation->getEConsommationHce());
$sheet->setCellValue('E20', $cotation->getEPuissanceKvaPointe());
$sheet->setCellValue('E21', $cotation->getEPuissanceKvaHph());
$sheet->setCellValue('E22', $cotation->getEPuissanceKvaHch());
$sheet->setCellValue('E23', $cotation->getEPuissanceKvaHpe());
$sheet->setCellValue('E24', $cotation->getEPuissanceKvaHce());
$drawingData = new Drawing();
$drawingData->setName('Logo Data');
$drawingData->setDescription('Logo Data');
$drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/enedis.png');
$drawingData->setCoordinates('E5');
$drawingData->setHeight(26);
$drawingData->setOffsetY(4);
$drawingData->setOffsetX(12);
$drawingData->setWorksheet($sheet);
}
if ($cotation->getGas()) {
$beginLetter = "D";
$endLetter = "E";
if ($cotation->getElectricity()) {
$beginLetter = "G";
$endLetter = "H";
}
//GRDF
$sheet->setCellValue($beginLetter.'5', 'Données consommation Gaz');
$sheet->setCellValue($beginLetter.'6', 'Fournisseur actuel');
$sheet->setCellValue($beginLetter.'7', 'Début de fourniture souhaitée');
$sheet->setCellValue($beginLetter.'8', 'Fin de la fourniture souhaitée');
$sheet->setCellValue($beginLetter.'9', 'Nombre de mois à fournir');
$sheet->setCellValue($beginLetter.'10', 'PCE');
$sheet->setCellValue($beginLetter.'11', 'Segment');
$sheet->setCellValue($beginLetter.'12', 'CAR (MWh)');
$sheet->getStyle($beginLetter.'5')->getFont()->setName("Arial")->setBold(true)->setSize(10);
$sheet->mergeCells($beginLetter."5:".$endLetter."5");
$sheet->getStyle($beginLetter.'$5:'.$endLetter.'5')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F4B084');
$sheet->getStyle($beginLetter.'$5:'.$endLetter.'5')->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle($beginLetter."5:".$endLetter."12")->getAlignment()->setVertical('center');
$sheet->getStyle($beginLetter."5:".$endLetter."12")->getFont()->setName("Arial")->setSize(8.5)->getColor()->setRGB("595959");
for ($i = 6; $i <= 12; $i++) {
$sheet->getStyle($beginLetter.''.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle($beginLetter.''.$i)->getFont()->setBold(true);
$sheet->getStyle($endLetter.''.$i)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB("AEAAAA");
$sheet->getStyle($endLetter.''.$i)->getAlignment()->setHorizontal('left');
}
$sheet->getStyle($beginLetter.'6:'.$beginLetter.'12')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F8CBAD');
$sheet->setCellValue($endLetter.'6', $cotation->getGasSupplier()?$cotation->getGasSupplier()->getName():"");
$sheet->setCellValue($endLetter.'7', $cotation->getGDesiredBegin()?$cotation->getGDesiredBegin()->format("d/m/Y"):"");
$sheet->setCellValue($endLetter.'8', $cotation->getGDesiredEnd()?$cotation->getGDesiredEnd()->format("d/m/Y"):"");
$sheet->setCellValue($endLetter.'9', $cotation->getGNombreMois());
$sheet->setCellValue($endLetter.'10', $cotation->getGPce());
$sheet->setCellValue($endLetter.'11', $cotation->getGSegment());
$sheet->setCellValue($endLetter.'12', $cotation->getGCarMwh());
$drawingData = new Drawing();
$drawingData->setName('Logo Data');
$drawingData->setDescription('Logo Data');
$drawingData->setPath($kernel->getProjectDir().'/public/assets/media/logos/grdf.png');
$drawingData->setCoordinates($endLetter.'5');
$drawingData->setHeight(26);
$drawingData->setOffsetY(4);
$drawingData->setOffsetX(12);
$drawingData->setWorksheet($sheet);
}
//END
$sheet->getRowDimension("2")->setRowHeight(18);
$sheet->getRowDimension("3")->setRowHeight(18);
$sheet->getRowDimension("5")->setRowHeight(26);
$sheet->getRowDimension("6")->setRowHeight(26);
$sheet->getRowDimension("7")->setRowHeight(26);
$sheet->getRowDimension("8")->setRowHeight(26);
$sheet->getRowDimension("9")->setRowHeight(26);
$sheet->getRowDimension("10")->setRowHeight(26);
$sheet->getRowDimension("11")->setRowHeight(26);
$sheet->getRowDimension("12")->setRowHeight(26);
$sheet->getRowDimension("13")->setRowHeight(26);
$sheet->getRowDimension("14")->setRowHeight(26);
$sheet->getRowDimension("15")->setRowHeight(26);
$sheet->getRowDimension("16")->setRowHeight(26);
$sheet->getRowDimension("17")->setRowHeight(26);
$sheet->getRowDimension("18")->setRowHeight(26);
$sheet->getRowDimension("19")->setRowHeight(26);
$sheet->getRowDimension("20")->setRowHeight(26);
$sheet->getRowDimension("21")->setRowHeight(26);
$sheet->getRowDimension("22")->setRowHeight(26);
$sheet->getRowDimension("23")->setRowHeight(26);
$sheet->getRowDimension("24")->setRowHeight(26);
$drawingLogo = new Drawing();
$drawingLogo->setName('Logo');
$drawingLogo->setDescription('Logo');
$drawingLogo->setPath($kernel->getProjectDir().'/public/assets/media/logo-01-01_SMALL.png');
$drawingLogo->setCoordinates('A2');
$drawingLogo->setHeight(36);
$drawingLogo->setOffsetY(6);
$drawingLogo->setOffsetX(12);
$drawingLogo->setWorksheet($sheet);
$sheet->setSelectedCell("A1");
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse();
$response->setCallback(function () use ($writer) {
$writer->save('php://output');
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="enedis.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/companies/{company}/cotations/{cotationId}/notif-princing", name="companies_cotations_notif-princing")
*/
public function companiesCotationsNotifPricingAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, int $cotationId, SendEmailService $sendEmailService)
{
$cotation = $em->getRepository(Cotation::class)->find($cotationId);
if (!$cotation) {
$cotation = $em->getRepository(CotationMultisite::class)->find($cotationId);
}
if (!$cotation) {
throw new RouteNotFoundException();
}
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$raisonSociale = $cotation->getCompanyName();
$siret = $cotation->getSiret();
$content = <<<EOD
Raison Sociale : $raisonSociale
<br/>
Siret : $siret
<br/>
EOD;
if ($cotation instanceof CotationMultisite) {
foreach ($cotation as $cotationItem) {
if ($cotation->getElectricity()) {
$fournisseurElec = $cotationItem->getElecDesiredSuppliersToString();
$debutFournitureElec = $cotationItem->getEDesiredBegin() ? $cotationItem->getEDesiredBegin()->format('d/m/Y') : '';
$finFournitureElec = $cotationItem->getEDesiredEnd() ? $cotationItem->getEDesiredEnd()->format('d/m/Y') : '';
$pdl = $cotationItem->getEPdl();
$content .= <<<EOD
Fournisseur(s) souhaité(s) ELEC : $fournisseurElec
<br/>
Début de fourniture ELEC : $debutFournitureElec
<br/>
Fin de fourniture ELEC : $finFournitureElec
<br/>
PDL : $pdl
<br/>
EOD;
}
if ($cotationItem->getGas()) {
$fournisseurGaz = $cotationItem->getGasDesiredSuppliersToString();
$debutFournitureGaz = $cotationItem->getGDesiredBegin() ? $cotationItem->getGDesiredBegin()->format('d/m/Y') : '';
$finFournitureGaz = $cotationItem->getGDesiredEnd() ? $cotationItem->getGDesiredEnd()->format('d/m/Y') : '';
$pce = $cotationItem->getGPce();
$content .= <<<EOD
Fournisseur(s) souhaité(s) GAZ : $fournisseurGaz
<br/>
Début de fourniture GAZ : $debutFournitureGaz
<br/>
Fin de fourniture GAZ : $finFournitureGaz
<br/>
PCE : $pce
<br/>
EOD;
}
}
} else {
if ($cotation->getElectricity()) {
$fournisseurElec = $cotation->getElecDesiredSuppliersToString();
$debutFournitureElec = $cotation->getEDesiredBegin() ? $cotation->getEDesiredBegin()->format('d/m/Y') : '';
$finFournitureElec = $cotation->getEDesiredEnd() ? $cotation->getEDesiredEnd()->format('d/m/Y') : '';
$pdl = $cotation->getEPdl();
$content .= <<<EOD
Fournisseur(s) souhaité(s) ELEC : $fournisseurElec
<br/>
Début de fourniture ELEC : $debutFournitureElec
<br/>
Fin de fourniture ELEC : $finFournitureElec
<br/>
PDL : $pdl
<br/>
EOD;
}
if ($cotation->getGas()) {
$fournisseurGaz = $cotation->getGasDesiredSuppliersToString();
$debutFournitureGaz = $cotation->getGDesiredBegin() ? $cotation->getGDesiredBegin()->format('d/m/Y') : '';
$finFournitureGaz = $cotation->getGDesiredEnd() ? $cotation->getGDesiredEnd()->format('d/m/Y') : '';
$pce = $cotation->getGPce();
$content .= <<<EOD
Fournisseur(s) souhaité(s) GAZ : $fournisseurGaz
<br/>
Début de fourniture GAZ : $debutFournitureGaz
<br/>
Fin de fourniture GAZ : $finFournitureGaz
<br/>
PCE : $pce
<br/>
EOD;
}
}
$dateEtHeureRdv = $cotation->getAppointmentDate() ? $cotation->getAppointmentDate()->format('d/m/Y H:i') : '';
$commercial = $cotation->getManager() ? $cotation->getManager()->getFirstName().' '.$cotation->getManager()->getLastName() : '';
$content .= <<<EOD
Date et heure de RDV : $dateEtHeureRdv
<br/>
Commercial : $commercial
<br/>
EOD;
$sendEmailService->send(
"Demande de cotation - ".$raisonSociale,
$this->getUser()->getManager()->getReferentPricing(),
'emails/flash_default.html.twig',
[
"title" => "Demande de cotation - ".$raisonSociale,
"content" => $content
]
);
$cotation->setPricingSentDate(new \DateTime('now'));
$em->flush();
$this->get('session')->getFlashBag()->add("success", "Notification envoyée à pricing");
return $this->redirectToRoute(($cotation instanceof CotationMultisite) ? "manager_companies_cotations-multisites_edit" : "manager_companies_cotations_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/turpe", name="companies_cotations_turpe")
*/
public function companiesCotationsTurpeAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, TurpeCalculatorService $turpeCalculatorService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$isLongueUtilisation = false;
if ($request->get("isLongueUtilisation") && $request->get("isLongueUtilisation") == "true") {
$isLongueUtilisation = true;
}
$turpe = $turpeCalculatorService->calc($cotation, $isLongueUtilisation);
return new Response($turpe,200);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/enedis-car", name="companies_cotations_enedis-car")
*/
public function companiesCotationsEnedisCarAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$cotation->getEPdl()) {
return new JsonResponse([
"success" => false,
"message" => "PDL non renseigné pour cette cotation"
]);
}
$data = $enedisService->getCar($cotation->getEPdl());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/enedis-donnees-contractuelles", name="companies_cotations_enedis-donnees-contractuelles")
*/
public function companiesCotationsEnedisDonneesContractuellesAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$cotation->getEPdl()) {
return new JsonResponse([
"success" => false,
"message" => "PDL non renseigné pour cette cotation"
]);
}
$data = $enedisService->getDonneesContractuelles($cotation->getEPdl());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/enedis-address", name="companies_cotations_enedis-address")
*/
public function companiesCotationsEnedisAddressAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$cotation->getEPdl()) {
return new JsonResponse([
"success" => false,
"message" => "PDL non renseigné pour cette cotation"
]);
}
$data = $enedisService->getDonneesContractuelles($cotation->getEPdl(), true);
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération des données ENEDIS. Veuillez les renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/enedis-depassements", name="companies_cotations_enedis-depassements")
*/
public function companiesCotationsEnedisDepassementsAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, EnedisService $enedisService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$cotation->getEPdl()) {
return new JsonResponse([
"success" => false,
"message" => "PDL non renseigné pour cette cotation"
]);
}
$data = $enedisService->getDonneesDepassements($cotation->getEPdl());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération des données de dépassements ENEDIS."
]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers", name="companies_cotations_offers")
*/
public function companiesCotationsOffersAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation], ["currentOffer" => "DESC"]);
$offersGas = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation], ["currentOffer" => "DESC"]);
return $this->render("app/clients/cotations_offers.html.twig", [
"offersElec" => $offersElec,
"offersGas" => $offersGas,
"company" => $company,
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/pdf", name="companies_cotations_offers_pdf")
*/
public function companiesCotationsOffersPdfAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, Pdf $knpSnappyPdf)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createFormBuilder()->getForm();
if ($cotation->getElectricity()) {
$form->add("etude_solution_elec", ChoiceType::class, [
"expanded" => false,
"multiple" => false,
"choices" => [
"Prendre un prix unique composé de la totalité de ses droits d’ARENH" => "1",
"Prendre un prix unique composé d’un taux modéré de ses droits d'ARENH" => "2",
"Maintenir un prix unique composé d'un prix 100 % fixe" => "3",
"Prendre un horosaisonnalisé 100 % fixe (uniquement prix de marché)" => "4",
"Prendre un prix horosaisonnalisé composé d’un taux modéré de ses droits d'ARENH" => "5",
"Maintenir un prix horosaisonnalisé composé de la totalité de ses droits d’ARENH" => "6",
],
"label" => "Choix de la solution ELEC",
])
->add("etude_commentaire_elec", TextType::class, [
"attr" => [
"placeholder" => ""
],
"label" => "Commentaire ELEC",
"required" => false,
]);
$form["etude_solution_elec"]->setData($cotation->getEtudeSolutionElec());
$form["etude_commentaire_elec"]->setData($cotation->getEtudeCommentaireElec());
}
if ($cotation->getGas()) {
$form->add("etude_solution_gaz", ChoiceType::class, [
"expanded" => false,
"multiple" => false,
"choices" => [
"Prendre un prix variable indexé sur le PEG" => "1",
"Maintenir un prix 100 % fixe" => "2",
],
"label" => "Choix de la solution GAZ",
])
->add("etude_commentaire_gaz", TextType::class, [
"attr" => [
"placeholder" => ""
],
"label" => "Commentaire GAZ",
"required" => false,
]);
$form["etude_solution_gaz"]->setData($cotation->getEtudeSolutionGaz());
$form["etude_commentaire_gaz"]->setData($cotation->getEtudeCommentaireGaz());
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($cotation->getElectricity()) {
$cotation->setEtudeSolutionElec($form["etude_solution_elec"]->getData());
$cotation->setEtudeCommentaireElec($form["etude_commentaire_elec"]->getData());
}
if ($cotation->getGas()) {
$cotation->setEtudeSolutionGaz($form["etude_solution_gaz"]->getData());
$cotation->setEtudeCommentaireGaz($form["etude_commentaire_gaz"]->getData());
}
$em->flush();
$offersElec = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotation, "displayed" => true], ["currentOffer" => "DESC"]);
$offersGas = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotation, "displayed" => true], ["currentOffer" => "DESC"]);
$html = $this->renderView('app/pdf/presentation-budget/section1.html.twig', array(
"offersElec" => $offersElec,
"offersGas" => $offersGas,
'cotation' => $cotation,
'multisite' => false,
));
$pdf = $knpSnappyPdf->getOutputFromHtml($html, array(
'orientation' => 'landscape',
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'page-height' => 340,
'page-width' => 200,
'encoding' => 'utf-8',
'images' => true,
'cookie' => array(),
'dpi' => 300,
'enable-external-links' => true,
'enable-internal-links' => true,
'margin-bottom' => 0
));
return new Response($pdf,200,array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="Flash-Presentation_budget.pdf"'
));
/*
return new PdfResponse(
$knpSnappyPdf->getOutputFromHtml($html),
'Flash-Presentation_budget.pdf'
);
*/
}
return $this->render("app/clients/cotation_offers_pdf.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
"multisite" => false,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/add", name="companies_cotations_offers_add")
*/
public function companiesCotationsOffersAddAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($request->get("elec")) {
if (!$cotation->getElectricity() || $cotation->getSelectedOfferElec() != null) {
throw new BadRequestHttpException();
}
$offer = new OfferElec();
if ($cotation->getCotationMultisite() && $request->get("duplicate")) {
$duplicateOffer = $em->getRepository(OfferElec::class)->find($request->get("duplicate"));
if ($duplicateOffer && $cotation->getCotationMultisite() === $duplicateOffer->getCotation()->getCotationMultisite()) {
$offer = clone $duplicateOffer;
}
}
$offer->setCotation($cotation);
$form = $this->createForm(OfferElecType::class, $offer);
$title = "Ajouter une offre Electricité";
$type = "elec";
} else {
if (!$cotation->getGas() || $cotation->getSelectedOfferGaz() != null) {
throw new BadRequestHttpException();
}
$offer = new OfferGaz();
if ($cotation->getCotationMultisite() && $request->get("duplicate")) {
$duplicateOffer = $em->getRepository(OfferGaz::class)->find($request->get("duplicate"));
if ($duplicateOffer && $cotation->getCotationMultisite() === $duplicateOffer->getCotation()->getCotationMultisite()) {
$offer = clone $duplicateOffer;
}
}
$offer->setCotation($cotation);
$form = $this->createForm(OfferGazType::class, $offer);
$title = "Ajouter une offre Gaz";
$type = "gas";
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($offer);
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_offers_directory'),
$fileName
);
$offer->setFile($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Offre fournisseur ajoutée");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
return $this->render("app/clients/cotation_offer_form.html.twig", [
"form" => $form->createView(),
"offer" => $offer,
"title" => $title,
"type" => $type,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/add-file", name="companies_cotations_offers_add-file")
*/
public function companiesCotationsOffersAddFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, DocusignService $docusignService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createFormBuilder()
->add('supplier', EntityType::class, [
"class" => Supplier::class,
"label" => "Fournisseur de l'offre",
"placeholder" => "Fournisseur de l'offre",
"required" => true,
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('s');
$qb->where('s.active = true');
return $qb;
},
])
->add('file', FileType::class, [
'attr' => [
'accept' => '.pdf, .doc, .docx',
'placeholder' => 'Importer l\'offre ou le contrat'
],
'label' => 'Document',
'required' => false,
'mapped' => false,
])->getForm();
$signatureAvailable = true;
if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
$signatureAvailable = false;
}
if ($signatureAvailable) {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "Envoyer la signature électronique de l'offre",
"required" => false,
"mapped" => false,
]);
} else {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
"data" => true,
"disabled" => true,
"required" => false,
"mapped" => false,
]);
}
if ($request->get("elec")) {
if (!$cotation->getElectricity() || $cotation->getSelectedOfferElec() != null) {
throw new BadRequestHttpException();
}
$offer = new OfferElec();
$offer->setCotation($cotation);
$title = "Ajouter le contrat Electricité";
$type = "elec";
} else {
if (!$cotation->getGas() || $cotation->getSelectedOfferGaz() != null) {
throw new BadRequestHttpException();
}
$offer = new OfferGaz();
$offer->setCotation($cotation);
$title = "Ajouter le contrat Gaz";
$type = "gas";
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Veuillez indiquer un fichier valide. Les extensions autorisées sont .pdf, .doc, .docx');
}
if ($form->isSubmitted() && $form->isValid()) {
$supplier = $form['supplier']->getData();
$offer->setSupplier($supplier);
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if ($extension && in_array($extension, ["pdf", "doc", "docx"])) {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_offers_directory'),
$fileName
);
$offer->setFile($fileName);
$em->persist($offer);
$em->flush();
// Signature électronique de l'offre
if ($form->get('enableDocusign')->getData()) {
$filePath = $this->getParameter('documents_offers_directory').$fileName;
// Création de la procédure
$procedureSign = new ProcedureSign();
$procedureSign->setUser($company->getUser());
$procedureSign->setFirstName($cotation->getFirstName());
$procedureSign->setLastName($cotation->getLastName());
$procedureSign->setEmail($cotation->getEmail());
$procedureSign->setPhone($cotation->getPhone());
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "cotation.offer",
"nrj" => $request->get("elec") ? "elec" : "gaz",
"id" => $offer->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
/*$fileCertificate = $this->getParameter('documents_fc_certificate');
if (file_exists($fileCertificate)) {
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile($filePath);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
// add certificate
$pagecount = $pdf->setSourceFile($fileCertificate);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
$pdf->Output($filePath, 'F');
}*/
// Lancement de la signature
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
try {
$response = $docusignService->sendFile($accessToken, $procedureSign);
$procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté. Le mail pour la signature électronique de l'offre a été envoyé au client.");
} catch (ApiException $e) {
$this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté.");
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
} else {
$this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté.");
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
} else {
$this->get("session")->getFlashBag()->add("success", "Contrat fournisseur ajouté. Vous devez l'envoyer pour signature au client.");
}
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
} else {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Fichier introuvable ou incorrect.");
}
}
return $this->render("app/clients/cotation_offer_contract_form.html.twig", [
"form" => $form->createView(),
"offer" => $offer,
"title" => $title,
"type" => $type,
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/preselect", name="companies_cotations_offers_elec_preselect")
*/
public function companiesCotationsOffersElecPreselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
throw new BadRequestHttpException();
}
$cotation->setPreselectedOfferElec($offer);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre éléctricité présélectionnée.");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/deselect", name="companies_cotations_offers_elec_deselect")
*/
public function companiesCotationsOffersElecDeselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotation->setPreselectedOfferElec(null);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre éléctricité désélectionnée.");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/choose", name="companies_cotations_offers_elec_choose")
*/
public function companiesCotationsOffersElecChooseAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
throw new BadRequestHttpException();
}
$cotation->setSelectedOfferElec($offer);
$em->flush();
// Mise à jour du state
if (
(!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
&&
(!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
) {
$stateTerminee = $em->getRepository(CotationState::class)->find(6);
$cotation->setState($stateTerminee);
$em->flush();
}
// Edition du contrat
$contract = new Contract();
$contract->setUser($cotation->getUser());
$contract->setCompany($cotation->getCompany());
$contract->setElectricity(true);
$contract->setElectricitySituation($cotation->getElectricitySituation());
$contract->setSupplier($offer->getSupplier());
$contract->setAddress($cotation->getAddress());
$contract->setAddress2($cotation->getAddress2());
$contract->setZipCode($cotation->getZipCode());
$contract->setCity($cotation->getCity());
$contract->setPdlNumber($cotation->getEPdl());
$contract->setOfferElec($offer);
$contract->setSepaIban($cotation->getSepaIban());
$contract->setSepaBic($cotation->getSepaBic());
$contract->setManager($cotation->getManager());
$contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
$contract->setState($contratStateEnAttenteClient);
if ($offer->getFile()) {
$filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
$contract->setFile($offer->getFile());
}
$em->persist($contract);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre éléctricité sélectionnée. Le contrat a été édité.");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/preselect", name="companies_cotations_offers_gas_preselect")
*/
public function companiesCotationsOffersGasPreselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
throw new BadRequestHttpException();
}
$cotation->setPreselectedOfferGaz($offer);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre gaz présélectionnée.");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/deselect", name="companies_cotations_offers_gas_deselect")
*/
public function companiesCotationsOffersGasDeselectAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotation->setPreselectedOfferGaz(null);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre gaz désélectionnée.");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/choose", name="companies_cotations_offers_gas_choose")
*/
public function companiesCotationsOffersGasChooseAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (($cotation->getCotationMultisite() && $cotation->getCotationMultisite()->getState()->getId() == 6) || (!$cotation->getCotationMultisite() && $cotation->getState()->getId() == 6)) {
throw new BadRequestHttpException();
}
$cotation->setSelectedOfferGaz($offer);
$em->flush();
// Mise à jour du state
if (
(!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSelectedOfferElec() != null))
&&
(!$cotation->getGas() || ($cotation->getGas() && $cotation->getSelectedOfferGaz() != null))
) {
$stateTerminee = $em->getRepository(CotationState::class)->find(6);
$cotation->setState($stateTerminee);
$em->flush();
}
// Edition du contrat
$contract = new Contract();
$contract->setUser($cotation->getUser());
$contract->setCompany($cotation->getCompany());
$contract->setGas(true);
$contract->setGasSituation($cotation->getElectricitySituation());
$contract->setSupplier($offer->getSupplier());
$contract->setAddress($cotation->getAddress());
$contract->setAddress2($cotation->getAddress2());
$contract->setZipCode($cotation->getZipCode());
$contract->setCity($cotation->getCity());
$contract->setPceNumber($cotation->getGPce());
$contract->setOfferGaz($offer);
$contract->setManager($cotation->getManager());
$contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
$contract->setState($contratStateEnAttenteClient);
if ($offer->getFile()) {
$filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
$contract->setFile($offer->getFile());
}
$em->persist($contract);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre gaz sélectionnée. Le contrat a été édité.");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/edit", name="companies_cotations_offers_elec_edit")
*/
public function companiesCotationsOffersElecEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(OfferElecType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_offers_directory'),
$fileName
);
$offer->setFile($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Offre fournisseur mise à jour");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
return $this->render("app/clients/cotation_offer_form.html.twig", [
"form" => $form->createView(),
"offer" => $offer,
"title" => "Modifier une offre Electricité",
"type" => "elec",
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/edit", name="companies_cotations_offers_gas_edit")
*/
public function companiesCotationsOffersGasEditAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(OfferGazType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_offers_directory'),
$fileName
);
$offer->setFile($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Offre fournisseur mise à jour");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
return $this->render("app/clients/cotation_offer_form.html.twig", [
"form" => $form->createView(),
"offer" => $offer,
"title" => "Modifier une offre Gaz",
"type" => "gas",
]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/file", name="companies_cotations_offers_elec_file")
*/
public function companiesCotationsOffersElecFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getFile()) {
$filePath = $this->getParameter('documents_offers_directory') . $offer->getFile();
return $this->file($filePath, $offer->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/file-delete", name="companies_cotations_offers_elec_file-delete")
*/
public function companiesCotationsOffersElecFileDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$offer->setFile(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_offers_elec_edit", ["company" => $company->getId(), "cotation" => $cotation->getId(), "offer" => $offer->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/hide", name="companies_cotations_offers_elec_hide")
*/
public function companiesCotationsOffersElecHideAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offer->setDisplayed(false);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre masquée");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/elec/{offer}/display", name="companies_cotations_offers_elec_display")
*/
public function companiesCotationsOffersElecDisplayAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferElec $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offer->setDisplayed(true);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre démasquée");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/file", name="companies_cotations_offers_gas_file")
*/
public function companiesCotationsOffersGasFileAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($offer->getFile()) {
$filePath = $this->getParameter('documents_offers_directory') . $offer->getFile();
return $this->file($filePath, $offer->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/file-delete", name="companies_cotations_offers_gas_file-delete")
*/
public function companiesCotationsOffersGasFileDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$offer->setFile(null);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations_offers_elec_edit", ["company" => $company->getId(), "cotation" => $cotation->getId(), "offer" => $offer->getId()]);
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/hide", name="companies_cotations_offers_gas_hide")
*/
public function companiesCotationsOffersGasHideAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offer->setDisplayed(false);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre masquée");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations/{cotation}/offers/gas/{offer}/display", name="companies_cotations_offers_gas_display")
*/
public function companiesCotationsOffersGasDisplayAction(Request $request, EntityManagerInterface $em, Company $company, Cotation $cotation, OfferGaz $offer)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$offer->getCotation() || $offer->getCotation()->getId() != $cotation->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offer->setDisplayed(true);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Offre démasquée");
if ($cotation->getCotationMultisite()) {
return $this->redirectToRoute("manager_companies_cotations-multisites_offers", ["company" => $company->getId(), "cotation" => $cotation->getCotationMultisite()->getId()]);
} else {
return $this->redirectToRoute("manager_companies_cotations_offers", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
}
/**
* @Route("/companies/{company}/cotations-multisites/add", name="companies_cotations-multisites_add")
*/
public function companiesCotationsMultisitesAddAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$cotation = new CotationMultisite();
$cotation->setCompany($company);
$cotation->setManager($this->getUser()->getManager());
$cotation->setSiret($company->getSiret());
$cotation->setCompanyName($company->getName());
$cotation->setFirstName($company->getUser()->getFirstName());
$cotation->setLastName($company->getUser()->getLastName());
$cotation->setPosition($company->getUser()->getPosition());
$cotation->setPhone($company->getPhone());
$cotation->setEmail($company->getEmail());
$cotation->setApeCode($company->getApeCode());
$cotation->setSector($company->getSector());
$form = $this->createForm(CotationMultisiteType::class, $cotation);
$form->add('type', ChoiceType::class, [
"label" => "Type d'énergie",
"choices" => [
"Elec" => "Elec",
"Gaz" => "Gaz",
],
"required" => true,
"mapped" => false,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$state = $em->getRepository(CotationState::class)->find(1);
$cotation->setState($state);
$cotation->setCreationDate(new \DateTime("now"));
$type = $form->get('type')->getData();
if ($type == "Elec") {
$cotation->setElectricity(true);
}
if ($type == "Gaz") {
$cotation->setGas(true);
}
$em->persist($cotation);
$em->flush();
return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
return $this->render("app/clients/cotation-multisite_form.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/edit", name="companies_cotations-multisites_edit")
*/
public function companiesCotationsMultisitesEditAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, DocusignService $docusignService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createForm(CotationMultisiteType::class, $cotation);
$signatureAvailable = true;
if (!$company->getUser()->getEmail() || !$company->getUser()->getPhone()) {
$signatureAvailable = false;
}
if ($signatureAvailable) {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "Envoyer la signature électronique de l'ACD",
"required" => false,
"mapped" => false,
]);
} else {
$form->add('enableDocusign', CheckboxType::class, [
"label" => "La signature électronique n'est pas disponible pour ce client. Les informations (Email, Téléphone) sont incomplètes.",
"data" => true,
"disabled" => true,
"required" => false,
"mapped" => false,
]);
}
if ($cotation->getCompany()->getValidated()) {
$form->add('acdFileUpload', FileType::class, [
'attr' => [
'placeholder' => 'Importer le fichier ACD'
],
'label' => 'Importer le fichier ACD',
'required' => false,
'mapped' => false
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$cotation->setEditDate(new \DateTime("now"));
$em->flush();
if ($form->get('oldInvoice')->getData()) {
$fileOldInvoice = $form->get('oldInvoice')->getData();
if ($fileOldInvoice != NULL) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileOldInvoice->guessExtension();
$fileOldInvoice->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOldInvoice($fileName);
}
}
$cotationSites = $form['cotations']->getData();
foreach ($cotationSites as $key => $cotationSite) {
$cotationSite->setManager($cotation->getManager());
$cotationSite->setCompany($cotation->getCompany());
$fileFactElec = $form['cotations'][$key]["factElec"]->getData();
if ($fileFactElec) {
$extension = $fileFactElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture elec");
} else {
$fileName = $cotation->getId() . "_" . $cotationSite->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotationSite->setFactElec($fileName);
$em->flush();
}
}
$fileFactGas = $form['cotations'][$key]["factGas"]->getData();
if ($fileFactGas) {
$extension = $fileFactGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la facture gaz");
} else {
$fileName = $cotation->getId() . "_" . $cotationSite->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileFactGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotationSite->setFactGas($fileName);
$em->flush();
}
}
}
$fileLiaseFiscale = $form['liasseFiscale']->getData();
if ($fileLiaseFiscale) {
$extension = $fileLiaseFiscale->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la liasse fiscale");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileLiaseFiscale->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setLiasseFiscale($fileName);
$em->flush();
}
}
$fileSgeElec = $form['sgeElec']->getData();
if ($fileSgeElec) {
$extension = $fileSgeElec->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la SGE");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileSgeElec->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setSgeElec($fileName);
$em->flush();
}
}
$fileOmegaGas = $form['omegaGas']->getData();
if ($fileOmegaGas) {
$extension = $fileOmegaGas->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "png", "jpeg", "jpg", "gif"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé pour la Omega");
} else {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $extension;
$fileOmegaGas->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$cotation->setOmegaGas($fileName);
$em->flush();
}
}
if ($form->has('acdFileUpload')) {
$fileAcd = $form->get('acdFileUpload')->getData();
if ($fileAcd != NULL) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.' . $fileAcd->guessExtension();
$fileAcd->move(
$this->getParameter('documents_acd_directory'),
$fileName
);
$cotation->setAcdFile($fileName);
$cotation->setAcdSignDate(new \DateTime('now'));
$em->flush();
}
}
// Signature électronique de l'ACD
if ($form->has('enableDocusign') && $form->get('enableDocusign')->getData()) {
// Lancement de la signature
$startSign = null;
if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
$startSign = $this::sendAcdMultisiteToDocusign($cotation, $company, $docusignService, $em);
} else {
$this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
}
if (!$startSign) {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
} else {
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
}
}
// Cotation status
if ($cotation->getState()->getId() != 5) {
if (
(!$cotation->getGas() || ($cotation->getGas() && $cotation->getOmegaGas()))
&&
(!$cotation->getElectricity() || ($cotation->getElectricity() && $cotation->getSgeElec()))
) {
$newState = $em->getRepository(CotationState::class)->find(4);
$cotation->setState($newState);
} else if ($cotation->getAcdFile()) {
$newState = $em->getRepository(CotationState::class)->find(3);
$cotation->setState($newState);
} else {
$newState = $em->getRepository(CotationState::class)->find(2);
$cotation->setState($newState);
}
}
$this->get("session")->getFlashBag()->add("success", "Demande de cotation mise à jour");
return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
return $this->render("app/clients/cotation-multisite_form.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/ellipro", name="companies_cotations-multisites_ellipro")
*/
public function companiesCotationMultisiteElliproAction(Request $request, Company $company, CotationMultisite $cotation, EllisphereService $ellisphereService)
{
if (!$cotation->getSiret()) {
return new JsonResponse([
"success" => false,
"message" => "Siret non renseigné pour cette cotation"
]);
}
$data = $ellisphereService->getNoteElliPro($cotation->getSiret());
if ($data) {
return new JsonResponse([
"success" => true,
"data" => $data
]);
} else {
return new JsonResponse([
"success" => false,
"message" => "Une erreur est survenue lors de la récupération de la note ElliPro. Veuillez la renseigner manuellement."
]);
}
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/acd", name="companies_cotations-multisites_acd")
*/
public function companiesCotationsMultisitesAcdAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->getAcdFile()) {
$filePath = $this->getParameter('documents_acd_directory') . $cotation->getAcdFile();
return $this->file($filePath, $cotation->getAcdFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
if ($cotation->getState()->getId() == 1) {
$newState = $em->getRepository(CotationState::class)->find(2);
$cotation->setState($newState);
$em->flush();
}
$pdf = $this->generateACDMultisite($cotation);
$filename = "ACD";
return $pdf->Output($filename.".pdf",'I');
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/send-acd", name="companies_cotations-multisites_send_acd")
*/
public function companiesCotationsMultisiteSendAcdAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, DocusignService $docusignService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotation->isAcdValid()) {
$this->get("session")->getFlashBag()->add("danger", "L'ACD a déjà été renseigné pour cette cotation.");
} else {
// Lancement de la signature
$startSign = null;
if ($cotation->getPhone() != $this->getUser()->getManager()->getPhone()) {
$startSign = $this::sendAcdMultisiteToDocusign($cotation, $company, $docusignService, $em);
} else {
$this->get("session")->getFlashBag()->add("danger", "Impossible d'envoyer l'ACD à votre numéro de téléphone.");
}
if (!$startSign) {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
} else {
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique de l'ACD a été envoyé au client.");
}
}
return $this->redirectToRoute("manager_companies_cotations-multisites_edit", ["company" => $company->getId(), "cotation" => $cotation->getId()]);
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/excel-elec", name="companies_cotations-multisites_excel-elec")
*/
public function companiesCotationsMultisiteExcelElecAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, CotationMultisite $cotation)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Cotation Multisite ELEC");
$sheet->getProtection()->setSheet(true);
$spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
//HEADER
// ---------- Helpers ----------
$thinBorder = [
'borders' => [
'allBorders' => ['borderStyle' => Border::BORDER_THIN],
],
];
$mediumOutline = [
'borders' => [
'outline' => ['borderStyle' => Border::BORDER_MEDIUM],
],
];
$centerWrap = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
];
$boldCenter = [
'font' => ['bold' => true, 'size' => 10],
] + $centerWrap;
$normalCenter = [
'font' => ['bold' => false, 'size' => 10],
] + $centerWrap;
$fill = function(string $hex) {
return [
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => ltrim($hex, '#')],
],
];
};
$fillInfoClients = $fill('#FCE4D6'); // A1:L4
$fillCotation = $fill('#E2EFDA'); // M1:P4
$fillContrats = $fill('#FFF2CC'); // Q1:T4
$fillSites = $fill('#DDEBF7'); // U1:AI3
$fillSousTitreBlue = $fill('#BDD7EE'); // Y4:AC4 (Puissances)
$fillSousTitreGrn = $fill('#C6E0B4'); // AD4:AI4 (Consommations MWh)
$fillHeader2 = $fill('#B4C6E7'); // Lignes 5-6 (libellés colonnes)
// ---------- Largeurs de colonnes ----------
$widths = [
'A'=>15,'B'=>15,'C'=>16,'D'=>15,'E'=>16,'F'=>16,'G'=>12,'H'=>22,'I'=>22,'J'=>14,'K'=>12,'L'=>16,
'M'=>18,'N'=>14,'O'=>28,'P'=>24,'Q'=>18,'R'=>16,'S'=>16,'T'=>18,
'U'=>24,'V'=>30,'W'=>14,'X'=>20,
// blocs Y..AI
'Y'=>10,'Z'=>10,'AA'=>10,'AB'=>10,'AC'=>10,
'AD'=>10,'AE'=>10,'AF'=>10,'AG'=>10,'AH'=>10,'AI'=>10, 'AJ'=>10
];
foreach ($widths as $col => $w) {
$sheet->getColumnDimension($col)->setWidth($w);
}
// ---------- Hauteurs de ligne ----------
$sheet->getRowDimension(1)->setRowHeight(24);
$sheet->getRowDimension(2)->setRowHeight(18);
$sheet->getRowDimension(3)->setRowHeight(18);
$sheet->getRowDimension(4)->setRowHeight(22);
$sheet->getRowDimension(5)->setRowHeight(22);
$sheet->getRowDimension(6)->setRowHeight(22);
// ---------- Contenu & fusions ----------
$sheet->mergeCells('A1:L4')->setCellValue('A1', 'Informations clients');
$sheet->mergeCells('M1:P4')->setCellValue('M1', 'Informations cotations');
$sheet->mergeCells('Q1:T4')->setCellValue('Q1', 'Informations contrats ');
$sheet->mergeCells('U1:AI3')->setCellValue('U1', 'Informations sites ');
$sheet->mergeCells('Y4:AC4')->setCellValue('Y4', 'Puissances');
$sheet->mergeCells('AD4:AI4')->setCellValue('AD4', 'Consommations MWh');
// Ligne 5 (labels de colonnes, fusionnées avec ligne 6)
$labels = [
'A5' => 'Nom du Site',
'B5' => 'Titulaire',
'C5' => 'SIRET Titulaire',
'D5' => 'Payeur',
'E5' => 'SIRET Payeur',
'F5' => 'Nom Prénom',
'G5' => 'Fonction',
'H5' => 'Adresse de facturation',
'I5' => 'Téléphone',
'J5' => 'Email',
'K5' => 'Code NAF',
'L5' => 'Secteur client',
'M5' => "Tenue de l'offre",
'N5' => 'Note Ellipro',
'O5' => 'Tarif unique/ horosaisonnalité, Arenh(%) …',
'P5' => 'Marge souhaitée POUR FLASH ',
'Q5' => 'Fournisseur actuel',
'R5' => 'Date de début de fourniture',
'S5' => 'Date de fin de fourniture',
'T5' => 'Nombre de mois à fournir',
'U5' => 'RAE',
'V5' => 'Adresse du site',
'W5' => 'Segment',
'X5' => 'Formule acheminement',
// Bloc Puissances
'Y5' => 'POINTE',
'Z5' => 'HPC',
'AA5' => 'HCH',
'AB5' => 'HPE',
'AC5' => 'HCE',
// Bloc Consommations MWh
'AD5' => 'POINTE',
'AE5' => 'HPC',
'AF5' => 'HCH',
'AG5' => 'HPE',
'AH5' => 'HCE',
'AI5' => 'CAR',
];
foreach ($labels as $cell => $text) {
// Fusion 5-6
[$col] = sscanf($cell, "%[A-Z]");
$sheet->mergeCells($col.'5:'.$col.'6');
$sheet->setCellValue($cell, $text);
}
// ---------- Styles ----------
$sheet->getStyle('A1:L4')->applyFromArray($boldCenter + $fillInfoClients + $mediumOutline);
$sheet->getStyle('M1:P4')->applyFromArray($boldCenter + $fillCotation + $mediumOutline);
$sheet->getStyle('Q1:T4')->applyFromArray($boldCenter + $fillContrats + $mediumOutline);
$sheet->getStyle('U1:AI3')->applyFromArray($boldCenter + $fillSites + $mediumOutline);
$sheet->getStyle('Y4:AC4')->applyFromArray($normalCenter + $fillSousTitreBlue + $mediumOutline);
$sheet->getStyle('AD4:AI4')->applyFromArray($normalCenter + $fillSousTitreGrn + $mediumOutline);
$sheet->getStyle('A5:AI6')->applyFromArray($boldCenter + $fillHeader2 + $thinBorder);
$sheet->getStyle('A5:X6')->applyFromArray($mediumOutline);
$sheet->getStyle('Y4:AC6')->applyFromArray($mediumOutline);
$sheet->getStyle('AD4:AI6')->applyFromArray($mediumOutline);
$i = 7;
foreach ($cotation->getCotations() as $site) {
/** @var Cotation $site */
$sheet->getStyle('C' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('E' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('U' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->setCellValue('A' . $i, $site->getName());
$sheet->setCellValue('B' . $i, $cotation->getCompanyName());
$sheet->setCellValue('C' . $i, $cotation->getSiret());
$sheet->setCellValue('D' . $i, $site->getCompanyName());
$sheet->setCellValue('E' . $i, $site->getSiret());
$sheet->setCellValue('F' . $i, $site->getFirstName() . ' ' . $site->getLastName());
$sheet->setCellValue('G' . $i, $site->getPosition());
$sheet->setCellValue('H' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
$sheet->setCellValue('I' . $i, $site->getPhone());
$sheet->setCellValue('J' . $i, $site->getEmail());
$sheet->setCellValue('K' . $i, $site->getApeCode());
$sheet->setCellValue('L' . $i, $site->getSector());
$sheet->setCellValue('M' . $i, $cotation->getTenueOffre());
$sheet->setCellValue('N' . $i, $site->getEliproNote());
$sheet->setCellValue('O' . $i, $site->getTarifType());
$sheet->setCellValue('P' . $i, $site->getDesiredMargin());
$sheet->setCellValue('Q' . $i, $site->getElectricitySupplier() ? $site->getElectricitySupplier()->getName() : "");
$sheet->setCellValue('R' . $i, ($site->getEDesiredBegin())->format('Y-m-d'));
$sheet->setCellValue('S' . $i, ($site->getEDesiredEnd())->format('Y-m-d'));
$sheet->setCellValue('T' . $i, $site->getENombreMois());
$sheet->setCellValue('U' . $i, $site->getEPdl());
$sheet->setCellValue('V' . $i, $site->getEAddress() . ' ' . $site->getEAddress2() . ' ' . $site->getEZipCode() . ' ' . $site->getECity());
$sheet->setCellValue('W' . $i, $site->getESegment());
$sheet->setCellValue('X' . $i, $site->getEFormuleAcheminement());
$sheet->setCellValue('Y' . $i, $site->getEPuissanceKvaPointe());
$sheet->setCellValue('Z' . $i, $site->getEPuissanceKvaHph());
$sheet->setCellValue('AA' . $i, $site->getEPuissanceKvaHch());
$sheet->setCellValue('AB' . $i, $site->getEPuissanceKvaHpe());
$sheet->setCellValue('AC' . $i, $site->getEPuissanceKvaHce());
$sheet->setCellValue('AD' . $i, $site->getEConsommationPointe());
$sheet->setCellValue('AE' . $i, $site->getEConsommationHph());
$sheet->setCellValue('AF' . $i, $site->getEConsommationHch());
$sheet->setCellValue('AG' . $i, $site->getEConsommationHpe());
$sheet->setCellValue('AH' . $i, $site->getEConsommationHce());
$sheet->setCellValue('AI' . $i, $site->getEConsommationPointe()+$site->getEConsommationHph()+$site->getEConsommationHch()+$site->getEConsommationHpe()+$site->getEConsommationHce());
$i++;
}
$sheet->freezePane('A7');
$sheet->setSelectedCell("A7");
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse();
$response->setCallback(function () use ($writer) {
$writer->save('php://output');
});
$filenane = "excel-elec_".$cotation->getCompanyName().'.xlsx';
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/excel-gaz", name="companies_cotations-multisites_excel-gaz")
*/
public function companiesCotationsMultisiteExcelGazAction(Request $request, EntityManagerInterface $em, KernelInterface $kernel, Company $company, CotationMultisite $cotation)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Cotation Multisite GAZ");
$sheet->getProtection()->setSheet(true);
$spreadsheet->getDefaultStyle()->getProtection()->setLocked(false);
//HEADER
// ---------- Helpers ----------
$thinBorder = [
'borders' => [
'allBorders' => ['borderStyle' => Border::BORDER_THIN],
],
];
$mediumOutline = [
'borders' => [
'outline' => ['borderStyle' => Border::BORDER_MEDIUM],
],
];
$centerWrap = [
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
'wrapText' => true,
],
];
$boldCenter = [
'font' => ['bold' => true, 'size' => 10],
] + $centerWrap;
$normalCenter = [
'font' => ['bold' => false, 'size' => 10],
] + $centerWrap;
$fill = function(string $hex) {
return [
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => ltrim($hex, '#')],
],
];
};
$fillInfoClients = $fill('#FCE4D6'); // A1:L4
$fillCotation = $fill('#E2EFDA'); // M1:O4
$fillContrats = $fill('#FFF2CC'); // P1:S4
$fillSites = $fill('#DDEBF7'); // T1:X4
$fillHeader2 = $fill('#B4C6E7'); // Lignes 5-6 (libellés colonnes)
$widths = [
'A'=>15,'B'=>15,'C'=>16,'D'=>15,'E'=>16,'F'=>16,'G'=>12,'H'=>22,'I'=>22,'J'=>14,'K'=>12,'L'=>16,
'M'=>18,'N'=>14,'O'=>24,'P'=>18,'Q'=>20,'R'=>22,'S'=>23,'T'=>15,
'U'=>24,'V'=>12,'W'=>18,'X'=>12, 'Y' => 12
];
foreach ($widths as $col => $w) {
$sheet->getColumnDimension($col)->setWidth($w);
}
$sheet->getRowDimension(1)->setRowHeight(24);
$sheet->getRowDimension(2)->setRowHeight(18);
$sheet->getRowDimension(3)->setRowHeight(18);
$sheet->getRowDimension(4)->setRowHeight(22);
$sheet->getRowDimension(5)->setRowHeight(22);
$sheet->getRowDimension(6)->setRowHeight(22);
// ---------- Groupes & fusions ----------
$sheet->mergeCells('A1:M4')->setCellValue('A1', 'Informations clients');
$sheet->mergeCells('N1:P4')->setCellValue('N1', 'Informations cotations');
$sheet->mergeCells('Q1:T4')->setCellValue('Q1', 'Informations contrats ');
$sheet->mergeCells('U1:Y4')->setCellValue('U1', 'Informations sites ');
$labels = [
'A5' => 'Nom du Site',
'B5' => 'Titulaire',
'C5' => 'SIRET Titulaire',
'D5' => 'Payeur',
'E5' => 'SIRET Payeur',
'F5' => 'Nom Prénom',
'G5' => 'Fonction',
'H5' => 'Adresse de facturation',
'I5' => 'Adresse de consommation',
'J5' => 'Téléphone',
'K5' => 'Email',
'L5' => 'Code NAF',
'M5' => 'Secteur client',
'N5' => "Tenue de l'offre",
'O5' => 'Note Ellipro',
'P5' => 'Marge souhaitée POUR FLASH ',
'Q5' => 'Fournisseur actuel',
'R5' => 'Date de début de fourniture',
'S5' => 'Date de fin de fourniture',
'T5' => 'Nombre de mois à fournir',
'U5' => 'PCE',
'V5' => 'Adresse du site',
'W5' => 'Profil',
'X5' => "Tarif d'acheminement",
'Y5' => 'CAR (Mwh)',
];
foreach ($labels as $cell => $text) {
[$col] = sscanf($cell, "%[A-Z]");
$sheet->mergeCells($col.'5:'.$col.'6');
$sheet->setCellValue($cell, $text);
}
// ---------- Styles ----------
$sheet->getStyle('A1:M4')->applyFromArray($boldCenter + $fillInfoClients + $mediumOutline);
$sheet->getStyle('N1:P4')->applyFromArray($boldCenter + $fillCotation + $mediumOutline);
$sheet->getStyle('Q1:T4')->applyFromArray($boldCenter + $fillContrats + $mediumOutline);
$sheet->getStyle('U1:Y4')->applyFromArray($boldCenter + $fillSites + $mediumOutline);
$sheet->getStyle('A5:Y6')->applyFromArray($boldCenter + $fillHeader2 + $thinBorder);
$sheet->getStyle('A5:Y6')->applyFromArray($mediumOutline);
$i = 7;
foreach ($cotation->getCotations() as $site) {
/** @var Cotation $site */
$sheet->getStyle('C' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('E' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('T' . $i)->getNumberFormat()->setFormatCode('0');
$sheet->setCellValue('A' . $i, $site->getName());
$sheet->setCellValue('B' . $i, $cotation->getCompanyName());
$sheet->setCellValue('C' . $i, $cotation->getSiret());
$sheet->setCellValue('D' . $i, $site->getCompanyName());
$sheet->setCellValue('E' . $i, $site->getSiret());
$sheet->setCellValue('F' . $i, $site->getFirstName() . ' ' . $site->getLastName());
$sheet->setCellValue('G' . $i, $site->getPosition());
$sheet->setCellValue('H' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
$sheet->setCellValue('I' . $i, $site->getGAddress() . ' ' . $site->getGAddress2() . ' ' . $site->getGZipCode() . ' ' . $site->getGCity());
$sheet->setCellValue('J' . $i, $site->getPhone());
$sheet->setCellValue('K' . $i, $site->getEmail());
$sheet->setCellValue('L' . $i, $site->getApeCode());
$sheet->setCellValue('M' . $i, $site->getSector());
$sheet->setCellValue('N' . $i, $cotation->getTenueOffre());
$sheet->setCellValue('O' . $i, $site->getEliproNote());
$sheet->setCellValue('P' . $i, $cotation->getDesiredMargin());
$sheet->setCellValue('Q' . $i, $site->getGasSupplier() ? $site->getGasSupplier()->getName() : "");
$sheet->setCellValue('R' . $i, $site->getGDesiredBegin());
$sheet->setCellValue('S' . $i, $site->getGDesiredEnd());
$sheet->setCellValue('T' . $i, $site->getGNombreMois());
$sheet->setCellValue('U' . $i, $site->getGPce());
$sheet->setCellValue('V' . $i, $site->getBillingAddress() . ' ' . $site->getBillingAddress2() . ' ' . $site->getBillingZipCode() . ' ' . $site->getBillingCity());
$sheet->setCellValue('W' . $i, $site->getGProfil());
$sheet->setCellValue('X' . $i, $site->getGSegment());
$sheet->setCellValue('Y' . $i, $site->getGCarMwh());
$i++;
}
$sheet->freezePane('A7');
$sheet->setSelectedCell("A7");
$writer = new Xlsx($spreadsheet);
$response = new StreamedResponse();
$response->setCallback(function () use ($writer) {
$writer->save('php://output');
});
$filenane = "excel-gaz_".$cotation->getCompanyName().'.xlsx';
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filenane.'"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/offers", name="companies_cotations-multisites_offers")
*/
public function companiesCotationsMultisitesOffersAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$offersBySite = [];
foreach ($cotation->getCotations() as $site) {
$offers = [];
if ($cotation->getElectricity()) {
$offers = array_merge($offers, $em->getRepository(OfferElec::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
}
if ($cotation->getGas()) {
$offers = array_merge($offers, $em->getRepository(OfferGaz::class)->findBy(["cotation" => $site], ["currentOffer" => "DESC"]));
}
$offersBySite[] = [
"site" => $site,
"offers" => $offers
];
}
return $this->render("app/clients/cotations-multisites_offers.html.twig", [
"offersBySite" => $offersBySite,
"company" => $company,
"cotation" => $cotation,
]);
}
/**
* @Route("/companies/{company}/cotations-multisites/{cotation}/offers/pdf", name="companies_cotations-multisites_offers_pdf")
*/
public function companiesCotationsMultisitesOffersPdfAction(Request $request, EntityManagerInterface $em, Company $company, CotationMultisite $cotation, Pdf $knpSnappyPdf, OfferCalculatorService $offerCalculatorService)
{
if (!$cotation->getCompany() || $cotation->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$form = $this->createFormBuilder()->getForm();
if ($cotation->getElectricity()) {
$form->add("etude_solution_elec", ChoiceType::class, [
"expanded" => false,
"multiple" => false,
"choices" => [
"Prendre un prix unique composé de la totalité de ses droits d’ARENH" => "1",
"Prendre un prix unique composé d’un taux modéré de ses droits d'ARENH" => "2",
"Maintenir un prix unique composé d'un prix 100 % fixe" => "3",
"Prendre un horosaisonnalisé 100 % fixe (uniquement prix de marché)" => "4",
"Prendre un prix horosaisonnalisé composé d’un taux modéré de ses droits d'ARENH" => "5",
"Maintenir un prix horosaisonnalisé composé de la totalité de ses droits d’ARENH" => "6",
],
"label" => "Choix de la solution ELEC",
])
->add("etude_commentaire_elec", TextType::class, [
"attr" => [
"placeholder" => ""
],
"label" => "Commentaire ELEC",
"required" => false,
]);
$form["etude_solution_elec"]->setData($cotation->getEtudeSolutionElec());
$form["etude_commentaire_elec"]->setData($cotation->getEtudeCommentaireElec());
}
if ($cotation->getGas()) {
$form->add("etude_solution_gaz", ChoiceType::class, [
"expanded" => false,
"multiple" => false,
"choices" => [
"Prendre un prix variable indexé sur le PEG" => "1",
"Maintenir un prix 100 % fixe" => "2",
],
"label" => "Choix de la solution GAZ",
])
->add("etude_commentaire_gaz", TextType::class, [
"attr" => [
"placeholder" => ""
],
"label" => "Commentaire GAZ",
"required" => false,
]);
$form["etude_solution_gaz"]->setData($cotation->getEtudeSolutionGaz());
$form["etude_commentaire_gaz"]->setData($cotation->getEtudeCommentaireGaz());
}
$form->add("etude_type", ChoiceType::class, [
"expanded" => false,
"multiple" => false,
"choices" => [
"Site par site" => "1",
"Globale" => "2",
"Globale + Site par site" => "3",
],
"label" => "Choix du type d'étude",
]);
$sitesChoices = [
//"Tous" => "ALL",
];
foreach ($cotation->getCotations() as $site) {
$sitesChoices[$site->getName()] = $site->getId();
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$offersElec = [];
$offersGas = [];
$cotationSite = [];
$supplierForSite = [
'elec' => [],
'gas' => [],
'global' => [
'consommationEstimation' => []
]
];
foreach ($sitesChoices as $siteName => $site) {
$cotationSiteElement = $em->getRepository(Cotation::class)->find($site);
if ($cotationSiteElement->getCotationMultisite() != $cotation) {
throw new BadRequestHttpException();
}
if ($cotationSiteElement->getElectricity()) {
$cotationSiteElement->setEtudeSolutionElec($form["etude_solution_elec"]->getData());
$cotationSiteElement->setEtudeCommentaireElec($form["etude_commentaire_elec"]->getData());
}
if ($cotationSiteElement->getGas()) {
$cotationSiteElement->setEtudeSolutionGaz($form["etude_solution_gaz"]->getData());
$cotationSiteElement->setEtudeCommentaireGaz($form["etude_commentaire_gaz"]->getData());
}
$em->flush();
$offerElecItem = $em->getRepository(OfferElec::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
$offersElec[$siteName] = $offerElecItem;
$offerGasItem = $em->getRepository(OfferGaz::class)->findBy(["cotation" => $cotationSiteElement, "displayed" => true], ["currentOffer" => "DESC"]);
$offersGas[$siteName] = $offerGasItem;
//Create array with elec and gas key for supplier choice in a site or multiple site
foreach ($offersElec[$siteName] as $offer) {
$supplierName = $cotationSiteElement->getPreselectedOfferElec()?->getSupplier()->getName();
if (isset($supplierName)) {
//Re-create variable calculated in front twig in past
if ($offer->getCurrentOffer()) {
$supplierForSite['elec'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcElec($offer);
}
//Re-create variable calculated in front twig in past
if ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offer->getId()) {
$supplierForSite['elec'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcElec($offer);
}
// Get supplier infos to display in twig template like logo, name and description
$supplierForSite['elec'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferElec()->getSupplier();
}
}
//Create array with elec and gas key for supplier choice in a site or multiple site
foreach ($offersGas[$siteName] as $offer) {
$supplierName = $cotationSiteElement->getPreselectedOfferGaz()?->getSupplier()->getName();
if (isset($supplierName)) {
//Re-create variable calculated in front twig in past
if ($offer->getCurrentOffer()) {
$supplierForSite['gas'][$supplierName]['offer'][$siteName]['actualOffer'] = $offerCalculatorService->calcGaz($offer);
}
//Re-create variable calculated in front twig in past
if ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offer->getId()) {
$supplierForSite['gas'][$supplierName]['offer'][$siteName]['currentOffer'] = $offerCalculatorService->calcGaz($offer);
}
// Get supplier infos to display in twig template like logo, name and description
$supplierForSite['gas'][$supplierName]['supplierInfos'] = $cotationSiteElement->getPreselectedOfferGaz()->getSupplier();
}
}
$cotationSite[$siteName] = $cotationSiteElement;
foreach ($offerElecItem as $offerItem) {
$offerCalculated = $offerCalculatorService->calcElec($offerItem);
$keyGlobalResult = [
'id',
'htt_2024',
'htt_2025',
'htt_2026',
'htt_2027',
'htt_2028',
'htt_2029',
'ach_taxes_per_year',
'moy_month',
'total_ttc',
'total_htt',
'subscription',
'capacite',
'cee',
'other_tax',
'budget_before_ach',
'acheminement',
'cta',
'cspe',
'cspe_index',
'total_ttc',
];
if ($offerItem->getCurrentOffer()) {
$type = 'actualOffer';
} elseif ($cotationSiteElement->getPreselectedOfferElec()?->getId() === $offerItem->getId()) {
$type = 'currentOffer';
}
if (isset($type)) {
foreach ($keyGlobalResult as $key) {
if (!isset($supplierForSite['global'][$type][$key])) {
$supplierForSite['global'][$type][$key] = 0;
}
$supplierForSite['global'][$type][$key] += $offerCalculated[$key];
}
if ($type === 'actualOffer') {
$consommationKeyArray = [
'carAdditional',
'carAverage',
'kvaAdditional',
'kvaAverage'
];
$consommationSubKeyArray = [
'pointe',
'hph',
'hch',
'hpe',
'hce',
];
foreach ($consommationKeyArray as $consommationKey) {
if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
$supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
}
foreach ($consommationSubKeyArray as $consommationSubKey) {
if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
$supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
}
}
}
$supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] += $cotationSiteElement->getEConsommationPointe();
$supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] += $cotationSiteElement->getEConsommationHph();
$supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] += $cotationSiteElement->getEConsommationHch();
$supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] += $cotationSiteElement->getEConsommationHpe();
$supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] += $cotationSiteElement->getEConsommationHce();
$supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] += $cotationSiteElement->getEPuissanceKvaPointe();
$supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] += $cotationSiteElement->getEPuissanceKvaHph();
$supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] += $cotationSiteElement->getEPuissanceKvaHch();
$supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] += $cotationSiteElement->getEPuissanceKvaHpe();
$supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] += $cotationSiteElement->getEPuissanceKvaHce();
}
$offerAnalysisAndDetailsKeyArray = [
'pointe_price',
'base_price',
'hp_price',
'hc_price',
'hph_price',
'hch_price',
'hpe_price',
'hce_price',
];
foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
$supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
}
$supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
}
}
unset($type);
}
}
foreach ($offerGasItem as $offerItem) {
$offerCalculated = $offerCalculatorService->calcGaz($offerItem);
$keyGlobalResult = [
'id',
'htt_2024',
'htt_2025',
'htt_2026',
'htt_2027',
'htt_2028',
'htt_2029',
'ach_taxes_per_year',
'moy_month',
'total_ttc',
'total_htt',
'subscription',
'cee',
'other_tax',
'budget_before_ach',
'acheminement',
'cta',
'total_ttc',
'fourniture',
'budget_fourniture',
];
if ($offerItem->getCurrentOffer()) {
$type = 'actualOffer';
} elseif ($cotationSiteElement->getPreselectedOfferGaz()?->getId() === $offerItem->getId()) {
$type = 'currentOffer';
}
if (isset($type)) {
foreach ($keyGlobalResult as $key) {
if (!isset($supplierForSite['global'][$type][$key])) {
$supplierForSite['global'][$type][$key] = 0;
}
$supplierForSite['global'][$type][$key] += $offerCalculated[$key];
}
if ($type === 'actualOffer') {
$consommationKeyArray = [
'carAdditional',
'carAverage',
];
$consommationSubKeyArray = [
'total'
];
foreach ($consommationKeyArray as $consommationKey) {
if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey])) {
$supplierForSite['global']['consommationEstimation'][$consommationKey] = [];
}
foreach ($consommationSubKeyArray as $consommationSubKey) {
if (!isset($supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey])) {
$supplierForSite['global']['consommationEstimation'][$consommationKey][$consommationSubKey] = 0;
}
}
}
$supplierForSite['global']['consommationEstimation']['carAdditional']['total'] += $cotationSiteElement->getGCarMwh();
}
$offerAnalysisAndDetailsKeyArray = [
'fourniture',
'budget_fourniture',
];
foreach ($offerAnalysisAndDetailsKeyArray as $offerAnalysisAndDetailsKey) {
if (isset($offerCalculated[$offerAnalysisAndDetailsKey])) {
if (!isset($supplierForSite['global'][$type][$offerAnalysisAndDetailsKey])) {
$supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] = 0;
}
$supplierForSite['global'][$type][$offerAnalysisAndDetailsKey] += ($offerCalculated[$offerAnalysisAndDetailsKey] / count($sitesChoices));
}
}
unset($type);
}
}
}
if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['total'])) {
$supplierForSite['global']['consommationEstimation']['carAverage']['total'] = $supplierForSite['global']['consommationEstimation']['carAdditional']['total'] / count($sitesChoices);
}
$roundPrecision = 3;
if (isset($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'])) {
$supplierForSite['global']['consommationEstimation']['carAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['carAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hph'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['carAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hch'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['carAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['carAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['carAdditional']['hce'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['kvaAverage']['pointe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['pointe'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['kvaAverage']['hph'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hph'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['kvaAverage']['hch'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hch'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['kvaAverage']['hpe'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hpe'] / count($sitesChoices), $roundPrecision);
$supplierForSite['global']['consommationEstimation']['kvaAverage']['hce'] = round($supplierForSite['global']['consommationEstimation']['kvaAdditional']['hce'] / count($sitesChoices), $roundPrecision);
}
$html = $this->renderView('app/pdf/presentation-budget/section1.html.twig', [
"offersElec" => $offersElec,
"offersGas" => $offersGas,
'cotation' => $cotationSite,
'multisite' => true,
'array_site' => $sitesChoices,
'supplierChoiceForMultiSite' => $supplierForSite,
"etude_type" => $form['etude_type']->getData() ?? 0
]);
$pdf = $knpSnappyPdf->getOutputFromHtml($html, array(
'orientation' => 'landscape',
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'page-height' => 340,
'page-width' => 200,
'encoding' => 'utf-8',
'images' => true,
'cookie' => array(),
'dpi' => 300,
'enable-external-links' => true,
'enable-internal-links' => true,
'margin-bottom' => 0
));
return new Response($pdf,200,array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="Flash-Presentation_budget.pdf"'
));
/*
return new PdfResponse(
$knpSnappyPdf->getOutputFromHtml($html),
'Flash-Presentation_budget.pdf'
);
*/
}
return $this->render("app/clients/cotation_offers_pdf.html.twig", [
"form" => $form->createView(),
"cotation" => $cotation,
"multisite" => true,
]);
}
/**
* @Route("/companies/{company}/contracts", name="companies_contracts")
*/
public function companiesContractsAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$contracts = $em->getRepository(Contract::class)->findBy(["company" => $company], ["expiryDate" => "DESC"]);
return $this->render("app/clients/contracts.html.twig", [
"company" => $company,
"contracts" => $contracts,
]);
}
/**
* @Route("/companies/{company}/contracts/add", name="companies_contracts_add")
*/
public function companiesContractsAddAction(Request $request, EntityManagerInterface $em, Company $company)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
$contract = new Contract();
$contract->setCompany($company);
$form = $this->createForm(ContractType::class, $contract);
$form->add('contractType', EntityType::class, [
'class' => \App\Entity\ContractType::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('t')
->where('t.active = TRUE')
->orderBy('t.label', 'ASC');
},
'choice_label' => 'label',
'label' => 'Type de contrat',
'required' => true,
'mapped' => false,
]);
$form["sepaIban"]->setData($company->getSepaIban());
$form["sepaBic"]->setData($company->getSepaBic());
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$contract->setManager($this->getUser()->getManager());
$em->persist($contract);
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setFile($fileName);
$em->flush();
}
}
$otherFile = $form['otherFile']->getData();
if ($otherFile) {
$extension = $otherFile->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
$otherFile->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setOtherFile($fileName);
$em->flush();
}
}
$rib = $form['ribFile']->getData();
if ($rib) {
$extension = $rib->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$rib->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setRibFile($fileName);
$em->flush();
}
}
if ($form['contractType']->getData()) {
switch ($form['contractType']->getData()->getId()) {
case 1:
$contract->setGas(true);
break;
case 2:
$contract->setElectricity(true);
break;
case 3:
//$contract->setGas(true);
//$contract->setElectricity(true);
break;
case 4:
$contract->setEngiePro(true);
break;
case 5:
$contract->setTelecom(true);
break;
case 6:
$contract->setPhotovoltaique(true);
break;
}
$em->flush();
}
if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
$contract->setSignDate(new \DateTime('now'));
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "Contrat ajouté avec succès");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId(), "creation" => 1]);
}
return $this->render("app/clients/contracts_form.html.twig", [
"form" => $form->createView(),
"contract" => $contract,
"title" => "Ajouter un contrat",
]);
}
/**
* @Route("/companies/{company}/contracts/{contract}/edit", name="companies_contracts_edit")
*/
public function companiesContractsEditAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, YousignService $yousignService)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($contract->getManager()->getId() != $this->getUser()->getManager()->getId() && !$contract->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (isset($_GET["proof"]) && $contract->getProcedureYousignId()) {
$zipBase64 = $yousignService->getProcedureProof($contract->getProcedureYousignId());
if ($zipBase64) {
$zip = base64_decode($zipBase64);
$response = new Response($zip);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
$response->headers->set('Content-length', strlen($zip));
return $response;
}
}
if (isset($_GET["proof-other"]) && $contract->getOtherFileProcedureYousignId()) {
$zipBase64 = $yousignService->getProcedureProof($contract->getOtherFileProcedureYousignId());
if ($zipBase64) {
$zip = base64_decode($zipBase64);
$response = new Response($zip);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment;filename="mandat_de_preuve.zip"');
$response->headers->set('Content-length', strlen($zip));
return $response;
}
}
$form = $this->createForm(ContractType::class, $contract);
if ($this->getUser()->getManager()->getAdmin()) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true');
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => true,
]);
$form["manager"]->setData($contract->getManager());
} elseif ($contract->getManager()->isSupervisedBy($this->getUser()->getManager()) || ($contract->getManager() === $this->getUser()->getManager())) {
$form->add('manager', EntityType::class, [
"label" => "Commercial associé",
'class' => Manager::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('m')
->leftJoin("m.account", "a")
->where('a.enabled = true')
->andWhere('(:manager MEMBER OF m.supervisors OR :manager = m)')
->setParameter('manager', $this->getUser()->getManager());
},
'choice_label' => 'fullName',
'attr' => [
"data-control" => "select2",
],
"required" => false,
"mapped" => true,
]);
$form["manager"]->setData($contract->getManager());
}
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setFile($fileName);
$em->flush();
}
}
$otherFile = $form['otherFile']->getData();
if ($otherFile) {
$extension = $otherFile->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . $otherFile->getClientOriginalName();
$otherFile->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setOtherFile($fileName);
$em->flush();
}
}
$rib = $form['ribFile']->getData();
if ($rib) {
$extension = $rib->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.' . $extension;
$rib->move(
$this->getParameter('documents_contracts_directory'),
$fileName
);
$contract->setRibFile($fileName);
$em->flush();
}
}
if (!$contract->getSignDate() && $contract->getState() && $contract->getState()->getId() == 4) {
$contract->setSignDate(new \DateTime('now'));
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "Contrat modifié avec succès");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
if ($request->query->get("backFromDocusign") && $request->query->get("event") == "Send") {
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
}
$signMember = $this->getContractSignMember($contract);
$creationWorkflow = $request->query->get('creation') === '1';
return $this->render("app/clients/contracts_form.html.twig", [
"form" => $form->createView(),
"contract" => $contract,
"title" => "Modifier un contrat",
"signMember" => $signMember,
'creation_workflow' => $creationWorkflow,
]);
}
/**
* @Route("/companies/{company}/contracts/{contract}/resiliation-email", name="companies_contracts_resiliation-email")
*/
public function companiesContractsResiliationEmailAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, SendEmailService $sendEmailService, Pdf $knpSnappyPdf)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (isset($_POST["file_elec_content"])) {
$contract->setResiliationElecEmailContent($_POST["file_elec_content"]);
$em->flush();
// Génération du PDF
$pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_elec_content"]);
// Email
$content = <<<EOD
Bonjour,<br/>
<br/>
Veuillez trouver ci-joint votre courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat de fourniture d'électricité actuel.<br/>
<br/>
<i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur Electricité",
$contract->getCompany()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur",
"content" => $content
],
'resiliation@flash-consulting.fr',
null,
[
[
"content" => $pdf,
"name" => "courrier_de_changement_fournisseur_elec.pdf",
"contentType" => "application/pdf"
]
]
);
$contract->setResiliationElecEmailSendDate(new \DateTime('now'));
$em->flush();
} elseif (isset($_POST["file_gas_content"])) {
$contract->setResiliationGasEmailContent($_POST["file_gas_content"]);
$em->flush();
// Génération du PDF
$pdf = $knpSnappyPdf->getOutputFromHtml($_POST["file_gas_content"]);
// Email
$content = <<<EOD
Bonjour,<br/>
<br/>
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/>
<br/>
<i>Ce courrier est conforme aux conditions de votre fournisseur d'énergie.</i><br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur Gaz",
$contract->getCompany()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur",
"content" => $content
],
'resiliation@flash-consulting.fr',
null,
[
[
"content" => $pdf,
"name" => "courrier_de_changement_fournisseur_gaz.pdf",
"contentType" => "application/pdf"
]
]
);
$contract->setResiliationGasEmailSendDate(new \DateTime('now'));
$em->flush();
} else {
$content = <<<EOD
Bonjour,<br/>
<br/>
Veuillez trouver ci-joint un modèle de courrier de changement de fournisseur à signer et à tamponner pour mettre fin à votre contrat actuel.<br/>
<br/>
<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/>
<br/>
De plus, nous avons également inclus <b>un guide</b> (voir pièces jointes) pour remplir le formulaire correctement.<br/>
<br/>
Nous vous recommandons d'envoyer cette lettre au plus vite <b>par courrier recommandé avec accusé de réception</b>.<br/>
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/>
<br/>
Si vous avez la moindre question ou besoin, n'hésitez pas à nous contacter. Nous vous remercions de votre confiance.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Lettre de changement de fournisseur et son guide",
$contract->getCompany()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Lettre de changement de fournisseur et son guide",
"content" => $content
],
'resiliation@flash-consulting.fr',
[
$this->getParameter('assets_directory')."Lettre de resiliation.docx",
$this->getParameter('assets_directory')."Guide pour remplir sa lettre de resiliation.docx",
]
);
if (isset($_GET["elec"])) {
$contract->setResiliationElecEmailSendDate(new \DateTime('now'));
}
if (isset($_GET["gas"])) {
$contract->setResiliationGasEmailSendDate(new \DateTime('now'));
}
$em->flush();
}
$this->get("session")->getFlashBag()->add("success", "L'email de changement de fournisseur a bien été envoyé");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
/**
* @Route("/companies/{company}/contracts/{contract}/delete", name="companies_contracts_delete")
*/
public function companiesContractsDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Admin only");
}
$contract->setOfferElec(null);
$contract->setOfferGaz(null);
$em->flush();
$em->remove($contract);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Contrat supprimée");
return $this->redirectToRoute("manager_contracts", ["pro" => 1]);
}
/**
* @Route("/companies/{company}/contracts/{contract}/file", name="companies_contracts_file")
*/
public function companiesContractsFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getFile()) {
return $this->getContractFile($contract, $request->get('mergeRib'));
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/contracts/{contract}/other-file", name="companies_contracts_other_file")
*/
public function companiesContractsOtherFileAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getOtherFile()) {
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/contracts/{contract}/rib", name="companies_contracts_rib")
*/
public function companiesContractsRibAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($contract->getRibFile()) {
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
return $this->file($filePath, $contract->getRibFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/contracts/{contract}/rib-delete", name="companies_contracts_rib-delete")
*/
public function companiesContractsRibDeleteAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$contract->setRibFile(null);
$em->flush();
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
/**
* @Route("/companies/{company}/contracts/{contract}/sign", name="companies_contracts_sign")
*/
public function companiesContractsSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (!$contract->getFile()) {
$this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
} else if (!$contract->getState() || $contract->getState()->getId() != 3) {
$this->get("session")->getFlashBag()->add("danger", "Le statut du contrat doit être: Contrat en attente de signature");
return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
} else {
return $this->sendContractFileToDocusign($contract, $docusignService, $em, true);
//return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
throw new NotFoundHttpException();
}
/**
* @Route("/companies/{company}/contracts/{contract}/other-file/sign", name="companies_contracts_other_file_sign")
*/
public function companiesContractsOtherFileSignAction(Request $request, EntityManagerInterface $em, Company $company, Contract $contract, DocusignService $docusignService)
{
if (!$contract->getCompany() || $contract->getCompany()->getId() != $company->getId()) {
throw new NotFoundHttpException();
}
if (!$this->getUser()->getManager()->getAdmin()) {
if ($company->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$company->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if (!$contract->getOtherFile()) {
$this->get("session")->getFlashBag()->add("danger", "Aucun fichier à envoyer pour signature.");
$this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
} else {
return $this->sendContractOtherFileToDocusign($contract, $docusignService, $em, true);
//return $this->redirectToRoute("manager_companies_contracts_edit", ["company" => $company->getId(), "contract" => $contract->getId()]);
}
throw new NotFoundHttpException();
}
private function getContractFile(Contract $contract, $mergeRib)
{
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
if ($mergeRib && $contract->getRibFile()) {
$fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
if (file_exists($fileRib)) {
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile($filePath);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
$pagecount = $pdf->setSourceFile($fileRib);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
return $this->file($pdf->Output($contract->getFile(), 'I'), $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
}
return $this->file($filePath, $contract->getFile(), ResponseHeaderBag::DISPOSITION_INLINE);
}
public function sendContractFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded)
{
$fileName = $contract->getFile();
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getFile();
$signMember = $this->getContractSignMember($contract);
// Création de la procédure
$procedureSign = new ProcedureSign();
if ($contract->getCompany()) {
$procedureSign->setUser($contract->getCompany()->getUser());
} else if ($contract->getUser()) {
$procedureSign->setUser($contract->getUser());
}
$procedureSign->setFirstName($signMember["firstName"]);
$procedureSign->setLastName($signMember["lastName"]);
$procedureSign->setEmail($signMember["email"]);
$procedureSign->setPhone($signMember["phone"]);
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "contract.file",
"id" => $contract->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
/*
$fileCertificate = $this->getParameter('documents_fc_certificate');
if (file_exists($fileCertificate)) {
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile($filePath);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
// add RIB
if ($contract->getRibFile()) {
$fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
if (file_exists($fileRib)) {
$pagecount = $pdf->setSourceFile($fileRib);
for ($i = 0; $i < $pagecount; $i++) {
$pdf->AddPage();
$tplidx = $pdf->importPage($i + 1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
}
}
// add certificate
$pagecount = $pdf->setSourceFile($fileCertificate);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
$pdf->Output($filePath, 'F');
}
*/
// Lancement de la signature
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
try {
if ($embedded) {
$response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
$procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
$em->flush();
return $this->redirect($response["url"]);
} else {
$response = $docusignService->sendFile($accessToken, $procedureSign);
$procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du contrat a été envoyé au client.");
return true;
}
} catch (ApiException $e) {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
return false;
}
public function sendContractOtherFileToDocusign(Contract $contract, DocusignService $docusignService, EntityManagerInterface $em, $embedded=false)
{
$fileName = $contract->getOtherFile();
$filePath = $this->getParameter('documents_contracts_directory') . $contract->getOtherFile();
$signMember = $this->getContractSignMember($contract);
// Création de la procédure
$procedureSign = new ProcedureSign();
if ($contract->getCompany()) {
$procedureSign->setUser($contract->getCompany()->getUser());
} else if ($contract->getUser()) {
$procedureSign->setUser($contract->getUser());
}
$procedureSign->setFirstName($signMember["firstName"]);
$procedureSign->setLastName($signMember["lastName"]);
$procedureSign->setEmail($signMember["email"]);
$procedureSign->setPhone($signMember["phone"]);
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "contract.other-file",
"id" => $contract->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
// Création de la position
/*
$yousignPosition = new YousignPosition();
$yousignPosition->setPosition("209,16,395,180");
$yousignPosition->setReason("Signé par ".$company->getUser()->getFirstName().' '.$company->getUser()->getLastName());
$fileCertificate = $this->getParameter('documents_fc_certificate');
if (file_exists($fileCertificate)) {
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile($filePath);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
// add RIB
if ($contract->getRibFile()) {
$fileRib = $this->getParameter('documents_contracts_directory') . $contract->getRibFile();
if (file_exists($fileRib)) {
$pagecount = $pdf->setSourceFile($fileRib);
for ($i = 0; $i < $pagecount; $i++) {
$pdf->AddPage();
$tplidx = $pdf->importPage($i + 1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
}
}
// add certificate
$pagecount = $pdf->setSourceFile($fileCertificate);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx);
}
$pdf->Output($filePath, 'F');
}
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile($filePath);
$yousignPosition->setPage($pagecount);
*/
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
try {
if ($embedded) {
$response = $docusignService->getEmbeddedSending($accessToken, $procedureSign, $contract);
$procedureSign->setDocusignEnvelopeId($response["envelope_id"]);
$em->flush();
return $this->redirect($response["url"]);
} else {
$response = $docusignService->sendFile($accessToken, $procedureSign);
$procedureSign->setDocusignEnvelopeId($response->getEnvelopeId());
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Le mail pour la signature électronique du fichier a été envoyé au client.");
return true;
}
} catch (ApiException $e) {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Erreur lors de l'envoi de la signature électronique");
}
return false;
}
private function getContractSignMember(Contract $contrat)
{
if ($contrat->getCompany()) {
$firstName = $contrat->getCompany()->getUser()->getFirstName();
$lastName = $contrat->getCompany()->getUser()->getLastName();
$email = $contrat->getCompany()->getUser()->getEmail();
$phone = $contrat->getCompany()->getUser()->getPhone();
if ($contrat->getOfferElec() && $contrat->getOfferElec()->getCotation()) {
$firstName = $contrat->getOfferElec()->getCotation()->getFirstName();
$lastName = $contrat->getOfferElec()->getCotation()->getLastName();
$email = $contrat->getOfferElec()->getCotation()->getEmail();
$phone = $contrat->getOfferElec()->getCotation()->getPhone();
} else if ($contrat->getOfferGaz() && $contrat->getOfferGaz()->getCotation()) {
$firstName = $contrat->getOfferGaz()->getCotation()->getFirstName();
$lastName = $contrat->getOfferGaz()->getCotation()->getLastName();
$email = $contrat->getOfferGaz()->getCotation()->getEmail();
$phone = $contrat->getOfferGaz()->getCotation()->getPhone();
}
} else if ($contrat->getUser()) {
$firstName = $contrat->getUser()->getFirstName();
$lastName = $contrat->getUser()->getLastName();
$email = $contrat->getUser()->getEmail();
$phone = $contrat->getUser()->getPhone();
} else {
$firstName = "";
$lastName = "";
$email = "contact@flash-consulting.fr";
$phone = "";
}
return [
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email,
"phone" => $phone,
];
}
/**
* @Route("/cotations", name="cotations")
*/
public function cotationsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
{
$page = $request->get("page");
if (!is_numeric($page) || $page < 1) {
$page = 1;
}
$nbByPage = 20;
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
if ($request->get("onlyInProgress")) {
if ($this->getUser()->getManager()->getAdmin()) {
$cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
} else {
$cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
}
$title = "Cotations monosites en cours";
} else {
if ($this->getUser()->getManager()->getAdmin()) {
$cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
} else {
$cotations_paginator = $em->getRepository(Cotation::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
}
$title = "Toutes les cotations monosites";
}
return $this->render("app/cotations/list.html.twig", [
"cotations_paginator" => $cotations_paginator,
"title" => $title,
]);
}
/**
* @Route("/cotations-multisites", name="cotations-multisites")
*/
public function cotationsMultisitesAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
{
$page = $request->get("page");
if (!is_numeric($page) || $page < 1) {
$page = 1;
}
$nbByPage = 20;
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
if ($request->get("onlyInProgress")) {
if ($this->getUser()->getManager()->getAdmin()) {
$cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords, true);
} else {
$cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,true, $this->getUser()->getManager());
}
$title = "Cotations multisites en cours";
} else {
if ($this->getUser()->getManager()->getAdmin()) {
$cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false);
} else {
$cotations_paginator = $em->getRepository(CotationMultisite::class)->findWithPaginator($page, $nbByPage, $paginator, $keywords,false, $this->getUser()->getManager());
}
$title = "Toutes les cotations multisites";
}
return $this->render("app/cotations-multisites/list.html.twig", [
"cotations_paginator" => $cotations_paginator,
"title" => $title,
]);
}
/**
* @Route("/contracts", name="contracts")
*/
public function contractsAction(Request $request, EntityManagerInterface $em, PaginatorInterface $paginator)
{
$page = $request->get("page");
if (!is_numeric($page) || $page < 1) {
$page = 1;
}
$nbByPage = 20;
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
if ($request->get("particulier")) {
if ($this->getUser()->getManager()->getAdmin()) {
$contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, true, false);
} else {
$contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), true, false);
}
return $this->render("app/contracts/list.html.twig", [
"contracts_paginator" => $contracts_paginator,
"title" => "Contrats particuliers",
"pro" => false,
]);
} elseif ($request->get("pro")) {
if ($this->getUser()->getManager()->getAdmin()) {
$contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, null, false, true);
} else {
$contracts_paginator = $em->getRepository(Contract::class)->searchForTermsWithPaginator($page, $nbByPage, $paginator, $keywords, $this->getUser()->getManager(), false, true);
}
return $this->render("app/contracts/list.html.twig", [
"contracts_paginator" => $contracts_paginator,
"title" => "Contrats professionnels",
"pro" => true,
]);
}
throw new NotAcceptableHttpException();
}
/**
* @Route("/roadmaps", name="roadmaps")
*/
public function roadmapsAction(Request $request, EntityManagerInterface $em)
{
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
if ($request->get("onlyOpened")) {
if ($this->getUser()->getManager()->getAdmin()) {
$roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null, true);
} else {
$roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager(), true);
}
return $this->render("app/roadmaps/list.html.twig", [
"roadmaps" => $roadmaps,
"title" => "Feuilles de routes en cours",
]);
} else {
if ($this->getUser()->getManager()->getAdmin()) {
$roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, null);
} else {
$roadmaps = $em->getRepository(Roadmap::class)->searchForTerms($keywords, $this->getUser()->getManager());
}
return $this->render("app/roadmaps/list.html.twig", [
"roadmaps" => $roadmaps,
"title" => "Feuilles de routes",
]);
}
}
/**
* @Route("/roadmaps/add", name="roadmaps_add")
*/
public function roadmapsAddAction(Request $request, EntityManagerInterface $em)
{
$roadmap = new Roadmap();
$form = $this->createForm(RoadmapType::class, $roadmap);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$roadmap->setCreationDate(new \DateTime("now"));
$roadmap->setManager($this->getUser()->getManager());
$em->persist($roadmap);
$em->flush();
$em->refresh($roadmap);
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$roadmap->setFilePath($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Feuille de route ajoutée");
return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
}
return $this->render("app/roadmaps/form.html.twig", [
"form" => $form->createView(),
"title" => "Ajouter une feuille de route",
"roadmap" => null,
]);
}
/**
* @Route("/roadmaps/{id}/edit", name="roadmaps_edit")
*/
public function roadmapEditAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($roadmap->getArchived()) {
throw new BadRequestHttpException("Archived");
}
$form = $this->createForm(RoadmapType::class, $roadmap);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$fileName = 'fdr_' . $roadmap->getId() . "_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$roadmap->setFilePath($fileName);
$em->flush();
}
}
$this->get("session")->getFlashBag()->add("success", "Feuille de route modifiée");
return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
}
return $this->render("app/roadmaps/form.html.twig", [
"form" => $form->createView(),
"title" => "Modifier une feuille de route",
"roadmap" => $roadmap,
]);
}
/**
* @Route("/roadmaps/{id}/file", name="roadmaps_file")
*/
public function roadmapFileAction(Request $request, Roadmap $roadmap)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($roadmap->getFilePath()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $roadmap->getFilePath();
return $this->file($filePath, $roadmap->getFilePath(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/roadmaps/{id}/file-delete", name="roadmaps_file-delete")
*/
public function roadmapFileDeleteAction(Request $request, Roadmap $roadmap, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$roadmap->setFilePath(null);
$em->flush();
return $this->redirectToRoute("manager_roadmaps_edit", ["id" => $roadmap->getId()]);
}
/**
* @Route("/roadmaps/{id}/delete", name="roadmaps_delete")
*/
public function roadmapDeleteAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new UnauthorizedHttpException("Admin only");
}
$em->remove($roadmap);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Feuille de route supprimée");
return $this->redirectToRoute("manager_roadmaps", ["onlyOpened" => 1]);
}
/**
* @Route("/roadmaps/{id}/convert", name="roadmaps_convert")
*/
public function roadmapConvertAction(Roadmap $roadmap, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($roadmap->getArchived()) {
throw new BadRequestHttpException("Archived");
}
// On cherche les clients pro similaires
$keywords = explode(" ", $roadmap->getCompanyName());
$keywords[] = $roadmap->getLastName();
if ($this->getUser()->getManager()->getAdmin()) {
$users = $em->getRepository(User::class)->searchForTerms($keywords, null, false, true);
} else {
$users = $em->getRepository(User::class)->searchForTerms($keywords, $this->getUser()->getManager(), false, true);
}
return $this->render("app/roadmaps/convert.html.twig", [
"roadmap" => $roadmap,
"users" => $users,
]);
}
/**
* @Route("/roadmaps/{id}/convert/{company}", name="roadmaps_convert_to_company")
* @ParamConverter("roadmap", options={"id" = "id"})
* @ParamConverter("company", options={"id" = "company"})
*/
public function roadmapConvertUserAction(Roadmap $roadmap, Company $company, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($roadmap->getManager()->getId() != $this->getUser()->getManager()->getId() && !$roadmap->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($roadmap->getArchived()) {
throw new BadRequestHttpException("Archived");
}
$roadmap->setArchived(true);
$roadmap->setCompany($company);
if ($roadmap->getContractType()->getId() == 4) {
// Engie PRO
$this->roadmapEngieProToContract(
$roadmap,
$company,
true,
"",
null,
"",
new \DateTime('now'),
null,
"",
true,
"",
null,
"",
new \DateTime('now'),
null,
"",
$em
);
}
if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 5) {
$this->roadmapTelecomToContract(
$roadmap,
$company,
"",
"",
false,
"",
$em
);
}
if ($roadmap->getContractType() && $roadmap->getContractType()->getId() == 6) {
$this->roadmapPhotovoltaiqueToContract(
$roadmap,
$company,
"",
"",
"",
"",
"",
false,
$em
);
}
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Feuille de route convertie");
return $this->redirectToRoute("manager_roadmaps");
}
/**
* @Route("/documents", name="documents")
*/
public function documentsAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$keywords = null;
if ($request->get("search")) {
$terms = explode(" ", $request->get("search"));
if (count($terms)) {
$keywords = $terms;
}
}
$documents = $em->getRepository(Document::class)->searchForTerms($keywords);
return $this->render("app/documents/list.html.twig", [
"documents" => $documents,
]);
}
/**
* @Route("/documents/add", name="documents_add")
*/
public function documentsAddAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$document = new Document();
$form = $this->createForm(DocumentType::class, $document);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
$relativePathFile = str_replace('/', '', $relativePathFile);
$file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
$document->setPath('/uploads/documents/' . $relativePathFile);
$document->setCreationDate(new \DateTime("now"));
$document->setVisible(true);
$document->setManager($this->getUser()->getManager());
$em->persist($document);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Document ajouté");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Impossible de télécharger ce document");
}
return $this->redirectToRoute("manager_documents");
}
return $this->render("app/documents/form.html.twig", [
"form" => $form->createView(),
"title" => "Ajouter un document à la boîte à outils"
]);
}
/**
* @Route("/documents/{id}/edit", name="documents_edit")
*/
public function documentsEditAction(Document $document, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$form = $this->createForm(DocumentType::class, $document);
$form->add('creationDate', DateType::class, [
"label" => "Date de publication",
'widget' => 'single_text',
'html5' => true,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$file = $form['file']->getData();
if ($file) {
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx", "xlsx", "zip", "rar"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
} else {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$relativePathFile = str_replace(' ', '', $originalFilename) . "_" . md5(uniqid()) . "." . $extension;
$relativePathFile = str_replace('/', '', $relativePathFile);
$file->move($this->getParameter('kernel.project_dir') . '/public/uploads/documents', $relativePathFile);
$document->setPath('/uploads/documents/' . $relativePathFile);
}
}
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Document modifié");
return $this->redirectToRoute("manager_documents");
}
return $this->render("app/documents/form.html.twig", [
"form" => $form->createView(),
"title" => "Modifier un document"
]);
}
/**
* @Route("/documents/{id}/activate", name="documents_activate")
*/
public function documentsActivateAction(Document $document, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$document->setVisible(true);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Document activé");
return $this->redirectToRoute("manager_documents");
}
/**
* @Route("/documents/{id}/desactivate", name="documents_desactivate")
*/
public function documentsDesactivateAction(Document $document, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$document->setVisible(false);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Document désactivé");
return $this->redirectToRoute("manager_documents");
}
/**
* @Route("/documents/{id}/delete", name="documents_delete")
*/
public function documentsDeleteAction(Document $document, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$em->remove($document);
$em->flush();
$this->get("session")->getFlashBag()->add("success", "Document supprimé");
return $this->redirectToRoute("manager_documents");
}
/**
* @Route("/managers", name="managers")
*/
public function managersAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$accounts = $em->getRepository(Account::class)->findManagers();
return $this->render("app/managers/list.html.twig", [
"accounts" => $accounts,
]);
}
/**
* @Route("/managers/add", name="managers_add")
*/
public function managersAddAction(Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$manager = new Manager();
$form = $this->createForm(ManagerType::class, $manager);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$error = false;
$accountEmail = $form["account_email"]->getData();
if (filter_var($accountEmail, FILTER_VALIDATE_EMAIL)) {
$other_account = $em->getRepository(Account::class)->findOneBy(['email' => $accountEmail]);
if ($other_account) {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
}
} else {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
}
if (!$error) {
$em->persist($manager);
$em->flush();
$account = new Account();
$account->setEmail($accountEmail);
$account->setEnabled($form["enabled"]->getData());
$account->setManager($manager);
$salt = md5(uniqid());
$pwd = $form['password']->getData();
$account->setSalt($salt);
$enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
$account->setPassword($enc_pwd);
$account->setRegistrationDate(new \DateTime('now'));
$em->persist($account);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Utilisateur créé avec succès');
return $this->redirectToRoute('manager_managers');
}
}
return $this->render('app/managers/form.html.twig', [
'form' => $form->createView(),
'title' => "Ajouter un utilisateur",
]);
}
/**
* @Route("/managers/{id}/edit", name="managers_edit")
*/
public function managersEditAction(Account $account, Request $request, EntityManagerInterface $em, PasswordEncoder $passwordEncoder)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
if (!$account->getManager()) {
throw new BadRequestHttpException();
}
$r_email = $account->getEmail();
$form = $this->createForm(ManagerType::class, $account->getManager());
$form["account_email"]->setData($account->getEmail());
$form["enabled"]->setData($account->getEnabled());
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$error = false;
$newEmail = $form["account_email"]->getData();
if ($r_email != $newEmail) {
if (filter_var($account->getEmail(), FILTER_VALIDATE_EMAIL)) {
$other_account = $em->getRepository(Account::class)->findOneBy(['email' => $newEmail]);
if ($other_account && $other_account->getId() != $account->getId()) {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail est déjà utilisée par un autre utilisateur');
}
} else {
$error = true;
$this->get('session')->getFlashBag()->add('danger', 'Cette adresse mail n\'est pas valide');
}
}
if (!$error) {
$account->setEmail($newEmail);
$account->setEnabled($form["enabled"]->getData());
$em->flush();
if ($form['password']->getData()) {
$salt = md5(uniqid());
$pwd = $form['password']->getData();
$account->setSalt($salt);
$enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
$account->setPassword($enc_pwd);
$em->flush();
}
$this->get('session')->getFlashBag()->add('success', 'Utilisateur modifié avec succès');
return $this->redirectToRoute('manager_managers_edit', ["id" => $account->getId()]);
}
}
return $this->render('app/managers/form.html.twig', [
'form' => $form->createView(),
'title' => "Modifier un utilisateur",
]);
}
/**
* @Route("/flash-energie/notification", name="managers_flash-energie_notification")
*/
public function managersFlashEnergieNotificationAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$form = $this->createFormBuilder()
->add('title', TextType::class, [
'attr' => [
'placeholder' => 'Titre',
],
'label' => 'Titre de la notification',
'required' => true,
'mapped' => false,
])
->add('message', TextType::class, [
'attr' => [
'placeholder' => 'Message',
],
'label' => 'Message de la notification',
'required' => true,
'mapped' => false,
])
->add('sendAfter', DateTimeType::class, [
'attr' => [
'placeholder' => 'Date d\'envoi',
],
'label' => 'Date et heure d\'envoi',
'required' => false,
'mapped' => false,
])->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$title = $form['title']->getData();
$message = $form['message']->getData();
$sendAfter = $form['sendAfter']->getData();
$devices = $em->getRepository(Device::class)->findAll();
foreach ($devices as $device) {
$notification = new Notification();
$notification->setTitle($title);
$notification->setMessage($message);
$notification->setDevice($device);
if ($sendAfter) {
$notification->setSendAfter($sendAfter);
}
$em->persist($notification);
}
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'L\'envoi de la notification a bien été programmé');
}
return $this->render('app/flash-energie/notifications/form.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/flash-energie/offers-individual", name="managers_flash-energie_offers-individual")
*/
public function managersFlashEnergieOffersIndividualAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$form = $this->createFormBuilder()
->add('emplacement1', EntityType::class, [
"class" => OfferIndividual::class,
"label" => "Choix 1",
"required" => false,
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('o');
$qb->where('o.type = \'ELEC\'');
return $qb;
},
'choice_label' => function($offerInd) {
return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
},
])
->add('emplacement2', EntityType::class, [
"class" => OfferIndividual::class,
"label" => "Choix 2",
"required" => false,
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('o');
$qb->where('o.type = \'ELEC\'');
return $qb;
},
'choice_label' => function($offerInd) {
return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
},
])
->add('emplacement3', EntityType::class, [
"class" => OfferIndividual::class,
"label" => "Choix 3",
"required" => false,
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('o');
$qb->where('o.type = \'ELEC\'');
return $qb;
},
'choice_label' => function($offerInd) {
return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
},
])
->add('emplacement4', EntityType::class, [
"class" => OfferIndividual::class,
"label" => "Choix 4",
"required" => false,
'query_builder' => function (EntityRepository $er) {
$qb = $er->createQueryBuilder('o');
$qb->where('o.type = \'ELEC\'');
return $qb;
},
'choice_label' => function($offerInd) {
return $offerInd->getSupplier()->getName().' - '.$offerInd->getBaseline();
},
])
->getForm();
$form['emplacement1']->setData($this->findOfferIndividuelByEmplacement("1", $em));
$form['emplacement2']->setData($this->findOfferIndividuelByEmplacement("2", $em));
$form['emplacement3']->setData($this->findOfferIndividuelByEmplacement("3", $em));
$form['emplacement4']->setData($this->findOfferIndividuelByEmplacement("4", $em));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$emplacement1 = $form['emplacement1']->getData();
$this->setOfferIndividualEmplacement($emplacement1, "1", $em);
$emplacement2 = $form['emplacement2']->getData();
$this->setOfferIndividualEmplacement($emplacement2, "2", $em);
$emplacement3 = $form['emplacement3']->getData();
$this->setOfferIndividualEmplacement($emplacement3, "3", $em);
$emplacement4 = $form['emplacement4']->getData();
$this->setOfferIndividualEmplacement($emplacement4, "4", $em);
}
$offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
$offersGaz = $em->getRepository(OfferIndividual::class)->findBy(["type" => "GAZ"]);
$offersDual = $em->getRepository(OfferIndividual::class)->findBy(["type" => "DUAL"]);
return $this->render('app/flash-energie/offers-individual/list.html.twig', [
'offersElec' => $offersElec,
'offersGaz' => $offersGaz,
'offersDual' => $offersDual,
'form' => $form->createView(),
]);
}
private function setOfferIndividualEmplacement(?OfferIndividual $offerIndividual, ?string $emplacement, EntityManagerInterface $em): void
{
$offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
foreach ($offersElec as $offer) {
$emplacements = explode(';', $offer->getEmplacements());
if ($offerIndividual) {
if ($offer->getId() == $offerIndividual->getId()) {
if (!in_array($emplacement, $emplacements)) {
$emplacements[] = $emplacement;
}
} else {
if (in_array($emplacement, $emplacements)) {
$emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
return $value !== $emplacement;
});
$emplacements = array_values($emplacements);
}
}
} else {
if (in_array($emplacement, $emplacements)) {
$emplacements = array_filter($emplacements, function ($value) use ($emplacement) {
return $value !== $emplacement;
});
$emplacements = array_values($emplacements);
}
}
$offer->setEmplacements(implode(";", $emplacements));
}
$em->flush();
}
private function findOfferIndividuelByEmplacement(string $emplacement, EntityManagerInterface $em)
{
$offersElec = $em->getRepository(OfferIndividual::class)->findBy(["type" => "ELEC"]);
foreach ($offersElec as $offer) {
$emplacements = explode(';', $offer->getEmplacements());
if (in_array($emplacement, $emplacements)) {
return $offer;
}
}
return null;
}
/**
* @Route("/flash-energie/offers-individual/add", name="managers_flash-energie_offers-individual_add")
*/
public function managersFlashEnergieOffersIndividualAddAction(Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$offer = new OfferIndividual();
$form = $this->createForm(OfferIndividualType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$offer->setCreationDate(new \DateTime('now'));
$em->persist($offer);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Offre ajoutée avec succès');
return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
}
return $this->render('app/flash-energie/offers-individual/form.html.twig', [
'offer' => $offer,
'form' => $form->createView(),
]);
}
/**
* @Route("/flash-energie/offers-individual/{id}/edit", name="managers_flash-energie_offers-individual_edit")
*/
public function managersFlashEnergieOffersIndividualEditAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$form = $this->createForm(OfferIndividualType::class, $offer);
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Offre modifiée avec succès');
return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
}
return $this->render('app/flash-energie/offers-individual/form.html.twig', [
'offer' => $offer,
'form' => $form->createView(),
]);
}
/**
* @Route("/flash-energie/offers-individual/{id}/active", name="managers_flash-energie_offers-individual_active")
*/
public function managersFlashEnergieOffersIndividualActiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$offersByType = $em->getRepository(OfferIndividual::class)->findBy(["type" => $offer->getType()]);
foreach ($offersByType as $offer2) {
$offer2->setActive(false);
}
$offer->setActive(true);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Offre activée avec succès');
return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
}
/**
* @Route("/flash-energie/offers-individual/{id}/deactive", name="managers_flash-energie_offers-individual_deactive")
*/
public function managersFlashEnergieOffersIndividualDeactiveAction(OfferIndividual $offer, Request $request, EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$offer->setActive(false);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Offre désactivée avec succès');
return $this->redirectToRoute("manager_managers_flash-energie_offers-individual");
}
/**
* @Route("/docusign/connexion-api", name="managers_docusign_connexion-api")
*/
public function managersDocusignConnexionApiAction(Request $request, DocusignService $docusignService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$connected = false;
$accessToken = $docusignService->getAccessToken();
if ($accessToken) {
$connected = true;
}
$form = $this->createFormBuilder()
->add("email", TextType::class, [
'label' => "Adresse e-mail",
'required' => true,
])
->add("file", FileType::class, [
'label' => "Fichier à signer",
'required' => true,
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($accessToken) {
try {
$file = $form->get("file")->getData();
$procedureSign = new ProcedureSign();
$procedureSign->setFirstName("Test");
$procedureSign->setLastName("Flash");
$procedureSign->setEmail($form->get("email")->getData());
$procedureSign->setPhone("0600000000");
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($file->getClientOriginalName());
$procedureSign->setFilePath($file->getPathname());
$response = $docusignService->sendFile($accessToken, $procedureSign);
$this->get('session')->getFlashBag()->add('success', 'Document envoyé pour signature, réf: '.$response->getEnvelopeId());
} catch (ApiException $e) {
$this->get('session')->getFlashBag()->add('danger', 'L\'envoi a echoué');
var_dump($e);
}
}
}
return $this->render('app/docusign/connexion-api.html.twig', [
"connected" => $connected,
"authorizationURL" => $docusignService->getAuthorizationURL(),
"form" => $form->createView(),
]);
}
/**
* @Route("/actions", name="actions")
*/
public function managersActionsAction()
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
return $this->render('app/actions/index.html.twig', [
]);
}
/**
* @Route("/actions/affect-unaffected-cotations", name="actions_affect-unaffected-cotations")
*/
public function managersActionsAffectUnaffectedCotationsAction(EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$unaffectedCotations = $em->getRepository(Cotation::class)->findBy(["manager" => null]);
$affected = 0;
foreach ($unaffectedCotations as $cotation) {
if ($cotation->getCompany() && $cotation->getCompany()->getUser() && $cotation->getCompany()->getUser()->getManager()) {
$cotation->setManager($cotation->getCompany()->getUser()->getManager());
$affected++;
}
}
$em->flush();
$this->get('session')->getFlashBag()->add('success', $affected.' cotation(s) affectée(s).');
return $this->redirectToRoute('manager_actions');
}
/**
* @Route("/actions/affect-unaffected-contracts", name="actions_affect-unaffected-contracts")
*/
public function managersActionsAffectUnaffectedContractsAction(EntityManagerInterface $em)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$unaffectedContracts = $em->getRepository(Contract::class)->findBy(["manager" => null]);
$affected = 0;
foreach ($unaffectedContracts as $contract) {
if ($contract->getCompany() && $contract->getCompany()->getUser() && $contract->getCompany()->getUser()->getManager()) {
$contract->setManager($contract->getCompany()->getUser()->getManager());
$affected++;
}
}
$em->flush();
$this->get('session')->getFlashBag()->add('success', $affected.' contrat(s) affecté(s).');
return $this->redirectToRoute('manager_actions');
}
/**
* @Route("/cotation-document/{id}/file", name="cotation-document_file")
*/
public function cotationDocumentFileAction(Request $request, EntityManagerInterface $em, CotationDocument $cotationDocument)
{
if (!$this->getUser()->getManager()->getAdmin()) {
if ($cotationDocument->getCotation()->getCompany()->getUser()->getManager()->getId() != $this->getUser()->getManager()->getId() && !$cotationDocument->getCotation()->getCompany()->getUser()->getManager()->isSupervisedBy($this->getUser()->getManager())) {
throw new NotFoundHttpException();
}
}
if ($cotationDocument->getPath()) {
$filePath = $this->getParameter('documents_justificatif_directory') . $cotationDocument->getPath();
return $this->file($filePath, $cotationDocument->getPath(), ResponseHeaderBag::DISPOSITION_INLINE);
}
throw new NotFoundHttpException();
}
/**
* @Route("/test-template", name="managers_test-template")
*/
public function managersTestTemplateAction(Request $request, EntityManagerInterface $em, YousignService $yousignService)
{
if (!$this->getUser()->getManager()->getAdmin()) {
throw new NotFoundHttpException();
}
$form = $this->createFormBuilder()
->add('supplier', EntityType::class, [
"class" => Supplier::class,
"label" => "Fournisseur",
"placeholder" => "Fournisseur",
"required" => true,
'mapped' => false,
])
->add('file', FileType::class, [
"label" => "Fichier",
"required" => true,
'mapped' => false,
])
->add('email', EmailType::class, [
'attr' => [
'placeholder' => 'Email',
],
"data" => "david@slapp.me",
'label' => 'Destinataire (email)',
'required' => true,
'mapped' => false,
])
->add('sepaIban', TextType::class, [
"label" => "IBAN",
"data" => "FR7611315000011234567890138",
"attr" => [
"placeholder" => "FR",
],
"required" => false,
])
->add('sepaBic', TextType::class, [
"label" => "BIC",
"data" => "INGBFR18XXX",
"attr" => [
"placeholder" => "",
],
"required" => false,
])->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && !$form->isValid()) {
$this->get('session')->getFlashBag()->add('danger', 'Le formulaire n\'est pas rempli correctement. Veuillez vérifier les champs.');
}
if ($form->isSubmitted() && $form->isValid()) {
$supplier = $form['supplier']->getData();
$file = $form['file']->getData();
$email = $form['email']->getData();
$sepaIban = $form['sepaIban']->getData();
$sepaBic = $form['sepaBic']->getData();
$extension = $file->guessExtension();
if (!$extension || !in_array($extension, ["pdf", "doc", "docx"])) {
$this->get("session")->getFlashBag()->add("danger", "Format de fichier non autorisé");
return $this->render('app/test_template.html.twig', [
'form' => $form->createView(),
]);
}
$fileName = "test-template_" . md5(uniqid()) . '.' . $extension;
$file->move(
$this->getParameter('documents_justificatif_directory'),
$fileName
);
$filePath = $this->getParameter('documents_justificatif_directory').$fileName;
$cotation = $em->getRepository(Cotation::class)->find(26);
$company = $cotation->getCompany();
// Création de la procédure
$procedureSign = new ProcedureSign();
$procedureSign->setUser($cotation->getUser());
$procedureSign->setFirstName($cotation->getFirstName());
$procedureSign->setLastName($cotation->getLastName());
$procedureSign->setEmail($email);
$procedureSign->setPhone("0604176553");
$procedureSign->setCreationDate(new \DateTime('now'));
$procedureSign->setNameFile($fileName);
$procedureSign->setFilePath($filePath);
$content = [
"type" => "cotation.test",
"id" => $cotation->getId()
];
$procedureSign->setContent(json_encode($content));
$em->persist($procedureSign);
$em->flush();
// Création de la position
$yousignPosition = new YousignPosition();
$yousignPosition->setReason("Signé par ".$cotation->getFirstName().' '.$cotation->getLastName());
$contract = new Contract();
$contract->setCompany($company);
$contract->setSepaBic($sepaBic);
$contract->setSepaIban($sepaIban);
$contract->setCity("Toulouse");
$contract->setPdlNumber("1234565432");
$contract->setElectricity(true);
$pdf = $yousignService->applyTemplate($yousignPosition, $filePath, $supplier->getCodeTemplate(), $contract);
// Lancement de la signature
/* $startSign = $yousignService->startSign($procedureSign, $yousignPosition);
if ($startSign) {
$this->get('session')->getFlashBag()->add('success', 'Top, c\'est envoyé !');
}*/
$pdf->Output($fileName,'I');
}
return $this->render('app/test_template.html.twig', [
'form' => $form->createView(),
]);
}
private function newContratForCompany(Company $company, EntityManagerInterface $em): Contract
{
$contract = new Contract();
$contract->setUser($company->getUser());
$contract->setCompany($company);
$contract->setAddress($company->getAddress());
$contract->setAddress2($company->getAddress2());
$contract->setZipCode($company->getZipCode());
$contract->setCity($company->getZipCode());
$contract->setManager($this->getUser()->getManager());
$contratStateEnAttenteClient = $em->getRepository(ContractState::class)->find(3);
$contract->setState($contratStateEnAttenteClient);
return $contract;
}
private function roadmapEngieProToContract(
Roadmap $roadmap,
Company $company,
?bool $elec,
?string $powerSubscribed,
?SituationGasElec $eSituation,
?string $eSegment,
\DateTime $eCommitmentDate,
?int $eDuree,
?string $eOptEnergieVerte,
?bool $gas,
?string $quantityConsumed,
?SituationGasElec $gSituation,
?string $gSegment,
\DateTime $gCommitmentDate,
?int $gDuree,
?string $gOptEnergieVerte,
EntityManagerInterface $em)
{
$twoContracts = ($elec && $gas && $eCommitmentDate != $gCommitmentDate);
$contract = $this->newContratForCompany($company, $em);
$contract->setEngiePro(true);
if ($elec) {
$contract->setElectricity(true);
$contract->setPdlNumber($company->getPdlNumber());
$contract->setSubscribedKvaPower($powerSubscribed);
$contract->setElectricitySituation($eSituation);
$contract->setEffectiveDate($eCommitmentDate);
if ($eDuree && $eDuree > 0) {
$expiryDate = clone $eCommitmentDate;
$expiryDate->modify('+ '.$eDuree.' years');
$contract->setExpiryDate($expiryDate);
}
$contract->setEngieProESegment($eSegment);
$contract->setEngieProEOptEnergieVerte($eOptEnergieVerte);
}
if ($gas && $twoContracts) {
$em->persist($contract);
$em->flush();
$contract = $this->newContratForCompany($company, $em);
$contract->setEngiePro(true);
$contract->setEffectiveDate($gCommitmentDate);
if ($gDuree && $gDuree > 0) {
$expiryDate = clone $gCommitmentDate;
$expiryDate->modify('+ '.$gDuree.' years');
$contract->setExpiryDate($expiryDate);
}
}
if ($gas) {
$contract->setGas(true);
$contract->setPceNumber($company->getPceNumber());
$contract->setGasSituation($gSituation);
$contract->setGasMeterReadingM3($quantityConsumed);
$contract->setEngieProGSegment($gSegment);
$contract->setEngieProGOptEnergieVerte($gOptEnergieVerte);
}
$em->persist($contract);
$em->flush();
}
private function roadmapTelecomToContract(
Roadmap $roadmap,
Company $company,
?string $offer,
?string $duration,
?bool $optionPremium,
?string $rio,
EntityManagerInterface $em)
{
$contract = $this->newContratForCompany($company, $em);
$contract->setTelecom(true);
$contract->setTelecomOffer($offer);
$contract->setTelecomDuration($duration);
$contract->setTelecomOptionPremium($optionPremium);
$contract->setTelecomRio($rio);
$em->persist($contract);
$em->flush();
}
private function roadmapPhotovoltaiqueToContract(
Roadmap $roadmap,
Company $company,
?string $buildintType,
?string $buildingYear,
?string $surface,
?string $exposition,
?string $mainMaterial,
?bool $recentWork,
EntityManagerInterface $em)
{
$contract = $this->newContratForCompany($company, $em);
$contract->setPhotovoltaique(true);
$contract->setPhotovBuildingType($buildintType);
$contract->setPhotovBuildingYear($buildingYear);
$contract->setPhotovSurface($surface);
$contract->setPhotovExposition($exposition);
$contract->setPhotovMainMaterial($mainMaterial);
$contract->setPhotovRecentWork($recentWork);
$em->persist($contract);
$em->flush();
}
}