Example #1
0
 public function initContent()
 {
     parent::initContent();
     $this->paypal = new PayPal();
     $this->context = Context::getContext();
     $this->id_module = (int) Tools::getValue('id_module');
     $this->id_order = (int) Tools::getValue('id_order');
     $order = new Order($this->id_order);
     $order_state = new OrderState($order->current_state);
     $paypal_order = PayPalOrder::getOrderById($this->id_order);
     if ($order_state->template[$this->context->language->id] == 'payment_error') {
         $this->context->smarty->assign(array('message' => $order_state->name[$this->context->language->id], 'logs' => array($this->paypal->l('An error occurred while processing payment.')), 'order' => $paypal_order, 'price' => Tools::displayPrice($paypal_order['total_paid'], $this->context->currency)));
         return $this->setTemplate('error.tpl');
     }
     $order_currency = new Currency((int) $order->id_currency);
     $display_currency = new Currency((int) $this->context->currency->id);
     $price = Tools::convertPriceFull($paypal_order['total_paid'], $order_currency, $display_currency);
     $this->context->smarty->assign(array('is_guest' => $this->context->customer->is_guest || $this->context->customer->id == false, 'order' => $paypal_order, 'price' => Tools::displayPrice($price, $this->context->currency->id), 'HOOK_ORDER_CONFIRMATION' => $this->displayOrderConfirmation(), 'HOOK_PAYMENT_RETURN' => $this->displayPaymentReturn()));
     if ($this->context->customer->is_guest || $this->context->customer->id == false) {
         $this->context->smarty->assign(array('id_order' => (int) $this->id_order, 'id_order_formatted' => sprintf('#%06d', (int) $this->id_order), 'order_reference' => $order->reference));
         /* If guest we clear the cookie for security reason */
         $this->context->customer->mylogout();
     }
     if ($this->context->getMobileDevice() == true) {
         $this->setTemplate('order-confirmation-mobile.tpl');
     } else {
         $this->setTemplate('order-confirmation.tpl');
     }
 }
 public function initContent()
 {
     $cart = $this->context->cart;
     $payments = array();
     $payments['message'] = $this->module->l('The order status is not paid! Go to my account and then reorder');
     if ($cart) {
         $total_to_pay = $cart->getOrderTotal(true);
         $rub_currency_id = Currency::getIdByIsoCode('RUB');
         if ($cart->id_currency != $rub_currency_id) {
             $from_currency = new Currency($cart->id_curre1ncy);
             $to_currency = new Currency($rub_currency_id);
             $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
         }
         $display = '';
         if (Configuration::get('YA_P2P_ACTIVE')) {
             $vars_p2p = Configuration::getMultiple(array('YA_P2P_NUMBER', 'YA_P2P_ACTIVE'));
             $this->context->smarty->assign(array('DATA_P2P' => $vars_p2p, 'price' => number_format($total_to_pay, 2, '.', ''), 'cart' => $this->context->cart));
             $display .= $this->display(__FILE__, 'payment.tpl');
         }
         if (Configuration::get('YA_ORG_ACTIVE')) {
             $vars_org = Configuration::getMultiple(array('YA_ORG_SHOPID', 'YA_ORG_SCID', 'YA_ORG_ACTIVE', 'YA_ORG_TYPE'));
             $this->context->smarty->assign(array('DATA_ORG' => $vars_org, 'id_cart' => $cart->id, 'customer' => new Customer($cart->id_customer), 'address' => new Address($this->context->cart->id_address_delivery), 'total_to_pay' => number_format($total_to_pay, 2, '.', ''), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/', 'shop_name' => Configuration::get('PS_SHOP_NAME')));
             $payments = Configuration::getMultiple(array('YA_ORG_PAYMENT_YANDEX', 'YA_ORG_PAYMENT_CARD', 'YA_ORG_PAYMENT_MOBILE', 'YA_ORG_PAYMENT_WEBMONEY', 'YA_ORG_PAYMENT_TERMINAL', 'YA_ORG_PAYMENT_SBER', 'YA_ORG_PAYMENT_PB', 'YA_ORG_PAYMENT_MA', 'YA_ORG_PAYMENT_ALFA'));
             if (Configuration::get('YA_ORG_INSIDE')) {
                 $payments['pt'] = Tools::getValue('type');
             } else {
                 $payments['pt'] = '';
             }
         }
     }
     $this->context->smarty->assign($payments);
     return $this->setTemplate('redirectk.tpl');
 }
 public function initContent()
 {
     $cart = $this->context->cart;
     $payments = array();
     $payments['message'] = $this->module->l('Заказ в статусе не оплачен! Перейдите в личный кабинет и нажмите перезаказ');
     if ($cart) {
         $total_to_pay = $cart->getOrderTotal(true);
         $rub_currency_id = Currency::getIdByIsoCode('RUB');
         if ($cart->id_currency != $rub_currency_id) {
             $from_currency = new Currency($cart->id_curre1ncy);
             $to_currency = new Currency($rub_currency_id);
             $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
         }
         $display = '';
         if (Configuration::get('YA_P2P_ACTIVE')) {
             $vars_p2p = Configuration::getMultiple(array('YA_P2P_NUMBER', 'YA_P2P_ACTIVE'));
             $this->context->smarty->assign(array('DATA_P2P' => $vars_p2p, 'price' => number_format($total_to_pay, 2, '.', ''), 'cart' => $this->context->cart));
             $display .= $this->display(__FILE__, 'payment.tpl');
         }
         if (Configuration::get('YA_ORG_ACTIVE')) {
             $vars_org = Configuration::getMultiple(array('YA_ORG_SHOPID', 'YA_ORG_SCID', 'YA_ORG_ACTIVE', 'YA_ORG_TYPE'));
             $this->context->smarty->assign(array('DATA_ORG' => $vars_org, 'id_cart' => $cart->id, 'customer' => new Customer($cart->id_customer), 'address' => new Address($this->context->cart->id_address_delivery), 'total_to_pay' => number_format($total_to_pay, 2, '.', ''), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->module->name . '/', 'shop_name' => Configuration::get('PS_SHOP_NAME')));
             $payments = Configuration::getMultiple(array('YA_ORG_PAYMENT_YANDEX', 'YA_ORG_PAYMENT_CARD', 'YA_ORG_PAYMENT_MOBILE', 'YA_ORG_PAYMENT_WEBMONEY', 'YA_ORG_PAYMENT_TERMINAL', 'YA_ORG_PAYMENT_SBER', 'YA_ORG_PAYMENT_PB', 'YA_ORG_PAYMENT_MA', 'YA_ORG_PAYMENT_ALFA'));
             $payments['pt'] = Tools::getValue('type');
         }
         //$this->module->validateOrder((int)$cart->id, _PS_OS_PREPARATION_, $cart->getOrderTotal(true, Cart::BOTH), $this->module->displayName, NULL, array(), NULL, false, $cart->secure_key);
     }
     $this->context->smarty->assign($payments);
     return $this->setTemplate('redirectk.tpl');
 }
Example #4
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, false);
     $nb_cart_rules = count($cart_rules);
     foreach ($cart_rules as &$discount) {
         $discount['value'] = Tools::convertPriceFull($discount['value'], new Currency((int) $discount['reduction_currency']), new Currency((int) $this->context->cart->id_currency));
     }
     $this->context->smarty->assign(array('nb_cart_rules' => (int) $nb_cart_rules, 'cart_rules' => $cart_rules, 'discount' => $cart_rules, 'nbDiscounts' => (int) $nb_cart_rules));
     $this->setTemplate(_PS_THEME_DIR_ . 'discount.tpl');
 }
 public function postProcess()
 {
     parent::postProcess();
     $log_on = Configuration::get('YA_P2P_LOGGING_ON');
     $cart = $this->context->cart;
     if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $customer = new Customer($cart->id_customer);
     if (!Validate::isLoadedObject($customer)) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $this->myCart = $this->context->cart;
     $total_to_pay = $cart->getOrderTotal(true);
     $rub_currency_id = Currency::getIdByIsoCode('RUB');
     if ($cart->id_currency != $rub_currency_id) {
         $from_currency = new Currency($cart->id_currency);
         $to_currency = new Currency($rub_currency_id);
         $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
     }
     if ($total_to_pay > 0 && $total_to_pay < 1) {
         $total_to_pay_limit = '1.00';
     } else {
         $total_to_pay_limit = number_format($total_to_pay, 2, '.', '');
     }
     $total_to_pay = number_format($total_to_pay, 2, '.', '');
     $this->module->payment_status = '';
     $code = Tools::getValue('code');
     $type = Tools::getValue('type');
     if (empty($code)) {
         $scope = array("payment.to-account(\"" . Configuration::get('YA_P2P_NUMBER') . "\",\"account\").limit(," . $total_to_pay_limit . ")", "money-source(\"wallet\",\"card\")");
         if ($type == 'wallet') {
             if ($log_on) {
                 $this->module->log_save('p2p_redirect: ' . $this->module->l('Type wallet'));
             }
             $auth_url = API::buildObtainTokenUrl(Configuration::get('YA_P2P_IDENTIFICATOR'), $this->context->link->getModuleLink('yamodule', 'redirect_wallet', array(), true), $scope);
         } elseif ($type == 'card') {
             if ($log_on) {
                 $this->module->log_save('redirect: ' . $this->module->l('Type card'));
             }
             Tools::redirect($this->context->link->getModuleLink('yamodule', 'redirect_card', array('code' => true, 'cnf' => true), true), '');
         }
         if ($log_on) {
             $this->module->log_save('p2p_redirect: url = ' . $auth_url);
         }
         Tools::redirect($auth_url, '');
     }
 }
 /**
  * Assign price and tax to the template
  */
 protected function assignPriceAndTax()
 {
     die('coucou');
     $id_customer = isset($this->context->customer) ? (int) $this->context->customer->id : 0;
     $id_group = (int) Group::getCurrent()->id;
     $id_country = $id_customer ? (int) Customer::getCurrentCountry($id_customer) : (int) Tools::getCountry();
     $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
     if ($group_reduction === false) {
         $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
     }
     // Tax
     $tax = (double) $this->product->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
     $this->context->smarty->assign('tax_rate', $tax);
     $product_price_with_tax = Product::getPriceStatic($this->product->id, true, null, 6) * 10;
     if (Product::$_taxCalculationMethod == PS_TAX_INC) {
         $product_price_with_tax = Tools::ps_round($product_price_with_tax, 2);
     }
     $product_price_without_eco_tax = (double) $product_price_with_tax - $this->product->ecotax;
     $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $ecotax_tax_amount = Tools::ps_round($this->product->ecotax, 2);
     if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
         $ecotax_tax_amount = Tools::ps_round($ecotax_tax_amount * (1 + $ecotax_rate / 100), 2);
     }
     $id_currency = (int) $this->context->cookie->id_currency;
     $id_product = (int) $this->product->id;
     $id_shop = $this->context->shop->id;
     $quantity_discounts = SpecificPrice::getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group, null, true, (int) $this->context->customer->id);
     foreach ($quantity_discounts as &$quantity_discount) {
         if ($quantity_discount['id_product_attribute']) {
             $combination = new Combination((int) $quantity_discount['id_product_attribute']);
             $attributes = $combination->getAttributesName((int) $this->context->language->id);
             foreach ($attributes as $attribute) {
                 $quantity_discount['attributes'] = $attribute['name'] . ' - ';
             }
             $quantity_discount['attributes'] = rtrim($quantity_discount['attributes'], ' - ');
         }
         if ((int) $quantity_discount['id_currency'] == 0 && $quantity_discount['reduction_type'] == 'amount') {
             $quantity_discount['reduction'] = Tools::convertPriceFull($quantity_discount['reduction'], null, Context::getContext()->currency);
         }
     }
     $product_price = $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false) * 10;
     $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $this->context->smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (double) $tax, $ecotax_tax_amount), 'ecotax_tax_inc' => $ecotax_tax_amount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'productPriceWithoutEcoTax' => (double) $product_price_without_eco_tax, 'group_reduction' => $group_reduction, 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'ecotax' => !count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'), 'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group)));
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, true, true);
     $nb_cart_rules = count($cart_rules);
     foreach ($cart_rules as $key => &$discount) {
         if ($discount['quantity_for_user'] === 0) {
             unset($cart_rules[$key]);
         }
         $discount['value'] = Tools::convertPriceFull($discount['value'], new Currency((int) $discount['reduction_currency']), new Currency((int) $this->context->cart->id_currency));
         if ($discount['gift_product'] !== 0) {
             $product = new Product((int) $discount['gift_product']);
             if (isset($product->name)) {
                 $discount['gift_product_name'] = current($product->name);
             }
         }
     }
     $this->context->smarty->assign(array('nb_cart_rules' => (int) $nb_cart_rules, 'cart_rules' => $cart_rules, 'discount' => $cart_rules, 'nbDiscounts' => (int) $nb_cart_rules));
     $this->setTemplate(_PS_THEME_DIR_ . 'discount.tpl');
 }
Example #8
0
 public function getOrderShippingCostExternal($cart)
 {
     if (!$this->soapClientExists() || !$this->checkModuleAvailability()) {
         return false;
     }
     $disabled_countries_ids = DpdPolandCountry::getDisabledCountriesIDs();
     $id_country = (int) Tools::getValue('id_country');
     if (!$id_country) {
         $country = Address::getCountryAndState((int) $cart->id_address_delivery);
         $id_country = $country['id_country'];
     }
     if (!($id_method = self::getMethodIdByCarrierId($this->id_carrier))) {
         self::$carriers[$this->id_carrier] = false;
         return false;
     }
     if (!$id_country || in_array($id_country, $disabled_countries_ids) && $id_method == _DPDPOLAND_CLASSIC_ID_) {
         return false;
     }
     if ($id_country) {
         $zone = Country::getIdZone($id_country);
     } else {
         return false;
     }
     if (!$this->id_carrier) {
         return false;
     }
     if ($id_country == Country::getByIso(self::POLAND_ISO_CODE) && $id_method == _DPDPOLAND_CLASSIC_ID_ || $id_country != Country::getByIso(self::POLAND_ISO_CODE) && $id_method == _DPDPOLAND_STANDARD_COD_ID_ || $id_country != Country::getByIso(self::POLAND_ISO_CODE) && $id_method == _DPDPOLAND_STANDARD_ID_) {
         return false;
     }
     if (isset(self::$carriers[$this->id_carrier])) {
         return self::$carriers[$this->id_carrier];
     }
     $total_weight = self::convertWeight($cart->getTotalWeight());
     if (Configuration::get(DpdPolandConfiguration::PRICE_CALCULATION_TYPE) == DpdPolandConfiguration::PRICE_CALCULATION_PRESTASHOP) {
         $carrier = new Carrier($this->id_carrier);
         $price = $carrier->getDeliveryPriceByWeight($total_weight, $zone);
         self::$carriers[$this->id_carrier] = $price;
         return self::$carriers[$this->id_carrier];
     }
     $price = DpdPolandCSV::getPrice($total_weight, $id_method, $cart);
     if ($price === false) {
         return false;
     }
     $id_currency_pl = Currency::getIdByIsoCode(_DPDPOLAND_CURRENCY_ISO_, (int) $this->context->shop->id);
     $currency_from = new Currency((int) $id_currency_pl);
     $currency_to = $this->context->currency;
     self::$carriers[$this->id_carrier] = Tools::convertPriceFull($price, $currency_from, $currency_to);
     return self::$carriers[$this->id_carrier];
 }
 public function hookdisplayPayment($params)
 {
     if (!$this->active) {
         return;
     }
     if (!$this->_checkCurrency($params['cart'])) {
         return;
     }
     $cart = $this->context->cart;
     $total_to_pay = $cart->getOrderTotal(true);
     $rub_currency_id = Currency::getIdByIsoCode('RUB');
     if ($cart->id_currency != $rub_currency_id) {
         $from_currency = new Currency($cart->id_curre1ncy);
         $to_currency = new Currency($rub_currency_id);
         $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
     }
     $display = '';
     if (Configuration::get('YA_P2P_ACTIVE')) {
         $vars_p2p = Configuration::getMultiple(array('YA_P2P_NUMBER', 'YA_P2P_ACTIVE'));
         $this->context->smarty->assign(array('DATA_P2P' => $vars_p2p, 'price' => number_format($total_to_pay, 2, '.', ''), 'cart' => $this->context->cart));
         $display .= $this->display(__FILE__, 'payment.tpl');
     }
     if (Configuration::get('YA_ORG_ACTIVE')) {
         $vars_org = Configuration::getMultiple(array('YA_ORG_SHOPID', 'YA_ORG_SCID', 'YA_ORG_ACTIVE', 'YA_ORG_TYPE'));
         $this->context->smarty->assign(array('DATA_ORG' => $vars_org, 'id_cart' => $params['cart']->id, 'customer' => new Customer($params['cart']->id_customer), 'address' => new Address($this->context->cart->id_address_delivery), 'total_to_pay' => number_format($total_to_pay, 2, '.', ''), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/', 'shop_name' => Configuration::get('PS_SHOP_NAME')));
         $payments = Configuration::getMultiple(array('YA_ORG_PAYMENT_YANDEX', 'YA_ORG_PAYMENT_CARD', 'YA_ORG_PAYMENT_MOBILE', 'YA_ORG_PAYMENT_WEBMONEY', 'YA_ORG_PAYMENT_TERMINAL', 'YA_ORG_PAYMENT_SBER', 'YA_ORG_PAYMENT_PB', 'YA_ORG_PAYMENT_MA', 'YA_ORG_PAYMENT_QW', 'YA_ORG_PAYMENT_QP', 'YA_ORG_PAYMENT_ALFA'));
         if ($payments['YA_ORG_PAYMENT_YANDEX']) {
             $this->smarty->assign(array('pt' => 'PC', 'buttontext' => $this->l('Оплата из кошелька в Яндекс.Деньгах.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_CARD']) {
             $this->smarty->assign(array('pt' => 'AC', 'buttontext' => $this->l('Оплата с произвольной банковской карты.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_MOBILE']) {
             $this->smarty->assign(array('pt' => 'MC', 'buttontext' => $this->l('Платеж со счета мобильного телефона.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_WEBMONEY']) {
             $this->smarty->assign(array('pt' => 'WM', 'buttontext' => $this->l('Оплата из кошелька в системе WebMoney.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_TERMINAL']) {
             $this->smarty->assign(array('pt' => 'GP', 'buttontext' => $this->l('Оплата наличными через кассы и терминалы.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_SBER']) {
             $this->smarty->assign(array('pt' => 'SB', 'buttontext' => $this->l('Оплата через Сбербанк: оплата по SMS или Сбербанк Онлайн.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_ALFA']) {
             $this->smarty->assign(array('pt' => 'AB', 'buttontext' => $this->l('Оплата через Альфа-Клик.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_PB']) {
             $this->smarty->assign(array('pt' => 'PB', 'buttontext' => $this->l('Оплата через Промсвязьбанк.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_MA']) {
             $this->smarty->assign(array('pt' => 'MA', 'buttontext' => $this->l('Оплата через MasterPass.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_QW']) {
             $this->smarty->assign(array('pt' => 'QW', 'buttontext' => $this->l('Оплата через QIWI Wallet.')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
         if ($payments['YA_ORG_PAYMENT_QP']) {
             $this->smarty->assign(array('pt' => 'QP', 'buttontext' => $this->l('Оплата через доверительный платеж (Куппи.ру).')));
             $display .= $this->display(__FILE__, 'kassa.tpl');
         }
     }
     $this->context->smarty->assign(array('this_path' => $this->_path, 'this_path_ssl' => Tools::getHttpHost(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     return $display;
 }
 public function postProcess()
 {
     parent::postProcess();
     $this->log_on = Configuration::get('YA_P2P_LOGGING_ON');
     $cart = $this->context->cart;
     if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $customer = new Customer($cart->id_customer);
     if (!Validate::isLoadedObject($customer)) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $this->myCart = $this->context->cart;
     $total_to_pay = $cart->getOrderTotal(true);
     $rub_currency_id = Currency::getIdByIsoCode('RUB');
     if ($cart->id_currency != $rub_currency_id) {
         $from_currency = new Currency($cart->id_currency);
         $to_currency = new Currency($rub_currency_id);
         $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
     }
     if ($total_to_pay > 0 && $total_to_pay < 1) {
         $total_to_pay_limit = '1.00';
     } else {
         $total_to_pay_limit = number_format($total_to_pay, 2, '.', '');
     }
     $total_to_pay = number_format($total_to_pay, 2, '.', '');
     $this->module->payment_status = false;
     $code = Tools::getValue('code');
     $cnf = Tools::getValue('cnf');
     if (empty($code)) {
         Tools::redirect('index.php?controller=order&step=3');
     } elseif (!empty($code) && $cnf) {
         $comment = $message = $this->module->l('total:') . $total_to_pay . $this->module->l(' rub');
         $response = API::getAccessToken(Configuration::get('YA_P2P_IDENTIFICATOR'), $code, $this->context->link->getModuleLink('yamodule', 'redirect', array(), true), Configuration::get('YA_P2P_KEY'));
         $token = $response->access_token;
         if ($token == '') {
             $scope = array("payment.to-account(\"" . Configuration::get('YA_P2P_NUMBER') . "\",\"account\").limit(," . $total_to_pay_limit . ")", "money-source(\"wallet\",\"card\")");
             if ($this->log_on) {
                 $this->module->log_save('wallet_redirect: ' . $this->module->l('Type wallet'));
             }
             $auth_url = API::buildObtainTokenUrl(Configuration::get('YA_P2P_IDENTIFICATOR'), $this->context->link->getModuleLink('yamodule', 'redirect_wallet', array(), true), $scope);
             if ($this->log_on) {
                 $this->module->log_save('wallet_redirect: url = ' . $auth_url);
             }
             Tools::redirect($auth_url, '');
         }
         $api = new API($token);
         $rarray = array('pattern_id' => 'p2p', 'to' => Configuration::get('YA_P2P_NUMBER'), 'amount_due' => $total_to_pay, 'comment' => trim($comment), 'message' => trim($message), 'label' => $this->context->cart->id);
         $request_payment = $api->requestPayment($rarray);
         switch ($request_payment->status) {
             case 'success':
                 if ($this->log_on) {
                     $this->module->log_save('wallet_redirect: ' . $this->module->l('request success'));
                 }
                 $this->context->cookie->ya_encrypt_token = urlencode(base64_encode($token));
                 $this->context->cookie->ya_encrypt_RequestId = urlencode(base64_encode($request_payment->request_id));
                 $this->context->cookie->write();
                 $this->module->payment_link = $this->context->link->getModuleLink('yamodule', 'redirect', array(), true);
                 do {
                     $process_payment = $api->processPayment(array("request_id" => $request_payment->request_id));
                     if ($process_payment->status == "in_progress") {
                         sleep(1);
                     }
                 } while ($process_payment->status == "in_progress");
                 $this->updateStatus($process_payment);
                 $this->error = false;
                 break;
             case 'refused':
                 if ($this->log_on) {
                     $this->module->log_save('wallet_redirect: ' . $this->module->l('request refused'));
                 }
                 $this->errors[] = $this->module->descriptionError($request_payment->error);
                 if ($this->log_on) {
                     $this->module->log_save('wallet_redirect: refused ' . $this->module->descriptionError($request_payment->error));
                 }
                 $this->error = true;
                 break;
             case 'hold_for_pickup':
                 if ($this->log_on) {
                     $this->module->log_save('wallet_redirect: ' . $this->module->l('hold_for_pickup'));
                 }
                 $this->errors[] = $this->module->l('Получатель перевода не найден, будет отправлен перевод до востребования. Успешное выполнение.');
                 if ($this->log_on) {
                     $this->module->log_save('wallet_redirect: hold_for_pickup ' . $this->module->l('Получатель перевода не найден, будет отправлен перевод до востребования. Успешное выполнение.'));
                 }
                 $this->error = true;
                 break;
         }
     }
 }
Example #11
0
 public static function convertPriceFull($amount, $currency_from = null, $currency_to = null)
 {
     if (version_compare(_PS_VERSION_, '1.5', '>')) {
         return Tools::convertPriceFull($amount, $currency_from, $currency_to);
     } else {
         if ($currency_from === $currency_to) {
             return $amount;
         }
         if ($currency_from === null) {
             $currency_from = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
         }
         if ($currency_to === null) {
             $currency_to = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
         }
         if ($currency_from->id == Configuration::get('PS_CURRENCY_DEFAULT')) {
             $amount *= $currency_to->conversion_rate;
         } else {
             $conversion_rate = $currency_from->conversion_rate == 0 ? 1 : $currency_from->conversion_rate;
             // Convert amount to default currency (using the old currency rate)
             $amount = Tools::ps_round($amount / $conversion_rate, 2);
             // Convert to new currency
             $amount *= $currency_to->conversion_rate;
         }
         return Tools::ps_round($amount, 2);
     }
 }
Example #12
0
 private function getTotal($device_currency_code, $order_currency_id, $total)
 {
     $this->setContext();
     $device_currency = Currency::getCurrencyInstance($device_currency_code);
     if ($device_currency_code != $order_currency_id) {
         $currency_from = Currency::getCurrencyInstance($order_currency_id);
         $total = Tools::convertPriceFull($total, $currency_from, $device_currency);
     }
     $total = Tools::displayPrice($total, $device_currency);
     return $total;
 }
 public function postProcess()
 {
     parent::postProcess();
     $dd = serialize($_REQUEST);
     $this->log_on = Configuration::get('YA_ORG_LOGGING_ON');
     if ($this->log_on) {
         $this->module->log_save('payment_kassa ' . $dd);
     }
     Tools::getValue('label') ? $data = explode('_', Tools::getValue('label')) : ($data = explode('_', Tools::getValue('customerNumber')));
     if (!empty($data) && $data[0] == 'KASSA') {
         $cart = new Cart($data[1]);
         if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
             Tools::redirect('index.php?controller=order&step=1');
         }
         $customer = new Customer($cart->id_customer);
         if (!Validate::isLoadedObject($customer)) {
             Tools::redirect('index.php?controller=order&step=1');
         }
         $total_to_pay = $cart->getOrderTotal(true);
         $rub_currency_id = Currency::getIdByIsoCode('RUB');
         if ($cart->id_currency != $rub_currency_id) {
             $from_currency = new Currency($cart->id_currency);
             $to_currency = new Currency($rub_currency_id);
             $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
         }
         $total_to_pay = number_format($total_to_pay, 2, '.', '');
         $amount = Tools::getValue('orderSumAmount');
         $action = Tools::getValue('action');
         $shopId = Tools::getValue('shopId');
         $invoiceId = Tools::getValue('invoiceId');
         $signature = md5($action . ';' . $amount . ';' . Tools::getValue('orderSumCurrencyPaycash') . ';' . Tools::getValue('orderSumBankPaycash') . ';' . $shopId . ';' . $invoiceId . ';' . Tools::getValue('customerNumber') . ';' . trim(Configuration::get('YA_ORG_MD5_PASSWORD')));
         $ord = $cart->orderExists() ? new Order((int) Order::getOrderByCartId($cart->id)) : $this->module->validateOrder($cart->id, _PS_OS_PREPARATION_, $cart->getOrderTotal(true, Cart::BOTH), $this->module->displayName, NULL, array(), NULL, false, $cart->secure_key);
         if (!$ord) {
             $this->module->validateResponse($this->module->l('Invalid order number'), 1, $action, $shopId, $invoiceId, true);
         }
         if (Tools::strtoupper($signature) != Tools::strtoupper(Tools::getValue('md5'))) {
             $this->module->validateResponse($this->module->l('Invalid signature'), 1, $action, $shopId, $invoiceId, true);
         }
         if ($amount != $total_to_pay) {
             $this->module->validateResponse($this->module->l('Incorrect payment amount'), $action == 'checkOrder' ? 100 : 200, $action, $shopId, $invoiceId, true);
         }
         if ($action == 'checkOrder') {
             if ($this->log_on) {
                 $this->module->log_save('payment_kassa: checkOrder invoiceId="' . $invoiceId . '" shopId="' . $shopId . '" ' . $this->module->l('check order'));
             }
             $this->module->validateResponse('', 0, $action, $shopId, $invoiceId, true);
         }
         if ($action == 'paymentAviso') {
             $history = new OrderHistory();
             $history->id_order = $ord->id;
             $history->changeIdOrderState(Configuration::get('PS_OS_PAYMENT'), $ord->id);
             $history->addWithemail(true);
             if ($this->log_on) {
                 $this->module->log_save('payment_kassa: paymentAviso invoiceId="' . $invoiceId . '" shopId="' . $shopId . '" #' . $ord->id . ' ' . $this->module->l('Order success'));
             }
             $this->module->validateResponse('', 0, $action, $shopId, $invoiceId, true);
         }
     } else {
         Tools::redirect('index.php?controller=order&step=3');
     }
 }
Example #14
0
 public static function convertPriceFull($amount, Currency $currency_from = null, Currency $currency_to = null, $round = true)
 {
     if ($round) {
         return Tools::convertPriceFull($amount, $currency_from, $currency_to);
     }
     if ($currency_from === $currency_to) {
         return $amount;
     }
     if ($currency_from === null) {
         $currency_from = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
     }
     if ($currency_to === null) {
         $currency_to = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
     }
     if ($currency_from->id == Configuration::get('PS_CURRENCY_DEFAULT')) {
         $amount *= $currency_to->conversion_rate;
     } else {
         $conversion_rate = $currency_from->conversion_rate == 0 ? 1 : $currency_from->conversion_rate;
         // Convert amount to default currency (using the old currency rate)
         $amount = $amount / $conversion_rate;
         // Convert to new currency
         $amount *= $currency_to->conversion_rate;
     }
     return $amount;
 }
Example #15
0
 function getProductAttributesOther($products)
 {
     return $products;
     if ($products) {
         $currency = new Currency($this->context->currency->id);
         $timeNow = time();
         $http = 'http';
         if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
             $http .= "s";
         }
         $http .= "://";
         foreach ($products as $i => &$product) {
             $product['image'] = Context::getContext()->link->getImageLink($product['link_rewrite'], $product['id_image'], 'home_default');
             if (strpos($product['image'], $http) === false) {
                 $product['image'] = $http . $product['image'];
             }
             $product['price_new'] = number_format(Tools::convertPriceFull($product['price'], $currency), 2, '.', ',');
             $product['price_old'] = '0';
             $product['reduction'] = '';
             if ($product['specific_prices']) {
                 $from = strtotime($product['specific_prices']['from']);
                 $to = strtotime($product['specific_prices']['to']);
                 if ($product['specific_prices']['from_quantity'] == '1' && ($timeNow >= $from && $timeNow <= $to || $product['specific_prices']['to'] == '0000-00-00 00:00:00')) {
                     $product['price_old'] = number_format(Tools::convertPriceFull($product['price_without_reduction'], $currency), 2, '.', ',');
                     if ($product['specific_prices']['reduction_type'] == 'percentage') {
                         $product['reduction'] = $product['specific_prices']['reduction'] * 100 . '%';
                     } else {
                         $product['reduction'] = number_format(Tools::convertPriceFull($product['specific_prices']['reduction'], $currency), 2, '.', ',');
                     }
                 }
             }
             $product['rates'] = '';
             $product['totalRates'] = '0';
             if (Module::isInstalled('productcomments') == 1) {
                 $productRate = $this->getProductRatings($product['id_product']);
                 if (isset($productRate) && $productRate['avg'] > 0) {
                     if ($productRate['total'] > 1) {
                         $product['totalRates'] = $productRate['total'] . 's';
                     } else {
                         $product['totalRates'] = $productRate['total'];
                     }
                     for ($i = 0; $i < 5; $i++) {
                         if ($productRate['avg'] >= $i) {
                             $product['rates'] .= '<div class="star"></div>';
                         } else {
                             $product['rates'] .= '<div class="star star_off"></div>';
                         }
                     }
                 } else {
                     $product['rates'] .= '<div class="star star_off"></div>';
                     $product['rates'] .= '<div class="star star_off"></div>';
                     $product['rates'] .= '<div class="star star_off"></div>';
                     $product['rates'] .= '<div class="star star_off"></div>';
                     $product['rates'] .= '<div class="star star_off"></div>';
                 }
             } else {
                 $product['rates'] .= '<div class="star star_off"></div>';
                 $product['rates'] .= '<div class="star star_off"></div>';
                 $product['rates'] .= '<div class="star star_off"></div>';
                 $product['rates'] .= '<div class="star star_off"></div>';
                 $product['rates'] .= '<div class="star star_off"></div>';
             }
             $product['isCompare'] = 0;
             if ($this->compareProductIds) {
                 if (in_array($product['id_product'], $this->compareProductIds)) {
                     $product['isCompare'] = 1;
                 }
             }
         }
     }
     return $products;
 }
    public function ajaxGetProductsForSupplyOrder()
    {
        require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/stock/ErpSupplyOrderClasses.php';
        require_once _PS_MODULE_DIR_ . 'erpillicopresta/erpillicopresta.php';
        /* manage advanced stock */
        $stock_management_active = Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT');
        $sales_forecast_type = Configuration::get('ERP_SALES_FORECAST_CHOICE');
        $id_supplier = (int) Tools::getValue('id_supplier', false);
        $id_currency = (int) Tools::getValue('id_currency', false);
        $id_categorie = (int) Tools::getValue('id_categorie', false);
        $id_manufacturer = (int) Tools::getValue('id_manufacturer', false);
        $id_warehouse = (int) Tools::getValue('id_warehouse', null);
        $existing_ids = Tools::getValue('ids');
        //$token_get_product      = Tools::getValue('token');
        $products = ErpSupplyOrderClasses::searchProduct($id_supplier, $id_categorie, $id_manufacturer, $id_currency);
        if (!empty($products)) {
            $advanced_stock_token = Tools::getAdminToken('AdminAdvancedStock' . (int) Tab::getIdFromClassName('AdminAdvancedStock') . (int) $this->context->employee->id);
            foreach ($products as $product) {
                // If product already in destination array, continue
                if (strrpos($existing_ids, $product['id']) !== false) {
                    continue;
                }
                $ids = explode('_', $product['id']);
                $id_product = $ids[0];
                $id_product_attribute = $ids[1];
                // If the advanced stock manager is activated
                if ($stock_management_active == '1') {
                    // Get the physical and usable quantities
                    $query = new DbQuery();
                    $query->select('physical_quantity');
                    $query->select('usable_quantity');
                    $query->from('stock');
                    $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute);
                    $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
                    /* the two quantities */
                    $physical_quantity = (int) $res['physical_quantity'];
                    $usable_quantity = (int) $res['usable_quantity'];
                    // The real quantity depends of the warehouse
                    $manager = StockManagerFactory::getManager();
                    $product['stock'] = $real_quantity = (int) $manager->getProductRealQuantities($id_product, $id_product_attribute, $id_warehouse, true);
                } else {
                    // get the free quantities
                    $product['stock'] = $usable_quantity = (int) Product::getQuantity($id_product, $id_product_attribute);
                }
                /*  TAX */
                /*  Get the current tax */
                $query = new DbQuery();
                $query->select('rate');
                $query->from('tax', 't');
                $query->innerJoin('tax_rule', 'tr', 'tr.id_tax = t.id_tax');
                $query->innerJoin('product', 'p', 'p.id_tax_rules_group = tr.id_tax_rules_group');
                $query->where('p.id_product = ' . (int) $id_product);
                $query->where('tr.id_country IN (SELECT id_country
                                                FROM ' . _DB_PREFIX_ . 'address
                                                WHERE id_supplier = ' . (int) $id_supplier . ')');
                $product['tax_rate'] = round(Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query), 1);
                $prices = ErpSupplyOrderClasses::getWholesalePrice((int) $id_product, (int) $id_product_attribute, (int) $id_supplier);
                $product['unit_price_te'] = Tools::convertPriceFull($prices, new Currency((int) $id_currency));
                // sales quantity for X rolling month
                $quantity_sales = ErpSupplyOrderClasses::getQuantitySales((int) $id_product, (int) $id_product_attribute);
                // if sale forecast is activ
                if ($sales_forecast_type != 0) {
                    // if we use the 6 month rolling method
                    if ($sales_forecast_type == 1) {
                        $sales_forecasts = round(ErpSupplyOrderClasses::getProductSalesForecasts($id_product, $id_product_attribute), 1);
                    } else {
                        $sales_forecasts = round(ErpSupplyOrderClasses::getProductSalesForecastsByPeriod($id_product, $id_product_attribute), 1);
                    }
                } else {
                    $sales_forecasts = 'NA';
                }
                // Sales gain
                $sales_gains = ErpSupplyOrderClasses::getProductSalesGains($id_product, $id_product_attribute);
                // Prepare the hidden json foreach line
                $product['comment'] = '';
                $product_json = Tools::jsonEncode($product);
                echo '<tr>
                                        <td class="product_json hide">' . $product_json . '</td>
                                        <td><input type="checkbox" class="select_product" name="select_product"/></td>
                                        <td>' . $product['supplier_reference'] . '</td>
                                        <td>' . $product['reference'] . '</td>
                                        <td>
                                                         <a href="#" class="cluetip-supply-price" title="' . $this->l('Supplier Price') . '"
                                                                                        rel="index.php?controller=AdminAdvancedStock&ajax=1&id_product=' . $id_product . '&id_product_attribute=' . $id_product_attribute . '&id_currency=' . $id_currency . '&task=getProductSupplierPrice&token=' . $advanced_stock_token . '" >
                                                                                                                           <img src="themes/default/img/icon-search.png">
                                                        </a>
                                                        ' . $product['name'] . '
                                        </td>';
                if (Configuration::get(ErpIllicopresta::getControllerStatusName('AdminAdvancedSupplyOrder'))) {
                    echo '<td align="center"> <p style="background-color:' . ErpSupplyOrderClasses::getStockLevelColor($real_quantity) . '; width:16px; height:16px"></p> </td>';
                }
                echo '<td align="center">' . $usable_quantity . '</td>
                                        ' . ($stock_management_active == '1' ? '
                                                                        <td align="center">' . $physical_quantity . '</td>
                                                                        <td align="center">' . $real_quantity . '</td>' : '') . '';
                if (Configuration::get(ErpIllicopresta::getControllerStatusName('AdminAdvancedSupplyOrder'))) {
                    echo '<td align="center">' . $quantity_sales . '</td>
                                                <td align="center">' . $sales_gains . '</td>';
                    if (Configuration::get('ERP_SALES_FORECAST_CHOICE') != 0) {
                        echo '<td>' . $sales_forecasts . '</td>';
                    }
                }
                echo '<td align="center"><input type="text" class="quantity_ordered" size="2" /></td>
                                        <td align="center"> <input type="text" name="comment" class="comment"/></td>
                                        
				</tr>';
            }
        } else {
            echo '<div class="list-empty-msg">
				<i class="icon-warning-sign list-empty-icon"></i>
				' . $this->l('No product found !') . '
			</div>';
        }
    }
Example #17
0
 function buildGroup_Products_default($group, $langId, $shopId)
 {
     //if (!$this->isCached('group.product.tpl', 'product|'.$group['id'])){
     $params = json_decode($group['params']);
     //array('saller'=>$this->l('Best Saller'), 'view'=>$this->l('Most View'), 'special'=>$this->l('Specials'), 'arrival'=>$this->l('New Arrivals'), 'manual'=>$this->l('Manual'));
     if ($params->productType == 'saller') {
         $arrSubCategory = VerticalMegaMenusLibraries::getCategoryIds($params->productCategory);
         $arrSubCategory[] = $params->productCategory;
         $products = $this->getProductsOrderSales($langId, $arrSubCategory, null, false, false, $params->productCount, 0, true);
     } elseif ($params->productType == 'special') {
         $arrSubCategory = VerticalMegaMenusLibraries::getCategoryIds($params->productCategory);
         $arrSubCategory[] = $params->productCategory;
         $products = $this->getProductsOrderSpecial($langId, $arrSubCategory, null, false, false, $params->productCount, 0, true);
     } elseif ($params->productType == 'arrival') {
         $arrSubCategory = VerticalMegaMenusLibraries::getCategoryIds($params->productCategory);
         $arrSubCategory[] = $params->productCategory;
         $products = $this->getProductsOrderAddDate($langId, $arrSubCategory, null, false, false, $params->productCount, 0, true);
     } elseif ($params->productType == 'manual') {
         $products = $this->getProductsByIds($langId, $params->productIds, false, true);
     }
     $timeNow = time();
     $currency = new Currency($this->context->currency->id);
     $link = Context::getContext()->link;
     $http = 'http';
     if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
         $http .= "s";
     }
     $http .= "://";
     if ($products) {
         foreach ($products as $i => &$product) {
             if (isset(self::$productCache['prod-' . $product['id_product']]) && self::$productCache['prod-' . $product['id_product']]) {
                 $product = self::$productCache['prod-' . $product['id_product']];
             } else {
                 $properties = Product::getProductProperties($langId, $product);
                 $id_image = Product::getCover($product['id_product']);
                 $imagePath = $link->getImageLink($product['link_rewrite'], $id_image['id_image'], 'home_default');
                 if (strpos($imagePath, $http) === false) {
                     $imagePath = $http . $imagePath;
                 }
                 $product['image'] = $imagePath;
                 $product['price_new'] = number_format(Tools::convertPriceFull($properties['price'], $currency), 2, '.', ',');
                 $product['price_old'] = '0';
                 $product['reduction'] = '';
                 $product['link'] = $properties['link'];
                 $specific_prices = $properties['specific_prices'];
                 $oldPrice = '';
                 $sale = '';
                 if ($specific_prices) {
                     $from = strtotime($specific_prices['from']);
                     $to = strtotime($specific_prices['to']);
                     $product['price_old'] = number_format(Tools::convertPriceFull($properties['price_without_reduction'], $currency), 2, '.', ',');
                     if ($specific_prices['from_quantity'] == '1' && ($timeNow >= $from && $timeNow <= $to || $specific_prices['to'] == '0000-00-00 00:00:00')) {
                         if ($specific_prices['reduction_type'] == 'percentage') {
                             $product['reduction'] = $specific_prices['reduction'] * 100 . '%';
                         } else {
                             $product['reduction'] = $currency->sign . number_format(Tools::convertPriceFull($specific_prices['reduction'], $currency), 2, '.', ',');
                         }
                     }
                 }
                 self::$productCache['prod-' . $product['id_product']] = $product;
             }
         }
     }
     $this->context->smarty->assign(array('currencySign' => $currency->sign, 'verticalProducts' => $products, 'params' => get_object_vars($params)));
     //}
     return $this->display(__FILE__, 'group.product.tpl', 'product|' . $group['id']);
 }
Example #18
0
 /**
  * Transforms euro prices from mollie back to the currency of the Cart (order)
  * @param float $amount in euros
  * @param int $cart_id
  * @return float in the currency of the cart
  */
 protected function _convertEuroToCartCurrency($amount, $cart_id)
 {
     $cart = new Cart($cart_id);
     $currency_euro = Currency::getIdByIsoCode('EUR');
     if (!$currency_euro) {
         // No Euro currency available!
         if ($this->module->getConfigValue('MOLLIE_DEBUG_LOG') == Mollie::DEBUG_LOG_ERRORS) {
             Logger::addLog(__METHOD__ . ' said: In order to use this module, you need to enable Euros as currency. Cart ID: ' . $cart_id, Mollie::CRASH);
         }
         die($this->module->lang['This payment method is only available for Euros.']);
     }
     if ($cart->id_currency !== $currency_euro) {
         // Convert euro currency to cart currency
         $amount = Tools::convertPriceFull($amount, Currency::getCurrencyInstance($currency_euro), Currency::getCurrencyInstance($cart->id_currency));
     }
     return round($amount, 2);
 }
Example #19
0
 /**
  * Assign template vars related to attribute groups and colors
  */
 protected function assignAttributesGroups()
 {
     $colors = array();
     $groups = array();
     // @todo (RM) should only get groups and not all declination ?
     $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
     if (is_array($attributes_groups) && $attributes_groups) {
         $combination_images = $this->product->getCombinationImages($this->context->language->id);
         $combination_prices_set = array();
         foreach ($attributes_groups as $k => $row) {
             // Color management
             if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) {
                 $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                 $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                 if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                     $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                 }
                 $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
             }
             if (!isset($groups[$row['id_attribute_group']])) {
                 $groups[$row['id_attribute_group']] = array('group_name' => $row['group_name'], 'name' => $row['public_group_name'], 'group_type' => $row['group_type'], 'default' => -1);
             }
             $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
             if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                 $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
             }
             if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                 $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
             }
             $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
             $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
             $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
             $combinations[$row['id_product_attribute']]['price'] = (double) Tools::convertPriceFull($row['price'], null, Context::getContext()->currency);
             // Call getPriceStatic in order to set $combination_specific_price
             if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                 Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                 $combination_prices_set[(int) $row['id_product_attribute']] = true;
                 $combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
             }
             $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
             $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
             $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
             $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
             $combinations[$row['id_product_attribute']]['unit_impact'] = Tools::convertPriceFull($row['unit_price_impact'], null, Context::getContext()->currency);
             $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
             if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {
                 $combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];
                 $combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);
             } else {
                 $combinations[$row['id_product_attribute']]['available_date'] = $combinations[$row['id_product_attribute']]['date_formatted'] = '';
             }
             if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                 $combinations[$row['id_product_attribute']]['id_image'] = -1;
             } else {
                 $combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];
                 if ($row['default_on']) {
                     if (isset($this->context->smarty->tpl_vars['cover']->value)) {
                         $current_cover = $this->context->smarty->tpl_vars['cover']->value;
                     }
                     if (is_array($combination_images[$row['id_product_attribute']])) {
                         foreach ($combination_images[$row['id_product_attribute']] as $tmp) {
                             if ($tmp['id_image'] == $current_cover['id_image']) {
                                 $combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];
                                 break;
                             }
                         }
                     }
                     if ($id_image > 0) {
                         if (isset($this->context->smarty->tpl_vars['images']->value)) {
                             $product_images = $this->context->smarty->tpl_vars['images']->value;
                         }
                         if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {
                             $product_images[$id_image]['cover'] = 1;
                             $this->context->smarty->assign('mainImage', $product_images[$id_image]);
                             if (count($product_images)) {
                                 $this->context->smarty->assign('images', $product_images);
                             }
                         }
                         if (isset($this->context->smarty->tpl_vars['cover']->value)) {
                             $cover = $this->context->smarty->tpl_vars['cover']->value;
                         }
                         if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {
                             $product_images[$cover['id_image']]['cover'] = 0;
                             if (isset($product_images[$id_image])) {
                                 $cover = $product_images[$id_image];
                             }
                             $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $id_image : (int) $id_image;
                             $cover['id_image_only'] = (int) $id_image;
                             $this->context->smarty->assign('cover', $cover);
                         }
                     }
                 }
             }
         }
         // wash attributes list (if some attributes are unavailables and if allowed to wash it)
         if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
             foreach ($groups as &$group) {
                 foreach ($group['attributes_quantity'] as $key => &$quantity) {
                     if ($quantity <= 0) {
                         unset($group['attributes'][$key]);
                     }
                 }
             }
             foreach ($colors as $key => $color) {
                 if ($color['attributes_quantity'] <= 0) {
                     unset($colors[$key]);
                 }
             }
         }
         foreach ($combinations as $id_product_attribute => $comb) {
             $attribute_list = '';
             foreach ($comb['attributes'] as $id_attribute) {
                 $attribute_list .= '\'' . (int) $id_attribute . '\',';
             }
             $attribute_list = rtrim($attribute_list, ',');
             $combinations[$id_product_attribute]['list'] = $attribute_list;
         }
         $this->context->smarty->assign(array('groups' => $groups, 'colors' => count($colors) ? $colors : false, 'combinations' => $combinations, 'combinationImages' => $combination_images));
     }
 }
 public function execValidation($cart)
 {
     global $cookie;
     if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->active) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process
     $authorized = false;
     foreach (Module::getPaymentModules() as $module) {
         if ($module['name'] == 'veritranspay') {
             $authorized = true;
             break;
         }
     }
     if (!$authorized) {
         die($this->module->l('This payment method is not available.', 'validation'));
     }
     $customer = new Customer($cart->id_customer);
     if (!Validate::isLoadedObject($customer)) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $usd = Configuration::get('VT_KURS');
     $cf = Configuration::get('VT_CONVENIENCE_FEE') * 0.01;
     $list_enable_payments = array();
     if (Configuration::get('ENABLED_CREDIT_CARD')) {
         $list_enable_payments[] = "credit_card";
     }
     if (Configuration::get('ENABLED_CIMB')) {
         $list_enable_payments[] = "cimb_clicks";
     }
     if (Configuration::get('ENABLED_MANDIRI')) {
         $list_enable_payments[] = "mandiri_clickpay";
     }
     if (Configuration::get('ENABLED_PERMATAVA')) {
         $list_enable_payments[] = "bank_transfer";
     }
     if (Configuration::get('ENABLED_BRIEPAY')) {
         $list_enable_payments[] = "bri_epay";
     }
     if (Configuration::get('ENABLED_TELKOMSEL_CASH')) {
         $list_enable_payments[] = "telkomsel_cash";
     }
     if (Configuration::get('ENABLED_XL_TUNAI')) {
         $list_enable_payments[] = "xl_tunai";
     }
     if (Configuration::get('ENABLED_MANDIRI_BILL')) {
         $list_enable_payments[] = "echannel";
     }
     if (Configuration::get('ENABLED_BBM_MONEY')) {
         $list_enable_payments[] = "bbm_money";
     }
     if (Configuration::get('ENABLED_INDOMARET')) {
         $list_enable_payments[] = "cstore";
     }
     if (Configuration::get('ENABLED_INDOSAT_DOMPETKU')) {
         $list_enable_payments[] = "indosat_dompetku";
     }
     if (Configuration::get('ENABLED_MANDIRI_ECASH')) {
         $list_enable_payments[] = "mandiri_ecash";
     }
     //error_log(print_r($list_enable_payments,TRUE));
     $veritrans = new Veritrans_Config();
     //SETUP
     Veritrans_Config::$serverKey = Configuration::get('VT_SERVER_KEY');
     Veritrans_Config::$isProduction = Configuration::get('VT_ENVIRONMENT') == 'production' ? true : false;
     $url = Veritrans_Config::getBaseUrl();
     if (version_compare(Configuration::get('PS_VERSION_DB'), '1.5') == -1) {
         $shipping_cost = $cart->getOrderShippingCost();
     } else {
         $shipping_cost = $cart->getTotalShippingCost();
     }
     $currency = new Currency($cookie->id_currency);
     $total = $cart->getOrderTotal(true, Cart::BOTH);
     $mailVars = array();
     $billing_address = new Address($cart->id_address_invoice);
     $delivery_address = new Address($cart->id_address_delivery);
     if (Configuration::get('VT_3D_SECURE') == 'on' || Configuration::get('VT_3D_SECURE') == 1) {
         Veritrans_Config::$is3ds = true;
     }
     if (Configuration::get('VT_SANITIZED') == 'on' || Configuration::get('VT_SANITIZED') == 1) {
         Veritrans_Config::$isSanitized = true;
     }
     //error_log('sanitized '.Configuration::get('VT_SANITIZED'));
     // Billing Address
     $params_billing_address = array('first_name' => $billing_address->firstname, 'last_name' => $billing_address->lastname, 'address' => $billing_address->address1, 'city' => $billing_address->city, 'postal_code' => $billing_address->postcode, 'phone' => $this->determineValidPhone($billing_address->phone, $billing_address->phone_mobile), 'country_code' => 'IDN');
     if ($cart->isVirtualCart()) {
     } else {
         if ($cart->id_address_delivery != $cart->id_address_invoice) {
             $params_shipping_address = array('first_name' => $delivery_address->firstname, 'last_name' => $delivery_address->lastname, 'address' => $delivery_address->address1, 'city' => $delivery_address->city, 'postal_code' => $delivery_address->postcode, 'phone' => $this->determineValidPhone($delivery_address->phone, $delivery_address->phone_mobile), 'country_code' => 'IDN');
         } else {
             $params_shipping_address = $params_billing_address;
         }
     }
     $params_customer_details = array('first_name' => $billing_address->firstname, 'last_name' => $billing_address->lastname, 'email' => $customer->email, 'phone' => $this->determineValidPhone($billing_address->phone, $billing_address->phone_mobile), 'billing_address' => $params_billing_address, 'shipping_address' => $params_shipping_address);
     $items = $this->addCommodities($cart, $shipping_cost, $usd);
     // convert the currency
     $cart_currency = new Currency($cart->id_currency);
     if ($cart_currency->iso_code != 'IDR') {
         // check whether if the IDR is installed or not
         if (Currency::exists('IDR', null)) {
             // use default rate
             if (version_compare(Configuration::get('PS_VERSION_DB'), '1.5') == -1) {
                 $conversion_func = function ($input) use($cart_currency) {
                     return Tools::convertPrice($input, new Currency(Currency::getIdByIsoCode('IDR')), true);
                 };
             } else {
                 $conversion_func = function ($input) use($cart_currency) {
                     return Tools::convertPriceFull($input, $cart_currency, new Currency(Currency::getIdByIsoCode('IDR')));
                 };
             }
         } else {
             // use rate
             $conversion_func = function ($input) {
                 return $input * intval(Configuration::get('VT_KURS'));
             };
         }
         foreach ($items as &$item) {
             $item['price'] = intval(round(call_user_func($conversion_func, $item['price'])));
         }
     } else {
         if ($cart_currency->iso_code == 'IDR') {
             foreach ($items as &$item) {
                 $item['price'] = intval(round($item['price']));
             }
         }
     }
     $this->validateOrder($cart->id, Configuration::get('VT_ORDER_STATE_ID'), $cart->getOrderTotal(true, Cart::BOTH), $this->displayName, NULL, $mailVars, (int) $currency->id, false, $customer->secure_key);
     $gross_amount = 0;
     unset($item);
     foreach ($items as $item) {
         $gross_amount += $item['price'] * $item['quantity'];
     }
     $isBniInstallment = Configuration::get('ENABLED_BNI_INSTALLMENT') == 1;
     $isMandiriInstallment = Configuration::get('ENABLED_MANDIRI_INSTALLMENT') == 1;
     $warning_redirect = false;
     $fullPayment = true;
     $installment_type_val = Configuration::get('VT_ENABLE_INSTALLMENT');
     $param_required;
     switch ($installment_type_val) {
         case 'all_product':
             if ($isBniInstallment) {
                 //$bni_term2 = $this->getTermInstallment('BNI');
                 $a = Configuration::get('VT_INSTALLMENTS_BNI');
                 $term = explode(',', $a);
                 $bni_term = $term;
                 //error_log(print_r($bni_term,true));
                 //error_log($bni_term,true);
             }
             if ($isMandiriInstallment) {
                 $mandiri_term = $this->getTermInstallment('MANDIRI');
                 $a = Configuration::get('VT_INSTALLMENTS_MANDIRI');
                 $term = explode(',', $a);
                 $mandiri_term = $term;
                 //error_log($mandiri_term,true);
                 //error_log(print_r($mandiri_term,true));
             }
             $param_installment = array();
             if ($isBniInstallment) {
                 $param_installment['bni'] = $bni_term;
             }
             if ($isMandiriInstallment) {
                 $param_installment['mandiri'] = $mandiri_term;
             }
             $param_required = "false";
             $fullPayment = false;
             break;
         case 'certain_product':
             $param_installment = null;
             $products_cart = $cart->getProducts();
             $num_product = count($products_cart);
             if ($num_product == 1) {
                 $attr_product = explode(',', $products_cart[0]['attributes_small']);
                 foreach ($attr_product as $att) {
                     $att_trim = ltrim($att);
                     $att_arr = explode(' ', $att_trim);
                     //error_log(print_r($att_arr,true));
                     if (strtolower($att_arr[0]) == 'installment') {
                         $fullPayment = false;
                         $param_installment = array();
                         $param_installment[strtolower($att_arr[1])] = array($att_arr[2]);
                     }
                 }
             } else {
                 $warning_redirect = true;
                 $keys['message'] = 1;
             }
             $param_required = "true";
             break;
         case 'off':
             $param_installment = null;
             break;
     }
     //error_log($param_installment,true);
     // $param_payment_option = array(
     // 	'installment' => array(
     // 						'required' => $param_required,
     // 						'installment_terms' => $param_installment
     // 					)
     // 	);
     $params_all = array('payment_type' => Configuration::get('VT_PAYMENT_TYPE'), 'vtweb' => array('enabled_payments' => $list_enable_payments), 'transaction_details' => array('order_id' => $this->currentOrder, 'gross_amount' => $gross_amount), 'item_details' => $items, 'customer_details' => $params_customer_details);
     if ($gross_amount < 500000) {
         $warning_redirect = true;
         $keys['message'] = 2;
     }
     if (!$warning_redirect && ($isBniInstallment || $isMandiriInstallment) && !$fullPayment) {
         $params_all['vtweb']['payment_options'] = $param_payment_option;
     }
     if (Configuration::get('VT_API_VERSION') == 2 && Configuration::get('VT_PAYMENT_TYPE') != 'vtdirect') {
         try {
             // Redirect to Veritrans VTWeb page
             if ($this->isInstallmentCart($cart->getProducts()) || $installment_type_val == 'all_product') {
                 $keys['isWarning'] = $warning_redirect;
             } else {
                 $keys['isWarning'] = false;
             }
             $keys['redirect_url'] = Veritrans_Vtweb::getRedirectionUrl($params_all);
         } catch (Exception $e) {
             $keys['errors'] = $e->getMessage();
             echo $e->getMessage();
         }
         return $keys;
     } else {
         if (Configuration::get('VT_API_VERSION') == 2 && Configuration::get('VT_PAYMENT_TYPE') == 'vtdirect') {
             echo 'not yet implementation.';
             exit;
         } else {
             echo 'The Veritrans API versions and the payment type is not valid.';
             exit;
         }
     }
 }
    /**
     * Loads products which quantity (hysical quantity) is equal or less than $threshold
     * @param int $threshold
     */
    protected function loadProducts($threshold)
    {
        // if there is already an order
        if (Tools::getValue('id_supply_order')) {
            $supply_order = new SupplyOrder((int) Tools::getValue('id_supply_order'));
        } else {
            // else, we just created a new order
            $supply_order = $this->object;
        }
        // if order is not valid, return;
        if (!Validate::isLoadedObject($supply_order)) {
            return;
        }
        // resets products if needed
        if (Tools::getValue('id_supply_order')) {
            $supply_order->resetProducts();
        }
        // gets products
        $query = new DbQuery();
        $query->select('
			ps.id_product,
			ps.id_product_attribute,
			ps.product_supplier_reference as supplier_reference,
			ps.product_supplier_price_te as unit_price_te,
			ps.id_currency,
			IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
			IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
			IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc');
        $query->from('product_supplier', 'ps');
        $query->leftJoin('stock', 's', '
			s.id_product = ps.id_product
			AND s.id_product_attribute = ps.id_product_attribute
			AND s.id_warehouse = ' . (int) $supply_order->id_warehouse);
        $query->innerJoin('warehouse_product_location', 'wpl', '
			wpl.id_product = ps.id_product
			AND wpl.id_product_attribute = ps.id_product_attribute
			AND wpl.id_warehouse = ' . (int) $supply_order->id_warehouse . '
		');
        $query->leftJoin('product', 'p', 'p.id_product = ps.id_product');
        $query->leftJoin('product_attribute', 'pa', '
			pa.id_product_attribute = ps.id_product_attribute
			AND p.id_product = ps.id_product
		');
        $query->where('ps.id_supplier = ' . (int) $supply_order->id_supplier);
        // gets items
        $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
        // loads order currency
        $order_currency = new Currency($supply_order->id_currency);
        if (!Validate::isLoadedObject($order_currency)) {
            return;
        }
        $manager = StockManagerFactory::getManager();
        foreach ($items as $item) {
            $diff = (int) $threshold;
            if ($supply_order->is_template != 1) {
                $real_quantity = (int) $manager->getProductRealQuantities($item['id_product'], $item['id_product_attribute'], $supply_order->id_warehouse, true);
                $diff = (int) $threshold - (int) $real_quantity;
            }
            if ($diff >= 0) {
                // sets supply_order_detail
                $supply_order_detail = new SupplyOrderDetail();
                $supply_order_detail->id_supply_order = $supply_order->id;
                $supply_order_detail->id_currency = $order_currency->id;
                $supply_order_detail->id_product = $item['id_product'];
                $supply_order_detail->id_product_attribute = $item['id_product_attribute'];
                $supply_order_detail->reference = $item['reference'];
                $supply_order_detail->supplier_reference = $item['supplier_reference'];
                $supply_order_detail->name = Product::getProductName($item['id_product'], $item['id_product_attribute'], $supply_order->id_lang);
                $supply_order_detail->ean13 = $item['ean13'];
                $supply_order_detail->upc = $item['upc'];
                $supply_order_detail->quantity_expected = (int) $diff == 0 ? 1 : (int) $diff;
                $supply_order_detail->exchange_rate = $order_currency->conversion_rate;
                $product_currency = new Currency($item['id_currency']);
                if (Validate::isLoadedObject($product_currency)) {
                    $supply_order_detail->unit_price_te = Tools::convertPriceFull($item['unit_price_te'], $product_currency, $order_currency);
                } else {
                    $supply_order_detail->unit_price_te = 0;
                }
                $supply_order_detail->save();
                unset($product_currency);
            }
        }
        // updates supply order
        $supply_order->update();
    }
    /**
     * search product for multi select product pop-up
     *
     */
    public static function searchProduct($id_supplier, $id_category, $id_manufacturer, $id_currency)
    {
        // get supplier id
        $id_supplier = !empty($id_supplier) ? (int) $id_supplier : false;
        // get category id
        $id_category = !empty($id_category) ? (int) $id_category : false;
        // get manufacturer id
        $id_manufacturer = !empty($id_manufacturer) ? (int) $id_manufacturer : false;
        // gets the currency
        $id_currency = !empty($id_currency) ? (int) $id_currency : false;
        // get lang from context
        $id_lang = (int) Context::getContext()->language->id;
        // Get trash category
        $trash_category_id = self::getTrashCategory();
        $query = new DbQuery();
        $query->select('
			CONCAT(p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\')) as id,
			ps.product_supplier_reference as supplier_reference,
			IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
			IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
			IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc,
			md5(CONCAT(\'' . _COOKIE_KEY_ . '\', p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\'))) as checksum,
			IFNULL(CONCAT(pl.name, \' : \', GROUP_CONCAT(DISTINCT agl.name, \' - \', al.name ORDER BY agl.name, \' - \', al.name ASC SEPARATOR \', \')), pl.name) as name,
			p.id_supplier as id_default_supplier,
			CASE WHEN (( TRIM(al.name) REGEXP "^[0-9]+$")) THEN LPAD( al.name ,"8", "0") ELSE al.name END as tri_al_name
		');
        $query->from('product', 'p');
        $query->innerJoin('product_lang', 'pl', 'pl.id_product = p.id_product AND pl.id_lang = ' . $id_lang);
        $query->leftJoin('product_attribute', 'pa', 'pa.id_product = p.id_product');
        $query->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pa.id_product_attribute');
        $query->leftJoin('attribute', 'atr', 'atr.id_attribute = pac.id_attribute');
        $query->leftJoin('attribute_lang', 'al', 'al.id_attribute = atr.id_attribute AND al.id_lang = ' . $id_lang);
        $query->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = atr.id_attribute_group AND agl.id_lang = ' . $id_lang);
        $query->leftJoin('product_supplier', 'ps', 'ps.id_product = p.id_product AND ps.id_product_attribute = IFNULL(pa.id_product_attribute, 0)');
        //$query->where('(pl.name LIKE \'%'.$pattern.'%\' OR p.reference LIKE \'%'.$pattern.'%\' OR ps.product_supplier_reference LIKE \'%'.$pattern.'%\')');
        $query->where('p.id_product NOT IN (SELECT pd.id_product FROM `' . _DB_PREFIX_ . 'product_download` pd WHERE (pd.id_product = p.id_product) AND (pd.active = 1))');
        $query->where('p.is_virtual = 0 AND p.cache_is_pack = 0');
        //filter by supplier
        if ($id_supplier) {
            $query->where('ps.id_supplier = ' . $id_supplier . ' OR p.id_supplier = ' . $id_supplier);
        }
        if ($id_category || !empty($trash_category_id)) {
            $query->leftJoin('category_product', 'pc', 'pc.id_product = p.id_product');
        }
        //filter by categorie
        if ($id_category) {
            $query->where('p.id_category_default = ' . $id_category . ' OR pc.id_category = ' . $id_category);
        }
        if (!empty($trash_category_id)) {
            $query->where('p.id_category_default != ' . $trash_category_id . ' AND pc.id_category != ' . $trash_category_id);
        }
        //filter by manufacturer
        if ($id_manufacturer) {
            $query->where('p.id_manufacturer = ' . $id_manufacturer);
        }
        $query->groupBy('p.id_product, pa.id_product_attribute');
        $query->orderBy(' pl.name  ASC, agl.name ASC, tri_al_name ASC ');
        $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
        foreach ($items as &$item) {
            $ids = explode('_', $item['id']);
            //New - display prices
            $prices = self::getWholesalePrice($ids[0], $ids[1], $id_supplier);
            if (!empty($prices)) {
                $item['unit_price_te'] = Tools::convertPriceFull($prices, new Currency((int) $id_currency), new Currency($id_currency));
            } else {
                $item['unit_price_te'] = '';
            }
        }
        if ($items) {
            return $items;
        }
    }
    /**
     * Check if this cart rule can be applied
     *
     * @param Context $context
     * @param bool $alreadyInCart Check if the voucher is already on the cart
     * @param bool $display_error Display error
     * @return bool|mixed|string
     */
    public function checkValidity(Context $context, $alreadyInCart = false, $display_error = true, $check_carrier = true)
    {
        if (!CartRule::isFeatureActive()) {
            return false;
        }
        if (!$this->active) {
            return !$display_error ? false : Tools::displayError('This voucher is disabled');
        }
        if (!$this->quantity) {
            return !$display_error ? false : Tools::displayError('This voucher has already been used');
        }
        if (strtotime($this->date_from) > time()) {
            return !$display_error ? false : Tools::displayError('This voucher is not valid yet');
        }
        if (strtotime($this->date_to) < time()) {
            return !$display_error ? false : Tools::displayError('This voucher has expired');
        }
        if ($context->cart->id_customer) {
            $quantityUsed = Db::getInstance()->getValue('
			SELECT count(*)
			FROM ' . _DB_PREFIX_ . 'orders o
			LEFT JOIN ' . _DB_PREFIX_ . 'order_cart_rule od ON o.id_order = od.id_order
			WHERE o.id_customer = ' . $context->cart->id_customer . '
			AND od.id_cart_rule = ' . (int) $this->id . '
			AND ' . (int) Configuration::get('PS_OS_ERROR') . ' != o.current_state
			');
            if ($quantityUsed + 1 > $this->quantity_per_user) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher anymore (usage limit reached)');
            }
        }
        // Get an intersection of the customer groups and the cart rule groups (if the customer is not logged in, the default group is Visitors)
        if ($this->group_restriction) {
            $id_cart_rule = (int) Db::getInstance()->getValue('
			SELECT crg.id_cart_rule
			FROM ' . _DB_PREFIX_ . 'cart_rule_group crg
			WHERE crg.id_cart_rule = ' . (int) $this->id . '
			AND crg.id_group ' . ($context->cart->id_customer ? 'IN (SELECT cg.id_group FROM ' . _DB_PREFIX_ . 'customer_group cg WHERE cg.id_customer = ' . (int) $context->cart->id_customer . ')' : '= ' . (int) Configuration::get('PS_UNIDENTIFIED_GROUP')));
            if (!$id_cart_rule) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher');
            }
        }
        // Check if the customer delivery address is usable with the cart rule
        if ($this->country_restriction) {
            if (!$context->cart->id_address_delivery) {
                return !$display_error ? false : Tools::displayError('You must choose a delivery address before applying this voucher to your order');
            }
            $id_cart_rule = (int) Db::getInstance()->getValue('
			SELECT crc.id_cart_rule
			FROM ' . _DB_PREFIX_ . 'cart_rule_country crc
			WHERE crc.id_cart_rule = ' . (int) $this->id . '
			AND crc.id_country = (SELECT a.id_country FROM ' . _DB_PREFIX_ . 'address a WHERE a.id_address = ' . (int) $context->cart->id_address_delivery . ' LIMIT 1)');
            if (!$id_cart_rule) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher in your country of delivery');
            }
        }
        // Check if the carrier chosen by the customer is usable with the cart rule
        if ($this->carrier_restriction && $check_carrier) {
            if (!$context->cart->id_carrier) {
                return !$display_error ? false : Tools::displayError('You must choose a carrier before applying this voucher to your order');
            }
            $id_cart_rule = (int) Db::getInstance()->getValue('
			SELECT crc.id_cart_rule
			FROM ' . _DB_PREFIX_ . 'cart_rule_carrier crc
			INNER JOIN ' . _DB_PREFIX_ . 'carrier c ON (c.id_reference = crc.id_carrier AND c.deleted = 0)
			WHERE crc.id_cart_rule = ' . (int) $this->id . '
			AND c.id_carrier = ' . (int) $context->cart->id_carrier);
            if (!$id_cart_rule) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher with this carrier');
            }
        }
        // Check if the cart rules appliy to the shop browsed by the customer
        if ($this->shop_restriction && $context->shop->id && Shop::isFeatureActive()) {
            $id_cart_rule = (int) Db::getInstance()->getValue('
			SELECT crs.id_cart_rule
			FROM ' . _DB_PREFIX_ . 'cart_rule_shop crs
			WHERE crs.id_cart_rule = ' . (int) $this->id . '
			AND crs.id_shop = ' . (int) $context->shop->id);
            if (!$id_cart_rule) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher');
            }
        }
        // Check if the products chosen by the customer are usable with the cart rule
        if ($this->product_restriction) {
            $r = $this->checkProductRestrictions($context, false, $display_error, $alreadyInCart);
            if ($r !== false && $display_error) {
                return $r;
            } elseif (!$r && !$display_error) {
                return false;
            }
        }
        // Check if the cart rule is only usable by a specific customer, and if the current customer is the right one
        if ($this->id_customer && $context->cart->id_customer != $this->id_customer) {
            if (!Context::getContext()->customer->isLogged()) {
                return !$display_error ? false : Tools::displayError('You cannot use this voucher') . ' - ' . Tools::displayError('Please log in first');
            }
            return !$display_error ? false : Tools::displayError('You cannot use this voucher');
        }
        if ($this->minimum_amount && $check_carrier) {
            // Minimum amount is converted to the contextual currency
            $minimum_amount = $this->minimum_amount;
            if ($this->minimum_amount_currency != Context::getContext()->currency->id) {
                $minimum_amount = Tools::convertPriceFull($minimum_amount, new Currency($this->minimum_amount_currency), Context::getContext()->currency);
            }
            $cartTotal = $context->cart->getOrderTotal($this->minimum_amount_tax, Cart::ONLY_PRODUCTS);
            if ($this->minimum_amount_shipping) {
                $cartTotal += $context->cart->getOrderTotal($this->minimum_amount_tax, Cart::ONLY_SHIPPING);
            }
            $products = $context->cart->getProducts();
            $cart_rules = $context->cart->getCartRules();
            foreach ($cart_rules as &$cart_rule) {
                if ($cart_rule['gift_product']) {
                    foreach ($products as $key => &$product) {
                        if (empty($product['gift']) && $product['id_product'] == $cart_rule['gift_product'] && $product['id_product_attribute'] == $cart_rule['gift_product_attribute']) {
                            $cartTotal = Tools::ps_round($cartTotal - $product[$this->minimum_amount_tax ? 'price_wt' : 'price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_);
                        }
                    }
                }
            }
            if ($cartTotal < $minimum_amount) {
                return !$display_error ? false : Tools::displayError('You have not reached the minimum amount required to use this voucher');
            }
        }
        /* This loop checks:
        			- if the voucher is already in the cart
        			- if a non compatible voucher is in the cart
        			- if there are products in the cart (gifts excluded)
        			Important note: this MUST be the last check, because if the tested cart rule has priority over a non combinable one in the cart, we will switch them
        		*/
        $nb_products = Cart::getNbProducts($context->cart->id);
        $otherCartRules = array();
        if ($check_carrier) {
            $otherCartRules = $context->cart->getCartRules();
        }
        if (count($otherCartRules)) {
            foreach ($otherCartRules as $otherCartRule) {
                if ($otherCartRule['id_cart_rule'] == $this->id && !$alreadyInCart) {
                    return !$display_error ? false : Tools::displayError('This voucher is already in your cart');
                }
                if ($otherCartRule['gift_product']) {
                    --$nb_products;
                }
                if ($this->cart_rule_restriction && $otherCartRule['cart_rule_restriction'] && $otherCartRule['id_cart_rule'] != $this->id) {
                    $combinable = Db::getInstance()->getValue('
					SELECT id_cart_rule_1
					FROM ' . _DB_PREFIX_ . 'cart_rule_combination
					WHERE (id_cart_rule_1 = ' . (int) $this->id . ' AND id_cart_rule_2 = ' . (int) $otherCartRule['id_cart_rule'] . ')
					OR (id_cart_rule_2 = ' . (int) $this->id . ' AND id_cart_rule_1 = ' . (int) $otherCartRule['id_cart_rule'] . ')');
                    if (!$combinable) {
                        $cart_rule = new CartRule((int) $otherCartRule['id_cart_rule'], $context->cart->id_lang);
                        // The cart rules are not combinable and the cart rule currently in the cart has priority over the one tested
                        if ($cart_rule->priority <= $this->priority) {
                            return !$display_error ? false : Tools::displayError('This voucher is not combinable with an other voucher already in your cart:') . ' ' . $cart_rule->name;
                        } else {
                            $context->cart->removeCartRule($cart_rule->id);
                        }
                    }
                }
            }
        }
        if (!$nb_products) {
            return !$display_error ? false : Tools::displayError('Cart is empty');
        }
        if (!$display_error) {
            return true;
        }
    }
Example #24
0
 private function convertPrice($data, $id_currency, $to_id_currency = false)
 {
     if ($this->currency_code == self::CURRENCY_NOT_SET && !$to_id_currency) {
         return $data;
     } elseif ($this->currency_code == self::CURRENCY_NOT_SET) {
         $currency_to = Currency::getCurrencyInstance($to_id_currency);
     } else {
         $currency_to = Currency::getCurrencyInstance($this->currency_code);
     }
     $currency_from = Currency::getCurrencyInstance($id_currency);
     return Tools::convertPriceFull($data, $currency_from, $currency_to);
 }
 public function postProcess()
 {
     parent::postProcess();
     $this->log_on = Configuration::get('YA_P2P_LOGGING_ON');
     $cart = $this->context->cart;
     if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $customer = new Customer($cart->id_customer);
     if (!Validate::isLoadedObject($customer)) {
         Tools::redirect('index.php?controller=order&step=1');
     }
     $this->myCart = $this->context->cart;
     $total_to_pay = $cart->getOrderTotal(true);
     $rub_currency_id = Currency::getIdByIsoCode('RUB');
     if ($cart->id_currency != $rub_currency_id) {
         $from_currency = new Currency($cart->id_currency);
         $to_currency = new Currency($rub_currency_id);
         $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
     }
     if ($total_to_pay > 0 && $total_to_pay < 1) {
         $total_to_pay_limit = '1.00';
     } else {
         $total_to_pay_limit = number_format($total_to_pay, 2, '.', '');
     }
     $total_to_pay = number_format($total_to_pay, 2, '.', '');
     $this->module->payment_status = false;
     $code = Tools::getValue('code');
     $cnf = Tools::getValue('cnf');
     if (empty($code)) {
         Tools::redirect('index.php?controller=order&step=3');
     } elseif (!empty($code) && $cnf) {
         $comment = $message = $this->module->l('total:') . $total_to_pay . $this->module->l(' rub');
         $response = ExternalPayment::getInstanceId(Configuration::get('YA_P2P_IDENTIFICATOR'));
         if ($response->status == "success") {
             if ($this->log_on) {
                 $this->module->log_save('card_redirect:  ' . $this->module->l('get instance success'));
             }
             $instance_id = $response->instance_id;
             $external_payment = new ExternalPayment($instance_id);
             $payment_options = array("pattern_id" => "p2p", "to" => Configuration::get('YA_P2P_NUMBER'), "amount_due" => $total_to_pay, "comment" => trim($comment), "message" => trim($message), "label" => $this->context->cart->id);
             $response = $external_payment->request($payment_options);
             if ($response->status == "success") {
                 if ($this->log_on) {
                     $this->module->log_save('card_redirect:  ' . $this->module->l('request success'));
                 }
                 $request_id = $response->request_id;
                 $this->context->cookie->ya_encrypt_CRequestId = urlencode(base64_encode($request_id));
                 $this->context->cookie->write();
                 do {
                     $process_options = array("request_id" => $request_id, 'ext_auth_success_uri' => $this->context->link->getModuleLink('yamodule', 'payment_card', array(), true), 'ext_auth_fail_uri' => $this->context->link->getModuleLink('yamodule', 'payment_card', array(), true));
                     $result = $external_payment->process($process_options);
                     if ($result->status == "in_progress") {
                         sleep(1);
                     }
                 } while ($result->status == "in_progress");
                 if ($result->status == 'success') {
                     $this->updateStatus($res);
                     $this->error = false;
                 } elseif ($result->status == 'ext_auth_required') {
                     $url = sprintf("%s?%s", $result->acs_uri, http_build_query($result->acs_params));
                     if ($this->log_on) {
                         $this->module->log_save('card_redirect:  ' . $this->module->l('redirect to') . ' ' . $url);
                     }
                     Tools::redirect($url, '');
                     exit;
                 } elseif ($result->status == 'refused') {
                     $this->errors[] = $this->module->descriptionError($resp->error) ? $this->module->descriptionError($resp->error) : $result->error;
                     if ($this->log_on) {
                         $this->module->log_save('card_redirect:refused ' . $this->module->descriptionError($resp->error) ? $this->module->descriptionError($resp->error) : $result->error);
                     }
                     $this->module->payment_status = 102;
                 }
             }
         }
     }
 }
Example #26
0
    /**
     * @static
     * @param $lang_id
     * @param $customer_id
     * @param bool $published
     * @param bool $includeGeneric
     * @param bool $inStock
     * @param JeproshopCartModelCart|null $cart
     * @return array
     */
    public static function getCustomerCartRules($lang_id, $customer_id, $published = false, $includeGeneric = true, $inStock = false, JeproshopCartModelCart $cart = null)
    {
        if (!JeproshopCartRuleModelCartRule::isFeaturePublished()) {
            return array();
        }
        $db = JFactory::getDBO();
        $query = "SELECT * FROM " . $db->quoteName('#_jeproshop_cart_rule') . " AS cart_rule LEFT JOIN " . $db->quoteName('#__jeproshop_cart_rule_lang') . " AS cart_ruler_lang";
        $query .= " ON (cart_rule." . $db->quoteName('cart_rule_id') . " = cart_rule_lang." . $db->quoteName('cart_rule_id') . " AND cart_rule_lang." . $db->quoteName('lang_id');
        $query .= " = " . (int) $lang_id . ") WHERE ( cart_rule." . $db->quoteName('customer_id') . " = " . (int) $customer_id . " OR cart_rule.group_restriction = 1 ";
        $query .= ($includeGeneric ? " OR cart_rule." . $db->quoteName('customer_id') . " = 0" : "") . ") AND cart_rule.date_from < '" . date('Y-m-d H:i:s') . "' AND cart_rule.date_to > '";
        $query .= date('Y-m-d H:i:s') . "' " . ($published ? "AND cart_rule." . $db->quoteName('published') . " = 1" : "") . ($inStock ? " AND cart_rule." . $db->quoteName('quantity') . " > 0" : "");
        $db->setQuery($query);
        $result = $db->loadObjectList();
        // Remove cart rule that does not match the customer groups
        $customerGroups = JeproshopCustomerModelCustomer::getStaticGroups($customer_id);
        foreach ($result as $key => $cart_rule) {
            if ($cart_rule->group_restriction) {
                $cartRuleGroups = Db::getInstance()->executeS('SELECT id_group FROM ' . _DB_PREFIX_ . 'cart_rule_group WHERE id_cart_rule = ' . (int) $cart_rule['id_cart_rule']);
                foreach ($cartRuleGroups as $cartRuleGroup) {
                    if (in_array($cartRuleGroup->group_id, $customerGroups)) {
                        continue 2;
                    }
                }
                unset($result[$key]);
            }
        }
        foreach ($result as &$cart_rule) {
            if ($cart_rule->quantity_per_user) {
                $quantity_used = Order::getDiscountsCustomer((int) $customer_id, (int) $cart_rule->cart_rule_id);
                if (isset($cart) && isset($cart)) {
                    $quantity_used += $cart->getDiscountsCustomer((int) $cart_rule->cart_rule_id);
                }
                $cart_rule->quantity_for_user = $cart_rule->quantity_per_user - $quantity_used;
            } else {
                $cart_rule->quantity_for_user = 0;
            }
        }
        unset($cart_rule);
        foreach ($result as $key => $cart_rule) {
            if ($cart_rule->shop_restriction) {
                $cartRuleShops = Db::getInstance()->executeS('SELECT id_shop FROM ' . _DB_PREFIX_ . 'cart_rule_shop WHERE id_cart_rule = ' . (int) $cart_rule['id_cart_rule']);
                foreach ($cartRuleShops as $cartRuleShop) {
                    if (Shop::isFeatureActive() && $cartRuleShop->shop_id == JeproshopContext::getContext()->shop->shop_id) {
                        continue 2;
                    }
                }
                unset($result[$key]);
            }
        }
        if (isset($cart) && isset($cart->cart_id)) {
            foreach ($result as $key => $cart_rule) {
                if ($cart_rule->product_restriction) {
                    $cr = new JeproshopCartRuleModelCartRule((int) $cart_rule->cart_rule_id);
                    $restriction = $cr->checkProductRestrictions(JeproshopContext::getContext(), false, false);
                    if ($restriction !== false) {
                        continue;
                    }
                    unset($result[$key]);
                }
            }
        }
        foreach ($result as $key => $cart_rule) {
            if ($cart_rule['country_restriction']) {
                $countries = Db::getInstance()->ExecuteS('
					SELECT `id_country`
					FROM `' . _DB_PREFIX_ . 'address`
					WHERE `customer_id` = ' . (int) $customer_id . '
					AND `deleted` = 0');
                if (is_array($countries) && count($countries)) {
                    foreach ($countries as $country) {
                        $id_cart_rule = (bool) Db::getInstance()->getValue('
							SELECT crc.id_cart_rule
							FROM ' . _DB_PREFIX_ . 'cart_rule_country crc
							WHERE crc.id_cart_rule = ' . (int) $cart_rule['id_cart_rule'] . '
							AND crc.id_country = ' . (int) $country['id_country']);
                        if (!$id_cart_rule) {
                            unset($result[$key]);
                        }
                    }
                }
            }
        }
        // Retro-compatibility with 1.4 discounts
        foreach ($result as &$cart_rule) {
            $cart_rule['value'] = 0;
            $cart_rule['minimal'] = Tools::convertPriceFull($cart_rule['minimum_amount'], new Currency($cart_rule['minimum_amount_currency']), Context::getContext()->currency);
            $cart_rule['cumulable'] = !$cart_rule['cart_rule_restriction'];
            $cart_rule['id_discount_type'] = false;
            if ($cart_rule['free_shipping']) {
                $cart_rule['id_discount_type'] = Discount::FREE_SHIPPING;
            } elseif ($cart_rule['reduction_percent'] > 0) {
                $cart_rule['id_discount_type'] = Discount::PERCENT;
                $cart_rule['value'] = $cart_rule['reduction_percent'];
            } elseif ($cart_rule['reduction_amount'] > 0) {
                $cart_rule->discount_type_id = Discount::AMOUNT;
                $cart_rule['value'] = $cart_rule['reduction_amount'];
            }
        }
        unset($cart_rule);
        return $result;
    }
Example #27
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $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));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         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']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
 public function hookdisplayPayment($params)
 {
     if (!$this->active) {
         return;
     }
     if (!$this->checkCurrency($params['cart'])) {
         return;
     }
     $cart = $this->context->cart;
     $total_to_pay = $cart->getOrderTotal(true);
     $rub_currency_id = Currency::getIdByIsoCode('RUB');
     if ($cart->id_currency != $rub_currency_id) {
         $from_currency = new Currency($cart->id_curre1ncy);
         $to_currency = new Currency($rub_currency_id);
         $total_to_pay = Tools::convertPriceFull($total_to_pay, $from_currency, $to_currency);
     }
     $this->context->smarty->assign(array('summ' => number_format($total_to_pay, 2, '.', ''), 'this_path' => $this->_path, 'this_path_ssl' => Tools::getHttpHost(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/'));
     $display = '';
     if (Configuration::get('YA_P2P_ACTIVE')) {
         $vars_p2p = Configuration::getMultiple(array('YA_P2P_NUMBER', 'YA_P2P_ACTIVE', 'YA_P2P_MIN'));
         $this->context->smarty->assign(array('DATA_P2P' => $vars_p2p, 'price' => number_format($total_to_pay, 2, '.', ''), 'cart' => $this->context->cart));
         $display .= $this->display(__FILE__, 'payment.tpl');
     }
     if (Configuration::get('YA_ORG_ACTIVE')) {
         $vars_org = Configuration::getMultiple(array('YA_ORG_SHOPID', 'YA_ORG_SCID', 'YA_ORG_ACTIVE', 'YA_ORG_TYPE', 'YA_ORG_MIN'));
         $this->context->smarty->assign(array('DATA_ORG' => $vars_org, 'id_cart' => $params['cart']->id, 'customer' => new Customer($params['cart']->id_customer), 'address' => new Address($this->context->cart->id_address_delivery), 'total_to_pay' => number_format($total_to_pay, 2, '.', ''), 'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/', 'shop_name' => Configuration::get('PS_SHOP_NAME')));
         $payments = Configuration::getMultiple(array('YA_ORG_PAYMENT_YANDEX', 'YA_ORG_PAYMENT_CARD', 'YA_ORG_PAYMENT_MOBILE', 'YA_ORG_PAYMENT_WEBMONEY', 'YA_ORG_PAYMENT_TERMINAL', 'YA_ORG_PAYMENT_SBER', 'YA_ORG_PAYMENT_PB', 'YA_ORG_PAYMENT_MA', 'YA_ORG_PAYMENT_QW', 'YA_ORG_PAYMENT_QP', 'YA_ORG_PAYMENT_ALFA'));
         if (Configuration::get('YA_ORG_INSIDE')) {
             if ($payments['YA_ORG_PAYMENT_YANDEX']) {
                 $this->smarty->assign(array('pt' => 'PC', 'buttontext' => $this->l('Payment from the purse in Yandex.Money.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_CARD']) {
                 $this->smarty->assign(array('pt' => 'AC', 'buttontext' => $this->l('Arbitrary payment with Bank card.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_MOBILE']) {
                 $this->smarty->assign(array('pt' => 'MC', 'buttontext' => $this->l('Payment with mobile phone account.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_WEBMONEY']) {
                 $this->smarty->assign(array('pt' => 'WM', 'buttontext' => $this->l('Payment of the purse in system WebMoney.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_TERMINAL']) {
                 $this->smarty->assign(array('pt' => 'GP', 'buttontext' => $this->l('Payment in cash through cash desks and terminals.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_SBER']) {
                 $this->smarty->assign(array('pt' => 'SB', 'buttontext' => $this->l('Payment via Sberbank: payment by SMS or Sberbank Online.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_ALFA']) {
                 $this->smarty->assign(array('pt' => 'AB', 'buttontext' => $this->l('Payment via Alfa-Click.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_PB']) {
                 $this->smarty->assign(array('pt' => 'PB', 'buttontext' => $this->l('Payments via Promsvyazbank.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_MA']) {
                 $this->smarty->assign(array('pt' => 'MA', 'buttontext' => $this->l('Payment via MasterPass.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_QW']) {
                 $this->smarty->assign(array('pt' => 'QW', 'buttontext' => $this->l('Payment via QIWI Wallet.')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
             if ($payments['YA_ORG_PAYMENT_QP']) {
                 $this->smarty->assign(array('pt' => 'QP', 'buttontext' => $this->l('Payment through a trusted payment (Kuppi.ru).')));
                 $display .= $this->display(__FILE__, 'kassa.tpl');
             }
         } else {
             $display .= $this->display(__FILE__, 'kassa_outside.tpl');
         }
     }
     return $display;
 }