<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use \MongoDB\Client as MongoDBClient;
use App\Entity\ImporterCSV;
use App\Entity\ManebiCSV;
use App\Entity\InvoiceSearch\InvoiceSearchEngine;
use App\Entity\InvoiceSearch\Criterion\OrderIdCriterion;
use App\Entity\InvoiceSearch\Criterion\InvoiceIdCriterion;
use App\Entity\InvoiceSearch\Criterion\DateCriterion;
use App\Entity\InvoiceSearch\Criterion\TypeCriterion;
use App\Entity\InvoiceSearch\Criterion\ShopCriterion;
use App\Entity\InvoiceSearch\Criterion\IdImportazioneCriterion;
use App\Entity\Profis\ManebiProfisXML;
use App\Entity\FatturaElettronica\ManebiFatturaElettronica;
use App\Entity\ManebiStats;
use App\Entity\OrderProduct;
use Dompdf\Dompdf;
/**
*
*/
class InvoiceController extends AdminController
{
public $importKey = 'Numero Fattura';
public $session = NULL;
/**
*
*/
public function manage(Request $request, ManebiStats $stats, SessionInterface $session)
{
$this->init($session);
if($request->attributes->get('_route') == 'admin_main'){
return new RedirectResponse($this->get('router')->generate('invoices_main'));
}
$filters = ['fatture-ids' => [], 'order-ids' => [], 'date-from' => '', 'date-to' => '', 'type' => ''];
$filter_params = [];
$export = false;
if($request->getMethod() == 'POST')
{
$filter_params['filter'] = $request->request->has('filter') ? $request->request->get('filter') : NULL;
$filter_params['filter-fatture-ids'] = $request->request->has('filter-fatture-ids') ? $request->request->get('filter-fatture-ids') : NULL;
$filter_params['filter-orders-ids'] = $request->request->has('filter-orders-ids') ? $request->request->get('filter-orders-ids') : NULL;
$filter_params['filter-date-from'] = $request->request->has('filter-date-from') ? $request->request->get('filter-date-from') : NULL;
$filter_params['filter-date-to'] = $request->request->has('filter-date-to') ? $request->request->get('filter-date-to') : NULL;
$filter_params['filter-type'] = $request->request->has('filter-type') ? $request->request->get('filter-type') : NULL;
$filter_params['filter-id-log-imports'] = $request->request->has('filter-id-log-imports') ? $request->request->get('filter-id-log-imports') : NULL;
}else{
$filter_params['filter'] = $request->query->has('filter') ? $request->query->get('filter') : NULL;
$filter_params['filter-fatture-ids'] = $request->query->has('filter-fatture-ids') ? $request->query->get('filter-fatture-ids') : NULL;
$filter_params['filter-orders-ids'] = $request->query->has('filter-orders-ids') ? $request->query->get('filter-orders-ids') : NULL;
$filter_params['filter-date-from'] = $request->query->has('filter-date-from') ? $request->query->get('filter-date-from') : NULL;
$filter_params['filter-date-to'] = $request->query->has('filter-date-to') ? $request->query->get('filter-date-to') : NULL;
$filter_params['filter-type'] = $request->query->has('filter-type') ? $request->query->get('filter-type') : NULL;
$filter_params['filter-id-log-imports'] = $request->query->has('filter-id-log-imports') ? $request->query->get('filter-id-log-imports') : NULL;
}
if($filter_params['filter'])
{
$invoiceSearchEngine = new InvoiceSearchEngine($this->getDoctrine()->getManager()->getConnection());
// Filter By Shop
if($this->session->has('id_shop'))
{
$this->id_shop = (int) $this->session->get('id_shop');
$shopIdCriterion = new ShopCriterion('shop-id');
$shopIdCriterion->setId($this->id_shop);
$invoiceSearchEngine->addCriterion($shopIdCriterion);
}
// Filter by ids
if($filter_params['filter-fatture-ids'])
{
$invoiceIdCriterion = new InvoiceIDCriterion('invoice-ids');
$_filtersIds = $filter_params['filter-fatture-ids'];
if(!empty($_filtersIds))
{
foreach($_filtersIds as $tag)
{
$filters['fatture-ids'][] = $tag['tag'];
}
}
$invoiceIdCriterion->setIDs($filters['fatture-ids']);
$invoiceSearchEngine->addCriterion($invoiceIdCriterion);
}
// Filter by ids
if($filter_params['filter-orders-ids'])
{
$orderIdCriterion = new OrderIDCriterion('order-ids');
$_filtersIds = $filter_params['filter-orders-ids'];
if(!empty($_filtersIds))
{
foreach($_filtersIds as $tag)
{
$filters['order-ids'][] = $tag['tag'];
}
}
$orderIdCriterion->setIDs($filters['order-ids']);
$invoiceSearchEngine->addCriterion($orderIdCriterion);
}
// Filter by Date From
if($filter_params['filter-date-from'])
{
$dateFrom = $filter_params['filter-date-from'];
if($dateFrom != ''){
$invoiceDateFromCriterion = new DateCriterion('date-from');
$invoiceDateFromCriterion->greaterOrEqualTo($dateFrom);
$invoiceSearchEngine->addCriterion($invoiceDateFromCriterion);
}
}
if($filter_params['filter-date-to'])
{
$dateTo = $filter_params['filter-date-to'];
if($dateTo != ''){
$invoiceDateToCriterion = new DateCriterion('date-to');
$invoiceDateToCriterion->lessOrEqualTo($dateTo);
$invoiceSearchEngine->addCriterion($invoiceDateToCriterion);
}
}
if($filter_params['filter-type'])
{
$type = $filter_params['filter-type'];
if($type != ''){
$invoiceTypeCriterion = new TypeCriterion('type');
$invoiceTypeCriterion->setValue($type);
$invoiceSearchEngine->addCriterion($invoiceTypeCriterion);
}
}
if($filter_params['filter-id-log-imports'])
{
$idImportazione = trim($filter_params['filter-id-log-imports']);
if($idImportazione != '')
{
$IdImportazioneCriterion = new IdImportazioneCriterion('id-log-imports');
$IdImportazioneCriterion->setValue($idImportazione);
$invoiceSearchEngine->addCriterion($IdImportazioneCriterion);
}
}
if($invoiceSearchEngine->search())
{
$results = $invoiceSearchEngine->getResults();
foreach($results as &$result)
{
$result['Prodotti'] = $this->getProdottiByOrder($result['Order']);
}
if($request->request->has('exportProfis'))
{
$type = $type == 'invoices' ? 'fatture' : $type;
$response = new Response($this->exportProfisXML($type, $results));
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
if($request->request->has('exportFatturaElettronica'))
{
$type = $type == 'invoices' ? 'fatture' : $type;
// Recupera i dettagli della Fattura/Nota credito
foreach($results as &$result)
{
$result['conversion_rate'] = $this->getConversionRate('EUR', 'GBP', $result['Created at']);
$result['tax_rate'] = $this->getTaxRateByCountry($result['Shipping Country']);
$result = \App\Pdf\ManebiPdf::getPdfVariables($result, [], $this->getDoctrine()->getManager()->getConnection());
}
$response = new Response($this->exportFatturaElettronica($type, $results));
$response->headers->set('Content-Type', 'application/octect-stream');
return $response;
}
if($request->request->has('exportCSV') || $request->request->has('exportCSVDetails'))
{
foreach($results as &$result)
{
$result['conversion_rate'] = $this->getConversionRate('EUR', 'GBP', $result['Created at']);
$result['tax_rate'] = $this->getTaxRateByCountry($result['Shipping Country']);
$result = \App\Pdf\ManebiPdf::getPdfVariables($result, [], $this->getDoctrine()->getManager()->getConnection());
}
if($request->request->has('exportCSV'))
{
$response = new Response($this->exportCSV($type, $results));
}
if($request->request->has('exportCSVDetails'))
{
$response = new Response($this->exportCSVDetails($type, $results));
}
return $response;
}
/*if($request->request->has('getPdf'))
{
$type = $type == 'invoices' ? 'fatture' : $type;
$response = new Response($this->getPdf($type, $results));
$response->headers->set('Content-Type', 'text/xml');
return $response;
}*/
return new JsonResponse(['status' => 'OK', 'data' => $results]);
}else{
return new JsonResponse(['status' => 'ERROR', 'message' => 'Cannot search']);
}
}
$params = [];
$params['ordiniSenzaIncassiERimborsi'] = $stats->getOrdiniSenzaIncassiERimborsi();
$params['shop'] = $this->getShop();
$params['id_shop'] = $this->session->get('id_shop');
return $this->render('invoices.html.twig', $params);
}
/**
* Get Invoice Data (Use Search Engine in order to search the target invoice)
*/
public function getInvoice(Request $request, SessionInterface $session, string $invoiceId, $getPdf = false)
{
$this->init($session);
$invoiceId = '#'.$invoiceId;
$invoiceSearchEngine = new InvoiceSearchEngine($this->getDoctrine()->getManager()->getConnection());
$orderIdCriterion = new OrderIDCriterion('order-ids');
$orderIdCriterion->setIDs([$invoiceId]);
$invoiceSearchEngine->addCriterion($orderIdCriterion);
if($invoiceSearchEngine->search())
{
$results = $invoiceSearchEngine->getResults();
}
if($getPdf && !empty($results))
{
$result = $results[0];
$result['conversion_rate'] = $this->getConversionRate('EUR', 'GBP', $result['Created at']);
$result['tax_rate'] = $this->getTaxRateByCountry($result['Shipping Country']);
//Recupera i prodotti
$prodotti = $this->getProdottiByOrder($result['Order']);
$result['Prodotti'] = $prodotti;
$result = \App\Pdf\ManebiPdf::getPdfVariables($result, [], $this->getDoctrine()->getManager()->getConnection());
//dump($result);
//die('test');
if($request->query->has('proforma_return'))
{
$domPdf = $this->getPdf('proforma_return', $this->session->get('id_shop'), ['order' => $result, 'prodotti' => $prodotti]);
}else {
$domPdf = $this->getPdf('fattura', $this->session->get('id_shop'), ['order' => $result, 'prodotti' => $prodotti]);
}
return new Response($domPdf->output(), 200,
[
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.'MANEBI-'.(!$request->query->has('proforma_return') ? 'INVOICE' : 'RETURN').' ' . (!$request->query->has('proforma_return') ? $result['Numero Fattura'] : (str_replace('#','',$result['Order']) .'-'.$result['Shipping Country'])) . '.pdf'.'"'
]);
}
return new JsonResponse(['status' => 'OK', 'data' => $results]);
}
/**
* Import Invoices
*/
public function shopify_import(Request $request, ImporterCSV $importerCSV, SessionInterface $session)
{
$this->init($session);
$params = ['stats' => [], 'load_results' => []];
$importerCSV->setDB($this->getDoctrine()->getManager());
$importerCSV->setShopId($this->session->get('id_shop'));
if($request->getMethod() == 'POST')
{
if(isset($_FILES['file-shopify-csv']) && !empty($_FILES['file-shopify-csv']))
{
if($_FILES['file-shopify-csv']['error'] == UPLOAD_ERR_OK)
{
$filename = date('Ymd_His').'-shopify';
copy($_FILES['file-shopify-csv']['tmp_name'], dirname(__FILE__) . '/../../temp/import_ordini/'.$filename.'.csv');
$result = $importerCSV->getFileFromShopify($_FILES['file-shopify-csv']['tmp_name']);
$output = '';
$csv = [];
//var_dump(\reset($result['rows']));
//$csv[] = array_keys((\reset($result['rows']))[0]);
$outputHeader = [];
$outputHeader[] = '"Ordini Letti",' . (count($result['processed_rows']) + count($result['orders_skipped']));
$outputHeader[] = '"Ordini Processati",' . count($result['processed_rows']);
$outputHeader[] = '"Ordini Esistenti",' . count($result['orders_skipped']) . ', '.implode(' - ', $result['orders_skipped']);
$outputHeader[] = '"Ordini Antecedenti Ultimo Ordine",' . count($result['orders_old']) . ', '.implode(' - ', $result['orders_old']);
$outputHeader[] = '"Ordini Aliquota diversa:",' . count($result['different_vat']) . ', '.implode(' - ', $result['different_vat']);
$outputHeader[] = '';
$outputHeader[] = '';
foreach($result['processed_rows'] as $order)
{
foreach($order as $order_line)
{
$csv[] = $order_line;
}
}
if(count($result['processed_rows']) > 0)
{
$output = $this->array2csv($csv, ',', '"', '\\');
}
$output = implode("\n", $outputHeader) . $output;
//file_put_contents('/tmp', $output, );
file_put_contents(dirname(__FILE__) . '/../../temp/import_ordini/'.$filename.'-output.csv', $output);
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Description: Manebi - File Transfer CSV Profis');
header('Content-Disposition: attachment; filename="' . $this->getShop()->getName() . ' - Import from Shopify - ' . date('Ymd_Hi') . '.csv"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
die($output);
}
}
if($request->query->get('loadInvoices') == 1)
{
$params['load_results'] = $importerCSV->loadInvoices();
// 2021-07-26 - Antonio@Tembo: reset Exports for imported file
$params['reset_export_results'] = $importerCSV->resetExport();
}
}
}
/**
* Import Invoices
*/
public function import(Request $request, ImporterCSV $importerCSV, SessionInterface $session)
{
$this->init($session);
$params = ['stats' => [], 'load_results' => []];
$importerCSV->setDB($this->getDoctrine()->getManager());
$importerCSV->setShopId($this->session->get('id_shop'));
if($request->getMethod() == 'POST')
{
if(isset($_FILES['file-csv']) && !empty($_FILES['file-csv']))
{
if($_FILES['file-csv']['error'] == UPLOAD_ERR_OK)
{
$result = $importerCSV->importFileInDb($_FILES['file-csv']['tmp_name'], 'tmp_csv_ordini');
if($result)
{
$params['stats'] = $importerCSV->getImportStats('ordini');
$params['check_vat_errors'] = $this->checkVatErrors();
$params['has_vat_errors'] = false;
if(!empty($params['check_vat_errors'])) {
foreach($params['check_vat_errors'] as $err)
{
if($err['IsError'] <> "OK")
{
$params['has_vat_errors'] = true;
break;
}
}
}
}
}
}
if($request->query->get('loadInvoices') == 1)
{
$params['load_results'] = $importerCSV->loadInvoices();
// 2021-07-26 - Antonio@Tembo: reset Exports for imported file
$params['reset_export_results'] = $importerCSV->resetExport();
}
}
$params['checkNumerazioneFatture'] = $this->checkNumerazioneFatture($this->session->get('id_shop'), date('Y'));
$params['shop'] = $this->getShop();
$params['id_shop'] = $this->session->get('id_shop');
$params['importazioni'] = $importerCSV->getImportazioni('invoices');
return $this->render('invoices.import.html.twig', $params);
}
/**
*
*/
public function delete(Request $request, SessionInterface $session, string $invoiceId)
{
$this->init($session);
$conn = $this->getDoctrine()->getManager()->getConnection();
$idOrder = (int) $invoiceId;
if($idOrder == 0)
{
$id_log_imports = (int) ($request->request->has('id_log_imports') ? $request->request->get('id_log_imports') : NULL);
if($id_log_imports > 0)
{
$conn->prepare('START TRANSACTION')->execute();
$conn->prepare('DELETE FROM `ordini_prodotti` WHERE `Order` IN (SELECT `Order` FROM `ordini` WHERE `id_log_imports` = '.(int) $id_log_imports.')')->execute();
$conn->prepare('DELETE FROM `ordini` WHERE `id_log_imports` = '.(int) $id_log_imports)->execute();
$conn->prepare('UPDATE `log_imports` SET `date_delete` = "' . date('Y-m-d H:i:s') . '" WHERE `id` = '.(int) $id_log_imports)->execute();
$conn->prepare('COMMIT')->execute();
return new JsonResponse(['status' => 'OK']);
}
return new JsonResponse(['status' => 'ERROR', 'message' => 'Importazione non valida']);
}else
{
$Order = '#' . $idOrder;
$conn->prepare('START TRANSACTION')->execute();
// Rimuovi i prodotti
$stmt = $conn->prepare('DELETE FROM `ordini_prodotti` WHERE `Order` = "' . $Order . '"');
$res = $stmt->execute();
// Rimuovi l'ordine
$stmt = $conn->prepare('DELETEFROM `ordini` WHERE `Order` = "' . $Order . '"');
$res = $stmt->execute();
$conn->prepare('COMMIT')->execute();
if($res)
{
return new JsonResponse(['status' => 'OK']);
}
}
return new JsonResponse(['status' => 'ERROR', 'message' => 'Ordine non valido']);
}
/**
* Export for PROFIS
*/
protected function exportProfisXML($type, $results)
{
$profis = new ManebiProfisXML();
$profis->setDB($this->getDoctrine()->getManager())
->setIdShop($this->session->get('id_shop'))
->setType($type)
->generate($results);
header('Content-Type: text/xml; charset=UTF-8');
header('Content-Description: Manebi - File Transfer XML Profis');
header('Content-Disposition: attachment; filename="MANEBI - INVOICES - '.date('Ymd_Hi').'.xml"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
return $profis->getXML(true);
}
/**
* Export Fattura Elettronica
*/
protected function exportFatturaElettronica($type, $results)
{
$fatturaElettronica = new ManebiFatturaElettronica();
$fatturaElettronica->setDB($this->getDoctrine()->getManager())
->setIdShop($this->session->get('id_shop'))
->setType($type)
->generate($results);
die();
header('Content-Type: application/octect-stream');
header('Content-Description: Manebi - File Transfer XML Profis');
header('Content-Disposition: attachment; filename="MANEBI - FATTURA ELETTRONICA - '.date('Ymd_Hi').'.xml"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
return $fatturaElettronica->getFiles(true);
}
/**
* Export for PROFIS
*/
protected function exportCSV($type, $results)
{
$csv = new ManebiCSV();
$csv->setType($type)->generateOrders($results);
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Description: Manebi - File Transfer CSV Profis');
header('Content-Disposition: attachment; filename="' . $this->getShop()->getName() . ' - ' . $type . ' - ' . date('Ymd_Hi') . '.csv"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
return $csv->getCSV(true);
}
/**
* Export for PROFIS
*/
protected function exportCSVDetails($type, $results)
{
$csv = new ManebiCSV();
$csv->setType($type)->generateOrdersDetails($results);
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Description: Manebi - File Transfer CSV Profis');
header('Content-Disposition: attachment; filename="' . $this->getShop()->getName() . ' - ' . $type . ' Details - ' . date('Ymd_Hi') . '.csv"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
return $csv->getCSV(true);
}
/**
*
*/
public function getProdottiByOrder($OrderID)
{
$conn = $this->getDoctrine()->getManager()->getConnection();
$stmt = $conn->prepare('SELECT *
FROM ordini_prodotti WHERE `Order` = "'.$OrderID.'"');
if($stmt->execute())
{
$products = $stmt->fetchAll();
if(!empty($products))
{
foreach($products as $key => &$product)
{
$_code = substr($product['SKU'], 0, 5);
$stmt = $conn->prepare('SELECT `HSCode`,`CountryOfOrigin`,`EU_ExtraEU`,`Weight` FROM `codici_doganali` WHERE `Codice` = "'.$_code.'"');
$stmt->execute();
$result = $stmt->fetch();
$product['HSCode'] = $result ? $result['HSCode'] : '';
$product['CountryOfOrigin'] = $result ? $result['CountryOfOrigin'] : '';
$product['EU_ExtraEU'] = $result ? $result['EU_ExtraEU'] : '';
$product['Weight'] = $result ? (float) $result['Weight'] * (float) $product['Quantity'] : '';
$_name = explode(' - ', $product['Name']);
if(isset($_name[1])) {
$product['Category'] = $_name[0];
$product['Articolo'] = $_name[1];
}else{
$product['Category'] = '';
$product['Articolo'] = $_name[0];
}
if(isset($_name[2]))
{
$product['CleanName'] = $_name[2];
}
if(isset($_name[3]))
{
$product['Size'] = (int) $_name[3];
}else
{
$product['Size'] = '';
}
}
return $products;
}
}
return [];
}
/**
* Genera il PDF di una singola fattura
*/
protected function getPdf($type, $id_shop, $result)
{
$options = new \Dompdf\Options();
$options->setIsRemoteEnabled(true);
$dompdf = new \Dompdf\Dompdf($options);
$dompdf->setPaper('A4', 'vertical');
// Recupera il giusto template dalla data dell'ordine
$createdDate = substr($result['order']['Created at'], 0, 10);
$templateVersion = '';
if($createdDate >= '2025-03-12')
{
$templateVersion = '2025-03-12';
}elseif($createdDate >= '2025-02-01')
{
$templateVersion = '2025-02-01';
}
if($type == "proforma_return")
$htmlPDF = $this->renderView('pdf/'.$templateVersion.'/pdf_proforma_return_' . $id_shop . '.html.twig', $result);
else
$htmlPDF = $this->renderView('pdf/'.$templateVersion.'/pdf_invoice_' . $id_shop . '.html.twig', $result);
$dompdf->load_html($htmlPDF);
$dompdf->render();
return $dompdf;
}
/**
*
*/
public function checkNumerazioneFatture($idShop, $anno)
{
$errors = [];
$conn = $this->getDoctrine()->getManager()->getConnection();
$stmt = $conn->prepare('SELECT `Order`, `Numero Fattura`, `Created at`
FROM `ordini` WHERE `Shop` = ' . (int) $idShop . ' AND `Numero Fattura` <> "" AND YEAR(`Created at`) = '.$anno.'
ORDER BY CONVERT(REPLACE(`Numero Fattura`,"B",""), UNSIGNED INT) ASC, DATE(`Created at`) ASC');
$stmt->execute();
$fatture = $stmt->fetchAll();
$_currentFattura = 0;
$_currentFatturaData = '';
foreach($fatture as $index => $f)
{
$fatturaNum = (int) str_replace('B', '', $f['Numero Fattura']);
if($index == 0)
{
$_currentOrder = $f['Order'];
$_currentFattura = $fatturaNum;
$_currentFatturaData = $f['Created at'];
continue;
}
if($fatturaNum - $_currentFattura != 1)
{
$errors = [
'ultima_fattura_ok' => $_currentFattura,
'ultima_fattura_ok_data' => $_currentFatturaData,
'ultimo_ordine_ok' => $_currentOrder,
'error_fattura' => $fatturaNum,
'error_fattura_data' => $f['Created at'],
'error_order' => $f['Order'],
];
break;
}
$_currentOrder = $f['Order'];
$_currentFattura = $fatturaNum;
$_currentFatturaData = $f['Created at'];
}
return $errors;
}
/**
*
*/
public function getConversionRate($fromCurr, $toCurr, $date)
{
$conn = $this->getDoctrine()->getManager()->getConnection();
$statement = $conn->prepare('SELECT rate FROM `conversion_rates` WHERE `currency_from` = "'.$fromCurr.'" AND `currency_to` = "'.$toCurr.'" AND `date` = DATE("'.$date.'")');
if($statement->execute())
{
return $statement->fetch();
}
return NULL;
}
/**
*
*/
public function getTaxRateByCountry($iso_code)
{
$conn = $this->getDoctrine()->getManager()->getConnection();
$statement = $conn->prepare('SELECT `rate` FROM `paesi` WHERE iso_code = "'.$iso_code.'" ');
$statement->execute();
return $statement->fetch();
}
/**
* Controlla se ci sono errori nella VAT dei paesi europei,
* confrontando il Vat rate di Shopify con i rate che abbiamo noi.
*/
public function checkVatErrors()
{
$conn = $this->getDoctrine()->getManager()->getConnection();
$statement = $conn->prepare('SELECT Y.`Order`,
Y.`Country`,
Y.`Shipping Country`,
Y.`Shipping Province`,
Y.`Shopify Country Rate`,
Y.`Manebi Country Rate`,
Y.`OrderVatRate`,
IFNULL(Y.`Province Tax Rate`,"") as "Province Tax Rate",
CASE
WHEN (Y.`OrderVatRate` > 0 AND Y.`Province Tax Rate` IS NULL) THEN "ERROR-PROVINCETAXRATE-NULL"
WHEN (Y.`OrderVatRate` IS NULL AND Y.`Province Tax Rate` > 0) THEN "ERROR-ORDERVATRATE-NULL"
WHEN (Y.`OrderVatRate` <> Y.`Province Tax Rate`) THEN "ERROR-ORDERVATRATE-DIFF-PROVINCETAXRATE"
ELSE "OK"
END as "IsError"
FROM (SELECT `Order`, `Shipping Country`, `Shipping Province`, `Tax 1 Name`,
p.name as "Country",
REGEXP_SUBSTR(`Tax 1 Name`,"[0-9\.]+") as "Shopify Country Rate",
CONVERT(ROUND(p.rate,2),VARCHAR(10)) as "Manebi Country Rate",
`OrderVatRate`,
prov.rate as "Province Tax Rate"
FROM tmp_csv_ordini X
join paesi p ON X.`Shipping Country` = p.`iso_code`
left join province prov ON (X.`Shipping Country` = prov.`iso_code_paese` AND X.`Shipping Province` = prov.iso_code)
) Y
WHERE ROUND(Y.`Shopify Country Rate`,2) <> Y.`Manebi Country Rate`;');
$statement->execute();
return $statement->fetchAll();
}
}