<?php
namespace App\Controller;
use DateTime;
use DateTimeZone;
use App\Entity\Colis;
use App\Entity\Client;
use App\Entity\Commande;
use App\Form\SearchType;
use App\Form\CommandeType;
use App\Entity\ClientFinal;
use App\Service\FedexService;
use App\Service\UtilsService;
use App\Form\CommandeAdminType;
use App\Service\BandeauService;
use App\Service\EmailGenerator;
use App\Form\CommandeCreneauType;
use App\Form\CommandeAdminEditType;
use App\Repository\ColisRepository;
use App\Repository\ClientRepository;
use App\Repository\CommandeRepository;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use App\Repository\ClientFinalRepository;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* @Route("/commande")
*/
class CommandeController extends AbstractController
{
private $utilsService;
private $emailGeneratorService;
private $fedexService;
private $roleAdmin;
private $baseDomain = 'https://wine.mbebordeaux.fr';
private $bandeauService;
public function __construct(UtilsService $utilsService, EmailGenerator $emailGeneratorService, FedexService $fedexService, BandeauService $bandeauService)
{
$this->utilsService = $utilsService;
$this->emailGeneratorService = $emailGeneratorService;
$this->fedexService = $fedexService;
$this->roleAdmin = $this->utilsService->isAdmin();
$this->bandeauService = $bandeauService;
}
/**
* @Route("/", name="app_commande_index", methods={"GET"})
*/
public function index(CommandeRepository $commandeRepository, PaginatorInterface $paginator, Request $request): Response
{
$user = $this->getUser();
$packaging = $request->query->get('packaging');
$state = $request->query->get('state');
if ($packaging == null) {
if ($this->roleAdmin) {
$packaging = "emballage_par_mbe";
}
else {
$packaging = "emballage_par_caviste";
}
}
if ($state == null) {
if ($this->roleAdmin) {
$state = "preparation";
}
else {
$state = "emballage_caviste";
}
}
$data = null;
$needPacking = false;
$needCollect = false;
$a_emballer_caviste = false;
$a_preparer_collecte = false;
$emb_livraison = false;
$exportPackingClient = false;
$exportPrepsClient = false;
$display_emballage_par_caviste = false;
$display_emballage_par_mbe = false;
$attention_emballage_par_caviste = false;
$attention_emballage_par_mbe = false;
if($packaging == "emballage_par_caviste") {
$emb_livraison = true;
}
if($state == "urgent"){
if ($this->roleAdmin){
$data = $commandeRepository->findUrgentOrderAdmin();
} else {
$data = $commandeRepository->findUrgentOrderClient($user->getClient());
}
} else {
if ($this->roleAdmin) {
if($packaging == "emballage_tous") {
$data = $commandeRepository->findby(
array(),
array('dateCollecte' => 'DESC')
);
}
else if($packaging == "archive_tous") {
//$data = $commandeRepository->findByState("archive", array('dateCollecte' => 'ASC'));
$data = $commandeRepository->findCommandesArchives();
}
else {
//Pour chaque onglet, on recherche par state et categorie pour tous les clients
/* if($state == 'tous') {
$data = $commandeRepository->findByEmballageLivraison($emb_livraison);
}
else { */
$data = $commandeRepository->findByStateAndEmballageLivraison($state, $emb_livraison);
/* } */
}
$needPacking = empty($commandeRepository->findByStateAndEmballageLivraison("emballage_mbe", $emb_livraison)) ? false : true;
$needCollect = empty($commandeRepository->findByStateAndEmballageLivraison("attente_collecte_mbe", $emb_livraison)) ? false : true;
if($needPacking || $needCollect) {
$attention_emballage_par_mbe = true;
}
} else {
$client = $user->getClient();
if($packaging == "emballage_tous") {
$data = $commandeRepository->findByClient($client, array('dateCollecte' => 'DESC'));
}
else if($packaging == "archive_tous") {
$data = $commandeRepository->findByStateAndClient(["archive", "canceled"], $client);
}
else {
if($state == "traitement_mbe") {
//req pour avoir les 2 states fusionnés
$data = $commandeRepository->findByTraitementMbeAndEmballageLivraisonAndCaviste($emb_livraison, $client);
}
else {
$data = $commandeRepository->findByStateAndEmballageLivraisonAndCaviste($state, $emb_livraison, $client);
}
}
/* if ($state == "tous") {
$data = $commandeRepository->findByClient($client);
} else if ($state == "prepare"){
$data = $commandeRepository->findOrderToPrepare($client);
} else {
$data = $commandeRepository->findByStateAndClient($state, $client);
// if ($state == 'attente') {
// $data += $commandeRepository->findByStateAndClient('emballage', $client);
// }
} */
$a_emballer_caviste = empty($commandeRepository->findByStateAndEmballageLivraisonAndCaviste("emballage_caviste", $emb_livraison, $client)) ? false : true;
$a_preparer_collecte = empty($commandeRepository->findByStateAndEmballageLivraisonAndCaviste("preparation", $emb_livraison, $client)) ? false : true;
$exportPackingClient = empty($commandeRepository->findByStateAndClient("emballage_caviste", $client)) ? false : true;
$exportPrepsClient = empty($commandeRepository->findByStateAndClient("preparation", $client)) ? false : true;
$display_emballage_par_caviste = empty($commandeRepository->findByEmballageLivraisonAndCaviste(true, $client)) ? false : true;
$display_emballage_par_mbe = empty($commandeRepository->findByEmballageLivraisonAndCaviste(false, $client)) ? false : true;
if($a_emballer_caviste) {
$attention_emballage_par_caviste = true;
}
if($a_preparer_collecte) {
$attention_emballage_par_mbe = true;
}
}
}
foreach($data as $com){
$previDebut = clone $com->getDateCollecte();
$previFin = clone $com->getDateCollecte();
$creoUpdatable = $com->getDateCollecte()->getTimestamp() > strtotime("+3 days");
$com->setPreviDebut($previDebut->modify("+7 days"));
$com->setPreviFin($previFin->modify("+12 days"));
$com->setcrenoUpdatable($creoUpdatable);
}
$commandes = $paginator->paginate(
$data,
$request->query->getInt('page', 1),
20
);
$isIsFirstConnexion = $user->isIsFirstConnexion();
$form = $this->createForm(SearchType::class);
$form->handleRequest($request);
$search = $request->query->get('search');
if ($search !== null && $search['recherche'] !== null) {
$data = $this->utilsService->search($search['recherche'], $this->roleAdmin);
$commandesfilter = $paginator->paginate(
$data,
$request->query->getInt('page',1),
20
);
$returnData = [
'commandes' => $commandesfilter,
'packagingController' => 'emballage_tous',
'stateController' => '',
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'packing' => $needPacking,
'collect' => $needCollect,
'a_emballer_caviste' => $a_emballer_caviste,
'a_preparer_collecte' => $a_preparer_collecte,
'display_emballage_par_caviste' => $display_emballage_par_caviste,
'display_emballage_par_mbe' => $display_emballage_par_mbe,
'attention_emballage_par_caviste' => $attention_emballage_par_caviste,
'attention_emballage_par_mbe' => $attention_emballage_par_mbe,
'exportPackingClient' => $exportPackingClient,
'exportPrepsClient' => $exportPrepsClient,
'isFirstConnexion' => $isIsFirstConnexion,
'searchForm' => $form,
'searchValue' => $search['recherche'],
'bandeau' => $this->bandeauService->displayPopup()
];
} else {
$returnData = [
'commandes' => $commandes,
'packagingController' => $packaging,
'stateController' => $state,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'packing' => $needPacking,
'collect' => $needCollect,
'a_emballer_caviste' => $a_emballer_caviste,
'a_preparer_collecte' => $a_preparer_collecte,
'display_emballage_par_caviste' => $display_emballage_par_caviste,
'display_emballage_par_mbe' => $display_emballage_par_mbe,
'attention_emballage_par_caviste' => $attention_emballage_par_caviste,
'attention_emballage_par_mbe' => $attention_emballage_par_mbe,
'exportPackingClient' => $exportPackingClient,
'exportPrepsClient' => $exportPrepsClient,
'isFirstConnexion' => $isIsFirstConnexion,
'searchForm' => $form,
'bandeau' => $this->bandeauService->displayPopup()
];
}
if ($this->roleAdmin) {
return $this->renderForm('commande/index_admin.html.twig', $returnData);
}
return $this->renderForm('commande/index.html.twig', $returnData);
}
public function horizontalSearch($worksheet, $highestColumn, $colSearch, $rowSearch) {
for ($column = $colSearch; $column != $highestColumn; $column++) {
if($column != $colSearch) {
$cell = $worksheet->getCell($column.$rowSearch);
if($cell != '') {
if(str_starts_with($cell->getValue(), '=')) {
return $cell->getCalculatedValue();
}
return $cell->getValue();
}
}
}
}
public function verticalSearch($worksheet, $highestRow, $colSearch, $rowSearch, $type, $produits) {
$values = [];
$stop = false;
$prestop = 0;
for ($row = $rowSearch; $row != $highestRow; $row++) {
if(($row != $rowSearch) && !$stop) {
$cell = $worksheet->getCell($colSearch.$row);
if(($type == 'destinataire') && ($cell != '')) {
$values[] = $cell->getValue();
$cleanValue = mb_strtolower(str_replace(" ", "", mb_convert_encoding($cell->getValue(), "UTF-8", "auto")));
if(str_starts_with($cleanValue, 'email:')) {
$stop = true;
}
}
else { //designation
if($cell != '') {
$produits = $this->productsSearch($worksheet, $row, $produits);
}
else {
if($prestop == 2) { //Ligne vide après "désignation, ne pas arrêter à cet endroit
$stop = true;
}
$prestop++;
}
}
}
}
if($type == 'designation') {
return $produits;
}
return $values;
}
public function productsSearch($worksheet, $rowSearch, $produits) {
$volume = 'classic';
$type = 'red';
$produit_nom = mb_strtolower(mb_convert_encoding($worksheet->getCell('A'.$rowSearch)->getValue(), "UTF-8", "auto"));
$produit_qte = intval(mb_strtolower(mb_convert_encoding($worksheet->getCell('E'.$rowSearch)->getValue(), "UTF-8", "auto")));
$produit_prixTotalEuros = mb_strtolower(mb_convert_encoding($worksheet->getCell('G'.$rowSearch)->getCalculatedValue(), "UTF-8", "auto"));
//Livraison
if (str_contains($produit_nom, 'transport')) {
$produits['livraison_prix'] = $produit_prixTotalEuros;
$produit_qte = 0;
}
// Contenance
if (str_contains($produit_nom, '1.5 l ')) {
$volume = 'magnum';
}
// Type
if (str_contains($produit_nom, 'white ')) {
$type = 'white';
}
else if (str_contains($produit_nom, 'sparkling ')) {
$type = 'sparkling';
}
// Quantité
$produits[$volume][$type] += $produit_qte;
$produits[$volume]['total'] += $produit_qte;
return $produits;
}
function in_array_recursive($needle, $haystack, $strict)
{
foreach ($haystack as $key => $element) {
if (!is_array($element)) {
if (strtolower($element) === strtolower($needle)) {
return true;
}
}
$isFound = false;
if (is_array($element)) {
$isFound = $this->in_array_recursive($needle, $element, $strict);
}
if ($isFound === true) {
return $key;
}
}
return false;
}
/* function searchForUsState($authorizedStates, $adresse, $stringSearch) {
$stringSearch = str_replace(array(", ", ","), " ", $stringSearch);
$stringSearchClean = strtolower($stringSearch);
$explodeSeparator = '';
$adresse['ville'] = '';
$adresse['etat_us'] = '';
$adresse['province'] = '';
$adresse['zip'] = '';
$exceptionsStates[] = ['name' => 'district of columbia', 'etat_us' => 'DC', 'province' => 'District de Columbia'];
$exceptionsStates[] = ['name' => 'new hampshire', 'etat_us' => 'NH', 'province' => 'New Hampshire'];
$exceptionsStates[] = ['name' => 'new-hampshire', 'etat_us' => 'NH', 'province' => 'New Hampshire'];
$exceptionsStates[] = ['name' => 'new jersey', 'etat_us' => 'NJ', 'province' => 'New Jersey'];
$exceptionsStates[] = ['name' => 'new-jersey', 'etat_us' => 'NJ', 'province' => 'New Jersey'];
$exceptionsStates[] = ['name' => 'new mexico', 'etat_us' => 'NM', 'province' => 'Nouveau-Mexique'];
$exceptionsStates[] = ['name' => 'new-mexico', 'etat_us' => 'NM', 'province' => 'Nouveau-Mexique'];
$exceptionsStates[] = ['name' => 'new york', 'etat_us' => 'NY', 'province' => 'New York'];
$exceptionsStates[] = ['name' => 'new-york', 'etat_us' => 'NY', 'province' => 'New York'];
$exceptionsStates[] = ['name' => 'north carolina', 'etat_us' => 'NC', 'province' => 'Caroline du Nord'];
$exceptionsStates[] = ['name' => 'north-carolina', 'etat_us' => 'NC', 'province' => 'Caroline du Nord'];
$exceptionsStates[] = ['name' => 'north dakota', 'etat_us' => 'ND', 'province' => 'Dakota du Nord'];
$exceptionsStates[] = ['name' => 'north-dakota', 'etat_us' => 'ND', 'province' => 'Dakota du Nord'];
$exceptionsStates[] = ['name' => 'rhode island', 'etat_us' => 'RI', 'province' => 'Rhode Island'];
$exceptionsStates[] = ['name' => 'south carolina', 'etat_us' => 'SC', 'province' => 'Caroline du Sud'];
$exceptionsStates[] = ['name' => 'south-carolina', 'etat_us' => 'SC', 'province' => 'Caroline du Sud'];
$exceptionsStates[] = ['name' => 'south dakota', 'etat_us' => 'SD', 'province' => 'Dakota du Sud'];
$exceptionsStates[] = ['name' => 'south-dakota', 'etat_us' => 'SD', 'province' => 'Dakota du Sud'];
$exceptionsStates[] = ['name' => 'virginia', 'etat_us' => 'VA', 'province' => 'Virginie'];
$exceptionsStates[] = ['name' => 'west virginia', 'etat_us' => 'WV', 'province' => 'Virginie-Occidentale'];
$exceptionsStates[] = ['name' => 'west-virginia', 'etat_us' => 'WV', 'province' => 'Virginie-Occidentale'];
foreach ($exceptionsStates as $key => $exceptionState) {
if (str_contains($stringSearchClean, $exceptionState['name'])) {
$explodeSeparator = $exceptionState['name'] . ' ';
$adresse['etat_us'] = $exceptionState['etat_us'];
$adresse['province'] = $exceptionState['province'];
}
}
if($explodeSeparator != '') {
$adressParts = explode($explodeSeparator, $stringSearchClean);
if($adressParts[0]) {
$adresse['ville'] = $adressParts[0];
}
if($adressParts[1]) {
$adresse['zip'] = $adressParts[1];
}
}
else {
$pieces = explode(" ", $stringSearch);
$zip = $pieces[intval(count($pieces)) - 1];
unset($pieces[intval(count($pieces)) - 1]);
$state = $pieces[intval(count($pieces)) - 1];
unset($pieces[intval(count($pieces)) - 1]);
$town = implode(" ", $pieces);
if(is_numeric($zip)) {
if($this->in_array_recursive($state, $authorizedStates, true)) {
$state = $this->in_array_recursive($state, $authorizedStates, true);
}
if (array_key_exists($state, $authorizedStates)) {
$adresse['zip'] = $zip;
$adresse['etat_us'] = $state;
$adresse['province'] = $authorizedStates[$state]['fr'];
$adresse['ville'] = $town;
}
}
}
return $adresse;
} */
function searchForUsState($authorizedStates, $adresse, $stringSearch) {
$stringSearch = str_replace(array(", ", ","), " ", $stringSearch);
$pieces = explode(" ", $stringSearch);
$adresse['ville'] = '';
$adresse['etat_us'] = '';
$adresse['province'] = '';
$adresse['zip'] = '';
foreach($pieces as $key => $piece) {
if (array_key_exists($piece, $authorizedStates)) {
$adresse['etat_us'] = $piece;
$adresse['province'] = $authorizedStates[$piece]['fr'];
$adresse['found'] = true;
}
else {
$hasFullnameState = $this->in_array_recursive($piece, $authorizedStates, true);
if($hasFullnameState) {
$adresse['etat_us'] = $hasFullnameState;
$adresse['province'] = $authorizedStates[$hasFullnameState]['fr'];
$adresse['found'] = true;
$hasFullnameState = false;
}
else {
if($adresse['found']) {
$adresse['zip'] .= $piece .' ';
}
else {
$adresse['ville'] .= $piece .' ';
}
}
}
}
return $adresse;
}
/* public function explodeAdress($data) {
$authorizedStates['AL'] = ['fr'=> 'Alabama', 'en' => 'Alabama'];
$authorizedStates['AK'] = ['fr'=> 'Alaska', 'en' => 'Alaska'];
$authorizedStates['AZ'] = ['fr'=> 'Arizona', 'en' => 'Arizona'];
$authorizedStates['AR'] = ['fr'=> 'Arkansas', 'en' => 'Arkansas'];
$authorizedStates['CA'] = ['fr'=> 'Californie', 'en' => 'California'];
$authorizedStates['CO'] = ['fr'=> 'Colorado', 'en' => 'Colorado'];
$authorizedStates['CT'] = ['fr'=> 'Connecticut', 'en' => 'Connecticut'];
$authorizedStates['DE'] = ['fr'=> 'Delaware', 'en' => 'Delaware'];
$authorizedStates['DC'] = ['fr'=> 'District de Columbia', 'en' => 'District of Columbia'];
$authorizedStates['FL'] = ['fr'=> 'Floride', 'en' => 'Florida'];
$authorizedStates['GA'] = ['fr'=> 'Géorgie', 'en' => 'Georgia'];
$authorizedStates['HI'] = ['fr'=> 'Hawaii', 'en' => 'Hawaii'];
$authorizedStates['ID'] = ['fr'=> 'Idaho', 'en' => 'Idaho'];
$authorizedStates['IL'] = ['fr'=> 'Illinois', 'en' => 'Illinois'];
$authorizedStates['IN'] = ['fr'=> 'Indiana', 'en' => 'Indiana'];
$authorizedStates['IA'] = ['fr'=> 'Iowa', 'en' => 'Iowa'];
$authorizedStates['KS'] = ['fr'=> 'Kansas', 'en' => 'Kansas'];
$authorizedStates['KY'] = ['fr'=> 'Kentucky', 'en' => 'Kentucky'];
$authorizedStates['LA'] = ['fr'=> 'Louisiane', 'en' => 'Louisiana'];
$authorizedStates['ME'] = ['fr'=> 'Maine', 'en' => 'Maine'];
$authorizedStates['MD'] = ['fr'=> 'Maryland', 'en' => 'Maryland'];
$authorizedStates['MA'] = ['fr'=> 'Massachusetts', 'en' => 'Massachusetts'];
$authorizedStates['MI'] = ['fr'=> 'Michigan', 'en' => 'Michigan'];
$authorizedStates['MN'] = ['fr'=> 'Minnesota', 'en' => 'Minnesota'];
// $authorizedStates['MS'] = ['fr'=> 'Mississippi', 'en' => 'Mississippi'];
$authorizedStates['MO'] = ['fr'=> 'Missouri', 'en' => 'Missouri'];
$authorizedStates['MT'] = ['fr'=> 'Montana', 'en' => 'Montana'];
$authorizedStates['NE'] = ['fr'=> 'Nebraska', 'en' => 'Nebraska'];
$authorizedStates['NV'] = ['fr'=> 'Nevada', 'en' => 'Nevada'];
$authorizedStates['NH'] = ['fr'=> 'New Hampshire', 'en' => 'New Hampshire'];
$authorizedStates['NJ'] = ['fr'=> 'New Jersey', 'en' => 'New Jersey'];
$authorizedStates['NM'] = ['fr'=> 'Nouveau-Mexique', 'en' => 'New Mexico'];
$authorizedStates['NY'] = ['fr'=> 'New York', 'en' => 'New York'];
$authorizedStates['NC'] = ['fr'=> 'Caroline du Nord', 'en' => 'North Carolina'];
$authorizedStates['ND'] = ['fr'=> 'Dakota du Nord', 'en' => 'North Dakota'];
$authorizedStates['OH'] = ['fr'=> 'Ohio', 'en' => 'Ohio'];
$authorizedStates['OK'] = ['fr'=> 'Oklahoma', 'en' => 'Oklahoma'];
$authorizedStates['OR'] = ['fr'=> 'Oregon', 'en' => 'Oregon'];
$authorizedStates['PA'] = ['fr'=> 'Pennsylvanie', 'en' => 'Pennsylvania'];
$authorizedStates['RI'] = ['fr'=> 'Rhode Island', 'en' => 'Rhode Island'];
$authorizedStates['SC'] = ['fr'=> 'Caroline du Sud', 'en' => 'South Carolina'];
$authorizedStates['SD'] = ['fr'=> 'Dakota du Sud', 'en' => 'South Dakota'];
$authorizedStates['TN'] = ['fr'=> 'Tennessee', 'en' => 'Tennessee'];
$authorizedStates['TX'] = ['fr'=> 'Texas', 'en' => 'Texas'];
// $authorizedStates['UT'] = ['fr'=> 'Utah', 'en' => 'Utah'];
$authorizedStates['VT'] = ['fr'=> 'Vermont', 'en' => 'Vermont'];
$authorizedStates['VA'] = ['fr'=> 'Virginie', 'en' => 'Virginia'];
$authorizedStates['WA'] = ['fr'=> 'Washington', 'en' => 'Washington'];
$authorizedStates['WV'] = ['fr'=> 'Virginie-Occidentale', 'en' => 'West Virginia'];
$authorizedStates['WI'] = ['fr'=> 'Wisconsin', 'en' => 'Wisconsin'];
$authorizedStates['WY'] = ['fr'=> 'Wyoming', 'en' => 'Wyoming'];
$adresse = [];
$adresse['found'] = false;
// $adresse['adresse'] = $data['destinataire'][1];
//On regarde si la ligne suivant l'adresse comprend un US state
// $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][3]);
// $adresse['complement'] = $data['destinataire'][2];
// if(!$adresse['found']) {
// $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][2]);
// $adresse['complement'] = '';
// }
$reversedData = array_reverse($data['destinataire'], true);
// exit();
$tempName = [];
$tempAdress = [];
$tempComplement = [];
$isAdressFound = false;
foreach($reversedData as $key => $reversedLine) {
$cleanValue = strtolower(str_replace(" ", "", $reversedLine));
if(!str_starts_with($cleanValue, 'tel:') && !str_starts_with($cleanValue, 'mobile:') && !str_starts_with($cleanValue, 'email:') && !str_starts_with($cleanValue, 'etats-unis') && !str_starts_with($cleanValue, 'etats unis') && !str_starts_with($cleanValue, 'united states')) {
if(!$adresse['found']) {
$adresse = $this->searchForUsState($authorizedStates, $adresse, $reversedLine);
}
else {
if(!$isAdressFound) {
if(is_numeric($reversedLine[0])) {
$tempAdress[$key] = $reversedLine;
$isAdressFound = true;
}
else {
$tempComplement[$key] = $reversedLine;
}
}
else {
$tempName[$key] = $reversedLine;
}
}
}
}
$adresse['client'] = implode(", ", array_reverse($tempName, true));
$adresse['adresse'] = implode(", ", array_reverse($tempAdress, true));
$adresse['complement'] = implode(", ", array_reverse($tempComplement, true));
// exit();
return $adresse;
} */
public function explodeAdress($data) {
$authorizedStates['AL'] = ['fr'=> 'Alabama', 'en' => 'Alabama'];
$authorizedStates['AK'] = ['fr'=> 'Alaska', 'en' => 'Alaska'];
$authorizedStates['AZ'] = ['fr'=> 'Arizona', 'en' => 'Arizona'];
$authorizedStates['AR'] = ['fr'=> 'Arkansas', 'en' => 'Arkansas'];
$authorizedStates['CA'] = ['fr'=> 'Californie', 'en' => 'California'];
$authorizedStates['CO'] = ['fr'=> 'Colorado', 'en' => 'Colorado'];
$authorizedStates['CT'] = ['fr'=> 'Connecticut', 'en' => 'Connecticut'];
$authorizedStates['DE'] = ['fr'=> 'Delaware', 'en' => 'Delaware'];
$authorizedStates['DC'] = ['fr'=> 'District de Columbia', 'en' => 'District of Columbia'];
$authorizedStates['FL'] = ['fr'=> 'Floride', 'en' => 'Florida'];
$authorizedStates['GA'] = ['fr'=> 'Géorgie', 'en' => 'Georgia'];
$authorizedStates['HI'] = ['fr'=> 'Hawaii', 'en' => 'Hawaii'];
$authorizedStates['ID'] = ['fr'=> 'Idaho', 'en' => 'Idaho'];
$authorizedStates['IL'] = ['fr'=> 'Illinois', 'en' => 'Illinois'];
$authorizedStates['IN'] = ['fr'=> 'Indiana', 'en' => 'Indiana'];
$authorizedStates['IA'] = ['fr'=> 'Iowa', 'en' => 'Iowa'];
$authorizedStates['KS'] = ['fr'=> 'Kansas', 'en' => 'Kansas'];
$authorizedStates['KY'] = ['fr'=> 'Kentucky', 'en' => 'Kentucky'];
$authorizedStates['LA'] = ['fr'=> 'Louisiane', 'en' => 'Louisiana'];
$authorizedStates['ME'] = ['fr'=> 'Maine', 'en' => 'Maine'];
$authorizedStates['MD'] = ['fr'=> 'Maryland', 'en' => 'Maryland'];
$authorizedStates['MA'] = ['fr'=> 'Massachusetts', 'en' => 'Massachusetts'];
$authorizedStates['MI'] = ['fr'=> 'Michigan', 'en' => 'Michigan'];
$authorizedStates['MN'] = ['fr'=> 'Minnesota', 'en' => 'Minnesota'];
// $authorizedStates['MS'] = ['fr'=> 'Mississippi', 'en' => 'Mississippi'];
$authorizedStates['MO'] = ['fr'=> 'Missouri', 'en' => 'Missouri'];
$authorizedStates['MT'] = ['fr'=> 'Montana', 'en' => 'Montana'];
$authorizedStates['NE'] = ['fr'=> 'Nebraska', 'en' => 'Nebraska'];
$authorizedStates['NV'] = ['fr'=> 'Nevada', 'en' => 'Nevada'];
$authorizedStates['NH'] = ['fr'=> 'New Hampshire', 'en' => 'New Hampshire'];
$authorizedStates['NJ'] = ['fr'=> 'New Jersey', 'en' => 'New Jersey'];
$authorizedStates['NM'] = ['fr'=> 'Nouveau-Mexique', 'en' => 'New Mexico'];
$authorizedStates['NY'] = ['fr'=> 'New York', 'en' => 'New York'];
$authorizedStates['NC'] = ['fr'=> 'Caroline du Nord', 'en' => 'North Carolina'];
$authorizedStates['ND'] = ['fr'=> 'Dakota du Nord', 'en' => 'North Dakota'];
$authorizedStates['OH'] = ['fr'=> 'Ohio', 'en' => 'Ohio'];
$authorizedStates['OK'] = ['fr'=> 'Oklahoma', 'en' => 'Oklahoma'];
$authorizedStates['OR'] = ['fr'=> 'Oregon', 'en' => 'Oregon'];
$authorizedStates['PA'] = ['fr'=> 'Pennsylvanie', 'en' => 'Pennsylvania'];
$authorizedStates['RI'] = ['fr'=> 'Rhode Island', 'en' => 'Rhode Island'];
$authorizedStates['SC'] = ['fr'=> 'Caroline du Sud', 'en' => 'South Carolina'];
$authorizedStates['SD'] = ['fr'=> 'Dakota du Sud', 'en' => 'South Dakota'];
$authorizedStates['TN'] = ['fr'=> 'Tennessee', 'en' => 'Tennessee'];
$authorizedStates['TX'] = ['fr'=> 'Texas', 'en' => 'Texas'];
// $authorizedStates['UT'] = ['fr'=> 'Utah', 'en' => 'Utah'];
$authorizedStates['VT'] = ['fr'=> 'Vermont', 'en' => 'Vermont'];
$authorizedStates['VA'] = ['fr'=> 'Virginie', 'en' => 'Virginia'];
$authorizedStates['WA'] = ['fr'=> 'Washington', 'en' => 'Washington'];
$authorizedStates['WV'] = ['fr'=> 'Virginie-Occidentale', 'en' => 'West Virginia'];
$authorizedStates['WI'] = ['fr'=> 'Wisconsin', 'en' => 'Wisconsin'];
$authorizedStates['WY'] = ['fr'=> 'Wyoming', 'en' => 'Wyoming'];
$adresse = [];
$adresse['found'] = false;
// $adresse['adresse'] = $data['destinataire'][1];
//On regarde si la ligne suivant l'adresse comprend un US state
/* $adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][3]);
$adresse['complement'] = $data['destinataire'][2];
if(!$adresse['found']) {
$adresse = $this->searchForUsState($authorizedStates, $adresse, $data['destinataire'][2]);
$adresse['complement'] = '';
} */
$reversedData = array_reverse($data['destinataire'], true);
$tempName = [];
$tempAdress = [];
$tempComplement = [];
$isAdressFound = false;
foreach($reversedData as $key => $reversedLine) {
$cleanValue = strtolower(str_replace(" ", "", $reversedLine));
if(!str_starts_with($cleanValue, 'tel:') && !str_starts_with($cleanValue, 'mobile:') && !str_starts_with($cleanValue, 'email:') && !str_starts_with($cleanValue, 'etats-unis') && !str_starts_with($cleanValue, 'etats unis') && !str_starts_with($cleanValue, 'united states')) {
if(!$adresse['found']) {
$adresse = $this->searchForUsState($authorizedStates, $adresse, $reversedLine);
}
else {
if(!$isAdressFound) {
if(is_numeric($reversedLine[0])) {
$tempAdress[$key] = $reversedLine;
$isAdressFound = true;
}
else {
$tempComplement[$key] = $reversedLine;
}
}
else {
$tempName[$key] = $reversedLine;
}
}
}
}
$adresse['client'] = implode(", ", array_reverse($tempName, true));
$adresse['adresse'] = implode(", ", array_reverse($tempAdress, true));
$adresse['complement'] = implode(", ", array_reverse($tempComplement, true));
return $adresse;
}
public function create_via_import(ClientRepository $clientRepository, CommandeRepository $commandeRepository)//: Response
{
$em = $this->getDoctrine()->getManager();
$path = 'xdeUEDJuejUDEiduhEDIOehdEUDHe/';
$createCommandeResponse['errorFound'] = false;
$createCommandeResponse['errorDetails'] = '';
$createCommandeResponse['excelFilePath'] = [];
foreach(glob($path.'*.xls') as $file) {
$erreur = '';
$originalFile = str_replace($path, "", $file);
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumn++;
$data = [];
$produits = [];
$produits['livraison_prix'] = 0;
$produits['classic']['red'] = 0;
$produits['classic']['white'] = 0;
$produits['classic']['sparkling'] = 0;
$produits['classic']['total'] = 0;
$produits['magnum']['red'] = 0;
$produits['magnum']['white'] = 0;
$produits['magnum']['sparkling'] = 0;
$produits['magnum']['total'] = 0;
for ($column = 'A'; $column != $highestColumn; $column++) {
for ($row = 1; $row <= $highestRow; $row++) {
$cell = $worksheet->getCell($column.$row);
if($column.$row == 'A1') {
$data['caviste'] = $cell->getValue();
}
else {
$cleanValue = mb_strtolower(str_replace(" ", "", mb_convert_encoding($cell->getValue(), "UTF-8", "auto")));
if(str_starts_with($cleanValue, 'facturen')) {
$data['facture'] = $this->horizontalSearch($worksheet, $highestColumn, $column, $row);
}
else if(str_starts_with($cleanValue, 'date:')) {
$data['date'] = $this->horizontalSearch($worksheet, $highestColumn, $column, $row);
}
else if(str_starts_with($cleanValue, 'dateexpeditionsouhaitee:')) {
$data['date_expedition'] = $this->horizontalSearch($worksheet, $highestColumn, $column, $row);
}
else if(str_starts_with($cleanValue, 'totaleuros')) {
$data['total_euros'] = $this->horizontalSearch($worksheet, $highestColumn, $column, $row);
}
else if(str_starts_with($cleanValue, 'consignee/')) {
$data['destinataire'] = $this->verticalSearch($worksheet, $highestRow, $column, $row, 'destinataire', false);
}
else if(str_starts_with($cleanValue, 'désignation')) {
$produits = $this->verticalSearch($worksheet, $highestRow, $column, $row, 'designation', $produits);
}
}
}
}
$data['telephone'] = '';
$data['email'] = '';
foreach($data['destinataire'] as $data_dest) {
$cleanValue = strtolower(str_replace(" ", "", $data_dest));
if(str_starts_with($cleanValue, 'tel:') || str_starts_with($cleanValue, 'mobile:')) {
$infos_tel = explode(":", $data_dest);
$data['telephone'] = $infos_tel[1];
}
else if(str_starts_with($cleanValue, 'email:')) {
$infos_email = explode(":", $data_dest);
$data['email'] = $infos_email[1];
}
}
if($data['caviste'] == 'Ets MARTIN') { //ETSM - ETS MARTIN
$client = $clientRepository->find(295);
}
else if($data['caviste'] == 'La Grande Cave de Saint Emilion') { //ETSM - LGC
$client = $clientRepository->find(296);
}
else { //ETSM - BX CLASSIQUE
$client = $clientRepository->find(320);
}
$adress = $this->explodeAdress($data);
$now = new DateTime('now', new DateTimeZone('Europe/Paris'));
$nombreBouteillesTotal = $produits['classic']['total'] + ($produits['magnum']['total'] * 2);
$nombre_colis_total = 0;
$cmdFacture = $commandeRepository->findOneBy([
'numeroFacture' => $data['facture'],
'client' => $client,
]);
$erreur .= $this->searchError(
$adress['client'],
$data['telephone'],
$data['email'],
$data['facture'],
$data['total_euros'],
$adress['zip'],
$adress['ville'],
$adress['adresse'],
$adress['etat_us'],
$cmdFacture,
$originalFile,
false
);
if($erreur == '') {
$commande = new Commande();
$stop = false;
while($stop == false) {
$colis = new Colis();
if($nombreBouteillesTotal - 12 >= 0) {
$nombreBouteillesTotal = $nombreBouteillesTotal - 12;
$colis->setNombreBouteille(12);
//Si il ne reste plus de bouteilles, on sort
if($nombreBouteillesTotal == 0) {
$stop = true;
}
}
else {
//add 1 colis de nombreBouteilles
$colis->setNombreBouteille($nombreBouteillesTotal);
$stop = true;
}
$colis->setCommande($commande);
$em->persist($colis);
$commande->addColi($colis);
$nombre_colis_total++;
}
$commande->setNombreColisTotal($nombre_colis_total);
$commande->setClient($client);
$clientFinal = new ClientFinal();
$clientFinal->setEmail($data['email']);
$clientFinal->setTelephone($data['telephone']);
$clientFinal->setCommande($commande);
$clientFinal->setFullName($adress['client']);
$commande->setClientFinal($clientFinal);
$commande->setAssuranceLivraison($client->isAssuranceDefaut());
$commande->setEmballageLivraison($client->isEmballageDefaut());
$commande->setNumeroFacture($data['facture']);
$commande->setMontantTotalFacture($data['total_euros'] - $produits['livraison_prix']);
$commande->setCodePostalLivraison($adress['zip']);
$commande->setVilleLivraison($adress['ville']);
$commande->setAdresseLivraison($adress['adresse']);
$commande->setComplementAdresseLivraison($adress['complement']);
$commande->setProvince($adress['province']);
$commande->setEtatUs($adress['etat_us']);
$commande->setDateCommandeSoumission($now);
$commande->setFedexPdfGenerated(false);
$commande->setFedexPdfAvailable(false);
$commande->setIsTemporaire(false);
$commande->setIsValideeParClient(true);
// if($client->isEmballageDefaut() == true) {
// $commande->setState('emballage_caviste');
// }
// else {
// $commande->setState('preparation');
// }
$commande->setState('attente_pec_transporteur');
$dateCollecte = $this->createDateCollecte($now, $data['date_expedition']);
// $nowClone = clone $now;
// $dateMin = $nowClone->modify("+1 days");
// $dateMinDay = $dateMin->format('l');
// //Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
// if($dateMinDay == 'Saturday') {
// $dateMin->modify("+2 days");
// $dateMinDay = $dateMin->format('l');
// }
// if($dateMinDay == 'Sunday') {
// $dateMin->modify("+1 days");
// $dateMinDay = $dateMin->format('l');
// }
// //On stocke la valeur de cette date min pour comparaison
// $dateMinCompare = $dateMin->format('Y-m-d');
// if($data['date_expedition']) {
// $date = str_replace("/","-", htmlspecialchars($data['date_expedition']));
// $dateSaisie = date('Y-m-d', strtotime($date));
// if($dateSaisie < $dateMinCompare) {
// $dateSaisie = $dateMinCompare;
// }
// }
// else {
// $dateSaisie = $dateMinCompare;
// }
// $dateCollecte = new DateTime($dateSaisie);
$commande->setDateCollecte($dateCollecte);
$commande->setNombreBouteilleRouge($produits['classic']['red']);
$commande->setNombreBouteilleBlanc($produits['classic']['white']);
$commande->setNombreBouteillePetillant($produits['classic']['sparkling']);
$commande->setNombreMagnumRouge($produits['magnum']['red']);
$commande->setNombreMagnumBlanc($produits['magnum']['white']);
$commande->setNombreMagnumPetillant($produits['magnum']['sparkling']);
$commande->setToken('gsrefgrdsgfres');
$commande->setFastPickup(true);
// commande_massive
if($nombreBouteillesTotal > 36) {
$commande->setCommandeMassive(true);
$this->emailGeneratorService->sendMassiveCommande($commande);
}
else {
$commande->setCommandeMassive(false);
}
//On change le fichier de dossier, vers upload_Hk2DvAtDeUccGXh
$newPath = 'upload_Hk2DvAtDeUccGXh/' . $originalFile;
$commande->setFichierFacture($originalFile);
// $cmdFacture = $commandeRepository->findOneByNumeroFacture($data['facture']);
$cmdFacture = $commandeRepository->findOneBy([
'numeroFacture' => $data['facture'],
'client' => $client,
]);
if($cmdFacture == null){
$em->persist($clientFinal);
$em->persist($commande);
$em->flush();
}
}
else {
//On change le fichier de dossier, vers upload_commande_error_ad41Ig7A4ZBd7S7
$newPath = 'upload_commande_error_ad41Ig7A4ZBd7S7/' . $originalFile;
$createCommandeResponse['errorFound'] = true;
$createCommandeResponse['errorDetails'] .= $erreur;
$createCommandeResponse['excelFilePath'][] = $newPath;
// $rapportErreur .= $erreur . ' La commande n\'a pas pu être générée.<br/>';
}
rename($file, $newPath);
}
return $createCommandeResponse;
}
public function searchError($fullName, $telephone, $email, $numeroFacture, $totalEuros, $codePostal, $ville, $adresse, $etatUs, $cmdFacture, $originalFile, $sameCustomer ){
$erreur = "";
switch (true) {
case $fullName == '':
$erreur .= 'Le <strong>nom du client</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
case $telephone == '':
$erreur .= 'Le <strong>numéro de téléphone</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
case $email == '':
$erreur .= 'L\' <strong>adresse mail</strong> du document "' . $originalFile . '" n\'est pas renseignée correctement.<br/>';
break;
case $numeroFacture == '':
$erreur .= 'Le <strong>numéro de facture</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
case $totalEuros == '':
$erreur .= 'Le <strong>montant total en euros</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
case $codePostal == '':
$erreur .= 'Le <strong>code postal de livraison</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
case $ville == '':
$erreur .= 'La <strong>ville de livraison</strong> du document "' . $originalFile . '" n\'est pas renseignée correctement.<br/>';
break;
case $adresse == '':
$erreur .= 'L\' <strong>adresse de livraison</strong> du document "' . $originalFile . '" n\'est pas renseignée correctement.<br/>';
break;
case $etatUs == '':
$erreur .= 'L\' <strong>État de livraison</strong> du document "' . $originalFile . '" n\'est pas renseigné correctement.<br/>';
break;
}
if($sameCustomer == false){
if($cmdFacture != null){
$erreur .= 'Le numéro de facture : '. $numeroFacture .'</strong> du document "' . $originalFile . '" est déjà présent dans la base de données pour ce client.<br/>';
}
}
return $erreur;
}
public function createDateCollecte($now, $dateExpedition){
$nowClone = clone $now;
$dateMin = $nowClone->modify("+1 days");
$dateMinDay = $dateMin->format('l');
//Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
if($dateMinDay == 'Saturday') {
$dateMin->modify("+2 days");
$dateMinDay = $dateMin->format('l');
}
if($dateMinDay == 'Sunday') {
$dateMin->modify("+1 days");
$dateMinDay = $dateMin->format('l');
}
//On stocke la valeur de cette date min pour comparaison
$dateMinCompare = $dateMin->format('Y-m-d');
if($dateExpedition != null) {
$date = str_replace("/","-", htmlspecialchars($dateExpedition));
$dateSaisie = date('Y-m-d', strtotime($date));
if($dateSaisie < $dateMinCompare) {
$dateSaisie = $dateMinCompare;
}
}
else {
$dateSaisie = $dateMinCompare;
}
$dateCollecte = new DateTime($dateSaisie);
return $dateCollecte;
}
public function create_via_import_idealwine(ClientRepository $clientRepository, CommandeRepository $commandeRepository)//: Response
{
ini_set('memory_limit', '800M');
$em = $this->getDoctrine()->getManager();
$path = 'VK74QTZTBQax9SkdDuax/';
$createCommandeResponse['errorFound'] = false;
$createCommandeResponse['errorDetails'] = '';
$createCommandeResponse['excelFilePath'] = [];
$erreur = '';
// echo '<pre>';
foreach(glob($path.'*.xlsx') as $file) {
// var_dump($file);
$originalFile = str_replace($path, "", $file);
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);
$worksheet = $spreadsheet->getActiveSheet();
// Tableau pour stocker les fullNames déjà traités
$fullNameProcessed = [];
$newPath = null;
// Parcourir chaque ligne (sauter la première ligne d'en-tête)
foreach ($worksheet->getRowIterator(2) as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Permet de lire toutes les cellules, même vides
// Récupération du client IDEALWINE
$client = $clientRepository->find(309);
$commande = new Commande();
// Récupérer les valeurs des colonnes
$numeroFacture = $worksheet->getCellByColumnAndRow(3, $row->getRowIndex())->getValue() ?? '';
$fullName = trim($worksheet->getCellByColumnAndRow(5, $row->getRowIndex())->getValue()) ?? '';
if(!($fullName == "" && $numeroFacture == "")){
if (!in_array($fullName, $fullNameProcessed)) {
$observation = $worksheet->getCellByColumnAndRow(7, $row->getRowIndex())->getValue() ?? '';
$codePostal = trim($worksheet->getCellByColumnAndRow(9, $row->getRowIndex())->getValue()) ?? '';
$ville = trim($worksheet->getCellByColumnAndRow(8, $row->getRowIndex())->getValue()) ?? '';
$etatUs = $worksheet->getCellByColumnAndRow(10, $row->getRowIndex())->getValue() ?? '';
$adresse = trim($worksheet->getCellByColumnAndRow(6, $row->getRowIndex())->getValue()) ?? '';
$telephone = $worksheet->getCellByColumnAndRow(12, $row->getRowIndex())->getValue() ?? '';
$email = trim($worksheet->getCellByColumnAndRow(13, $row->getRowIndex())->getValue()) ?? '';
$nombreColisSouhaite = $worksheet->getCellByColumnAndRow(17, $row->getRowIndex())->getValue() ?? 0;
$totalEuros = $worksheet->getCellByColumnAndRow(18, $row->getRowIndex())->getValue() ?? 0;
$rouge = $worksheet->getCellByColumnAndRow(14, $row->getRowIndex())->getValue() ?? 0;
$rougeMagnum = $worksheet->getCellByColumnAndRow(15, $row->getRowIndex())->getValue() ?? 0;
$autre = $worksheet->getCellByColumnAndRow(16, $row->getRowIndex())->getValue() ?? 0;
$rouge = intval($rouge) + intval($autre);
// ON VERIFIE S'IL Y A
$worksheetInterne = $spreadsheet->getActiveSheet();
// Variable pour detecter si plusieurs lignes du même client
$sameCustomer=false;
$same = false;
foreach ($worksheetInterne->getRowIterator(2) as $rowInterne) {
$cellIteratorInterne = $rowInterne->getCellIterator();
$cellIteratorInterne->setIterateOnlyExistingCells(false); // Permet de lire toutes les cellules, même vides
$fullNameInterne = trim($worksheet->getCellByColumnAndRow(5, $rowInterne->getRowIndex())->getValue());
if($fullNameInterne == $fullName){
// Permet juste de pas prendre la première occurence car c'est la même ligne.
if($same){
$rougeInterne = $worksheetInterne->getCellByColumnAndRow(14, $rowInterne->getRowIndex())->getValue() ?? 0;
$rougeMagnumInterne = $worksheetInterne->getCellByColumnAndRow(15, $rowInterne->getRowIndex())->getValue() ?? 0;
$autreInterne = $worksheetInterne->getCellByColumnAndRow(16, $rowInterne->getRowIndex())->getValue() ?? 0;
$numeroFactureInterne = $worksheetInterne->getCellByColumnAndRow(3, $rowInterne->getRowIndex())->getValue() ?? '';
$nombreColisSouhaiteInterne = $worksheetInterne->getCellByColumnAndRow(17, $rowInterne->getRowIndex())->getValue() ?? 0;
$totalEurosInterne = $worksheetInterne->getCellByColumnAndRow(18, $rowInterne->getRowIndex())->getValue() ?? 0;
// On additionne avec les autres
$rouge = intval($rougeInterne) + intval($autreInterne) + intval($rouge);
$rougeMagnum = intval($rougeMagnumInterne) + intval($rougeMagnumInterne);
$nombreColisSouhaite = intval($nombreColisSouhaiteInterne) + $nombreColisSouhaite;
$numeroFacture .= ", ".$numeroFactureInterne;
$totalEuros = floatval($totalEuros) + floatval($totalEurosInterne);
$sameCustomer=true;
}
$same = true;
}
}
// Stocker le fullName dans le tableau pour éviter les doublons
$fullNameProcessed[] = $fullName;
// var_dump("-------------------------");
// var_dump($numeroFacture);
// var_dump($fullName);
// var_dump($observation);
// var_dump($codePostal);
// var_dump($ville);
// var_dump($etatUs);
// var_dump($adresse);
// var_dump($telephone);
// var_dump($email);
// var_dump($totalEuros);
// var_dump("Nombre de colis souhaité : ".$nombreColisSouhaite);
// var_dump("Nombre de bouteilles : ".$rouge);
// var_dump("Nombre de magnum : ".$rougeMagnum);
// var_dump("-------------------------");
$cmdFacture = null;
if($numeroFacture != ""){
$cmdFacture = $commandeRepository->findOneBy([
'numeroFacture' => $numeroFacture,
'client' => $client,
]);
}
/************************************
* TEST SI UNE ERREUR DANS LA LIGNE *
************************************/
$erreur .= $this->searchError(
$fullName,
$telephone,
$email,
$numeroFacture,
$totalEuros,
$codePostal,
$ville,
$adresse,
$etatUs,
$cmdFacture,
$originalFile,
$sameCustomer
);
if($erreur == '') {
// FOREACH POUR GENERATION COLIS
$rougeMagnumDouble = intval($rougeMagnum) + intval($rougeMagnum);
$nombreBouteillesTotal = intval($rouge) + $rougeMagnumDouble;
$repartitionColis = $this->repartirBouteillesEnColis($nombreBouteillesTotal, $nombreColisSouhaite);
// var_dump($repartitionColis);
foreach ($repartitionColis as $keyColis => $valueColis) {
$colis = new Colis();
$colis->setNombreBouteille($valueColis);
$em->persist($colis);
$commande->addColi($colis);
}
$commande->setClient($client);
// Configurer les objets Commande et ClientFinal
$commande->setEtatUs($etatUs);
$commande->setProvince($this->utilsService->getProvinceByEtatUs($etatUs));
$commande->setNumeroFacture($numeroFacture);
$commande->setNombreColisTotal(sizeof($repartitionColis));
$commande->setMontantTotalFacture($totalEuros);
$commande->setCodePostalLivraison($codePostal);
$commande->setVilleLivraison($ville);
$commande->setAdresseLivraison($adresse);
$commande->setObservation($observation);
$clientFinal = new ClientFinal();
$clientFinal->setFullName($fullName);
$clientFinal->setEmail($email);
$clientFinal->setTelephone($telephone);
$clientFinal->setCommande($commande);
$commande->setClientFinal($clientFinal);
// Paramètres supplémentaires
$now = new DateTime('now', new DateTimeZone('Europe/Paris'));
$commande->setAssuranceLivraison($client->isAssuranceDefaut());
$commande->setEmballageLivraison($client->isEmballageDefaut());
$commande->setDateCommandeSoumission($now);
$commande->setFedexPdfGenerated(false);
$commande->setFedexPdfAvailable(false);
$commande->setIsTemporaire(false);
$commande->setIsValideeParClient(true);
$commande->setToken('gsrefgrdsgfres');
$commande->setFastPickup(true);
// Gestion de l'état selon l'emballage
// if ($client->isEmballageDefaut() == true) {
// $commande->setState('emballage_caviste');
// } else {
// $commande->setState('preparation');
// }
$commande->setState('attente_pec_transporteur');
$dateCollecte = $this->createDateCollecte($now, null);
$commande->setDateCollecte($dateCollecte);
// Quantité des bouteilles
$commande->setNombreBouteilleRouge($rouge);
$commande->setNombreBouteilleBlanc(0);
$commande->setNombreBouteillePetillant(0);
$commande->setNombreMagnumRouge($rougeMagnum);
$commande->setNombreMagnumBlanc(0);
$commande->setNombreMagnumPetillant(0);
// Gestion des commandes massives
if ($nombreBouteillesTotal > 36) {
$commande->setCommandeMassive(true);
$this->emailGeneratorService->sendMassiveCommande($commande);
} else {
$commande->setCommandeMassive(false);
}
$commande->setFichierFacture($originalFile);
// Persister les objets
$em->persist($clientFinal);
$em->persist($commande);
// Flusher à la fin de la boucle
$em->flush();
}else{
$createCommandeResponse['errorFound'] = true;
$createCommandeResponse['errorDetails'] .= $erreur;
// $createCommandeResponse['excelFilePath'][] = $newPath;
$createCommandeResponse['excelFilePath'][] = "";
}
}
}
}
//On change le fichier de dossier, vers upload_Hk2DvAtDeUccGXh
$newPath = 'upload_Hk2DvAtDeUccGXh/' . $originalFile;
rename($file, $newPath);
}
// var_dump($createCommandeResponse);
// echo '</pre>';
return $createCommandeResponse;
}
function repartirBouteillesEnColis($nombreBouteilles, $nombreColisSouhaite) {
// Maximum de bouteilles par colis
$maxBouteillesParColis = 12;
// Si le nombre de colis souhaité ne peut pas respecter la contrainte des 12 bouteilles max
if ($nombreColisSouhaite * $maxBouteillesParColis < $nombreBouteilles) {
// Calculer le nombre minimal de colis requis pour respecter la contrainte de 12 bouteilles max
$nombreColisRequis = ceil($nombreBouteilles / $maxBouteillesParColis);
$nombreColisSouhaite = $nombreColisRequis;
}
// Tableau pour stocker la répartition des bouteilles par colis
$repartition = [];
// Calcul de la répartition équitable
$bouteillesParColis = floor($nombreBouteilles / $nombreColisSouhaite); // Répartition équitable dans chaque colis
$resteBouteilles = $nombreBouteilles % $nombreColisSouhaite; // Bouteilles restantes à répartir
// Ajouter les bouteilles à chaque colis
for ($i = 0; $i < $nombreColisSouhaite; $i++) {
// Si il reste des bouteilles à répartir, on en ajoute 1 supplémentaire dans les premiers colis
if ($resteBouteilles > 0) {
$repartition[] = $bouteillesParColis + 1;
$resteBouteilles--;
} else {
$repartition[] = $bouteillesParColis;
}
}
return $repartition;
}
/**
* @Route("/kdioejfeiofjeiofesjf", name="app_commande_kdioejfeiofjeiofesjf", methods={"GET", "POST"})
*/
public function kdioejfeiofjeiofesjf(Request $request): Response{
set_time_limit(6000);
// $csvPath = $this->getParameter('kernel.project_dir') . '/public/mbe_taxe.csv';
$csvPath = $this->getParameter('kernel.project_dir') . '/public/mbe_taxe_en_test.csv';
if (!file_exists($csvPath)) {
return new Response('Fichier non trouvé.', 404);
}
echo '<pre>';
$rows = [];
if (($handle = fopen($csvPath, 'r')) !== false) {
$header = fgetcsv($handle, 0, ";");
$i=0;
$errorMails = null;
while (($data = fgetcsv($handle, 0, ";")) !== false) {
if($i>=0 && $i<82){
$i++;
if (isset($data[11])) {
// 1. Remplacer espaces multiples par un seul
$data[11] = preg_replace('/\s+/', ' ', $data[11]);
// 2. Supprimer les espaces au début/fin
$data[11] = trim($data[11]);
}
$send = $data[14];
if($send != "ok"){
try {
$res = $this->emailGeneratorService->sendEmailTaxe($data);
if ($res) {
// $success++;
} else {
// $fail++;
$errorMails[] = $data[8]; // ou ce qui correspond à l'email
}
} catch (\Exception $e) {
// $fail++;
// $errorMails[] = $data[8];
$errorMails[] = [
'email' => $data[8],
'error' => $e->getMessage()
];
// log $e->getMessage();
}
// $res = $this->emailGeneratorService->sendEmailTaxe($data);
$deliveryDate = $data[0]; // Delivery Date
$chateauName = $data[1]; // Château Name
$recipientName = $data[2]; // Recipient's Name
$cp = $data[3]; // cp
$ville = $data[4]; // ville
$deliveryAddr = $data[5]; // Delivery Address
$etat = $data[6]; // etat
$trackingNumber = $data[7]; // Tracking Number
$email = $data[8];
$phone = $data[9]; // Téléphone
$montant = $data[10]; // $XXX
$proforma = $data[11]; // proforma
$lienPaiement = $data[12]; // Lien de paiement
$facture = $data[13]; // facture
var_dump("---------------------- NUMERO : ".$i." ---------------------");
var_dump("deliveryDate : ". $deliveryDate );
var_dump("chateauName : ". $chateauName );
var_dump("recipientName : ". $recipientName );
var_dump("cp : ". $cp );
var_dump("ville : ". $ville );
var_dump("deliveryAddr : ". $deliveryAddr );
var_dump("etat : ". $etat );
var_dump("trackingNumber: ". $trackingNumber );
var_dump("email : ". $email );
var_dump("phone : ". $phone );
var_dump("montant : ". $montant );
var_dump("proforma : ". $proforma );
var_dump("lienPaiement : ". $lienPaiement );
var_dump("facture : ". $facture );
}
}
}
fclose($handle);
var_dump($errorMails);
}
echo '</pre>';
exit();
}
/**
* @Route("/new", name="app_commande_new", methods={"GET", "POST"})
*/
public function new(Request $request, CommandeRepository $commandeRepository, ClientRepository $clientRepository, ColisRepository $colisRepository, ClientFinalRepository $clientFinalRepository): Response
{
// $this->addFlash("info", 'Bonjour et bienvenue sur la plateforme !');
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$cmdTemporaire = null;
/* $creneauxLivraison = $this->createCreneauxLivraison($commandeRepository, 30); */
if ($this->roleAdmin) {
$commande = new Commande();
$form = $this->createForm(CommandeAdminType::class, $commande);
$oldFichier = '';
} else {
$thisClient = $user->getClient();
//récupère la dernière commande si elle est temporaire
$cmdTemporaire = $commandeRepository->findOneTemporaireByClient($thisClient);
if ($cmdTemporaire) {
$commande = $cmdTemporaire;
$form = $this->createForm(CommandeType::class, $cmdTemporaire);
$oldFichier = $commande->getFichierFacture();
} else {
$commande = new Commande();
$form = $this->createForm(CommandeType::class, $commande);
$oldFichier = '';
}
}
$form->handleRequest($request);
if ($form->isSubmitted()) {
$commande->setCommandeMassive(false);
$postColis = $_POST['colis'];
if ($this->roleAdmin) {
$postCommande = $_POST['commande_admin'];
} else {
$postCommande = $_POST['commande'];
}
$nbMagnumSaisi = intval($postCommande['nombreMagnumRouge']) + intval($postCommande['nombreMagnumBlanc']) + intval($postCommande['nombreMagnumPetillant']);
$nbBouteillesSaisi = intval($postCommande['nombreBouteilleRouge']) + intval($postCommande['nombreBouteilleBlanc']) + intval($postCommande['nombreBouteillePetillant']);
$nbBouteillesTotal = ($nbMagnumSaisi * 2) + $nbBouteillesSaisi;
$nombreBouteillesRenseigneDansColis = 0;
if($this->roleAdmin) {
foreach ($postColis["new"] as $key => $value) {
$nombreBouteillesRenseigneDansColis += intval($value);
}
}
if($this->roleAdmin) {
// Test si le nombre de bouteilles total correspond au nombre de bouteilles dans les colis uniquement pour les admins
if($nbBouteillesTotal != $nombreBouteillesRenseigneDansColis){
$this->addFlash("error", 'Le nombre de bouteilles total ne correspond au nombre de bouteilles dans les colis');
$colisThisCommande = [];
return $this->renderForm('commande/new_admin.html.twig', [
'commande' => $commande,
'form' => $form,
'user' => $this->getUser(),
/* 'creneauxLivraison' => $creneauxLivraison, */
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
]);
}
}
if ($this->roleAdmin) {
$postCommande = $_POST['commande_admin'];
$thisClient = $clientRepository->find($postCommande['client']);
} else {
$postCommande = $_POST['commande'];
$thisClient = $user->getClient();
}
$assuranceLivraison = false;
$emballageLivraison = false;
$assuranceLivraison = $postCommande['assuranceLivraison'] == 'true' ? true : false ;
$emballageLivraison = $postCommande['emballageLivraison'] == 'true' ? true : false ;
$now = new DateTime('now', new DateTimeZone('Europe/Paris'));
$etatUs = htmlspecialchars($_POST['input_etat_us']);
if($etatUs == ''){
$this->addFlash("error", 'Sélectionner un État pour créer une commande.');
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
$cmdAEnvoyer = $cmdTemporaire;
}
else {
$colisThisCommande = [];
$cmdAEnvoyer = $commande;
}
$formOptions = [
'commande' => $cmdAEnvoyer,
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
];
if ($this->roleAdmin) {
return $this->renderForm('commande/new_admin.html.twig', $formOptions);
}
else {
return $this->renderForm('commande/new.html.twig', $formOptions);
}
}
if ($etatUs == "MS" || $etatUs == "UT") {
$this->addFlash("error", 'Il n\'est pas possible de sélectionner une adresse dans cet État.');
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
$cmdAEnvoyer = $cmdTemporaire;
}
else {
$colisThisCommande = [];
$cmdAEnvoyer = $commande;
}
$formOptions = [
'commande' => $cmdAEnvoyer,
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
];
if ($this->roleAdmin) {
return $this->renderForm('commande/new_admin.html.twig', $formOptions);
}
else {
return $this->renderForm('commande/new.html.twig', $formOptions);
}
}
//_____Client final_____
if($commande->getClientFinal()->getId()) {
//Update
$clientFinal = $commande->getClientFinal();
}else {
$clientFinal = new ClientFinal();
}
if (!filter_var($postCommande['clientFinal']['email'], FILTER_VALIDATE_EMAIL)) {
$this->addFlash("error", 'L\'email du destinataire n\'est pas valide');
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
$cmdAEnvoyer = $cmdTemporaire;
}
else {
$colisThisCommande = [];
$cmdAEnvoyer = $commande;
}
$formOptions = [
'commande' => $cmdAEnvoyer,
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
];
if ($this->roleAdmin) {
return $this->renderForm('commande/new_admin.html.twig', $formOptions);
}
else {
return $this->renderForm('commande/new.html.twig', $formOptions);
}
}
$clientFinal->setEmail($postCommande['clientFinal']['email']);
if(strlen($postCommande['clientFinal']['telephone']) != 10){
$this->addFlash("error", 'Le numéro de téléphone doit être composé de 10 chiffres.');
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
$cmdAEnvoyer = $cmdTemporaire;
}
else {
$colisThisCommande = [];
$cmdAEnvoyer = $commande;
}
$formOptions = [
'commande' => $cmdAEnvoyer,
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
];
if ($this->roleAdmin) {
return $this->renderForm('commande/new_admin.html.twig', $formOptions);
}
else {
return $this->renderForm('commande/new.html.twig', $formOptions);
}
}
$clientFinal->setTelephone($postCommande['clientFinal']['telephone']);
if (strlen($postCommande['clientFinal']['fullName']) > 70) {
$this->addFlash("error", 'Le nom et prénom sont trop long');
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
$cmdAEnvoyer = $cmdTemporaire;
}
else {
$colisThisCommande = [];
$cmdAEnvoyer = $commande;
}
$formOptions = [
'commande' => $cmdAEnvoyer,
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
];
if ($this->roleAdmin) {
return $this->renderForm('commande/new_admin.html.twig', $formOptions);
}
else {
return $this->renderForm('commande/new.html.twig', $formOptions);
}
}
$clientFinal->setFullName($postCommande['clientFinal']['fullName']);
// $clientFinal->setPrenom($postCommande['clientFinal']['prenom']);
// $clientFinal->setNom($postCommande['clientFinal']['nom']);
$em->persist($clientFinal);
$em->flush();
$indexData = [
'id' => $clientFinal->getId(),
'full_name' => $clientFinal->getFullName()
];
$this->utilsService->updateIndex('clientFinal', $indexData);
//_____Fichier Facture_____
//Si on modifie une commande temporaire
if($commande->getId()) {
//On compare avec la value de l'input
//Si les deux valeurs sont différentes
if ($_POST['input_filename'] != '' && $_POST['input_filename'] !== $oldFichier) {
if (isset($_FILES)) {
if ($this->roleAdmin) {
$fileImage = $_FILES['commande_admin'];
} else {
$fileImage = $_FILES['commande'];
}
//$fileImage = $_FILES['commande'];
$name = $fileImage['name']['fichierFacture'];
$originalFilename = pathinfo($name, PATHINFO_FILENAME);
// $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
// $safeFilenameClean = $this->is_valid_filename($safeFilename);
$extension = pathinfo($name, PATHINFO_EXTENSION);
if($commande->getClient() != null ){
$id = $commande->getClient()->getId();
} else {
$id = $this->getUser()->getId();
}
$newFilename = 'facture_' . $id . '_' . uniqid() . '.' . $extension;
// Formats autorisés
$allowTypes = array('pdf','jpg','png','jpeg');
if(in_array($extension, $allowTypes)){
move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
$commande->setFichierFacture($newFilename);
$em->persist($commande);
}
//On unlink l'ancien fichier
if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
}
}
}
//Sinon
else {
//On set fichierFacture avec l'ancienne value
$commande->setFichierFacture($oldFichier);
$em->persist($commande);
}
$commande->setIsTemporaire(false);
}
else {
if( isset($_FILES)){
if ($this->roleAdmin) {
$fileImage = $_FILES['commande_admin'];
} else {
$fileImage = $_FILES['commande'];
}
//$fileImage = $_FILES;
$name = $fileImage['name']['fichierFacture'];
$originalFilename = pathinfo($name, PATHINFO_FILENAME);
// $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
// $safeFilenameClean = $this->is_valid_filename($safeFilename);
$extension = pathinfo($name, PATHINFO_EXTENSION);
if($commande->getClient() != null ){
$id = $commande->getClient()->getId();
} else {
$id = $this->getUser()->getId();
}
$newFilename = 'facture_' . $id . '_' . uniqid() . '.' . $extension;
// Formats autorisés
$allowTypes = array('pdf','jpg','png','jpeg');
if(in_array($extension, $allowTypes)){
move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
$commande->setFichierFacture($newFilename);
$em->persist($commande);
}
}
}
if($this->roleAdmin){
$commande->setIsTemporaire(false);
}
else {
$commande->setIsTemporaire(true);
}
$montant = $this->checkMontant($postCommande['montantTotalFacture']);
//_____Commande_____
$commande->setClient($thisClient);
$commande->setClientFinal($clientFinal);
$commande->setNombreColisTotal($postCommande['nombreColisTotal']);
$commande->setNumeroDae($postCommande['numeroDae']);
$commande->setAssuranceLivraison($assuranceLivraison);
$commande->setEmballageLivraison($emballageLivraison);
$commande->setNumeroFacture($postCommande['numeroFacture']);
$commande->setMontantTotalFacture(floatval($montant));
/* $commande->setDateDebutFenetre($dateDebutFenetre);
$commande->setDateFinFenetre($dateFinFenetre); */
$commande->setCodePostalLivraison(str_replace(' ', '', $postCommande['codePostalLivraison']));
$commande->setVilleLivraison(trim($postCommande['villeLivraison']));
$commande->setAdresseLivraison($postCommande['adresseLivraison']);
$commande->setComplementAdresseLivraison($postCommande['complementAdresseLivraison']);
$commande->setEtatUs($etatUs);
$commande->setObservation($postCommande['observation']);
$commande->setProvince($this->utilsService->getProvinceByEtatUs($etatUs));
$commande->setNombreBouteilleRouge($postCommande['nombreBouteilleRouge']);
$commande->setNombreBouteilleBlanc($postCommande['nombreBouteilleBlanc']);
$commande->setNombreBouteillePetillant($postCommande['nombreBouteillePetillant']);
$commande->setIsValideeParClient(false);
$commande->setDateCommandeSoumission($now);
if(isset($_POST['urgentCheckbox'])){
$commande->setFastPickup(true);
$commande->setIsValideeParClient(true);
}else{
$commande->setFastPickup(false);
}
if($emballageLivraison == true) {
$commande->setState('emballage_caviste');
}
else {
$commande->setState('preparation');
}
// TODO A RETIRER
$commande->setToken("gsrefgrdsgfres");
//$commande->setIsTemporaire(true);
$commande->setFedexPdfGenerated(false);
$commande->setFedexPdfAvailable(false);
//_____Colis_____
//Si on édite une commande temporaire
if ($commande->getId()) {
//On crée un array contenant les ids de tous les colis liés à cette commande
$colisThisCommande = $colisRepository->findColisByCommande($commande);
//$bddCommandes = [];
foreach ($colisThisCommande as $key => $colisEnBdd) {
$colis = $colisRepository->find($colisEnBdd);
$colisRepository->remove($colis);
}
// if (isset($postColis['update'])) {
// //On prend l'array colis[update] et pour chaque item, on update la quantité et on unset la key de l'array de colis
// foreach ($postColis['update'] as $idColis => $qteBouteilles) {
// $colis = $colisRepository->find($idColis);
// $colis->setNombreBouteille($qteBouteilles);
// $colis->setCommande($commande);
// $em->persist($colis);
// $em->flush();
// if (($arrayKey = array_search($idColis, $bddCommandes)) !== false) {
// unset($bddCommandes[$arrayKey]);
// }
// }
// }
// //Si il reste des keys dans l'array, on delete tout simplement les lignes concernées
// if (sizeof($bddCommandes) > 0) {
// foreach ($bddCommandes as $key => $bddCommande) {
// $colis = $colisRepository->find($bddCommande);
// // $colisRepository->remove($colis);
// }
// }
}
//Puis on crée de nouveaux colis pour les values de colis[new]
if (array_key_exists("new", $postColis)) {
foreach ($postColis['new'] as $postColi) {
$colis = new Colis();
$colis->setNombreBouteille($postColi);
$colis->setCommande($commande);
$em->persist($colis);
$em->flush();
$commande->addColi($colis);
}
}
if($nbBouteillesTotal > 36 && !$this->roleAdmin){
$commande->setCommandeMassive(true);
$this->emailGeneratorService->sendMassiveCommande($commande);
}
$em->persist($commande);
$em->flush();
$tokenPayload = [
"id"=> $commande->getId(),
/* "exp"=> strtotime("+1 week") */
];
$token = $this->utilsService->generateJWT($tokenPayload);
$url = $this->baseDomain . $this->generateUrl('app_client_final_validate', array('token' => $token));
//TODO send the validation email
$em->persist($commande);
$em->flush();
$indexData = [
'id' => $commande->getId(),
'numero_facture' => $commande->getNumeroFacture(),
'code_postal_livraison' => $commande->getCodePostalLivraison(),
'ville_livraison' => $commande->getVilleLivraison(),
];
$this->utilsService->updateIndex('commande', $indexData);
if($this->roleAdmin){
$payload = [
'id' => $commande->getId(),
/* 'exp' => time() + 604800 // one week validation */
];
$dateCreneau1Clone = clone $commande->getDateCollecte();
$dateCreneau2Clone = clone $commande->getDateCollecte();
if($commande->isEmballageLivraison()){
$dateCreneau1Brut = $dateCreneau1Clone->modify("+7 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+12 days");
} else {
$dateCreneau1Brut = $dateCreneau1Clone->modify("+22 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+27 days");
}
$dateCreneau1 = $dateCreneau1Brut->format('d/m/Y');
$dateCreneau2 = $dateCreneau2Brut->format('d/m/Y');
$token = $this->utilsService->generateJWT($payload);
$url = $this->baseDomain . $this->generateUrl('app_client_final_validate', array('token' => $token ));
$res = false;
if($commande->isFastPickup() != true){
$res = $this->emailGeneratorService->sendEmailToFinalCustomer(
$commande->getClientFinal()->getEmail(),
$commande->getClientFinal()->getFullName(),
$commande->getClient()->getRaisonSociale(),
$url,
false,
$dateCreneau1,
$dateCreneau2
);
}
}
return $this->redirectToRoute("app_recapitulatif_commande", ["id" => $commande->getId()], Response::HTTP_SEE_OTHER);
}
//Si l'user est admin, on ne prend pas en compte les commandes temporaires
if ($this->roleAdmin) {
$colisThisCommande = [];
return $this->renderForm('commande/new_admin.html.twig', [
'commande' => $commande,
'form' => $form,
'user' => $this->getUser(),
/* 'creneauxLivraison' => $creneauxLivraison, */
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
]);
//Si l'user est client
} else {
//Si le client a une commande isTemporaire == true, on le renvoie vers le form pré-rempli
if ($cmdTemporaire) {
$colisThisCommande = $colisRepository->findColisByCommande($cmdTemporaire);
return $this->renderForm('commande/new.html.twig', [
'commande' => $cmdTemporaire,
'form' => $form,
'user' => $this->getUser(),
'packing' => $cmdTemporaire->isEmballageLivraison() ? 'yes' : 'no',
/* 'creneauxLivraison' => $creneauxLivraison, */
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
]);
}
//Sinon on le renvoie vers le form vide
else {
$colisThisCommande = [];
return $this->renderForm('commande/new.html.twig', [
'commande' => $commande,
'form' => $form,
'user' => $this->getUser(),
/* 'creneauxLivraison' => $creneauxLivraison, */
'admin' => $this->roleAdmin,
'colisThisCommande' => $colisThisCommande,
'bandeau' => $this->bandeauService->displayPopup()
]);
}
}
}
/**
* @Route("/exportlist_commande_dsqde8cse9dx5fe8", name="commande_export_list", methods={"GET", "POST"})
*/
public function exportListCommand(Request $request, CommandeRepository $commandeRepository): Response
{
//need to fetch the commandes that need to be prepared
//for the admin only the one he need to pack
//for the caviste the one he need to prepare for mbe and the one he need to pack
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
if($this->roleAdmin){
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = "attente_collecte_mbe";
$commandes = $commandeRepository->findCommandesByCreneauByState($dateDebut, $dateFin, $state);
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
}else{
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = "preparation";
$commandes = $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut, $dateFin, $state, $user->getClient());
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
}
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$this->addFlash("error", "Le fichier Excel n'a pas pu être généré");
return $response;
}
/**
* @Route("/exportlist_commande_emb_dsqde8cse9dx5fe8", name="commande_export_list_emb", methods={"GET", "POST"})
*/
public function exportListCommandEmb(Request $request, CommandeRepository $commandeRepository): Response
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
if($this->roleAdmin){
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = "emballage_mbe";
$commandes = $commandeRepository->findCommandesByCreneauByState($dateDebut, $dateFin, $state);
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
} else {
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = "emballage_caviste";
$commandes = $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut, $dateFin, $state, $user->getClient());
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
}
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$this->addFlash("error", "Le fichier Excel n'a pas pu être généré");
return $response;
}
/**
* @Route("/exportlist_commande_all_dsqde8cse9dx5fe8", name="commande_export_list_all", methods={"GET", "POST"})
*/
public function exportListCommandAll(Request $request, CommandeRepository $commandeRepository): Response
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
if($this->roleAdmin){
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = null;
$commandes = $commandeRepository->findCommandesByCreneauByState($dateDebut, $dateFin, $state);
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
} else {
$dateDebut = $_POST["dateDebut"];
$dateFin = $_POST["dateFin"];
if($dateFin == "" || $dateDebut == ""){
$this->addFlash("error", "La date de début ou la date de fin n'est pas correcte");
}else{
$state = null;
$commandes = $commandeRepository->findCommandesByCreneauByStateByClient($dateDebut, $dateFin, $state, $user->getClient());
$this->addFlash("success", "Le fichier Excel a bien été généré");
return $this->createExcelCommandes($commandes);
}
}
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$this->addFlash("error", "Le fichier Excel n'a pas pu être généré");
return $response;
}
/**
* @Route("/checkDispo", name="app_check_dispo", methods={"GET", "POST"})
*/
public function checkDispo(CommandeRepository $commandeRepository): Response
{
//On recherche la date avant laquelle on ne peut pas accepter de collecte (j+2)
$now = new DateTime('now', new DateTimeZone('Europe/Paris')); //'2023-10-26 11:38:04.646428'
$dateMin = $now->modify("+2 days");
$dateMinDay = $dateMin->format('l');
//Si la date minimum tombe un week-end, on inclut le we dans les jours où on ne peut pas accepter de collecte
if($dateMinDay == 'Saturday') {
$dateMin->modify("+2 days");
$dateMinDay = $dateMin->format('l');
}
if($dateMinDay == 'Sunday') {
$dateMin->modify("+1 days");
$dateMinDay = $dateMin->format('l');
}
//On stocke la valeur de cette date min pour comparaison
$dateMinCompare = $dateMin->format('Y-m-d');
//Si une date est rensignée
if (isset($_POST['datevalue'])) {
$date = str_replace("/","-", htmlspecialchars($_POST['datevalue']));
}
$dateSaisie = date('Y-m-d', strtotime($date));
//On compare les dates.
//Si la date sélectionnée par l'utilisateur est antérieure à la date autorisée, on return une erreur.
if($dateSaisie < $dateMinCompare) {
return $this->json([
'success' => false,
'available' => false,
'dateClean' => '',
'dateCreneau1' => '',
'dateCreneau2' => '',
'dateCreneau1MBE' => '',
'dateCreneau2MBE' => ''
]);
}
//Pas de vérification du nombre de commandes sur le créneau si l'utilisateur est admin
$available = true;
$dateOk = new DateTime($date);
$dateCreneau1Clone = clone $dateOk;
$dateCreneau2Clone = clone $dateOk;
$dateCreneau1MBEClone = clone $dateOk;
$dateCreneau2MBEClone = clone $dateOk;
$dateCreneau1Brut = $dateCreneau1Clone->modify("+7 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+12 days");
$dateCreneau1BMBErut = $dateCreneau1MBEClone->modify("+22 days");
$dateCreneau2MEBrut = $dateCreneau2MBEClone->modify("+27 days");
$dateCreneau1 = $dateCreneau1Brut->format('d/m/Y');
$dateCreneau2 = $dateCreneau2Brut->format('d/m/Y');
$dateCreneau1MBE = $dateCreneau1BMBErut->format('d/m/Y');
$dateCreneau2MBE = $dateCreneau2MEBrut->format('d/m/Y');
if($this->roleAdmin){
return $this->json([
'success' => true,
'available' => $available,
'dateClean' => $dateOk->format('Y-m-d'),
'dateCreneau1' => $dateCreneau1,
'dateCreneau2' => $dateCreneau2,
'dateCreneau1MBE' => $dateCreneau1MBE,
'dateCreneau2MBE' => $dateCreneau2MBE
]);
}
//On vérifie le nombre de commandes sur le créneau si l'utilisateur n'est pas admin
else {
$commandes = $commandeRepository->findByDateCollecte($dateOk);
$dateOkClean = $dateOk->format('Y-m-d');
if(count($commandes) >= 35){
$available = false;
$dateOkClean = '';
$dateCreneau1 = '';
$dateCreneau2 = '';
$dateCreneau1MBE = '';
$dateCreneau2MBE = '';
}
return $this->json([
'success' => true,
'available' => $available,
'dateClean' => $dateOkClean,
'dateCreneau1' => $dateCreneau1,
'dateCreneau2' => $dateCreneau2,
'dateCreneau1MBE' => $dateCreneau1MBE,
'dateCreneau2MBE' => $dateCreneau2MBE
]);
}
}
/**
* @Route("/checkDefault", name="app_check_default", methods={"GET", "POST"})
*/
public function checkDefault(ClientRepository $clientRepository)
{
if (isset($_POST['clientId'])) {
$clientId = $_POST['clientId'];
if($this->roleAdmin){
$data = $clientRepository->findById($clientId);
return $this->json([
'defaultAssurance' => $data[0]->isAssuranceDefaut(),
'defaultPacking' => $data[0]->isEmballageDefaut(),
'fast' => $data[0]->isFastPickup()
]);
} else {
//TODO GET CLIENT DATA
}
}
}
/**
* @Route("/{id}/recapitulatif_commande", name="app_recapitulatif_commande", methods={"GET", "POST"})
*/
public function recapitulatif_commande(Commande $commande, ColisRepository $colisRepository): Response
{
$previDebut = clone $commande->getDateCollecte();
$previFin = clone $commande->getDateCollecte();
$dateLivraison = $this->translateCreneauLivraison($previDebut->modify("+7 days"), $previFin->modify("+12 days"));
/* $besoinConsentementDates = $this->besoinConsentementDates($commande->getDateDebutFenetre(), $commande->getDateFinFenetre()); */
$besoinConsentementDates = $this->besoinConsentementDates($previDebut->modify("+7 days"), $previFin->modify("+12 days"));
$colisThisCommande = $colisRepository->findColisByCommande($commande);
$nombreBouteillesRenseigneDansColis = 0;
foreach ($colisThisCommande as $key => $colisEnBdd) {
$nombreBouteillesRenseigneDansColis += $colisEnBdd->getNombreBouteille();
}
return $this->render('commande/recap_commande.html.twig', [
'commande' => $commande,
'admin' => $this->roleAdmin,
'user' => $this->getUser(),
'dateLivraison' => $dateLivraison,
'besoinConsentementDates' => $besoinConsentementDates,
'nombreBouteillesRenseigneDansColis' => $nombreBouteillesRenseigneDansColis
]);
}
/**
* @Route("/{id}/valider_commande_temporaire", name="app_valider_commande_temporaire", methods={"GET", "POST"})
*/
public function valider_commande_temporaire(string $id, CommandeRepository $commandeRepository, ColisRepository $colisRepository): Response
{
$em = $this->getDoctrine()->getManager();
$commande = $commandeRepository->find($id);
$colisThisCommande = $colisRepository->findColisByCommande($commande);
$nombreBouteillesRenseigneDansColis = 0;
foreach ($colisThisCommande as $key => $colisEnBdd) {
$nombreBouteillesRenseigneDansColis += $colisEnBdd->getNombreBouteille();
}
$totalMagnumsAttendu = ($commande->getNombreMagnumRouge() + $commande->getNombreMagnumBlanc() + $commande->getNombreMagnumPetillant()) * 2;
$totalBouteillesAttendu = $commande->getNombreBouteilleRouge() + $commande->getNombreBouteilleBlanc() + $commande->getNombreBouteillePetillant();
$totalAttendu = $totalMagnumsAttendu + $totalBouteillesAttendu;
if($nombreBouteillesRenseigneDansColis != $totalAttendu) {
return new Response("ErreurColis");
}
$commande->setIsTemporaire(false);
$em->persist($commande);
$em->flush();
//return new Response("OK");
//return new Response("NOPE");
//si la commande est valide on envois le mail de confirmation au client final
$payload = [
'id' => $commande->getId(),
/* 'exp' => time() + 604800 // one week validation */
];
$dateCreneau1Clone = clone $commande->getDateCollecte();
$dateCreneau2Clone = clone $commande->getDateCollecte();
if($commande->isEmballageLivraison()){
$dateCreneau1Brut = $dateCreneau1Clone->modify("+7 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+12 days");
} else {
$dateCreneau1Brut = $dateCreneau1Clone->modify("+22 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+27 days");
}
$dateCreneau1 = $dateCreneau1Brut->format('d/m/Y');
$dateCreneau2 = $dateCreneau2Brut->format('d/m/Y');
if(!$this->roleAdmin){
$token = $this->utilsService->generateJWT($payload);
$url = $this->baseDomain . $this->generateUrl('app_client_final_validate', array('token' => $token ));
$res = false;
if($commande->isFastPickup() != true){
$res = $this->emailGeneratorService->sendEmailToFinalCustomer(
$commande->getClientFinal()->getEmail(),
$commande->getClientFinal()->getFullName(),
$commande->getClient()->getRaisonSociale(),
$url,
false,
$dateCreneau1,
$dateCreneau2
);
}
$indexData = [
'id' => $commande->getId(),
'numero_facture' => $commande->getNumeroFacture(),
'code_postal_livraison' => $commande->getCodePostalLivraison(),
'ville_livraison' => $commande->getVilleLivraison(),
];
$this->utilsService->updateIndex('commande', $indexData, $commande->getId());
//var_dump($res);
if($res) {
if($commande->isFastPickup()){
return new JsonResponse(['message' => 'OK', 'fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
}else{
return new JsonResponse(['message' => 'OK', 'fastPickup' => false]);
}
return new Response("OK");
}
else {
if($commande->isFastPickup()){
return new JsonResponse(['message' => 'OK', 'fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
}else{
return new JsonResponse(['message' => 'ErreurMail', 'fastPickup' => false]);
}
return new Response("ErreurMail");
// return new Response("OK");
}
} else {
$indexData = [
'id' => $commande->getId(),
'numero_facture' => $commande->getNumeroFacture(),
'code_postal_livraison' => $commande->getCodePostalLivraison(),
'ville_livraison' => $commande->getVilleLivraison(),
];
$this->utilsService->updateIndex('commande', $indexData, $commande->getId());
if($commande->isFastPickup()){
return new JsonResponse(['message' => 'OK', 'fastPickup' => true,'url' => $this->generateUrl('app_commande_index')]);
}else{
return new JsonResponse(['message' => 'OK', 'fastPickup' => false]);
}
return new Response("OK");
}
}
/**
* @Route("/{id}/relance", name="relance_client_final", methods={"GET"})
*/
public function relanceClientFinal(Commande $commande, CommandeRepository $commandeRepository): Response
{
if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
//send the email to client final
$payload = [
'id' => $commande->getId(),
/* 'exp' => time() + 604800 // one week validation */
];
$dateCreneau1Clone = clone $commande->getDateCollecte();
$dateCreneau2Clone = clone $commande->getDateCollecte();
if($commande->isEmballageLivraison()){
$dateCreneau1Brut = $dateCreneau1Clone->modify("+7 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+12 days");
} else {
$dateCreneau1Brut = $dateCreneau1Clone->modify("+22 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+27 days");
}
$dateCreneau1 = $dateCreneau1Brut->format('d/m/Y');
$dateCreneau2 = $dateCreneau2Brut->format('d/m/Y');
$token = $this->utilsService->generateJWT($payload);
$url =$this->baseDomain . $this->generateUrl('app_client_final_validate', array('token' => $token ));
$res = false;
if($commande->isFastPickup() != true){
$res = $this->emailGeneratorService->sendEmailToFinalCustomer(
$commande->getClientFinal()->getEmail(),
$commande->getClientFinal()->getFullName(),
$commande->getClient()->getPrenomContact() . ' ' . $commande->getClient()->getNomContact(),
$url,
true,
$dateCreneau1,
$dateCreneau2
);
}
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}", name="app_commande_show", methods={"GET"})
*/
public function show(Commande $commande): Response
{
return $this->render('commande/show.html.twig', [
'commande' => $commande,
]);
}
/**
* @Route("/{id}/edit", name="app_commande_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, Commande $commande, CommandeRepository $commandeRepository, ColisRepository $colisRepository): Response
{
$oldFichier = $commande->getFichierFacture();
$oldFichierProForma = $commande->getFichierFactureProForma();
if ($this->roleAdmin) {
$form = $this->createForm(CommandeAdminType::class, $commande);
}
else {
$form = $this->createForm(CommandeType::class, $commande);
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$postColis = $_POST['colis'];
$postCommande = $_POST['commande_admin'];
$assuranceLivraison = $postCommande['assuranceLivraison'] == 'true' ? true : false ;
$emballagelivraison = $postCommande['emballageLivraison'] == 'true' ? true : false ;
$commande->setAssuranceLivraison($assuranceLivraison);
$commande->setEmballageLivraison($emballagelivraison);
if($emballagelivraison && $commande->getState() == 'preparation'){
$commande->setState('emballage_caviste');
}
if(!$emballagelivraison && $commande->getState() == 'emballage_caviste'){
$commande->setState('preparation');
}
if (($_POST['input_filename'] != '') && ($_POST['input_filename'] !== $oldFichier)) {
if (isset($_FILES)) {
if ($this->roleAdmin) {
$fileImage = $_FILES['commande_admin'];
} else {
$fileImage = $_FILES['commande'];
}
//$fileImage = $_FILES['commande'];
$name = $fileImage['name']['fichierFacture'];
$originalFilename = pathinfo($name, PATHINFO_FILENAME);
// $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
// $safeFilenameClean = $this->is_valid_filename($safeFilename);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$newFilename = 'facture_' . $commande->getClient()->getId() . '_' . uniqid() . '.' . $extension;
// Formats autorisés
$allowTypes = array('pdf','jpg','png','jpeg');
if(in_array($extension, $allowTypes)){
move_uploaded_file($fileImage['tmp_name']['fichierFacture'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
$commande->setFichierFacture($newFilename);
}
//On unlink l'ancien fichier
// if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
// unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
// }
}
}else{
$commande->setFichierFacture($oldFichier);
}
if (($_POST['input_filename_pro_forma'] != '') && ($_POST['input_filename_pro_forma'] !== $oldFichierProForma)) {
if (isset($_FILES)) {
if ($this->roleAdmin) {
$fileImage = $_FILES['commande_admin'];
} else {
$fileImage = $_FILES['commande'];
}
//$fileImage = $_FILES['commande'];
$name = $fileImage['name']['fichierFactureProForma'];
$originalFilename = pathinfo($name, PATHINFO_FILENAME);
// $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
// $safeFilenameClean = $this->is_valid_filename($safeFilename);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$newFilename = 'facture_pro_forma_' . $commande->getClient()->getId() . '_' . uniqid() . '.' . $extension;
// Formats autorisés
$allowTypes = array('pdf','jpg','png','jpeg','xls');
if(in_array($extension, $allowTypes)){
move_uploaded_file($fileImage['tmp_name']['fichierFactureProForma'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
$commande->setFichierFactureProForma($newFilename);
}
//On unlink l'ancien fichier
// if(file_exists("upload_Hk2DvAtDeUccGXh/".$oldFichier)) {
// unlink("upload_Hk2DvAtDeUccGXh/".$oldFichier);
// }
}
}else{
$commande->setFichierFactureProForma($oldFichierProForma);
}
$em = $this->getDoctrine()->getManager();
$colisThisCommande = $colisRepository->findColisByCommande($commande);
foreach ($colisThisCommande as $key => $colisEnBdd) {
$colis = $colisRepository->find($colisEnBdd);
$colisRepository->remove($colis);
}
if (array_key_exists("new", $postColis)) {
foreach ($postColis['new'] as $postColi) {
$colis = new Colis();
$colis->setNombreBouteille($postColi);
$colis->setCommande($commande);
$em->persist($colis);
$em->flush();
$commande->addColi($colis);
}
}
$nbMagnumSaisi = intval($postCommande['nombreMagnumRouge']) + intval($postCommande['nombreMagnumBlanc']) + intval($postCommande['nombreMagnumPetillant']);
$nbBouteillesSaisi = intval($postCommande['nombreBouteilleRouge']) + intval($postCommande['nombreBouteilleBlanc']) + intval($postCommande['nombreBouteillePetillant']);
$nbBouteillesTotal = ($nbMagnumSaisi * 2) + $nbBouteillesSaisi;
if($nbBouteillesTotal > 36 && !$this->roleAdmin){
$commande->setCommandeMassive(true);
$this->emailGeneratorService->sendMassiveCommande($commande);
}
$commandeRepository->add($commande, true);
$indexData = [
'id' => $commande->getId(),
'numero_facture' => $commande->getNumeroFacture(),
'code_postal_livraison' => $commande->getCodePostalLivraison(),
'ville_livraison' => $commande->getVilleLivraison(),
];
$this->utilsService->updateIndex('commande', $indexData, $commande->getId());
// exit();
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
$colisThisCommande = $colisRepository->findColisByCommande($commande);
return $this->renderForm('commande/edit.html.twig', [
'commande' => $commande,
'form' => $form,
'admin' => $this->roleAdmin,
'user' => $this->getUser(),
'colisThisCommande' => $colisThisCommande,
'edit' => true
]);
}
//i think this not used anymore, need to check
/**
* @Route("/{id}/packing", name="packing", methods={"GET"})
*/
public function emballageCommande(Commande $commande, CommandeRepository $commandeRepository): Response
{
/* if (!$this->roleAdmin) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
} */
if ($this->roleAdmin) {
$commande->setState("attente_pec_transporteur");
}
else {
if($commande->isIsValideeParClient() == true) {
$commande->setState("attente_pec_transporteur");
}
else {
$commande->setState("attente_client");
}
}
$commandeRepository->add($commande, true);
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/forcevalidate", name="validate_force", methods={"GET"})
*/
public function forceValidate(Commande $commande, CommandeRepository $commandeRepository): Response
{
$oldState = $commande->getState();
$cavistePacking = $commande->isEmballageLivraison();
if($cavistePacking){
$packing = "emballage_par_caviste";
} else {
$packing = "emballage_par_mbe";
}
if (!$this->roleAdmin) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
$commande->setIsValideeParClient(true);
if($commande->getState() == "attente_client"){
$commande->setState($commande->isEmballageLivraison() ? "attente_pec_transporteur" : "attente_collecte_mbe");
}
$commandeRepository->add($commande, true);
return $this->redirectToRoute('app_commande_index', ['state' => $oldState, 'packaging' => $packing], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/archive", name="archive", methods={"GET"})
*/
public function archiveCommande(Commande $commande, CommandeRepository $commandeRepository): Response
{
/* if (!$this->roleAdmin) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
} */
$commande->setState("archive");
$commandeRepository->add($commande, true);
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/creneau", name="update_creno", methods={"GET", "POST"})
*/
public function updateCreneau(Request $request, Commande $commande, CommandeRepository $commandeRepository): Response
{
if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
$form = $this->createForm(CommandeCreneauType::class, $commande);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() ) {
$commandeRepository->add($commande, true);
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('commande/creneau_update.html.twig', [
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
]);
}
/**
* @Route("/{id}/client", name="app_commande_client", methods={"GET", "POST"})
*/
public function listeCommandeClient(Request $request, Client $client, PaginatorInterface $paginator, CommandeRepository $commandeRepository): Response
{
$user = $this->getUser();
$data = $commandeRepository->findByClient($client->getId());
$state = null;
$commandes = $paginator->paginate(
$data,
$request->query->getInt('page', 1),
20
);
return $this->render('commande/index_commandes_par_client.html.twig', [
'nom_client' => $client->getRaisonSociale(),
'commandes' => $commandes,
'user' => $user,
'admin' => $this->roleAdmin,
]);
// return $this->render('commande/index.html.twig', [
// 'commandes' => $commandes,
// 'stateController' => $state,
// 'user' => $this->getUser(),
// 'admin' => $this->roleAdmin
// ]);
}
/**
* @Route("/{id}/updateState", name="app_commande_update_state", methods={"GET"})
*/
public function updateStatusCommande(Request $request, Commande $commande, CommandeRepository $commandeRepository): Response
{
//true = caviste
//false = mbe
$cavistePacking = $commande->isEmballageLivraison();
$clientFinalValidate = $commande->isIsValideeParClient();
$commandeState = $commande->getState();
$oldState = $commande->getState();
$newState = $commande->getState();
if($cavistePacking){
$packing = "emballage_par_caviste";
if($commandeState == "emballage_caviste"){
if($clientFinalValidate){
$newState = "attente_pec_transporteur";
} else {
$newState = "attente_client";
}
}
} else {
$packing = "emballage_par_mbe";
if($commandeState == "preparation"){
if($clientFinalValidate){
$newState = "attente_collecte_mbe";
} else {
$newState = "attente_client";
}
}
if($commandeState == "attente_collecte_mbe"){
$newState = "emballage_mbe";
}
if($commandeState == "emballage_mbe"){
$newState = "attente_pec_transporteur";
}
}
if($commandeState == "attente_pec_transporteur"){
$newState = "archive";
}
$commande->setState($newState);
$commandeRepository->add($commande, true);
$this->addFlash("success", "Le statut de la commande a été modifié");
return $this->redirectToRoute('app_commande_index', ['state' => $oldState, 'packaging' => $packing], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/undoState", name="app_commande_undo_state", methods={"GET"})
*/
public function undoStatusArchiveCommande(Request $request, Commande $commande, CommandeRepository $commandeRepository): Response
{
$commandeState = $commande->getState();
$newState = $commande->getState();
if($commandeState == "archive"){
$newState = "attente_pec_transporteur";
}
$commande->setState($newState);
$commandeRepository->add($commande, true);
$this->addFlash("success", "Le statut de la commande a été modifié");
return $this->redirectToRoute('app_commande_index', ['state' => $newState], Response::HTTP_SEE_OTHER);
}
public function getFedexToken()
{
$url = "https://apis.fedex.com/oauth/token";
$payload = "grant_type=client_credentials&client_id=l7c771e0d2fd444799b4ce63c4ccd10032&client_secret=7dacb43d3ecc4d239d27236f37a39075";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$json = json_decode($response, true);
curl_close($ch);
return $json['access_token'];
}
/**
* @Route("/{id}/fedex", name="fedex_info", methods={"GET"})
*/
public function getFedexShippingPdf(Commande $commande, CommandeRepository $commandeRepository): Response
{
$user = $this->getUser();
$client = $commande->getClient();
if (!$this->roleAdmin) {
if ($user != $client->getUser()) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
}
$accountNumber = "782780123";
$fedexToken = $this->getFedexToken();
$fedexEndpoint = "https://apis.fedex.com/ship/v1/shipments";
$totalBottles = $commande->getNombreBouteilleRouge() + $commande->getNombreBouteilleBlanc() + $commande->getNombreBouteillePetillant() + ($commande->getNombreMagnumRouge() * 2 ) + ($commande->getNombreMagnumBlanc() * 2 ) + ($commande->getNombreMagnumPetillant() * 2 );
$totalPrice = $commande->getMontantTotalFacture();
$weightOfAllPackage = $totalBottles * 1.5;
$bottleValue = round($totalPrice / $totalBottles, 2);
$commodities = '';
$requestedPackageLineItems = '';
$docs = '';
// parti colis
$colis = $commande->getColis();
$docIds = $this->getDocumentId($commande);
foreach($colis as $coli){
$bottles = $coli->getNombreBouteille();
$weight = $bottles * 1.5;
$commodities .= '{
"quantity": "1",
"unitPrice":{
"amount":"' . $bottleValue . '",
"currency":"EUR"
},
"customsValue": {
"amount": "' . $bottleValue * $bottles . '",
"currency": "EUR"
},
"quantityUnits":"PCS",
"description": "The carton consists of bottles of wine under 14% alchohol.",
"name":"Wine",
"countryOfManufacture": "FR",
"weight":{
"units":"KG",
"value":"' . $weight . '"
}
},';
$requestedPackageLineItems .= '{
"groupPackageCount": "1",
"subPackagingType": "OTHER",
"weight":{
"units":"KG",
"value":"' . $weight . '"
},
"packageSpecialServices": {
"specialServiceTypes": [
"ALCOHOL",
"SIGNATURE_OPTION"
],
"alcoholDetail": {
"alcoholRecipientType": "CONSUMER"
},
"signatureOptionType": "DIRECT"
}
},';
}
foreach($docIds as $docId){
$docs .= '{
"documentId": "' . $docId . '"
},';
}
//client final
$recipientsName = $commande->getClientFinal()->getFullName();
$recipientsPhone = $commande->getClientFinal()->getTelephone();
$recipientsAddress = $commande->getAdresseLivraison();
$recipientsAddressCompl = $commande->getComplementAdresseLivraison();
$recipientsCity = $commande->getVilleLivraison();
$recipientsStateOrProvinceCode = $commande->getEtatUs();
$recipientsPostalCode = $commande->getCodePostalLivraison();
$recipientsEmail = $commande->getClientFinal()->getEmail();
// A SAUVEGARDER, pour système notification.
// emailNotificationDetail: {
// "aggregationType": "PER_SHIPMENT",
// "emailNotificationRecipients": [
// {
// "name" : "' . $recipientsName . '",
// "emailNotificationRecipientType" : "RECIPIENT",
// "emailAddress" : "' . $recipientsEmail . '",
// "notificationFormatType" : "HTML",
// "locale" : "en_US",
// "notificationEventType" : ["ON_DELIVERY", "ON_EXCEPTION", "ON_SHIPMENT", "ON_TENDER", "ON_ESTIMATED_DELIVERY"]
// }
// ]
// },
if($recipientsAddressCompl && $recipientsAddressCompl != "" && $recipientsAddressCompl != " ") {
if(strlen($recipientsAddressCompl) < 35) {
$recipientsAddress .= '", "' . $recipientsAddressCompl;
}
else {
$partsAddressCompl = explode(" ", $recipientsAddressCompl);
$line1 = $line2 = "";
foreach ($partsAddressCompl as $key => $partAddressCompl) {
if((strlen($line1) + strlen($partAddressCompl)) < 35) {
$line1 .= $partAddressCompl . " ";
}
else if((strlen($line2) + strlen($partAddressCompl)) < 35) {
$line2 .= $partAddressCompl . " ";
}
}
if($line1 != "") {
$recipientsAddress .= '", "' . $line1;
}
if($line2 != "") {
$recipientsAddress .= '", "' . $line2;
}
}
}
// var_dump($commande->isDap());
// var_dump($commande->isServicePriority());
$prio = "INTERNATIONAL_ECONOMY";
if($commande->isServicePriority()){
// var_dump("on rentre dap");
$prio = "FEDEX_INTERNATIONAL_PRIORITY";
}else{
// var_dump("on rentre pas dap");
}
$typePayment = "SENDER";
if($commande->isDap()){
// var_dump("on rentre servicePriority");
$typePayment = "RECIPIENT";
}else{
// var_dump("on rentre pas servicePriority");
}
// exit();
$post = '{
"labelResponseOptions": "URL_ONLY",
"requestedShipment": {
"shipmentSpecialServices": {
"specialServiceTypes": [
"ELECTRONIC_TRADE_DOCUMENTS"
],
"etdDetail": {
"attachedDocuments":['. rtrim($docs, ',') .']
}
},
"customsClearanceDetail":{
"dutiesPayment":{
"paymentType":"'.$typePayment.'"
},
"commercialInvoice":{},
"commodities" : [' . rtrim($commodities, ',') . '],
"dutiesPayment":{
"payor":{
},
"billingDetails":{},
"paymentType": "'.$typePayment.'"
}
},
"shipper": {
"contact": {
"companyName" : "FR0011 MBE MERIGNAC VIN USA",
"phoneNumber": "1234567890"
},
"address": {
"streetLines": [
"FR0011 MBE MERIGNAC VIN USA",
"11, RUE JACQUARD"
],
"city": "MERIGNAC",
"postalCode": "33700",
"countryCode": "FR"
}
},
"recipients": [
{
"contact": {
"personName": "' . $recipientsName . '",
"phoneNumber": "' . $recipientsPhone . '"
},
"address": {
"streetLines": [
"' . $recipientsAddress . '"
],
"city": "' . $recipientsCity . '",
"stateOrProvinceCode": "' . $recipientsStateOrProvinceCode . '",
"postalCode": "' . $recipientsPostalCode . '",
"countryCode": "US"
}
}
],
"pickupType" : "CONTACT_FEDEX_TO_SCHEDULE",
"serviceType" : "'.$prio.'",
"packagingType" : "YOUR_PACKAGING",
"blockInsightVisibility": true,
"shippingChargesPayment": {
"paymentType": "SENDER"
},
"labelSpecification": {
"imageType": "PDF",
"labelStockType": "PAPER_LETTER"
},
"totalPackageCount":' . $commande->getNombreColisTotal() . ' ,
"requestedPackageLineItems": [' . rtrim($requestedPackageLineItems, ',') . ']
},
"accountNumber": {
"value": "' . $accountNumber . '"
}
}
';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $fedexEndpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => array(
'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
'x-locale: en_US',
'Content-Type: application/json',
'Authorization: Bearer ' . $fedexToken
),
));
$response = curl_exec($curl);
$json = json_decode($response, true);
if (isset($json['errors'])) {
foreach ($json['errors'] as $error) {
$this->addFlash("error", $error['message'] . '(Code erreur : "' . $error["code"] . '")');
}
} else {
$url = "";
$trackingNumbers = "";
if($commande->getNombreColisTotal() > 1){
$url = $json['output']['transactionShipments'][0]['shipmentDocuments'][0]['url'];
foreach($json['output']['transactionShipments'][0]['pieceResponses'] as $x ){
$trackingNumbers = $trackingNumbers . $x['trackingNumber'] . ', ' ;
}
$commande->setIndividualTrackingNumbers($trackingNumbers);
} else {
$url = $json['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0]['url'];
}
$trackingNumber = $json['output']['transactionShipments'][0]['masterTrackingNumber'];
$numFacture = $this->is_valid_filename($commande->getNumeroFacture());
$fileName = 'shipping_' . $trackingNumber . '.pdf';
file_put_contents('etiquette_eXfdeEI18e68F48E6f4e89/' . $fileName, fopen($url, 'r'));
$fileContent = file_get_contents('etiquette_eXfdeEI18e68F48E6f4e89/' . $fileName);
$magicBytes = substr($fileContent, 0, 4); // Read the first 4 bytes
$date = new DateTime($json['output']['transactionShipments'][0]["shipDatestamp"]);
// Check if the first 4 bytes match the PDF file signature
if ($magicBytes === "%PDF") {
$commande->setFedexPdfGenerated(true);
$commande->setTrackingNumber($trackingNumber);
$commande->setShipDate($date);
$commandeRepository->add($commande, true);
$this->addFlash("success", "PDF généré");
// Email envoi caviste uniquement $commande->isEmballageLivraison() == 'emballage_par_caviste' en pièce jointe le PDF
if($commande->isEmballageLivraison()){
$this->emailGeneratorService->sendFedexShippingDocument($commande, $client);
}
$indexData = [
'id' => $commande->getId(),
'numero_facture' => $commande->getNumeroFacture(),
'code_postal_livraison' => $commande->getCodePostalLivraison(),
'ville_livraison' => $commande->getVilleLivraison(),
'tracking_number' => $trackingNumber,
];
$this->utilsService->updateIndex('commande', $indexData, $commande->getId());
$dateCreneau1Clone = clone $commande->getDateCollecte();
$dateCreneau2Clone = clone $commande->getDateCollecte();
if($commande->isEmballageLivraison()){
$dateCreneau1Brut = $dateCreneau1Clone->modify("+7 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+12 days");
} else {
$dateCreneau1Brut = $dateCreneau1Clone->modify("+22 days");
$dateCreneau2Brut = $dateCreneau2Clone->modify("+27 days");
}
$dateCreneau1 = $dateCreneau1Brut->format('d/m/Y');
$dateCreneau2 = $dateCreneau2Brut->format('d/m/Y');
$numeroSuivi = $commande->getTrackingNumber();
$linkTracking = 'https://www.fedex.com/fedextrack/?trknbr='.$numeroSuivi.'&trkqual=2460581000~'.$numeroSuivi.'~FX';
$res = $this->emailGeneratorService->sendEmailToFinalCustomerTrack(
$commande->getClientFinal()->getEmail(),
$commande->getClientFinal()->getFullName(),
$commande->getClient()->getRaisonSociale(),
$dateCreneau1,
$dateCreneau2,
$numeroSuivi,
$linkTracking
);
} else {
$this->addFlash("error", "PDF non généré");
$this->cancelFedex($trackingNumber);
}
}
curl_close($curl);
return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur', 'packaging' => $commande->isEmballageLivraison() ? 'emballage_par_caviste' : 'emballage_par_mbe'], Response::HTTP_SEE_OTHER);
}
public function getDocumentId(Commande $commande)
{
$this->csv_facture($commande, true);
$numFacture = $this->is_valid_filename($commande->getNumeroFacture());
$docIds = [];
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSITTBPermitCA-I-22023V2.pdf', 'importerPermitInfo.pdf', 'application/pdf', 'OTHER');
if($commande->getFichierFactureProForma() != null){
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./upload_Hk2DvAtDeUccGXh/'.$commande->getFichierFactureProForma(), $commande->getFichierFactureProForma(), 'application/vnd.ms-excel', 'PRO_FORMA_INVOICE');
}else{
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/'.$commande->getProForma(), 'proInvoice_' . $numFacture . '.xls', 'application/vnd.ms-excel', 'PRO_FORMA_INVOICE');
}
if($commande->getNombreBouteilleRouge() > 0 || $commande->getNombreMagnumRouge() > 0){
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaVinDeFranceROUGE.pdf', 'CSIColaVinDeFranceROUGE.pdf', 'application/pdf', 'OTHER');
}
if($commande->getNombreBouteilleBlanc() > 0 || $commande->getNombreMagnumBlanc() > 0){
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaVinDeFranceBLANC.pdf', 'CSIColaVinDeFranceBLANC.pdf', 'application/pdf', 'OTHER');
}
if($commande->getNombreBouteillePetillant() > 0 || $commande->getNombreMagnumPetillant() > 0){
$docIds[] = $this->fedexService->uploadDocumentPreShipFedex('./doc_kyseUa8iCjUywtKtgu8J/CSIColaCHAMPAGNE.pdf', 'CSIColaCHAMPAGNE.pdf', 'application/pdf', 'OTHER');
}
return $docIds;
}
/**
* @Route("/{id}/addDocument", name="app_commande_add_document", methods={"GET", "POST"})
*/
public function addDocumentPostShip(Commande $commande, CommandeRepository $commandeRepository, Request $request) : Response
{
if (!$this->roleAdmin && $this->getUser()->getClient() != $commande->getClient() ) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
$form = $this->createFormBuilder()
->add('document', FileType::class, [
"label" => "Choisir un fichier",
"required" => true,
"data_class" => null,
"attr" => ["hidden" => true, "name" => "myFile", "class" => "drop-zone__input"],
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$file = $_FILES['myFile'];
$name = $file['name'];
$originalFilename = pathinfo($name, PATHINFO_FILENAME);
// $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
// $safeFilenameClean = $this->is_valid_filename($safeFilename);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$newFilename = 'prior_' . $commande->getTrackingNumber() . '_' . uniqid() . '.' . $extension;
// Formats autorisés
$allowTypes = array('pdf','jpg','png','jpeg');
if(in_array($extension, $allowTypes)){
move_uploaded_file($file['tmp_name'],"upload_Hk2DvAtDeUccGXh/".$newFilename);
}
$res = $this->fedexService->uploadDocumentPostShipFedex("upload_Hk2DvAtDeUccGXh/".$newFilename, 'document.pdf', 'application/pdf', 'OTHER', $commande->getTrackingNumber(), $commande->getShipDate());
if($res == 'error'){
$this->addFlash("error", "Erreur Document non ajouté");
} else {
$this->addFlash("success", "Document ajouté");
$commande->setFedexPdfAvailable(true);
$commande->setPriorUrl($newFilename);
$commandeRepository->add($commande, true);
}
return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur', 'packaging' => $_GET['packing']], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('commande/addDocument.html.twig', [
'form' => $form,
'user' => $this->getUser(),
'admin' => $this->roleAdmin,
]);
}
/**
* @Route("/{id}/cancelshipping", name="app_commande_cancel_shipping", methods={"GET"})
*/
public function cancelShipping(Commande $commande, CommandeRepository $commandeRepository) : Response
{
$fedexCommandeTokken = $commande->getTrackingNumber();
$fileName = 'etiquette_eXfdeEI18e68F48E6f4e89/shipping_' . $fedexCommandeTokken . '.pdf';
$priorName = $commande->getPriorUrl();
$res = $this->cancelFedex($fedexCommandeTokken);
if($res["output"]["cancelledShipment"]){
$commande->setFedexPdfGenerated(false);
$commande->setTrackingNumber(NULL);
$commande->setShipDate(NULL);
$commande->setFedexPdfAvailable(false);
$commande->setPriorUrl(NULL);
$commande->setIndividualTrackingNumbers(NULL);
$commandeRepository->add($commande, true);
if (file_exists($fileName)) {
unlink($fileName);
}
if (file_exists($priorName)) {
unlink($priorName);
}
$this->addFlash("success", "Commande annulée");
} else {
$this->addFlash("error", "La commande n'a pas été annulée");
}
return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur'], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/cancelCommande", name="app_commande_cancel", methods={"GET"})
*/
public function cancelCommande(Commande $commande, CommandeRepository $commandeRepository) : Response
{
$fedexCommandeTokken = $commande->getTrackingNumber();
if($fedexCommandeTokken) {
$res = $this->cancelFedex($fedexCommandeTokken);
}
if(!$fedexCommandeTokken || $res["output"]["cancelledShipment"]){
$commande->setFedexPdfGenerated(false);
$commande->setTrackingNumber(NULL);
$commande->setShipDate(NULL);
$commande->setFedexPdfAvailable(false);
$commande->setState('canceled');
$commandeRepository->add($commande, true);
$this->addFlash("success", "Commande annulée");
} else {
$this->addFlash("error", "La commande n'a pas été annulée");
}
return $this->redirectToRoute('app_commande_index', ['state' => 'attente_pec_transporteur'], Response::HTTP_SEE_OTHER);
}
private function cancelFedex($trackingNumber)
{
$fedexEndpoint = 'https://apis.fedex.com/ship/v1/shipments/cancel';
$payload = '{
"trackingNumber": " ' . $trackingNumber . ' ",
"senderCountryCode": "FR",
"deletionControl": "DELETE_ALL_PACKAGES",
"accountNumber": {
"value": "782780123"
}
}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $fedexEndpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => array(
'x-customer-transaction-id: 624deea6-b709-470c-8c39-4b5511281492',
'x-locale: en_US',
'Content-Type: application/json',
'Authorization: Bearer ' . $this->getFedexToken()
),
));
$response = curl_exec($curl);
$json = json_decode($response, true);
return $json;
}
/**
* @Route("/{id}", name="app_commande_delete", methods={"POST"})
*/
// public function delete(Request $request, Commande $commande, CommandeRepository $commandeRepository): Response
// {
// if ($this->isCsrfTokenValid('delete' . $commande->getId(), $request->request->get('_token'))) {
// $commandeRepository->remove($commande, true);
// }
// return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
// }
/**
* @Route("/{id}/csv_invoice", name="csv_invoice", methods={"GET"})
*/
public function csv_facture(Commande $commande, $internalCall = false): Response
{
$user = $this->getUser();
$client = $commande->getClient();
if (!$this->roleAdmin) {
if ($user != $client->getUser()) {
return $this->redirectToRoute('app_commande_index', [], Response::HTTP_SEE_OTHER);
}
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$writer = new Xls($spreadsheet);
$fileName = $commande->getClientFinal()->getFullName() . " Invoice";
$sheet = $spreadsheet->getActiveSheet();
//Styling the sheet
//invoice data block
$sheet->mergeCells('B2:C2');
$sheet->mergeCells('B3:C3');
//shipper block
$sheet->mergeCells('A7:B7');
$sheet->mergeCells('A8:B8');
$sheet->mergeCells('A9:B9');
$sheet->mergeCells('A10:B10');
$sheet->mergeCells('A11:B11');
$sheet->mergeCells('A12:B12');
//importer/delivery block
$sheet->mergeCells('E2:F2');
$sheet->mergeCells('E3:F3');
$sheet->mergeCells('E4:F4');
$sheet->mergeCells('E5:F5');
$sheet->mergeCells('E6:F6');
$sheet->mergeCells('E7:F7');
$sheet->mergeCells('E8:F8');
$sheet->mergeCells('G2:H2');
$sheet->mergeCells('G3:H3');
$sheet->mergeCells('G4:H4');
$sheet->mergeCells('G5:H5');
$sheet->mergeCells('G6:H6');
$sheet->mergeCells('G7:H7');
$sheet->mergeCells('G8:H8');
$sheet->mergeCells('G9:H9');
$sheet->mergeCells('E10:H10');
$sheet->mergeCells('E11:H11');
$sheet->mergeCells('E12:H12');
//manufacturer/producer block
$sheet->mergeCells('A23:E23');
$sheet->mergeCells('A25:B25');
$sheet->mergeCells('A26:B26');
$sheet->mergeCells('A27:B27');
$sheet->mergeCells('A28:B28');
$sheet->mergeCells('A29:B29');
$sheet->mergeCells('A30:B30');
$sheet->getColumnDimension('A')->setWidth(93, 'px');
$sheet->getColumnDimension('B')->setWidth(237, 'px');
$sheet->getColumnDimension('C')->setWidth(105, 'px');
$sheet->getColumnDimension('D')->setWidth(88, 'px');
$sheet->getColumnDimension('E')->setWidth(128, 'px');
$sheet->getColumnDimension('F')->setWidth(111, 'px');
$sheet->getColumnDimension('G')->setWidth(91, 'px');
$sheet->getColumnDimension('H')->setWidth(217, 'px');
$sheet->getColumnDimension('I')->setWidth(95, 'px');
$styleBorder = [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
'color' => ['argb' => '00000000'],
],
],
];
$styleBold = [
'font' => [
'bold' => true,
],
];
$styleLink = [
'font' => [
'color' => array('rgb' => '006fbf'),
'underline' => true,
],
];
$sheet->getStyle('A2')->applyFromArray($styleBorder);
//$sheet->getStyle('A3:A4')->applyFromArray($styleBorder);
$sheet->getStyle('A2:C3')->applyFromArray($styleBorder);
//$sheet->getStyle('B3:C4')->applyFromArray($styleBorder);
$sheet->getStyle('A7:B12')->applyFromArray($styleBorder);
$sheet->getStyle('A25:B30')->applyFromArray($styleBorder);
$sheet->getStyle('E2:F2')->applyFromArray($styleBorder);
$sheet->getStyle('G2:h2')->applyFromArray($styleBorder);
$sheet->getStyle('E3:F10')->applyFromArray($styleBorder);
$sheet->getStyle('G3:H10')->applyFromArray($styleBorder);
$sheet->getStyle('E10:H10')->applyFromArray($styleBorder);
$sheet->getStyle('E11:H11')->applyFromArray($styleBorder);
$sheet->getStyle('E12:H12')->applyFromArray($styleBorder);
$sheet->getStyle('A15:I18')->applyFromArray($styleBorder);
// $sheet->getStyle('A25:E25')->applyFromArray($styleBorder);
// $sheet->getStyle('A26:E26')->applyFromArray($styleBorder);
// $sheet->getStyle('A27:E27')->applyFromArray($styleBorder);
$sheet->getStyle('A2:A7')->applyFromArray($styleBold);
$sheet->getStyle('E2:H9')->applyFromArray($styleBold);
$sheet->getStyle('E10:H13')->applyFromArray($styleBold);
$sheet->getStyle('A23:G29')->applyFromArray($styleBold);
$sheet->getStyle('A12')->applyFromArray($styleLink);
$sheet->getStyle('E8:F8')->applyFromArray($styleLink);
$sheet->getStyle('G9:H9')->applyFromArray($styleLink);
$sheet->getStyle('A30')->applyFromArray($styleLink);
$sheet->getStyle('G23:H25')
->getBorders()
->getAllBorders()
->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM)
->setColor(new Color('00000000'));
$sheet->getStyle('A15:I18')
->getBorders()
->getInside()
->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN)
->setColor(new Color('00000000'));
$sheet->getStyle('A2:C3')
->getBorders()
->getInside()
->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN)
->setColor(new Color('00000000'));
$sheet->getStyle('A15:H18')->getAlignment()->setWrapText(true);
$sheet->getStyle('A1:I30')->getAlignment()->setHorizontal('center');
$sheet->getStyle('A1:I30')->getAlignment()->setVertical('center');
$sheet->getStyle('A20:B22')->getAlignment()->setHorizontal('left');
$sheet->setShowGridlines(false);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Paid');
$drawing->setDescription('Paid');
$drawing->setPath('https://wine.mbebordeaux.fr/images/PNG/mbe.png');
$drawing->setCoordinates('G26');
$drawing->setOffsetX(110);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
//Sheet content
//fixed value
$sheet->setCellValue('A2', 'DATE');
$sheet->setCellValue('A3', 'INVOICE NO.');
//$sheet->setCellValue('A4', 'EORI ');
$sheet->setCellValue('A7', 'MANUFACTURER');
// $sheet->setCellValue('A8', 'MBE011 Mérignac');
// $sheet->setCellValue('A9', '11, Rue Jacquard');
// $sheet->setCellValue('A10', '33700 MERIGNAC');
// $sheet->setCellValueExplicit('A11', '+33535546864', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
// $sheet->setCellValue('A12', 'mbe011@mbefrance.fr');
// $sheet->getCell('A12')->getHyperlink()->setUrl('mailto:mbe011@mbefrance.fr');
$sheet->setCellValue('A15', 'COUNTRY OF ORIGIN');
$sheet->setCellValue('B15', 'DESCRIPTION');
$sheet->setCellValue('C15', 'ALCOHOL %');
$sheet->setCellValue('D15', 'HTS NUMBER');
$sheet->setCellValue('E15', 'TTB ID NUMBER');
$sheet->setCellValue('F15', 'No. Bottles');
$sheet->setCellValue('G15', 'Unit Quantity');
$sheet->setCellValue('H15', 'TOTAL QUANTITY (LITERS)');
$sheet->setCellValue('I15', 'TOTAL VALUE');
$sheet->setCellValue('A20', 'INCOTERM : ');
if($commande->isDap()){
$sheet->setCellValue('B20', 'DAP');
}else{
$sheet->setCellValue('B20', 'DDP');
}
$sheet->setCellValue('A21', 'The Exporter of the products covered by this document declares that, except where otherwise clearly indicated, these products are of European Union preferentiel origin.');
$sheet->setCellValue('A22', 'Origin : ');
$sheet->setCellValue('B22', 'France');
$sheet->setCellValue('A23', 'Bottle with CRD Capsule - Duty free - DAE not established - Personnal Consumption');
$sheet->setCellValue('A25', 'SHIPPER');
// $sheet->setCellValue('E2', 'Bottle with CRD Capsule - Duty free - DAE not established - Personnal Consumption');
// $sheet->setCellValue('E4', 'ISC');
$sheet->setCellValue('E2', 'IMPORTER ADDRESS');
$sheet->setCellValue('E4', 'Ilona Liberi DBA Chianti Services Imports');
$sheet->setCellValue('E5', '3141 Temescal Avenue');
$sheet->setCellValue('E6', 'Norco, CA 92860');
$sheet->setCellValue('E7', '(949)306-3678');
$sheet->setCellValue('E8', 'ilonaliberi@chiantiservicesimports.com');
$sheet->getCell('E8')->getHyperlink()->setUrl('mailto:ilonaliberi@chiantiservicesimports.com');
$sheet->setCellValue('G2', 'DELIVERY ADDRESS');
$sheet->setCellValue('E10', 'TAX ID 81-5435990 ');
$sheet->setCellValue('E11', 'TTB PERMIT CA - I - 22023');
$sheet->setCellValue('E12', 'DUNS #08 084 6225 ');
$sheet->setCellValue('G23', 'TOTAL VALUE:');
$sheet->setCellValue('G24', 'TOTAL LITERS: ');
$sheet->setCellValue('G25', 'TOTAL Bottles: ');
//not fixed value
$eori = $client->getEori();
$invoiceNo = $commande->getNumeroFacture();
$orderDate = date('d-M-y');
$finalClientName = $commande->getClientFinal()->getFullName();
$finalClientAdress = $commande->getAdresseLivraison();
$finalClientCity = $commande->getVilleLivraison();
$finalClientPhone = $commande->getClientFinal()->getTelephone();
$finalClientEmail = $commande->getClientFinal()->getEmail();
$clientInfo = $client->getNomContact() . " - " . $client->getAdresse() . " " . $client->getCodePostal() . " " . $client->getVille();
$bottlesRed = $commande->getNombreBouteilleRouge() + ( $commande->getNombreMagnumRouge() * 2 );
$bottlesWhite = $commande->getNombreBouteilleBlanc() + ( $commande->getNombreMagnumBlanc() * 2 );
$bottlesSparkling = $commande->getNombreBouteillePetillant() + ( $commande->getNombreMagnumPetillant() * 2 );
$totalBottles = $bottlesRed + $bottlesWhite + $bottlesSparkling;
$totalPrice = $commande->getMontantTotalFacture();
$bottlePrice = $totalPrice / $totalBottles;
$sheet->setCellValue('B3', $invoiceNo);
//$sheet->setCellValue('B4', $eori);
$sheet->setCellValue('B2', $orderDate);
$sheet->setCellValue('G3', $finalClientName);
$sheet->setCellValue('G4', $finalClientAdress);
$sheet->setCellValue('G5', $commande->getComplementAdresseLivraison());
$sheet->setCellValue('G6', $finalClientCity . ' , ' . $commande->getCodePostalLivraison() . ' , ' . $commande->getProvince());
$sheet->setCellValue('G7', 'USA');
$sheet->setCellValueExplicit('G8', $finalClientPhone, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('G9', $finalClientEmail);
$sheet->getCell('G9')->getHyperlink()->setUrl('mailto:' . $finalClientEmail);
$sheet->setCellValue('H25', $totalBottles);
$sheet->setCellValue('H24', $totalBottles * 0.75);
$sheet->setCellValue('H23', $totalPrice . " €");
$sheet->setCellValue('A26', 'MBE011 Mérignac');
$sheet->setCellValue('A27', '11, Rue Jacquard');
$sheet->setCellValue('A28', '33700 MERIGNAC');
$sheet->setCellValueExplicit('A29', '+33535546864', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('A30', 'mbe011@mbefrance.fr');
$sheet->getCell('A30')->getHyperlink()->setUrl('mailto:mbe011@mbefrance.fr');
$sheet->setCellValue('A8', $client->getRaisonSociale());
$sheet->setCellValue('A9', $client->getAdresse());
$sheet->setCellValue('A10', $client->getVille() . " / France / " . $client->getCodePostal());
$sheet->setCellValue('A11', $eori);
$sheet->setCellValue('A12', $client->getEmailContact());
$sheet->getCell('A12')->getHyperlink()->setUrl('mailto:' . $client->getEmailContact());
$bI = 16;
if ($bottlesRed > 0) {
$sheet->setCellValue('A' . $bI, 'FRANCE');
$sheet->setCellValue('B' . $bI, 'Red Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
$sheet->setCellValue('C' . $bI, '<= 14 %');
$sheet->setCellValue('D' . $bI, '2204215040');
$sheet->setCellValueExplicit('E' . $bI, '18216001000126', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('F' . $bI, $bottlesRed);
$sheet->setCellValue('G' . $bI, '0,75');
$sheet->setCellValue('H' . $bI, $bottlesRed * 0.75);
$sheet->setCellValue('I' . $bI, round($bottlesRed * $bottlePrice, 2) . " €");
$bI++;
}
if ($bottlesWhite > 0) {
$sheet->setCellValue('A' . $bI, 'FRANCE');
$sheet->setCellValue('B' . $bI, 'White Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
$sheet->setCellValue('C' . $bI, '<= 14 %');
$sheet->setCellValue('D' . $bI, '2204215055');
$sheet->setCellValueExplicit('E' . $bI, '18216001000127', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('F' . $bI, $bottlesWhite);
$sheet->setCellValue('G' . $bI, '0,75');
$sheet->setCellValue('H' . $bI, $bottlesWhite * 0.75);
$sheet->setCellValue('I' . $bI, round($bottlesWhite * $bottlePrice, 2) . " €");
$bI++;
}
if ($bottlesSparkling > 0) {
$sheet->setCellValue('A' . $bI, 'FRANCE');
$sheet->setCellValue('B' . $bI, 'Sparkling Table Wine - Bottle with CRD Capsule - Duty free - DAE not established ');
$sheet->setCellValue('C' . $bI, '<= 14 %');
$sheet->setCellValue('D' . $bI, '2204215075');
$sheet->setCellValueExplicit('E' . $bI, '18216001000125', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$sheet->setCellValue('F' . $bI, $bottlesSparkling);
$sheet->setCellValue('G' . $bI, '0,75');
$sheet->setCellValue('H' . $bI, $bottlesSparkling * 0.75);
$sheet->setCellValue('I' . $bI, round($bottlesSparkling * $bottlePrice, 2) . " €");
}
$unique = uniqid();
if($internalCall){
$em = $this->getDoctrine()->getManager();
$path = './doc_kyseUa8iCjUywtKtgu8J/'.$unique.'_tmp.xls';
$writer->save($path);
$commande->setProForma($unique.'_tmp.xls');
$em->persist($commande);
$em->flush();
}
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="' . $fileName . '.xls"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* Si vous utilisez les annotations, activez sensio/framework-extra-bundle.
*
* @Route("/commande/toggle", name="commande_toggle", methods={"POST"})
*/
public function toggle(
Request $request,
CsrfTokenManagerInterface $csrfManager
): JsonResponse {
$em = $this->getDoctrine()->getManager();
// 1. Récupération et décodage du JSON
$data = json_decode($request->getContent(), true);
if (!\is_array($data)) {
return new JsonResponse([
'status' => 'error',
'message' => 'Données JSON invalides.'
], 400);
}
// 2. Vérification du token CSRF
$submittedToken = $request->headers->get('X-CSRF-TOKEN');
if (!$csrfManager->isTokenValid(new CsrfToken('toggle-commande', $submittedToken))) {
return new JsonResponse([
'status' => 'error',
'message' => 'Jeton CSRF invalide.'
], 400);
}
// 3. Validation des paramètres
$id = $data['commandeId'] ?? null;
$field = $data['field'] ?? null;
$value = $data['value'] ?? null;
if (null === $id || !\in_array($field, ['dap', 'priority'], true) || !\in_array($value, [0,1], true)) {
return new JsonResponse([
'status' => 'error',
'message' => 'Paramètres manquants ou invalides.'
], 400);
}
// 4. Récupération de l’entité
/** @var Commande|null $commande */
$commande = $em->getRepository(Commande::class)->find($id);
if (null === $commande) {
return new JsonResponse([
'status' => 'error',
'message' => 'Commande introuvable.'
], 404);
}
// 5. Mise à jour du champ demandé
if ('dap' === $field) {
$commande->setDap((bool) $value);
} else {
$commande->setServicePriority((bool) $value);
}
// 6. Persistance
$em->persist($commande);
$em->flush();
// 7. Réponse JSON
return new JsonResponse([
'status' => 'success',
]);
}
function isCreneauActif($commandeRepository, $dateCreneau)
{
if (intval($commandeRepository->countCommandesByCreneau($dateCreneau)) < 500000000) {
$isCreneauActif = true;
} else {
$isCreneauActif = false;
}
return $isCreneauActif;
}
function createCreneauxLivraison($commandeRepository, $nombreCreneauxACreer)
{
$creneauxLivraison = [];
$jourDebut = intval(date("d"));
$moisDebut = intval(date("m"));
$anneeDebut = intval(date("Y"));
$init1 = true;
$init2 = true;
for ($i = 0; $i < $nombreCreneauxACreer; $i++) {
switch (true) {
//créneau du 1er au 5
case $jourDebut < '6':
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-16';
$dateFinCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-' . $this->utilsService->getDernierJourMois($moisDebut, $anneeDebut);
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 16 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> ' . $this->utilsService->getDernierJourMois($moisDebut, $anneeDebut) . ' ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
$jourDebut += 5;
break;
//créneau du 6 au 10
case $jourDebut < '11':
if (intval($moisDebut) == 12) {
$moisSuivant = '01';
$anneeFin = $anneeDebut + 1;
} else {
$moisSuivant = intval($moisDebut) + 1;
$anneeFin = $anneeDebut;
}
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-21';
$dateFinCreneau = strval($anneeFin) . '-' . sprintf('%02d', strval($moisSuivant)) . '-05';
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 21 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 5 ' . $this->utilsService->getMoisToutesLettres($moisSuivant) . '</strong>';
$jourDebut += 5;
break;
//créneau du 11 au 15
case $jourDebut < '16':
if (intval($moisDebut) == 12) {
$moisSuivant = '01';
$anneeFin = $anneeDebut + 1;
} else {
$moisSuivant = intval($moisDebut) + 1;
$anneeFin = $anneeDebut;
}
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-26';
$dateFinCreneau = strval($anneeFin) . '-' . sprintf('%02d', strval($moisSuivant)) . '-10';
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 26 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 10 ' . $this->utilsService->getMoisToutesLettres($moisSuivant) . '</strong>';
$jourDebut += 5;
break;
//créneau du 16 au 20
case $jourDebut < '21':
//On vérifie le mois suivant
if ($moisDebut != 12) {
$moisDebut += 1;
} else {
$moisDebut = '01';
$anneeDebut += 1;
}
$init1 = false;
$init2 = false;
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-01';
$dateFinCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-15';
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 1<sup>er</sup> ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 15 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
$jourDebut += 5;
break;
//créneau du 21 au 25
case $jourDebut < '26':
//Calcul selon la date du mois en cours
if ($init1 == true) {
if ($moisDebut != 12) {
$moisDebut += 1;
} else {
$moisDebut = '01';
$anneeDebut += 1;
}
$init1 = false;
$init2 = false;
}
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-06';
$dateFinCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-20';
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 6 ' . $this->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 20 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
$jourDebut += 5;
break;
//créneau du 26 à la fin du mois
default:
//Calcul selon la date du mois en cours
if ($init2 == true) {
if ($moisDebut != 12) {
$moisDebut += 1;
} else {
$moisDebut = '01';
$anneeDebut += 1;
}
$init1 = false;
$init2 = false;
}
$jourDebut = 1;
$dateDebutCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-11';
$dateFinCreneau = strval($anneeDebut) . '-' . sprintf('%02d', strval($moisDebut)) . '-25';
$creneauxLivraison[$i]['creneauDebut'] = $dateDebutCreneau;
$creneauxLivraison[$i]['creneauFin'] = $dateFinCreneau;
$creneauxLivraison[$i]['creneauActif'] = $this->isCreneauActif($commandeRepository, $dateDebutCreneau);
$creneauxLivraison[$i]['creneauToutesLettres'] = 'du <strong> 11 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong><br/> au <br/><strong> 25 ' . $this->utilsService->getMoisToutesLettres($moisDebut) . '</strong>';
break;
}
}
return $creneauxLivraison;
}
function translateCreneauLivraison($dateDebut, $dateFin)
{
$dateDebut = $dateDebut->format('Y-m-d');
$dateDebutPieces = explode("-", $dateDebut);
$dateFin = $dateFin->format('Y-m-d');
$dateFinPieces = explode("-", $dateFin);
$dateString = "du <strong>" . $dateDebutPieces[2] . " " . $this->utilsService->getMoisToutesLettres($dateDebutPieces[1]) . "</strong> au <strong>" . $dateFinPieces[2] . " " . $this->utilsService->getMoisToutesLettres($dateFinPieces[1]) . "</strong>";
return $dateString;
}
function besoinConsentementDates($dateDebut, $dateFin)
{
$dateDebut = $dateDebut->format('md');
$dateFin = $dateFin->format('md');
$dateDebutIndispo = "0615";
$dateFinIndispo = "1015";
if ($dateDebut >= $dateDebutIndispo && $dateDebut <= $dateFinIndispo) {
$besoinConsentementDates = true;
} else if ($dateFin >= $dateDebutIndispo && $dateFin <= $dateFinIndispo) {
$besoinConsentementDates = true;
} else {
$besoinConsentementDates = false;
}
return $besoinConsentementDates;
}
function createExcelCommandes($commandes){
$telAlphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z');
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
foreach(range('A','Z') as $columnID) {
$sheet->getColumnDimension($columnID)->setAutoSize(true);
$sheet->getColumnDimension('A'.$columnID)->setAutoSize(true);
}
$writer = new Xls($spreadsheet);
$fileName = "export";
$fileName .= date("Y-m-d_H:i:s");
$sheet->setCellValue('A1', 'Numéro commande');
$sheet->setCellValue('B1', 'Date de création');
$sheet->setCellValue('C1', 'Statut de la commande');
$sheet->setCellValue('D1', 'Raison sociale');
$sheet->setCellValue('E1', 'Identifiant client MBE');
$sheet->setCellValue('F1', 'Nom du client');
$sheet->setCellValue('G1', 'Prénom du client');
$sheet->setCellValue('H1', 'Email du client');
$sheet->setCellValue('I1', 'Téléphone du client');
$sheet->setCellValue('J1', 'Adresse du client');
$sheet->setCellValue('K1', 'Code postal du client');
$sheet->setCellValue('L1', 'Ville du client');
$sheet->setCellValue('M1', 'Eori');
$sheet->setCellValue('N1', 'Nombre de colis');
$sheet->setCellValue('O1', 'Nombre de bouteille rouge');
$sheet->setCellValue('P1', 'Nombre de bouteille blanc');
$sheet->setCellValue('Q1', 'Nombre de bouteille pétillant');
$sheet->setCellValue('R1', 'Numéro DAE');
$sheet->setCellValue('S1', 'Assurance livraison');
$sheet->setCellValue('T1', 'Emballage livraison');
$sheet->setCellValue('U1', 'Facture client final');
$sheet->setCellValue('V1', 'Numéro facture client final');
$sheet->setCellValue('W1', 'Montant total facture');
$sheet->setCellValue('X1', 'Date de collecte');
$sheet->setCellValue('Y1', 'Créneau début');
$sheet->setCellValue('Z1', 'Créneau fin');
$sheet->setCellValue('AA1', 'Code postal livraison');
$sheet->setCellValue('AB1', 'Ville livraison');
$sheet->setCellValue('AC1', 'Adresse livraison');
$sheet->setCellValue('AD1', 'CPL Adresse livraison');
$sheet->setCellValue('AE1', 'Etat US');
$sheet->setCellValue('AF1', 'Observation');
$sheet->setCellValue('AG1', 'Numéro de suivi');
$sheet->setCellValue('AH1', 'Nom du destinataire');
$sheet->setCellValue('AI1', 'total de bouteilles');
$sheet->setCellValue('AJ1', 'Type d\'emballage');
$sheet->setCellValue('AK1', 'tracking numbers');
$sheet->setCellValue('AL1', 'Magnum rouge');
$sheet->setCellValue('AM1', 'Magnum blanc');
$sheet->setCellValue('AN1', 'Magnum pétillant');
$sheet->setCellValue('AO1', 'DAP');
$sheet->setCellValue('AP1', 'Service priority');
$sheet->setCellValue('AQ1', 'Destinataire Email');
$sheet->setCellValue('AR1', 'Destinataire Telephone');
$index = 2;
foreach ($commandes as $keyCommande => $commandeValue) {
$totalBottles = $commandeValue->getNombreBouteillePetillant() + $commandeValue->getNombreBouteilleBlanc() + $commandeValue->getNombreBouteilleRouge() ;
$previDebut = clone $commandeValue->getDateCollecte();
$previFin = clone $commandeValue->getDateCollecte();
$finalClientPhone = $commandeValue->getClientFinal()->getTelephone();
$finalClientEmail = $commandeValue->getClientFinal()->getEmail();
$sheet->setCellValue('A'.$index, $commandeValue->getId());
$sheet->setCellValue('B'.$index, $commandeValue->getDateCommandeSoumission()->format('d/m/Y'));
$sheet->setCellValue('C'.$index, $this->convertStateToHuman($commandeValue->getState(), $commandeValue->isEmballageLivraison()));
$sheet->setCellValue('D'.$index, $commandeValue->getClient()->getRaisonSociale());
$sheet->setCellValue('E'.$index, $commandeValue->getClient()->getIdClientMBEHub());
$sheet->setCellValue('F'.$index, $commandeValue->getClient()->getNomContact());
$sheet->setCellValue('G'.$index, $commandeValue->getClient()->getPrenomContact());
$sheet->setCellValue('H'.$index, $commandeValue->getClient()->getEmailContact());
$sheet->setCellValue('I'.$index, $commandeValue->getClient()->getTelephoneContact());
$sheet->setCellValue('J'.$index, $commandeValue->getClient()->getAdresse());
$sheet->setCellValue('K'.$index, $commandeValue->getClient()->getCodePostal());
$sheet->setCellValue('L'.$index, $commandeValue->getClient()->getVille());
$sheet->setCellValue('M'.$index, $commandeValue->getClient()->getEori());
$sheet->setCellValue('N'.$index, $commandeValue->getNombreColisTotal());
$sheet->setCellValue('O'.$index, $commandeValue->getNombreBouteilleRouge());
$sheet->setCellValue('P'.$index, $commandeValue->getNombreBouteilleBlanc());
$sheet->setCellValue('Q'.$index, $commandeValue->getNombreBouteillePetillant());
$sheet->setCellValue('R'.$index, $commandeValue->getNumeroDae());
if($commandeValue->isAssuranceLivraison()){
$sheet->setCellValue('S'.$index, "OUI");
}else{
$sheet->setCellValue('S'.$index, "NON");
}
if($commandeValue->isEmballageLivraison()){
$sheet->setCellValue('T'.$index, "OUI");
}else{
$sheet->setCellValue('T'.$index, "NON");
}
// $sheet->setCellValue('R'.$index, $commandeValue->isAssuranceLivraison());
// $sheet->setCellValue('S'.$index, $commandeValue->isEmballageLivraison());
$sheet->setCellValue('U'.$index, $commandeValue->getFichierFacture());
$sheet->setCellValue('V'.$index, ' '.$commandeValue->getNumeroFacture());
$sheet->setCellValue('W'.$index, $commandeValue->getMontantTotalFacture());
$sheet->setCellValue('X'.$index, $commandeValue->getDateCollecte()->format('d/m/Y'));
$sheet->setCellValue('Y'.$index, $previDebut->modify("+7 days")->format('d/m/Y'));
$sheet->setCellValue('Z'.$index, $previFin->modify("+12 days")->format('d/m/Y'));
/* $sheet->setCellValue('V'.$index, $commandeValue->getDateDebutFenetre()->format('d/m/Y'));
$sheet->setCellValue('W'.$index, $commandeValue->getDateFinFenetre()->format('d/m/Y')); */
$sheet->setCellValue('AA'.$index, $commandeValue->getCodePostalLivraison());
$sheet->setCellValue('AB'.$index, $commandeValue->getVilleLivraison());
$sheet->setCellValue('AC'.$index, $commandeValue->getAdresseLivraison());
$sheet->setCellValue('AD'.$index, $commandeValue->getComplementAdresseLivraison());
$sheet->setCellValue('AE'.$index, $commandeValue->getEtatUs());
$sheet->setCellValue('AF'.$index, $commandeValue->getObservation());
$sheet->setCellValue('AG'.$index, ' '.$commandeValue->getTrackingNumber());
$sheet->setCellValue('AH'.$index, $commandeValue->getClientFinal()->getFullName());
$calcMagnum = 0;
$calcMagnum = intval($commandeValue->getNombreMagnumRouge()) + intval($commandeValue->getNombreMagnumBlanc()) + intval($commandeValue->getNombreMagnumPetillant());
$sheet->setCellValue('AI'.$index, $commandeValue->getNombreBouteillePetillant() + $commandeValue->getNombreBouteilleBlanc() + $commandeValue->getNombreBouteilleRouge() + $calcMagnum);
$sheet->setCellValue('AJ'.$index, $commandeValue->getTypeEmballage());
$sheet->setCellValue('AK'.$index, ' '.$commandeValue->getIndividualTrackingNumbers());
$sheet->setCellValue('AL'.$index, ' '.$commandeValue->getNombreMagnumRouge());
$sheet->setCellValue('AM'.$index, ' '.$commandeValue->getNombreMagnumBlanc());
$sheet->setCellValue('AN'.$index, ' '.$commandeValue->getNombreMagnumPetillant());
if($commandeValue->isDap()){
$sheet->setCellValue('AO'.$index, "OUI");
}else{
$sheet->setCellValue('AO'.$index, "NON");
}
if($commandeValue->isServicePriority()){
$sheet->setCellValue('AP'.$index, "OUI");
}else{
$sheet->setCellValue('AP'.$index, "NON");
}
$sheet->setCellValue('AQ'.$index, ' '.$finalClientPhone);
$sheet->setCellValue('AR'.$index, ' '.$finalClientEmail);
$indexAlphabet=19;
$indexColis = 1;
foreach ($commandeValue->getColis() as $keyColis => $valueColis) {
$sheet->setCellValue('A'.$telAlphabet[$indexAlphabet].$index, "Colis n°".$indexColis." Nombre bouteilles : ".$valueColis->getNombreBouteille());
$indexAlphabet++;
$indexColis++;
}
$index++;
}
$response = new StreamedResponse(function () use ($writer) {
$writer->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="' . $fileName . '.xls"');
$response->headers->set('Cache-Control','max-age=0');
return $response ;
}
function convertStateToHuman($state, $cavistePacking){
switch ($state) {
case 'preparation':
return 'préparation';
break;
case 'emballage_caviste':
return 'Emballage caviste';
break;
case 'attente_client':
return 'Attente validation client';
break;
case 'attente_collecte_mbe':
return 'Collecte MBE';
break;
case 'attente_pec_transporteur':
if($cavistePacking){
return 'Attente collecte Fedex(Caviste)';
} else {
if($this->roleAdmin){
return 'Attente collecte Fedex(MBE)';
} else {
return 'En cours de traitement (MBE)';
}
}
break;
case 'emballage_mbe':
if($this->roleAdmin){
return 'Emballage MBE';
} else {
return 'En cours de traitement (MBE)';
}
break;
case 'archive':
return 'Archivée';
break;
default:
'N/A';
break;
}
}
function is_valid_filename($filename) {
// Liste des caractères interdits dans les noms de fichiers sur la plupart des systèmes de fichiers
$forbidden_chars = array("/", "\\", ":", "*", "?", "\"", "<", ">", "|", "#", "&", "=", "%", "+", ";", " ");
// Remplacer les caractères interdits par "_"
$filename = str_replace($forbidden_chars, '_', $filename);
// Vérifie si le nom de fichier est vide après remplacement
if (trim($filename) == '') {
return false; // Le nom de fichier est vide
}
// Le nom de fichier est valide
return $filename;
}
function checkMontant($montant) {
$montant = str_replace(',', '.', $montant);
$montant = preg_replace('/[^0-9,.]/', '', $montant);
return $montant;
}
}