Files
masimmo.pl/modules/raty/raty.php
Roman Pyrih e75fa515f5 Save
2024-12-12 15:57:01 +01:00

793 lines
33 KiB
PHP

<?php
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
if (!defined('_PS_VERSION_')) {
exit;
}
class Raty extends PaymentModule
{
protected $_html = '';
protected $_postErrors = array();
public $details;
public $owner;
public $address;
public $extra_mail_vars;
public $paymentUrl;
public $kalkulatorUrl;
public function __construct()
{
$this->name = 'raty';
$this->tab = 'payments_gateways';
$this->version = '1.5.12';
$this->author = 'Alior Bank';
$this->bootstrap = true;
$this->is_eu_compatible = 1;
$this->controllers = array('payment', 'validation');
$this->is_eu_compatible = 1;
$this->ps_versions_compliancy = array('min' => '1.7');
parent::__construct();
$this->displayName = $this->l('Raty');
$this->description = $this->l('Moduł do obsługi rat Alior Banku.');
$this->confirmUninstall = $this->l('Czy jesteś pewien aby odinstalować ten moduł?');
$this->kalkulatorUrl = 'https://kalkulator.raty.aliorbank.pl/';
$this->paymentUrl = 'https://raty.aliorbank.pl/directcreditsystem-frontend-consumerfinance-internet-standard/paymentprovider/';
if (!Configuration::get('RATY_NAME')) {
$this->warning = $this->l('No name provided');
}
}
private function createOrderState()
{
// create new order status STATUSNAME
$values_to_insert = [
'invoice' => 0,
'send_email' => 0,
'module_name' => $this->name,
'color' => 'RoyalBlue',
'unremovable' => 0,
'hidden' => 0,
'logable' => 0,
'delivery' => 0,
'shipped' => 0,
'paid' => 0,
'deleted' => 0
];
if (!Db::getInstance()->insert('order_state', $values_to_insert)) {
return false;
}
$id_order_state = (int) Db::getInstance()->Insert_ID();
$languages = Language::getLanguages(false);
foreach ($languages as $language) {
Db::getInstance()->insert('order_state_lang', [
'id_order_state' => $id_order_state,
'id_lang' => $language['id_lang'],
'name' => 'Oczekiwanie na zatwierdzenie umowy ratalnej przez Alior Bank',
'template' => ''
]);
}
if (!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alior.gif', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 'os' . DIRECTORY_SEPARATOR . $id_order_state . '.gif')) {
return false;
}
Configuration::updateValue('PS_OS_RATY', $id_order_state);
unset($id_order_state);
return true;
}
public function install()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
if (
!parent::install()
|| !$this->installSql()
|| !$this->registerHook('displayHeader')
|| !$this->registerHook('displayProductButtons')
|| !$this->registerHook('displayShoppingCartFooter')
|| !$this->registerHook('payment')
|| !$this->registerHook('paymentOptions')
|| !$this->registerHook('paymentReturn')
|| !$this->registerHook('displayAdminProductsMainStepLeftColumnBottom')
|| !$this->registerHook('displayBackOfficeCategory')
|| !$this->registerHook('actionObjectProductUpdateBefore')
|| !$this->registerHook('actionObjectCategoryAddBefore')
|| !$this->registerHook('actionObjectCategoryUpdateBefore')
|| !$this->createOrderState()
|| !Configuration::updateValue('RATY_NAME', 'Raty')
|| !Configuration::updateValue('RATY_PARTNERID', '1001')
|| !Configuration::updateValue('RATY_SUBPARTNERID', '')
|| !Configuration::updateValue('RATY_MCC', '')
|| !Configuration::updateValue('RATY_STANDARD_PROMOTION', '')
|| !Configuration::updateValue('RATY_CATEGORY_PROMOTION', '')
|| !Configuration::updateValue('RATY_CATEGORY_PROMOTION_START', '')
|| !Configuration::updateValue('RATY_CATEGORY_PROMOTION_END', '')
|| !Configuration::updateValue('RATY_PRODUCT_PROMOTION', '')
|| !Configuration::updateValue('RATY_PRODUCT_PROMOTION_START', '')
|| !Configuration::updateValue('RATY_PRODUCT_PROMOTION_END', '')
|| !Configuration::updateValue('RATY_MIN_VALUE', '0')
|| !Configuration::updateValue('RATY_MAX_VALUE', '26920')
|| !Configuration::updateValue('RATY_SALT', 'QWERSJR1234$$%')
|| !Configuration::updateValue('RATY_TITLE', 'Raty - Alior Bank')
|| !Configuration::updateValue('RATY_DESCRIPTION', '')
) {
return false;
}
return true;
}
public function uninstall()
{
if (
!parent::uninstall()
|| !Configuration::deleteByName('RATY_NAME')
|| !Configuration::deleteByName('RATY_PARTNERID')
|| !Configuration::deleteByName('RATY_SUBPARTNERID')
|| !Configuration::deleteByName('RATY_MCC')
|| !Configuration::deleteByName('RATY_STANDARD_PROMOTION')
|| !Configuration::deleteByName('RATY_CATEGORY_PROMOTION')
|| !Configuration::deleteByName('RATY_CATEGORY_PROMOTION_START')
|| !Configuration::deleteByName('RATY_CATEGORY_PROMOTION_END')
|| !Configuration::deleteByName('RATY_PRODUCT_PROMOTION')
|| !Configuration::deleteByName('RATY_PRODUCT_PROMOTION_START')
|| !Configuration::deleteByName('RATY_PRODUCT_PROMOTION_END')
|| !Configuration::deleteByName('RATY_MIN_VALUE')
|| !Configuration::deleteByName('RATY_MAX_VALUE')
|| !Configuration::deleteByName('RATY_SALT')
|| !Configuration::deleteByName('RATY_TITLE')
|| !Configuration::deleteByName('RATY_DESCRIPTION')
) {
return false;
}
return true;
}
protected function installSql() {
$data = [
'product' => 'alior_product_promotion',
'product_shop' => 'alior_product_promotion',
'category' => 'alior_category_promotion',
'category_shop' => 'alior_category_promotion',
];
foreach($data as $table => $column) {
if(!$this->isColumnExists($table, $column)) {
$sql = 'ALTER TABLE ' . _DB_PREFIX_ . $table . ' ADD ' . $column . ' INT NULL';
$result = Db::getInstance()->execute($sql);
if(!$result) {
return false;
}
}
}
return true;
}
private function isColumnExists($table, $column) {
$db = Db::getInstance();
$db->executeS("SELECT count(" . $column . ') FROM ' . _DB_PREFIX_ . $table);
return $db->numRows() > 0;
}
public function hookActionObjectProductUpdateBefore($params) {
$product = $params['object'];
if(!isset($_POST['alior_product_promotion'])) {
$product->alior_product_promotion = 0;
}
return;
}
public function hookActionObjectCategoryUpdateBefore($params) {
$category = $params['object'];
$category->alior_category_promotion = 1;
if(!isset($_POST['alior_category_promotion'])) {
$category->alior_category_promotion = 0;
}
return;
}
public function hookActionObjectCategoryAddBefore($params) {
$category = $params['object'];
$category->alior_category_promotion = 1;
if(!isset($_POST['alior_category_promotion'])) {
$category->alior_category_promotion = 0;
}
return;
}
public function hookDisplayAdminProductsMainStepLeftColumnBottom($params) {
$product = new Product($params['id_product']);
$this->context->smarty->assign(array('alior_product_promotion' => $product->alior_product_promotion));
return $this->display(__FILE__, 'views/templates/hook/updateproduct.tpl');
}
public function hookDisplayBackOfficeCategory($params) {
$id = (int)Tools::getValue('id_category');
if(isset($params['request'])) {
$id = $params['request']->get('categoryId');
}
$category = new Category($id);
$this->context->smarty->assign(array('alior_category_promotion' => $category->alior_category_promotion));
return $this->display(__FILE__, 'views/templates/hook/updatecategory.tpl');
}
public function hookPaymentOptions($params)
{
if (!$this->active) {
return;
}
if (!$this->checkCurrency($params['cart']) || !$this->checkAmount($params['cart']->getOrderTotal()) || !$this->getPromotion($params['cart']->getProducts())) {
return;
}
$this->context->smarty->assign(['raty_description' => Configuration::get('RATY_DESCRIPTION')]);
$offlineOption = new PaymentOption();
$offlineOption->setCallToActionText(Configuration::get('RATY_TITLE'))
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
->setAdditionalInformation($this->fetch('module:raty/views/templates/front/payment_infos.tpl'))
->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/alior.gif'));
return [
$offlineOption,
];
}
public function getContent()
{
$output = '';
if (Tools::isSubmit('submitRaty')) {
$error = false;
if (!($raty_parentid = Tools::getValue('RATY_PARTNERID')) || empty($raty_parentid)) {
$output .= $this->displayError($this->l('Musisz wypełnić pole \'Parent ID\'.'));
$error = true;
} elseif (!$error) {
Configuration::updateValue('RATY_PARTNERID', $raty_parentid);
}
Configuration::updateValue('RATY_SUBPARTNERID', Tools::getValue('RATY_SUBPARTNERID'));
if (!($raty_salt = Tools::getValue('RATY_SALT')) || empty($raty_salt)) {
$output .= $this->displayError($this->l('Musisz wypełnić pole \'Salt\'.'));
$error = true;
} elseif (!$error) {
Configuration::updateValue('RATY_SALT', $raty_salt);
}
Configuration::updateValue('RATY_MCC', Tools::getValue('RATY_MCC'));
Configuration::updateValue('RATY_STANDARD_PROMOTION', Tools::getValue('RATY_STANDARD_PROMOTION'));
Configuration::updateValue('RATY_CATEGORY_PROMOTION', Tools::getValue('RATY_CATEGORY_PROMOTION'));
Configuration::updateValue('RATY_CATEGORY_PROMOTION_START', Tools::getValue('RATY_CATEGORY_PROMOTION_START'));
Configuration::updateValue('RATY_CATEGORY_PROMOTION_END', Tools::getValue('RATY_CATEGORY_PROMOTION_END'));
Configuration::updateValue('RATY_PRODUCT_PROMOTION', Tools::getValue('RATY_PRODUCT_PROMOTION'));
Configuration::updateValue('RATY_PRODUCT_PROMOTION_START', Tools::getValue('RATY_PRODUCT_PROMOTION_START'));
Configuration::updateValue('RATY_PRODUCT_PROMOTION_END', Tools::getValue('RATY_PRODUCT_PROMOTION_END'));
Configuration::updateValue('RATY_MIN_VALUE', $this->changeNumberFormat(Tools::getValue('RATY_MIN_VALUE')));
Configuration::updateValue('RATY_MAX_VALUE', $this->changeNumberFormat(Tools::getValue('RATY_MAX_VALUE')));
Configuration::updateValue('RATY_DESCRIPTION', Tools::getValue('RATY_DESCRIPTION'));
Configuration::updateValue('RATY_TITLE', Tools::getValue('RATY_TITLE'));
if (!$error) {
$output .= $this->displayConfirmation($this->l('Parametry uaktualnione.'));
}
}
return $output . $this->renderForm();
}
public function hookDisplayProductButtons($params)
{
$product = $params['product'];
if (empty($product->price_amount)){
return;
}
$price = $product->price_amount;
if (!$this->checkAmount($price)) {
return;
}
$promotion = $this->getPromotion([$product]);
if (!$promotion) {
return;
}
if (!$this->isCached('productraty.tpl', $this->getCacheId($product->id))) {
$promotion = str_replace('${sep}', '%2C', $promotion);
$this->smarty->assign(array(
'this_path_raty' => $this->_path,
'this_kalkulator' => $this->kalkulatorUrl .
'init?supervisor=' . Configuration::get('RATY_PARTNERID') .
'&promotionList='.$promotion.'&amount=',
'this_cena' => $this->changeNumberFormat(round($price, 2))
));
}
return $this->display(__FILE__, 'productraty.tpl', $this->getCacheId($product->id));
}
public function hookDisplayProductAdditionalInfo($params)
{
$product = $params['product'];
if (empty($product->price_amount)){
return;
}
$price = $product->price_amount;
if (!$this->checkAmount($price)) {
return;
}
$promotion = $this->getPromotion([$product]);
if (!$promotion) {
return;
}
if (!$this->isCached('productraty.tpl', $this->getCacheId($product->id))) {
$promotion = str_replace('${sep}', '%2C', $promotion);
$this->smarty->assign(array(
'this_path_raty' => $this->_path,
'this_kalkulator' => $this->kalkulatorUrl .
'init?supervisor=' . Configuration::get('RATY_PARTNERID') .
'&promotionList='.$promotion.'&amount=',
'this_cena' => $this->changeNumberFormat(round($price, 2))
));
}
return $this->display(__FILE__, 'productraty.tpl', $this->getCacheId($product->id));
}
public function hookDisplayShoppingCartFooter($params)
{
if (!$this->checkCurrency($params['cart']) || !$this->checkAmount($params['cart']->getOrderTotal())) {
return;
}
$promotion = $this->getPromotion($params['cart']->getProducts());
if(!$promotion){
return;
}
$promotion = str_replace('${sep}', '%2C', $promotion);
$this->smarty->assign(array(
'this_path_raty' => $this->_path,
'this_kalkulator' => $this->kalkulatorUrl .
'init?supervisor=' . Configuration::get('RATY_PARTNERID') .
'&promotionList='.$promotion.'&amount=',
'this_cena' => $this->changeNumberFormat($params['cart']->getOrderTotal()),
));
return $this->display(__FILE__, 'raty_cart.tpl');
}
public function hookDisplayHeader($params)
{
$this->context->controller->addCSS($this->_path . 'raty.css', 'all');
}
public function hookPaymentReturn($params)
{
if (!$this->active) {
return;
}
$order = $params['order'];
$state = $order->getCurrentState();
if (in_array($state, array(Configuration::get('PS_OS_RATY'), Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')))) {
$customer = new Customer($order->id_customer);
$firstName = $customer->firstname;
$lastName = $customer->lastname;
$partnerId = Configuration::get('RATY_PARTNERID');
$subpartnerId = Configuration::get('RATY_SUBPARTNERID');
$mcc = Configuration::get('RATY_MCC');
$promotion = $this->getPromotion($order->getProductsDetail());
$salt = Configuration::get('RATY_SALT');
$calculatedIncome = '';
$limit = '';
$transactionCode = $order->reference;
$total = $this->getRounded($order->total_paid);
$date = date('Y-m-d');
$time = date('H:i:s');
$dateAndTime = $date . 'T' . $time;
$verificationCode = hash('sha256', $salt . $this->changeNumberFormat($total) .
$transactionCode . $partnerId . $subpartnerId . $dateAndTime . $mcc . $firstName . $lastName . $limit . $calculatedIncome . $promotion);
$values = [
'url' => $this->paymentUrl,
'firstName' => $firstName,
'lastName' => $lastName,
'partnerId' => $partnerId,
'subpartnerId' => $subpartnerId,
'mcc' => $mcc,
'limit' => $limit,
'promotion' => $promotion,
'calculatedIncome' => $calculatedIncome,
'verificationCode' => $verificationCode,
'transactionCode' => $transactionCode,
'dateAndTime' => $dateAndTime,
'amount' => $this->changeNumberFormat($total),
'status' => 'ok',
'articlesList' => base64_encode(json_encode($this->getAliorsArticlesListJson($order)))
];
$this->context->smarty->assign($values);
} else {
$this->context->smarty->assign('status', 'failed');
}
return $this->context->smarty->fetch('module:raty/views/templates/hook/payment_return.tpl');
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Ustawienia'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('PartnerID'),
'name' => 'RATY_PARTNERID',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod partnera handlowego')
),
array(
'type' => 'text',
'label' => $this->l('SubpartnerID'),
'name' => 'RATY_SUBPARTNERID',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Dodatkowy kod partnera handlowego.')
),
array(
'type' => 'text',
'label' => $this->l('MCC'),
'name' => 'RATY_MCC',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod MCC.')
),
array(
'type' => 'text',
'label' => $this->l('Oferta standardowa'),
'name' => 'RATY_STANDARD_PROMOTION',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod oferty standardowej.')
),
array(
'type' => 'html',
'label' => $this->l('Oferta specjalna dla Kategorii'),
'name' => 'RATY_CATEGORY_PROMOTION',
'desc' => $this->l('Kod oferty specjalnej dla Kategorii.'),
'html_content' =>
'<div class="row">'
. '<div>'
. '<div class="col-lg-6 col-md-12 col-sm-12">'
. '<input type="text" name="RATY_CATEGORY_PROMOTION" id="RATY_CATEGORY_PROMOTION" class="" value="' . Configuration::get('RATY_CATEGORY_PROMOTION') . '" style="width: 250px;">'
. '</div>'
. '<div class="col-lg-6 col-md-12 col-sm-12" style="padding-top: 0; display: flex;">'
. '<span class="col-lg-3 control-label">Czas trwania:</span>'
. '<div class="col-lg-9">'
. '<input type="date" name="RATY_CATEGORY_PROMOTION_START" id="RATY_CATEGORY_PROMOTION_START" class="" value="' . Configuration::get('RATY_CATEGORY_PROMOTION_START') . '"> - '
. '<input type="date" name="RATY_CATEGORY_PROMOTION_END" id="RATY_CATEGORY_PROMOTION_END" class="" value="' . Configuration::get('RATY_CATEGORY_PROMOTION_END') . '">'
. '</div>'
. '</div>'
. '</div>'
),
array(
'type' => 'html',
'label' => $this->l('Oferta specjalna dla Produktu'),
'name' => 'RATY_PRODUCT_PROMOTION',
'desc' => $this->l('Kod oferty specjalnej dla Produktu.'),
'html_content' =>
'<div class="row">'
. '<div>'
. '<div class="col-lg-6 col-md-12 col-sm-12">'
. '<input type="text" name="RATY_PRODUCT_PROMOTION" id="RATY_PRODUCT_PROMOTION" class="" value="' . Configuration::get('RATY_PRODUCT_PROMOTION') . '" style="width: 250px;">'
. '</div>'
. '<div class="col-lg-6 col-md-12 col-sm-12" style="padding-top: 0; display: flex;">'
. '<span class="col-lg-3 control-label">Czas trwania:</span>'
. '<div class="col-lg-9">'
. '<input type="date" name="RATY_PRODUCT_PROMOTION_START" id="RATY_PRODUCT_PROMOTION_START" class="" value="' . Configuration::get('RATY_PRODUCT_PROMOTION_START') . '"> - '
. '<input type="date" name="RATY_PRODUCT_PROMOTION_END" id="RATY_PRODUCT_PROMOTION_END" class="" value="' . Configuration::get('RATY_PRODUCT_PROMOTION_END') . '">'
. '</div>'
. '</div>'
. '</div>'
),
array(
'type' => 'text',
'label' => $this->l('Minimalna wartość'),
'name' => 'RATY_MIN_VALUE',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Minimalna wartość od której dostępna jest sprzedaż ratalna.')
),
array(
'type' => 'text',
'label' => $this->l('Maksymalna wartość'),
'name' => 'RATY_MAX_VALUE',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Maksymalna wartość do której dostępna jest sprzedaż ratalna.')
),
array(
'type' => 'text',
'label' => $this->l('Salt'),
'name' => 'RATY_SALT',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod Salt odtrzymany od banku')
),
array(
'type' => 'text',
'label' => $this->l('Nazwa płatności'),
'name' => 'RATY_TITLE',
'class' => 'fixed-width-xxl',
),
array(
'type' => 'textarea',
'label' => $this->l('Dodatkowy opis'),
'name' => 'RATY_DESCRIPTION',
'class' => 'fixed-width-xxl',
),
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitRaty';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
public function checkCurrency($cart)
{
$currency_order = new Currency($cart->id_currency);
$currencies_module = $this->getCurrency($cart->id_currency);
if (is_array($currencies_module)) {
foreach ($currencies_module as $currency_module) {
if ($currency_order->id == $currency_module['id_currency']) {
return true;
}
}
}
return false;
}
public function getConfigFieldsValues()
{
return array(
'RATY_PARTNERID' => Tools::getValue('RATY_PARTNERID', Configuration::get('RATY_PARTNERID')),
'RATY_SUBPARTNERID' => Tools::getValue('RATY_SUBPARTNERID', Configuration::get('RATY_SUBPARTNERID')),
'RATY_MCC' => Tools::getValue('RATY_MCC', Configuration::get('RATY_MCC')),
'RATY_STANDARD_PROMOTION' => Tools::getValue('RATY_STANDARD_PROMOTION', Configuration::get('RATY_STANDARD_PROMOTION')),
'RATY_PRODUCT_PROMOTION' => Tools::getValue('RATY_PRODUCT_PROMOTION', Configuration::get('RATY_PRODUCT_PROMOTION')),
'RATY_PRODUCT_PROMOTION_START' => Tools::getValue('RATY_PRODUCT_PROMOTION_START', Configuration::get('RATY_PRODUCT_PROMOTION_START')),
'RATY_PRODUCT_PROMOTION_END' => Tools::getValue('RATY_PRODUCT_PROMOTION_END', Configuration::get('RATY_PRODUCT_PROMOTION_END')),
'RATY_CATEGORY_PROMOTION' => Tools::getValue('RATY_CATEGORY_PROMOTION', Configuration::get('RATY_CATEGORY_PROMOTION')),
'RATY_CATEGORY_PROMOTION_START' => Tools::getValue('RATY_CATEGORY_PROMOTION_START', Configuration::get('RATY_CATEGORY_PROMOTION_START')),
'RATY_CATEGORY_PROMOTION_END' => Tools::getValue('RATY_CATEGORY_PROMOTION_END', Configuration::get('RATY_CATEGORY_PROMOTION_END')),
'RATY_MIN_VALUE' => Tools::getValue('RATY_MIN_VALUE', $this->changeNumberFormat(Configuration::get('RATY_MIN_VALUE'))),
'RATY_MAX_VALUE' => Tools::getValue('RATY_MAX_VALUE', $this->changeNumberFormat(Configuration::get('RATY_MAX_VALUE'))),
'RATY_SALT' => Tools::getValue('RATY_SALT', Configuration::get('RATY_SALT')),
'RATY_TITLE' => Tools::getValue('RATY_TITLE', Configuration::get('RATY_TITLE')),
'RATY_DESCRIPTION' => Tools::getValue('RATY_DESCRIPTION', Configuration::get('RATY_DESCRIPTION')),
);
}
public function checkAmount($total)
{
$minValue = (float) $this->changeNumberFormat(Configuration::get('RATY_MIN_VALUE'));
$maxValue = (float) $this->changeNumberFormat(Configuration::get('RATY_MAX_VALUE'));
if($minValue > 0 && $maxValue > 0) {
return $total >= $minValue && $total <= $maxValue;
}
return false;
}
private function changeNumberFormat($value)
{
return number_format($value, 2, '.', '');
}
private function getAliorsArticlesListJson($order)
{
$products = $order->getProductsDetail();
$totalShippingCost = (float)$order->total_shipping;
$totalDiscounts = (float)$order->total_discounts;
$totalWrapping = (float)$order->total_wrapping;
// @see https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue
// json_encode makes float values wrong. This is simple fix
if (version_compare(phpversion(), '7.1', '>=')) {
ini_set( 'serialize_precision', -1 );
}
$json = ['articlesList' => []];
foreach ($products as $prod) {
if (!empty($prod['unit_price_tax_incl'])){
$price = $prod['unit_price_tax_incl'];
} else {
$price = !empty($prod['product_price_wt']) ? $prod['product_price_wt'] : $prod['product_price'];
}
$json['articlesList'][] = [
"category" => $this->getAliorsCategory($prod['id_category_default']),
"name" => $this->clearName($prod['product_name']),
"number" => (int)$prod['product_quantity'],
"price" => $this->getRounded($price),
];
}
if ($totalShippingCost){
$json['articlesList'][] = [
"category" => 'TKC_USLUGI', // from Alior's docs
"name" => 'Shipping costs',
"number" => 1,
"price" => $this->getRounded($totalShippingCost),
];
}
if ($totalDiscounts){
$json['articlesList'][] = [
"category" => 'TKC_RABAT', // from Alior's docs
"name" => 'Discount',
"number" => 1,
"price" => $this->getRounded($totalDiscounts) * -1,
];
}
if ($totalWrapping){
$json['articlesList'][] = [
"category" => 'TKC_USLUGI', // from Alior's docs
"name" => 'Inne',
"number" => 1,
"price" => $this->getRounded($totalWrapping),
];
}
return $json;
}
/**
* Returns Alior's ID of category based on mapping (see map.php)
* @return string
*/
private function getAliorsCategory($shopCategoryId)
{
$map = require(dirname(__FILE__) . '/map.php');
if (empty($map)) {
return '';
}
foreach ($map as $aliorId => $shopCats) {
if (in_array($shopCategoryId, $shopCats)) {
return $aliorId;
}
}
return !empty($map['default']) ? $map['default'] : '';
}
/**
* @param $price
* @return |null
*/
private function getRounded($price) {
$precision = method_exists('Context', 'getComputingPrecision')
? Context::getContext()->getComputingPrecision()
: _PS_PRICE_DISPLAY_PRECISION_;
if (is_array($this->context->currency)) {
return Tools::ps_round($price, (int)$this->context->currency['decimals'] * $precision);
} elseif (is_object($this->context->currency)) {
return Tools::ps_round($price, (int)$this->context->currency->decimals * $precision);
}
return null;
}
/**
* @param $name
* @return string
*/
private function clearName($name) {
$name = str_replace('|', '', $name);
return preg_replace('/[\x00-\x1F]/', '', $name);
}
private function checkCategoryPromotion($product) {
$categories = Product::getProductCategories($product->id);
foreach($categories as $categoryId)
{
$category = new Category($categoryId);
if($category->alior_category_promotion) {
return true;
}
}
return false;
}
public function formatDate($date, $expectedFormat = 'j-M-Y', $currentFormat = 'Y-m-d'){
if(!$date){
return 0;
}
$date = DateTime::createFromFormat($currentFormat, $date);
return $date->format($expectedFormat);
}
private function getPromotion($products) {
$todayDate = date("Y/m/d");
$promotionsType = [];
$isProductPromotionValid = true;
$isCategoryPromotionValid = true;
if(
!Configuration::get('RATY_PRODUCT_PROMOTION_START') ||
$this->formatDate(Configuration::get('RATY_PRODUCT_PROMOTION_START'), "Y/m/d", "Y-m-d") > $todayDate ||
$this->formatDate(Configuration::get('RATY_PRODUCT_PROMOTION_END'), "Y/m/d", "Y-m-d") < $todayDate
) {
$isProductPromotionValid = false;
}
if(
!Configuration::get('RATY_CATEGORY_PROMOTION_START') ||
$this->formatDate(Configuration::get('RATY_CATEGORY_PROMOTION_START'), "Y/m/d", "Y-m-d") > $todayDate ||
$this->formatDate(Configuration::get('RATY_CATEGORY_PROMOTION_END'), "Y/m/d", "Y-m-d") < $todayDate
) {
$isCategoryPromotionValid = false;
}
foreach($products as $product) {
array_push($promotionsType, $this->getProductPromotion($product, $isProductPromotionValid, $isCategoryPromotionValid));
}
$promotion = explode('${sep}', Configuration::get('RATY_' . $promotionsType[0] .'_PROMOTION'));
if(count($promotionsType) > 1) {
for($i = 1; $i < count($promotionsType); $i++) {
$promotionType = explode('${sep}', Configuration::get('RATY_' . $promotionsType[$i] .'_PROMOTION'));
$promotion = array_intersect($promotion, $promotionType);
}
}
return implode('${sep}', $promotion);
}
private function getProductPromotion($product, $isProductPromotionValid, $isCategoryPromotionValid) {
if(is_array($product)){
$product = new Product($product['id_product']);
}
if($isProductPromotionValid && $product->alior_product_promotion) {
return 'PRODUCT';
}
if($isCategoryPromotionValid && $this->checkCategoryPromotion($product)) {
return 'CATEGORY';
}
return 'STANDARD';
}
}