Exemplo n.º 1
0
 /**
  * @global object $cookie Employee cookie necessary to keep trace of his/her actions
  */
 public function postProcess()
 {
     global $currentIndex, $cookie;
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         if ($this->tabAccess['edit'] === '1') {
             if (!$order->hasBeenShipped()) {
                 die(Tools::displayError('The shipping number can only be set once the order has been shipped.'));
             }
             $_GET['view' . $this->table] = true;
             $shipping_number = pSQL(Tools::getValue('shipping_number'));
             $order->shipping_number = $shipping_number;
             $order->update();
             if ($shipping_number) {
                 global $_LANGMAIL;
                 $customer = new Customer((int) $order->id_customer);
                 $carrier = new Carrier((int) $order->id_carrier);
                 if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) {
                     die(Tools::displayError());
                 }
                 $templateVars = array('{order_amount}' => Tools::displayPrice($order->total_paid, $currency, false), '{carrier_name}' => $carrier->name, '{tracking_number}' => $order->shipping_number, '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id);
                 if (strpos($order->payment, 'COD') === false) {
                     @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 } else {
                     @Mail::Send((int) $order->id_lang, 'in_transit_cod', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 //Send SMS
                 $delivery = new Address((int) $order->id_address_delivery);
                 if (strpos($order->payment, 'COD') === false) {
                     $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped via ' . $carrier->name . '. The airway bill no is ' . $order->shipping_number . '. www.indusdiva.com';
                 } else {
                     $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped. Carrier: ' . $carrier->name . ', AWB No. : ' . $order->shipping_number . ', Amount payable:' . Tools::displayPrice($order->total_paid, $currency, false) . '. www.indusdiva.com';
                 }
                 Tools::sendSMS($delivery->phone_mobile, $smsText);
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     } elseif (Tools::isSubmit('submitExpectedShippingDate') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         $dateshipping = new DateTime(Tools::getValue('expected_shipping_date'));
         $order->expected_shipping_date = pSQL($dateshipping->format('Y-m-d H:i:s'));
         $order->update();
         $order = new Order($id_order);
     } elseif (Tools::isSubmit('submitCarrier') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         $order->shipping_number = '';
         $order->id_carrier = (int) Tools::getValue('id_carrier');
         $order->update();
         $order = new Order($id_order);
     } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         if ($this->tabAccess['edit'] === '1') {
             $_GET['view' . $this->table] = true;
             if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) {
                 $this->_errors[] = Tools::displayError('Invalid new order status');
             } else {
                 if ($newOrderStatusId == _PS_OS_DELIVERED_ && strpos($order->payment, 'COD')) {
                     $paymentHistory = new OrderPaymentHistory();
                     $paymentHistory->id_order = (int) $id_order;
                     $paymentHistory->id_employee = (int) $cookie->id_employee;
                     $paymentHistory->changeIdOrderPaymentState(_PS_PS_PAYMENT_WITH_CARRIER_, (int) $id_order);
                     $paymentHistory->addState();
                 }
                 $history = new OrderHistory();
                 $history->id_order = (int) $id_order;
                 $history->id_employee = (int) $cookie->id_employee;
                 $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order);
                 $order = new Order((int) $order->id);
                 $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang);
                 $templateVars = array();
                 if ($history->id_order_state == _PS_OS_SHIPPING_ and $order->shipping_number) {
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                 } elseif ($history->id_order_state == _PS_OS_CHEQUE_) {
                     $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : '');
                 } elseif ($history->id_order_state == _PS_OS_BANKWIRE_) {
                     $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : '');
                 }
                 if ($history->id_order_state == _PS_OS_CANCELED_) {
                     $this->cancelOrder($id_order);
                 }
                 if ($history->addWithemail(true, $templateVars)) {
                     Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token);
                 }
                 $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     } elseif (isset($_POST['submitMessage'])) {
         $_GET['view' . $this->table] = true;
         if ($this->tabAccess['edit'] === '1') {
             if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) {
                 $this->_errors[] = Tools::displayError('An error occurred before sending message');
             } elseif (!Tools::getValue('message')) {
                 $this->_errors[] = Tools::displayError('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 and (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') {
                             $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.');
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')';
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.');
                         }
                     }
                 }
                 if (!sizeof($this->_errors)) {
                     $message = new Message();
                     $message->id_employee = (int) $cookie->id_employee;
                     $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');
                     $message->id_order = $id_order;
                     $message->private = Tools::getValue('visibility');
                     if (!$message->add()) {
                         $this->_errors[] = Tools::displayError('An error occurred while sending message.');
                     } elseif ($message->private) {
                         Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token);
                     } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) {
                         $order = new Order((int) $message->id_order);
                         if (Validate::isLoadedObject($order)) {
                             $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message));
                             if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                                 Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token);
                             }
                         }
                     }
                     $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.');
                 }
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) {
         if ($this->tabAccess['delete'] === '1') {
             $productList = Tools::getValue('id_order_detail');
             $customizationList = Tools::getValue('id_customization');
             $qtyList = Tools::getValue('cancelQuantity');
             $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
             $full_product_list = $productList;
             $full_quantity_list = $qtyList;
             if ($customizationList) {
                 foreach ($customizationList as $key => $id_order_detail) {
                     $full_product_list[$id_order_detail] = $id_order_detail;
                     $full_quantity_list[$id_order_detail] = $customizationQtyList[$key];
                 }
             }
             if ($productList or $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 selected for product.');
                         }
                         // check actionable quantity
                         $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('Invalid quantity selected for 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 selected for product.');
                         }
                         if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                             $this->_errors[] = Tools::displayError('Invalid quantity selected for product.');
                         }
                     }
                 }
                 if (!sizeof($this->_errors) and $productList) {
                     foreach ($productList as $key => $id_order_detail) {
                         $qtyCancelProduct = abs($qtyList[$key]);
                         $orderDetail = new OrderDetail((int) $id_order_detail);
                         // Reinject product
                         if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) {
                             $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected;
                             $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct;
                             if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) {
                                 $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>';
                             } else {
                                 $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL;
                                 $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID);
                                 $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang));
                                 if (!empty($orderDetail->product_attribute_id)) {
                                     $updProduct['quantity_attribute'] = (int) $newProductQty;
                                     $product['quantity_attribute'] = $updProduct['quantity_attribute'];
                                 } else {
                                     $updProduct['stock_quantity'] = (int) $newProductQty;
                                     $product['stock_quantity'] = $updProduct['stock_quantity'];
                                 }
                                 Hook::updateQuantity($product, $order);
                             }
                         }
                         // Delete product
                         if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) {
                             $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>';
                         }
                         Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail));
                     }
                 }
                 if (!sizeof($this->_errors) and $customizationList) {
                     foreach ($customizationList as $id_customization => $id_order_detail) {
                         $orderDetail = new OrderDetail((int) $id_order_detail);
                         $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                         if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) {
                             $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization;
                         }
                     }
                 }
                 // E-mail params
                 if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) {
                     $customer = new Customer((int) $order->id_customer);
                     $params['{lastname}'] = $customer->lastname;
                     $params['{firstname}'] = $customer->firstname;
                     $params['{id_order}'] = $order->id;
                 }
                 // Generate credit slip
                 if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) {
                     if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) {
                         $this->_errors[] = Tools::displayError('Cannot generate credit slip');
                     } else {
                         Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list));
                         @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                     }
                 }
                 // Generate voucher
                 if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) {
                     if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) {
                         $this->_errors[] = Tools::displayError('Cannot generate voucher');
                     } else {
                         $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
                         $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                         $params['{voucher_num}'] = $voucher->name;
                         @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                     }
                 }
             } else {
                 $this->_errors[] = Tools::displayError('No product or quantity selected.');
             }
             // Redirect if no errors
             if (!sizeof($this->_errors)) {
                 Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (Tools::isSubmit('updateOrder') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) {
         $cart = Cart::getCartByOrderId($order->id);
         $update = false;
         if ($discountValue = Tools::getValue('addDiscount')) {
             $discountVoucher = new Discount();
             $discountVoucher->name = 'ADMIND-' . $order->id . date('mdHis');
             $discountVoucher->id_discount_type = 2;
             $discountVoucher->id_customer = $order->id_customer;
             $discountVoucher->cumulable = 1;
             $discountVoucher->cumulable_reduction = 1;
             $discountVoucher->date_from = $order->date_add;
             $discountVoucher->date_to = date('Y-m-d', time() + 86400);
             $discountVoucher->quantity = 1;
             $discountVoucher->quantity_per_user = 1;
             $discountVoucher->value = (double) $discountValue;
             $discountVoucher->minimal = 0;
             $discountVoucher->id_currency = 4;
             $discountVoucher->behavior_not_exhausted = 1;
             $discountVoucher->add(true);
             $cart->addDiscount($discountVoucher->id);
             $order->addDiscount($discountVoucher->id, $discountVoucher->name, $discountVoucher->value);
             $cart->update();
             $update = true;
         }
         //waive shipping, create a free shipping voucher, apply, reload the order object
         if (Tools::getValue('waiveShipping')) {
             $freeShipVoucher = new Discount();
             $freeShipVoucher->name = 'ADMINFS-' . $order->id . date('mdHis');
             $freeShipVoucher->id_discount_type = 3;
             $freeShipVoucher->id_customer = $order->id_customer;
             $freeShipVoucher->cumulable = 1;
             $freeShipVoucher->cumulable_reduction = 1;
             $freeShipVoucher->date_from = $order->date_add;
             $freeShipVoucher->date_to = date('Y-m-d', time() + 86400);
             $freeShipVoucher->quantity = 0;
             $freeShipVoucher->quantity_per_user = 1;
             $freeShipVoucher->value = 0;
             $freeShipVoucher->add(true);
             $cart->addDiscount($freeShipVoucher->id);
             $order->addDiscount($freeShipVoucher->id, $freeShipVoucher->name, $freeShipVoucher->value);
             $cart->update();
             $update = true;
         }
         $id_product = false;
         if ($id_product = Tools::getValue('addProductID')) {
             $product = new Product((int) $id_product, true, (int) $cookie->id_lang);
             if ($product->quantity > 0 && $product->available_for_order) {
                 $cart->updateQty(1, $id_product);
             }
             $orderDetail = null;
             $db = Db::getInstance();
             $res = $db->getRow('select id_order_detail from ps_order_detail where id_order = ' . $order->id . ' and product_id = ' . $id_product);
             $vat_address = new Address((int) $order->id_address_delivery);
             $customer = new Customer((int) $order->id_customer);
             $unitPrice = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             if ($res) {
                 $orderDetail = new OrderDetail($res['id_order_detail']);
                 $orderDetail->product_quantity = $orderDetail->product_quantity + 1;
             } else {
                 $productName = $product->name;
                 $orderDetail = new OrderDetail();
                 $orderDetail->product_quantity = 1;
                 $orderDetail->id_order = $order->id;
                 $orderDetail->product_id = $id_product;
                 $orderDetail->product_name = $productName;
                 $orderDetail->product_ean13 = $product->ean13;
                 $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $specificPrice = 0;
                 $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity);
                 $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE);
                 $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                 $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0);
                 $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0);
                 $orderDetail->tax_rate = $tax_rate;
                 $orderDetail->tax_name = 'default_tax';
                 $orderDetail->group_reduction = 0;
                 $orderDetail->product_quantity_in_stock = (int) Product::getQuantity((int) $id_product, NULL);
                 $orderDetail->product_quantity_refunded = 0;
                 $orderDetail->product_quantity_reinjected = 0;
                 $orderDetail->ecotax = 0;
                 $orderDetail->ecotax_tax_rate = 0;
                 $orderDetail->discount_quantity_applied = 0;
                 $orderDetail->add(true, true);
             }
             $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity);
             $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE);
             $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
             $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0);
             $orderDetail->reduction_amount = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0);
             $orderDetail->update();
             $product->addStockMvt(-1, _STOCK_MOVEMENT_ORDER_REASON_, NULL, $order->id, (int) $cookie->id_employee);
             $update = true;
         }
         if ($update) {
             //Recalculate product prices with and without tax from order detail
             $detailIds = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                     SELECT id_order_detail
                     FROM `' . _DB_PREFIX_ . 'order_detail` od
                     WHERE od.`id_order` = ' . (int) $order->id);
             $totalProducts = 0.0;
             $totalProductsWT = 0.0;
             foreach ($detailIds as $id) {
                 $reduction_amount = 0.0;
                 $orderDetail = new OrderDetail($id['id_order_detail']);
                 $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01);
                 if ($orderDetail->reduction_percent != 0.0) {
                     $reduction_amount = $price * $orderDetail->reduction_percent / 100;
                 } elseif ($orderDetail->reduction_amount != 0.0) {
                     $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2);
                 }
                 if (isset($reduction_amount) and $reduction_amount) {
                     $price = Tools::ps_round($price - $reduction_amount, 2);
                 }
                 $productPriceWithoutTax = $price / (1 + $orderDetail->tax_rate * 0.01);
                 //Update order
                 $totalProducts += $orderDetail->product_quantity * $productPriceWithoutTax;
                 $totalProductsWT += $orderDetail->product_quantity * $price;
             }
             $order->total_products = Tools::ps_round($totalProducts, 2);
             $order->total_products_wt = Tools::ps_round($totalProductsWT, 2);
             $order->total_shipping = $cart->getOrderShippingCost();
             //$order->total_products = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order->total_discounts = abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
             $order->total_paid = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod;
             $order->total_paid_real = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod;
             //$order->total_products_wt = (float)($cart->getOrderTotal(true, Cart::ONLY_PRODUCTS));
             $order->update();
         }
         // Redirect if no errors
         if (!sizeof($this->_errors)) {
             Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
         }
     } elseif (isset($_GET['messageReaded'])) {
         Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee);
     }
     parent::postProcess();
 }
Exemplo n.º 2
0
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
    {
        global $cart, $link, $cookie;
        $id_payment_state = _PS_PS_NOT_PAID_;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) {
            if ($secure_key !== false and $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->id_address_delivery);
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_customization = $cart->getCartCustomizationCost();
            $order->total_donation = round($cookie->donation_amount);
            unset($cookie->donation_amount);
            if (strpos($order->payment, 'COD') === false) {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true));
            } else {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false));
                $order->total_cod = COD_CHARGE;
            }
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            $shippingdate = $cart->getExpectedShippingDate();
            $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            // 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 (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) {
                $id_order_state = _PS_OS_ERROR_;
                $id_payment_state = _PS_PS_NOT_PAID_;
            } else {
                if (strpos($order->payment, 'COD') === false) {
                    $id_payment_state = _PS_PS_PAID_;
                }
            }
            //update payment status
            // Creating order
            if ($cart->OrderExists() == false) {
                $cart_value = $cart->getOrderTotal();
                if ($cart_value >= 1000) {
                    //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL))
                    //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE);
                }
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        if ($product['stock_quantity'] < 1) {
                            SolrSearch::updateProduct((int) $product['id_product']);
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], 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, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $specificPrice = 0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . (double) Group::getReduction((int) $order->id_customer) . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 8) {
                                        $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />';
                                    } else {
                                        if ($text['index'] == 1) {
                                            $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />';
                                        } else {
                                            if ($text['index'] == 2) {
                                                $customizationText .= 'Stitched to measure blouse.' . '<br />';
                                            } else {
                                                if ($text['index'] == 3) {
                                                    $customizationText .= 'Stitched to measure in-skirt.' . '<br />';
                                                } else {
                                                    if ($text['index'] == 4) {
                                                        $customizationText .= 'Stitched to measure kurta.' . '<br />';
                                                    } else {
                                                        if ($text['index'] == 5) {
                                                            $customizationText .= 'Stitched to measure salwar.' . '<br />';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    //if giftcard, create voucher and send the mails now.
                    $categories = Product::getProductCategories($product['id_product']);
                    if (in_array(CAT_GIFTCARD, $categories)) {
                        $friendsName = '';
                        $friendsEmail = '';
                        $giftMessage = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 21) {
                                        $friendsName = $text['value'];
                                    } else {
                                        if ($text['index'] == 22) {
                                            $friendsEmail = $text['value'];
                                        } else {
                                            if ($text['index'] == 23) {
                                                $giftMessage = $text['value'];
                                            } else {
                                                if ($text['index'] == 25) {
                                                    $couponCode = $text['value'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //$couponCode = "GC" . Tools::rand_string(8);
                        // create discount
                        $languages = Language::getLanguages($order);
                        $voucher = new Discount();
                        $voucher->id_discount_type = 2;
                        foreach ($languages as $language) {
                            $voucher->description[$language['id_lang']] = $product['name'];
                        }
                        $voucher->value = (double) $unitPrice;
                        $voucher->name = $couponCode;
                        $voucher->id_currency = 2;
                        //USD
                        $voucher->quantity = 1;
                        $voucher->quantity_per_user = 1;
                        $voucher->cumulable = 1;
                        $voucher->cumulable_reduction = 1;
                        $voucher->minimal = 0;
                        $voucher->active = 1;
                        $voucher->cart_display = 0;
                        $now = time();
                        $voucher->date_from = date('Y-m-d H:i:s', $now);
                        $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365);
                        /* 365 days */
                        $voucher->add();
                        $productObj = new Product($product['id_product'], true, 1);
                        $idImage = $productObj->getCoverWs();
                        if ($idImage) {
                            $idImage = $productObj->id . '-' . $idImage;
                        } else {
                            $idImage = Language::getIsoById(1) . '-default';
                        }
                        $params = array();
                        $params['{voucher_code}'] = $voucher->name;
                        $params['{freinds_name}'] = $friendsName;
                        $params['{gift_message}'] = $giftMessage;
                        $params['{product_name}'] = $product['name'];
                        $params['{voucher_value}'] = $voucher->value;
                        $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location;
                        $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname;
                        $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card';
                        @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                        @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang);
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) and $outOfStock) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                //Payment status
                $paymentHistory = new OrderPaymentHistory();
                $paymentHistory->id_order = (int) $order->id;
                $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id);
                $paymentHistory->addState();
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                //Update tracking code for quantium
                if ($order->id_carrier == QUANTIUM) {
                    if (strpos($order->payment, 'COD') === false) {
                        $order->shipping_number = 'VBN' . $order->id;
                    } else {
                        $order->shipping_number = 'VBC' . $order->id;
                    }
                    $order->update();
                } else {
                    if ($order->id_carrier == SABEXPRESS) {
                        $db = Db::getInstance();
                        $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                        $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0");
                        $awb = $res['awb'];
                        $id = $res['id'];
                        $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                        $db->Execute('UNLOCK TABLES');
                        $order->shipping_number = $awb;
                        $order->update();
                    } else {
                        if ($order->id_carrier == AFL) {
                            $db = Db::getInstance();
                            $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                            $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0");
                            $awb = $res['awb'];
                            $id = $res['id'];
                            $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                            $db->Execute('UNLOCK TABLES');
                            $order->shipping_number = $awb;
                            $order->update();
                        }
                    }
                }
                // Send an e-mail to customer
                if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) {
                    //deduct reward points
                    $points_redeemed = $cart->getPoints();
                    if ($points_redeemed) {
                        VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    /*
                    if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0)
                    {
                        VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    */
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $shippingdate = new DateTime($order->expected_shipping_date);
                    $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $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="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; 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}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if (Validate::isEmail($customer->email)) {
                        if ($id_order_state == _PS_OS_BANKWIRE_) {
                            Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        } else {
                            $data['payment'] = 'Online Payment';
                            Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        }
                    }
                    //Send SMS
                    //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com';
                    //Tools::sendSMS($delivery->phone_mobile, $smsText);
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }