src/Controller/IncassiController.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  9. use \MongoDB\Client as MongoDBClient;
  10. use App\Entity\ImporterCSV;
  11. use App\Entity\ManebiCSV;
  12. use App\Entity\IncassiSearch\IncassiSearchEngine;
  13. use App\Entity\IncassiSearch\Criterion\OrderIDCriterion;
  14. use App\Entity\IncassiSearch\Criterion\DateCriterion;
  15. use App\Entity\IncassiSearch\Criterion\TypeCriterion;
  16. use App\Entity\IncassiSearch\Criterion\OrderTypeCriterion;
  17. use App\Entity\IncassiSearch\Criterion\ShopCriterion;
  18. use App\Entity\IncassiSearch\Criterion\CreditNoteCriterion;
  19. use App\Entity\IncassiSearch\Criterion\SourceCriterion;
  20. use App\Entity\IncassiSearch\Criterion\IdImportazioneCriterion;
  21. use App\Entity\Profis\ManebiProfisXML;
  22. use App\Entity\FatturaElettronica\ManebiFatturaElettronica;
  23. use SessionIdInterface;
  24. /**
  25.  * 
  26.  */
  27. class IncassiController extends AdminController
  28. {
  29.     /**
  30.      * 
  31.      */
  32.     public function manage(Request $requestSessionInterface $session)
  33.     {
  34.         $this->init($session);
  35.         $this->conn $this->getDoctrine()->getManager()->getConnection();
  36.         $filters = ['ids' => [], 'date-from' => '''date-to' => ''];
  37.         $filter_params = [];
  38.         $export false;
  39.         if($request->getMethod() == 'POST')
  40.         {
  41.             $filter_params['filter'] = $request->request->has('filter') ? $request->request->get('filter') : NULL;
  42.             $filter_params['filter-tipo']  = $request->request->has('filter-tipo') ? $request->request->get('filter-tipo') : NULL;
  43.             $filter_params['filter-order-type']  = $request->request->has('filter-order-type') ? $request->request->get('filter-order-type') : NULL;
  44.             $filter_params['filter-date-from'] = $request->request->has('filter-date-from') ? $request->request->get('filter-date-from') : NULL;
  45.             $filter_params['filter-date-to'] = $request->request->has('filter-date-to') ? $request->request->get('filter-date-to') : NULL;
  46.             $filter_params['filter-orders-ids']  = $request->request->has('filter-orders-ids') ? $request->request->get('filter-orders-ids') : NULL;
  47.             $filter_params['filter-credit-notes-from']  = $request->request->has('filter-credit-notes-from') ? $request->request->get('filter-credit-notes-from') : NULL;
  48.             $filter_params['filter-credit-notes-to']  = $request->request->has('filter-credit-notes-to') ? $request->request->get('filter-credit-notes-to') : NULL;
  49.             $filter_params['filter-source']  = $request->request->has('filter-source') ? $request->request->get('filter-source') : NULL;
  50.             $filter_params['filter-id-log-imports']  = $request->request->has('filter-id-log-imports') ? $request->request->get('filter-id-log-imports') : NULL;
  51.         }else{
  52.             $filter_params['filter'] = $request->query->has('filter') ? $request->query->get('filter') : NULL;
  53.             $filter_params['filter-tipo']  = $request->query->has('filter-tipo') ? $request->query->get('filter-tipo') : NULL;
  54.             $filter_params['filter-order-type']  = $request->query->has('filter-order-type') ? $request->query->get('filter-order-type') : NULL;
  55.             $filter_params['filter-date-from'] = $request->query->has('filter-date-from') ? $request->query->get('filter-date-from') : NULL;
  56.             $filter_params['filter-date-to'] = $request->query->has('filter-date-to') ? $request->query->get('filter-date-to') : NULL;
  57.             $filter_params['filter-orders-ids']  = $request->query->has('filter-orders-ids') ? $request->query->get('filter-orders-ids') : NULL;
  58.             $filter_params['filter-credit-notes-from']  = $request->query->has('filter-credit-notes-from') ? $request->query->get('filter-credit-notes-from') : NULL;
  59.             $filter_params['filter-credit-notes-to']  = $request->query->has('filter-credit-notes-to') ? $request->query->get('filter-credit-notes-to') : NULL;
  60.             $filter_params['filter-source']  = $request->query->has('filter-source') ? $request->query->get('filter-source') : NULL;
  61.             $filter_params['filter-id-log-imports']  = $request->query->has('filter-id-log-imports') ? $request->query->get('filter-id-log-imports') : NULL;
  62.         }
  63.         if($filter_params['filter'])
  64.         {
  65.             $incassiSearchEngine = new IncassiSearchEngine($this->conn);
  66.             // Filter By Shop
  67.             if($this->session->has('id_shop'))
  68.             {
  69.                 $this->id_shop = (int) $this->session->get('id_shop');
  70.                 $shopIdCriterion = new ShopCriterion('shop-id');
  71.                 $shopIdCriterion->setId($this->id_shop);
  72.  
  73.                 $incassiSearchEngine->addCriterion($shopIdCriterion);
  74.             }
  75.             // Filter by Date From
  76.             if($filter_params['filter-date-from'])
  77.             {
  78.                 $dateFrom $filter_params['filter-date-from'];
  79.                 if($dateFrom != ''){
  80.                     $incassiDateFromCriterion = new DateCriterion('date-from');
  81.                     $incassiDateFromCriterion->greaterOrEqualTo($dateFrom);
  82.                     $incassiSearchEngine->addCriterion($incassiDateFromCriterion);
  83.                 }
  84.                 
  85.             }
  86.             if($filter_params['filter-date-to'])
  87.             {
  88.                 $dateTo $filter_params['filter-date-to'];
  89.                 if($dateTo != ''){
  90.                     $incassiDateToCriterion = new DateCriterion('date-to');
  91.                     $incassiDateToCriterion->lessOrEqualTo($dateTo);
  92.                     $incassiSearchEngine->addCriterion($incassiDateToCriterion);
  93.                 }
  94.             }
  95.             if($filter_params['filter-tipo'])
  96.             {
  97.                 $type $filter_params['filter-tipo'];
  98.                 if($type != ''){
  99.                     $incassiTypeCriterion = new TypeCriterion('type');
  100.                     $incassiTypeCriterion->setValue($type);
  101.                     $incassiSearchEngine->addCriterion($incassiTypeCriterion);
  102.                 }
  103.             }
  104.             if($filter_params['filter-order-type'])
  105.             {
  106.                 $type $filter_params['filter-order-type'];
  107.                 if($type != ''){
  108.                     $orderTypeCriterion = new OrderTypeCriterion('order-type');
  109.                     $orderTypeCriterion->setValue($type);
  110.                     $incassiSearchEngine->addCriterion($orderTypeCriterion);
  111.                 }
  112.             }
  113.             // Filter by ids
  114.             if($filter_params['filter-orders-ids'])
  115.             {
  116.                 $orderIdCriterion = new OrderIDCriterion('order-ids');
  117.                 $_filtersIds $filter_params['filter-orders-ids'];
  118.                 
  119.                 if(!empty($_filtersIds))
  120.                 {
  121.                     foreach($_filtersIds as $tag)
  122.                     {
  123.                         $filters['order-ids'][] = $tag['tag'];
  124.                     }
  125.                 }
  126.                 $orderIdCriterion->setIDs($filters['order-ids']);
  127.                 $incassiSearchEngine->addCriterion($orderIdCriterion);
  128.             }
  129.             // Filter credit notes
  130.             if($filter_params['filter-credit-notes-from'])
  131.             {
  132.             $dateFrom $filter_params['filter-credit-notes-from'];
  133.             if($dateFrom != '')
  134.             {
  135.                 $creditNoteFromCriterion = new CreditNoteCriterion('credit-notes-from');
  136.                 $creditNoteFromCriterion->greaterOrEqualTo($dateFrom);
  137.                 $incassiSearchEngine->addCriterion($creditNoteFromCriterion);
  138.             }   
  139.             }
  140.             if($filter_params['filter-credit-notes-to'])
  141.             {
  142.                 $dateTo $filter_params['filter-credit-notes-to'];
  143.                 if($dateTo != '')
  144.                 {
  145.                     $creditNoteToCriterion = new CreditNoteCriterion('credit-notes-to');
  146.                     $creditNoteToCriterion->lessOrEqualTo($dateTo);
  147.                     $incassiSearchEngine->addCriterion($creditNoteToCriterion);
  148.                 }   
  149.             }
  150.             if($filter_params['filter-source'])
  151.             {
  152.                 $source $filter_params['filter-source'];
  153.                 if($source != '')
  154.                 {
  155.                     $sourceCriterion = new SourceCriterion('source');
  156.                     $sourceCriterion->setValue($source);
  157.                     $incassiSearchEngine->addCriterion($sourceCriterion);
  158.                 }
  159.             }
  160.             if($filter_params['filter-id-log-imports'])
  161.             {
  162.                 $idImportazione trim($filter_params['filter-id-log-imports']);
  163.                 if($idImportazione != '')
  164.                 {
  165.                     $IdImportazioneCriterion = new IdImportazioneCriterion('id-log-imports');
  166.                     $IdImportazioneCriterion->setValue($idImportazione);
  167.                     $incassiSearchEngine->addCriterion($IdImportazioneCriterion);
  168.                 }
  169.             }
  170.             if($incassiSearchEngine->search())
  171.             {
  172.                 $results $incassiSearchEngine->getResults();
  173.                 if($request->request->has('exportFatturaElettronica') || $request->request->has('exportProfis') || $request->request->has('exportCSV') || $request->request->has('exportCSVDetails'))
  174.                 {
  175.                     foreach($results as $key => $res)
  176.                     {
  177.                         $stmt $this->conn->prepare('SELECT * FROM ordini WHERE `Order` = "'.$res['Order'].'"');
  178.                         if($res $stmt->execute())
  179.                         {
  180.                             $results[$key]['OrderData'] = $stmt->fetchAll();
  181.                             if(!empty($results[$key]['OrderData']))
  182.                             {
  183.                                 $results[$key]['OrderData'] = $results[$key]['OrderData'][0]; 
  184.                             }
  185.                         }
  186.                     }
  187.                     if($request->request->has('exportProfis'))
  188.                     {
  189.                         $response = new Response($this->exportProfisXML('incassi-rimborsi'$results));
  190.                         $response->headers->set('Content-Type''text/xml');
  191.                     }
  192.                     if($request->request->has('exportFatturaElettronica') || $request->request->has('exportCSV') || $request->request->has('exportCSVDetails'))
  193.                     {
  194.                         foreach($results as &$result)
  195.                         {
  196.                             $result['conversion_rate'] = $this->getConversionRate('EUR''GBP'$result['OrderData']['Created at']);
  197.                             $result['tax_rate'] = $this->getTaxRateByCountry($result['OrderData']['Shipping Country']);
  198.                             
  199.                             $result['Prodotti'] = $this->getProdottiByOrder($result['Order']);
  200.                             $prodotti_nc $this->getProdottiByNotaCredito($result);
  201.                             $shipping_nc $this->getShippingByNotaCredito($result);
  202.                             $result = \App\Pdf\ManebiPdf::getPdfVariables($result, [
  203.                                     'prodotti_nc' => $prodotti_nc,
  204.                                     'shipping_nc' => $shipping_nc
  205.                                 ], 
  206.                                 $this->getDoctrine()->getManager()->getConnection()
  207.                             );
  208.                         }
  209.                         if($request->request->has('exportFatturaElettronica'))
  210.                         {
  211.                             $response = new Response($this->exportFatturaElettronicaNotaCredito($type$results));
  212.                             $response->headers->set('Content-Type''application/octect-stream');
  213.                             return $response;
  214.                         }
  215.                         if($request->request->has('exportCSV'))
  216.                             $response = new Response($this->exportCSV('incassi-rimborsi'$results));
  217.                             
  218.                         if($request->request->has('exportCSVDetails'))
  219.                             $response = new Response($this->exportCSVDetails('incassi-rimborsi'$results));
  220.                     }
  221.                     return $response;
  222.                 }
  223.                 return new JsonResponse(['status' => 'OK''data' => $results]);
  224.             }else{
  225.                 return new JsonResponse(['status' => 'ERROR''message' => 'Cannot search']);
  226.             }
  227.         }
  228.         $incassiSenzaOrdine $this->getIncassiSenzaOrdine($this->session->get('id_shop'));
  229.         $ordiniSenzaIncassi $this->getOrdiniSenzaIncassi($this->session->get('id_shop'));
  230.         $params = [];
  231.         $params['incassiSenzaOrdine'] = $incassiSenzaOrdine;
  232.         $params['shop'] = $this->getShop();
  233.         $params['id_shop'] = $this->session->get('id_shop');
  234.         return $this->render('incassi.html.twig'$params);
  235.     }
  236.     /**
  237.      * Export for PROFIS
  238.      */
  239.     protected function exportProfisXML($type$results)
  240.     {
  241.         $profis = new ManebiProfisXML();
  242.         $profis->setDB($this->getDoctrine()->getManager())
  243.                ->setIdShop($this->session->get('id_shop'))
  244.                ->setType($type)
  245.                ->generate($results);
  246.         
  247.         header('Content-Type: text/xml; charset=UTF-8');
  248.         header('Content-Description: Manebi - File Transfer XML Profis');
  249.         header('Content-Disposition: attachment; filename="MANEBI - INVOICES - '.date('Ymd_Hi').'.xml"');
  250.         header('Content-Transfer-Encoding: binary');
  251.         header('Expires: 0');
  252.         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  253.         return $profis->getXML(true);
  254.     }
  255.     /**
  256.      * Export CSV
  257.      */
  258.     protected function exportCSV($type$results)
  259.     {
  260.         $csv = new ManebiCSV();
  261.         $csv->setType($type)->setDB($this->getDoctrine()->getManager())->generateIncassi($results);
  262.         
  263.         header('Content-Type: text/csv; charset=UTF-8');
  264.         header('Content-Description: Manebi - File Transfer CSV Profis');
  265.         header('Content-Disposition: attachment; filename="' $this->getShop()->getName() . ' - ' $type ' - ' date('Ymd_Hi') . '.csv"');
  266.         header('Content-Transfer-Encoding: binary');
  267.         header('Expires: 0');
  268.         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  269.         return $csv->getCSV(true);
  270.     }
  271.     /**
  272.      * Export CSV Details
  273.      */
  274.     protected function exportCSVDetails($type$results)
  275.     {
  276.         $csv = new ManebiCSV();
  277.         $csv->setType($type)->setDB($this->getDoctrine()->getManager())->generateIncassiDetails($results);
  278.         
  279.         header('Content-Type: text/csv; charset=UTF-8');
  280.         header('Content-Description: Manebi - File Transfer CSV Profis');
  281.         header('Content-Disposition: attachment; filename="' $this->getShop()->getName() . ' - ' $type ' DETAILS - ' date('Ymd_Hi') . '.csv"');
  282.         header('Content-Transfer-Encoding: binary');
  283.         header('Expires: 0');
  284.         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  285.         return $csv->getCSV(true);
  286.     }
  287.     /**
  288.      * 
  289.      */
  290.     public function import(Request $requestImporterCSV $importerCSVSessionInterface $session)
  291.     {
  292.         $this->init($session);
  293.         $params = ['stats' => [], 'load_results' => []];
  294.         $importerCSV->setDb($this->getDoctrine()->getManager());
  295.         $importerCSV->setShopId($this->session->get('id_shop'));
  296.         if($request->getMethod() == 'POST')
  297.         {
  298.             $tipoIncasso $request->request->get('tipo_incasso');
  299.             
  300.             if(isset($_FILES['incassi-file-csv']) && !empty($_FILES['incassi-file-csv']))
  301.             {
  302.                 if($_FILES['incassi-file-csv']['error'] == UPLOAD_ERR_OK)
  303.                 {
  304.                     $idImportazione = (int) $importerCSV->addImportazione('incassi'$_FILES['incassi-file-csv']['name']);
  305.                     $result $importerCSV->importIncassiInDb($tipoIncasso$_FILES['incassi-file-csv']['tmp_name'], $idImportazione);
  306.                     if($result)
  307.                     {
  308.                         $params['stats'] = $importerCSV->getImportStats('incassi'$tipoIncasso);
  309.                     }
  310.                 }
  311.             }
  312.         }
  313.         $params['shop'] = $this->getShop();
  314.         $params['id_shop'] = $this->session->get('id_shop');
  315.         $params['importazioni'] = $importerCSV->getImportazioni('incassi');
  316.         return $this->render('incassi.import.html.twig'$params);
  317.     }
  318.     public function getIncassiSenzaOrdine($id_shop$count false)
  319.     {
  320.         $conn $this->getDoctrine()->getManager()->getConnection();
  321.         $statement  $conn->prepare('SELECT I.id, I.PaymentReference, I.Order, I.Date, I.Source, I.Type, I.`ChargeAmount`, I.`RefundAmount`, 
  322.                                       (SELECT IF(((`Numero Fattura` = "") AND (`Corrispettivo` = "")), "NO", "") FROM `ordini` WHERE `Order` = I.`Order`) AS "Gestito"
  323.                                 FROM `incassi` I
  324.                                 LEFT JOIN `ordini` O ON (I.`Order` = O.`Order` AND O.`Shop` = ' $id_shop ' AND (`Numero Fattura` <> "" OR `Corrispettivo` <> ""))
  325.                                 WHERE 1 AND I.`Shop` = ' $id_shop ' AND O.Order IS NULL');
  326.         if($res $statement->execute())
  327.         {
  328.             if($count)
  329.             {
  330.                 return count($statement->fetchAll());
  331.             }
  332.             return $statement->fetchAll();
  333.         }
  334.         return NULL;
  335.     }
  336.     /**
  337.      * 
  338.      */
  339.     public function getOrdiniSenzaIncassi($count false)
  340.     {
  341.         $conn $this->getDoctrine()->getManager()->getConnection();
  342.         $statement  $conn->prepare('SELECT * FROM
  343.                                         (SELECT I.id, O.Order, O.`Numero Fattura`, O.`Corrispettivo`, O.`Payment Reference`, I.`PaymentReference`, I.Source, I.`ChargeAmount`, I.`RefundAmount`
  344.                                         FROM ordini O
  345.                                         JOIN incassi I ON (O.Order = I.`Order`)
  346.                                         WHERE I.`Order` <> ""
  347.                                         
  348.                                         UNION
  349.                                         
  350.                                         (
  351.                                         SELECT I.id, O.Order, O.`Numero Fattura`, O.`Corrispettivo`, O.`Payment Reference`, I.`PaymentReference`, I.Source, I.`ChargeAmount`, I.`RefundAmount`
  352.                                         FROM ordini O
  353.                                         JOIN incassi I ON (I.Order = "" AND (INSTR(O.`Payment Reference`, I.`PaymentReference`) > 0))
  354.                                         )) INCASSI 
  355.                                         WHERE INCASSI.Order NOT IN (SELECT `Order` FROM ordini)
  356.                                         ');
  357.         if($res $statement->execute())
  358.         {
  359.             if($count)
  360.             {
  361.                 return count($statement->fetchAll());
  362.             }
  363.             return $statement->fetchAll();
  364.         }
  365.         return NULL;
  366.     }
  367.     /**
  368.      * Export Fattura Elettronica per Nota Credito
  369.      */
  370.     protected function exportFatturaElettronicaNotaCredito($type$results)
  371.     {
  372.         $fatturaElettronica = new ManebiFatturaElettronica();
  373.         $fatturaElettronica->setDB($this->getDoctrine()->getManager())
  374.             ->setIdShop($this->session->get('id_shop'))
  375.             ->setType($type)
  376.             ->generate($results);
  377.         
  378.         die();
  379.     }
  380.     /**
  381.      * 
  382.      */
  383.     public function getIncassi($count false)
  384.     {
  385.         $conn $this->getDoctrine()->getManager()->getConnection();
  386.         $statement  $conn->prepare('SELECT * FROM
  387.                                         (SELECT I.id, O.Order, O.`Numero Fattura`, O.`Corrispettivo`, O.`Payment Reference`, I.`PaymentReference`, I.Source, I.`ChargeAmount`, I.`RefundAmount`
  388.                                         FROM ordini O
  389.                                         JOIN incassi I ON (O.Order = I.`Order`)
  390.                                         WHERE I.`Order` <> ""
  391.                                         
  392.                                         UNION
  393.                                         
  394.                                         (
  395.                                         SELECT I.id, O.Order, O.`Numero Fattura`, O.`Corrispettivo`, O.`Payment Reference`, I.`PaymentReference`, I.Source, I.`ChargeAmount`, I.`RefundAmount`
  396.                                         FROM ordini O
  397.                                         JOIN incassi I ON (I.Order = "" AND (INSTR(O.`Payment Reference`, I.`PaymentReference`) > 0))
  398.                                         )) INCASSI 
  399.                                         WHERE INCASSI.Order NOT IN (SELECT `Order` FROM ordini)');
  400.         if($res $statement->execute())
  401.         {
  402.             if($count)
  403.             {
  404.                 return count($statement->fetchAll());
  405.             }
  406.             return $statement->fetchAll();
  407.         }
  408.         return NULL;
  409.     }
  410.     /**
  411.      * 
  412.      */
  413.     public function assignNumNotaCredito(Request $requestSessionInterface $session)
  414.     {
  415.         $this->init($session);
  416.         $year date('Y');
  417.         $preview $request->query->has('preview') && $request->query->get('preview') == 'true' true false;
  418.         $confirm $request->query->has('confirm') ? (int) $request->query->get('confirm') : 0;
  419.         $result = [];
  420.         
  421.         if($preview)
  422.         {
  423.             if(!$request->query->has('filter-date-to'))
  424.             {
  425.                 $result['status'] = 'ERROR';
  426.                 $result['message'] = 'Devi specificare una data di fine nel filtro per identificare correttamente l\'anno delle Note Credito da analizzare';
  427.                 
  428.                 return new JsonResponse($result);
  429.             }
  430.             $year date('Y'strtotime($request->query->get('filter-date-to')));
  431.             //Recupera l'ultimo Numero Nota Credito Assegnato
  432.             $lastNotaCredito $this->getLastNotaCredito($year$this->session->get('id_shop'));
  433.             // Anteprima
  434.             if(!empty($lastNotaCredito))
  435.             {
  436.                 $result['status'] = 'OK';
  437.                 $result['lastNotaCredito'] = $lastNotaCredito;
  438.                 $result['rimborsi'] = [];
  439.                 $result['rimborsi'][] = $lastNotaCredito;
  440.                 $lastDateNotaCredito date('Y-m-d'strtotime($lastNotaCredito['Date']));
  441.                 $lastNumNotaCredito $lastNotaCredito['NotaCredito'];
  442.                 
  443.                 $rimborsi $this->getRimborsiSenzaNotaCredito($year$this->session->get('id_shop'));
  444.                 
  445.                 $N $lastNumNotaCredito;
  446.                 foreach($rimborsi as &$r)
  447.                 {
  448.                     $date date('Y-m-d'strtotime($r['Date']));
  449.                     // Se la data di rimborso Ã¨ inferiore alla data dell'ultima nota credito, allora c'è un errore!
  450.                     if($date $lastDateNotaCredito)
  451.                     {
  452.                         $result['status'] = 'ERROR';
  453.                         $result['message'] = 'Attenzione! L\'Ordine '.$r['Order'].' ha una data di rimborso "'.$date.'" superiore alla data dell\'ultima Nota di Credito '.$lastNumNotaCredito.' (Ordine '.$lastNotaCredito['Order'].')';
  454.                         $result['rimborsi'][] = $r;
  455.                         break;
  456.                     }
  457.                     if($r['Order'] == '')
  458.                     {
  459.                         $result['status'] = 'ERROR';
  460.                         $result['message'] = 'Attenzione! Il rimborso '.strtoupper($r['Source']).' in data '.$r['Date'].' Ã¨ associato ad un Ordine che non Ã¨ stato importato  (Payment Reference: '.  $r['PaymentReference']  .') per favore importa prima di tutto questo ordine e potrai così assegnare una Nota Credito';
  461.                         $result['rimborsi'][] = $r;
  462.                         break;
  463.                     }
  464.                     // Controlla se l'ordine Ã¨ ok
  465.                     if($result['status'] != 'ERROR')
  466.                     {
  467.                         $N++;
  468.                         $r['NotaCredito'] = $N;
  469.                         $result['rimborsi'][] = $r;
  470.                     }
  471.                 }
  472.             }else{
  473.                 $result['status'] = 'ERROR';
  474.                 $result['message'] = 'Non esiste una Nota di Credito di partenza per l\'anno '.$year.'. Controllare i rimborsi';
  475.             }
  476.         }else{
  477.             //Modalità non anteprima per conferma numerazione
  478.             if($confirm)
  479.             {
  480.                 $rimborsi json_decode($request->getContent(), true);
  481.                 
  482.                 if(!empty($rimborsi))
  483.                 {
  484.                     $conn $this->getDoctrine()->getManager()->getConnection();
  485.                     $result['NoteCredito'] = [];
  486.                     foreach($rimborsi as $r)
  487.                     {
  488.                         $statement  $conn->prepare('UPDATE `incassi` SET `NotaCredito` = '. (int) $r['NotaCredito'].' WHERE `id` = '.(int) $r['id']);
  489.                         if($statement->execute())
  490.                         {
  491.                             $result['status'] = 'OK';
  492.                             $result['NoteCredito'][] = ['id' => $r['id'], 'NotaCredito' => $r['NotaCredito']];
  493.                         }
  494.                     }
  495.                     if($result['status'] == 'OK')
  496.                     {
  497.                         $result['message'] = 'Operazione effettuata con successo. '.count($result['NoteCredito']).' Note Credito assegnate. Aggiorna la tabella per visualizzare la nuova numerazione.';
  498.                     }
  499.                 }
  500.             }else{
  501.                 $result['status'] = 'WARNING';
  502.                 $result['message'] = 'Nessuna conferma all\'operazione. Nulla da eseguire';
  503.             }
  504.         }
  505.         
  506.         return new JsonResponse($result);
  507.     }
  508.     /**
  509.      * Elimina Incasso
  510.      */
  511.     public function deleteIncasso(Request $request$incassoId)
  512.     {
  513.         $result = [];
  514.         $conn $this->getDoctrine()->getManager()->getConnection();
  515.         $statement  $conn->prepare('DELETE FROM incassi WHERE id = '.(int) $incassoId);
  516.         if($res $statement->execute())
  517.         {
  518.             $result['status'] = 'OK';
  519.         }else{
  520.             $result['status'] = 'ERROR';
  521.             $result['message'] = 'Incasso non eliminato';
  522.         }
  523.         return new JsonResponse($result);
  524.     }
  525.     /**
  526.      * 
  527.      */
  528.     protected function getLastNotaCredito($year$id_shop)
  529.     {
  530.         $conn  $this->getDoctrine()->getManager()->getConnection();
  531.         $sql 'SELECT I.id, O.Order, I.`PaymentReference`, I.`Source`, I.`Type`, I.`Date`, I.`NotaCredito`,
  532.                     IFNULL(O.`Numero Fattura`, "") as "Fattura", 
  533.                     IFNULL(O.`Corrispettivo`, "") as "Corrispettivo"
  534.             FROM `incassi` I
  535.             JOIN `ordini` O ON (O.`Order` = I.`Order`)
  536.                     /* LEFT JOIN `ordini` O ON (CASE
  537.                     --                            WHEN I.Order <> "" THEN (I.Order = O.`Order`)
  538.                     --                            WHEN I.PaymentReference <> "" THEN (INSTR(O.`Payment Reference`, I.`PaymentReference`) > 0)
  539.             --                            ELSE FALSE
  540.             --                        END = TRUE)*/
  541.                     WHERE 1 AND YEAR(I.Date) = '.(int) $year.' AND I.`Shop` = ' $id_shop ' AND I.Type = "refund" 
  542.                             AND O.`Numero Fattura` <> ""
  543.                             AND IFNULL(I.`NotaCredito`,"") <> ""
  544.                     ORDER BY I.Date DESC LIMIT 1';
  545.         $statement  $conn->prepare($sql);
  546.         if($res $statement->execute())
  547.         {
  548.             return $statement->fetch();
  549.         }
  550.         return [];
  551.     }
  552.     /**
  553.      * 
  554.      */
  555.     protected function getRimborsiSenzaNotaCredito($year$id_shop$count false)
  556.     {
  557.         $conn  $this->getDoctrine()->getManager()->getConnection();
  558.         $sql 'SELECT I.id, O.Order, I.`PaymentReference`, I.`Source`, I.`Type`, I.`Date`, I.`NotaCredito`, I.`ChargeAmount`, I.`RefundAmount`,
  559.                     IFNULL(O.`Numero Fattura`, "") as "Fattura", 
  560.                     IFNULL(O.`Corrispettivo`, "") as "Corrispettivo"
  561.             FROM `incassi` I
  562.             JOIN `ordini` O ON (O.`Order` = I.`Order`)
  563.                     /* LEFT JOIN `ordini` O ON (CASE
  564.                     --                            WHEN I.Order <> "" THEN (I.Order = O.`Order`)
  565.                     --                            WHEN I.PaymentReference <> "" THEN (INSTR(O.`Payment Reference`, I.`PaymentReference`) > 0)
  566.                     --                            ELSE FALSE
  567.                     --                        END = TRUE)*/
  568.                     WHERE 1 AND YEAR(I.Date) = '.(int) $year.' AND I.`Shop` = ' $id_shop ' AND I.Type = "refund" 
  569.                             AND IFNULL(O.`Numero Fattura`, "") <> ""
  570.                             AND IFNULL(I.`NotaCredito`,  "") = ""
  571.                     ORDER BY I.Date ASC';
  572.         
  573.         $statement  $conn->prepare($sql);
  574.         if($res $statement->execute())
  575.         {
  576.             return $statement->fetchAll();
  577.         }
  578.         return [];
  579.     }
  580.     /**
  581.      * 
  582.      */
  583.     public function getConversionRate($fromCurr$toCurr$date)
  584.     {
  585.         $conn $this->getDoctrine()->getManager()->getConnection();
  586.         $statement $conn->prepare('SELECT rate FROM `conversion_rates` WHERE `currency_from` = "'.$fromCurr.'" AND `currency_to` = "'.$toCurr.'" AND `date` = DATE("'.$date.'")');
  587.         if($statement->execute())
  588.         {
  589.             return $statement->fetch();
  590.         }
  591.         return NULL;
  592.     }
  593.     /**
  594.      *
  595.      */
  596.     public function getTaxRateByCountry($iso_code)
  597.     {
  598.         $conn $this->getDoctrine()->getManager()->getConnection();
  599.         $statement $conn->prepare('SELECT `rate` FROM `paesi` WHERE iso_code = "'.$iso_code.'" ');
  600.         $statement->execute();
  601.         return $statement->fetch();
  602.     }
  603.     /**
  604.      * 
  605.      */
  606.     public function getProdottiByOrder($OrderID)
  607.     {
  608.         $conn $this->getDoctrine()->getManager()->getConnection();
  609.         $stmt $conn->prepare('SELECT OP.*, C.HSCode, C.CountryOfOrigin 
  610.                                 FROM ordini_prodotti OP
  611.                                 LEFT JOIN codici_doganali C ON (SUBSTR(OP.`SKU`,1,5) = C.`Codice`)
  612.                                 WHERE OP.`Order` = "'$OrderID .'"');
  613.         if($stmt->execute())
  614.         {
  615.             $products $stmt->fetchAll();
  616.             if(!empty($products))
  617.             {
  618.                 foreach($products as $key => &$product)
  619.                 { 
  620.                     $_code substr($product['SKU'], 05);
  621.                     $stmt $conn->prepare('SELECT `HSCode` FROM `codici_doganali` WHERE  `Codice` = "'.$_code.'"');
  622.                     $stmt->execute();
  623.                     $result $stmt->fetch();
  624.                     $product['HSCode'] = $result $result['HSCode'] : '';
  625.                     $_name explode(' - '$product['Name']);
  626.                     if(isset($_name[1])) {
  627.                         $product['Category'] = $_name[0];
  628.                         $product['Articolo'] = $_name[1];
  629.                     }else{
  630.                         $product['Category'] = '';
  631.                         $product['Articolo'] = $_name[0];
  632.                     }
  633.                     if(isset($_name[2]))
  634.                     {
  635.                         $product['CleanName'] = $_name[2];
  636.                     }
  637.                     if(isset($_name[3]))
  638.                     {
  639.                         $product['Size'] = (int) $_name[3];
  640.                     }else {
  641.                         $product['Size'] = '';
  642.                     }
  643.                 }
  644.                 return $products;
  645.             }
  646.         }
  647.         return [];
  648.     }
  649.     /**
  650.     * 
  651.     */
  652.     public function getProdottiByNotaCredito($NotaCredito)
  653.     {
  654.         $conn $this->getDoctrine()->getManager()->getConnection();
  655.         $stmt $conn->prepare('SELECT NCP.SKU, NCP.QuantityRefund, NCP.`PriceRefund`, IFNULL(OP.Name, NCP.Name) as "Name", OP.Price, C.HSCode as "HSCode", C.CountryOfOrigin as "CountryOfOrigin"
  656.                                     FROM notecredito_prodotti NCP
  657.                                     LEFT JOIN ordini_prodotti OP ON (NCP.`Order` = OP.`Order` AND NCP.Shop = OP.Shop AND NCP.SKU = OP.SKU)
  658.                                     LEFT JOIN codici_doganali C ON (SUBSTR(OP.`SKU`,1,5) = C.`Codice`)
  659.                                     WHERE NCP.Shop = '.$NotaCredito['Shop'].' AND NCP.`Order` = "'.$NotaCredito['Order'].'" AND NCP.`NotaCredito` = "'.$NotaCredito['NotaCredito'].'"');
  660.         if($stmt->execute())
  661.         {
  662.             $products $stmt->fetchAll();
  663.             if(!empty($products))
  664.             {   
  665.                 foreach($products as &$p)
  666.                 {
  667.                     $_name explode(' - '$p['Name']);
  668.                     $p['Category'] = $_name[0];
  669.                     $p['Articolo'] = isset($_name[1]) ? $_name[1] : '';
  670.     
  671.                     if(isset($_name[2]))
  672.                     {
  673.                         $p['CleanName'] = $_name[2];
  674.                     }
  675.     
  676.                     if(isset($_name[3]))
  677.                     {
  678.                         $p['Size'] = (int) $_name[3];
  679.                     }else {
  680.                         $p['Size'] = '';
  681.                     }
  682.                 }
  683.             }
  684.         }
  685.         return $products;
  686.     }
  687.     /**
  688.     * 
  689.     */
  690.     public function getShippingByNotaCredito($NotaCredito)
  691.     {
  692.         $conn $this->getDoctrine()->getManager()->getConnection();
  693.         $stmt $conn->prepare('SELECT NCS.*
  694.                                     FROM notecredito_spedizioni NCS
  695.                                     WHERE NCS.Shop = '.$NotaCredito['Shop'].' AND NCS.`Order` = "'.$NotaCredito['Order'].'" AND NCS.`NotaCredito` = "'.$NotaCredito['NotaCredito'].'"');
  696.         if($stmt->execute())
  697.         {
  698.             $shipping $stmt->fetch();
  699.         }
  700.         return $shipping;
  701.     }
  702.     /**
  703.      * 
  704.      */
  705.     public function import_note_credito_prodotti(Request $requestSessionInterface $sessionImporterCSV $importerCSV)
  706.     {
  707.         $this->init($session);
  708.         $params = [];
  709.         $params = ['result' => []];
  710.         
  711.         $params['id_shop'] = $this->session->get('id_shop');
  712.         $importerCSV->setDb($this->getDoctrine()->getManager());
  713.         $importerCSV->setShopId($this->session->get('id_shop'));
  714.         if($request->getMethod() == 'POST')
  715.         {
  716.             $tipoIncasso $request->request->get('tipo_incasso');
  717.             
  718.             if(isset($_FILES['note-credito-prodotti-file-csv']) && !empty($_FILES['note-credito-prodotti-file-csv']))
  719.             {
  720.                 if($_FILES['note-credito-prodotti-file-csv']['error'] == UPLOAD_ERR_OK)
  721.                 {
  722.                     $result $importerCSV->importNoteCreditoProdottiInDb($_FILES['note-credito-prodotti-file-csv']['tmp_name']);
  723.                     if($result){
  724.                         $params['result'] = $result;
  725.                     }
  726.                 }
  727.             }
  728.         }
  729.         return $this->render('incassi.import.note_credito_prodotti.html.twig'$params);
  730.     }
  731.     /**
  732.      * 
  733.      */
  734.     public function deleteImportIncasso(Request $requestSessionInterface $session)
  735.     {
  736.         $this->init($session);
  737.         $conn $this->getDoctrine()->getManager()->getConnection();
  738.         $params = ['result' => []];
  739.         $params['id_shop'] = $this->session->get('id_shop');
  740.         $id_log_imports = (int) ($request->request->has('id_log_imports') ? $request->request->get('id_log_imports') : NULL);
  741.         if($id_log_imports 0)
  742.         {
  743.             $conn->prepare('START TRANSACTION')->execute();
  744.             $conn->prepare('DELETE FROM `incassi` WHERE `id_log_imports` = '.(int) $id_log_imports)->execute();
  745.             $conn->prepare('UPDATE `log_imports` SET `date_delete` = "' date('Y-m-d H:i:s') . '" WHERE `id` = '.(int) $id_log_imports)->execute();
  746.             $conn->prepare('COMMIT')->execute();
  747.             return new JsonResponse(['status' => 'OK']);
  748.         }
  749.         return new JsonResponse(['status' => 'ERROR''message' => 'Importazione non valida']);
  750.     }
  751. }
  752.