Exemple #1
0
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] == 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
         } else {
             $product['warehouse_name'] = '--';
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'));
     return parent::renderView();
 }
 /**
  * Hook called when order status changed
  * register a discount for sponsor and send him an e-mail
  */
 public function hookUpdateOrderStatus($params)
 {
     if (!Validate::isLoadedObject($params['newOrderStatus'])) {
         die($this->l('Missing parameters'));
     }
     $orderState = $params['newOrderStatus'];
     $order = new Order((int) $params['id_order']);
     if ($order and !Validate::isLoadedObject($order)) {
         die($this->l('Incorrect Order object.'));
     }
     include_once dirname(__FILE__) . '/ReferralProgramModule.php';
     $customer = new Customer((int) $order->id_customer);
     $stats = $customer->getStats();
     $nbOrdersCustomer = (int) $stats['nb_orders'] + 1;
     // hack to count current order
     $referralprogram = new ReferralProgramModule(ReferralProgramModule::isSponsorised((int) $customer->id, true));
     if (!Validate::isLoadedObject($referralprogram)) {
         return false;
     }
     $sponsor = new Customer((int) $referralprogram->id_sponsor);
     if ((int) $orderState->logable and $nbOrdersCustomer >= (int) $this->_configuration['REFERRAL_ORDER_QUANTITY'] and $referralprogram->registerDiscountForSponsor((int) $order->id_currency)) {
         $cartRule = new CartRule((int) $referralprogram->id_cart_rule_sponsor);
         $currency = new Currency((int) $order->id_currency);
         $discount_display = ReferralProgram::displayDiscount($cartRule->reduction_percent ? $cartRule->reduction_percent : $cartRule->reduction_amount, $cartRule->reduction_percent ? 1 : 2, $currency);
         $data = array('{sponsored_firstname}' => $customer->firstname, '{sponsored_lastname}' => $customer->lastname, '{discount_display}' => $discount_display, '{discount_name}' => $cartRule->code);
         Mail::Send((int) $order->id_lang, 'referralprogram-congratulations', Mail::l('Congratulations!', (int) $order->id_lang), $data, $sponsor->email, $sponsor->firstname . ' ' . $sponsor->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
         return true;
     }
     return false;
 }
Exemple #3
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     // get discount value (ready to display)
     $discount_type = (int) Configuration::get('REFERRAL_DISCOUNT_TYPE');
     if ($discount_type == 1) {
         $discount = Discount::display((double) Configuration::get('REFERRAL_PERCENTAGE'), $discount_type, new Currency($this->context->currency->id));
     } else {
         $discount = Discount::display((double) Configuration::get('REFERRAL_DISCOUNT_VALUE_' . (int) $this->context->currency->id), $discount_type, new Currency($this->context->currency->id));
     }
     $activeTab = 'sponsor';
     $error = false;
     // Mailing invitation to friend sponsor
     $invitation_sent = false;
     $nbInvitation = 0;
     if (Tools::isSubmit('submitSponsorFriends') and Tools::getValue('friendsEmail') and sizeof($friendsEmail = Tools::getValue('friendsEmail')) >= 1) {
         $activeTab = 'sponsor';
         if (!Tools::getValue('conditionsValided')) {
             $error = 'conditions not valided';
         } else {
             $friendsLastName = Tools::getValue('friendsLastName');
             $friendsFirstName = Tools::getValue('friendsFirstName');
             $mails_exists = array();
             foreach ($friendsEmail as $key => $friendEmail) {
                 $friendEmail = strval($friendEmail);
                 $friendLastName = strval($friendsLastName[$key]);
                 $friendFirstName = strval($friendsFirstName[$key]);
                 if (empty($friendEmail) and empty($friendLastName) and empty($friendFirstName)) {
                     continue;
                 } elseif (empty($friendEmail) or !Validate::isEmail($friendEmail)) {
                     $error = 'email invalid';
                 } elseif (empty($friendFirstName) or empty($friendLastName) or !Validate::isName($friendLastName) or !Validate::isName($friendFirstName)) {
                     $error = 'name invalid';
                 } elseif (ReferralProgramModule::isEmailExists($friendEmail) or Customer::customerExists($friendEmail)) {
                     $mails_exists[] = $friendEmail;
                 } else {
                     $referralprogram = new ReferralProgramModule();
                     $referralprogram->id_sponsor = (int) $this->context->customer->id;
                     $referralprogram->firstname = $friendFirstName;
                     $referralprogram->lastname = $friendLastName;
                     $referralprogram->email = $friendEmail;
                     if (!$referralprogram->validateFields(false)) {
                         $error = 'name invalid';
                     } else {
                         if ($referralprogram->save()) {
                             if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                                 $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                             } else {
                                 $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                             }
                             $vars = array('{email}' => strval($this->context->customer->email), '{lastname}' => strval($this->context->customer->lastname), '{firstname}' => strval($this->context->customer->firstname), '{email_friend}' => $friendEmail, '{lastname_friend}' => $friendLastName, '{firstname_friend}' => $friendFirstName, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                             Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $friendEmail, $friendFirstName . ' ' . $friendLastName, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                             $invitation_sent = true;
                             $nbInvitation++;
                             $activeTab = 'pending';
                         } else {
                             $error = 'cannot add friends';
                         }
                     }
                 }
                 if ($error) {
                     break;
                 }
             }
             if ($nbInvitation > 0) {
                 unset($_POST);
             }
             //Not to stop the sending of e-mails in case of doubloon
             if (sizeof($mails_exists)) {
                 $error = 'email exists';
             }
         }
     }
     // Mailing revive
     $revive_sent = false;
     $nbRevive = 0;
     if (Tools::isSubmit('revive')) {
         $activeTab = 'pending';
         if (Tools::getValue('friendChecked') and sizeof($friendsChecked = Tools::getValue('friendChecked')) >= 1) {
             foreach ($friendsChecked as $key => $friendChecked) {
                 if (ReferralProgramModule::isSponsorFriend((int) $this->context->customer->id, (int) $friendChecked)) {
                     if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                         $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                     } else {
                         $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                     }
                     $referralprogram = new ReferralProgramModule((int) $key);
                     $vars = array('{email}' => $this->context->customer->email, '{lastname}' => $this->context->customer->lastname, '{firstname}' => $this->context->customer->firstname, '{email_friend}' => $referralprogram->email, '{lastname_friend}' => $referralprogram->lastname, '{firstname_friend}' => $referralprogram->firstname, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                     $referralprogram->save();
                     Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $referralprogram->email, $referralprogram->firstname . ' ' . $referralprogram->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                     $revive_sent = true;
                     $nbRevive++;
                 }
             }
         } else {
             $error = 'no revive checked';
         }
     }
     $customer = new Customer((int) $this->context->customer->id);
     $stats = $customer->getStats();
     $orderQuantity = (int) Configuration::get('REFERRAL_ORDER_QUANTITY');
     $canSendInvitations = false;
     if ((int) $stats['nb_orders'] >= $orderQuantity) {
         $canSendInvitations = true;
     }
     // Smarty display
     $this->context->smarty->assign(array('activeTab' => $activeTab, 'discount' => $discount, 'orderQuantity' => $orderQuantity, 'canSendInvitations' => $canSendInvitations, 'nbFriends' => (int) Configuration::get('REFERRAL_NB_FRIENDS'), 'error' => $error, 'invitation_sent' => $invitation_sent, 'nbInvitation' => $nbInvitation, 'pendingFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'pending'), 'revive_sent' => $revive_sent, 'nbRevive' => $nbRevive, 'subscribeFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'subscribed'), 'mails_exists' => isset($mails_exists) ? $mails_exists : array()));
     $this->setTemplate('program.tpl');
 }
 public function renderView()
 {
     if (!($cart = $this->loadObject(true))) {
         return;
     }
     $customer = new Customer($cart->id_customer);
     $currency = new Currency($cart->id_currency);
     $this->context->cart = $cart;
     $this->context->currency = $currency;
     $this->context->customer = $customer;
     $this->toolbar_title = sprintf($this->l('Cart #%06d'), $this->context->cart->id);
     $products = $cart->getProducts();
     $customized_datas = Product::getAllCustomizedDatas((int) $cart->id);
     Product::addCustomizationPrice($products, $customized_datas);
     $summary = $cart->getSummaryDetails();
     /* Display order information */
     $id_order = (int) Order::getOrderByCartId($cart->id);
     $order = new Order($id_order);
     if (Validate::isLoadedObject($order)) {
         $tax_calculation_method = $order->getTaxCalculationMethod();
         $id_shop = (int) $order->id_shop;
     } else {
         $id_shop = (int) $cart->id_shop;
         $tax_calculation_method = Group::getPriceDisplayMethod(Group::getCurrent()->id);
     }
     if ($tax_calculation_method == PS_TAX_EXC) {
         $total_products = $summary['total_products'];
         $total_discounts = $summary['total_discounts_tax_exc'];
         $total_wrapping = $summary['total_wrapping_tax_exc'];
         $total_price = $summary['total_price_without_tax'];
         $total_shipping = $summary['total_shipping_tax_exc'];
     } else {
         $total_products = $summary['total_products_wt'];
         $total_discounts = $summary['total_discounts'];
         $total_wrapping = $summary['total_wrapping'];
         $total_price = $summary['total_price'];
         $total_shipping = $summary['total_shipping'];
     }
     foreach ($products as $k => &$product) {
         if ($tax_calculation_method == PS_TAX_EXC) {
             $product['product_price'] = $product['price'];
             $product['product_total'] = $product['total'];
         } else {
             $product['product_price'] = $product['price_wt'];
             $product['product_total'] = $product['total_wt'];
         }
         $image = array();
         if (isset($product['id_product_attribute']) && (int) $product['id_product_attribute']) {
             $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'product_attribute_image WHERE id_product_attribute = ' . (int) $product['id_product_attribute']);
         }
         if (!isset($image['id_image'])) {
             $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'image WHERE id_product = ' . (int) $product['id_product'] . ' AND cover = 1');
         }
         $product_obj = new Product($product['id_product']);
         $product['qty_in_stock'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], isset($product['id_product_attribute']) ? $product['id_product_attribute'] : null, (int) $id_shop);
         $image_product = new Image($image['id_image']);
         $product['image'] = isset($image['id_image']) ? ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $image_product->getExistingImgPath() . '.jpg', 'product_mini_' . (int) $product['id_product'] . (isset($product['id_product_attribute']) ? '_' . (int) $product['id_product_attribute'] : '') . '.jpg', 45, 'jpg') : '--';
     }
     $helper = new HelperKpi();
     $helper->id = 'box-kpi-cart';
     $helper->icon = 'icon-shopping-cart';
     $helper->color = 'color1';
     $helper->title = $this->l('Total Cart', null, null, false);
     $helper->subtitle = sprintf($this->l('Cart #%06d', null, null, false), $cart->id);
     $helper->value = Tools::displayPrice($total_price, $currency);
     $kpi = $helper->generate();
     $this->tpl_view_vars = array('kpi' => $kpi, 'products' => $products, 'discounts' => $cart->getCartRules(), 'order' => $order, 'cart' => $cart, 'currency' => $currency, 'customer' => $customer, 'customer_stats' => $customer->getStats(), 'total_products' => $total_products, 'total_discounts' => $total_discounts, 'total_wrapping' => $total_wrapping, 'total_price' => $total_price, 'total_shipping' => $total_shipping, 'customized_datas' => $customized_datas);
     return parent::renderView();
 }
 private function buildXMLOrder($id_order)
 {
     CertissimLogger::insertLog(__METHOD__ . ' : ' . __LINE__, 'construction du flux pour order ' . $id_order);
     $order = new Order($id_order);
     //gets back the delivery address
     $address_delivery = new Address((int) $order->id_address_delivery);
     //gets back the invoice address
     $address_invoice = new Address((int) $order->id_address_invoice);
     //gets back the customer
     $customer = new Customer((int) $order->id_customer);
     //initializatino of the XML root: <control>
     $xml_element_control = new CertissimControl();
     //gets the lang used in the order
     $id_lang = $order->id_lang;
     //sets the gender, depends on PS version
     if (_PS_VERSION_ < '1.5') {
         $gender = $customer->id_gender == 2 ? $this->l('Ms.') : $this->l('Mr.');
     } else {
         $customer_gender = new Gender($customer->id_gender);
         $lang_id = Language::getIdByIso('en');
         if (empty($lang_id)) {
             $lang_id = Language::getIdByIso('fr');
         }
         CertissimLogger::insertLog(__METHOD__ . ' : ' . __LINE__, "id_gender = " . $customer->id_gender . ", gender name =" . $customer_gender->name[$lang_id]);
         $gender = $this->l($customer_gender->name[$lang_id]);
     }
     //initialization of the element <utilisateur type='facturation'...>
     $xml_element_invoice_customer = new CertissimUtilisateur('facturation', $gender, $address_invoice->lastname, $address_invoice->firstname, $address_invoice->company, $address_invoice->phone, $address_invoice->phone_mobile, null, $customer->email);
     //gets customer stats
     $customer_stats = $customer->getStats();
     //gets already existing orders for the customer
     $all_orders = Order::getCustomerOrders((int) $customer->id);
     //initialization of the element <siteconso>
     $xml_element_invoice_customer_stats = new CertissimSiteconso($customer_stats['total_orders'], $customer_stats['nb_orders'], $all_orders[count($all_orders) - 1]['date_add'], count($all_orders) > 1 ? $all_orders[1]['date_add'] : null);
     //gets back the invoice country
     $country = new Country((int) $address_invoice->id_country);
     //initialization of the element <adresse type="facturation" ...>
     $xml_element_invoice_address = new CertissimAdresse('facturation', $address_invoice->address1, $address_invoice->address2, $address_invoice->postcode, $address_invoice->city, $country->name[$id_lang]);
     //gets back the carrier used for this order
     $carrier = new Carrier((int) $order->id_carrier);
     //gets the carrier certissim type
     if (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
         $carrier_type = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE', null, null, $order->id_shop);
     } else {
         $carrier_type = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE');
     }
     //if the order is to be delivered at home: element <utilisateur type="livraison"...> has to be added
     if ($carrier_type == 4) {
         //initialization of the element <utilisateur type="livraison" ...>
         $xml_element_delivery_customer = new CertissimUtilisateur('livraison', $customer->id_gender == 2 ? $this->l('Miss') : $this->l('Mister'), $address_delivery->lastname, $address_delivery->firstname, $address_delivery->company, $address_delivery->phone, $address_delivery->phone_mobile, null, $customer->email);
         //gets back the delivery country
         $country = new Country((int) $address_delivery->id_country);
         //initialization of the element <adresse type="livraison" ...>
         $xml_element_delivery_address = new CertissimAdresse('livraison', $address_delivery->address1, $address_delivery->address2, $address_delivery->postcode, $address_delivery->city, $country->name[$id_lang], null);
     }
     //gets the used currency
     $currency = new Currency((int) $order->id_currency);
     if (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
         $siteid = Configuration::get('CERTISSIM_SITEID', null, null, $order->id_shop);
     } else {
         $siteid = Configuration::get('CERTISSIM_SITEID');
     }
     //initialize the element <infocommande>
     $xml_element_order_details = new CertissimInfocommande($siteid, $order->id, (string) $order->total_paid, self::getIpByOrder((int) $order->id), date('Y-m-d H:i:s'), $currency->iso_code);
     //gets the order products
     $products = $order->getProducts();
     //define the default product type (depends on PS version)
     if (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
         $default_product_type = Configuration::get('CERTISSIM_DEFAULT_PRODUCT_TYPE', null, null, $order->id_shop);
     } else {
         $default_product_type = Configuration::get('CERTISSIM_DEFAULT_PRODUCT_TYPE');
     }
     //initialization of the element <list ...>
     $xml_element_products_list = new CertissimProductList();
     //initialize the boolean that says if all the products in the order are downloadables
     $alldownloadables = true;
     foreach ($products as $product) {
         //check if the visited product is downloadable and update the boolean value
         $alldownloadables = $alldownloadables && strlen($product['download_hash']) > 0;
         //gets the main product category
         $product_categories = Product::getProductCategories((int) $product['product_id']);
         $product_category = array_pop($product_categories);
         //initilization of the element <produit ...>
         $xml_element_product = new CertissimXMLElement("<produit></produit>");
         //gets the product certissim category (depends on PS version)
         if (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
             $product_type = Configuration::get('CERTISSIM' . $product_category . '_PRODUCT_TYPE', null, null, $order->id_shop);
         } else {
             $product_type = Configuration::get('CERTISSIM' . $product_category . '_PRODUCT_TYPE');
         }
         //if a certissim category is set: the type attribute takes the product certissim type value
         if ($product_type) {
             $xml_element_product->addAttribute('type', Configuration::get('CERTISSIM' . $product_category . '_PRODUCT_TYPE', null, null, $order->id_shop));
         } else {
             //if certissim category not set: the type attribute takes the default value
             $xml_element_product->addAttribute('type', $default_product_type);
         }
         //sets the product reference that will be inserted into the XML stream
         //uses the product name by default
         $product_ref = $product['product_name'];
         //prefers ean13 if defined
         if (!empty($product['product_ean13'])) {
             $product_ref = $product['product_ean13'];
         }
         //prefers local reference if defined
         if (!empty($product['product_reference'])) {
             $product_ref = $product['product_reference'];
         }
         //adds attributes ref, nb, prixunit, and sets the value of the element <product> with the product name
         $xml_element_product->addAttribute('ref', CertissimTools::normalizeString($product_ref));
         $xml_element_product->addAttribute('nb', $product['product_quantity']);
         $xml_element_product->addAttribute('prixunit', $product['total_price']);
         $xml_element_product->setValue($product['product_name']);
         //adds the element <product> to the element <list>
         $xml_element_products_list->addProduit($xml_element_product);
     }
     if ($alldownloadables) {
         $real_carrier_type = '5';
     } elseif (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
         //if selected carrier fianet type is defined, the type used will be the one got in the Configuration
         if (in_array(Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE', null, null, $order->id_shop), array_keys($this->_carrier_types))) {
             $real_carrier_type = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE', null, null, $order->id_shop);
             $real_carrier_speed = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_SPEED', null, null, $order->id_shop);
         } else {
             $real_carrier_type = Configuration::get('CERTISSIM_DEFAULT_CARRIER_TYPE', null, null, $order->id_shop);
             $real_carrier_speed = Configuration::get('CERTISSIM_DEFAULT_CARRIER_SPEED', null, null, $order->id_shop);
         }
     } elseif (in_array(Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE'), array_keys($this->_carrier_types))) {
         $real_carrier_type = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_TYPE');
         $real_carrier_speed = Configuration::get('CERTISSIM_' . (string) $carrier->id . '_CARRIER_SPEED');
     } else {
         $real_carrier_type = Configuration::get('CERTISSIM_DEFAULT_CARRIER_TYPE');
         $real_carrier_speed = Configuration::get('CERTISSIM_DEFAULT_CARRIER_SPEED');
     }
     //initialization of the element <transport>
     $xml_element_carrier = new CertissimTransport($real_carrier_type, $alldownloadables ? 'Téléchargement' : Tools::htmlentitiesUTF8($carrier->name), $alldownloadables ? '1' : $real_carrier_speed, null);
     //find the id of the payment module used (depends on the PS version)
     if (_PS_VERSION_ >= '1.5') {
         $id_payment_module = PaymentModule::getModuleIdByName($order->module);
     } else {
         $payment_module = Module::getInstanceByName($order->module);
         $id_payment_module = $payment_module->id;
     }
     //initialization of the element <paiement>
     if (_PS_VERSION_ >= '1.5' && Shop::isFeatureActive()) {
         $payment_type = $this->_payment_types[Configuration::get('CERTISSIM_' . $id_payment_module . '_PAYMENT_TYPE', null, null, $order->id_shop)];
     } else {
         $payment_type = $this->_payment_types[Configuration::get('CERTISSIM_' . $id_payment_module . '_PAYMENT_TYPE')];
     }
     $xml_element_payment = new CertissimPaiement($payment_type);
     //initialization of the element <stack>
     $stack = new CertissimXMLElement("<stack></stack>");
     //agregates each elements in a main stream
     $xml_element_invoice_customer->childSiteconso($xml_element_invoice_customer_stats);
     $xml_element_control->childUtilisateur($xml_element_invoice_customer);
     $xml_element_control->childAdresse($xml_element_invoice_address);
     if (isset($xml_element_delivery_customer)) {
         $xml_element_control->childUtilisateur($xml_element_delivery_customer);
     }
     if (isset($xml_element_delivery_address)) {
         $xml_element_control->childAdresse($xml_element_delivery_address);
     }
     $xml_element_order_details->childTransport($xml_element_carrier);
     $xml_element_order_details->childList($xml_element_products_list);
     $xml_element_control->childInfocommande($xml_element_order_details);
     $xml_element_control->childPaiement($xml_element_payment);
     //add CDATA sections to protect against encoding issues
     $xml_element_control->addCdataSections();
     //add the <control> element into <stack>
     $stack->childControl($xml_element_control);
     CertissimLogger::insertLog(__METHOD__ . ' : ' . __LINE__, "---- flux généré pour commande {$id_order} ----");
     CertissimLogger::insertLog(__METHOD__ . ' : ' . __LINE__, $xml_element_control->getXML());
     CertissimLogger::insertLog(__METHOD__ . ' : ' . __LINE__, "---------------------------------------");
     return $stack;
 }
Exemple #6
0
    public function viewDetails()
    {
        global $currentIndex, $cookie;
        if (!($cart = $this->loadObject(true))) {
            return;
        }
        $customer = new Customer($cart->id_customer);
        $customerStats = $customer->getStats();
        $products = $cart->getProducts();
        $customizedDatas = Product::getAllCustomizedDatas((int) $cart->id);
        Product::addCustomizationPrice($products, $customizedDatas);
        $summary = $cart->getSummaryDetails();
        $discounts = $cart->getDiscounts();
        $currency = new Currency($cart->id_currency);
        $currentLanguage = new Language((int) $cookie->id_lang);
        // display cart header
        echo '<h2>' . ($customer->id ? $customer->firstname . ' ' . $customer->lastname : $this->l('Guest')) . ' - ' . $this->l('Cart #') . sprintf('%06d', $cart->id) . ' ' . $this->l('from') . ' ' . $cart->date_upd . '</h2>';
        /* Display customer information */
        echo '
		<br />
		<div style="float: left;">
		<fieldset style="width: 400px">
			<legend><img src="../img/admin/tab-customers.gif" /> ' . $this->l('Customer information') . '</legend>
			<span style="font-weight: bold; font-size: 14px;">';
        if ($customer->id) {
            echo '
			<a href="?tab=AdminCustomers&id_customer=' . $customer->id . '&viewcustomer&token=' . Tools::getAdminToken('AdminCustomers' . (int) Tab::getIdFromClassName('AdminCustomers') . (int) $cookie->id_employee) . '"> ' . $customer->firstname . ' ' . $customer->lastname . '</a></span> (' . $this->l('#') . $customer->id . ')<br />
			(<a href="mailto:' . $customer->email . '">' . $customer->email . '</a>)<br /><br />
			' . $this->l('Account registered:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Valid orders placed:') . ' <b>' . $customerStats['nb_orders'] . '</b><br />
			' . $this->l('Total paid since registration:') . ' <b>' . Tools::displayPrice($customerStats['total_orders'], $currency, false) . '</b><br />';
        } else {
            echo $this->l('Guest not registered') . '</span>';
        }
        echo '</fieldset>';
        echo '
		</div>
		<div style="float: left; margin-left: 40px">';
        /* Display order information */
        $id_order = (int) Order::getOrderByCartId($cart->id);
        $order = new Order($id_order);
        if ($order->getTaxCalculationMethod() == PS_TAX_EXC) {
            $total_products = $summary['total_products'];
            $total_discount = $summary['total_discounts_tax_exc'];
            $total_wrapping = $summary['total_wrapping_tax_exc'];
            $total_price = $summary['total_price_without_tax'];
            $total_shipping = $summary['total_shipping_tax_exc'];
        } else {
            $total_products = $summary['total_products_wt'];
            $total_discount = $summary['total_discounts'];
            $total_wrapping = $summary['total_wrapping'];
            $total_price = $summary['total_price'];
            $total_shipping = $summary['total_shipping'];
        }
        echo '
		<fieldset style="width: 400px">
			<legend><img src="../img/admin/cart.gif" /> ' . $this->l('Order information') . '</legend>
			<span style="font-weight: bold; font-size: 14px;">';
        if ($order->id) {
            echo '
			<a href="?tab=AdminOrders&id_order=' . (int) $order->id . '&vieworder&token=' . Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee) . '"> ' . $this->l('Order #') . sprintf('%06d', $order->id) . '</a></span>
			<br /><br />
			' . $this->l('Made on:') . ' ' . Tools::displayDate($order->date_add, (int) $cookie->id_lang, true) . '<br /><br /><br /><br />';
        } else {
            echo $this->l('No order created from this cart') . '</span>';
        }
        echo '</fieldset>';
        echo '
		</div>';
        // List of products
        echo '
		<br style="clear:both;" />
			<fieldset style="margin-top:25px; width: 715px; ">
				<legend><img src="../img/admin/cart.gif" alt="' . $this->l('Products') . '" />' . $this->l('Cart summary') . '</legend>
				<div style="float:left;">
					<table style="width: 700px;" cellspacing="0" cellpadding="0" class="table" id="orderProducts">
						<tr>
							<th align="center" style="width: 60px">&nbsp;</th>
							<th>' . $this->l('Product') . '</th>
							<th style="width: 80px; text-align: center">' . $this->l('UP') . '</th>
							<th style="width: 20px; text-align: center">' . $this->l('Qty') . '</th>
							<th style="width: 30px; text-align: center">' . $this->l('Stock') . '</th>
							<th style="width: 90px; text-align: right; font-weight:bold;">' . $this->l('Total') . '</th>
						</tr>';
        $tokenCatalog = Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee);
        foreach ($products as $k => $product) {
            if ($order->getTaxCalculationMethod() == PS_TAX_EXC) {
                $product_price = $product['price'];
                $product_total = $product['total'];
            } else {
                $product_price = $product['price_wt'];
                $product_total = $product['total_wt'];
            }
            $image = array();
            if (isset($product['id_product_attribute']) and (int) $product['id_product_attribute']) {
                $image = Db::getInstance()->getRow('
								SELECT id_image
								FROM ' . _DB_PREFIX_ . 'product_attribute_image
								WHERE id_product_attribute = ' . (int) $product['id_product_attribute']);
            }
            if (!isset($image['id_image'])) {
                $image = Db::getInstance()->getRow('
								SELECT id_image
								FROM ' . _DB_PREFIX_ . 'image
								WHERE id_product = ' . (int) $product['id_product'] . ' AND cover = 1');
            }
            $stock = Db::getInstance()->getRow('
							SELECT ' . ($product['id_product_attribute'] ? 'pa' : 'p') . '.quantity
							FROM ' . _DB_PREFIX_ . 'product p
							' . ($product['id_product_attribute'] ? 'LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON p.id_product = pa.id_product' : '') . '
							WHERE p.id_product = ' . (int) $product['id_product'] . '
							' . ($product['id_product_attribute'] ? 'AND pa.id_product_attribute = ' . (int) $product['id_product_attribute'] : ''));
            /* Customization display */
            $this->displayCustomizedDatas($customizedDatas, $product, $currency, $image, $tokenCatalog, $stock);
            if ($product['cart_quantity'] > $product['customizationQuantityTotal']) {
                $imageProduct = new Image($image['id_image']);
                echo '
								<tr>
									<td align="center">' . (isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_ . 'p/' . $imageProduct->getExistingImgPath() . '.jpg', 'product_mini_' . (int) $product['id_product'] . (isset($product['id_product_attribute']) ? '_' . (int) $product['id_product_attribute'] : '') . '.jpg', 45, 'jpg') : '--') . '</td>
									<td><a href="index.php?tab=AdminCatalog&id_product=' . $product['id_product'] . '&updateproduct&token=' . $tokenCatalog . '">
										<span class="productName">' . $product['name'] . '</span><br />
										' . ($product['reference'] ? $this->l('Ref:') . ' ' . $product['reference'] : '') . (($product['reference'] and $product['supplier_reference']) ? ' / ' . $product['supplier_reference'] : '') . '</a></td>
									<td align="center">' . Tools::displayPrice($product_price, $currency, false) . '</td>
									<td align="center" class="productQuantity">' . ((int) $product['cart_quantity'] - $product['customizationQuantityTotal']) . '</td>
									<td align="center" class="productQuantity">' . (int) $stock['quantity'] . '</td>
									<td align="right">' . Tools::displayPrice($product_total, $currency, false) . '</td>
								</tr>';
            }
        }
        echo '
					<tr class="cart_total_product">
				<td colspan="5">' . $this->l('Total products:') . '</td>
				<td class="price bold right">' . Tools::displayPrice($total_products, $currency, false) . '</td>
			</tr>';
        if ($summary['total_discounts'] != 0) {
            echo '
			<tr class="cart_total_voucher">
				<td colspan="5">' . $this->l('Total vouchers:') . '</td>
				<td class="price-discount bold right">' . Tools::displayPrice($total_discount, $currency, false) . '</td>
			</tr>';
        }
        if ($summary['total_wrapping'] > 0) {
            echo '
			 <tr class="cart_total_voucher">
				<td colspan="5">' . $this->l('Total gift-wrapping:') . '</td>
				<td class="price-discount bold right">' . Tools::displayPrice($total_wrapping, $currency, false) . '</td>
			</tr>';
        }
        if ($cart->getOrderTotal(true, Cart::ONLY_SHIPPING) > 0) {
            echo '
			<tr class="cart_total_delivery">
				<td colspan="5">' . $this->l('Total shipping:') . '</td>
				<td class="price bold right">' . Tools::displayPrice($total_shipping, $currency, false) . '</td>
			</tr>';
        }
        echo '
			<tr class="cart_total_price">
				<td colspan="5" class="bold">' . $this->l('Total:') . '</td>
				<td class="price bold right">' . Tools::displayPrice($total_price, $currency, false) . '</td>
			</tr>
			</table>';
        if (sizeof($discounts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table" style="width:280px; margin:15px 0px 0px 420px;">
				<tr>
					<th><img src="../img/admin/coupon.gif" alt="' . $this->l('Discounts') . '" />' . $this->l('Discount name') . '</th>
					<th align="center" style="width: 100px">' . $this->l('Value') . '</th>
				</tr>';
            foreach ($discounts as $discount) {
                echo '
				<tr>
					<td><a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&updatediscount&token=' . Tools::getAdminToken('AdminDiscounts' . (int) Tab::getIdFromClassName('AdminDiscounts') . (int) $cookie->id_employee) . '">' . $discount['name'] . '</a></td>
					<td align="center">- ' . Tools::displayPrice($discount['value_real'], $currency, false) . '</td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div style="float:left; margin-top:15px;">' . $this->l('According to the group of this customer, prices are printed:') . ' <b>' . ($order->getTaxCalculationMethod() == PS_TAX_EXC ? $this->l('tax excluded.') : $this->l('tax included.')) . '</b>
				</div></div>';
        // Cancel product
        echo '
			</fieldset>
		<div class="clear" style="height:20px;">&nbsp;</div>';
    }
    if (Tools::getValue('friendChecked') and sizeof($friendsChecked = Tools::getValue('friendChecked')) >= 1) {
        foreach ($friendsChecked as $key => $friendChecked) {
            if (ReferralProgramModule::isSponsorFriend((int) $cookie->id_customer, (int) $friendChecked)) {
                if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                    $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                } else {
                    $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                }
                $referralprogram = new ReferralProgramModule((int) $key);
                $vars = array('{email}' => $cookie->email, '{lastname}' => $cookie->customer_lastname, '{firstname}' => $cookie->customer_firstname, '{email_friend}' => $referralprogram->email, '{lastname_friend}' => $referralprogram->lastname, '{firstname_friend}' => $referralprogram->firstname, '{link}' => 'authentication.php?create_account=1&sponsor=' . base64_encode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), '{discount}' => $discount);
                $referralprogram->save();
                Mail::Send((int) $cookie->id_lang, 'referralprogram-invitation', Mail::l('Referral Program'), $vars, $referralprogram->email, $referralprogram->firstname . ' ' . $referralprogram->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
                $revive_sent = true;
                $nbRevive++;
            }
        }
    } else {
        $error = 'no revive checked';
    }
}
$customer = new Customer((int) $cookie->id_customer);
$stats = $customer->getStats();
$orderQuantity = (int) Configuration::get('REFERRAL_ORDER_QUANTITY');
$canSendInvitations = false;
if ((int) $stats['nb_orders'] >= $orderQuantity) {
    $canSendInvitations = true;
}
// Smarty display
$smarty->assign(array('activeTab' => $activeTab, 'discount' => $discount, 'orderQuantity' => $orderQuantity, 'canSendInvitations' => $canSendInvitations, 'nbFriends' => (int) Configuration::get('REFERRAL_NB_FRIENDS'), 'error' => $error, 'invitation_sent' => $invitation_sent, 'nbInvitation' => $nbInvitation, 'pendingFriends' => ReferralProgramModule::getSponsorFriend((int) $cookie->id_customer, 'pending'), 'revive_sent' => $revive_sent, 'nbRevive' => $nbRevive, 'subscribeFriends' => ReferralProgramModule::getSponsorFriend((int) $cookie->id_customer, 'subscribed'), 'mails_exists' => isset($mails_exists) ? $mails_exists : array()));
echo Module::display(dirname(__FILE__) . '/referralprogram.php', 'referralprogram-program.tpl');
include dirname(__FILE__) . '/../../footer.php';
 public function hookNewOrder($params)
 {
     if ($params['order']->total_paid <= 0) {
         return;
     }
     if (!$this->needCheck($params['order']->module, $params['order']->total_paid)) {
         return false;
     }
     $address_delivery = new Address((int) $params['order']->id_address_delivery);
     $address_invoice = new Address((int) $params['order']->id_address_invoice);
     $customer = new Customer((int) $params['order']->id_customer);
     $orderFianet = new fianet_order_xml();
     $id_lang = Configuration::get('PS_LANG_DEFAULT');
     if ($address_invoice->company == '') {
         $orderFianet->billing_user->set_quality_nonprofessional();
     } else {
         $orderFianet->billing_user->set_quality_professional();
     }
     $orderFianet->billing_user->titre = $customer->id_gender == 1 ? $this->l('Mr.') : ($customer->id_gender == 2 ? $this->l('Mrs') : $this->l('Mr.'));
     $orderFianet->billing_user->nom = utf8_decode($address_invoice->lastname);
     $orderFianet->billing_user->prenom = utf8_decode($address_invoice->firstname);
     $orderFianet->billing_user->societe = utf8_decode($address_invoice->company);
     $orderFianet->billing_user->telhome = utf8_decode($address_invoice->phone);
     $orderFianet->billing_user->office = '';
     $orderFianet->billing_user->telmobile = utf8_decode($address_invoice->phone_mobile);
     $orderFianet->billing_user->telfax = '';
     $orderFianet->billing_user->email = $customer->email;
     $customer_stats = $customer->getStats();
     $all_orders = Order::getCustomerOrders((int) $customer->id);
     $orderFianet->billing_user->site_conso = new fianet_user_siteconso_xml();
     $orderFianet->billing_user->site_conso->ca = $customer_stats['total_orders'];
     $orderFianet->billing_user->site_conso->nb = $customer_stats['nb_orders'];
     $orderFianet->billing_user->site_conso->datepremcmd = $all_orders[count($all_orders) - 1]['date_add'];
     if (count($all_orders) > 1) {
         $orderFianet->billing_user->site_conso->datederncmd = $all_orders[1]['date_add'];
     }
     $orderFianet->billing_adress->rue1 = utf8_decode($address_invoice->address1);
     $orderFianet->billing_adress->rue2 = utf8_decode($address_invoice->address2);
     $orderFianet->billing_adress->cpostal = utf8_decode($address_invoice->postcode);
     $orderFianet->billing_adress->ville = utf8_decode($address_invoice->city);
     $country = new Country((int) $address_invoice->id_country);
     $orderFianet->billing_adress->pays = utf8_decode($country->name[$id_lang]);
     //delivery adresse not send if carrier id is 1 or 2
     $carrier_id = array(1, 2);
     if (!in_array(Configuration::get('SAC_CARRIER_TYPE_' . (int) $params['cart']->id_carrier), $carrier_id)) {
         $orderFianet->delivery_user = new fianet_delivery_user_xml();
         $orderFianet->delivery_adress = new fianet_delivery_adress_xml();
         if ($address_delivery->company == '') {
             $orderFianet->delivery_user->set_quality_nonprofessional();
         } else {
             $orderFianet->delivery_user->set_quality_professional();
         }
         $orderFianet->delivery_user->titre = $customer->id_gender == 1 ? $this->l('Mr.') : ($customer->id_gender == 2 ? $this->l('Mrs') : $this->l('Unknown'));
         $orderFianet->delivery_user->nom = utf8_decode($address_delivery->lastname);
         $orderFianet->delivery_user->prenom = utf8_decode($address_delivery->firstname);
         $orderFianet->delivery_user->societe = utf8_decode($address_delivery->company);
         $orderFianet->delivery_user->telhome = utf8_decode($address_delivery->phone);
         $orderFianet->delivery_user->office = '';
         $orderFianet->delivery_user->telmobile = utf8_decode($address_delivery->phone_mobile);
         $orderFianet->delivery_user->telfax = '';
         $orderFianet->delivery_user->email = $customer->email;
         $orderFianet->delivery_adress->rue1 = utf8_decode($address_delivery->address1);
         $orderFianet->delivery_adress->rue2 = utf8_decode($address_delivery->address2);
         $orderFianet->delivery_adress->cpostal = utf8_decode($address_delivery->postcode);
         $orderFianet->delivery_adress->ville = utf8_decode($address_delivery->city);
         $country = new Country((int) $address_delivery->id_country);
         $orderFianet->delivery_adress->pays = utf8_decode($country->name[$id_lang]);
     }
     $orderFianet->info_commande->refid = $params['order']->id;
     $orderFianet->info_commande->montant = $params['order']->total_paid;
     $currency = new Currency((int) $params['order']->id_currency);
     $orderFianet->info_commande->devise = $currency->iso_code;
     $orderFianet->info_commande->ip = self::getIpByCart((int) $params['cart']->id);
     $orderFianet->info_commande->timestamp = date('Y-m-d H:i:s');
     $products = $params['cart']->getProducts();
     $default_product_type = Configuration::get('SAC_DEFAULT_PRODUCT_TYPE');
     foreach ($products as $product) {
         $product_categories = Product::getIndexedCategories((int) $product['id_product']);
         $have_sac_cat = false;
         $produit = new fianet_product_xml();
         if (Configuration::get('SAC_CATEGORY_TYPE_' . $product['id_category_default'])) {
             $produit->type = Configuration::get('SAC_CATEGORY_TYPE_' . $product['id_category_default']);
         } else {
             $produit->type = $default_product_type;
         }
         $produit->ref = utf8_decode((isset($product['reference']) and !empty($product['reference'])) ? $product['reference'] : ((isset($product['ean13']) and !empty($product['ean13'])) ? $product['ean13'] : $product['name']));
         $produit->nb = $product['cart_quantity'];
         $produit->prixunit = $product['price'];
         $produit->name = utf8_decode($product['name']);
         $orderFianet->info_commande->list->add_product($produit);
     }
     $carrier = new Carrier((int) $params['order']->id_carrier);
     $orderFianet->info_commande->transport->type = Configuration::get('SAC_CARRIER_TYPE_' . (int) $carrier->id);
     $orderFianet->info_commande->transport->nom = $carrier->name;
     $orderFianet->info_commande->transport->rapidite = self::getCarrierFastById((int) $carrier->id);
     $orderFianet->payment->type = Configuration::get('SAC_PAYMENT_TYPE_' . substr($params['order']->module, 0, 15));
     $xml = $orderFianet->get_xml();
     $sender = new fianet_sender();
     if (Configuration::get('SAC_PRODUCTION')) {
         $sender->mode = 'production';
     } else {
         $sender->mode = 'test';
     }
     $sender->add_order($orderFianet);
     $res = $sender->send_orders_stacking();
     Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'fianet_fraud_orders(id_order, date_add) VALUES(' . (int) $params['order']->id . ', \'' . pSQL(date('Y-m-d H:i:s')) . '\')');
     return true;
 }
Exemple #9
0
 /**
  * Hook called when order status changed
  * register a discount for sponsor and send him an e-mail
  */
 public function hookUpdateOrderStatus($params)
 {
     if (!Validate::isLoadedObject($params['newOrderStatus'])) {
         die(Tools::displayError('Some parameters are missing.'));
     }
     $orderState = $params['newOrderStatus'];
     $order = new Order(intval($params['id_order']));
     if ($order and !Validate::isLoadedObject($order)) {
         die(Tools::displayError('Incorrect object Order.'));
     }
     $customer = new Customer($order->id_customer);
     $stats = $customer->getStats();
     $nbOrdersCustomer = intval($stats['nb_orders']) + 1;
     // hack to count current order
     $referralprogram = new ReferralProgramModule(ReferralProgramModule::isSponsorised(intval($customer->id), true));
     if (!Validate::isLoadedObject($referralprogram)) {
         return false;
     }
     $sponsor = new Customer($referralprogram->id_sponsor);
     if (intval($orderState->logable) and $nbOrdersCustomer >= intval($this->_configuration['REFERRAL_ORDER_QUANTITY'])) {
         if ($referralprogram->registerDiscountForSponsor()) {
             $discount = new Discount($referralprogram->id_discount_sponsor);
             $currency = new Currency($order->id_currency);
             $discount_display = $discount->display($discount->value, $discount->id_discount_type, $currency);
             $data = array('{sponsored_firstname}' => $customer->firstname, '{sponsored_lastname}' => $customer->lastname, '{discount_display}' => $discount_display, '{discount_name}' => $discount->name);
             Mail::Send(intval($order->id_lang), 'referralprogram-congratulations', $this->l('Congratulations!'), $data, $sponsor->email, $sponsor->firstname . ' ' . $sponsor->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
             return true;
         }
     }
     return false;
 }
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $order_details = AphOrderDetail::getList($order->id);
     foreach ($order_details as &$order_detail) {
         $products[$order_detail['id_order_detail']]['delivery_date'] = $order_detail['delivery_date'];
         $products[$order_detail['id_order_detail']]['delivery_time_from'] = $order_detail['delivery_time_from'];
         $products[$order_detail['id_order_detail']]['delivery_time_to'] = $order_detail['delivery_time_to'];
     }
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     $options_time = array();
     $time_slice = Configuration::get('APH_CALENDAR_TIME_SLICE');
     for ($hours = 0; $hours < 24; $hours++) {
         // the interval for hours is '1'
         for ($mins = 0; $mins < 60; $mins += $time_slice) {
             // the interval for mins is 'APH_CALENDAR_TIME_SLICE'
             $options_time[str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($mins, 2, '0', STR_PAD_LEFT)] = str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($mins, 2, '0', STR_PAD_LEFT);
         }
     }
     $this->tpl_view_vars['options_time'] = $options_time;
     $employees = array();
     $e = AphEmployeeProduct::getEmployeesByShop((int) Context::getContext()->shop->id);
     foreach ($e as $employee) {
         $employees[$employee['id_employee']] = $employee['fullName'];
     }
     $this->tpl_view_vars['employees'] = $employees;
     $helper = new HelperView($this);
     $this->setHelperDisplay($helper);
     $helper->tpl_vars = $this->getTemplateViewVars();
     $helper->base_folder = $this->getTemplatePath() . 'aph_orders/helpers/';
     $helper->base_tpl = 'view/view.tpl';
     $view = $helper->generateView();
     return $view;
 }
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] == 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->l('This product is out of stock: ') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     //by webkul to get data to show hotel rooms order data on order detail page
     $cart_id = Cart::getCartIdByOrderId(Tools::getValue('id_order'));
     $cart_detail_data = array();
     $cart_detail_data_obj = new HotelCartBookingData();
     $cart_detail_data = $cart_detail_data_obj->getCartCurrentDataByCartId((int) $cart_id);
     if ($cart_detail_data) {
         foreach ($cart_detail_data as $key => $value) {
             $product_image_id = Product::getCover($value['id_product']);
             $link_rewrite = (new Product((int) $value['id_product'], Configuration::get('PS_LANG_DEFAULT')))->link_rewrite[Configuration::get('PS_LANG_DEFAULT')];
             if ($product_image_id) {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $product_image_id['id_image'], 'small_default');
             } else {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $this->context->language->iso_code . "-default", 'small_default');
             }
             $cart_detail_data[$key]['room_type'] = (new Product((int) $value['id_product']))->name[Configuration::get('PS_LANG_DEFAULT')];
             $cart_detail_data[$key]['room_num'] = (new HotelRoomInformation((int) $value['id_room']))->room_num;
             $cart_detail_data[$key]['date_from'] = (new DateTime($value['date_from']))->format('d-M Y');
             $cart_detail_data[$key]['date_to'] = (new DateTime($value['date_to']))->format('d-M Y');
             $cust_obj = new Customer($value['id_customer']);
             $cart_detail_data[$key]['alloted_cust_name'] = $cust_obj->firstname . ' ' . $cust_obj->lastname;
             $cart_detail_data[$key]['alloted_cust_email'] = $cust_obj->email;
             $cart_detail_data[$key]['avail_rooms_to_swap'] = (new HotelBookingDetail())->getAvailableRoomsForSwaping($value['date_from'], $value['date_to'], $value['id_product'], $value['id_hotel']);
             $obj_booking_dtl = new HotelBookingDetail();
             $num_days = $obj_booking_dtl->getNumberOfDays($cart_detail_data[$key]['date_from'], $cart_detail_data[$key]['date_to']);
             //quantity of product
             $cart_detail_data[$key]['amt_with_qty'] = $value['amount'] * $num_days;
         }
     }
     //end
     //by webkul to send order status on order detail page
     $obj_bookin_detail = new HotelBookingDetail();
     $htl_booking_data_order_id = $obj_bookin_detail->getBookingDataByOrderId(Tools::getValue('id_order'));
     if ($htl_booking_data_order_id) {
         foreach ($htl_booking_data_order_id as $key => $value) {
             $htl_booking_data_order_id[$key]['room_num'] = (new HotelRoomInformation())->getHotelRoomInfoById($value['id_room']);
             $htl_booking_data_order_id[$key]['order_status'] = $value['id_status'];
             $htl_booking_data_order_id[$key]['date_from'] = (new DateTime($value['date_from']))->format('d-M Y');
             $htl_booking_data_order_id[$key]['date_to'] = (new DateTime($value['date_to']))->format('d-M Y');
         }
     }
     $htl_order_status = HotelOrderStatus::getAllHotelOrderStatus();
     //end
     // Smarty assign
     $this->tpl_view_vars = array('htl_booking_order_data' => $htl_booking_data_order_id, 'hotel_order_status' => $htl_order_status, 'cart_detail_data' => $cart_detail_data, 'order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
    public function viewDetails()
    {
        global $currentIndex, $cookie, $link;
        $irow = 0;
        if (!($order = $this->loadObject())) {
            return;
        }
        $customer = new Customer($order->id_customer);
        $customerStats = $customer->getStats();
        $addressInvoice = new Address($order->id_address_invoice, (int) $cookie->id_lang);
        if (Validate::isLoadedObject($addressInvoice) and $addressInvoice->id_state) {
            $invoiceState = new State((int) $addressInvoice->id_state);
        }
        $addressDelivery = new Address($order->id_address_delivery, (int) $cookie->id_lang);
        if (Validate::isLoadedObject($addressDelivery) and $addressDelivery->id_state) {
            $deliveryState = new State((int) $addressDelivery->id_state);
        }
        $carrier = new Carrier($order->id_carrier);
        $history = $order->getHistory($cookie->id_lang);
        $products = $order->getProducts();
        $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
        Product::addCustomizationPrice($products, $customizedDatas);
        $discounts = $order->getDiscounts();
        $messages = Message::getMessagesByOrderId($order->id, true);
        $states = OrderState::getOrderStates((int) $cookie->id_lang);
        $currency = new Currency($order->id_currency);
        $currentLanguage = new Language((int) $cookie->id_lang);
        $currentState = OrderHistory::getLastOrderState($order->id);
        $sources = ConnectionsSource::getOrderSources($order->id);
        $cart = Cart::getCartByOrderId($order->id);
        $row = array_shift($history);
        if ($prevOrder = Db::getInstance()->getValue('SELECT id_order FROM ' . _DB_PREFIX_ . 'orders WHERE id_order < ' . (int) $order->id . ' ORDER BY id_order DESC')) {
            $prevOrder = '<a href="' . $currentIndex . '&token=' . Tools::getValue('token') . '&vieworder&id_order=' . $prevOrder . '"><img style="width:24px;height:24px" src="../img/admin/arrow-left.png" /></a>';
        }
        if ($nextOrder = Db::getInstance()->getValue('SELECT id_order FROM ' . _DB_PREFIX_ . 'orders WHERE id_order > ' . (int) $order->id . ' ORDER BY id_order ASC')) {
            $nextOrder = '<a href="' . $currentIndex . '&token=' . Tools::getValue('token') . '&vieworder&id_order=' . $nextOrder . '"><img style="width:24px;height:24px" src="../img/admin/arrow-right.png" /></a>';
        }
        if ($order->total_paid != $order->total_paid_real) {
            echo '<center><span class="warning" style="font-size: 16px">' . $this->l('Warning:') . ' ' . Tools::displayPrice($order->total_paid_real, $currency, false) . ' ' . $this->l('paid instead of') . ' ' . Tools::displayPrice($order->total_paid, $currency, false) . ' !</span></center><div class="clear"><br /><br /></div>';
        }
        // display bar code if module enabled
        $hook = Module::hookExec('invoice', array('id_order' => $order->id));
        if ($hook !== false) {
            echo '<div style="float: right; margin: -40px 40px 10px 0;">';
            echo $hook;
            echo '</div><br class="clear" />';
        }
        // display order header
        echo '
		<div style="float:left" style="width:440px">';
        echo '<h2>
				' . $prevOrder . '
				' . (Validate::isLoadedObject($customer) ? $customer->firstname . ' ' . $customer->lastname . ' - ' : '') . $this->l('Order #') . sprintf('%06d', $order->id) . '
				' . $nextOrder . '
			</h2>
			<div style="width:429px">
				' . ((($currentState->invoice or $order->invoice_number) and count($products)) ? '<a href="pdf.php?id_order=' . $order->id . '&pdf"><img src="../img/admin/charged_ok.gif" alt="' . $this->l('View invoice') . '" /> ' . $this->l('View invoice') . '</a>' : '<img src="../img/admin/charged_ko.gif" alt="' . $this->l('No invoice') . '" /> ' . $this->l('No invoice')) . ' -
				' . (($currentState->delivery or $order->delivery_number) ? '<a href="pdf.php?id_delivery=' . $order->delivery_number . '"><img src="../img/admin/delivery.gif" alt="' . $this->l('View delivery slip') . '" /> ' . $this->l('View delivery slip') . '</a>' : '<img src="../img/admin/delivery_ko.gif" alt="' . $this->l('No delivery slip') . '" /> ' . $this->l('No delivery slip')) . ' -
				<a href="javascript:window.print()"><img src="../img/admin/printer.gif" alt="' . $this->l('Print order') . '" title="' . $this->l('Print order') . '" /> ' . $this->l('Print page') . '</a>
			</div>
			<div class="clear">&nbsp;</div>';
        /* Display current status */
        echo '
			<table cellspacing="0" cellpadding="0" class="table" style="width: 429px">
				<tr>
					<th>' . Tools::displayDate($row['date_add'], (int) $cookie->id_lang, true) . '</th>
					<th><img src="../img/os/' . $row['id_order_state'] . '.gif" /></th>
					<th>' . stripslashes($row['ostate_name']) . '</th>
					<th>' . (!empty($row['employee_lastname']) ? '(' . stripslashes(Tools::substr($row['employee_firstname'], 0, 1)) . '. ' . stripslashes($row['employee_lastname']) . ')' : '') . '</th>
				</tr>';
        /* Display previous status */
        foreach ($history as $row) {
            echo '
				<tr class="' . ($irow++ % 2 ? 'alt_row' : '') . '">
					<td>' . Tools::displayDate($row['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td><img src="../img/os/' . $row['id_order_state'] . '.gif" /></td>
					<td>' . stripslashes($row['ostate_name']) . '</td>
					<td>' . (!empty($row['employee_lastname']) ? '(' . stripslashes(Tools::substr($row['employee_firstname'], 0, 1)) . '. ' . stripslashes($row['employee_lastname']) . ')' : '') . '</td>
				</tr>';
        }
        echo '
			</table>
			<br />';
        /* Display status form */
        echo '
			<form action="' . $currentIndex . '&view' . $this->table . '&token=' . $this->token . '" method="post" style="text-align:center;">
				<select name="id_order_state">';
        $currentStateTab = $order->getCurrentStateFull($cookie->id_lang);
        foreach ($states as $state) {
            echo '<option value="' . $state['id_order_state'] . '"' . ($state['id_order_state'] == $currentStateTab['id_order_state'] ? ' selected="selected"' : '') . '>' . stripslashes($state['name']) . '</option>';
        }
        echo '
				</select>
				<input type="hidden" name="id_order" value="' . $order->id . '" />
				<input type="submit" name="submitState" value="' . $this->l('Change') . '" class="button" />
			</form>';
        /* Display customer information */
        if (Validate::isLoadedObject($customer)) {
            echo '<br />
			<fieldset style="width: 400px">
				<legend><img src="../img/admin/tab-customers.gif" /> ' . $this->l('Customer information') . '</legend>
				<span style="font-weight: bold; font-size: 14px;"><a href="?tab=AdminCustomers&id_customer=' . $customer->id . '&viewcustomer&token=' . Tools::getAdminToken('AdminCustomers' . (int) Tab::getIdFromClassName('AdminCustomers') . (int) $cookie->id_employee) . '"> ' . $customer->firstname . ' ' . $customer->lastname . '</a></span> (' . $this->l('#') . $customer->id . ')<br />
				(<a href="mailto:' . $customer->email . '">' . $customer->email . '</a>)<br /><br />';
            if ($customer->isGuest()) {
                echo '
				' . $this->l('This order has been placed by a') . ' <b>' . $this->l('guest') . '</b>';
                if (!Customer::customerExists($customer->email)) {
                    echo '<form method="POST" action="index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&token=' . Tools::getAdminTokenLite('AdminCustomers') . '">
						<input type="hidden" name="id_lang" value="' . (int) $order->id_lang . '" />
						<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="' . $this->l('Transform to customer') . '" /></p>
						' . $this->l('This feature will generate a random password and send an e-mail to the customer') . '
					</form>';
                } else {
                    echo '<div><b style="color:red;">' . $this->l('A registered customer account exists with the same email address') . '</b></div>';
                }
            } else {
                echo $this->l('Account registered:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
				' . $this->l('Valid orders placed:') . ' <b>' . $customerStats['nb_orders'] . '</b><br />
				' . $this->l('Total paid since registration:') . ' <b>' . Tools::displayPrice(Tools::ps_round(Tools::convertPrice($customerStats['total_orders'], $currency), 2), $currency, false) . '</b><br />';
            }
            echo '</fieldset>';
        }
        /* Display sources */
        if (sizeof($sources)) {
            echo '<br />
			<fieldset style="width: 400px;"><legend><img src="../img/admin/tab-stats.gif" /> ' . $this->l('Sources') . '</legend><ul ' . (sizeof($sources) > 3 ? 'style="height: 200px; overflow-y: scroll; width: 360px;"' : '') . '>';
            foreach ($sources as $source) {
                echo '<li>
						' . Tools::displayDate($source['date_add'], (int) $cookie->id_lang, true) . '<br />
						<b>' . $this->l('From:') . '</b> <a href="' . $source['http_referer'] . '">' . preg_replace('/^www./', '', parse_url($source['http_referer'], PHP_URL_HOST)) . '</a><br />
						<b>' . $this->l('To:') . '</b> ' . $source['request_uri'] . '<br />
						' . ($source['keywords'] ? '<b>' . $this->l('Keywords:') . '</b> ' . $source['keywords'] . '<br />' : '') . '<br />
					</li>';
            }
            echo '</ul></fieldset>';
        }
        // display hook specified to this page : AdminOrder
        if (($hook = Module::hookExec('adminOrder', array('id_order' => $order->id))) !== false) {
            echo $hook;
        }
        echo '
		</div>
		<div style="float: left; margin-left: 40px">';
        /* Display invoice information */
        echo '<fieldset style="width: 400px">';
        if (($currentState->invoice or $order->invoice_number) and count($products)) {
            echo '<legend><a href="pdf.php?id_order=' . $order->id . '&pdf"><img src="../img/admin/charged_ok.gif" /> ' . $this->l('Invoice') . '</a></legend>
				<a href="pdf.php?id_order=' . $order->id . '&pdf">' . $this->l('Invoice #') . '<b>' . Configuration::get('PS_INVOICE_PREFIX', (int) $cookie->id_lang) . sprintf('%06d', $order->invoice_number) . '</b></a>
				<br />' . $this->l('Created on:') . ' ' . Tools::displayDate($order->invoice_date, (int) $cookie->id_lang, true);
        } else {
            echo '<legend><img src="../img/admin/charged_ko.gif" />' . $this->l('Invoice') . '</legend>
				' . $this->l('No invoice yet.');
        }
        echo '</fieldset><br />';
        /* Display shipping infos */
        echo '
		<fieldset style="width:400px">
			<legend><img src="../img/admin/delivery.gif" /> ' . $this->l('Shipping information') . '</legend>
			' . $this->l('Total weight:') . ' <b>' . number_format($order->getTotalWeight(), 3) . ' ' . Configuration::get('PS_WEIGHT_UNIT') . '</b><br />
			' . $this->l('Carrier:') . ' <b>' . ($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name) . '</b><br />
			' . (($currentState->delivery or $order->delivery_number) ? '<br /><a href="pdf.php?id_delivery=' . $order->delivery_number . '">' . $this->l('Delivery slip #') . '<b>' . Configuration::get('PS_DELIVERY_PREFIX', (int) $cookie->id_lang) . sprintf('%06d', $order->delivery_number) . '</b></a><br />' : '');
        if ($order->shipping_number) {
            echo $this->l('Tracking number:') . ' <b>' . $order->shipping_number . '</b> ' . (!empty($carrier->url) ? '(<a href="' . str_replace('@', $order->shipping_number, $carrier->url) . '" target="_blank">' . $this->l('Track the shipment') . '</a>)' : '');
        }
        /* Carrier module */
        if ($carrier->is_module == 1) {
            $module = Module::getInstanceByName($carrier->external_module_name);
            if (method_exists($module, 'displayInfoByCart')) {
                echo call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
            }
        }
        /* Display shipping number field */
        if ($carrier->url && $order->hasBeenShipped()) {
            echo '
				<form action="' . $currentIndex . '&view' . $this->table . '&token=' . $this->token . '" method="post" style="margin-top:10px;">
					<input type="text" name="shipping_number" value="' . $order->shipping_number . '" />
					<input type="hidden" name="id_order" value="' . $order->id . '" />
					<input type="submit" name="submitShippingNumber" value="' . $this->l('Set shipping number') . '" class="button" />
				</form>';
        }
        echo '
		</fieldset>';
        /* Display summary order */
        echo '
		<br />
		<fieldset style="width: 400px">
			<legend><img src="../img/admin/details.gif" /> ' . $this->l('Order details') . '</legend>
			<label>' . $this->l('Original cart:') . ' </label>
			<div style="margin: 2px 0 1em 190px;"><a href="?tab=AdminCarts&id_cart=' . $cart->id . '&viewcart&token=' . Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $cookie->id_employee) . '">' . $this->l('Cart #') . sprintf('%06d', $cart->id) . '</a></div>
			<label>' . $this->l('Payment mode:') . ' </label>
			<div style="margin: 2px 0 1em 190px;">' . Tools::substr($order->payment, 0, 32) . ' ' . ($order->module ? '(' . $order->module . ')' : '') . '</div>
			<div style="margin: 2px 0 1em 50px;">
				<table class="table" width="300px;" cellspacing="0" cellpadding="0">
					<tr><td width="150px;">' . $this->l('Products') . '</td><td align="right">' . Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false) . '</td></tr>
					' . ($order->total_discounts > 0 ? '<tr><td>' . $this->l('Discounts') . '</td><td align="right">-' . Tools::displayPrice($order->total_discounts, $currency, false) . '</td></tr>' : '') . '
					' . ($order->total_wrapping > 0 ? '<tr><td>' . $this->l('Wrapping') . '</td><td align="right">' . Tools::displayPrice($order->total_wrapping, $currency, false) . '</td></tr>' : '') . '
					<tr><td>' . $this->l('Shipping') . '</td><td align="right">' . Tools::displayPrice($order->total_shipping, $currency, false) . '</td></tr>
					<tr style="font-size: 20px"><td>' . $this->l('Total') . '</td><td align="right">' . Tools::displayPrice($order->total_paid, $currency, false) . ($order->total_paid != $order->total_paid_real ? '<br /><font color="red">(' . $this->l('Paid:') . ' ' . Tools::displayPrice($order->total_paid_real, $currency, false, false) . ')</font>' : '') . '</td></tr>
				</table>
			</div>
			<div style="float: left; margin-right: 10px; margin-left: 42px;">
				<span class="bold">' . $this->l('Recycled package:') . '</span>
				' . ($order->recyclable ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '
			</div>
			<div style="float: left; margin-right: 10px;">
				<span class="bold">' . $this->l('Gift wrapping:') . '</span>
				 ' . ($order->gift ? '<img src="../img/admin/enabled.gif" />
			</div>
			<div style="clear: left; margin: 0px 42px 0px 42px; padding-top: 2px;">
				' . (!empty($order->gift_message) ? '<div style="border: 1px dashed #999; padding: 5px; margin-top: 8px;"><b>' . $this->l('Message:') . '</b><br />' . nl2br2($order->gift_message) . '</div>' : '') : '<img src="../img/admin/disabled.gif" />') . '
			</div>
		</fieldset>';
        echo '</div>
		<div class="clear">&nbsp;</div>';
        /* Display adresses : delivery & invoice */
        echo '<div class="clear">&nbsp;</div>
		<div style="float: left">
			<fieldset style="width: 400px;">
				<legend><img src="../img/admin/delivery.gif" alt="' . $this->l('Shipping address') . '" />' . $this->l('Shipping address') . '</legend>
				<div style="float: right">
					<a href="?tab=AdminAddresses&id_address=' . $addressDelivery->id . '&addaddress&realedit=1&id_order=' . $order->id . ($addressDelivery->id == $addressInvoice->id ? '&address_type=1' : '') . '&token=' . Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee) . '&back=' . urlencode($_SERVER['REQUEST_URI']) . '"><img src="../img/admin/edit.gif" /></a>
					<a href="http://maps.google.com/maps?f=q&hl=' . $currentLanguage->iso_code . '&geocode=&q=' . $addressDelivery->address1 . ' ' . $addressDelivery->postcode . ' ' . $addressDelivery->city . ($addressDelivery->id_state ? ' ' . $deliveryState->name : '') . '" target="_blank"><img src="../img/admin/google.gif" alt="" class="middle" /></a>
				</div>
				' . $this->displayAddressDetail($addressDelivery) . (!empty($addressDelivery->other) ? '<hr />' . $addressDelivery->other . '<br />' : '') . '</fieldset>
		</div>
		<div style="float: left; margin-left: 40px">
			<fieldset style="width: 400px;">
				<legend><img src="../img/admin/invoice.gif" alt="' . $this->l('Invoice address') . '" />' . $this->l('Invoice address') . '</legend>
				<div style="float: right"><a href="?tab=AdminAddresses&id_address=' . $addressInvoice->id . '&addaddress&realedit=1&id_order=' . $order->id . ($addressDelivery->id == $addressInvoice->id ? '&address_type=2' : '') . '&back=' . urlencode($_SERVER['REQUEST_URI']) . '&token=' . Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee) . '"><img src="../img/admin/edit.gif" /></a></div>
				' . $this->displayAddressDetail($addressInvoice) . (!empty($addressInvoice->other) ? '<hr />' . $addressInvoice->other . '<br />' : '') . '</fieldset>
		</div>
		<div class="clear">&nbsp;</div>';
        // List of products
        echo '
		<a name="products"><br /></a>
		<form action="' . $currentIndex . '&submitCreditSlip&vieworder&token=' . $this->token . '" method="post" onsubmit="return orderDeleteProduct(\'' . $this->l('Cannot return this product') . '\', \'' . $this->l('Quantity to cancel is greater than quantity available') . '\');">
			<input type="hidden" name="id_order" value="' . $order->id . '" />
			<fieldset style="width: 868px; ">
				<legend><img src="../img/admin/cart.gif" alt="' . $this->l('Products') . '" />' . $this->l('Products') . '</legend>
				<div style="float:left;">
					<table style="width: 868px;" cellspacing="0" cellpadding="0" class="table" id="orderProducts">
						<tr>
							<th align="center" style="width: 60px">&nbsp;</th>
							<th>' . $this->l('Product') . '</th>
							<th style="width: 80px; text-align: center">' . $this->l('UP') . ' <sup>*</sup></th>
							<th style="width: 20px; text-align: center">' . $this->l('Qty') . '</th>
							' . ($order->hasBeenPaid() ? '<th style="width: 20px; text-align: center">' . $this->l('Refunded') . '</th>' : '') . '
							' . ($order->hasBeenDelivered() ? '<th style="width: 20px; text-align: center">' . $this->l('Returned') . '</th>' : '') . '
							<th style="width: 30px; text-align: center">' . $this->l('Stock') . '</th>
							<th style="width: 90px; text-align: center">' . $this->l('Total') . ' <sup>*</sup></th>
							<th colspan="2" style="width: 120px;"><img src="../img/admin/delete.gif" alt="' . $this->l('Products') . '" /> ' . ($order->hasBeenDelivered() ? $this->l('Return') : ($order->hasBeenPaid() ? $this->l('Refund') : $this->l('Cancel'))) . '</th>';
        echo '
						</tr>';
        $tokenCatalog = Tools::getAdminToken('AdminCatalog' . (int) Tab::getIdFromClassName('AdminCatalog') . (int) $cookie->id_employee);
        foreach ($products as $k => $product) {
            if ($order->getTaxCalculationMethod() == PS_TAX_EXC) {
                $product_price = $product['product_price'] + $product['ecotax'];
            } else {
                $product_price = $product['product_price_wt'];
            }
            $image = array();
            if (isset($product['product_attribute_id']) and (int) $product['product_attribute_id']) {
                $image = Db::getInstance()->getRow('
								SELECT id_image
								FROM ' . _DB_PREFIX_ . 'product_attribute_image
								WHERE id_product_attribute = ' . (int) $product['product_attribute_id']);
            }
            if (!isset($image['id_image']) or !$image['id_image']) {
                $image = Db::getInstance()->getRow('
								SELECT id_image
								FROM ' . _DB_PREFIX_ . 'image
								WHERE id_product = ' . (int) $product['product_id'] . ' AND cover = 1');
            }
            $stock = Db::getInstance()->getRow('
							SELECT ' . ($product['product_attribute_id'] ? 'pa' : 'p') . '.quantity
							FROM ' . _DB_PREFIX_ . 'product p
							' . ($product['product_attribute_id'] ? 'LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute pa ON p.id_product = pa.id_product' : '') . '
							WHERE p.id_product = ' . (int) $product['product_id'] . '
							' . ($product['product_attribute_id'] ? 'AND pa.id_product_attribute = ' . (int) $product['product_attribute_id'] : ''));
            if (isset($image['id_image'])) {
                $target = _PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product['product_id'] . (isset($product['product_attribute_id']) ? '_' . (int) $product['product_attribute_id'] : '') . '.jpg';
                if (file_exists($target)) {
                    $products[$k]['image_size'] = getimagesize($target);
                }
            }
            // Customization display
            $this->displayCustomizedDatas($customizedDatas, $product, $currency, $image, $tokenCatalog, $k);
            // Normal display
            if ($product['product_quantity'] > $product['customizationQuantityTotal']) {
                $quantity = $product['product_quantity'] - $product['customizationQuantityTotal'];
                $imageObj = new Image($image['id_image']);
                echo '
								<tr' . ((isset($image['id_image']) and isset($products[$k]['image_size'])) ? ' height="' . ($products[$k]['image_size'][1] + 7) . '"' : '') . '>
									<td align="center">' . (isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_ . 'p/' . $imageObj->getExistingImgPath() . '.jpg', 'product_mini_' . (int) $product['product_id'] . (isset($product['product_attribute_id']) ? '_' . (int) $product['product_attribute_id'] : '') . '.jpg', 45, 'jpg') : '--') . '</td>
									<td><a href="index.php?tab=AdminCatalog&id_product=' . $product['product_id'] . '&updateproduct&token=' . $tokenCatalog . '">
										<span class="productName">' . $product['product_name'] . '</span><br />
										' . ($product['product_reference'] ? $this->l('Ref:') . ' ' . $product['product_reference'] . '<br />' : '') . ($product['product_supplier_reference'] ? $this->l('Ref Supplier:') . ' ' . $product['product_supplier_reference'] : '') . '</a></td>
									<td align="center">' . Tools::displayPrice($product_price, $currency, false) . '</td>
									<td align="center" class="productQuantity" ' . ($quantity > 1 ? 'style="font-weight:700;font-size:1.1em;color:red"' : '') . '>' . (int) $quantity . '</td>
									' . ($order->hasBeenPaid() ? '<td align="center" class="productQuantity">' . (int) $product['product_quantity_refunded'] . '</td>' : '') . '
									' . ($order->hasBeenDelivered() ? '<td align="center" class="productQuantity">' . (int) $product['product_quantity_return'] . '</td>' : '') . '
									<td align="center" class="productQuantity">' . (int) $stock['quantity'] . '</td>
									<td align="center">' . Tools::displayPrice(Tools::ps_round($product_price, 2) * ((int) $product['product_quantity'] - $product['customizationQuantityTotal']), $currency, false) . '</td>
									<td align="center" class="cancelCheck">
										<input type="hidden" name="totalQtyReturn" id="totalQtyReturn" value="' . (int) $product['product_quantity_return'] . '" />
										<input type="hidden" name="totalQty" id="totalQty" value="' . (int) $product['product_quantity'] . '" />
										<input type="hidden" name="productName" id="productName" value="' . $product['product_name'] . '" />';
                if ((!$order->hasBeenDelivered() or Configuration::get('PS_ORDER_RETURN')) and (int) $product['product_quantity_return'] < (int) $product['product_quantity']) {
                    echo '
										<input type="checkbox" name="id_order_detail[' . $k . ']" id="id_order_detail[' . $k . ']" value="' . $product['id_order_detail'] . '" onchange="setCancelQuantity(this, ' . (int) $product['id_order_detail'] . ', ' . (int) ($product['product_quantity_in_stock'] - $product['customizationQuantityTotal'] - $product['product_quantity_reinjected']) . ')" ' . ((int) ($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int) $product['product_quantity'] ? 'disabled="disabled" ' : '') . '/>';
                } else {
                    echo '--';
                }
                echo '
									</td>
									<td class="cancelQuantity">';
                if ((int) ($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int) $product['product_quantity']) {
                    echo '<input type="hidden" name="cancelQuantity[' . $k . ']" value="0" />';
                } elseif (!$order->hasBeenDelivered() or Configuration::get('PS_ORDER_RETURN')) {
                    echo '
										<input type="text" id="cancelQuantity_' . (int) $product['id_order_detail'] . '" name="cancelQuantity[' . $k . ']" size="2" onclick="selectCheckbox(this);" value="" /> ';
                }
                echo $this->getCancelledProductNumber($order, $product) . '
									</td>
								</tr>';
            }
        }
        echo '
					</table>
					<div style="float:left; width:280px; margin-top:15px;"><sup>*</sup> ' . $this->l('According to the group of this customer, prices are printed:') . ' ' . ($order->getTaxCalculationMethod() == PS_TAX_EXC ? $this->l('tax excluded.') : $this->l('tax included.')) . (!Configuration::get('PS_ORDER_RETURN') ? '<br /><br />' . $this->l('Merchandise returns are disabled') : '') . '</div>';
        if (sizeof($discounts)) {
            echo '
					<div style="float:right; width:280px; margin-top:15px;">
					<table cellspacing="0" cellpadding="0" class="table" style="width:100%;">
						<tr>
							<th><img src="../img/admin/coupon.gif" alt="' . $this->l('Discounts') . '" />' . $this->l('Discount name') . '</th>
							<th align="center" style="width: 100px">' . $this->l('Value') . '</th>
						</tr>';
            foreach ($discounts as $discount) {
                echo '
						<tr>
							<td>' . $discount['name'] . '</td>
							<td align="center">' . ($discount['value'] != 0.0 ? '- ' : '') . Tools::displayPrice($discount['value'], $currency, false) . '</td>
						</tr>';
            }
            echo '
					</table></div>';
        }
        echo '
				</div>';
        // Cancel product
        echo '
				<div style="clear:both; height:15px;">&nbsp;</div>
				<div style="float: right; width: 160px;">';
        if ($order->hasBeenDelivered() and Configuration::get('PS_ORDER_RETURN')) {
            echo '
					<input type="checkbox" id="reinjectQuantities" name="reinjectQuantities" class="button" />&nbsp;<label for="reinjectQuantities" style="float:none; font-weight:normal;">' . $this->l('Re-stock products') . '</label><br />';
        }
        if (!$order->hasBeenDelivered() and $order->hasBeenPaid() or $order->hasBeenDelivered() and Configuration::get('PS_ORDER_RETURN')) {
            echo '
					<input type="checkbox" id="generateCreditSlip" name="generateCreditSlip" class="button" onclick="toogleShippingCost(this)" />&nbsp;<label for="generateCreditSlip" style="float:none; font-weight:normal;">' . $this->l('Generate a credit slip') . '</label><br />
					<input type="checkbox" id="generateDiscount" name="generateDiscount" class="button" onclick="toogleShippingCost(this)" />&nbsp;<label for="generateDiscount" style="float:none; font-weight:normal;">' . $this->l('Generate a voucher') . '</label><br />
					<span id="spanShippingBack" style="display:none;"><input type="checkbox" id="shippingBack" name="shippingBack" class="button" />&nbsp;<label for="shippingBack" style="float:none; font-weight:normal;">' . $this->l('Repay shipping costs') . '</label><br /></span>';
        }
        if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Configuration::get('PS_ORDER_RETURN')) {
            echo '
					<div style="text-align:center; margin-top:5px;"><input type="submit" name="cancelProduct" value="' . ($order->hasBeenDelivered() ? $this->l('Return products') : ($order->hasBeenPaid() ? $this->l('Refund products') : $this->l('Cancel products'))) . '" class="button" style="margin-top:8px;" /></div>';
        }
        echo '
				</div>';
        echo '
			</fieldset>
		</form>
		<div class="clear" style="height:20px;">&nbsp;</div>';
        /* Display send a message to customer & returns/credit slip*/
        $returns = OrderReturn::getOrdersReturn($order->id_customer, $order->id);
        $slips = OrderSlip::getOrdersSlip($order->id_customer, $order->id);
        echo '
		<div style="float: left">
			<form action="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '&token=' . $this->token . '" method="post" onsubmit="if (getE(\'visibility\').checked == true) return confirm(\'' . $this->l('Do you want to send this message to the customer?', __CLASS__, true, false) . '\');">
			<fieldset style="width: 400px;">
				<legend style="cursor: pointer;" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><img src="../img/admin/email_edit.gif" /> ' . $this->l('New message') . '</legend>
				<div id="message_m" style="display: ' . (Tools::getValue('message') ? 'none' : 'block') . '; overflow: auto; width: 400px;">
					<a href="#" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><b>' . $this->l('Click here') . '</b> ' . $this->l('to add a comment or send a message to the customer') . '</a>
				</div>
				<div id="message" style="display: ' . (Tools::getValue('message') ? 'block' : 'none') . '">
					<select name="order_message" id="order_message" onchange="orderOverwriteMessage(this, \'' . $this->l('Do you want to overwrite your existing message?') . '\')">
						<option value="0" selected="selected">-- ' . $this->l('Choose a standard message') . ' --</option>';
        $orderMessages = OrderMessage::getOrderMessages((int) $order->id_lang);
        foreach ($orderMessages as $orderMessage) {
            echo '		<option value="' . htmlentities($orderMessage['message'], ENT_COMPAT, 'UTF-8') . '">' . $orderMessage['name'] . '</option>';
        }
        echo '		</select><br /><br />
					<b>' . $this->l('Display to consumer?') . '</b>
					<input type="radio" name="visibility" id="visibility" value="0" /> ' . $this->l('Yes') . '
					<input type="radio" name="visibility" value="1" checked="checked" /> ' . $this->l('No') . '
					<p id="nbchars" style="display:inline;font-size:10px;color:#666;"></p><br /><br />
					<textarea id="txt_msg" name="message" cols="50" rows="8" onKeyUp="var length = document.getElementById(\'txt_msg\').value.length; if (length > 600) length = \'600+\'; document.getElementById(\'nbchars\').innerHTML = \'' . $this->l('600 chars max') . ' (\' + length + \')\';">' . htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8') . '</textarea><br /><br />
					<input type="hidden" name="id_order" value="' . (int) $order->id . '" />
					<input type="hidden" name="id_customer" value="' . (int) $order->id_customer . '" />
					<input type="submit" class="button" name="submitMessage" value="' . $this->l('Send') . '" />
				</div>
			</fieldset>
			</form>';
        /* Display list of messages */
        if (sizeof($messages)) {
            echo '
			<br />
			<fieldset style="width: 400px;">
			<legend><img src="../img/admin/email.gif" /> ' . $this->l('Messages') . '</legend>';
            foreach ($messages as $message) {
                echo '<div style="overflow:auto; width:400px;" ' . ($message['is_new_for_me'] ? 'class="new_message"' : '') . '>';
                if ($message['is_new_for_me']) {
                    echo '<a class="new_message" title="' . $this->l('Mark this message as \'viewed\'') . '" href="' . Tools::safeOutput($_SERVER['REQUEST_URI']) . '&token=' . $this->token . '&messageReaded=' . (int) $message['id_message'] . '"><img src="../img/admin/enabled.gif" alt="" /></a>';
                }
                echo $this->l('At') . ' <i>' . Tools::displayDate($message['date_add'], (int) $cookie->id_lang, true);
                echo '</i> ' . $this->l('from') . ' <b>' . ($message['elastname'] ? $message['efirstname'] . ' ' . $message['elastname'] : $message['cfirstname'] . ' ' . $message['clastname']) . '</b>';
                echo (int) $message['private'] == 1 ? '<span style="color:red; font-weight:bold;">' . $this->l('Private:') . '</span>' : '';
                echo '<p>' . nl2br2($message['message']) . '</p>';
                echo '</div>';
                echo '<br />';
            }
            echo '<p class="info">' . $this->l('When you read a message, please click on the green check.') . '</p>';
            echo '</fieldset>';
        }
        echo '</div>';
        /* Display return product */
        echo '<div style="float: left; margin-left: 40px">
			<fieldset style="width: 400px;">
				<legend><img src="../img/admin/return.gif" alt="' . $this->l('Merchandise returns') . '" />' . $this->l('Merchandise returns') . '</legend>';
        if (!sizeof($returns)) {
            echo $this->l('No merchandise return for this order.');
        } else {
            foreach ($returns as $return) {
                $state = new OrderReturnState($return['state']);
                echo '(' . Tools::displayDate($return['date_upd'], $cookie->id_lang) . ') :
				<b><a href="index.php?tab=AdminReturn&id_order_return=' . $return['id_order_return'] . '&updateorder_return&token=' . Tools::getAdminToken('AdminReturn' . (int) Tab::getIdFromClassName('AdminReturn') . (int) $cookie->id_employee) . '">' . $this->l('#') . sprintf('%06d', $return['id_order_return']) . '</a></b> -
				' . $state->name[$cookie->id_lang] . '<br />';
            }
        }
        echo '</fieldset>';
        /* Display credit slip */
        echo '
				<br />
				<fieldset style="width: 400px;">
					<legend><img src="../img/admin/slip.gif" alt="' . $this->l('Credit slip') . '" />' . $this->l('Credit slip') . '</legend>';
        if (!sizeof($slips)) {
            echo $this->l('No slip for this order.');
        } else {
            foreach ($slips as $slip) {
                echo '(' . Tools::displayDate($slip['date_upd'], $cookie->id_lang) . ') : <b><a href="pdf.php?id_order_slip=' . $slip['id_order_slip'] . '">' . $this->l('#') . sprintf('%06d', $slip['id_order_slip']) . '</a></b><br />';
            }
        }
        echo '</fieldset>
		</div>';
        echo '<div class="clear">&nbsp;</div>';
        echo '<br /><br /><a href="' . $currentIndex . '&token=' . $this->token . '"><img src="../img/admin/arrow2.gif" /> ' . $this->l('Back to list') . '</a><br />';
    }
 public function renderView()
 {
     $neoExchange = new NeoExchanges(Tools::getValue('id_neo_exchange'));
     $order = new Order(Tools::getValue('id_neo_exchange'));
     if (!Validate::isLoadedObject($neoExchange)) {
         $this->errors[] = Tools::displayError('The order cannot be found within your database.');
     }
     $customer = new Customer($neoExchange->id_customer);
     //$carrier = new Carrier($neoExchange->id_carrier);
     $currency = new Currency((int) $neoExchange->id_currency);
     $buys = new NeoItemsBuyCore(Tools::getValue('id_neo_exchange'));
     $sales = new NeoItemsSalesCore(Tools::getValue('id_neo_exchange'));
     $products = $this->getProducts($buys);
     $products2 = $this->getProducts($sales);
     //$products = $this->getProducts($neoExchange);
     // Carrier module call
     /*$carrier_module_call = null;
             if ($carrier->is_module)
             {
                 $module = Module::getInstanceByName($carrier->external_module_name);
                 if (method_exists($module, 'displayInfoByCart'))
                     $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $neoExchange->id_cart);
             }
     
             // Retrieve addresses information
             $addressInvoice = new Address($neoExchange->id_address_invoice, $this->context->language->id);
             if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state)
                 $invoiceState = new State((int)$addressInvoice->id_state);
     
             if ($neoExchange->id_address_invoice == $neoExchange->id_address_delivery)
             {
                 $addressDelivery = $addressInvoice;
                 if (isset($invoiceState))
                     $deliveryState = $invoiceState;
             }
             else
             {
                 $addressDelivery = new Address($neoExchange->id_address_delivery, $this->context->language->id);
                 if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state)
                     $deliveryState = new State((int)($addressDelivery->id_state));
             }*/
     $this->toolbar_title = sprintf($this->l('Intercambio #%1$d (%2$s) - %3$s %4$s'), $neoExchange->id, $neoExchange->reference, $customer->firstname, $customer->lastname);
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $neoExchange->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->l('Shop: %s'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $neoExchange->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     $total_buy = 0;
     $total_sale = 0;
     $products_buy = count($products);
     $products_sale = count($products2);
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         $total_buy += $product['price'];
     }
     foreach ($products2 as &$product) {
         $total_sale += $product['price'];
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $neoExchange->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $neoExchange, 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'customerStats' => $customer->getStats(), 'products' => $products, 'products2' => $products2, 'total_buy' => $total_buy, 'total_sale' => $total_sale, 'products_buy' => $products_buy, 'products_sale' => $products_sale, 'neo_order_shipping_price' => 0, 'orders_total_paid_tax_incl' => $neoExchange->getOrdersTotalPaid(), 'total_paid' => $neoExchange->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($neoExchange->id_customer, $neoExchange->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($neoExchange->id_customer), 'orderMessages' => OrderMessage::getOrderMessages($neoExchange->id_lang), 'messages' => Message::getMessagesByOrderId($neoExchange->id, true), 'history' => $history, 'neoStatus' => NeoStatusCore::getNeoStatus(), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($neoExchange->id), 'currentState' => $neoExchange->getCurrentOrderState(), 'currency' => new Currency($neoExchange->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($neoExchange->id_shop), 'previousOrder' => $neoExchange->getPreviousOrderId(), 'nextOrder' => $neoExchange->getNextOrderId(), 'current_index' => self::$currentIndex, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->tabAccess['edit'] == 1, 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $neoExchange->getInvoicesCollection(), 'not_paid_invoices_collection' => $neoExchange->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $neoExchange->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $neoExchange, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
 public function renderView()
 {
     $order = new Order(Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         $this->errors[] = $this->trans('The order cannot be found within your database.', array(), 'Admin.OrdersCustomers.Notification');
     }
     $customer = new Customer($order->id_customer);
     $carrier = new Carrier($order->id_carrier);
     $products = $this->getProducts($order);
     $currency = new Currency((int) $order->id_currency);
     // Carrier module call
     $carrier_module_call = null;
     if ($carrier->is_module) {
         $module = Module::getInstanceByName($carrier->external_module_name);
         if (method_exists($module, 'displayInfoByCart')) {
             $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
         }
     }
     // Retrieve addresses information
     $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
     if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state) {
         $invoiceState = new State((int) $addressInvoice->id_state);
     }
     if ($order->id_address_invoice == $order->id_address_delivery) {
         $addressDelivery = $addressInvoice;
         if (isset($invoiceState)) {
             $deliveryState = $invoiceState;
         }
     } else {
         $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
         if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state) {
             $deliveryState = new State((int) $addressDelivery->id_state);
         }
     }
     $this->toolbar_title = $this->trans('Order #%id% (%ref%) - %firstname% %lastname%', array('%id%' => $order->id, '%ref%' => $order->reference, '%firstname%' => $customer->firstname, '%lastname%' => $customer->lastname), 'Admin.OrdersCustomers.Feature');
     if (Shop::isFeatureActive()) {
         $shop = new Shop((int) $order->id_shop);
         $this->toolbar_title .= ' - ' . sprintf($this->trans('Shop: %s', array(), 'Admin.OrdersCustomers.Feature'), $shop->name);
     }
     // gets warehouses to ship products, if and only if advanced stock management is activated
     $warehouse_list = null;
     $order_details = $order->getOrderDetailList();
     foreach ($order_details as $order_detail) {
         $product = new Product($order_detail['product_id']);
         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management) {
             $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
             foreach ($warehouses as $warehouse) {
                 if (!isset($warehouse_list[$warehouse['id_warehouse']])) {
                     $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
                 }
             }
         }
     }
     $payment_methods = array();
     foreach (PaymentModule::getInstalledPaymentModules() as $payment) {
         $module = Module::getInstanceByName($payment['name']);
         if (Validate::isLoadedObject($module) && $module->active) {
             $payment_methods[] = $module->displayName;
         }
     }
     // display warning if there are products out of stock
     $display_out_of_stock_warning = false;
     $current_order_state = $order->getCurrentOrderState();
     if (Configuration::get('PS_STOCK_MANAGEMENT') && (!Validate::isLoadedObject($current_order_state) || $current_order_state->delivery != 1 && $current_order_state->shipped != 1)) {
         $display_out_of_stock_warning = true;
     }
     // products current stock (from stock_available)
     foreach ($products as &$product) {
         // Get total customized quantity for current product
         $customized_product_quantity = 0;
         if (is_array($product['customizedDatas'])) {
             foreach ($product['customizedDatas'] as $customizationPerAddress) {
                 foreach ($customizationPerAddress as $customizationId => $customization) {
                     $customized_product_quantity += (int) $customization['quantity'];
                 }
             }
         }
         $product['customized_product_quantity'] = $customized_product_quantity;
         $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
         $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
         $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
         $product['amount_refundable'] = $product['total_price_tax_excl'] - $resume['amount_tax_excl'];
         $product['amount_refundable_tax_incl'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
         $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
         $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
         $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
         // if the current stock requires a warning
         if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
             $this->displayWarning($this->trans('This product is out of stock: ', array(), 'Admin.OrdersCustomers.Notification') . ' ' . $product['product_name']);
         }
         if ($product['id_warehouse'] != 0) {
             $warehouse = new Warehouse((int) $product['id_warehouse']);
             $product['warehouse_name'] = $warehouse->name;
             $warehouse_location = WarehouseProductLocation::getProductLocation($product['product_id'], $product['product_attribute_id'], $product['id_warehouse']);
             if (!empty($warehouse_location)) {
                 $product['warehouse_location'] = $warehouse_location;
             } else {
                 $product['warehouse_location'] = false;
             }
         } else {
             $product['warehouse_name'] = '--';
             $product['warehouse_location'] = false;
         }
     }
     // Package management for order
     foreach ($products as &$product) {
         $pack_items = $product['cache_is_pack'] ? Pack::getItemTable($product['id_product'], $this->context->language->id, true) : array();
         foreach ($pack_items as &$pack_item) {
             $pack_item['current_stock'] = StockAvailable::getQuantityAvailableByProduct($pack_item['id_product'], $pack_item['id_product_attribute'], $pack_item['id_shop']);
             // if the current stock requires a warning
             if ($product['current_stock'] <= 0 && $display_out_of_stock_warning) {
                 $this->displayWarning($this->trans('This product, included in package (' . $product['product_name'] . ') is out of stock: ', array(), 'Admin.OrdersCustomers.Notification') . ' ' . $pack_item['product_name']);
             }
             $this->setProductImageInformations($pack_item);
             if ($pack_item['image'] != null) {
                 $name = 'product_mini_' . (int) $pack_item['id_product'] . (isset($pack_item['id_product_attribute']) ? '_' . (int) $pack_item['id_product_attribute'] : '') . '.jpg';
                 // generate image cache, only for back office
                 $pack_item['image_tag'] = ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $pack_item['image']->getExistingImgPath() . '.jpg', $name, 45, 'jpg');
                 if (file_exists(_PS_TMP_IMG_DIR_ . $name)) {
                     $pack_item['image_size'] = getimagesize(_PS_TMP_IMG_DIR_ . $name);
                 } else {
                     $pack_item['image_size'] = false;
                 }
             }
         }
         $product['pack_items'] = $pack_items;
     }
     $gender = new Gender((int) $customer->id_gender, $this->context->language->id);
     $history = $order->getHistory($this->context->language->id);
     foreach ($history as &$order_state) {
         $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black';
     }
     // Smarty assign
     $this->tpl_view_vars = array('order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array('delivery' => $addressDelivery, 'deliveryState' => isset($deliveryState) ? $deliveryState : null, 'invoice' => $addressInvoice, 'invoiceState' => isset($invoiceState) ? $invoiceState : null), 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), 'total_paid' => $order->getTotalPaid(), 'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), 'currentState' => $order->getCurrentOrderState(), 'currency' => new Currency($order->id_currency), 'currencies' => Currency::getCurrenciesByIdShop($order->id_shop), 'previousOrder' => $order->getPreviousOrderId(), 'nextOrder' => $order->getNextOrderId(), 'current_index' => self::$currentIndex, 'carrierModuleCall' => $carrier_module_call, 'iso_code_lang' => $this->context->language->iso_code, 'id_lang' => $this->context->language->id, 'can_edit' => $this->access('edit'), 'current_id_lang' => $this->context->language->id, 'invoices_collection' => $order->getInvoicesCollection(), 'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(), 'payment_methods' => $payment_methods, 'invoice_management_active' => Configuration::get('PS_INVOICE', null, null, $order->id_shop), 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'carrier_list' => $this->getCarrierList($order), 'recalculate_shipping_cost' => (int) Configuration::get('PS_ORDER_RECALCULATE_SHIPPING'), 'HOOK_CONTENT_ORDER' => Hook::exec('displayAdminOrderContentOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_CONTENT_SHIP' => Hook::exec('displayAdminOrderContentShip', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_ORDER' => Hook::exec('displayAdminOrderTabOrder', array('order' => $order, 'products' => $products, 'customer' => $customer)), 'HOOK_TAB_SHIP' => Hook::exec('displayAdminOrderTabShip', array('order' => $order, 'products' => $products, 'customer' => $customer)));
     return parent::renderView();
 }
 public function renderView()
 {
     /** @var Cart $cart */
     if (!($cart = $this->loadObject(true))) {
         return;
     }
     $customer = new Customer($cart->id_customer);
     $currency = new Currency($cart->id_currency);
     $this->context->cart = $cart;
     $this->context->currency = $currency;
     $this->context->customer = $customer;
     $this->toolbar_title = sprintf($this->l('Cart #%06d'), $this->context->cart->id);
     $products = $cart->getProducts();
     $customized_datas = Product::getAllCustomizedDatas((int) $cart->id);
     Product::addCustomizationPrice($products, $customized_datas);
     $summary = $cart->getSummaryDetails();
     /* Display order information */
     $id_order = (int) Order::getOrderByCartId($cart->id);
     $order = new Order($id_order);
     if (Validate::isLoadedObject($order)) {
         $tax_calculation_method = $order->getTaxCalculationMethod();
         $id_shop = (int) $order->id_shop;
     } else {
         $id_shop = (int) $cart->id_shop;
         $tax_calculation_method = Group::getPriceDisplayMethod(Group::getCurrent()->id);
     }
     if ($tax_calculation_method == PS_TAX_EXC) {
         $total_products = $summary['total_products'];
         $total_discounts = $summary['total_discounts_tax_exc'];
         $total_wrapping = $summary['total_wrapping_tax_exc'];
         $total_price = $summary['total_price_without_tax'];
         $total_shipping = $summary['total_shipping_tax_exc'];
     } else {
         $total_products = $summary['total_products_wt'];
         $total_discounts = $summary['total_discounts'];
         $total_wrapping = $summary['total_wrapping'];
         $total_price = $summary['total_price'];
         $total_shipping = $summary['total_shipping'];
     }
     foreach ($products as $k => &$product) {
         if ($tax_calculation_method == PS_TAX_EXC) {
             $product['product_price'] = $product['price'];
             $product['product_total'] = $product['total'];
         } else {
             $product['product_price'] = $product['price_wt'];
             $product['product_total'] = $product['total_wt'];
         }
         $image = array();
         if (isset($product['id_product_attribute']) && (int) $product['id_product_attribute']) {
             $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'product_attribute_image WHERE id_product_attribute = ' . (int) $product['id_product_attribute']);
         }
         if (!isset($image['id_image'])) {
             $image = Db::getInstance()->getRow('SELECT id_image FROM ' . _DB_PREFIX_ . 'image WHERE id_product = ' . (int) $product['id_product'] . ' AND cover = 1');
         }
         $product['qty_in_stock'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], isset($product['id_product_attribute']) ? $product['id_product_attribute'] : null, (int) $id_shop);
         $image_product = new Image($image['id_image']);
         $product['image'] = isset($image['id_image']) ? ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $image_product->getExistingImgPath() . '.jpg', 'product_mini_' . (int) $product['id_product'] . (isset($product['id_product_attribute']) ? '_' . (int) $product['id_product_attribute'] : '') . '.jpg', 45, 'jpg') : '--';
     }
     $helper = new HelperKpi();
     $helper->id = 'box-kpi-cart';
     $helper->icon = 'icon-shopping-cart';
     $helper->color = 'color1';
     $helper->title = $this->l('Total Cart', null, null, false);
     $helper->subtitle = sprintf($this->l('Cart #%06d', null, null, false), $cart->id);
     $helper->value = Tools::displayPrice($total_price, $currency);
     $kpi = $helper->generate();
     // by webkul to show rooms available in the cart
     $cart_id = $cart->id;
     $cart_detail_data = array();
     $cart_detail_data_obj = new HotelCartBookingData();
     $cart_detail_data = $cart_detail_data_obj->getCartCurrentDataByCartId((int) $cart_id);
     if ($cart_detail_data) {
         foreach ($cart_detail_data as $key => $value) {
             $product_image_id = Product::getCover($value['id_product']);
             $link_rewrite = (new Product((int) $value['id_product'], Configuration::get('PS_LANG_DEFAULT')))->link_rewrite[Configuration::get('PS_LANG_DEFAULT')];
             if ($product_image_id) {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $product_image_id['id_image'], 'small_default');
             } else {
                 $cart_detail_data[$key]['image_link'] = $this->context->link->getImageLink($link_rewrite, $this->context->language->iso_code . "-default", 'small_default');
             }
             $cart_detail_data[$key]['room_type'] = (new Product((int) $value['id_product']))->name[Configuration::get('PS_LANG_DEFAULT')];
             $cart_detail_data[$key]['room_num'] = (new HotelRoomInformation((int) $value['id_room']))->room_num;
             $cart_detail_data[$key]['date_from'] = (new DateTime($value['date_from']))->format('d-M Y');
             $cart_detail_data[$key]['date_to'] = (new DateTime($value['date_to']))->format('d-M Y');
         }
     }
     //end
     $this->tpl_view_vars = array('cart_detail_data' => $cart_detail_data, 'kpi' => $kpi, 'products' => $products, 'discounts' => $cart->getCartRules(), 'order' => $order, 'cart' => $cart, 'currency' => $currency, 'customer' => $customer, 'customer_stats' => $customer->getStats(), 'total_products' => $total_products, 'total_discounts' => $total_discounts, 'total_wrapping' => $total_wrapping, 'total_price' => $total_price, 'total_shipping' => $total_shipping, 'customized_datas' => $customized_datas, 'tax_calculation_method' => $tax_calculation_method);
     return parent::renderView();
 }