<?php
namespace App\Controller;
use App\Entity\Account;
use App\Entity\Contract;
use App\Entity\ContractState;
use App\Entity\Cotation;
use App\Entity\CotationMultisite;
use App\Entity\CotationState;
use App\Entity\InseeNaf;
use App\Entity\OfferElec;
use App\Entity\OfferGaz;
use App\Entity\ProcedureSign;
use App\Security\PasswordEncoder;
use App\Service\DocusignService;
use App\Service\PappersService;
use App\Service\SendEmailService;
use App\Service\YousignService;
use Doctrine\ORM\EntityManagerInterface;
use PieGraph;
use PiePlot;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* Class DefaultController
* @package App\Controller
*
* @Route("/", name="default_")
*/
class DefaultController extends AbstractController
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
if ($this->getUser()) {
if ($this->isGranted("ROLE_MANAGER")) {
return $this->redirectToRoute("manager_homepage");
}
}
return $this->redirectToRoute("default_login");
}
/**
* @Route(
* path="/login",
* name="login"
* )
*
* @return Response
*/
public function loginAction(Request $request, PasswordEncoder $passwordEncoder, EventDispatcherInterface $eventDispatcher)
{
$form = $this->createFormBuilder()
->add("username", EmailType::class, [
"attr" => [
"placeholder" => "Adresse mail"
],
"label" => "Adresse mail",
])
->add("password", PasswordType::class, [
"attr" => [
"placeholder" => "Mot de passe"
],
"label" => "Mot de passe",
])->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$username = $form['username']->getData();
$password = $form['password']->getData();
$account = $this->getDoctrine()->getRepository(Account::class)->findOneBy(['email' => $username]);
if ($account) {
$isValid = $passwordEncoder->isPasswordValid($account->getPassword(), $password, $account->getSalt());
if ($isValid) {
if ($account->getEnabled()) {
$session = $this->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken($account, null, $firewall, $account->getRoles());
$this->get('security.token_storage')->setToken($token);
$session->set('_security_' . $firewall, serialize($token));
//$event = new InteractiveLoginEvent($request, $token);
//$eventDispatcher->dispatch('security.interactive_login', $event);
return $this->redirectToRoute('default_homepage');
} else {
$this->get("session")->getFlashBag()->add("danger", "Compte inactif");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Identifiant ou mot de passe incorrect");
}
} else {
$this->get("session")->getFlashBag()->add("danger", "Identifiant ou mot de passe incorrect");
}
}
return $this->render('login.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route(
* path="/logout",
* name="logout"
* )
*/
public function logoutAction()
{
$this->get('security.token_storage')->setToken(null);
$this->get('session')->invalidate();
return $this->redirectToRoute("default_login");
}
/**
* @Route(
* path="/forgot",
* name="forgot_password"
* )
*
* @param Request $request
* @return Response
*/
public function forgotPasswordAction(Request $request, SendEmailService $sendEmailService)
{
$form = $this->createFormBuilder()
->add('email', EmailType::class, array(
'attr' => array(
'placeholder' => 'Adresse mail',
),
"label" => "Adresse mail",
'required' => true,
))
->getForm();
$form->handleRequest($request);
$error = null;
if ($form->isSubmitted()) {
if ($form->isValid()) {
$data = $form->getData();
$em = $this->getDoctrine()->getManager();
$account = $em->getRepository(Account::class)->findOneBy(["email" => $data["email"]]);
if ($account) {
if ($account->getEnabled()) {
$token = hash("sha256", uniqid());
$account->setPasswordRequest($token);
$account->setPasswordRequestDate(new \DateTime('now'));
$em->flush();
$link = $this->generateUrl("default_reset_password", ["email" => $account->getEmail(), "token" => $token], UrlGeneratorInterface::ABSOLUTE_URL);
$content = <<<EOD
<br/>
Une demande de réinitialisation de mot de passe a été demandée pour votre compte Flash Énergie.<br/>
<br/>
Pour réinitialiser votre mot de passe, rendez-vous sur le lien suivant: <a href="$link">$link</a><br/>
Ce lien est valable 24h.
<br/>
Si vous n'êtes pas à l'origine de ce changement, veuillez contacter en urgence votre responsable.<br/>
EOD;
$sendEmailService->send(
"Flash Énergie: Demande de réinitialisation de mot de passe",
$account->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Demande de réinitialisation de mot de passe",
"content" => $content
]
);
$this->get('session')->getFlashBag()->add("success", "Un mail contenant un lien de réinitialisation a été envoyé à l'adresse indiquée. Ce lien est valide pendant 24h.");
return $this->redirectToRoute("default_login");
} else {
$this->get('session')->getFlashBag()->add("warning", "Votre compte n'est pas actif");
}
} else {
$this->get('session')->getFlashBag()->add("danger", "Aucun compte trouvé avec cette adresse");
}
} else {
$this->get('session')->getFlashBag()->add("warning", "Merci de saisir une adresse mail valide");
}
}
return $this->render('forgot_password.html.twig', [
"form" => $form->createView(),
]);
}
/**
* @Route(
* path="/reset_password/{email}/{token}",
* name="reset_password"
* )
*
* @param Request $request
* @return Response
*/
public function reset_password(Request $request, PasswordEncoder $passwordEncoder, EntityManagerInterface $em)
{
$em = $this->getDoctrine()->getManager();
$account = $em->getRepository(Account::class)->findOneBy(["email" => $request->get("email")]);
if ($account) {
if ($account->getPasswordRequest() && $account->getPasswordRequestDate()) {
if ($account->getPasswordRequest() == $request->get("token")) {
$now = new \DateTime('now');
if ($now->getTimestamp() - $account->getPasswordRequestDate()->getTimestamp() < 86400) {
$label_attr = [
"class" => "font-size-h6 font-weight-bolder text-dark",
];
$input_attr = [
"class" => "form-control h-auto py-5 px-6 border-0 rounded-lg font-size-h6 step4-view-form-field"
];
$form = $this->createFormBuilder(null, [])
->add("password", RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => [
"attr" => $input_attr,
"label" => "Mot de passe",
"label_attr" => $label_attr
],
'second_options' => [
"attr" => $input_attr,
"label" => "Confirmer le mot de passe",
"label_attr" => $label_attr
]
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$salt = md5(uniqid());
$pwd = $form['password']->getData();
$account->setSalt($salt);
$enc_pwd = $passwordEncoder->encodePassword($pwd, $salt);
$account->setPassword($enc_pwd);
$account->setPasswordRequest(null);
$account->setPasswordRequestDate(null);
$em->flush();
$this->get('session')->getFlashBag()->add("success", "Votre mot de passe a été réinitialisé, vous pouvez maintenant vous connecter à votre espace.");
return $this->redirectToRoute("default_login");
}
return $this->render("reset_password.html.twig", [
'form' => $form->createView()
]);
} else {
throw new NotFoundHttpException("Cette URL n'est plus valide");
}
} else {
throw new NotFoundHttpException("Cette URL n'est pas valide");
}
}
}
throw new NotFoundHttpException();
}
/**
* @Route(
* path="/yousignevent",
* name="yousignevent"
* )
*
* @param Request $request
* @return Response
*/
public function yousignEvent(Request $request, EntityManagerInterface $em, YousignService $yousignService, SendEmailService $sendEmailService)
{
$requestData = json_decode($request->getContent(), true);
$eventName = $request->headers->get("X-Yousign-Event-Name");
if (!$eventName) {
error_log("Header X-Yousign-Event-Name not found.");
throw new BadRequestHttpException("Header X-Yousign-Event-Name not found.");
}
$procedureId = $request->headers->get("X-Flash-Data-Header");
if (!$procedureId) {
error_log("Header X-Flash-Data-Header not found.");
throw new BadRequestHttpException("Header X-Flash-Data-Header not found.");
}
$procedureSign = $em->getRepository(ProcedureSign::class)->find($procedureId);
if (!$procedureSign) {
error_log("ProcedureSign not found.");
throw new BadRequestHttpException("ProcedureSign not found.");
}
switch ($eventName) {
case "procedure.finished":
// Traitement de l'évènement
$procedureJson = json_decode($procedureSign->getContent());
switch ($procedureJson->type) {
case "cotation.acd":
$cotation = $em->getRepository(Cotation::class)->find($procedureJson->id);
$cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
if ($cotation) {
// Récupération du fichier signé
$fileId = $requestData["procedure"]["files"][0]["id"];
$fileContent = $yousignService->getFile($fileId);
if ($fileContent) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
$cotation->setAcdFile($fileName);
}
$cotation->setAcdSignDate(new \DateTime('now'));
$cotation->setState($cotationStateAcd);
$em->flush();
if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
$companyName = $cotation->getCompanyName();
$content = <<<EOD
<br/>
L'ACD associé à la cotation de <b>$companyName</b> a été signé.<br/>
Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: ACD signé",
$cotation->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature de l'ACD",
"content" => $content
]
);
}
}
break;
case "cotation.offer":
if ($procedureJson->nrj == "elec") {
$offer = $em->getRepository(OfferElec::class)->find($procedureJson->id);
} else {
$offer = $em->getRepository(OfferGaz::class)->find($procedureJson->id);
}
if ($offer) {
$cotation = $offer->getCotation();
$company = $cotation->getCompany();
// Récupération du fichier signé
$fileId = $requestData["procedure"]["files"][0]["id"];
$fileContent = $yousignService->getFile($fileId);
if ($fileContent) {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_offers_directory') . $fileName, $fileContent);
$offer->setFile($fileName);
$offer->setSignDate(new \DateTime('now'));
$offer->setProcedureYousignId($requestData["procedure"]["id"]);
}
$em->flush();
// Edition du contrat
$contract = new Contract();
$contract->setUser($cotation->getUser());
$contract->setCompany($cotation->getCompany());
$contract->setSupplier($offer->getSupplier());
$contract->setAddress($cotation->getAddress());
$contract->setAddress2($cotation->getAddress2());
$contract->setZipCode($cotation->getZipCode());
$contract->setCity($cotation->getCity());
$contract->setManager($cotation->getManager());
if ($procedureJson->nrj == "elec") {
$contract->setPdlNumber($cotation->getEPdl());
$contract->setOfferElec($offer);
$contract->setElectricity(true);
$contract->setElectricitySituation($cotation->getElectricitySituation());
$cotation->setSelectedOfferElec($offer);
} else {
$contract->setPceNumber($cotation->getGPce());
$contract->setOfferGaz($offer);
$contract->setGas(true);
$contract->setGasSituation($cotation->getElectricitySituation());
$cotation->setSelectedOfferGaz($offer);
}
$contratStateEnAttenteFournisseur = $em->getRepository(ContractState::class)->find(7);
$contract->setState($contratStateEnAttenteFournisseur);
if ($offer->getFile()) {
$filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
$contract->setFile($offer->getFile());
}
$contract->setSignDate(new \DateTime('now'));
$contract->setProcedureYousignId($requestData["procedure"]["id"]);
$em->persist($contract);
$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();
}
if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
$companyName = $cotation->getCompanyName();
$content = <<<EOD
<br/>
L'offre associée à la cotation de <b>$companyName</b> a été signé.<br/>
Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: Offre signée",
$cotation->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature de l'offre",
"content" => $content
]
);
}
}
break;
case "contract.file":
$contract = $em->getRepository(Contract::class)->find($procedureJson->id);
$contractStateAccepted = $em->getRepository(ContractState::class)->find(7);
if ($contract) {
// Récupération du fichier signé
$fileId = $requestData["procedure"]["files"][0]["id"];
$fileContent = $yousignService->getFile($fileId);
if ($fileContent) {
$fileName = $contract->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
$contract->setFile($fileName);
}
if ($contract->getState() && $contract->getState()->getId() == 3) {
$contract->setState($contractStateAccepted);
}
$contract->setSignDate(new \DateTime('now'));
$contract->setProcedureYousignId($procedureJson->id);
$em->flush();
if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
$companyName = $contract->getCompany()->getName();
$content = <<<EOD
<br/>
Le contrat de <b>$companyName</b> a été signé.<br/>
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: contrat signé",
$contract->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature du contrat",
"content" => $content
]
);
}
}
break;
case "contract.other-file":
$contract = $em->getRepository(Contract::class)->find($procedureJson->id);
if ($contract) {
// Récupération du fichier signé
$fileId = $requestData["procedure"]["files"][0]["id"];
$fileContent = $yousignService->getFile($fileId);
if ($fileContent) {
$fileName = $requestData["procedure"]["files"][0]["name"];
file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
$contract->setOtherFile($fileName);
}
$contract->setOtherFileSignDate(new \DateTime('now'));
$contract->setOtherFileProcedureYousignId($procedureJson->id);
$em->flush();
if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
$companyName = $contract->getCompany()->getName();
$content = <<<EOD
<br/>
Un document associé au contrat de <b>$companyName</b> a été signé.<br/>
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: document signé",
$contract->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature d'un document",
"content" => $content
]
);
}
}
break;
}
$procedureSign->setSignDate(new \DateTime('now'));
$em->flush();
break;
}
return new Response("Success", 200);
}
/**
* @Route(
* path="/docusignconnect",
* name="docusignconnect"
* )
*
* @param Request $request
* @return Response
*/
public function docusignConnect(Request $request, EntityManagerInterface $em, DocusignService $docusignService, SendEmailService $sendEmailService)
{
//$hmacKey = "MaDBne1eSxgjvu3xJXrfG8KV8zhS3uISPSIP/76CYyg=";
//$hmacKey = "Ed4gs/w9b2Ruhp4FhYDQ/todnR1Tzu3XxnZra24qJJ0=";
$hmacKey = "DjXEsnc9rVIgrmp1hmxiC0HxmQgHjpizBKl+Afk4M8g=";
$payload = file_get_contents('php://input');
$signature = $request->headers->get("X-DocuSign-Signature-1");
if ($docusignService::isValidHmac($hmacKey, $payload, $signature)) {
$payload = json_decode($request->getContent(), true);
$envelopeId = $payload["data"]["envelopeId"];
$procedureSign = $em->getRepository(ProcedureSign::class)->findOneBy(["docusignEnvelopeId" => $envelopeId]);
if (!$procedureSign) {
//throw new BadRequestHttpException("ProcedureSign not found.");
return new Response("ProcedureSign not found.", 200);
}
$accessToken = $docusignService->getAccessToken();
switch ($payload["event"]) {
case "envelope-completed":
// Traitement de l'évènement
$procedureJson = json_decode($procedureSign->getContent());
switch ($procedureJson->type) {
case "cotation.acd":
$cotation = $em->getRepository(Cotation::class)->find($procedureJson->id);
$cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
if ($cotation) {
// Récupération du fichier signé
if ($accessToken) {
$documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
$fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
if ($fileContent) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
$cotation->setAcdFile($fileName);
}
}
$cotation->setAcdSignDate(new \DateTime('now'));
$cotation->setState($cotationStateAcd);
$em->flush();
if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
$companyName = $cotation->getCompanyName();
$content = <<<EOD
<br/>
L'ACD associé à la cotation monosite de <b>$companyName</b> a été signé.<br/>
Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: ACD signé",
$cotation->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature de l'ACD",
"content" => $content
]
);
}
}
break;
case "cotation.offer":
if ($procedureJson->nrj == "elec") {
$offer = $em->getRepository(OfferElec::class)->find($procedureJson->id);
} else {
$offer = $em->getRepository(OfferGaz::class)->find($procedureJson->id);
}
if ($offer) {
$cotation = $offer->getCotation();
$company = $cotation->getCompany();
// Récupération du fichier signé
if ($accessToken) {
$documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
$fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
if ($fileContent) {
$fileName = $company->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_offers_directory') . $fileName, $fileContent);
$offer->setFile($fileName);
$offer->setSignDate(new \DateTime('now'));
$offer->setDocusignEnvelopeId($envelopeId);
}
}
$em->flush();
// Edition du contrat
$contract = new Contract();
$contract->setUser($cotation->getUser());
$contract->setCompany($cotation->getCompany());
$contract->setSupplier($offer->getSupplier());
$contract->setAddress($cotation->getAddress());
$contract->setAddress2($cotation->getAddress2());
$contract->setZipCode($cotation->getZipCode());
$contract->setCity($cotation->getCity());
$contract->setManager($cotation->getManager());
if ($procedureJson->nrj == "elec") {
$contract->setPdlNumber($cotation->getEPdl());
$contract->setOfferElec($offer);
$contract->setElectricity(true);
$contract->setElectricitySituation($cotation->getElectricitySituation());
$cotation->setSelectedOfferElec($offer);
} else {
$contract->setPceNumber($cotation->getGPce());
$contract->setOfferGaz($offer);
$contract->setGas(true);
$contract->setGasSituation($cotation->getElectricitySituation());
$cotation->setSelectedOfferGaz($offer);
}
$contratStateEnAttenteFournisseur = $em->getRepository(ContractState::class)->find(7);
$contract->setState($contratStateEnAttenteFournisseur);
if ($offer->getFile()) {
$filePathFrom = $this->getParameter('documents_offers_directory') . $offer->getFile();
copy($filePathFrom, $this->getParameter('documents_contracts_directory') . $offer->getFile());
$contract->setFile($offer->getFile());
}
$contract->setSignDate(new \DateTime('now'));
$contract->setDocusignEnvelopeId($envelopeId);
$em->persist($contract);
$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();
}
if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
$companyName = $cotation->getCompanyName();
$content = <<<EOD
<br/>
L'offre associée à la cotation de <b>$companyName</b> a été signé.<br/>
Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: Offre signée",
$cotation->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature de l'offre",
"content" => $content
]
);
}
}
break;
case "contract.file":
$contract = $em->getRepository(Contract::class)->find($procedureJson->id);
$contractStateAccepted = $em->getRepository(ContractState::class)->find(7);
if ($contract) {
// Récupération du fichier signé
if ($accessToken) {
$documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
$fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
if ($fileContent) {
$fileName = $contract->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
$contract->setFile($fileName);
}
}
if ($contract->getState() && $contract->getState()->getId() == 3) {
$contract->setState($contractStateAccepted);
}
$contract->setSignDate(new \DateTime('now'));
$contract->setDocusignEnvelopeId($envelopeId);
$em->flush();
if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
$companyName = $contract->getCompany()->getName();
$content = <<<EOD
<br/>
Le contrat de <b>$companyName</b> a été signé.<br/>
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: contrat signé",
$contract->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature du contrat",
"content" => $content
]
);
}
}
break;
case "contract.other-file":
$contract = $em->getRepository(Contract::class)->find($procedureJson->id);
if ($contract) {
// Récupération du fichier signé
if ($accessToken) {
$documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
$fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
if ($fileContent) {
$fileName = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["name"];
file_put_contents($this->getParameter('documents_contracts_directory') . $fileName, $fileContent);
$contract->setOtherFile($fileName);
}
}
$contract->setOtherFileSignDate(new \DateTime('now'));
$contract->setOtherFileDocusignEnvelopeId($envelopeId);
$em->flush();
if ($contract->getManager() && $contract->getManager()->getEmail() && $contract->getCompany()) {
$companyName = $contract->getCompany()->getName();
$content = <<<EOD
<br/>
Un document associé au contrat de <b>$companyName</b> a été signé.<br/>
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: document signé",
$contract->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature d'un document",
"content" => $content
]
);
}
}
break;
case "cotation-multisite.acd":
$cotation = $em->getRepository(CotationMultisite::class)->find($procedureJson->id);
$cotationStateAcd = $em->getRepository(CotationState::class)->find(3);
if ($cotation) {
// Récupération du fichier signé
if ($accessToken) {
$documentId = $payload["data"]["envelopeSummary"]["envelopeDocuments"][0]["documentId"];
$fileContent = $docusignService->getFile($accessToken, $documentId, $envelopeId);
if ($fileContent) {
$fileName = $cotation->getId() . "_" . md5(uniqid()) . '.pdf';
file_put_contents($this->getParameter('documents_acd_directory') . $fileName, $fileContent);
$cotation->setAcdFile($fileName);
}
}
$cotation->setAcdSignDate(new \DateTime('now'));
$cotation->setState($cotationStateAcd);
$em->flush();
if ($cotation->getManager() && $cotation->getManager()->getEmail()) {
$companyName = $cotation->getCompanyName();
$content = <<<EOD
<br/>
L'ACD associé à la cotation multisite de <b>$companyName</b> a été signé.<br/>
Veuillez vous rapprocher du client afin de poursuivre ce dossier de cotation.
<br/>
Pricing Flash Énergie
EOD;
$sendEmailService->send(
"CRM Flash Énergie: ACD signé",
$cotation->getManager()->getEmail(),
'emails/flash_default.html.twig',
[
"title" => "Notification de signature de l'ACD",
"content" => $content
]
);
}
}
break;
}
$procedureSign->setSignDate(new \DateTime('now'));
$em->flush();
break;
}
} else {
error_log("Bad HMAC verification.");
throw new BadRequestHttpException("Bad HMAC verification.");
}
return new Response("Success", 200);
}
/**
* @Route(
* path="/fe-invitation/{token}",
* name="flash_energie_token"
* )
*
* @param Request $request
* @return Response
*/
public function FeInvitationToken(Request $request, EntityManagerInterface $em, $token)
{
return $this->redirect("flashenergie://invitation?token=" . $token, 301);
}
/**
* @Route(
* path="/fe-reset-password/{token}/{mail}",
* name="flash_energie_reset_password_token"
* )
*
* @param Request $request
* @return Response
*/
public function FeRestPasswordToken(Request $request, EntityManagerInterface $em, $token, $mail)
{
return $this->redirect("flashenergie://resetPassword?token=" . $token . "&email=" . $mail, 301);
}
/**
* @Route(
* path="/calculatrice-turpe/{id}",
* name="calculatrice-turpe"
* )
*
* @return Response
*/
public function calculatriceTurpeAction(Cotation $cotation, Request $request)
{
return $this->render('app/cotations/calculatrice_turpe.html.twig', [
"cotation" => $cotation,
]);
}
/**
* @Route(
* path="/graph-conso/{id}",
* name="graph-conso"
* )
*
*/
public function graphConsoAction(Cotation $cotation, Request $request)
{
require_once($_SERVER["DOCUMENT_ROOT"] . '../../assets/lib/jpgraph/jpgraph.php');
require_once($_SERVER["DOCUMENT_ROOT"] . '../../assets/lib/jpgraph/jpgraph_pie.php');
if ($cotation->getESegment() == "C5") {
$data = array(
$cotation->getEConsommationPointe(),
$cotation->getEConsommationHph(),
$cotation->getEConsommationHch(),
);
$labels = array(
"Base: ".$cotation->getEConsommationPointe()." \n(%.1f%%)",
"HP: ".$cotation->getEConsommationHph()." \n(%.1f%%)",
"HC: ".$cotation->getEConsommationHch()." \n(%.1f%%)",
);
$legends = ['Base', 'HP', 'HC'];
$aCols = 3;
} else {
$data = array(
$cotation->getEConsommationPointe(),
$cotation->getEConsommationHph(),
$cotation->getEConsommationHch(),
$cotation->getEConsommationHpe(),
$cotation->getEConsommationHce()
);
$labels = array(
"Pointe: ".$cotation->getEConsommationPointe()." \n(%.1f%%)",
"HPH: ".$cotation->getEConsommationHph()." \n(%.1f%%)",
"HCH: ".$cotation->getEConsommationHch()." \n(%.1f%%)",
"HPE: ".$cotation->getEConsommationHpe()." \n(%.1f%%)",
"HCE: ".$cotation->getEConsommationHce()." \n(%.1f%%)"
);
$legends = ['Pointe', 'HPH', 'HCH', 'HPE', 'HCE'];
$aCols = 5;
}
// Create the Pie Graph.
$graph = new PieGraph(300,250);
// Set A title for the plot
$graph->title->Set("CAR (MWh)");
$graph->title->SetMargin(0);
$graph->SetBox(true);
$graph->legend->SetPos(0.5,0.97,'center','bottom');
$graph->legend->SetColumns($aCols);
// Create
try {
$p1 = new PiePlot($data);
$p1->SetLegends($legends);
$p1->SetLabels($labels);
$p1->SetLabelPos(1);
$graph->Add($p1);
$p1->ShowBorder();
$p1->SetColor('black');
$p1->SetSliceColors(array('#ff5a78', '#ff9444', '#0099e3', '#ffc55a', '#17b8b7'));
$graph->Stroke();
} catch (\Exception $e) {
return new Response("<img src='' />", 200);
}
}
/**
* @Route(
* path="/external-api/pappers/search",
* name="external-api_pappers_search"
* )
*
*/
public function externalApiPappersSearchAction(PappersService $pappersService, Request $request)
{
return new JsonResponse($pappersService->searchCompany($request->get('q')));
}
/**
* @Route(
* path="/naf/search",
* name="naf_search"
* )
*
*/
public function nafSearchAction(Request $request, EntityManagerInterface $em)
{
$naf = $em->getRepository(InseeNaf::class)->findOneBy(["code" => strtoupper($request->get('code'))]);
if ($naf) {
return new JsonResponse([
"success" => true,
"code" => $naf->getCode(),
"libelle" => $naf->getLibelle(),
]);
}
return new JsonResponse([
"success" => false,
]);
}
}