bebeboutik/modules/ant_dropshippingtracking/AdminAntDropshippingtracking.php
Michael RICOIS d7ea10a2bb Mails
2018-02-02 12:28:49 +01:00

455 lines
24 KiB
PHP

<?php
if (!defined('_PS_VERSION_')) {
exit;
}
require_once _PS_ROOT_DIR_.'/modules/privatesales/Sale.php';
require_once PS_ADMIN_DIR .'/helpers/HelperFormBootstrap.php';
class AdminAntDropshippingtracking extends AdminTab
{
protected $_html;
public function __construct($config_tab = true)
{
parent::__construct();
$this->controller = 'AdminModules';
$this->module_name = 'ant_dropshippingtracking';
$this->config_tab = (bool)$config_tab;
if ($config_tab) {
$this->controller = 'AdminAntDropshippingtracking';
}
}
public function _postProcess()
{
$this->_html = '';
if ($id_sale = Tools::getValue('id_sale')) {
// Selection des produits de la vente
$errors = 0;
$sale_names = array();
foreach(Db::getInstance()->ExecuteS('
SELECT c.`name`, c.`id_lang`
FROM `'._DB_PREFIX_.'privatesale` p
LEFT JOIN `'._DB_PREFIX_.'category_lang` c ON (c.`id_category` = p.`id_category`)
WHERE p.`id_sale` = '.(int)$id_sale.'
') as $key => $row) {
$sale_names[(int)$row['id_lang']] = $row['name'];
}
$sale_products = array();
foreach(Db::getInstance()->ExecuteS('
SELECT DISTINCT `id_product`
FROM `'._DB_PREFIX_.'product_ps_cache`
WHERE `id_sale` = '.(int) $id_sale.'
') as $key => $row) {
$sale_products[(int)$row['id_product']] = (int)$row['id_product'];
}
$infosTrackingEnable = $infosTrackingDisable = 0;
// Fichier avec infos tracking
if (Tools::isSubmit('submitOrderTracking')) {
$infosTrackingEnable = 1;
}
// Fichier sans infos de tracking
if (Tools::isSubmit('submitOrderTrackingNull')) {
$infosTrackingDisable = 1;
}
// Gestion du fichier CSV
$orders = array();
if (isset($_FILES['csvfile']) && $_FILES['csvfile']['name'] != '') {
$cols = array(
'id_order',
'tracking_number',
'carrier',
'link',
);
$i = 0;
$f = fopen($_FILES['csvfile']['tmp_name'], 'r');
while ($data = fgetcsv($f, 0, ';')) {
$i++;
if ($i == 1) {
continue;
}
// Get Data
$num = count($data);
// Check line integrity
if ($num != count($cols)) {
$orders = array();
break;
}
// Assign var
$line = array();
for ($c=0; $c<$num; $c++) {
$name = $cols[$c];
switch ($name) {
case 'tracking_number':
case 'link';
$line[$name] = trim($data[$c]);
break;
default:
$line[$name] = $data[$c];
break;
}
}
// Vérification des données
if ($infosTrackingDisable == 1) {
if ($line['tracking_number'] != ''){
$orders = array();
break;
}
if ($line['link'] != ''){
$orders = array();
break;
}
}
if ($infosTrackingEnable == 1) {
if ($line['tracking_number'] == ''){
$orders = array();
break;
}
if ($line['link'] == ''){
$orders = array();
break;
}
}
// Assign orders
$orders[(int) $line['id_order']] = array(
'id_order' => (int)$line['id_order'],
'tracking_number' => $line['tracking_number'],
'carrier' => $line['carrier'],
'link' => $line['link'],
);
}
}
else {
$this->_html .= HelperFormBootstrap::displayErrors($this->l('Fichier manquant !'));
}
// Traitement des commandes
if (count($orders) > 0) {
foreach ($orders as $id_order => $o) {
if ($id_order != 0) {
$order = new Order((int)$id_order);
if (Validate::isLoadedObject($order)) {
$order_details = array();
foreach (Db::getInstance()->ExecuteS('
SELECT DISTINCT `id_order_detail`, `product_name`,`product_id`, `product_attribute_id`, `product_quantity` - GREATEST(`product_quantity_return`, `product_quantity_refunded`) AS `quantity`
FROM `'._DB_PREFIX_.'order_detail`
WHERE `id_order` = '.(int) $id_order.'
') as $key => $row) {
$order_details[(int)$row['id_order_detail']] = $row;
}
$fully_sent = false;
// Calcul des produits déjà envoyés par LaPoste
$products_sent = array();
foreach (Db::getInstance()->ExecuteS('
SELECT d.`id_order_detail`, IF(
(d.`product_quantity` - IF(
d.`product_quantity_return` > 0, d.`product_quantity_return`, d.`product_quantity_refunded`
) - IFNULL(SUM(s.`quantity`), 0)) > 0, 1, 0
) AS `remain`
FROM `'._DB_PREFIX_.'order_detail` d
LEFT OUTER JOIN `'._DB_PREFIX_.'lapostews` s
ON s.`id_order_detail` = d.`id_order_detail`
WHERE d.`id_order` = '.(int) $order->id.'
GROUP BY d.`id_order_detail`
') as $quantity_remain) {
if ((int) $quantity_remain['remain'] == 0) {
$products_sent[] = (int) $quantity_remain['id_order_detail'];
}
}
// Calcul des produits déjà envoyé Exapaq
foreach (Db::getInstance()->ExecuteS('
SELECT d.`id_order_detail`, IF(
(d.`product_quantity` - IF(
d.`product_quantity_return` > 0, d.`product_quantity_return`, d.`product_quantity_refunded`
) - IFNULL(SUM(s.`quantity`), 0)) > 0, 1, 0
) AS `remain`
FROM `'._DB_PREFIX_.'order_detail` d
LEFT OUTER JOIN `'._DB_PREFIX_.'exapaqws` s
ON s.`id_order_detail` = d.`id_order_detail`
WHERE d.`id_order` = '.(int) $order->id.'
GROUP BY d.`id_order_detail`
') as $quantity_remain) {
if ((int) $quantity_remain['remain'] == 0) {
$products_sent[] = (int) $quantity_remain['id_order_detail'];
}
}
// Calcul des produits déjà envoyé MondialRelay
foreach (Db::getInstance()->ExecuteS('
SELECT d.`id_order_detail`, IF(
(d.`product_quantity` - IF(
d.`product_quantity_return` > 0, d.`product_quantity_return`, d.`product_quantity_refunded`
) - IFNULL(SUM(s.`quantity`), 0)) > 0, 1, 0
) AS `remain`
FROM `'._DB_PREFIX_.'order_detail` d
LEFT OUTER JOIN `'._DB_PREFIX_.'mondialrelay_parcel` s
ON s.`id_order_detail` = d.`id_order_detail`
WHERE d.`id_order` = '.(int) $order->id.'
GROUP BY d.`id_order_detail`
') as $quantity_remain) {
if ((int) $quantity_remain['remain'] == 0) {
$products_sent[] = (int) $quantity_remain['id_order_detail'];
}
}
// Calcul des produits déjà envoyé Philea
foreach (Db::getInstance()->ExecuteS('
SELECT d.`id_order_detail`, IF(
(d.`product_quantity` - IF(
d.`product_quantity_return` > 0, d.`product_quantity_return`, d.`product_quantity_refunded`
) - IFNULL(SUM(s.`quantity`), 0)) > 0, 1, 0
) AS `remain`
FROM `'._DB_PREFIX_.'order_detail` d
LEFT OUTER JOIN `'._DB_PREFIX_.'philea_parcel` s
ON s.`id_order_detail` = d.`id_order_detail`
WHERE d.`id_order` = '.(int) $order->id.'
GROUP BY d.`id_order_detail`
') as $quantity_remain) {
if ((int) $quantity_remain['remain'] == 0) {
$products_sent[] = (int) $quantity_remain['id_order_detail'];
}
}
// Calcul des produits déjà envoyé Dropshipping
foreach (Db::getInstance()->ExecuteS('
SELECT d.`id_order_detail`, IF(
(d.`product_quantity` - IF(
d.`product_quantity_return` > 0, d.`product_quantity_return`, d.`product_quantity_refunded`
) - IFNULL(SUM(s.`quantity`), 0)) > 0, 1, 0
) AS `remain`
FROM `'._DB_PREFIX_.'order_detail` d
LEFT OUTER JOIN `'._DB_PREFIX_.'ant_dropshipping_parcel` s
ON s.`id_order_detail` = d.`id_order_detail`
WHERE d.`id_order` = '.(int) $order->id.'
GROUP BY d.`id_order_detail`
') as $quantity_remain) {
if ((int) $quantity_remain['remain'] == 0) {
$products_sent[] = (int) $quantity_remain['id_order_detail'];
}
}
$remaining = array();
foreach($order_details as $id_order_detail => $d) {
// Calcul des produits restant
if (!in_array($id_order_detail, $products_sent) && !in_array($d['product_id'], $sale_products)) {
$remaining[] = (int)$id_order_detail;
}
// Marquage envoi
elseif (!in_array($id_order_detail, $products_sent) && in_array((int)$d['product_id'],$sale_products)) {
if ($infosTrackingEnable == 1) {
Db::getInstance()->ExecuteS('
INSERT INTO `'._DB_PREFIX_.'ant_dropshipping_parcel`
VALUES (
'.(int) $id_order_detail.',
'.(int) $d['quantity'].',
"'.pSQL($o['tracking_number']).'",
"'.pSQL($o['carrier']).'",
"'.pSQL($o['link']).'",
NOW()
)
');
}
if ($infosTrackingDisable == 1) {
// Supprimer tracking_number et link
Db::getInstance()->ExecuteS('
INSERT INTO `'._DB_PREFIX_.'ant_dropshipping_parcel`
VALUES (
'.(int) $id_order_detail.',
'.(int) $d['quantity'].',
"",
"NOTRACKING",
"",
NOW()
)
');
}
}
}
if (count($remaining) == 0) {
$fully_sent = true;
} else {
$fully_sent = false;
}
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState(($fully_sent ? Configuration::get('PS_OS_SHIPPING') : 17), (int) $order->id);
$history->id_employee = 0;
$history->add();
// Send Mail with tracking info
if ($infosTrackingEnable == 1) {
Db::getInstance()->ExecuteS('
INSERT INTO `'._DB_PREFIX_.'shipping_history`
VALUES (
'.(int) $order->id.',
"'.pSQL($o['tracking_number']).'",
NOW(),
0,
'.(int)$id_sale.'
)
');
global $_LANGMAIL;
$subject = 'Package in transit';
$customer = new Customer((int) $order->id_customer);
$templateVars = array(
'{followup}' => $o['link'],
'{carrier}' => $o['carrier'],
'{tracking_number}' => $o['tracking_number'],
'{sale}' => $sale_names[(int)$order->id_lang],
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{id_order}' => (int) $order->id,
);
if (!Mail::Send(intval($order->id_lang), 'in_transit_dropshipping',
((is_array($_LANGMAIL) && key_exists($subject, $_LANGMAIL)) ? $_LANGMAIL[$subject] : $subject),
$templateVars, $customer->email, $customer->firstname.' '.$customer->lastname)) {
$errors++;
}
}
// Send Mail without tracking info
if ($infosTrackingDisable == 1) {
$subject = 'Package in transit';
$customer = new Customer((int) $order->id_customer);
$templateVars = array(
'{sale}' => $sale_names[(int)$order->id_lang],
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{id_order}' => (int) $order->id,
);
if (!Mail::Send(intval($order->id_lang), 'in_transit_dropshipping_noinfo',
((is_array($_LANGMAIL) && key_exists($subject, $_LANGMAIL)) ? $_LANGMAIL[$subject] : $subject),
$templateVars, $customer->email, $customer->firstname.' '.$customer->lastname)) {
$errors++;
}
}
}
if ($errors == 0) {
$this->_html .= HelperFormBootstrap::displaySuccess($this->l('Fichier importé avec succès !'));
} else {
$this->_html .= HelperFormBootstrap::displayErrors($this->l($errors.' mails n\'ont pas pu être envoyés'));
}
}
}
// Cookie
if (!isset($_COOKIE['logistics_sales'])){
setcookie('logistics_sales', $id_sale, 0, __PS_BASE_URI__);
} else {
$sales = explode('-', $_COOKIE['logistics_sales']);
if(!in_array($id_sale,$sales)){
$sales[] = $id_sale;
}
setcookie('logistics_sales', implode('-', $sales), 0, __PS_BASE_URI__);
}
}
else {
$this->_html .= HelperFormBootstrap::displayErrors($this->l('Aucune commande trouvée, vérifier votre fichier'));
}
}
}
public function display()
{
global $cookie, $currentIndex;
$base_link = $currentIndex . '&token='.Tools::getAdminTokenLite('AdminAntDropshippingtracking');
$this->_html = '';
$this->_postProcess();
$id_category_options = array();
foreach(Db::getInstance()->ExecuteS('
SELECT p.`id_sale`, c.`name`, c.`id_category`
FROM `'._DB_PREFIX_.'privatesale` p
LEFT JOIN `'._DB_PREFIX_.'category_lang` c ON (c.`id_category` = p.`id_category`)
LEFT JOIN `'._DB_PREFIX_.'privatesale_shipping_sale` s ON (s.`id_sale` = p.`id_sale`)
WHERE c.`id_lang` = '.$cookie->id_lang.'
AND s.id_shipping = 2
-- AND p.`date_start` > "2017-01-01 00:00:00"
ORDER BY p.`id_sale` DESC
LIMIT 1200
') as $row) {
$extrafields = Category::getSalesInfos(array((int) $row['id_category']));
$id_category_options[] = array(
'label' => (int) $row['id_sale'].' (#'.(int) $row['id_category'].') - '.$row['name'].(empty($extrafields[(int) $row['id_category']]['sales'][1])?'':' - '.$extrafields[(int) $row['id_category']]['sales'][1]) ,
'value' => (int) $row['id_sale']
);
}
$helperForm = new HelperFormBootstrap();
$helperForm->_select2 = true;
$this->_html .= $helperForm->renderStyle();
$this->_html .= '
<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-title">
<h2 class=""><span class="text-rose anticon anticon-truck"></span> '.$this->l('Import information dropshipping').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">
<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post" enctype="multipart/form-data">
<div class="col-md-12">';
$help = '<br>
<p class="help-block">'.$this->l('Format: id_order;tracking_number;carrier;tracking_link').'</p>
<p class="help-block">'.$this->l('The subsequent columns and the first line are ignored.').'</p>
<p class="help-block">'.$this->l('With tracking infos, all columns must be set.').'</p>
<p class="help-block">'.$this->l('Without tracking infos, use the same format but columns tracking_number, carrier and tracking_link must be empty.').'</p>
';
$input = array(
'label' => $this->l('Sale: '),
'type' => 'select2',
'label-class' => 'control-label',
'select-class' => 'input-class',
'name' => 'id_sale',
'options' => $id_category_options,
);
$this->_html .= '<div class="clearfix"></div>'.$helperForm->generateInput($input);
$input = array(
'type' => 'file',
'label' => $this->l('File:'),
'name' => 'csvfile',
'html' => $help
);
$this->_html .= $helperForm->generateInput($input);
$this->_html .= '
</div>
<div class="clearfix"></div>
<div class="ln_solid"></div>
<div class="form-group text-right">
<button type="submit" class="btn btn-primary" name="submitOrderTracking">'.$this->l('Importer avec tracking').'</button>
<button type="submit" class="btn btn-primary" name="submitOrderTrackingNull">'.$this->l('Importer sans tracking').'</button>
</div>
</form>
</div>
</div>
</div>
</div>
';
$this->_html .= $helperForm->renderScript();
echo $this->_html;
}
}