Esempio n. 1
0
    public function setWsShippingNumber($shipping_number)
    {
        $id_order_carrier = Db::getInstance()->getValue('
			SELECT `id_order_carrier`
			FROM `' . _DB_PREFIX_ . 'order_carrier`
			WHERE `id_order` = ' . (int) $this->id);
        if ($id_order_carrier) {
            $order_carrier = new OrderCarrier($id_order_carrier);
            $order_carrier->tracking_number = $shipping_number;
            $order_carrier->update();
        } else {
            $this->shipping_number = $shipping_number;
        }
        return true;
    }
Esempio n. 2
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $history->changeIdOrderState((int) $order_state->id, $order, $use_existings_payment);
                     $carrier = new Carrier($order->id_carrier, $order->id_lang);
                     $templateVars = array();
                     if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                         $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                             foreach ($order->getProducts() as $product) {
                                 if (StockAvailable::dependsOnStock($product['product_id'])) {
                                     StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
Esempio n. 3
0
    /**
     * This method allows to generate first invoice of the current order
     */
    public function setInvoice($use_existing_payment = false)
    {
        if (Configuration::get('PS_INVOICE') && !$this->hasInvoice()) {
            if ($id = (int) $this->hasDelivery()) {
                $order_invoice = new OrderInvoice($id);
            } else {
                $order_invoice = new OrderInvoice();
            }
            $order_invoice->id_order = $this->id;
            if (!$id) {
                $order_invoice->number = 0;
            }
            $address = new Address((int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $carrier = new Carrier((int) $this->id_carrier);
            $tax_calculator = $carrier->getTaxCalculator($address);
            $order_invoice->total_discount_tax_excl = $this->total_discounts_tax_excl;
            $order_invoice->total_discount_tax_incl = $this->total_discounts_tax_incl;
            $order_invoice->total_paid_tax_excl = $this->total_paid_tax_excl;
            $order_invoice->total_paid_tax_incl = $this->total_paid_tax_incl;
            $order_invoice->total_products = $this->total_products;
            $order_invoice->total_products_wt = $this->total_products_wt;
            $order_invoice->total_shipping_tax_excl = $this->total_shipping_tax_excl;
            $order_invoice->total_shipping_tax_incl = $this->total_shipping_tax_incl;
            $order_invoice->shipping_tax_computation_method = $tax_calculator->computation_method;
            $order_invoice->total_wrapping_tax_excl = $this->total_wrapping_tax_excl;
            $order_invoice->total_wrapping_tax_incl = $this->total_wrapping_tax_incl;
            // Save Order invoice
            $order_invoice->save();
            $this->setLastInvoiceNumber($order_invoice->id, $this->id_shop);
            $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
            // Update order_carrier
            $id_order_carrier = Db::getInstance()->getValue('
				SELECT `id_order_carrier`
				FROM `' . _DB_PREFIX_ . 'order_carrier`
				WHERE `id_order` = ' . (int) $order_invoice->id_order . '
				AND (`id_order_invoice` IS NULL OR `id_order_invoice` = 0)');
            if ($id_order_carrier) {
                $order_carrier = new OrderCarrier($id_order_carrier);
                $order_carrier->id_order_invoice = (int) $order_invoice->id;
                $order_carrier->update();
            }
            // Update order detail
            Db::getInstance()->execute('
				UPDATE `' . _DB_PREFIX_ . 'order_detail`
				SET `id_order_invoice` = ' . (int) $order_invoice->id . '
				WHERE `id_order` = ' . (int) $order_invoice->id_order);
            // Update order payment
            if ($use_existing_payment) {
                $id_order_payments = Db::getInstance()->executeS('
					SELECT DISTINCT op.id_order_payment
					FROM `' . _DB_PREFIX_ . 'order_payment` op
					INNER JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.reference = op.order_reference)
					LEFT JOIN `' . _DB_PREFIX_ . 'order_invoice_payment` oip ON (oip.id_order_payment = op.id_order_payment)
					WHERE (oip.id_order != ' . (int) $order_invoice->id_order . ' OR oip.id_order IS NULL) AND o.id_order = ' . (int) $order_invoice->id_order);
                if (count($id_order_payments)) {
                    foreach ($id_order_payments as $order_payment) {
                        Db::getInstance()->execute('
							INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment`
							SET
								`id_order_invoice` = ' . (int) $order_invoice->id . ',
								`id_order_payment` = ' . (int) $order_payment['id_order_payment'] . ',
								`id_order` = ' . (int) $order_invoice->id_order);
                    }
                    // Clear cache
                    Cache::clean('order_invoice_paid_*');
                }
            }
            // Update order cart rule
            Db::getInstance()->execute('
				UPDATE `' . _DB_PREFIX_ . 'order_cart_rule`
				SET `id_order_invoice` = ' . (int) $order_invoice->id . '
				WHERE `id_order` = ' . (int) $order_invoice->id_order);
            // Keep it for backward compatibility, to remove on 1.6 version
            $this->invoice_date = $order_invoice->date_add;
            $this->invoice_number = $this->getInvoiceNumber($order_invoice->id);
            $this->update();
        }
    }
Esempio n. 4
0
 public function hookNewOrder($params)
 {
     $current_email = $this->context->customer->email;
     // Get value.
     $send24_consumer_key = Configuration::get('send24_consumer_key');
     $send24_consumer_secret = Configuration::get('send24_consumer_secret');
     // Get shipping value.
     $address = new Address($this->context->cart->id_address_delivery);
     $select_country = $this->express;
     // get/check Express.
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, "https://send24.com/wc-api/v3/get_products");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_USERPWD, $send24_consumer_key . ":" . $send24_consumer_secret);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
     $send24_countries = Tools::jsonDecode(curl_exec($ch));
     curl_close($ch);
     $n = count($send24_countries);
     for ($i = 0; $i < $n; $i++) {
         if ($send24_countries[$i]->title == $select_country) {
             $send24_product_id = $send24_countries[$i]->product_id;
             $i = $n;
             $is_available = true;
         } else {
             $is_available = false;
         }
     }
     if ($is_available == true) {
         $insurance_price = 0;
         $discount = "false";
         $ship_total = $type = $price_need = '';
         if ($select_country == $this->express) {
             $select_country = 'Danmark';
             $where_shop_id = 'ekspres';
         }
         // Create order.
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, "https://send24.com/wc-api/v3/create_order");
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HEADER, false);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_USERPWD, $send24_consumer_key . ":" . $send24_consumer_secret);
         curl_setopt($ch, CURLOPT_POSTFIELDS, '
                                         {
                                         "TO_company": "' . $address->company . '",
                                         "TO_first_name": "' . $address->firstname . '",
                                         "TO_last_name": "' . $address->lastname . '",
                                         "TO_phone": "' . $address->phone . '",
                                         "TO_email": "' . $current_email . '",
                                         "TO_country": "' . $select_country . '",
                                         "TO_city": "' . $address->city . '",
                                         "TO_postcode": "' . $address->postcode . '",
                                         "Insurance" : "' . $insurance_price . '",
                                         "Weight": "5",
                                         "TO_address": "' . $address->address1 . '",
                                         "WHAT_product_id": "' . $send24_product_id . '",
                                         "WHERE_shop_id": "' . $where_shop_id . '",
                                         "discount": "' . $discount . '",
                                         "type": "' . $type . '",
                                         "need_points": "' . $price_need . '",
                                         "total": "' . $ship_total . '",
                                         "ship_mail": "' . $current_email . '",
                                         "bill_mail": "' . $current_email . '"
                                         }
                                         ');
         curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
         $response = curl_exec($ch);
         $response_order = Tools::jsonDecode($response, JSON_FORCE_OBJECT);
         if (!empty($response_order)) {
             $tracking_number = explode('?', $response_order['track']);
             $objOrder = $params['order'];
             $history = new OrderHistory();
             $history->id_order = (int) $objOrder->id;
             $order_carrier = new OrderCarrier($history->id_order);
             $order_carrier->tracking_number = $tracking_number['1'];
             Db::getInstance()->insert('send24order_value', array('id_order' => (int) $history->id_order, 'order_number' => $response_order['order_number'], 'link_to_pdf' => $response_order['link_to_pdf'], 'link_to_doc' => $response_order['link_to_doc'], 'link_to_zpl' => $response_order['link_to_zpl'], 'link_to_epl' => $response_order['link_to_epl'], 'track' => $response_order['track'], 'date_add' => date('Y-m-d H:i:s')));
             $order_carrier->update();
         }
         // Delete Carriers.
         // self::deleteCarriers();
         foreach ($this->carriers as $value) {
             $carriers = new Carrier((int) Configuration::get(self::PREFIX . $value));
             $carriers->delay = array('1' => '(viser leveringstid i dag)');
             $carriers->deleted = 0;
             $carriers->update();
         }
         curl_close($ch);
     }
     return true;
 }
Esempio n. 5
0
 private function updateOrder($id_address, $id_method, Order &$order)
 {
     $id_carrier = $this->getIdcarrierFromIdMethod($id_method);
     if ($id_carrier && Validate::isLoadedObject(new Carrier($id_carrier))) {
         if ($order->id_address_delivery != $id_address || $order->id_carrier != $id_carrier || $order->shipping_number != $this->id_shipment) {
             $order->id_address_delivery = (int) $id_address;
             $order->id_carrier = (int) $id_carrier;
             if (version_compare(_PS_VERSION_, '1.5', '>=') && ($id_order_carrier = (int) $order->getIdOrderCarrier())) {
                 $order_carrier = new OrderCarrier((int) $id_order_carrier);
                 $order_carrier->id_carrier = $order->id_carrier;
                 $order_carrier->update();
             }
             if (!$order->update()) {
                 self::$errors[] = $this->l('Order could not be updated');
                 return false;
             }
         }
         return true;
     } else {
         self::$errors[] = $this->l('Carrier does not exists. Order could not be updated.');
         return false;
     }
 }
 public function renderList()
 {
     $this->toolbar_title = $this->l('Order Management');
     $statuses_array = array();
     $statuses = ErpOrderState::getOrderStates((int) $this->context->language->id);
     foreach ($statuses as $status) {
         $statuses_array[$status['id_order_state']] = $status['name'];
     }
     require_once _PS_MODULE_DIR_ . 'erpillicopresta/models/ErpFeature.php';
     $this->context->smarty->assign(array('token_mr' => ModuleCore::isEnabled('mondialrelay') ? MondialRelay::getToken('back') : 'false', 'token_expeditor' => ModuleCore::isEnabled('expeditor') ? Tools::getAdminToken('AdminExpeditor' . (int) Tab::getIdFromClassName('AdminExpeditor') . (int) $this->context->employee->id) : 'false', 'id_employee' => (int) $this->context->employee->id, 'order_statuses' => $statuses_array, 'controller_status' => $this->controller_status, 'erp_feature' => ErpFeature::getFeaturesWithToken($this->context->language->iso_code), 'template_path' => $this->template_path, 'expeditor_status' => Configuration::get('EXPEDITOR_STATE_EXP'), '_module_dir_' => _MODULE_DIR_));
     $this->tpl_list_vars['has_bulk_actions'] = 'true';
     // handle may contain error messages
     $handle = Tools::getValue('handle');
     switch (trim($handle)) {
         case '':
             break;
         case 'false':
             $this->confirmations[] = $this->l('All orders have been updated') . '<br/>';
             break;
         default:
             if (!empty($handle)) {
                 // $handle = str_replace('u00e9', 'é', $handle);
                 // $handle = str_replace('u00ea', 'ê', $handle);
                 $handle = Tools::replaceAccentedChars($handle);
                 // We take note about orders with error: no valid carrier (split on order number #)
                 $orderWithoutShipping = strstr($handle, '#') != false ? true : false;
                 $errors = explode('<br/>', str_replace('#', '<br/>', $handle));
                 foreach ($errors as $key => $error) {
                     if (!empty($error)) {
                         if (!$orderWithoutShipping) {
                             $message = $error;
                         } else {
                             $message = $error;
                         }
                         $this->errors[] = Tools::displayError($message);
                     }
                 }
             }
             break;
     }
     if (Tools::getValue('linkPDF') != '' && Tools::getValue('newState') != '') {
         // if state need invoice generation
         if (ErpOrderState::invoiceAvailable(Tools::getValue('newState'))) {
             $pdf_link = new Link();
             $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateInvoicesPDF3&id_orders=' . Tools::getValue('linkPDF');
             $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $pdf_link . '" alt="invoices">' . $this->l('Download all invoices') . '<br/></a>';
         }
         // if state need delivery slip generation
         if (ErpOrderState::deliverySlipAvailable(Tools::getValue('newState'))) {
             $pdf_link = new Link();
             $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateDeliverySlipsPDF2&id_orders=' . Tools::getValue('linkPDF');
             $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $pdf_link . '" alt="delivery">' . $this->l('Download all delivery slip') . '<br/></a>';
         }
     }
     if (Tools::getValue('linkPDFPrint') != '') {
         if ($this->controller_status == STATUS1 && count(explode(',', Tools::getValue('linkPDFPrint'))) > ERP_ORDERFR) {
             $this->informations[] = sprintf($this->l('You are using the free version of 1-Click ERP which limits the possible number of documents to print to %d orders'), ERP_ORDERFR);
         } else {
             $invoices = '';
             $delivery = '';
             foreach (explode(',', Tools::getValue('linkPDFPrint')) as $id_order) {
                 if (ErpOrderState::invoiceAvailable(ErpOrder::getIdStateByIdOrder($id_order))) {
                     $invoices .= $id_order . ',';
                 }
                 if (ErpOrderState::deliverySlipAvailable(ErpOrder::getIdStateByIdOrder($id_order))) {
                     $delivery .= $id_order . ',';
                 }
             }
             if ($invoices != '') {
                 $pdf_link = new Link();
                 $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateInvoicesPDF3&id_orders=' . Tools::substr($invoices, 0, -1);
                 $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $pdf_link . '" alt="invoices">' . $this->l('Download all invoices') . '</br></a>';
             }
             if ($delivery != '') {
                 $pdf_link = new Link();
                 $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateDeliverySlipsPDF2&id_orders=' . Tools::substr($delivery, 0, -1);
                 $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $pdf_link . '" alt="delivery">' . $this->l('Download all delivery slip') . '</br></a>';
             }
             if ($invoices == '' && $delivery == '') {
                 $this->errors[] = $this->l('The selected orders have no invoice or delivery !') . '<br/>';
             }
         }
     }
     if (Tools::getValue('etiquettesMR') != '') {
         // Downlad all pdf and zip then delete and display link to zip file
         $etiquettesMR = explode(' ', Tools::getValue('etiquettesMR'));
         unset($etiquettesMR[count($etiquettesMR) - 1]);
         $zipPath = '../modules/erpillicopresta/export/mondialrelay.zip';
         $zip = new ZipArchive();
         if ($zip->open($zipPath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
             throw new Exception($this->l('Impossible to create the zip archive containing the shipping labels to Mondial Relay carrier !') . '<br/>');
         }
         foreach ($etiquettesMR as $key => $i) {
             $zip->addFromString('mondialrelay_' . $key . '.pdf', Tools::file_get_contents($i));
         }
         $zip->close();
         //Display link to dl zip file
         $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $zipPath . '" alt="zip_file">' . $this->l('Download zip archive which contents all labels for Mondial Relay shipment') . '<br/></a>';
         if (Tools::getValue('deliveryNumbersMR') != '') {
             // Get all tracking numbers
             $numbers = explode(" ", Tools::getValue('deliveryNumbersMR'));
             unset($numbers[count($numbers) - 1]);
             foreach ($numbers as $number) {
                 $tabNumber = explode("-", $number);
                 $order_carrier = new OrderCarrier(ErpOrder::getIdCarrierbyIdOrder((int) $tabNumber[1]));
                 $order = new ErpOrder((int) $tabNumber[1]);
                 // Update carrier
                 $order->shipping_number = $tabNumber[0];
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL($tabNumber[0]);
                 $order_carrier->update();
             }
         }
     }
     if (Tools::getValue('expeditorCSV') != '') {
         // CSV file creation
         $csvPath = '../modules/erpillicopresta/export/expeditor_inet.csv';
         $fileCSV = fopen($csvPath, 'w');
         // Fill in file
         fwrite($fileCSV, str_replace(',', '', Tools::getValue('expeditorCSV')));
         //Close
         fclose($fileCSV);
         // link creation
         $this->confirmations[] = '&nbsp;<a target="_blank" href="' . $csvPath . '" alt="csv_file">' . $this->l('Download export file (CSV) for ExpeditorInet') . '</br></a>';
     }
     if (Tools::getValue('idOthers') != '') {
         //BEGIN Initialisations for TNT
         if (Module::isEnabled('tntcarrier')) {
             $TNTCheck = false;
             require_once _PS_MODULE_DIR_ . '/tntcarrier/classes/PackageTnt.php';
             if (class_exists('ZipArchive', false) && ($tnt_zip = new ZipArchive())) {
                 // Protection du ZIP
                 $dateday = new DateTime();
                 $uniqid_file = uniqid('file_');
                 $token = md5($dateday->getTimestamp() . $uniqid_file);
                 // Put all tnt pdf into a zip
                 $tnt_zip_path = 'erpillicopresta/export/tnt_' . date('Y-m-d_His') . '_' . $uniqid_file . $token . '.zip';
                 if ($tnt_zip->open(_PS_MODULE_DIR_ . $tnt_zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
                     $this->errors[] = Tools::displayError($this->l('Failed to create a ZIP archive containing the shipping labels to TNT carrier !') . '<br/>');
                 } else {
                     // one or several id orders
                     $id_others_order_array = strpos(Tools::getValue('idOthers'), ',') !== false ? explode(',', Tools::getValue('idOthers')) : (int) Tools::getValue('idOthers');
                     // Browse all orders not in ExpeditorInet nor MondialRelay
                     foreach ((array) $id_others_order_array as $i => $id_order) {
                         // BEGIN Commande TNT
                         $id_order = (int) $id_order;
                         if (ErpOrder::isTntOrder($id_order)) {
                             // status change
                             $currOrder = new ErpOrder($id_order);
                             $currOrder->setCurrentState(4, $this->context->employee->id);
                             // Start to check that weight order is valid if not tnt crash !
                             //echo($data['poid'] * 1000);die;
                             // Get tracking number : dedicated class created for this action
                             // Execution of the hook generating the tracking number at an order opening ... So ctrl c / ctrl v to execute here
                             /*$erp_tntCarrier = new ErpTntCarrier();
                               $generate = $erp_tntCarrier->generateShipping($id_order);*/
                             $generateShipping = Hook::exec('adminOrder', array('id_order' => $id_order));
                             $tnt = new PackageTnt($id_order);
                             $tntNumber = $tnt->getShippingNumber();
                             if (count($tntNumber) == 0) {
                                 $this->errors[] = Tools::displayError($this->l('Failed to get shipping number from TNT services : you have to fit the weight of the order.'));
                                 continue;
                             }
                             $tntNumber = $tntNumber[0]['shipping_number'];
                             // Update order
                             $order_carrier = new OrderCarrier(ErpOrder::getIdCarrierbyIdOrder((int) $id_order));
                             $order = new ErpOrder((int) $id_order);
                             $order->shipping_number = $tntNumber;
                             $order->update();
                             $order_carrier->tracking_number = pSQL($tntNumber);
                             $order_carrier->update();
                             // Add pdf to zip
                             $tnt_zip->addFile(_PS_MODULE_DIR_ . '/tntcarrier/pdf/' . $tntNumber . '.pdf', $tntNumber . '.pdf');
                             $TNTCheck = true;
                         }
                         // END Order TNT
                         // SPLICE  idOther
                         if (is_array($id_others_order_array)) {
                             unset($id_others_order_array[$i]);
                         } else {
                             unset($id_others_order_array);
                         }
                     }
                     //Display dl zip link
                     $tnt_zip->close();
                     if ($TNTCheck) {
                         $this->confirmations[] = '&nbsp;<a target="_blank" href="' . _MODULE_DIR_ . $tnt_zip_path . '" alt="zip_file">' . $this->l('Download zip archive which contents all labels for TNT shipment') . '<br/></a>';
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError($this->l('Class ZipArchive does not exist !') . '<br/>');
             }
             //END Initialisations for TNT
         }
         // Display for order not  processed  : idothers
         if (isset($id_others_order_array)) {
             if (count($id_others_order_array) == 1) {
                 //var_dump($id_others_order_array);die();
                 if (is_array($id_others_order_array)) {
                     $id_others_order_array = $id_others_order_array[1];
                 }
                 $this->errors[] = Tools::displayError($this->l('The following order has not been processed : order #') . $id_others_order_array . '. ' . $this->l('Please make sure that the carrier is either TNT, ExpeditorInet, or MondialRelay and that the order fits the carrier requirements.'));
             } elseif (count($id_others_order_array) > 1) {
                 $this->errors[] = Tools::displayError($this->l('The following orders have not been processed : orders #') . implode(", ", $id_others_order_array) . '. ' . $this->l('Please make sure that the carrier is either TNT, ExpeditorInet, or MondialRelay and that the orders fit the carrier requirements.'));
             }
         }
     }
     return parent::renderList();
 }
 public function processChangeCarrier()
 {
     $id_order = (int) Tools::getValue('id_o');
     $id_new_carrier = (int) Tools::getValue('new_carrier');
     $price_incl = (double) Tools::getValue('pr_incl');
     $price_excl = (double) Tools::getValue('pr_excl');
     $order = new Order($id_order);
     $result = array();
     $result['error'] = '';
     if ($id_new_carrier == 0) {
         $result['error'] = $this->l('Error: cannot select carrier');
     } else {
         if ($order->id < 1) {
             $result['error'] = $this->l('Error: cannot find order');
         } else {
             $total_carrierwt = (double) $order->total_products_wt + (double) $price_incl;
             $total_carrier = (double) $order->total_products + (double) $price_excl;
             $order->total_paid = (double) $total_carrierwt;
             $order->total_paid_tax_incl = (double) $total_carrierwt;
             $order->total_paid_tax_excl = (double) $total_carrier;
             $order->total_paid_real = (double) $total_carrierwt;
             $order->total_shipping = (double) $price_incl;
             $order->total_shipping_tax_excl = (double) $price_excl;
             $order->total_shipping_tax_incl = (double) $price_incl;
             $order->carrier_tax_rate = (double) $order->carrier_tax_rate;
             $order->id_carrier = (int) $id_new_carrier;
             if (!$order->update()) {
                 $result['error'] = $this->l('Error: cannot update order');
                 $result['status'] = false;
             } else {
                 if ($order->invoice_number > 0) {
                     $order_invoice = new OrderInvoice($order->invoice_number);
                     $order_invoice->total_paid_tax_incl = (double) $total_carrierwt;
                     $order_invoice->total_paid_tax_excl = (double) $total_carrier;
                     $order_invoice->total_shipping_tax_excl = (double) $price_excl;
                     $order_invoice->total_shipping_tax_incl = (double) $price_incl;
                     if (!$order_invoice->update()) {
                         $result['error'] = $this->l('Error: cannot update order invoice');
                         $result['status'] = false;
                     }
                 }
                 $id_order_carrier = Db::getInstance()->getValue('
                         SELECT `id_order_carrier`
                         FROM `' . _DB_PREFIX_ . 'order_carrier`
                         WHERE `id_order` = ' . (int) $order->id);
                 if ($id_order_carrier) {
                     $order_carrier = new OrderCarrier($id_order_carrier);
                     $order_carrier->id_carrier = $order->id_carrier;
                     $order_carrier->shipping_cost_tax_excl = (double) $price_excl;
                     $order_carrier->shipping_cost_tax_incl = (double) $price_incl;
                     if (!$order_carrier->update()) {
                         $result['error'] = $this->l('Error: cannot update order carrier');
                         $result['status'] = false;
                     }
                 }
                 $result['status'] = true;
             }
         }
     }
     if ($result['status']) {
         $this->sendCarrierToYandex($order);
     }
     return $result;
 }
Esempio n. 8
0
    public function getShippingLabel($id_order)
    {
        if (is_array($this->_response['errors']) && !count($this->_response['errors'])) {
            $this->_request = $this->buildLabelRequest();
            $error_code = null;
            do {
                $this->_post_response = $this->curl_post($this->_dhl_post_url, $this->_request);
                $this->_xml = @simplexml_load_string($this->_post_response);
                if ($this->_xml === false) {
                    $this->_xml = @simplexml_load_string(utf8_encode($this->_post_response));
                }
                $error_code = @$this->_xml->GetCapabilityResponse->Note->Condition->ConditionCode;
                $date = date('Y-m-d', strtotime('+1 day', strtotime(date('Y-m-d'))));
            } while ($error_code == '1003');
            //do while error will be non "Pick-up service is not provided on this day."
            /** IF TIME OUT ERROR */
            if ($this->_post_response == 28) {
                $this->_error = $this->l('[Error #28] Time out error. The request took more than the time limit of execution');
                $this->_error = array(0, $this->_error);
            } elseif ($this->_xml->Response->Status->Condition) {
                $this->_error = strlen($this->_xml->Response->Status->Condition->ConditionData) ? $this->_xml->Response->Status->Condition->ConditionData : $this->_xml->Response->Status->Condition->ConditionCode;
                $this->_error = array(0, $this->_error);
            } else {
                $this->_response[] = $this->_xml;
                $this->_trackingIdType = $this->_dhl_label_infos['ShippingType'];
                //the same for all packages, shipping method
                $this->_tracking_numbers[] = (string) $this->_xml->Pieces->Piece->LicensePlate;
            }
        } else {
            $this->_response[0] = 0;
            return $this->_response;
        }
        //if some request failed but before it were successful requests, we need to cancel all successful requests
        if ($this->_error) {
            return $this->_error;
        }
        //if success
        if ((int) $this->_dhl_label_order_status > 0) {
            $history = new OrderHistory();
            $history->id_order = (int) $id_order;
            $history->changeIdOrderState($this->_dhl_label_order_status, $id_order);
            $history->addWithemail();
        }
        //saving tracking number
        $order = new Order($id_order);
        $order->shipping_number = implode(', ', $this->_tracking_numbers);
        $order->update();
        $id_order_carrier = Db::getInstance()->getValue('
			 SELECT `id_order_carrier`
			 FROM `' . _DB_PREFIX_ . 'order_carrier`
			 WHERE `id_order` = ' . (int) $order->id);
        if ($id_order_carrier) {
            $order_carrier = new OrderCarrier($id_order_carrier);
            $order_carrier->tracking_number = implode(', ', $this->_tracking_numbers);
            $order_carrier->update();
        }
        //sending email to customer
        if ($order->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('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id);
            if ($this->getPSV() == 1.6) {
                $templateVars['{order_name}'] = $order->getUniqReference();
            }
            @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);
        }
        $this->_tracking_numbers = serialize($this->_tracking_numbers);
        Db::getInstance()->execute('
			UPDATE `' . _DB_PREFIX_ . 'fe_dhl_labels_info`
			SET `tracking_id_type` = \'' . pSQL($this->_trackingIdType) . '\', `tracking_numbers` = \'' . $this->_tracking_numbers . '\'
			WHERE `id_order` = ' . (int) $id_order . '
		');
        return array(1, $this->_response);
    }
Esempio n. 9
0
    /**
     * This method allows to generate first invoice of the current order
     */
    public function setInvoice($use_existing_payment = false)
    {
        if (!$this->hasInvoice()) {
            $order_invoice = new OrderInvoice();
            $order_invoice->id_order = $this->id;
            $order_invoice->number = Configuration::get('PS_INVOICE_START_NUMBER');
            // If invoice start number has been set, you clean the value of this configuration
            if ($order_invoice->number) {
                Configuration::updateValue('PS_INVOICE_START_NUMBER', false);
            } else {
                $order_invoice->number = Order::getLastInvoiceNumber() + 1;
            }
            $invoice_address = new Address((int) $this->id_address_invoice);
            $carrier = new Carrier((int) $this->id_carrier);
            $tax_calculator = $carrier->getTaxCalculator($invoice_address);
            $order_invoice->total_discount_tax_excl = $this->total_discounts_tax_excl;
            $order_invoice->total_discount_tax_incl = $this->total_discounts_tax_incl;
            $order_invoice->total_paid_tax_excl = $this->total_paid_tax_excl;
            $order_invoice->total_paid_tax_incl = $this->total_paid_tax_incl;
            $order_invoice->total_products = $this->total_products;
            $order_invoice->total_products_wt = $this->total_products_wt;
            $order_invoice->total_shipping_tax_excl = $this->total_shipping_tax_excl;
            $order_invoice->total_shipping_tax_incl = $this->total_shipping_tax_incl;
            $order_invoice->shipping_tax_computation_method = $tax_calculator->computation_method;
            $order_invoice->total_wrapping_tax_excl = $this->total_wrapping_tax_excl;
            $order_invoice->total_wrapping_tax_incl = $this->total_wrapping_tax_incl;
            // Save Order invoice
            $order_invoice->add();
            $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
            // Update order_carrier
            $id_order_carrier = Db::getInstance()->getValue('
				SELECT `id_order_carrier`
				FROM `' . _DB_PREFIX_ . 'order_carrier`
				WHERE `id_order` = ' . (int) $order_invoice->id_order . '
				AND (`id_order_invoice` IS NULL OR `id_order_invoice` = 0)');
            if ($id_order_carrier) {
                $order_carrier = new OrderCarrier($id_order_carrier);
                $order_carrier->id_order_invoice = (int) $order_invoice->id;
                $order_carrier->update();
            }
            // Update order detail
            Db::getInstance()->execute('
				UPDATE `' . _DB_PREFIX_ . 'order_detail`
				SET `id_order_invoice` = ' . (int) $order_invoice->id . '
				WHERE `id_order` = ' . (int) $order_invoice->id_order);
            // Update order payment
            if ($use_existing_payment) {
                $id_order_payments = Db::getInstance()->executeS('
					SELECT op.id_order_payment 
					FROM `' . _DB_PREFIX_ . 'order_payment` op
					INNER JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.reference = op.order_reference)
					LEFT JOIN `' . _DB_PREFIX_ . 'order_invoice_payment` oip ON (oip.id_order_payment = op.id_order_payment)					
					WHERE oip.id_order_payment IS NULL AND o.id_order = ' . (int) $order_invoice->id_order);
                if (count($id_order_payments)) {
                    foreach ($id_order_payments as $order_payment) {
                        Db::getInstance()->execute('
							INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment`
							SET
								`id_order_invoice` = ' . (int) $order_invoice->id . ',
								`id_order_payment` = ' . (int) $order_payment['id_order_payment'] . ',
								`id_order` = ' . (int) $order_invoice->id_order);
                    }
                }
            }
            // Update order cart rule
            Db::getInstance()->execute('
				UPDATE `' . _DB_PREFIX_ . 'order_cart_rule`
				SET `id_order_invoice` = ' . (int) $order_invoice->id . '
				WHERE `id_order` = ' . (int) $order_invoice->id_order);
            // Keep it for backward compatibility, to remove on 1.6 version
            $this->invoice_date = $order_invoice->date_add;
            $this->invoice_number = $order_invoice->number;
            $this->update();
        }
    }
Esempio n. 10
0
    public static function trackingStatus($id_order, $shipping_number)
    {
        // MAIL::SEND is bugged in 1.5 !
        // http://forge.prestashop.com/browse/PNM-754 (Unresolved as of 2013-04-15)
        // Context fix (it's that easy)
        Context::getContext()->link = new Link();
        // Fix context by adding employee
        $cookie = new Cookie('psAdmin');
        Context::getContext()->employee = new Employee($cookie->id_employee);
        $o = new Order($id_order);
        $o->shipping_number = $shipping_number;
        $o->save();
        // New in 1.5
        $id_order_carrier = Db::getInstance()->getValue('
				SELECT `id_order_carrier`
				FROM `' . _DB_PREFIX_ . 'order_carrier`
				WHERE `id_order` = ' . (int) $id_order);
        $order_carrier = new OrderCarrier($id_order_carrier);
        $order_carrier->tracking_number = $shipping_number;
        $order_carrier->id_order = $id_order;
        $order_carrier->id_carrier = $o->id_carrier;
        $order_carrier->update();
        // No, there is no method in Order to retrieve the orderCarrier object(s)
        $history = new OrderHistory();
        $history->id_order = (int) $o->id;
        $history->id_order_state = _PS_OS_SHIPPING_;
        $history->changeIdOrderState(_PS_OS_SHIPPING_);
        $history->save();
        $customer = new Customer($o->id_customer);
        $carrier = new Carrier($o->id_carrier);
        $tracking_url = str_replace('@', $o->shipping_number, $carrier->url);
        $templateVars = array('{tracking_link}' => '<a href = "' . $tracking_url . '">' . $o->shipping_number . '</a>', '{tracking_code}' => $o->shipping_number, '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $o->id);
        Mail::Send($o->id_lang, 'tracking', 'Tracking number for your order', $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _MYDIR_ . '/mails/', true);
    }
Esempio n. 11
0
 /**
  * Re calculate shipping cost
  * @return object $order
  */
 public function refreshShippingCost()
 {
     if (empty($this->id)) {
         return false;
     }
     if (!Configuration::get('PS_ORDER_RECALCULATE_SHIPPING')) {
         return $this;
     }
     $fake_cart = new Cart((int) $this->id_cart);
     $new_cart = $fake_cart->duplicate();
     $new_cart = $new_cart['cart'];
     // assign order id_address_delivery to cart
     $new_cart->id_address_delivery = (int) $this->id_address_delivery;
     // assign id_carrier
     $new_cart->id_carrier = (int) $this->id_carrier;
     //remove all products : cart (maybe change in the meantime)
     foreach ($new_cart->getProducts() as $product) {
         $new_cart->deleteProduct((int) $product['id_product'], (int) $product['id_product_attribute']);
     }
     // add real order products
     foreach ($this->getProducts() as $product) {
         $new_cart->updateQty($product['product_quantity'], (int) $product['product_id']);
     }
     // get new shipping cost
     $base_total_shipping_tax_incl = (double) $new_cart->getPackageShippingCost((int) $new_cart->id_carrier, true, null);
     $base_total_shipping_tax_excl = (double) $new_cart->getPackageShippingCost((int) $new_cart->id_carrier, false, null);
     // calculate diff price, then apply new order totals
     $diff_shipping_tax_incl = $this->total_shipping_tax_incl - $base_total_shipping_tax_incl;
     $diff_shipping_tax_excl = $this->total_shipping_tax_excl - $base_total_shipping_tax_excl;
     $this->total_shipping_tax_excl = $this->total_shipping_tax_excl - $diff_shipping_tax_excl;
     $this->total_shipping_tax_incl = $this->total_shipping_tax_incl - $diff_shipping_tax_incl;
     $this->total_shipping = $this->total_shipping_tax_incl;
     $this->total_paid_tax_excl = $this->total_paid_tax_excl - $diff_shipping_tax_excl;
     $this->total_paid_tax_incl = $this->total_paid_tax_incl - $diff_shipping_tax_incl;
     $this->total_paid = $this->total_paid_tax_incl;
     $this->update();
     // save order_carrier prices, we'll save order right after this in update() method
     $order_carrier = new OrderCarrier((int) $this->getIdOrderCarrier());
     $order_carrier->shipping_cost_tax_excl = $this->total_shipping_tax_excl;
     $order_carrier->shipping_cost_tax_incl = $this->total_shipping_tax_incl;
     $order_carrier->update();
     // remove fake cart
     $new_cart->delete();
     return $this;
 }