コード例 #1
0
ファイル: gopay_tools.php プロジェクト: greench/prestashop
 public function processPayment($result, $orderId)
 {
     $gopay = new Gopay();
     $gpErrors = "";
     $history = new OrderHistory();
     $history->id_order = $orderId;
     if ($result["code"] == GopayHelper::WAITING) {
         $gpErrors = $result["description"];
     } else {
         if ($result["code"] == GopayHelper::PAYMENT_DONE) {
             if ($history->getLastOrderState($orderId)->id == intval(_PS_OS_GOPAY_)) {
                 $history->changeIdOrderState(intval(_PS_OS_PAYMENT_), intval($orderId));
                 $history->addWithemail();
             }
         } else {
             if ($result["code"] == GopayHelper::CANCELED || $result["code"] == GopayHelper::TIMEOUTED) {
                 if ($history->getLastOrderState($orderId)->id == intval(_PS_OS_GOPAY_)) {
                     $history->changeIdOrderState(intval(_PS_OS_CANCELED_), $orderId);
                     $history->addWithemail();
                 }
                 $gpErrors = $result["description"];
             }
         }
     }
     return $gpErrors;
 }
コード例 #2
0
ファイル: result.php プロジェクト: venya/prestashop
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $oplata = new Oplata();
     if ($_POST['order_status'] == OplataCls::ORDER_DECLINED) {
         $this->errors[] = Tools::displayError('Order declined');
     }
     $settings = array('merchant_id' => $oplata->getOption('merchant'), 'secret_key' => $oplata->getOption('secret_key'));
     $isPaymentValid = OplataCls::isPaymentValid($settings, $_POST);
     if ($isPaymentValid !== true) {
         $this->errors[] = Tools::displayError($isPaymentValid);
     }
     $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');
     }
     if (empty($this->errors)) {
         list($orderId, ) = explode(OplataCls::ORDER_SEPARATOR, $_POST['order_id']);
         $history = new OrderHistory();
         $history->id_order = $orderId;
         $history->changeIdOrderState((int) Configuration::get('PS_OS_PAYMENT'), $orderId);
         $history->addWithemail(true, array('order_name' => $orderId));
         Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $cart->id . '&id_module=' . $this->module->id . '&id_order=' . $this->module->currentOrder . '&key=' . $customer->secure_key);
     }
 }
コード例 #3
0
ファイル: OrderDetailController.php プロジェクト: Eximagen/3m
 public function postProcess()
 {
     parent::postProcess();
     if (Tools::isSubmit('markAsReceived')) {
         $idOrder = (int) Tools::getValue('id_order');
         $order = new Order($idOrder);
         if (Validate::isLoadedObject($order)) {
             if ($order->getCurrentState() == 15) {
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState(16, $order);
                 // 16: Ready for Production
                 //var_dump($order,$new_history);
                 $myfile = fopen(PS_PRODUCT_IMG_PATH . "/orders/" . $order->reference . ".txt", "w") or die("Unable to open file!");
                 $txt = "Order Confirmed\n Order Reference: " . $order->reference;
                 fwrite($myfile, $txt);
                 fclose($myfile);
                 $new_history->addWithemail(true);
             }
             $this->context->smarty->assign('receipt_confirmation', true);
         } else {
             $this->_errors[] = Tools::displayError('Error: Invalid order number');
         }
     }
 }
コード例 #4
0
ファイル: callback.php プロジェクト: cloudipsp/prestashop
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     if (empty($_POST)) {
         $fap = json_decode(file_get_contents("php://input"));
         $_POST = array();
         foreach ($fap as $key => $val) {
             $_POST[$key] = $val;
         }
     }
     try {
         if ($_POST['order_status'] == FondyCls::ORDER_DECLINED) {
             exit('Order declined');
         }
         $fondy = new Fondy();
         $settings = array('merchant_id' => $fondy->getOption('merchant'), 'secret_key' => $fondy->getOption('secret_key'));
         $isPaymentValid = FondyCls::isPaymentValid($settings, $_POST);
         if ($isPaymentValid !== true) {
             exit($isPaymentValid);
         }
         list($orderId, ) = explode(FondyCls::ORDER_SEPARATOR, $_POST['order_id']);
         $history = new OrderHistory();
         $history->id_order = $orderId;
         $id_order_state = _PS_OS_PAYMENT_;
         $history->changeIdOrderState(intval($id_order_state), intval($orderId));
         $history->addWithemail(true, "");
         exit('OK');
     } catch (Exception $e) {
         exit(get_class($e) . ': ' . $e->getMessage());
     }
 }
コード例 #5
0
ファイル: retorno.php プロジェクト: dlanileonardo/pagseguro
function TransactionNotification($notificationCode)
{
    ob_clean();
    global $cookie;
    $credentials = new PagSeguroAccountCredentials(Configuration::get("PAGSEGURO_BUSINESS"), Configuration::get("PAGSEGURO_TOKEN"));
    try {
        $transaction = PagSeguroNotificationService::checkTransaction($credentials, $notificationCode);
        $id_transaction = $transaction->getCode();
        $id_status = $transaction->getStatus()->getValue();
        $order_state = Configuration::get("PAGSEGURO_STATUS_{$id_status}");
        $orderState = new OrderState($order_state);
        $status = $orderState->name[$cookie->id_lang];
        $id_order = Db::getInstance()->getValue("SELECT id_order FROM " . _DB_PREFIX_ . "pagseguro_order WHERE id_transaction = '{$id_transaction}'");
        $order = new Order(intval($id_order));
        /** ENVIO DO EMAIL * */
        $pagseguro = new pagseguro();
        $idCustomer = $order->id_customer;
        $idLang = $order->id_lang;
        $customer = new Customer(intval($idCustomer));
        $mailVars = array('{email}' => Configuration::get('PS_SHOP_EMAIL'), '{firstname}' => stripslashes($customer->firstname), '{lastname}' => stripslashes($customer->lastname), '{terceiro}' => stripslashes($pagseguro->displayName), '{id_order}' => stripslashes($pagseguro->currentOrder), '{status}' => stripslashes($status));
        $pagseguro->enviar($mailVars, 'pagseguro', $status, $pagseguro->displayName, $idCustomer, $idLang, $customer->email, 'modules/pagseguro/mails/');
        /** /ENVIO DO EMAIL * */
        $extraVars = array();
        $history = new OrderHistory();
        $history->id_order = intval($id_order);
        $history->changeIdOrderState(intval($order_state), intval($id_order));
        $history->addWithemail(true, $extraVars);
        die("Sucesso!");
    } catch (PagSeguroServiceException $e) {
        file_put_contents(dirname(__FILE__) . "/error.log", var_export($e, true));
        die("Error!");
    }
}
コード例 #6
0
 public function updateStatus(&$resp)
 {
     $this->log_on = Configuration::get('YA_P2P_LOGGING_ON');
     if ($resp->status == 'success') {
         $cart = $this->context->cart;
         if ($cart->id > 0) {
             if ($cart->orderExists()) {
                 $ord = new Order((int) Order::getOrderByCartId($cart->id));
                 $id_order = $ord->id;
             } else {
                 $ord = $this->module->validateOrder($cart->id, Configuration::get('PS_OS_PAYMENT'), $cart->getOrderTotal(true, Cart::BOTH), $this->module->displayName . " Банковская карта", null, array(), null, false, $cart->secure_key);
                 $id_order = $this->module->currentOrder;
             }
             if ($ord) {
                 $history = new OrderHistory();
                 $history->id_order = $id_order;
                 $history->changeIdOrderState(Configuration::get('PS_OS_PAYMENT'), $id_order);
                 $history->addWithemail(true);
             }
         }
         if ($this->log_on) {
             $this->module->logSave('payment_card: #' . $this->module->currentOrder . ' ' . $this->module->l('Order success'));
         }
         Tools::redirect($this->context->link->getPageLink('order-confirmation') . '&id_cart=' . $this->context->cart->id . '&id_module=' . $this->module->id . '&id_order=' . $this->module->currentOrder . '&key=' . $this->context->cart->secure_key);
     }
 }
コード例 #7
0
    public function validateOrderPay($id_cart, $id_order_state, $amount_paid, $extraCosts, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
    {
        $statusPending = Configuration::get('PAYNL_WAIT');
        $statusPaid = Configuration::get('PAYNL_SUCCESS');
        // Als er nog geen order van dit cartid is, de order valideren.
        $orderId = Order::getOrderByCartId($id_cart);
        if ($orderId == false) {
            if ($id_order_state == $statusPaid) {
                if ($extraCosts != 0) {
                    $id_order_state_tmp = $statusPending;
                } else {
                    $id_order_state_tmp = $statusPaid;
                }
            } else {
                $id_order_state_tmp = $id_order_state;
            }
            $result = parent::validateOrder($id_cart, $id_order_state_tmp, $amount_paid, $payment_method, $message, $extra_vars, $currency_special, $dont_touch_amount, $secure_key, $shop);
            $orderId = $this->currentOrder;
            if ($extraCosts == 0 && $id_order_state_tmp == $statusPaid) {
                //Als er geen extra kosten zijn, en de order staat op betaald zijn we klaar
                return $result;
            }
        }
        if ($orderId && $id_order_state == $statusPaid) {
            $order = new Order($orderId);
            $shippingCost = $order->total_shipping;
            $newShippingCosts = $shippingCost + $extraCosts;
            $extraCostsExcl = round($extraCosts / (1 + 21 / 100), 2);
            if ($extraCosts != 0) {
                //als de order extra kosten heeft, moeten deze worden toegevoegd.
                $order->total_shipping = $newShippingCosts;
                $order->total_shipping_tax_excl = $order->total_shipping_tax_excl + $extraCostsExcl;
                $order->total_shipping_tax_incl = $newShippingCosts;
                $order->total_paid_tax_excl = $order->total_paid_tax_excl + $extraCostsExcl;
                $order->total_paid_tax_incl = $order->total_paid_real = $order->total_paid = $order->total_paid + $extraCosts;
            }
            $result = $order->addOrderPayment($amount_paid, $payment_method, $extra_vars['transaction_id']);
            if (number_format($order->total_paid_tax_incl, 2) !== number_format($amount_paid, 2)) {
                $id_order_state = Configuration::get('PS_OS_ERROR');
            }
            //paymentid ophalen
            $orderPayment = OrderPayment::getByOrderId($order->id);
            $history = new OrderHistory();
            $history->id_order = (int) $order->id;
            $history->changeIdOrderState((int) $id_order_state, $order, $orderPayment);
            $res = Db::getInstance()->getRow('
			SELECT `invoice_number`, `invoice_date`, `delivery_number`, `delivery_date`
			FROM `' . _DB_PREFIX_ . 'orders`
			WHERE `id_order` = ' . (int) $order->id);
            $order->invoice_date = $res['invoice_date'];
            $order->invoice_number = $res['invoice_number'];
            $order->delivery_date = $res['delivery_date'];
            $order->delivery_number = $res['delivery_number'];
            $order->update();
            $history->addWithemail();
        }
        return $result;
    }
コード例 #8
0
 public static function changeOrderStatus($id_order, $id_new_state)
 {
     $new_history = new OrderHistory();
     $new_history->id_order = (int) $id_order;
     $new_history->changeIdOrderState((int) $id_new_state, $id_order, true);
     if (!$new_history->addWithemail(true)) {
         ShiptomyidLog::addLog('Error changing order_state to #' . $id_new_state, $id_order);
     }
 }
コード例 #9
0
 public function postProcess()
 {
     parent::postProcess();
     //ИД заказа
     $ordernumber = Tools::getValue('InvId');
     //Сумма заказа
     $amount = Tools::getValue('OutSum');
     $signature = md5($amount . ':' . $ordernumber . ':' . Configuration::get('robokassa_password2'));
     //Проверка подписи
     if (strtoupper($signature) != Tools::getValue('SignatureValue')) {
         robokassa::validateAnsver($this->module->l('Invalid signature'));
     }
     if (Configuration::get('robokassa_postvalidate')) {
         $cart = new Cart((int) $ordernumber);
         //Проверка существования заказа
         if (!Validate::isLoadedObject($cart)) {
             robokassa::validateAnsver($this->module->l('Cart does not exist'));
         }
         $total_to_pay = $cart->getOrderTotal(true, Cart::BOTH);
         $currency_rub = new Currency(Currency::getIdByIsoCode('RUB'));
         if ($cart->id_currency != $currency_rub->id) {
             $currency = new Currency($cart->id_currency);
             $total_to_pay = $total_to_pay / $currency->conversion_rate * $currency_rub->conversion_rate;
         }
         $total_to_pay = number_format($total_to_pay, 2, '.', '');
         //Проверка суммы заказа
         if ($amount != $total_to_pay) {
             robokassa::validateAnsver($this->module->l('Incorrect payment summ'));
         }
         $this->module->validateOrder((int) $cart->id, Configuration::get('PS_OS_PAYMENT'), $cart->getOrderTotal(true, Cart::BOTH), $this->module->displayName, NULL, array(), NULL, false, $cart->secure_key);
     } else {
         $order = new Order((int) $ordernumber);
         //Проверка существования заказа
         if (!Validate::isLoadedObject($order)) {
             robokassa::validateAnsver($this->module->l('Order does not exist'));
         }
         $total_to_pay = $order->total_paid;
         $currency_rub = new Currency(Currency::getIdByIsoCode('RUB'));
         if ($order->id_currency != $currency_rub->id) {
             $currency = new Currency($order->id_currency);
             $total_to_pay = $total_to_pay / $currency->conversion_rate * $currency_rub->conversion_rate;
         }
         $total_to_pay = number_format($total_to_pay, 2, '.', '');
         //Проверка суммы заказа
         if ($amount != $total_to_pay) {
             robokassa::validateAnsver($this->module->l('Incorrect payment summ'));
         }
         //Меняем статус заказа
         $history = new OrderHistory();
         $history->id_order = $ordernumber;
         $history->changeIdOrderState(Configuration::get('PS_OS_PAYMENT'), $ordernumber);
         $history->addWithemail(true);
     }
     die('OK' . $ordernumber);
 }
コード例 #10
0
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     // Log requests from Privat API side in Debug mode.
     if (Configuration::get('PRIVAT24_DEBUG_MODE')) {
         $logger = new FileLogger();
         $logger->setFilename(_PS_ROOT_DIR_ . '/log/' . $this->module->name . '_' . date('Ymd_His') . '_response.log');
         $logger->logError($_POST);
     }
     $payment = array();
     parse_str(Tools::getValue('payment'), $payment);
     $hash = sha1(md5(Tools::getValue('payment') . $this->module->merchant_password));
     if ($payment && $hash === Tools::getValue('signature')) {
         if ($payment['state'] == 'ok') {
             $state = Configuration::get('PRIVAT24_WAITINGPAYMENT_OS');
             $cart_id = (int) $payment['order'];
             $order = new Order(Order::getOrderByCartId($cart_id));
             if (!Validate::isLoadedObject($order)) {
                 PrestaShopLogger::addLog('Privat24: cannot get order by cart id ' . $cart_id, 3);
                 die;
             }
             if ($order->getCurrentState() != $state) {
                 PrestaShopLogger::addLog(sprintf('Privat24: order id %s current state %s !== expected state %s', $order->id, $order->getCurrentState(), $state), 3);
                 die;
             }
             // Check paid currency and paid amount.
             $id_currency = Currency::getIdByIsoCode($payment['ccy']);
             if (!$id_currency) {
                 PrestaShopLogger::addLog(sprintf('Privat24: order id %s cannot get currency id by iso code: %s', $order->id, $payment['ccy']), 3);
                 die;
             }
             if ($order->id_currency != $id_currency) {
                 PrestaShopLogger::addLog(sprintf('Privat 24: order id %s, order currency id %s does not match with %s', $order->id, $order->id_currency, $id_currency), 3);
                 die;
             }
             if ((double) $order->total_paid != (double) $payment['amt']) {
                 PrestaShopLogger::addLog(sprintf('Privat 24: order id %s order total paid %s does not match %s', $order->id, $order->total_paid, $payment['amt']), 3);
                 die;
             }
             $order_history = new OrderHistory();
             $order_history->id_order = $order->id;
             $order_history->changeIdOrderState(_PS_OS_PAYMENT_, $order->id);
             $order_history->addWithemail();
             $this->setPaymentTransaction($order, $payment);
             $this->module->paymentNotify($order, $payment);
             PrestaShopLogger::addLog(sprintf('Privat24 payment accepted: order id: %s, amount: %s, ref: %s', $order->id, $payment['amt'], $payment['ref']), 1);
         } else {
             PrestaShopLogger::addLog(sprintf('Privat24 payment failed: state: %s, order: %s, ref: %s', $payment['state'], $payment['order'], $payment['ref']), 3, null, null, null, true);
         }
     } else {
         PrestaShopLogger::addLog('Privat24: Payment callback bad signature.', 3, null, null, null, true);
     }
     die;
 }
コード例 #11
0
 public function initContent()
 {
     global $smarty, $cart;
     $this->display_column_left = false;
     $this->display_column_right = false;
     parent::initContent();
     if (!empty($_POST)) {
         $b_is_SSL = function_exists('curl_init') && function_exists('curl_setopt') && function_exists('curl_exec') && function_exists('curl_close');
         $p24_session_id = $_POST["p24_session_id"];
         $p24_order_id = $_POST["p24_order_id"];
         $p24_id_sprzedawcy = Configuration::get('P24_ID_SPRZEDAWCY');
         //TWÓJ ID_SPRZEDAWCY;
         $sa_sid = explode('|', $_POST["p24_session_id"]);
         $sa_sid = preg_replace('/[^a-z0-9]/i', '', $sa_sid[1]);
         $o_order = Db::getInstance()->getRow('SELECT `i_id_order`,`i_amount` FROM `' . _DB_PREFIX_ . 'przelewy24_amount` WHERE `s_sid`="' . $sa_sid . '"');
         $p24_kwota = (int) $o_order['i_amount'];
         // WYNIK POBRANY Z TWOJEJ BAZY (w groszach)
         $i_id_order = $o_order['i_id_order'];
         $WYNIK = false;
         $url = 'secure.przelewy24.pl';
         if (Configuration::get('P24_TEST_MODE') == 1) {
             $url = 'sandbox.przelewy24.pl';
         }
         if ($b_is_SSL) {
             $WYNIK = p24_weryfikujSSL($p24_id_sprzedawcy, $p24_session_id, $p24_order_id, $p24_kwota, $url);
         } else {
             $WYNIK = p24_weryfikujNoSSL($p24_id_sprzedawcy, $p24_session_id, $p24_order_id, $p24_kwota, $url);
         }
         $o_przelewy24 = new Przelewy24();
         $opis = "przelewy24.pl";
         $cart = new Cart($i_id_order);
         $secure_key = $cart->secure_key;
         if ($WYNIK[0] == 'TRUE') {
             $order_id = Order::getOrderByCartId(intval($i_id_order));
             $order = new Order($order_id);
             $history = new OrderHistory();
             $history->id_order = intval($order_id);
             $order_state = Configuration::get('P24_ORDER_STATE_2');
             $history->changeIdOrderState($order_state, intval($order_id));
             $history->addWithemail(true);
             $payments = $order->getOrderPaymentCollection();
             if (count($payments) > 0) {
                 $payments[0]->transaction_id = $p24_order_id;
                 $payments[0]->update();
             }
         }
         $smarty->assign('p24_status', 'success');
     }
     $this->setTemplate('paymentSuccessful.tpl');
 }
コード例 #12
0
 /**
  * Makes requesting a refund
  */
 public function display()
 {
     $sa = new DotpaySellerApi($this->config->getDotpaySellerApiUrl());
     $result = $sa->makeReturnMoney($this->config->getDotpayApiUsername(), $this->config->getDotpayApiPassword(), Tools::getValue('payment'), Tools::getValue('amount'), Tools::getValue('order_id'), Tools::getValue('description'));
     if ($result['http_code'] == 200) {
         $status = 'success';
         $state = $this->config->getDotpayWaitingRefundStatusId();
         $history = new OrderHistory();
         $history->id_order = Tools::getValue('order_id');
         $history->changeIdOrderState($state, $history->id_order);
         $history->addWithemail(true);
     } else {
         $status = 'error';
         $this->context->cookie->dotpay_error = $result['detail'];
     }
     Tools::redirectAdmin($this->getRedirectUrl($status));
 }
コード例 #13
0
 private function updateOrderStatus($orderId, $statusName)
 {
     $query = '
         SELECT osl.`id_order_state`, osl.`name` FROM `' . _DB_PREFIX_ . 'order_state_lang` osl
         JOIN `' . _DB_PREFIX_ . 'order_state` os ON osl.`id_order_state` = os.`id_order_state` AND module_name = \'pagseguro\'
         WHERE osl.`name` LIKE "' . $statusName . '" GROUP BY osl.`name` LIMIT 0, 1
     ';
     if ($result = Db::getInstance()->executeS($query)) {
         $status = $result[0]['id_order_state'];
         $order = new Order($orderId);
         $history = new OrderHistory();
         $history->id_order = (int) $order->id;
         $history->changeIdOrderState($status, $order->id);
         return (bool) $history->addWithemail();
     }
     return false;
 }
コード例 #14
0
ファイル: callback.php プロジェクト: venya/prestashop
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     try {
         if ($_POST['order_status'] == OplataCls::ORDER_DECLINED) {
             exit('Order declined');
         }
         $oplata = new Oplata();
         $settings = array('merchant_id' => $oplata->getOption('merchant'), 'secret_key' => $oplata->getOption('secret_key'));
         $isPaymentValid = OplataCls::isPaymentValid($settings, $_POST);
         if ($isPaymentValid !== true) {
             exit($isPaymentValid);
         }
         list($orderId, ) = explode(OplataCls::ORDER_SEPARATOR, $_POST['order_id']);
         $history = new OrderHistory();
         $history->id_order = $orderId;
         $history->changeIdOrderState((int) Configuration::get('PS_OS_PAYMENT'), $orderId);
         $history->addWithemail(true, array('order_name' => $orderId));
         exit('OK');
     } catch (Exception $e) {
         exit(get_class($e) . ': ' . $e->getMessage());
     }
 }
コード例 #15
0
ファイル: result.php プロジェクト: cloudipsp/prestashop
 public function postProcess()
 {
     list($orderId, ) = explode(FondyCls::ORDER_SEPARATOR, $_POST['order_id']);
     $this->_order = new Order(intval($orderId));
     $this->_customer = new Customer($this->_order->id_customer);
     if ($_POST['order_status'] == FondyCls::ORDER_DECLINED) {
         $this->showError(Tools::displayError('Order declined'));
     }
     $settings = array('merchant_id' => $this->getOption('merchant'), 'secret_key' => $this->getOption('secret_key'));
     $isPaymentValid = FondyCls::isPaymentValid($settings, $_POST);
     if ($isPaymentValid !== true) {
         $this->showError(Tools::displayError($isPaymentValid));
     }
     if (!Validate::isLoadedObject($this->_customer)) {
         Tools::redirectLink(__PS_BASE_URI__ . 'order.php?step=1');
     }
     $history = new OrderHistory();
     $history->id_order = $orderId;
     $id_order_state = _PS_OS_PAYMENT_;
     $history->changeIdOrderState(intval($id_order_state), intval($orderId));
     $history->addWithemail(true, "");
     // redirect to success
     Tools::redirectLink(__PS_BASE_URI__ . 'modules/fondy/result-success.php');
 }
コード例 #16
0
ファイル: Order.php プロジェクト: baroni93/PrestaShop-1.4
    /** Set current order state
     * @param int $id_order_state
     * @param int $id_employee (/!\ not optional except for Webservice.
     */
    public function setCurrentState($id_order_state, $id_employee = 0)
    {
        if (empty($id_order_state)) {
            return false;
        }
        $history = new OrderHistory();
        $history->id_order = (int) $this->id;
        $history->id_employee = (int) $id_employee;
        $history->changeIdOrderState((int) $id_order_state, (int) $this->id);
        $res = Db::getInstance()->getRow('
		SELECT `invoice_number`, `invoice_date`, `delivery_number`, `delivery_date`
		FROM `' . _DB_PREFIX_ . 'orders`
		WHERE `id_order` = ' . (int) $this->id);
        $this->invoice_date = $res['invoice_date'];
        $this->invoice_number = $res['invoice_number'];
        $this->delivery_date = $res['delivery_date'];
        $this->delivery_number = $res['delivery_number'];
        $history->addWithemail();
    }
コード例 #17
0
 public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
 {
     if (self::DEBUG_MODE) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true);
     }
     if (!isset($this->context)) {
         $this->context = Context::getContext();
     }
     $this->context->cart = new Cart($id_cart);
     $this->context->customer = new Customer($this->context->cart->id_customer);
     // The tax cart is loaded before the customer so re-cache the tax calculation method
     $this->context->cart->setTaxCalculationMethod();
     $this->context->language = new Language($this->context->cart->id_lang);
     $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
     ShopUrl::resetMainDomainCache();
     $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
     $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
         $context_country = $this->context->country;
     }
     $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id);
     if (!Validate::isLoadedObject($order_status)) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true);
         throw new PrestaShopException('Can\'t load Order status');
     }
     if (!$this->active) {
         PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true);
         die(Tools::displayError());
     }
     // Does order already exists ?
     if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) {
         if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true);
             die(Tools::displayError());
         }
         // For each package, generate an order
         $delivery_option_list = $this->context->cart->getDeliveryOptionList();
         $package_list = $this->context->cart->getPackageList();
         $cart_delivery_option = $this->context->cart->getDeliveryOption();
         // If some delivery options are not defined, or not valid, use the first valid option
         foreach ($delivery_option_list as $id_address => $package) {
             if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) {
                 foreach ($package as $key => $val) {
                     $cart_delivery_option[$id_address] = $key;
                     break;
                 }
             }
         }
         $order_list = array();
         $order_detail_list = array();
         do {
             $reference = Order::generateReference();
         } while (Order::getByReference($reference)->count());
         $this->currentOrderReference = $reference;
         $order_creation_failed = false;
         $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2);
         foreach ($cart_delivery_option as $id_address => $key_carriers) {
             foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) {
                 foreach ($data['package_list'] as $id_package) {
                     // Rewrite the id_warehouse
                     $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier);
                     $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier;
                 }
             }
         }
         // Make sure CartRule caches are empty
         CartRule::cleanCache();
         $cart_rules = $this->context->cart->getCartRules();
         foreach ($cart_rules as $cart_rule) {
             if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) {
                 if ($error = $rule->checkValidity($this->context, true, true)) {
                     $this->context->cart->removeCartRule((int) $rule->id);
                     if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) {
                         if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
                             Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                         }
                         Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code));
                     } else {
                         $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code;
                         $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name));
                         PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id);
                     }
                 }
             }
         }
         foreach ($package_list as $id_address => $packageByAddress) {
             foreach ($packageByAddress as $id_package => $package) {
                 $order = new Order();
                 $order->product_list = $package['product_list'];
                 if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
                     $address = new Address($id_address);
                     $this->context->country = new Country($address->id_country, $this->context->cart->id_lang);
                     if (!$this->context->country->active) {
                         throw new PrestaShopException('The delivery address country is not active.');
                     }
                 }
                 $carrier = null;
                 if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) {
                     $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang);
                     $order->id_carrier = (int) $carrier->id;
                     $id_carrier = (int) $carrier->id;
                 } else {
                     $order->id_carrier = 0;
                     $id_carrier = 0;
                 }
                 $order->id_customer = (int) $this->context->cart->id_customer;
                 $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
                 $order->id_address_delivery = (int) $id_address;
                 $order->id_currency = $this->context->currency->id;
                 $order->id_lang = (int) $this->context->cart->id_lang;
                 $order->id_cart = (int) $this->context->cart->id;
                 $order->reference = $reference;
                 $order->id_shop = (int) $this->context->shop->id;
                 $order->id_shop_group = (int) $this->context->shop->id_shop_group;
                 $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key);
                 $order->payment = $payment_method;
                 if (isset($this->name)) {
                     $order->module = $this->name;
                 }
                 $order->recyclable = $this->context->cart->recyclable;
                 $order->gift = (int) $this->context->cart->gift;
                 $order->gift_message = $this->context->cart->gift_message;
                 $order->mobile_theme = $this->context->cart->mobile_theme;
                 $order->conversion_rate = $this->context->currency->conversion_rate;
                 $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid;
                 $order->total_paid_real = 0;
                 $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier);
                 $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier));
                 $order->total_discounts = $order->total_discounts_tax_incl;
                 $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list);
                 $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list);
                 $order->total_shipping = $order->total_shipping_tax_incl;
                 if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
                     $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
                 }
                 $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier));
                 $order->total_wrapping = $order->total_wrapping_tax_incl;
                 $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_);
                 $order->total_paid = $order->total_paid_tax_incl;
                 $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
                 $order->invoice_date = '0000-00-00 00:00:00';
                 $order->delivery_date = '0000-00-00 00:00:00';
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Creating order
                 $result = $order->add();
                 if (!$result) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true);
                     throw new PrestaShopException('Can\'t save Order');
                 }
                 // Amount paid by customer is not the right one -> Status = payment error
                 // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
                 // if ($order->total_paid != $order->total_paid_real)
                 // We use number_format in order to compare two string
                 if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) {
                     $id_order_state = Configuration::get('PS_OS_ERROR');
                 }
                 $order_list[] = $order;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Insert new Order detail list using cart for the current order
                 $order_detail = new OrderDetail(null, null, $this->context);
                 $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']);
                 $order_detail_list[] = $order_detail;
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Adding an entry in order_carrier table
                 if (!is_null($carrier)) {
                     $order_carrier = new OrderCarrier();
                     $order_carrier->id_order = (int) $order->id;
                     $order_carrier->id_carrier = (int) $id_carrier;
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl;
                     $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl;
                     $order_carrier->add();
                 }
             }
         }
         // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') {
             $this->context->country = $context_country;
         }
         if (!$this->context->country->active) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true);
             throw new PrestaShopException('The order address country is not active.');
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true);
         }
         // Register Payment only if the order status validate the order
         if ($order_status->logable) {
             // $order is the last order loop in the foreach
             // The method addOrderPayment of the class Order make a create a paymentOrder
             //     linked to the order reference and not to the order id
             if (isset($extra_vars['transaction_id'])) {
                 $transaction_id = $extra_vars['transaction_id'];
             } else {
                 $transaction_id = null;
             }
             if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) {
                 PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true);
                 throw new PrestaShopException('Can\'t save Order Payment');
             }
         }
         // Next !
         $only_one_gift = false;
         $cart_rule_used = array();
         $products = $this->context->cart->getProducts();
         // Make sure CarRule caches are empty
         CartRule::cleanCache();
         foreach ($order_detail_list as $key => $order_detail) {
             $order = $order_list[$key];
             if (!$order_creation_failed && isset($order->id)) {
                 if (!$secure_key) {
                     $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation');
                 }
                 // Optional message to attach to this order
                 if (isset($message) & !empty($message)) {
                     $msg = new Message();
                     $message = strip_tags($message, '<br>');
                     if (Validate::isCleanHtml($message)) {
                         if (self::DEBUG_MODE) {
                             PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                         }
                         $msg->message = $message;
                         $msg->id_order = (int) $order->id;
                         $msg->private = 1;
                         $msg->add();
                     }
                 }
                 // Insert new Order detail list using cart for the current order
                 //$orderDetail = new OrderDetail(null, null, $this->context);
                 //$orderDetail->createList($order, $this->context->cart, $id_order_state);
                 // Construct order detail table for the email
                 $products_list = '';
                 $virtual_product = true;
                 $ppropertiessmartprice_hook1 = null;
                 $product_var_tpl_list = array();
                 foreach ($order->product_list as $product) {
                     PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency));
                     $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                     $ppropertiessmartprice_hook2 = '';
                     $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array());
                     $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart);
                     $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas);
                     if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) {
                         $product_var_tpl['customization'] = array();
                         foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) {
                             if ($product['id_cart_product'] == $customization['id_cart_product']) {
                                 $customization_text = '';
                                 if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) {
                                     foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) {
                                         $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />';
                                     }
                                 }
                                 if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) {
                                     $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />';
                                 }
                                 $customization_quantity = (int) $product['customization_quantity'];
                                 $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total')));
                             }
                         }
                     }
                     $product_var_tpl_list[] = $product_var_tpl;
                     // Check if is not a virutal product for the displaying of shipping
                     if (!$product['is_virtual']) {
                         $virtual_product &= false;
                     }
                 }
                 // end foreach ($products)
                 PP::smartyPPAssign();
                 $product_list_txt = '';
                 $product_list_html = '';
                 if (count($product_var_tpl_list) > 0) {
                     $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
                     $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
                 }
                 $cart_rules_list = array();
                 $total_reduction_value_ti = 0;
                 $total_reduction_value_tex = 0;
                 foreach ($cart_rules as $cart_rule) {
                     $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list);
                     $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package));
                     // If the reduction is not applicable to this order, then continue with the next one
                     if (!$values['tax_excl']) {
                         continue;
                     }
                     // IF
                     //     This is not multi-shipping
                     //     The value of the voucher is greater than the total of the order
                     //     Partial use is allowed
                     //     This is an "amount" reduction, not a reduction in % or a gift
                     // THEN
                     //     The voucher is cloned with a new value corresponding to the remainder
                     if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) {
                         // Create a new voucher from the original
                         $voucher = new CartRule($cart_rule['obj']->id);
                         // We need to instantiate the CartRule without lang parameter to allow saving it
                         unset($voucher->id);
                         // Set a new voucher code
                         $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2';
                         if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) {
                             $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code);
                         }
                         // Set the new voucher value
                         if ($voucher->reduction_tax) {
                             $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_incl;
                             }
                         } else {
                             $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products;
                             // Add total shipping amout only if reduction amount > total shipping
                             if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) {
                                 $voucher->reduction_amount -= $order->total_shipping_tax_excl;
                             }
                         }
                         if ($voucher->reduction_amount <= 0) {
                             continue;
                         }
                         $voucher->id_customer = $order->id_customer;
                         $voucher->quantity = 1;
                         $voucher->quantity_per_user = 1;
                         $voucher->free_shipping = 0;
                         if ($voucher->add()) {
                             // If the voucher has conditions, they are now copied to the new voucher
                             CartRule::copyConditions($cart_rule['obj']->id, $voucher->id);
                             $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference());
                             Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                         }
                         $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti;
                         $values['tax_excl'] = $order->total_products - $total_reduction_value_tex;
                     }
                     $total_reduction_value_ti += $values['tax_incl'];
                     $total_reduction_value_tex += $values['tax_excl'];
                     $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
                     if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) {
                         $cart_rule_used[] = $cart_rule['obj']->id;
                         // Create a new instance of Cart Rule without id_lang, in order to update its quantity
                         $cart_rule_to_update = new CartRule($cart_rule['obj']->id);
                         $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1);
                         $cart_rule_to_update->update();
                     }
                     $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false));
                 }
                 $cart_rules_list_txt = '';
                 $cart_rules_list_html = '';
                 if (count($cart_rules_list) > 0) {
                     $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
                     $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
                 }
                 // Specify order id for message
                 $old_message = Message::getMessageByCartId((int) $this->context->cart->id);
                 if ($old_message) {
                     $update_message = new Message((int) $old_message['id_message']);
                     $update_message->id_order = (int) $order->id;
                     $update_message->update();
                     // Add this message in the 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 = $this->context->customer->email;
                     $customer_thread->status = 'open';
                     $customer_thread->token = Tools::passwdGen(12);
                     $customer_thread->add();
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = 0;
                     $customer_message->message = $update_message->message;
                     $customer_message->private = 0;
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving message');
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Hook validate order
                 Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status));
                 foreach ($this->context->cart->getProducts() as $product) {
                     if ($order_status->logable) {
                         ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                     }
                 }
                 if (self::DEBUG_MODE) {
                     PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true);
                 }
                 // Set the order status
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState((int) $id_order_state, $order, true);
                 $new_history->addWithemail(true, $extra_vars);
                 // Switch to back order if needed
                 if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) {
                     $history = new OrderHistory();
                     $history->id_order = (int) $order->id;
                     $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true);
                     $history->addWithemail();
                 }
                 unset($order_detail);
                 // Order is reloaded because the status just changed
                 $order = new Order($order->id);
                 // Send an e-mail to customer (one order = one email)
                 if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) {
                     $invoice = new Address($order->id_address_invoice);
                     $delivery = new Address($order->id_address_delivery);
                     $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false;
                     $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false;
                     $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false));
                     if (is_array($extra_vars)) {
                         $data = array_merge($data, $extra_vars);
                     }
                     // Join PDF invoice
                     if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) {
                         $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty);
                         $file_attachement = array();
                         $file_attachement['content'] = $pdf->render(false);
                         $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf';
                         $file_attachement['mime'] = 'application/pdf';
                     } else {
                         $file_attachement = null;
                     }
                     if (self::DEBUG_MODE) {
                         PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true);
                     }
                     if (Validate::isEmail($this->context->customer->email)) {
                         Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                     }
                 }
                 // updates stock in shops
                 if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                     $product_list = $order->getProducts();
                     foreach ($product_list as $product) {
                         // if the available quantities depends on the physical stock
                         if (StockAvailable::dependsOnStock($product['product_id'])) {
                             // synchronizes
                             StockAvailable::synchronize($product['product_id'], $order->id_shop);
                         }
                     }
                 }
             } else {
                 $error = Tools::displayError('Order creation failed');
                 PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart);
                 die($error);
             }
         }
         // End foreach $order_detail_list
         // Update Order Details Tax in case cart rules have free shipping
         foreach ($order->getOrderDetailList() as $detail) {
             $order_detail = new OrderDetail($detail['id_order_detail']);
             $order_detail->updateTaxAmount($order);
         }
         // Use the last order as currentOrder
         if (isset($order) && $order->id) {
             $this->currentOrder = (int) $order->id;
         }
         if (self::DEBUG_MODE) {
             PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true);
         }
         return true;
     } else {
         $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
         PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id);
         die($error);
     }
 }
コード例 #18
0
 public function validation()
 {
     if (!$this->active) {
         return;
     }
     if (!array_key_exists('xml', $_POST)) {
         return;
     }
     if (_PS_MAGIC_QUOTES_GPC_) {
         $_POST['xml'] = stripslashes($_POST['xml']);
     }
     require_once dirname(__FILE__) . '/mapi/mapi_package.php';
     if (HIPAY_MAPI_COMM_XML::analyzeNotificationXML($_POST['xml'], $operation, $status, $date, $time, $transid, $amount, $currency, $id_cart, $data) === false) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Analysis error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
         return false;
     }
     if (_PS_VERSION_ >= 1.5) {
         Context::getContext()->cart = new Cart((int) $id_cart);
     }
     $cart = new Cart((int) $id_cart);
     if (Tools::encrypt($cart->id . $cart->secure_key . Configuration::get('HIPAY_SALT')) != Tools::getValue('token')) {
         file_put_contents('logs' . Configuration::get('HIPAY_UNIQID') . '.txt', '[' . date('Y-m-d H:i:s') . '] Token error: ' . htmlentities($_POST['xml']) . "\n", FILE_APPEND);
     } else {
         if (trim($operation) == 'capture' and trim(strtolower($status)) == 'ok') {
             /* Paiement capturé sur Hipay = Paiement accepté sur Prestashop */
             $orderMessage = $operation . ': ' . $status . '\\ndate: ' . $date . ' ' . $time . '\\ntransaction: ' . $transid . '\\namount: ' . (double) $amount . ' ' . $currency . '\\nid_cart: ' . (int) $id_cart;
             $this->validateOrder((int) $id_cart, Configuration::get('PS_OS_PAYMENT'), (double) $amount, $this->displayName, $orderMessage, array(), NULL, false, $cart->secure_key);
         } elseif (trim($operation) == 'refund' and trim(strtolower($status)) == 'ok') {
             /* Paiement remboursé sur Hipay */
             if (!($id_order = Order::getOrderByCartId((int) $id_cart))) {
                 die(Tools::displayError());
             }
             $order = new Order((int) $id_order);
             if (!$order->valid or $order->getCurrentState() === Configuration::get('PS_OS_REFUND')) {
                 die(Tools::displayError());
             }
             $orderHistory = new OrderHistory();
             $orderHistory->id_order = (int) $order->id;
             $orderHistory->changeIdOrderState((int) Configuration::get('PS_OS_REFUND'), (int) $id_order);
             $orderHistory->addWithemail();
         }
     }
 }
コード例 #19
0
ファイル: adminorderapproval.php プロジェクト: Eximagen/3m
 private function approveOrderForValidLink($link)
 {
     $orderID = Order::getOrderIDbyActivationLink($link);
     if (!orderID) {
         return false;
     } else {
         $order = new Order($orderID);
         if (Validate::isLoadedObject($order)) {
             if ($order->getCurrentState() == 13) {
                 $new_history = new OrderHistory();
                 $new_history->id_order = (int) $order->id;
                 $new_history->changeIdOrderState(15, $order);
                 // 15: Design Approval
                 $new_history->addWithemail(true);
             }
             return true;
         } else {
             return false;
         }
     }
 }
コード例 #20
0
 /**
  * Creating of the PrestaShop order
  * @param $neteven_order
  * @param $neteven_orders
  * @return int
  */
 private function createOrder($neteven_order, $neteven_orders)
 {
     if (constant('_PS_VERSION_') >= 1.5) {
         include_once dirname(__FILE__) . '/OrderInvoiceOverride.php';
     }
     // Treatment of customer
     $id_customer = $this->addCustomerInBDD($neteven_order);
     if ($this->time_analyse) {
         $this->current_time_2 = time();
         Toolbox::displayDebugMessage(self::getL('Customer') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's');
     }
     // Treatment of addresses of the customer
     $id_address_billing = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->BillingAddress, 'facturation', $id_customer);
     $id_address_shipping = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->ShippingAddress, 'livraison', $id_customer);
     if ($this->time_analyse) {
         $this->current_time_0 = time();
         Toolbox::displayDebugMessage(self::getL('Address') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's');
     }
     // Get secure key of customer
     $secure_key_default = md5(uniqid(rand(), true));
     if ($secure_key = Db::getInstance()->getValue('SELECT `secure_key` FROM `' . _DB_PREFIX_ . 'customer` WHERE `id_customer` = ' . (int) $id_customer)) {
         $secure_key_default = $secure_key;
     } else {
         Toolbox::addLogLine(self::getL('Problem with a secure key recovery for the customer / NetEven Order Id') . ' ' . $neteven_order->OrderID);
     }
     // Treatment of order informations
     $total_wt = 0;
     $total_product = 0;
     $total_product_wt = 0;
     foreach ($neteven_orders as $neteven_order_temp) {
         if ($neteven_order_temp->OrderID == $neteven_order->OrderID) {
             if (in_array($neteven_order_temp->Status, $this->getValue('t_list_order_status'))) {
                 continue;
             }
             $total_product += floatval($neteven_order_temp->Price->_) - floatval($neteven_order_temp->VAT->_);
             $total_product_wt += floatval($neteven_order_temp->Price->_);
         }
     }
     $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_;
     $date_now = date('Y-m-d H:i:s');
     if ($this->time_analyse) {
         $this->current_time_2 = time();
         Toolbox::displayDebugMessage(self::getL('Order total') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's');
     }
     // Creating and add order in PrestaShop
     if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = 0'))) {
         // Creating cart
         $cart = new Cart();
         $cart->id_address_delivery = (int) $id_address_shipping;
         $cart->id_address_invoice = (int) $id_address_billing;
         $cart->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
         $cart->id_customer = (int) $id_customer;
         $cart->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
         $cart->id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
         $cart->recyclable = 1;
         $cart->gift = 0;
         $cart->gift_message = '';
         $cart->date_add = $date_now;
         $cart->secure_key = $secure_key_default;
         $cart->date_upd = $date_now;
         if (!$cart->add()) {
             Toolbox::addLogLine(self::getL('Failed for cart creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID);
         }
         if ($this->time_analyse) {
             $this->current_time_0 = time();
             Toolbox::displayDebugMessage(self::getL('Cart') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's');
         }
         // Creating order
         $id_order_temp = 0;
         $order = new Order();
         $order->id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
         $order->id_lang = Configuration::get('PS_LANG_DEFAULT');
         $order->id_customer = $id_customer;
         $order->id_cart = $cart->id;
         $order->id_currency = Configuration::get('PS_CURRENCY_DEFAULT');
         $order->id_address_delivery = $id_address_shipping;
         $order->id_address_invoice = $id_address_billing;
         $order->secure_key = $secure_key_default;
         $order->payment = $neteven_order->PaymentMethod;
         $order->conversion_rate = 1;
         $order->module = 'nqgatewayneteven';
         $order->recyclable = 0;
         $order->gift = 0;
         $order->gift_message = '';
         $order->shipping_number = '';
         //generate reference order
         $nbr_order_neteven = Configuration::get('NUMBER_ORDER_NETEVEN');
         if (false === $nbr_order_neteven) {
             $nbr_order_neteven = 1;
         } else {
             $nbr_order_neteven = (int) str_replace('N', '', $nbr_order_neteven);
             $nbr_order_neteven++;
         }
         $next_ref_gen_order_neteven = 'N' . sprintf('%07s', $nbr_order_neteven);
         Configuration::updateValue('NUMBER_ORDER_NETEVEN', $next_ref_gen_order_neteven);
         $order->reference = $next_ref_gen_order_neteven;
         //-----
         $carrier = new Carrier((int) $order->id_carrier);
         $carrier_tax_rate = false;
         if (method_exists($carrier, 'getTaxesRate')) {
             $carrier_tax_rate = $carrier->getTaxesRate(new Address($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
         }
         $total_shipping_tax_excl = $carrier_tax_rate ? $neteven_order->OrderShippingCost->_ / ($carrier_tax_rate / 100) : $neteven_order->OrderShippingCost->_;
         $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_;
         $total = $total_product + $total_shipping_tax_excl;
         $order->total_discounts_tax_excl = 0;
         $order->total_discounts_tax_incl = 0;
         $order->total_discounts = 0;
         $order->total_wrapping_tax_excl = 0;
         $order->total_wrapping_tax_incl = 0;
         $order->total_wrapping = 0;
         $order->total_products = (double) number_format($total_product, 2, '.', '');
         $order->total_products_wt = (double) number_format($total_product_wt, 2, '.', '');
         $order->total_shipping_tax_excl = (double) number_format($total_shipping_tax_excl, 2, '.', '');
         $order->total_shipping_tax_incl = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', '');
         $order->total_shipping = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', '');
         $order->total_paid_tax_excl = (double) number_format($total, 2, '.', '');
         $order->total_paid_tax_incl = (double) number_format($total_wt, 2, '.', '');
         $order->total_paid_real = (double) number_format($total_wt, 2, '.', '');
         $order->total_paid = (double) number_format($total_wt, 2, '.', '');
         $order->carrier_tax_rate = 0;
         $order->total_wrapping = 0;
         $order->invoice_number = 0;
         $order->delivery_number = 0;
         $order->invoice_date = $date_now;
         $order->delivery_date = $date_now;
         $order->valid = 1;
         $order->date_add = $date_now;
         $order->date_upd = $date_now;
         if (Configuration::get('PS_SHOP_ENABLE')) {
             $order->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT');
         }
         if (!$order->add()) {
             Toolbox::addLogLine(self::getL('Failed for order creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID);
         } else {
             $id_order_temp = $order->id;
             Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_carrier` (`id_order`, `id_carrier`, `id_order_invoice`, `weight`, `shipping_cost_tax_excl`, `shipping_cost_tax_incl`, `tracking_number`, `date_add`) VALUES (' . (int) $id_order_temp . ', ' . (int) Configuration::get('PS_CARRIER_DEFAULT') . ', 0, 0, 0, 0, 0,"' . pSQL(date('Y-m-d H:i:s')) . '")');
             Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "Place de marché ' . $neteven_order->MarketPlaceName . '", "' . pSQL(date('Y-m-d H:i:s')) . '")');
             Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "ID order NetEven ' . $neteven_order->MarketPlaceOrderId . '", "' . pSQL(date('Y-m-d H:i:s')) . '")');
             if ($this->time_analyse) {
                 $this->current_time_2 = time();
                 Toolbox::displayDebugMessage(self::getL('Order') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's');
             }
             Toolbox::addLogLine(self::getL('Add order Id') . ' ' . (int) $id_order_temp . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID);
             // Update order state in order
             $order_state = array_merge($this->getValue('order_state_before'), array($this->getValue('id_order_state_neteven')), $this->getValue('order_state_after'));
             if (is_array($order_state) && count($order_state) > 0) {
                 foreach ($order_state as $id_order_state) {
                     if (class_exists('OrderInvoiceOverride' && method_exists('OrderInvoiceOverride', 'clearCacheTotalPaid'))) {
                         OrderInvoiceOverride::clearCacheTotalPaid();
                     }
                     $new_history = new OrderHistory();
                     $new_history->id_order = (int) $id_order_temp;
                     $new_history->changeIdOrderState((int) $id_order_state, $id_order_temp);
                     $new_history->addWithemail(true, array());
                     Toolbox::addLogLine(self::getL('Save order state Id') . ' ' . (int) $id_order_state . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID);
                 }
             }
             if ($this->time_analyse) {
                 $this->current_time_0 = time();
                 Toolbox::displayDebugMessage(self::getL('History') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's');
             }
             // Insert order in orders_gateway table
             if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order_temp . ', 0, "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) {
                 Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID);
             } else {
                 Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID);
             }
         }
     } else {
         $id_order_temp = $res['id_order'];
         Toolbox::addLogLine(self::getL('Get already exported order Id') . ' ' . $res['id_order'] . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID);
     }
     return $id_order_temp;
 }
コード例 #21
0
function updateTracking($static = false, $idShop = 0, $idGroupShop = 0)
{
    $api = new ShipwireTracking();
    $api->retrieveFull();
    $d = $api->sendData();
    if ($d['Status']) {
        if ($static) {
            return false;
        } else {
            die('KO');
        }
    }
    if ($d['TotalOrders'] > 0) {
        foreach ($d['Order'] as $order) {
            $o = array();
            if (isset($order['@attributes'])) {
                $o = $order['@attributes'];
            }
            if (!isset($o['id'])) {
                Logger::addLog('Shipwire: Order ID not defined. >>>>' . print_r($d, true) . '<<<<', 4);
                continue;
            }
            $orderExists = Db::getInstance()->ExecuteS('SELECT `id_order`
				FROM `' . _DB_PREFIX_ . 'shipwire_order`
				WHERE `id_order` = ' . (int) $o['id'] . ' LIMIT 1');
            if (isset($orderExists[0]['id_order']) && !empty($orderExists[0]['id_order'])) {
                Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'shipwire_order` SET ' . (isset($order['TrackingNumber']) ? '`tracking_number` = \'' . pSQL($order['TrackingNumber']) . '\',' : '') . (isset($o['shipped']) ? '`shipped` = \'' . pSQL($o['shipped']) . '\'' : '') . (isset($o['shipper']) ? ',`shipper` = \'' . pSQL($o['shipper']) . '\'' : '') . (isset($o['shipDate']) ? ',`shipDate` = \'' . pSQL($o['shipDate']) . '\'' : '') . (isset($o['expectedDeliveryDate']) ? ',`expectedDeliveryDate` = \'' . pSQL($o['expectedDeliveryDate']) . '\'' : '') . (isset($o['href']) ? ',`href` = \'' . pSQL($o['href']) . '\'' : '') . (isset($o['shipperFullName']) ? ',`shipperFullName` = \'' . pSQL($o['shipperFullName']) . '\'' : '') . ' WHERE `id_order` = ' . (int) $o['id']);
            } else {
                Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'shipwire_order`
				(`id_order`, `id_shop`, `id_group_shop`, `tracking_number`, `shipped`, `shipper`, `shipDate`, `expectedDeliveryDate`, `href`, `shipperFullName`)
				VALUES (
				\'' . pSQL($o['id']) . '\'' . ',' . (int) $idShop . ',' . (int) $idGroupShop . (isset($order['TrackingNumber']) ? ',\'' . pSQL($order['TrackingNumber']) . '\'' : ',\'\'') . (isset($o['shipped']) ? ',\'' . pSQL($o['shipped']) . '\'' : ',\'\'') . (isset($o['shipper']) ? ',\'' . pSQL($o['shipper']) . '\'' : ',\'\'') . (isset($o['shipDate']) ? ',\'' . pSQL($o['shipDate']) . '\'' : ',\'\'') . (isset($o['expectedDeliveryDate']) ? ',\'' . pSQL($o['expectedDeliveryDate']) . '\'' : ',\'\'') . (isset($o['href']) ? ',\'' . pSQL($o['href']) . '\'' : ',\'\'') . (isset($o['shipperFullName']) ? ',\'' . pSQL($o['shipperFullName']) . '\'' : ',\'\'') . ')');
            }
            $result = Db::getInstance()->getValue('SELECT `transaction_ref`
				FROM `' . _DB_PREFIX_ . 'shipwire_order`
				WHERE `id_order` = ' . (int) $o['id']);
            if (empty($result)) {
                $module = new Shipwire();
                $module->updateOrderStatus((int) $o['id'], true);
            }
            if (isset($order['TrackingNumber'])) {
                Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'orders`
										SET `shipping_number` = \'' . pSQL($order['TrackingNumber']) . '\'
										WHERE `id_order` = ' . (int) $o['id']);
                if ($o['id']) {
                    $psOrder = new Order($o['id']);
                    if ($psOrder->id) {
                        $history = new OrderHistory();
                        $history->id_order = $o['id'];
                        if (isset($o['shipped']) && $o['shipped'] == 'YES') {
                            $history->changeIdOrderState(Configuration::get('SHIPWIRE_SENT_ID'), $o['id']);
                        }
                        $history->addWithemail();
                    }
                }
            }
        }
    }
    if (Configuration::get('PS_CIPHER_ALGORITHM')) {
        $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
    } else {
        $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
    }
    $shipWireInventoryUpdate = new ShipwireInventoryUpdate(Configuration::get('SHIPWIRE_API_USER'), $cipherTool->decrypt(Configuration::get('SHIPWIRE_API_PASSWD')));
    $shipWireInventoryUpdate->getInventory();
    if ($static) {
        return true;
    } else {
        die('OK');
    }
}
コード例 #22
0
ファイル: ipn.php プロジェクト: rtajmahal/PrestaShop-modules
$params = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
    $params .= '&' . $key . '=' . urlencode(stripslashes($value));
}
// Checking params by asking PayPal
include _PS_MODULE_DIR_ . 'paypal/api/paypal_lib.php';
$paypalAPI = new PaypalLib();
$result = $paypalAPI->makeSimpleCall($paypal->getAPIURL(), $paypal->getAPIScript(), $params);
if (!$result || Tools::strlen($result) < 8 || !($status = substr($result, -8)) || $status != 'VERIFIED') {
    die($paypal->l('Cannot verify PayPal order'));
}
// Getting order status
switch ($status) {
    case 'Completed':
        $id_order_state = Configuration::get('PS_OS_PAYMENT');
        break;
    case 'Pending':
        $id_order_state = Configuration::get('PS_OS_PAYPAL');
        break;
    default:
        $id_order_state = Configuration::get('PS_OS_ERROR');
}
if ($order->getCurrentState() == $id_order_state) {
    die($paypal->l('Same status'));
}
// Set order state in order history
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState((int) $id_order_state, (int) $order->id);
$history->addWithemail(true, $extraVars);
コード例 #23
0
                break;
            case 5:
            case 9:
                /* Payment OK */
                $ogone->validate((int) $_GET['orderID'], _PS_OS_PAYMENT_, (double) $_GET['amount'], $ogone->l('Payment authorized / OK') . $params, $_GET['secure_key']);
                break;
            case 6:
            case 7:
            case 8:
                // Payment canceled later
                if ($id_order = (int) Order::getOrderByCartId((int) $_GET['orderID'])) {
                    // Update the amount really paid
                    $order = new Order($id_order);
                    $order->total_paid_real = 0;
                    $order->update();
                    // Send a new message and change the state
                    $history = new OrderHistory();
                    $history->id_order = $id_order;
                    $history->changeIdOrderState(_PS_OS_ERROR_, $id_order);
                    $history->addWithemail(true, array());
                }
                break;
            default:
                $ogone->validate((int) $_GET['orderID'], _PS_OS_ERROR_, (double) $_GET['amount'], $ogone->l('Unknown status:') . ' ' . $_GET['STATUS'] . $params, $_GET['secure_key']);
        }
        exit;
    } else {
        $message = $ogone->l('Invalid SHA-1 signature') . '<br />' . $ogone->l('SHA-1 given:') . ' ' . $_GET['SHASIGN'] . '<br />' . $ogone->l('SHA-1 calculated:') . ' ' . $sha1 . '<br />' . $ogone->l('Plain key:') . ' ' . $shasign;
        $ogone->validate((int) $_GET['orderID'], _PS_OS_ERROR_, 0, $message . '<br />' . $params, $_GET['secure_key']);
    }
}
コード例 #24
0
 private function _dealerAction($action, $param, $orderId)
 {
     $order = new Order($orderId);
     $webService = new BuysterWebService();
     $reference = BuysterOperation::getReferenceId($order->id_cart);
     $price = $order->total_paid;
     if ($action == "DUPLICATE") {
         $parametre = 'fromTransactionReference=' . $reference . ';';
         $result = $webService->operation($action, $param, $price, $parametre);
     } else {
         if ($action == "VALIDATE") {
             $parametre = 'operationCaptureNewDelay=' . $param . ';';
             $result = $webService->operation($action, $reference, $price, $parametre);
         } else {
             $parametre = NULL;
             $result = $webService->operation($action, $reference, $price, $parametre);
         }
     }
     if ($result['responseCode'] == "00") {
         $history = new OrderHistory();
         $history->id_order = (int) $orderId;
         if ($action == "DUPLICATE") {
             $operation = BuysterOperation::getOperationId($order->id_cart);
             if ($operation == 'paymentValidation') {
                 $history->changeIdOrderState((int) Configuration::get('BUYSTER_PAYMENT_STATE_VALIDATION'), (int) $orderId);
             } else {
                 $history->changeIdOrderState((int) Configuration::get('BUYSTER_PAYMENT_STATE'), (int) $orderId);
             }
             BuysterOperation::setReferenceReference($param, $reference);
             $reference = $param;
         }
         if ($action == "VALIDATE") {
             $history->changeIdOrderState((int) Configuration::get('PS_OS_PAYMENT'), (int) $orderId);
         }
         if ($action == "REFUND") {
             $history->changeIdOrderState((int) Configuration::get('PS_OS_REFUND'), (int) $orderId);
         }
         if ($action == "CANCEL") {
             $history->changeIdOrderState((int) Configuration::get('PS_OS_CANCELED'), (int) $orderId);
         }
         $history->addWithemail();
     }
     $return = '';
     if ($result['responseCode'] == "99") {
         $return = '<span style="color:red">Probl&egrave;me technique au niveau du serveur Buyster</span><br/>';
     }
     if ($result['responseCode'] == "00") {
         $return .= '<span style="color:green">L\'&eacute;tat de votre commande a &eacute;t&eacute; modifi&eacute;.</span><br/>';
     } else {
         if ($result['responseCode'] == "24") {
             $return = '<span style="color:red">Op&eacuteration impossible. L\'op&eacuteration que vous souhaitez r&eacute;aliser n\'est pas compatible avec l\'&eacute;tat de la transaction.</span><br/>';
         } else {
             $return .= $result['responseDescription'] . '<br/>';
         }
     }
     return $return;
 }
コード例 #25
0
    public function update_cart_by_junglee_xml($order_id, $data)
    {
        $xml = simplexml_load_string($data);
        $prefix = _DB_PREFIX_;
        $tablename = $prefix . 'orders';
        $total_amount = 0;
        $total_principal = 0;
        $shipping_amount = 0;
        $total_promo = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $total_principal += $principal;
            $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo);
            $shipping_amount += $Shipping;
            $total_promo += $principal_promo + $shipping_promo + $other_promo;
        }
        $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel;
        $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "junglee" where `prestashop_order_id` = "' . $order_id . '" ';
        Db::getInstance()->Execute($sql);
        $email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
        $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" ';
        $results = Db::getInstance()->ExecuteS($sql);
        if (empty($results)) {
            $name = (string) $xml->ProcessedOrder->BuyerInfo->BuyerName;
            $name_arr = explode(' ', $name);
            if (count($name_arr) > 1) {
                $firstname = '';
                for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                    $firstname = $firstname . ' ' . $name_arr[$i];
                }
                $lastname = $name_arr[count($name_arr) - 1];
            } else {
                $firstname = $name;
                $lastname = '.';
            }
            $password = Tools::passwdGen();
            $customer = new Customer();
            $customer->firstname = trim($firstname);
            $customer->lastname = $lastname;
            $customer->email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
            $customer->passwd = md5($password);
            $customer->active = 1;
            if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                $customer->is_guest = 1;
            } else {
                $customer->is_guest = 0;
            }
            $customer->add();
            $customer_id = $customer->id;
            if (Configuration::get('PS_CUSTOMER_CREATION_EMAIL') && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                Mail::Send($this->context->language->id, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $password), $customer->email, $customer->firstname . ' ' . $customer->lastname);
            }
        } else {
            $customer_id = $results[0]['id_customer'];
        }
        $id_country = Country::getByIso((string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
        if ($id_country == 0 || $id_country == '') {
            $id_country = 110;
        }
        $name = (string) $xml->ProcessedOrder->ShippingAddress->Name;
        $name_arr = explode(' ', $name);
        if (count($name_arr) > 1) {
            $firstname = '';
            for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                $firstname = $firstname . ' ' . $name_arr[$i];
            }
            $lastname = $name_arr[count($name_arr) - 1];
        } else {
            $firstname = $name;
            $lastname = '.';
        }
        $address = new Address();
        $address->id_country = $id_country;
        $address->id_state = 0;
        $address->id_customer = $customer_id;
        $address->alias = 'My Address';
        $address->firstname = trim($firstname);
        $address->lastname = $lastname;
        $address->address1 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne;
        $address->address2 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo;
        $address->postcode = (string) $xml->ProcessedOrder->ShippingAddress->PostalCode;
        $address->city = (string) $xml->ProcessedOrder->ShippingAddress->City . ' ' . (string) $xml->ProcessedOrder->ShippingAddress->State;
        $address->active = 1;
        $address->add();
        $address_id = $address->id;
        //$id_order_state = Configuration::get('PS_OS_PREPARATION');
        $id_order_state = 99;
        $reference = Order::generateReference();
        $order = new Order();
        $order->id = $order_id;
        $order->id_customer = (int) $customer_id;
        $order->id_address_invoice = (int) $address_id;
        $carrier = null;
        $sql = 'SELECT id_carrier from  `' . $prefix . 'carrier` where `active` = 1 and `deleted` = 0 limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $id_carrier = $result[0]['id_carrier'];
        $sql = 'SELECT id_currency from  `' . $prefix . 'currency` where `active` = 1 and `deleted` = 0 and `iso_code` = "INR" limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $currency_id = $result[0]['id_currency'];
        $sql = 'UPDATE `' . $tablename . '` set 
			  `id_customer` = ' . (int) $customer_id . ',
			  `id_carrier` = ' . $id_carrier . ',
			  `id_address_invoice` = ' . (int) $address_id . ',
			  `id_address_delivery` = ' . (int) $address_id . ',
			  `id_currency` = ' . $currency_id . ',
			  `reference` = "' . $reference . '",
			  `secure_key` = "' . md5(uniqid()) . '",
			  
			  `total_paid` = ' . $total_amount . ',
			  `total_paid_tax_incl` = ' . $total_amount . ',
			  `total_paid_tax_excl` = ' . $total_amount . ',
			  `total_paid_real` = 0,
			 
			  `total_shipping` = ' . $shipping_amount . ',
			  `total_shipping_tax_incl` = ' . $shipping_amount . ',
			  `total_shipping_tax_excl` = ' . $shipping_amount . ',
			  
			  `total_discounts` = ' . (double) $total_promo . ',
			  `total_discounts_tax_incl` = ' . (double) $total_promo . ',
			  `total_discounts_tax_excl` = ' . (double) $total_promo . ',
			  
			  `total_products` = ' . $total_principal . ',
			  `total_products_wt` = ' . $total_principal . ',
			  
			  `invoice_date` = "0000-00-00 00:00:00",
			  `delivery_date` = "0000-00-00 00:00:00"
			  where `id_order` = ' . $order_id . ' ';
        //`round_mode` = '.Configuration::get('PS_PRICE_ROUND_MODE').',
        /*`total_wrapping_tax_incl` = '.$WrappingAmount.',
          `total_wrapping_tax_excl` = '.$WrappingAmount.',
          `total_wrapping` = '.$WrappingAmount.',*/
        Db::getInstance()->Execute($sql);
        $acknowledge_arr = array();
        $i = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode;
            $acknowledge_arr['items'][$i]['product_id'] = $product_id;
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $sql = 'INSERT into `' . $prefix . 'order_detail` set
							`id_order` = ' . $order_id . ',
							`product_id` = ' . $product_id . ',
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Amount * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Amount . ',
							`original_product_price` = ' . $Amount . '
							';
            Db::getInstance()->Execute($sql);
            $sql = 'UPDATE `' . $prefix . 'stock_available` set
						`quantity` = `quantity` - ' . $Quantity . '
						where `id_product` = ' . $product_id . ' and
						`id_product_attribute` = 0
						';
            Db::getInstance()->Execute($sql);
            $date = date('Y-m-d');
            $sql = 'UPDATE `' . $prefix . 'product_sale` set
						`quantity` = `quantity` + ' . $Quantity . ',
						`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
						`date_upd` = ' . $date . '
						where `id_product` = ' . $product_id . '
						';
            Db::getInstance()->Execute($sql);
            $i++;
        }
        // Adding an entry in order_carrier table
        if (!is_null($carrier)) {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        } else {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        }
        // Set the order status
        $history = new OrderHistory();
        $history->id_order = (int) $order->id;
        $history->changeIdOrderState((int) $id_order_state, $order->id, true);
        $history->addWithemail(true, array());
        $acknowledge_arr['MerchantOrderID'] = (int) $order->id;
    }
コード例 #26
0
ファイル: Order.php プロジェクト: payfort/prestashop-payfort
 public function successOrder($response_params, $response_mode)
 {
     $status = $this->pfConfig->getSuccessOrderStatusId();
     if ($this->getStatusId() == $status) {
         return true;
     }
     if ($this->getOrderId()) {
         $history = new OrderHistory();
         $history->id_order = (int) $this->getOrderId();
         $history->changeIdOrderState($status, $this->getLoadedOrder());
         $history->addWithemail(true, array());
         $message = $this->module->l('Payfort Fort update: payment complete.', 'order');
         $this->addMessage($message);
     }
     return true;
 }
コード例 #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();
 }
コード例 #28
0
 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');
     }
 }
コード例 #29
0
 }
 if (_PS_VERSION_ >= '1.5') {
     $ppec->getContext()->cookie->id_cart = $cart->id;
     $ppec->validateOrder((int) $cart->id, $payment_type, (double) $cart->getOrderTotal(true, Cart::BOTH), 'PayPal', $message, $transaction, (int) $cart->id_currency, false, $customer->secure_key, $ppec->getContext()->shop);
 } else {
     $ppec->validateOrder((int) $cart->id, $payment_type, (double) $cart->getOrderTotal(true, Cart::BOTH), 'PayPal', $message, $transaction, (int) $cart->id_currency, false, $customer->secure_key);
 }
 if (!$ppec->currentOrder) {
     $ppec->logs[] = $this->l('Cannot create order');
 } else {
     $id_order = (int) $ppec->currentOrder;
     $order = new Order($id_order);
     $history = new OrderHistory();
     $history->id_order = (int) $id_order;
     $history->changeIdOrderState((int) $payment_type, $id_order);
     $history->addWithemail();
     $history->add();
 }
 unset(Context::getContext()->cookie->{PaypalExpressCheckout::$COOKIE_NAME});
 // Update for the Paypal shipping cost
 if ($order) {
     $values = array('key' => $customer->secure_key, 'id_module' => (int) $ppec->id, 'id_cart' => (int) $cart->id, 'id_order' => (int) $ppec->currentOrder);
     $query = http_build_query($values, '', '&');
     if (_PS_VERSION_ < '1.5') {
         Tools::redirectLink(__PS_BASE_URI__ . '/modules/paypal/express_checkout/submit.php?' . $query);
     } else {
         $controller = new FrontController();
         $controller->init();
         Tools::redirect(Context::getContext()->link->getModuleLink('paypal', 'submit', $values));
     }
 }
コード例 #30
0
 /**
  * process the pay result
  */
 public function processPayResult()
 {
     try {
         $payResult = PilipayPayResult::fromRequest();
         if (Configuration::get(self::PILIPAY_TESTMODE) == '1') {
             $secret = 'cbkmqa1s';
         } else {
             $secret = Configuration::get(self::PILIPAY_APP_SECRET);
         }
         if (!$payResult->verify($secret)) {
             $payResult->returnDealResultToPilibaba(400);
         }
         $order = new Order($payResult->orderNo);
         if (strcasecmp($order->payment, $this->name) !== 0) {
             $payResult->returnDealResultToPilibaba(401);
         }
         $orderState = $payResult->isSuccess() ? self::OS_PAID : self::OS_ERROR;
         self::log('info', "order {$order->id} is to be updated to {$orderState} via {$this->name}");
         $orderHistory = new OrderHistory();
         $orderHistory->id_order = $order->id;
         $orderHistory->changeIdOrderState(Configuration::get($orderState), $order);
         $orderHistory->addWithemail();
         self::log('info', "order {$order->id} state updated to " . $orderState);
         $payResult->returnDealResultToPilibaba(1);
     } catch (Exception $e) {
         $payResult->returnDealResultToPilibaba($e->getCode());
     }
 }