Files
2019-11-20 07:44:43 +01:00

546 lines
24 KiB
PHP

<?php
/**
* 2007-2017 Decanet
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.decanet.fr for more information.
*
* @author Decanet SA <contact@decanet.fr>
* @copyright 2007-2017 Decanet SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
require_once(dirname(__FILE__).'/../../prelevementsepa.php');
class AdminSepaOrdersController extends ModuleAdminController
{
public $module = 'prelevementsepa';
public $name = 'prelevementsepa';
public function __construct()
{
$this->path = _PS_MODULE_DIR_.$this->module.'/';
$this->className = 'prelevementsepa';
$this->display = 'edit';
$this->multishop_context = Shop::CONTEXT_ALL;
$this->id_lang = (int)Context::getContext()->language->id;
$this->lang = true;
$this->deleted = false;
$this->colorOnBackground = false;
$this->url = __PS_BASE_URI__.basename(_PS_MODULE_DIR_).'/'.$this->name.'/';
$this->images = $this->url.'views/img/';
$this->context = Context::getContext();
$this->bootstrap = true;
parent::__construct();
}
public function postProcess()
{
if (Tools::isSubmit('submitGenerateXML') || Tools::isSubmit('submitRegenerateXML')) {
require_once(dirname(__FILE__).'/../../classes/PrevSepaOrder.php');
require_once(dirname(__FILE__).'/../../classes/PrevSepaOrderTraited.php');
require_once(dirname(__FILE__).'/../../classes/PrevSepa.php');
require_once(dirname(__FILE__).'/../../classes/SepaDD.php');
require_once(dirname(__FILE__).'/../../classes/SepaDDCbi.php');
$order_state = false;
if (Tools::isSubmit('submitGenerateXML')) {
if ((int)Tools::getValue('id_order_state')>0) {
$id_order_state = (int)Tools::getValue('id_order_state');
$order_state = new OrderState($id_order_state);
if (!Validate::isLoadedObject($order_state)) {
$this->errors[] = sprintf(
Tools::displayError('Order status #%d cannot be loaded'),
$id_order_state
);
}
}
}
$params = array(
'name' => $this->module->conf_keys['creancier'],
'IBAN' => $this->module->conf_keys['IBAN'],
'BIC' => $this->module->conf_keys['BIC'],
'batch' => true,
'creditor_id' => $this->module->conf_keys['ICS'],
'delay_working' => $this->module->conf_keys['delay_working'],
'currency' => 'EUR',
'CBI' => $this->module->conf_keys['CBI']
);
if ($this->module->conf_keys['format']!='cbi') {
$sepadd = new SepaDD($params);
} else {
$sepadd = new SepaDDCbi($params);
}
if (Tools::isSubmit('submitGenerateXML')) {
$sepatraited_obj = new PrevSepaOrderTraited();
$sepatraited_obj->order_state = (int)Tools::getValue('id_order_state');
$sepatraited_obj->add();
}
if (Tools::getIsset('sepaordersBox') &&
is_array(Tools::getValue('sepaordersBox')) &&
count(Tools::getValue('sepaordersBox'))>0) {
foreach (Tools::getValue('sepaordersBox') as $id_sepa) {
if (count($this->errors)==0) {
$sepa_obj = new PrevSepaOrder((int)$id_sepa);
$order = new Order((int)$sepa_obj->id_order);
$id_order = $order->id;
if (!Validate::isLoadedObject($order)) {
$this->errors[] = sprintf(
Tools::displayError('Order #%d cannot be loaded'),
$id_order
);
} else {
if (Tools::isSubmit('submitGenerateXML')) {
$sepatraited_obj->addOrder($id_order);
}
try {
$customer = new Customer((int)$order->id_customer);
$sepa_customer_obj = new PrevSepa($sepa_obj->id_sepa);
$sepa_obj->traite = 1;
$amount = (int)round($order->total_paid * 100);
$sepa_obj->save();
if ((Tools::strlen($customer->company)>0)) {
$name = $customer->company;
} elseif (Tools::strlen($customer->firstname.$customer->lastname) > 3) {
$name = $customer->firstname.' '.$customer->lastname;
} else {
$name = 'No name';
}
$mandateid = $order->invoice_number ? Configuration::get('PS_INVOICE_PREFIX', $order->id_lang).sprintf('%06d', $order->invoice_number) : $order->reference;
$payment = array(
'name' => $name,
'IBAN' => $sepa_customer_obj->iban,
'BIC' => $sepa_customer_obj->bic,
'amount' => $amount,
'type' => empty($sepa_customer_obj->sepa_type) ? 'RCUR' : $sepa_customer_obj->sepa_type,
'collection_date' => date(
'Y-m-d',
$this->getWorkingDays(
time(),
($this->module->conf_keys['delay_working']?
$this->module->conf_keys['delay_working']:2)
)
),
'mandate_id' => $mandateid,
'mandate_date' => date('Y-m-d'),
'description' => str_replace(
'[reference]',
$order->reference,
$this->module->conf_keys['label']
)
);
$sepadd->addPayment($payment);
if ($sepa_customer_obj->sepa_type=='FRST') {
$sepa_customer_obj->sepa_type='RCUR';
$sepa_customer_obj->save();
}
if (Tools::isSubmit('submitGenerateXML')) {
if ($order_state && Validate::isLoadedObject($order_state)) {
$current_order_state = $order->getCurrentOrderState();
if ($current_order_state->id == $order_state->id) {
$this->errors[] = $this->displayWarning(
sprintf('Order #%d has already been assigned this status.', $id_order)
);
} else {
$history = new OrderHistory();
$history->id_order = $order->id;
$history->id_employee = (int)$this->context->employee->id;
$use_existings_payment = !$order->hasInvoice();
$history->changeIdOrderState(
(int)$order_state->id,
$order,
$use_existings_payment
);
$carrier = new Carrier($order->id_carrier, $order->id_lang);
$templateVars = array();
if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING')
&& $order->shipping_number
) {
$templateVars = array(
'{followup}' => str_replace(
'@',
$order->shipping_number,
$carrier->url
)
);
}
if ($history->addWithemail(true, $templateVars)) {
if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
foreach ($order->getProducts() as $product) {
if (StockAvailable::dependsOnStock($product['product_id'])) {
StockAvailable::synchronize(
$product['product_id'],
(int)$product['id_shop']
);
}
}
}
} else {
$this->errors[] = sprintf(
Tools::displayError('Cannot change status for order #%d.'),
$id_order
);
}
}
}
}
} catch (Exception $e) {
$this->errors[] = 'Order '.$order->reference.' : '.$e->getMessage();
}
}
}
}
}
if (count($this->errors)==0) {
$filename = 'sepa_file_'.date('Y-m-d-His').'.xml';
file_put_contents(_PS_CACHE_DIR_.$filename, $sepadd->save());
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token
.'&file='.$filename);
}
}
parent::postProcess();
}
public function renderForm()
{
if (Tools::getIsset('dl')) {
if (!file_exists(_PS_CACHE_DIR_.Tools::getValue('dl'))) {
$this->errors[] = $this->module->l('A problem occurred with the file download. '
. 'Maybe you have already downloaded it?');
} else {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.Tools::getValue('dl'));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.filesize(_PS_CACHE_DIR_.Tools::getValue('dl')));
readfile(_PS_CACHE_DIR_.Tools::getValue('dl'));
@unlink(_PS_CACHE_DIR_.Tools::getValue('dl'));
die();
}
}
require_once(dirname(__FILE__).'/../../classes/PrevSepaOrder.php');
$traited = (int)Tools::getValue('etat', 0);
if (Tools::getIsset('submitResetsepaorders')) {
$_POST['sepaordersFilter_id_sepa_detail'] = null;
$_POST['sepaordersFilter_order'] = null;
$_POST['sepaordersFilter_customer'] = null;
}
$fields_list = array(
'id_sepa_detail' => array(
'title' => $this->l('Id'),
'width' => 140,
'type' => 'text',
),
'order' => array(
'title' => $this->l('Order number'),
'width' => 140,
'type' => 'text',
'search' => 'true',
'orderby' => false
),
'customer' => array(
'title' => $this->l('Customer'),
'width' => 140,
'type' => 'text',
'search' => 'true',
'orderby' => false
),
'sepa_date' => array(
'title' => $this->l('Payment date'),
'width' => 70,
'type' => 'date',
'search' => false,
'orderby' => false
),
'jn' => array(
'title' => $this->l('J +/-N'),
'width' => 70,
'type' => 'text',
'search' => false,
'orderby' => false
),
'remarks' => array(
'title' => $this->l('Remarks'),
'width' => 140,
'type' => 'text',
'search' => false,
'orderby' => false,
)
);
$helper = new HelperList();
$helper->module = $this->module;
$helper->shopLinkType = '';
//$helper->simple_header = true;
$helper->list_id = $list_id = 'sepaorders';
if ($traited == 1) {
$helper->actions = array('view');
}
$helper->identifier = 'id_sepa_detail';
//$helper->show_toolbar = true;
$helper->title = $this->l('SEPA Direct Debits');
$helper->no_link = true;
$helper->token = $this->token;
$helper->currentIndex = self::$currentIndex;
// if (!$traited) {
$helper->bulk_actions = array(
'generateXML' => array(
'text' => $this->l('Generate the XML file'),
'icon' => 'icon-refresh'
)
);
$helper->force_show_bulk_actions = true;
// }
if (Tools::getIsset('file')) {
$helper->tpl_vars['dlFile'] = Tools::getValue('file');
}
if (Tools::isSubmit('submitBulkgenerateXMLconfiguration')) {
if (Tools::getIsset('cancel')) {
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token);
}
$helper->tpl_vars['updateOrderStatus_mode'] = 1;
$statuses = OrderState::getOrderStates((int)$this->context->language->id);
$helper->tpl_vars['order_statuses'] = array();
foreach ($statuses as $status) {
$helper->tpl_vars['order_statuses'][$status['id_order_state']] = $status['name'];
}
$helper->tpl_vars['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
}
$helper->tpl_vars['POST'] = $_POST;
if ($traited == 2) {
$sepa = PrevSepaOrder::getAllSepa(0, 0, null);
} else {
$sepa = PrevSepaOrder::getAllSepa($traited);
}
$sepa_list = array();
if ($sepa && count($sepa)>0) {
foreach ($sepa as $s) {
if (Tools::getValue('sepaordersFilter_id_sepa_detail') && Tools::getValue('sepaordersFilter_id_sepa_detail') != $s['id_sepa_detail']) {
continue;
}
$s['remarks'] = '';
$s['jn'] = '';
if (empty($s['rum'])) {
$s['remarks'] .= $this->l('RUM is empty')."; ";
}
if (empty($s['iban'])) {
$s['remarks'] .= $this->l('IBAN is empty')."; ";
}
if (empty($s['bic'])) {
$s['remarks'] .= $this->l('BIC is empty')."; ";
}
$s['order'] = new Order((int)$s['id_order']);
if ($s['order']->valid == 1) {
if (Tools::getValue('sepaordersFilter_order') && !preg_match('#'.Tools::getValue('sepaordersFilter_order').'#i', $s['order']->reference)) {
continue;
}
$nbdays = (strtotime($s['sepa_date']) - time()) / 86400;
// die(var_dump(intval($nbdays)));
if ($nbdays < 0) {
$s['jn'] = 'J -'.floor(abs($nbdays));
} else {
$s['jn'] = 'J +'.floor(abs($nbdays));
}
$customer_obj = new Customer((int)$s['order']->id_customer);
if (Tools::getValue('sepaordersFilter_customer') && !preg_match('#'.Tools::getValue('sepaordersFilter_customer').'#i', $customer_obj->firstname) && !preg_match('#'.Tools::getValue('sepaordersFilter_customer').'#i', $customer_obj->lastname)) {
continue;
}
$sepa_list[] = array(
'id_sepa_detail' => $s['id_sepa_detail'],
'order' => $s['order']->reference,
'customer' => Tools::strtoupper(Tools::substr($customer_obj->firstname, 0, 1).'. '.$customer_obj->lastname),
'sepa_date' => $s['sepa_date'],
'jn' => $s['jn'],
'remarks' => $s['remarks']
);
}
}
}
return $helper->generateList($sepa_list, $fields_list);
}
public function ajaxProcessGetUnvalidOrdersSEPA()
{
$sepa = PrevSepaOrder::getAllUnActive();
if (is_array($sepa) && count($sepa)) {
foreach ($sepa as &$s) {
$s['order'] = new Order((int)$s['id_order']);
$s['customer'] = new Customer((int)$s['order']->id_customer);
}
}
$this->context->smarty->assign('path', $this->url);
$this->context->smarty->assign('modimgdir', $this->images);
$this->context->smarty->assign('sepaList', $sepa);
echo $this->context->smarty->fetch($this->path.'views/templates/admin/sepa_list.tpl');
die();
}
public function getWorkingDays($date_start, $nb_days)
{
$wd = 1;
$i = 1;
while ($wd <= $nb_days) {
$date_mk = $date_start + (86400 * $i);
if ((date("N", $date_mk) != 6) && (date("N", $date_mk) != 7)) {
$wd++;
}
$i++;
}
return $date_start +(86400 * ($i-1));
}
public function getWorkingDay($date_start, $nb_days)
{
$date_start = $date_start + (86400 * $nb_days);
if ((date("N", $date_start) != 6) && (date("N", $date_start) != 7)) {
return $date_start;
} else {
$date_start = $date_start + 86400;
if ((date("N", $date_start) != 6) && (date("N", $date_start) != 7)) {
return $date_start;
} else {
return $date_start + 86400;
}
}
}
public function renderView()
{
require_once(dirname(__FILE__).'/../../classes/PrevSepaOrder.php');
$sepa_obj = new PrevSepaOrder((int) Tools::getValue('id_sepa_detail'));
$sepa = PrevSepaOrder::getGeneratedSepaList($sepa_obj->id_order);
$fields_list = array(
'id_sepa_detail' => array(
'title' => $this->l('Id'),
'width' => 140,
'type' => 'text',
),
'order' => array(
'title' => $this->l('Order number'),
'width' => 140,
'type' => 'text',
),
'sepa_date' => array(
'title' => $this->l('Payment date'),
'width' => 140,
'type' => 'date',
),
'jn' => array(
'title' => $this->l('J +/-N'),
'width' => 140,
'type' => 'text',
'search' => false,
'orderby' => false,
),
'remarks' => array(
'title' => $this->l('Remarks'),
'width' => 140,
'type' => 'text',
'search' => false,
'orderby' => false,
)
);
$helper = new HelperList();
// $helper->module = $this->module;
$helper->shopLinkType = '';
$helper->simple_header = false;
$helper->actions = array('');
$helper->identifier = 'id_sepa_detail';
$helper->title = $this->l('SEPA Direct Debits');
$helper->no_link = true;
$helper->token = $this->token;
$helper->currentIndex = self::$currentIndex;
$sepa_list = array();
if (count($sepa)>0) {
foreach ($sepa as $s) {
$s['remarks'] = '';
$s['jn'] = '';
if (empty($s['rum'])) {
$s['remarks'] .= $this->l('RUM is empty')."; ";
}
if (empty($s['iban'])) {
$s['remarks'] .= $this->l('IBAN is empty')."; ";
}
if (empty($s['bic'])) {
$s['remarks'] .= $this->l('BIC is empty')."; ";
}
$s['order'] = new Order((int)$s['id_order']);
if ($s['order']->valid == 1) {
$nbdays = (strtotime($s['sepa_date']) - time()) / 86400;
if ($nbdays < 0) {
$s['jn'] = 'J -'.floor(abs($nbdays));
} else {
$s['jn'] = 'J +'.floor(abs($nbdays));
}
$sepa_list[] = array(
'id_sepa_detail' => $s['id_sepa_detail'],
'order' => $s['order']->reference,
'sepa_date' => $s['sepa_date'],
'jn' => $s['jn'],
'remarks' => $s['remarks']
);
}
}
}
$this->tpl_view_vars = array(
'sepas' => $sepa_list,
'sepalist' => $helper->generateList($sepa_list, $fields_list)
);
if (Tools::getIsset('file')) {
$this->tpl_view_vars['dlFile'] = Tools::getValue('file');
}
return parent::renderView();
}
}