Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class AdminOrdersController extends AdminOrdersControllerCore
- {
- /*
- * module: customerportfolio
- * date: 2016-09-06 11:13:35
- * version: 1.5
- */
- public function __construct()
- {
- $this->bootstrap = true;
- $this->table = 'order';
- $this->className = 'Order';
- $this->lang = false;
- $this->addRowAction('view');
- $this->explicitSelect = true;
- $this->deleted = false;
- $this->context = Context::getContext();
- $this->_select = '
- a.id_currency,
- a.id_order AS id_pdf,
- CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`,
- osl.`name` AS `osname`,
- os.`color`,
- IF((SELECT COUNT(so.id_order) FROM `'._DB_PREFIX_.'orders` so WHERE so.id_customer = a.id_customer) > 1, 0, 1) as new';
- $this->_join = '
- LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`)
- LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = a.`current_state`)
- LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)$this->context->language->id.')';
- if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
- {
- $this->_join = $this->_join.'
- LEFT JOIN `'._DB_PREFIX_.'portfolio_customer_employee` pce ON (pce.`id_customer` = a.`id_customer`)';
- $this->_where = ' AND pce.`id_employee` = '.$this->context->cookie->id_employee.' ';
- }
- $this->_orderBy = 'id_order';
- $this->_orderWay = 'DESC';
- $statuses_array = array();
- $statuses = OrderState::getOrderStates((int)$this->context->language->id);
- foreach ($statuses as $status)
- $statuses_array[$status['id_order_state']] = $status['name'];
- $this->fields_list = array(
- 'id_order' => array(
- 'title' => $this->l('ID'),
- 'align' => 'center',
- 'width' => 25
- ),
- 'reference' => array(
- 'title' => $this->l('Reference'),
- 'align' => 'center',
- 'width' => 65
- ),
- 'new' => array(
- 'title' => $this->l('New'),
- 'width' => 25,
- 'align' => 'center',
- 'type' => 'bool',
- 'tmpTableFilter' => true,
- 'icon' => array(
- 0 => 'blank.gif',
- 1 => array(
- 'src' => 'note.png',
- 'alt' => $this->l('First customer order'),
- )
- ),
- 'orderby' => false
- ),
- 'customer' => array(
- 'title' => $this->l('Customer'),
- 'havingFilter' => true,
- ),
- 'total_paid_tax_incl' => array(
- 'title' => $this->l('Total'),
- 'width' => 70,
- 'align' => 'right',
- 'prefix' => '<b>',
- 'suffix' => '</b>',
- 'type' => 'price',
- 'currency' => true
- ),
- 'payment' => array(
- 'title' => $this->l('Payment'),
- 'width' => 100
- ),
- 'osname' => array(
- 'title' => $this->l('Status'),
- 'color' => 'color',
- 'width' => 280,
- 'type' => 'select',
- 'list' => $statuses_array,
- 'filter_key' => 'os!id_order_state',
- 'filter_type' => 'int'
- ),
- 'date_add' => array(
- 'title' => $this->l('Date'),
- 'width' => 130,
- 'align' => 'right',
- 'type' => 'datetime',
- 'filter_key' => 'a!date_add'
- ),
- 'id_pdf' => array(
- 'title' => $this->l('PDF'),
- 'width' => 35,
- 'align' => 'center',
- 'callback' => 'printPDFIcons',
- 'orderby' => false,
- 'search' => false,
- 'remove_onclick' => true)
- );
- $this->shopLinkType = 'shop';
- $this->shopShareDatas = Shop::SHARE_ORDER;
- if (Tools::isSubmit('id_order'))
- {
- $order = new Order((int)Tools::getValue('id_order'));
- if (!Validate::isLoadedObject($order))
- throw new PrestaShopException('Cannot load Order object');
- $this->context->cart = new Cart($order->id_cart);
- $this->context->customer = new Customer($order->id_customer);
- }
- AdminController::__construct();
- }
- /*
- * module: customerportfolio
- * date: 2016-09-06 11:13:35
- * version: 1.5
- */
- public function renderView()
- {
- $order = new Order(Tools::getValue('id_order'));
- if (!Validate::isLoadedObject($order))
- throw new PrestaShopException('object can\'t be loaded');
- if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL') && !empty($order->id_customer))
- {
- $check_access = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'portfolio_customer_employee`
- WHERE id_customer = '.$order->id_customer.' AND `id_employee` = '.$this->context->cookie->id_employee.';');
- if (empty($check_access))
- {
- $this->errors[] = $this->l('Access denied.');
- return;
- }
- }
- $customer = new Customer($order->id_customer);
- $carrier = new Carrier($order->id_carrier);
- $products = $this->getProducts($order);
- $currency = new Currency((int)$order->id_currency);
- $carrier_module_call = null;
- if ($carrier->is_module)
- {
- $module = Module::getInstanceByName($carrier->external_module_name);
- if (method_exists($module, 'displayInfoByCart'))
- $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
- }
- $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
- if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state)
- $invoiceState = new State((int)$addressInvoice->id_state);
- if ($order->id_address_invoice == $order->id_address_delivery)
- {
- $addressDelivery = $addressInvoice;
- if (isset($invoiceState))
- $deliveryState = $invoiceState;
- }
- else
- {
- $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
- if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state)
- $deliveryState = new State((int)$addressDelivery->id_state);
- }
- $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
- $warehouse_list = null;
- $order_details = $order->getOrderDetailList();
- foreach ($order_details as $order_detail)
- {
- $product = new Product($order_detail['product_id']);
- if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management)
- {
- $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
- foreach ($warehouses as $warehouse)
- if (!isset($warehouse_list[$warehouse['id_warehouse']]))
- $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
- }
- }
- $payment_methods = array();
- foreach (PaymentModule::getInstalledPaymentModules() as $payment)
- {
- $module = Module::getInstanceByName($payment['name']);
- if (Validate::isLoadedObject($module))
- $payment_methods[] = $module->displayName;
- }
- $display_out_of_stock_warning = false;
- $current_order_state = $order->getCurrentOrderState();
- if ($current_order_state->delivery != 1 && $current_order_state->shipped != 1)
- $display_out_of_stock_warning = true;
- foreach ($products as &$product)
- {
- $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
- $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
- $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
- $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
- $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
- $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
- $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
- if ($product['current_stock'] == 0 && $display_out_of_stock_warning)
- $this->displayWarning($this->l('This product is out of stock: ').' '.$product['product_name']);
- }
- if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
- {
- $previous = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders o, '._DB_PREFIX_.'portfolio_customer_employee pce WHERE pce.id_customer=o.id_customer AND pce.id_employee='.$this->context->cookie->id_employee.' AND o.id_order < '.(int)$order->id.' ORDER BY o.id_order DESC');
- $next = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders o, '._DB_PREFIX_.'portfolio_customer_employee pce WHERE pce.id_customer=o.id_customer AND pce.id_employee='.$this->context->cookie->id_employee.' AND o.id_order > '.(int)$order->id.' ORDER BY o.id_order ASC');
- }
- else
- {
- $previous = $order->getPreviousOrderId();
- $next = $order->getNextOrderId();
- }
- $this->tpl_view_vars = array(
- 'order' => $order,
- 'cart' => new Cart($order->id_cart),
- 'customer' => $customer,
- 'customer_addresses' => $customer->getAddresses($this->context->language->id),
- 'addresses' => array(
- 'delivery' => $addressDelivery,
- 'deliveryState' => isset($deliveryState) ? $deliveryState : null,
- 'invoice' => $addressInvoice,
- 'invoiceState' => isset($invoiceState) ? $invoiceState : null
- ),
- 'customerStats' => $customer->getStats(),
- 'products' => $products,
- 'discounts' => $order->getCartRules(),
- 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), // Get the sum of total_paid_tax_incl of the order with similar reference
- 'total_paid' => $order->getTotalPaid(),
- 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id),
- 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, 0),
- 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang),
- 'messages' => Message::getMessagesByOrderId($order->id, true),
- 'carrier' => new Carrier($order->id_carrier),
- 'history' => $order->getHistory($this->context->language->id),
- 'states' => OrderState::getOrderStates($this->context->language->id),
- 'warehouse_list' => $warehouse_list,
- 'sources' => ConnectionsSource::getOrderSources($order->id),
- 'currentState' => $order->getCurrentOrderState(),
- 'currency' => new Currency($order->id_currency),
- 'currencies' => Currency::getCurrencies(),
- 'previousOrder' => $previous,
- 'nextOrder' => $next,
- 'current_index' => self::$currentIndex,
- 'carrierModuleCall' => $carrier_module_call,
- 'iso_code_lang' => $this->context->language->iso_code,
- 'id_lang' => $this->context->language->id,
- 'can_edit' => ($this->tabAccess['edit'] == 1),
- 'current_id_lang' => $this->context->language->id,
- 'invoices_collection' => $order->getInvoicesCollection(),
- 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(),
- 'payment_methods' => $payment_methods,
- 'invoice_management_active' => Configuration::get('PS_INVOICE')
- );
- return AdminController::renderView();
- }
- /*
- * module: customerportfolio
- * date: 2016-09-06 11:13:35
- * version: 1.5
- */
- public function ajaxProcessSearchCustomers()
- {
- if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
- {
- $sql = 'SELECT c.*
- FROM `'._DB_PREFIX_.'customer` c, `'._DB_PREFIX_.'portfolio_customer_employee` pce
- WHERE pce.`id_customer`=c.`id_customer` AND pce.`id_employee`='.$this->context->cookie->id_employee.' AND
- (c.`email` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
- OR c.`id_customer` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
- OR c.`lastname` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
- OR c.`firstname` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
- )'.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER);
- $customers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
- }
- else
- $customers = Customer::searchByName(pSQL(Tools::getValue('customer_search')));
- if ($customers)
- $to_return = array('customers' => $customers, 'found' => true);
- else
- $to_return = array('found' => false);
- $this->content = Tools::jsonEncode($to_return);
- }
- if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
- $order = new Order(Tools::getValue('id_order'));
- if (!Validate::isLoadedObject($order)) {
- throw new PrestaShopException('Can\'t load Order object');
- }
- }
- if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
- if (!Validate::isLoadedObject($order_carrier)) {
- $this->errors[] = Tools::displayError('Order carrier ID is invalid');
- } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
- $this->errors[] = Tools::displayError('Tracking number is incorrect');
- } else {
- $order->shipping_number = Tools::getValue('tracking_number');
- $order->update();
- $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
- if ($order_carrier->update()) {
- $customer = new Customer((int) $order->id_customer);
- $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
- if (!Validate::isLoadedObject($customer)) {
- throw new PrestaShopException('Can\'t load Customer object');
- }
- if (!Validate::isLoadedObject($carrier)) {
- throw new PrestaShopException('Can\'t load Carrier object');
- }
- $templateVars = array(
- '{followup}' => str_replace('@', $order->shipping_number, $carrier->url),
- '{firstname}' => $customer->firstname,
- '{lastname}' => $customer->lastname,
- '{id_order}' => $order->id
- );
- if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE)) {
- Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order));
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- } else {
- $this->errors[] = Tools::displayError('An error occurred while sending e-mail to the customer.');
- }
- } else {
- $this->errors[] = Tools::displayError('Order carrier can\'t be updated');
- }
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::isSubmit('submitState') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $order_state = new OrderState(Tools::getValue('id_order_state'));
- if (!Validate::isLoadedObject($order_state)) {
- $this->errors[] = Tools::displayError('Invalid new order status');
- } else {
- $current_order_state = $order->getCurrentOrderState();
- if ($current_order_state->id != $order_state->id) {
- $history = new OrderHistory();
- $history->id_order = $order->id;
- $history->id_employee = (int) $this->context->employee->id;
- $history->changeIdOrderState($order_state->id, $order->id);
- $carrier = new Carrier($order->id_carrier, $order->id_lang);
- $templateVars = array();
- if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
- $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
- } elseif ($history->id_order_state == Configuration::get('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 == Configuration::get('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->addWithemail(TRUE, $templateVars)) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&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('This order is already assigned this status');
- }
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $customer = new Customer(Tools::getValue('id_customer'));
- if (!Validate::isLoadedObject($customer)) {
- $this->errors[] = Tools::displayError('Customer is invalid');
- } elseif (!Tools::getValue('message')) {
- $this->errors[] = Tools::displayError('Message cannot be blank');
- } else {
- $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
- foreach ($rules['required'] as $field) {
- if (($value = Tools::getValue($field)) == FALSE && (string) $value != '0') {
- if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
- $this->errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.');
- }
- }
- }
- foreach ($rules['size'] as $field => $maxLength) {
- if (Tools::getValue($field) && 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 (!count($this->errors)) {
- $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
- if (!$id_customer_thread) {
- $customer_thread = new CustomerThread();
- $customer_thread->id_contact = 0;
- $customer_thread->id_customer = (int) $order->id_customer;
- $customer_thread->id_shop = (int) $this->context->shop->id;
- $customer_thread->id_order = (int) $order->id;
- $customer_thread->id_lang = (int) $this->context->language->id;
- $customer_thread->email = $customer->email;
- $customer_thread->status = 'open';
- $customer_thread->token = Tools::passwdGen(12);
- $customer_thread->add();
- } else {
- $customer_thread = new CustomerThread((int) $id_customer_thread);
- }
- $customer_message = new CustomerMessage();
- $customer_message->id_customer_thread = $customer_thread->id;
- $customer_message->id_employee = (int) $this->context->employee->id;
- $customer_message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');
- $customer_message->private = Tools::getValue('visibility');
- if (!$customer_message->add()) {
- $this->errors[] = Tools::displayError('An error occurred while saving message');
- } elseif ($customer_message->private) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
- } else {
- $message = $customer_message->message;
- if (Configuration::get('PS_MAIL_TYPE') != Mail::TYPE_TEXT) {
- $message = Tools::nl2br($customer_message->message);
- }
- $varsTpl = array(
- '{lastname}' => $customer->lastname,
- '{firstname}' => $customer->firstname,
- '{id_order}' => $order->id,
- '{message}' => $message
- );
- if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE)) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
- }
- }
- $this->errors[] = Tools::displayError('An error occurred while sending e-mail to the customer.');
- }
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to delete here.');
- }
- } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
- if ($this->tabAccess['edit'] == '1') {
- if (is_array($_POST['partialRefundProduct'])) {
- $amount = 0;
- $order_detail_list = array();
- foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
- if (isset($amount_detail) && !empty($amount_detail)) {
- $amount += $amount_detail;
- $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
- $order_detail_list[$id_order_detail]['amount'] = (float) $amount_detail;
- }
- }
- $shipping_cost_amount = (float) Tools::getValue('partialRefundShippingCost');
- if ($shipping_cost_amount > 0) {
- $amount += $shipping_cost_amount;
- }
- if ($amount > 0) {
- if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
- $this->errors[] = Tools::displayError('Cannot generate partial credit slip');
- }
- } else {
- $this->errors[] = Tools::displayError('You have to write an amount if you want to do a partial credit slip');
- }
- if (!count($this->errors)) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
- }
- } else {
- $this->errors[] = Tools::displayError('Partial refund data is incorrect');
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to delete here.');
- }
- } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
- if ($this->tabAccess['delete'] === '1') {
- if (!Tools::isSubmit('id_order_detail')) {
- $this->errors[] = Tools::displayError('You must select a product');
- } elseif (!Tools::isSubmit('cancelQuantity')) {
- $this->errors[] = Tools::displayError('You must enter a quantity');
- } else {
- $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 || $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.');
- }
- $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 (!count($this->errors) && $productList) {
- foreach ($productList as $key => $id_order_detail) {
- $qty_cancel_product = abs($qtyList[$key]);
- $order_detail = new OrderDetail((int) ($id_order_detail));
- if (!$order->hasBeenDelivered() || ($order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities'))) {
- $reinjectable_quantity = (int) $order_detail->product_quantity - (int) $order_detail->product_quantity_reinjected;
- $quantity_to_reinject = $qty_cancel_product > $reinjectable_quantity ? $reinjectable_quantity : $qty_cancel_product;
- $product_to_inject = new Product($order_detail->product_id, FALSE, $this->context->language->id, $order->id_shop);
- $product = new Product($order_detail->product_id);
- if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')
- && $product->advanced_stock_management
- && $order_detail->id_warehouse != 0) {
- $manager = StockManagerFactory::getManager();
- $movements = StockMvt::getNegativeStockMvts(
- $order_detail->id_order, $order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject
- );
- foreach ($movements as $movement) {
- $manager->addProduct(
- $order_detail->product_id, $order_detail->product_attribute_id, new Warehouse($movement['id_warehouse']), $movement['physical_quantity'], NULL, $movement['price_te'], TRUE
- );
- }
- StockAvailable::synchronize($order_detail->product_id);
- } else if ($order_detail->id_warehouse == 0) {
- StockAvailable::updateQuantity(
- $order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject, $order->id_shop
- );
- } else {
- $this->errors[] = Tools::displayError('Cannot re-stock product');
- }
- }
- $order_detail = new OrderDetail((int) $id_order_detail);
- if (!$order->deleteProduct($order, $order_detail, $qtyCancelProduct)) {
- $this->errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
- }
- Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => $id_order_detail));
- }
- }
- if (!count($this->errors) && $customizationList) {
- foreach ($customizationList as $id_customization => $id_order_detail) {
- $order_detail = new OrderDetail((int) ($id_order_detail));
- $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
- if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
- $this->errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization;
- }
- }
- }
- if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
- $customer = new Customer((int) ($order->id_customer));
- $params['{lastname}'] = $customer->lastname;
- $params['{firstname}'] = $customer->firstname;
- $params['{id_order}'] = $order->id;
- }
- if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
- if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
- $this->errors[] = Tools::displayError('Cannot generate credit slip');
- } else {
- Hook::exec('actionOrderSlipAdd', 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', $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE
- );
- }
- }
- if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
- if (TRUE || !$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip for order #'), Tools::isSubmit('shippingBack'))) {
- $this->errors[] = Tools::displayError('Cannot generate voucher');
- } else {
- $currency = $this->context->currency;
- $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', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE);
- }
- }
- } else {
- $this->errors[] = Tools::displayError('No product or quantity selected.');
- }
- if (!count($this->errors)) {
- Tools::redirectAdmin(self::$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('messageReaded')) {
- Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
- } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
- $currency = new Currency(Tools::getValue('payment_currency'));
- $order_has_invoice = $order->hasInvoice();
- if ($order_has_invoice) {
- $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
- } else {
- $order_invoice = NULL;
- }
- if (!Validate::isLoadedObject($order)) {
- $this->errors[] = Tools::displayError('Order can\'t be found');
- } elseif (!Validate::isPrice($amount)) {
- $this->errors[] = Tools::displayError('Amount is invalid');
- } elseif (!Validate::isString(Tools::getValue('payment_method'))) {
- $this->errors[] = Tools::displayError('Payment method is invalid');
- } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
- $this->errors[] = Tools::displayError('Transaction ID is invalid');
- } elseif (!Validate::isLoadedObject($currency)) {
- $this->errors[] = Tools::displayError('Currency is invalid');
- } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
- $this->errors[] = Tools::displayError('Invoice is invalid');
- } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
- $this->errors[] = Tools::displayError('Date is invalid');
- } else {
- if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
- $this->errors[] = Tools::displayError('An error occurred on adding order payment');
- } else {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- }
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::isSubmit('submitEditNote')) {
- $note = Tools::getValue('note');
- $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
- if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
- if ($this->tabAccess['edit'] === '1') {
- $order_invoice->note = $note;
- if ($order_invoice->save()) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
- } else {
- $this->errors[] = Tools::displayError('Unable to save invoice note.');
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } else {
- $this->errors[] = Tools::displayError('Unable to load invoice for edit note.');
- }
- } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) &&
- ($module_name = Tools::getValue('payment_module_name')) &&
- ($id_order_state = Tools::getValue('id_order_state'))) {
- if ($this->tabAccess['edit'] === '1') {
- $payment_module = Module::getInstanceByName($module_name);
- $cart = new Cart((int) $id_cart);
- $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(TRUE, Cart::BOTH), $payment_module->displayName, sprintf($this->l('Manual order - ID Employee :%d'), (int) Context::getContext()->cookie->id_employee), array(), NULL, FALSE, $cart->secure_key);
- require_once(_PS_MODULE_DIR_ . "belvg_preorderproducts/belvg_preorderproducts.php");
- $products = $cart->getProducts();
- $preorder_fl = FALSE;
- foreach ($products as $product) {
- if ($preorder_id = ProductPreorder::checkActiveStatic($product['id_product'], $product['id_product_attribute'])) {
- $preorder_init_product_obj = $product;
- $preorder_fl = TRUE;
- break;
- }
- }
- if ($preorder_fl) {
- $objOrder = new Order($payment_module->currentOrder);
- Belvg_PreOrderProducts::checkPreorder($objOrder);
- }
- if ($payment_module->currentOrder) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to add here.');
- }
- } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $address = new Address(Tools::getValue('id_address'));
- if (Validate::isLoadedObject($address)) {
- if (Tools::isSubmit('submitAddressShipping')) {
- $order->id_address_delivery = $address->id;
- } elseif (Tools::isSubmit('submitAddressInvoice')) {
- $order->id_address_invoice = $address->id;
- }
- $order->update();
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- } else {
- $this->errors[] = Tools::displayErrror('This address can\'t be loaded');
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
- $old_currency = new Currency($order->id_currency);
- $currency = new Currency(Tools::getValue('new_currency'));
- if (!Validate::isLoadedObject($currency)) {
- throw new PrestaShopException('Can\'t load Currency object');
- }
- foreach ($order->getOrderDetailList() as $row) {
- $order_detail = new OrderDetail($row['id_order_detail']);
- $order_detail->product_price = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
- $order_detail->reduction_amount = Tools::convertPriceFull($order_detail->reduction_amount, $old_currency, $currency);
- $order_detail->unit_price_tax_incl = Tools::convertPriceFull($order_detail->unit_price_tax_incl, $old_currency, $currency);
- $order_detail->unit_price_tax_excl = Tools::convertPriceFull($order_detail->unit_price_tax_excl, $old_currency, $currency);
- $order_detail->total_price_tax_incl = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
- $order_detail->total_price_tax_excl = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
- $order_detail->group_reduction = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
- $order_detail->product_quantity_discount = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
- $order_detail->update();
- }
- $id_order_carrier = Db::getInstance()->getValue('
- SELECT `id_order_carrier`
- FROM `' . _DB_PREFIX_ . 'order_carrier`
- WHERE `id_order` = ' . (int) $order->id);
- $order_carrier = new OrderCarrier($id_order_carrier);
- $order_carrier->shipping_cost_tax_excl = (float) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
- $order_carrier->shipping_cost_tax_incl = (float) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
- $order_carrier->update();
- $order->total_discounts = Tools::convertPriceFull($order->total_discounts, $old_currency, $currency);
- $order->total_discounts_tax_incl = Tools::convertPriceFull($order->total_discounts_tax_incl, $old_currency, $currency);
- $order->total_discounts_tax_excl = Tools::convertPriceFull($order->total_discounts_tax_excl, $old_currency, $currency);
- $order->total_paid = Tools::convertPriceFull($order->total_paid, $old_currency, $currency);
- $order->total_paid_tax_incl = Tools::convertPriceFull($order->total_paid_tax_incl, $old_currency, $currency);
- $order->total_paid_tax_excl = Tools::convertPriceFull($order->total_discounts_tax_excl, $old_currency, $currency);
- $order->total_paid_real = Tools::convertPriceFull($order->total_paid_real, $old_currency, $currency);
- $order->total_products = Tools::convertPriceFull($order->total_products, $old_currency, $currency);
- $order->total_products_wt = Tools::convertPriceFull($order->total_products_wt, $old_currency, $currency);
- $order->total_shipping = Tools::convertPriceFull($order->total_shipping, $old_currency, $currency);
- $order->total_shipping_tax_incl = Tools::convertPriceFull($order->total_shipping_tax_incl, $old_currency, $currency);
- $order->total_shipping_tax_excl = Tools::convertPriceFull($order->total_shipping_tax_excl, $old_currency, $currency);
- $order->total_wrapping = Tools::convertPriceFull($order->total_wrapping, $old_currency, $currency);
- $order->total_wrapping_tax_incl = Tools::convertPriceFull($order->total_wrapping_tax_incl, $old_currency, $currency);
- $order->total_wrapping_tax_excl = Tools::convertPriceFull($order->total_wrapping_tax_excl, $old_currency, $currency);
- $order->id_currency = $currency->id;
- $order->update();
- } else {
- $this->errors[] = Tools::displayError('You cannot change the currency');
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
- if ($order->hasInvoice()) {
- $this->errors[] = Tools::displayError('This order already has an invoice');
- } else {
- $order->setInvoice();
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- }
- } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
- if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
- if ($order_cart_rule->id_order_invoice) {
- $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
- if (!Validate::isLoadedObject($order_invoice)) {
- throw new PrestaShopException('Can\'t load Order Invoice object');
- }
- $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
- $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
- $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
- $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
- $order_invoice->update();
- }
- $order->total_discounts -= $order_cart_rule->value;
- $order->total_discounts_tax_incl -= $order_cart_rule->value;
- $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
- $order->total_paid += $order_cart_rule->value;
- $order->total_paid_tax_incl += $order_cart_rule->value;
- $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
- $order_cart_rule->delete();
- $order->update();
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- } else {
- $this->errors[] = Tools::displayError('Cannot edit this Order Cart Rule');
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- } elseif (Tools::getValue('submitNewVoucher') && isset($order)) {
- if ($this->tabAccess['edit'] === '1') {
- if (!Tools::getValue('discount_name')) {
- $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount');
- } else {
- if ($order->hasInvoice()) {
- if (!Tools::isSubmit('discount_all_invoices')) {
- $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
- if (!Validate::isLoadedObject($order_invoice)) {
- throw new PrestaShopException('Can\'t load Order Invoice object');
- }
- }
- }
- $cart_rules = array();
- switch (Tools::getValue('discount_type')) {
- case 1:
- if (Tools::getValue('discount_value') < 100) {
- if (isset($order_invoice)) {
- $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
- $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- } elseif ($order->hasInvoice()) {
- $order_invoices_collection = $order->getInvoicesCollection();
- foreach ($order_invoices_collection as $order_invoice) {
- $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
- $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- }
- } else {
- $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
- $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
- }
- } else {
- $this->errors[] = Tools::displayError('Discount value is invalid');
- }
- break;
- case 2:
- if (isset($order_invoice)) {
- if (Tools::getValue('discount_value') > $order_invoice->total_paid_tax_incl) {
- $this->errors[] = Tools::displayError('Discount value is greater than the order invoice total');
- } else {
- $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
- $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- }
- } elseif ($order->hasInvoice()) {
- $order_invoices_collection = $order->getInvoicesCollection();
- foreach ($order_invoices_collection as $order_invoice) {
- if (Tools::getValue('discount_value') > $order_invoice->total_paid_tax_incl) {
- $this->errors[] = Tools::displayError('Discount value is greater than the order invoice total (Invoice:') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id) . ')';
- } else {
- $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
- $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- }
- }
- } else {
- if (Tools::getValue('discount_value') > $order->total_paid_tax_incl) {
- $this->errors[] = Tools::displayError('Discount value is greater than the order total');
- } else {
- $cart_rules[0]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
- $cart_rules[0]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
- }
- }
- break;
- case 3:
- if (isset($order_invoice)) {
- if ($order_invoice->total_shipping_tax_incl > 0) {
- $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
- $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- }
- } elseif ($order->hasInvoice()) {
- $order_invoices_collection = $order->getInvoicesCollection();
- foreach ($order_invoices_collection as $order_invoice) {
- if ($order_invoice->total_shipping_tax_incl <= 0) {
- continue;
- }
- $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
- $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
- $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
- }
- } else {
- $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
- $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
- }
- break;
- default:
- $this->errors[] = Tools::displayError('Discount type is invalid');
- break;
- }
- $res = TRUE;
- foreach ($cart_rules as &$cart_rule) {
- $cartRuleObj = new CartRule();
- $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
- $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
- $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
- $cartRuleObj->quantity = 0;
- $cartRuleObj->quantity_per_user = 1;
- if (Tools::getValue('discount_type') == 1) {
- $cartRuleObj->reduction_percent = Tools::getValue('discount_value');
- } elseif (Tools::getValue('discount_type') == 2) {
- $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
- } elseif (Tools::getValue('discount_type') == 3) {
- $cartRuleObj->free_shipping = 1;
- }
- $cartRuleObj->active = 0;
- if ($res = $cartRuleObj->add()) {
- $cart_rule['id'] = $cartRuleObj->id;
- } else {
- break;
- }
- }
- if ($res) {
- foreach ($cart_rules as $id_order_invoice => $cart_rule) {
- $order_cart_rule = new OrderCartRule();
- $order_cart_rule->id_order = $order->id;
- $order_cart_rule->id_cart_rule = $cart_rule['id'];
- $order_cart_rule->id_order_invoice = $id_order_invoice;
- $order_cart_rule->name = Tools::getValue('discount_name');
- $order_cart_rule->value = $cart_rule['value_tax_incl'];
- $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
- $res &= $order_cart_rule->add();
- $order->total_discounts += $order_cart_rule->value;
- $order->total_discounts_tax_incl += $order_cart_rule->value;
- $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
- $order->total_paid -= $order_cart_rule->value;
- $order->total_paid_tax_incl -= $order_cart_rule->value;
- $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
- }
- $res &= $order->update();
- }
- if ($res) {
- Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
- } else {
- $this->errors[] = Tools::displayError('An error occurred on OrderCartRule creation');
- }
- }
- } else {
- $this->errors[] = Tools::displayError('You do not have permission to edit here.');
- }
- }
- parent::postProcess();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement