Example #1
0
 public static function reinjectQuantities(&$orderDetail, $quantity)
 {
     global $cookie;
     if (!Validate::isLoadedObject($orderDetail)) {
         die(Tools::displayError());
     }
     if (Pack::isPack((int) $orderDetail->product_id)) {
         $products_pack = Pack::getItems((int) $orderDetail->product_id, (int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($products_pack as $product_pack) {
             if (!$product_pack->addStockMvt((int) ($product_pack->pack_quantity * $quantity), _STOCK_MOVEMENT_ORDER_REASON_, (int) $product_pack->id_product_attribute, (int) $orderDetail->id_order, (int) $cookie->id_employee)) {
                 return false;
             }
         }
     }
     $product = new Product((int) $orderDetail->product_id);
     if (!$product->addStockMvt((int) $quantity, _STOCK_MOVEMENT_ORDER_REASON_, (int) $orderDetail->product_attribute_id, (int) $orderDetail->id_order, (int) $cookie->id_employee)) {
         return false;
     }
     $orderDetail->product_quantity_reinjected += (int) $quantity;
     return true;
 }
Example #2
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();
 }
    /**
     * postProcess handle every checks before saving products information
     *
     * @param mixed $token
     * @return void
     */
    public function postProcess($token = null)
    {
        global $cookie, $currentIndex;
        // Add a new product
        if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) {
            if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')) {
                $this->submitAddproduct($token);
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        }
        /* Delete a product in the download folder */
        if (Tools::getValue('deleteVirtualProduct')) {
            if ($this->tabAccess['delete'] === '1') {
                $this->deleteVirtualProduct();
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('submitAddAttachments')) {
            if ($this->tabAccess['add'] === '1') {
                $languages = Language::getLanguages(false);
                $is_attachment_name_valid = false;
                foreach ($languages as $language) {
                    $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']);
                    if (strlen($attachment_name_lang) > 0) {
                        $is_attachment_name_valid = true;
                    }
                    if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) {
                        $this->_errors[] = Tools::displayError('Invalid Name');
                    } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) {
                        $this->_errors[] = Tools::displayError('Name is too long');
                    }
                    if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) {
                        $this->_errors[] = Tools::displayError('Invalid description');
                    }
                }
                if (!$is_attachment_name_valid) {
                    $this->_errors[] = Tools::displayError('Attachment Name Required');
                }
                if (empty($this->_errors)) {
                    if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) {
                        if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) {
                            $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb');
                        } else {
                            do {
                                $uniqid = sha1(microtime());
                            } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid));
                            if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) {
                                $this->_errors[] = $this->l('File copy failed');
                            }
                            @unlink($_FILES['attachment_file']['tmp_name']);
                        }
                    } elseif ((int) $_FILES['attachment_file']['error'] === 1) {
                        $max_upload = (int) ini_get('upload_max_filesize');
                        $max_post = (int) ini_get('post_max_size');
                        $upload_mb = min($max_upload, $max_post);
                        $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>';
                    }
                    if (empty($this->_errors) && isset($uniqid)) {
                        $attachment = new Attachment();
                        foreach ($languages as $language) {
                            if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) {
                                $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]);
                            }
                            if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) {
                                $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]);
                            }
                        }
                        $attachment->file = $uniqid;
                        $attachment->mime = $_FILES['attachment_file']['type'];
                        $attachment->file_name = pSQL($_FILES['attachment_file']['name']);
                        if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 128) {
                            $this->_errors[] = Tools::displayError('Invalid file extension');
                        }
                        if (!Validate::isGenericName($attachment->file_name)) {
                            $this->_errors[] = Tools::displayError('Invalid file name');
                        }
                        if (Tools::strlen($attachment->file_name) > 128) {
                            $this->_errors[] = Tools::displayError('File name too long');
                        }
                        if (!sizeof($this->_errors)) {
                            $attachment->add();
                            Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token));
                        } else {
                            $this->_errors[] = Tools::displayError('Invalid file');
                        }
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('submitAttachments')) {
            if ($this->tabAccess['edit'] === '1') {
                if ($id = (int) Tools::getValue($this->identifier)) {
                    if (Attachment::attachToProduct($id, $_POST['attachments'])) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token));
                    }
                }
            }
        } elseif (isset($_GET['duplicate' . $this->table])) {
            if ($this->tabAccess['add'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    $id_product_old = $product->id;
                    unset($product->id);
                    unset($product->id_product);
                    $product->indexed = 0;
                    $product->active = 0;
                    if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) {
                        if ($product->hasAttributes()) {
                            Product::updateDefaultAttribute($product->id);
                        }
                        if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) {
                            $this->_errors[] = Tools::displayError('An error occurred while copying images.');
                        } else {
                            Hook::addProduct($product);
                            Search::indexation(false, $product->id);
                            Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token));
                        }
                    } else {
                        $this->_errors[] = Tools::displayError('An error occurred while creating object.');
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($object = $this->loadObject())) {
                    if ($object->toggleStatus()) {
                        Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token);
                    } else {
                        $this->_errors[] = Tools::displayError('An error occurred while updating status.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (isset($_GET['delete' . $this->table])) {
            if ($this->tabAccess['delete'] === '1') {
                if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) {
                    // check if request at least one object with noZeroObject
                    if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) {
                        $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                    } else {
                        $id_category = Tools::getValue('id_category');
                        $category_url = empty($id_category) ? '' : '&id_category=' . $id_category;
                        if ($this->deleted) {
                            $object->deleteImages();
                            $object->deleted = 1;
                            if ($object->update()) {
                                Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url);
                            }
                        } elseif ($object->delete()) {
                            Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url);
                        }
                        $this->_errors[] = Tools::displayError('An error occurred during deletion.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::getValue('submitDel' . $this->table)) {
            if ($this->tabAccess['delete'] === '1') {
                if (isset($_POST[$this->table . 'Box'])) {
                    $object = new $this->className();
                    if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) {
                        $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.');
                    } else {
                        $result = true;
                        if ($this->deleted) {
                            foreach (Tools::getValue($this->table . 'Box') as $id) {
                                $toDelete = new $this->className($id);
                                $toDelete->deleted = 1;
                                $result = $result and $toDelete->update();
                            }
                        } else {
                            $result = $object->deleteSelection(Tools::getValue($this->table . 'Box'));
                        }
                        if ($result) {
                            $id_category = Tools::getValue('id_category');
                            $category_url = empty($id_category) ? '' : '&id_category=' . $id_category;
                            Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url);
                        }
                        $this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
                    }
                } else {
                    $this->_errors[] = Tools::displayError('You must select at least one element to delete.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) {
            /* PrestaShop demo mode */
            if (_PS_MODE_DEMO_) {
                $this->_errors[] = Tools::displayError('This functionnality has been disabled.');
                return;
            }
            /* PrestaShop demo mode*/
            if ($this->tabAccess['edit'] === '1') {
                /* Delete product image */
                if (isset($_GET['deleteImage'])) {
                    $image->delete();
                    if (!Image::getCover($image->id_product)) {
                        $first_img = Db::getInstance()->getRow('
						SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image`
						WHERE `id_product` = ' . (int) $image->id_product);
                        Db::getInstance()->Execute('
						UPDATE `' . _DB_PREFIX_ . 'image`
						SET `cover` = 1
						WHERE `id_image` = ' . (int) $first_img['id_image']);
                    }
                    @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg');
                    @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg');
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token));
                } elseif (isset($_GET['editImage'])) {
                    if ($image->cover) {
                        $_POST['cover'] = 1;
                    }
                    $languages = Language::getLanguages(false);
                    foreach ($languages as $language) {
                        if (isset($image->legend[$language['id_lang']])) {
                            $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']];
                        }
                    }
                    $_POST['id_image'] = $image->id;
                    $this->displayForm();
                } elseif (isset($_GET['coverImage'])) {
                    Image::deleteCover($image->id_product);
                    $image->cover = 1;
                    if (!$image->update()) {
                        $this->_errors[] = Tools::displayError('Cannot change the product cover');
                    } else {
                        $productId = (int) Tools::getValue('id_product');
                        @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg');
                        @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg');
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token));
                    }
                } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) {
                    $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection'));
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token));
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitProductAttribute')) {
            if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) {
                    $this->_errors[] = Tools::displayError('Attribute price required.');
                }
                if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) {
                    $this->_errors[] = Tools::displayError('You must add at least one attribute.');
                }
                if (!sizeof($this->_errors)) {
                    if (!isset($_POST['attribute_wholesale_price'])) {
                        $_POST['attribute_wholesale_price'] = 0;
                    }
                    if (!isset($_POST['attribute_price_impact'])) {
                        $_POST['attribute_price_impact'] = 0;
                    }
                    if (!isset($_POST['attribute_weight_impact'])) {
                        $_POST['attribute_weight_impact'] = 0;
                    }
                    if (!isset($_POST['attribute_ecotax'])) {
                        $_POST['attribute_ecotax'] = 0;
                    }
                    if (Tools::getValue('attribute_default')) {
                        $product->deleteDefaultAttributes();
                    }
                    // Change existing one
                    if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) {
                        if ($this->tabAccess['edit'] === '1') {
                            if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) {
                                $this->_errors[] = Tools::displayError('This attribute already exists.');
                            } else {
                                $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity'));
                                if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) {
                                    $reason = new StockMvtReason((int) $id_reason);
                                    $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign;
                                    if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) {
                                        $this->_errors[] = Tools::displayError('An error occurred while updating qty.');
                                    }
                                }
                                Hook::updateProductAttribute((int) $id_product_attribute);
                            }
                        } else {
                            $this->_errors[] = Tools::displayError('You do not have permission to add here.');
                        }
                    } else {
                        if ($this->tabAccess['add'] === '1') {
                            if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) {
                                $this->_errors[] = Tools::displayError('This combination already exists.');
                            } else {
                                $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity'));
                            }
                        } else {
                            $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.');
                        }
                    }
                    if (!sizeof($this->_errors)) {
                        $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list'));
                        $product->checkDefaultAttributes();
                    }
                    if (!sizeof($this->_errors)) {
                        if (!$product->cache_default_attribute) {
                            Product::updateDefaultAttribute($product->id);
                        }
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token));
                    }
                }
            }
        } elseif (Tools::isSubmit('deleteProductAttribute')) {
            if ($this->tabAccess['delete'] === '1') {
                if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) {
                    $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute'));
                    $product->checkDefaultAttributes();
                    $product->updateQuantityProductWithAttributeQuantity();
                    if (!$product->hasAttributes()) {
                        $product->cache_default_attribute = 0;
                        $product->update();
                    } else {
                        Product::updateDefaultAttribute($id_product);
                    }
                    Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
                } else {
                    $this->_errors[] = Tools::displayError('Cannot delete attribute');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('deleteAllProductAttributes')) {
            if ($this->tabAccess['delete'] === '1') {
                if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) {
                    $product->deleteProductAttributes();
                    $product->updateQuantityProductWithAttributeQuantity();
                    if ($product->cache_default_attribute) {
                        $product->cache_default_attribute = 0;
                        $product->update();
                    }
                    Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
                } else {
                    $this->_errors[] = Tools::displayError('Cannot delete attributes');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('defaultProductAttribute')) {
            if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                $product->deleteDefaultAttributes();
                $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute'));
                Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token));
            } else {
                $this->_errors[] = Tools::displayError('Cannot make default attribute');
            }
        } elseif (Tools::isSubmit('submitProductFeature')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    // delete all objects
                    $product->deleteFeatures();
                    // add new objects
                    $languages = Language::getLanguages(false);
                    foreach ($_POST as $key => $val) {
                        if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) {
                            if ($val) {
                                $product->addFeaturesToDB($match[1], $val);
                            } else {
                                if ($default_value = $this->checkFeatures($languages, $match[1])) {
                                    $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']);
                                    foreach ($languages as $language) {
                                        if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) {
                                            $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust);
                                        } else {
                                            $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding features.');
                }
            }
            $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
        } elseif (Tools::isSubmit('submitPricesModification')) {
            $_POST['tabs'] = 5;
            if ($this->tabAccess['edit'] === '1') {
                $id_specific_prices = Tools::getValue('spm_id_specific_price');
                $id_shops = Tools::getValue('spm_id_shop');
                $id_currencies = Tools::getValue('spm_id_currency');
                $id_countries = Tools::getValue('spm_id_country');
                $id_groups = Tools::getValue('spm_id_group');
                $prices = Tools::getValue('spm_price');
                $from_quantities = Tools::getValue('spm_from_quantity');
                $reductions = Tools::getValue('spm_reduction');
                $reduction_types = Tools::getValue('spm_reduction_type');
                $froms = Tools::getValue('spm_from');
                $tos = Tools::getValue('spm_to');
                foreach ($id_specific_prices as $key => $id_specific_price) {
                    if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) {
                        $specificPrice = new SpecificPrice((int) $id_specific_price);
                        $specificPrice->id_shop = (int) $id_shops[$key];
                        $specificPrice->id_currency = (int) $id_currencies[$key];
                        $specificPrice->id_country = (int) $id_countries[$key];
                        $specificPrice->id_group = (int) $id_groups[$key];
                        $specificPrice->price = (double) $prices[$key];
                        $specificPrice->from_quantity = (int) $from_quantities[$key];
                        $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]);
                        $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key];
                        $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key];
                        $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key];
                        if (!$specificPrice->update()) {
                            $this->_errors = Tools::displayError('An error occurred while updating the specific price.');
                        }
                    }
                }
                if (!sizeof($this->_errors)) {
                    Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token));
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('submitPriceAddition')) {
            if ($this->tabAccess['add'] === '1') {
                $id_product = (int) Tools::getValue('id_product');
                $id_shop = Tools::getValue('sp_id_shop');
                $id_currency = Tools::getValue('sp_id_currency');
                $id_country = Tools::getValue('sp_id_country');
                $id_group = Tools::getValue('sp_id_group');
                $price = Tools::getValue('sp_price');
                $from_quantity = Tools::getValue('sp_from_quantity');
                $reduction = (double) Tools::getValue('sp_reduction');
                $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type');
                $from = Tools::getValue('sp_from');
                $to = Tools::getValue('sp_to');
                if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) {
                    $specificPrice = new SpecificPrice();
                    $specificPrice->id_product = $id_product;
                    $specificPrice->id_shop = (int) $id_shop;
                    $specificPrice->id_currency = (int) $id_currency;
                    $specificPrice->id_country = (int) $id_country;
                    $specificPrice->id_group = (int) $id_group;
                    $specificPrice->price = (double) $price;
                    $specificPrice->from_quantity = (int) $from_quantity;
                    $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction);
                    $specificPrice->reduction_type = $reduction_type;
                    $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from;
                    $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to;
                    if (!$specificPrice->add()) {
                        $this->_errors = Tools::displayError('An error occurred while updating the specific price.');
                    } else {
                        Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token));
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to add here.');
            }
        } elseif (Tools::isSubmit('deleteSpecificPrice')) {
            if ($this->tabAccess['delete'] === '1') {
                if (!($obj = $this->loadObject())) {
                    return;
                }
                if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) {
                    $this->_errors[] = Tools::displayError('Invalid specific price ID');
                } else {
                    $specificPrice = new SpecificPrice((int) $id_specific_price);
                    if (!$specificPrice->delete()) {
                        $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price');
                    } else {
                        Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token));
                    }
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
            }
        } elseif (Tools::isSubmit('submitSpecificPricePriorities')) {
            if (!($obj = $this->loadObject())) {
                return;
            }
            if (!($priorities = Tools::getValue('specificPricePriority'))) {
                $this->_errors[] = Tools::displayError('Please specify priorities');
            } elseif (Tools::isSubmit('specificPricePriorityToAll')) {
                if (!SpecificPrice::setPriorities($priorities)) {
                    $this->_errors[] = Tools::displayError('An error occurred while updating priorities.');
                } else {
                    Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token));
                }
            } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) {
                $this->_errors[] = Tools::displayError('An error occurred while setting priorities.');
            } else {
                Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token));
            }
        } elseif (Tools::isSubmit('submitCustomizationConfiguration')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) {
                        $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.');
                    }
                    if (!sizeof($this->_errors) and !$product->updateLabels()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization.');
                    }
                    $product->uploadable_files = (int) $_POST['uploadable_files'];
                    $product->text_fields = (int) $_POST['text_fields'];
                    $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0;
                    if (!sizeof($this->_errors) and !$product->update()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.');
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('submitProductCustomization')) {
            if ($this->tabAccess['edit'] === '1') {
                if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
                    foreach ($_POST as $field => $value) {
                        if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) {
                            $this->_errors[] = Tools::displayError('Label fields are invalid');
                        }
                    }
                    if (!sizeof($this->_errors) and !$product->updateLabels()) {
                        $this->_errors[] = Tools::displayError('An error occurred while updating customization.');
                    }
                    if (!sizeof($this->_errors)) {
                        Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token));
                    }
                } else {
                    $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (isset($_GET['position'])) {
            if ($this->tabAccess['edit'] !== '1') {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            } elseif (!Validate::isLoadedObject($object = $this->loadObject())) {
                $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
            }
            if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) {
                $this->_errors[] = Tools::displayError('Failed to update the position.');
            } else {
                Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog'));
            }
        } else {
            parent::postProcess(true);
        }
    }
 public function setPayment($type)
 {
     $address_invoice = new Address((int) $this->context->cart->id_address_invoice);
     $country = new Country((int) $address_invoice->id_country);
     $currency = new Currency((int) $this->context->cart->id_currency);
     if (!$this->verifCountryAndCurrency($country, $currency)) {
         return false;
     }
     $klarna = new Klarna();
     $klarnaInt = new KlarnaIntegration($klarna);
     $klarna->config(Configuration::get('KLARNA_STORE_ID_' . $this->countries[$country->iso_code]['name']), Configuration::get('KLARNA_SECRET_' . $this->countries[$country->iso_code]['name']), $this->countries[$country->iso_code]['code'], $this->countries[$country->iso_code]['langue'], $this->countries[$country->iso_code]['currency'], Configuration::get('KLARNA_MOD'), 'mysql', $this->_getDb());
     if ($type == 'invoice' && Configuration::get('KLARNA_INVOICE_FEE_' . $this->countries[$country->iso_code]['name']) > 0 && !$this->isInCart($this->context->cart, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']))) {
         $this->context->cart->updateQty(1, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']));
         $productInvoicefee = new Product((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']));
         $productInvoicefee->addStockMvt(1, 1);
         $productInvoicefee->update();
     }
     $this->initReservation($klarna, $this->context->cart, $this->context->customer, isset($_POST['klarna_house_number']) ? htmlentities($_POST['klarna_house_number'], ENT_QUOTES, 'ISO-8859-1') : null, isset($_POST['klarna_house_ext']) ? htmlentities($_POST['klarna_house_ext'], ENT_QUOTES, 'ISO-8859-1') : null);
     if (Tools::isSubmit('klarna_pno')) {
         $pno = Tools::safeOutput(Tools::getValue('klarna_pno'));
     } else {
         $day = $_POST['klarna_pno_day'] < 10 ? '0' . (int) $_POST['klarna_pno_day'] : (int) $_POST['klarna_pno_day'];
         $month = $_POST['klarna_pno_month'] < 10 ? '0' . (int) $_POST['klarna_pno_month'] : (int) $_POST['klarna_pno_month'];
         $pno = Tools::safeOutput($day . $month . Tools::getValue('klarna_pno_year'));
     }
     $pclass = $type == 'invoice' ? KlarnaPClass::INVOICE : (int) Tools::getValue('paymentAccount');
     try {
         if ($country->iso_code == 'DE' || $country->iso_code == 'NL') {
             if ($this->context->customer->id_gender != 1 && $this->context->customer->id_gender != 2 && $this->context->customer->id_gender != 3) {
                 $gender = (int) $_POST['klarna_gender'];
                 $customer = new Customer($this->context->customer->id);
                 $customer->id_gender = (int) $_POST['klarna_gender'];
                 $Customer->birthday = (int) $_POST['klarna_pno_year'] . '-' . $month . '-' . $day;
                 $customer->update();
             } else {
                 $gender = $this->context->customer->id_gender == 1 ? 1 : 0;
             }
         } else {
             $gender = null;
         }
         $result = $klarnaInt->reserve($pno, $gender, -1, KlarnaFlags::NO_FLAG, (int) $pclass);
         // Here we get the reservation number or invoice number
         $rno = $result[0];
         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'klarna_rno', array('id_cart' => (int) $this->context->cart->id, 'rno' => pSQL($rno), 'pno' => pSQL($pno), 'house_number' => isset($_POST['klarna_house_number']) ? pSQL($_POST['klarna_house_number']) : null, 'house_ext' => isset($_POST['klarna_house_ext']) ? pSQL($_POST['klarna_house_ext']) : null, 'state' => self::RESERVED, 'type' => pSQL($type), 'pclass' => $type == 'invoice' ? null : (int) Tools::getValue('paymentAccount')), 'INSERT');
         $updateResult = $klarnaInt->updateOrderNo($rno, (int) $this->context->cart->id);
         if ($result[1] == KlarnaFlags::PENDING) {
             $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_PENDING'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key);
         } else {
             if ($result[1] == KlarnaFlags::ACCEPTED) {
                 $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_ACCEPTED'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key);
             }
         }
         $redirect = __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $this->context->cart->secure_key;
         header('Location: ' . $redirect);
         exit;
     } catch (Exception $e) {
         /*remove invoiceFee if existe*/
         $this->context->cart->deleteProduct((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']));
         return array('error' => true, 'message' => Tools::safeOutput(utf8_encode($e->getMessage())));
     }
 }