/** * check and update stocks * @return array */ public function checkAndUpdateStocks() { $products = $this->order->getProducts(); $productRepo = new ProductRepository(); /** @var $orderProduct OrderProduct */ $productsEmptyStocks = array(); foreach ($products as $orderProduct) { /** @var $product SimpleProduct */ $product = $productRepo->getProduct($orderProduct->product_srl, false); if ($orderProduct->quantity == $product->qty) { $productsEmptyStocks[] = $product; } $product->substractFromStock($orderProduct->quantity); } return $productsEmptyStocks; }
protected function getArticles(Order $order, $cart = false) { $this->to_refund = 0; $this->to_refund_tax = 0; if ($cart) { $products = $cart->getProducts(); } else { $products = $order->getProducts(); foreach ($products as $key => &$order_item) { $order_item['product_quantity'] -= $order_item['product_quantity_refunded']; $this->to_refund += $order_item['product_quantity_refunded'] * $order_item['unit_price_tax_incl']; $this->to_refund_tax += $order_item['product_quantity_refunded'] * $order_item['unit_price_tax_excl']; if ((int) $order_item['product_quantity'] <= 0) { unset($products[$key]); } } } $articles = array(); $link = new Link(); foreach ($products as $order_item) { if ($cart) { $productId = $order_item['id_product']; $Product = new Product($productId); $discounts = $order_item['reduction_applies']; $quantity = $order_item['cart_quantity']; $price = $order_item['price_wt']; $description_short = strip_tags($order_item['description_short']); $image_url = str_replace('http://', '', $link->getImageLink('product', $order_item['id_image'])); $name = $order_item['name']; $sku = $order_item['id_product_attribute']; $product_url = $link->getProductLink($productId); } else { $productId = $order_item['product_id']; $Product = new Product($productId); $discounts = $order_item['reduction_amount_tax_incl']; $quantity = $order_item['product_quantity']; $price = $order_item['unit_price_tax_incl']; $description_short = strip_tags($order_item['description_short']); $image_url = str_replace('http://', '', $link->getImageLink('product', $order_item['image']->id)); $name = $order_item['product_name']; $sku = $order_item['product_attribute_id']; $product_url = $link->getProductLink($productId); } $articles[] = array("id" => $productId, "sku" => $sku, "name" => $name, "description" => substr($description_short, 0, 255), "url" => $product_url, "image_url" => 'http://' . $image_url, "quantity" => intval($quantity), "price" => static::formatDecimals($price), "tax_rate" => static::formatDecimals($Product->getTaxesRate()), "discount" => static::formatDecimals($discounts)); } return $articles; }
public function initContent() { parent::initContent(); $this->context->smarty->assign(array('is_guest' => $this->context->customer->is_guest, 'HOOK_ORDER_CONFIRMATION' => $this->displayOrderConfirmation(), 'HOOK_PAYMENT_RETURN' => $this->displayPaymentReturn())); $order = new Order((int) $this->id_order); if ($this->context->customer->is_guest) { $this->context->smarty->assign(array('name' => $this->context->customer->firstname . ' ' . $this->context->customer->lastname, 'id_order' => $this->id_order, 'reference_order' => $this->reference, 'id_order_formatted' => sprintf('#%06d', $this->id_order), 'email' => $this->context->customer->email, 'amount' => $order->total_paid)); /* If guest we clear the cookie for security reason */ $this->context->customer->mylogout(); } else { $this->context->smarty->assign(array('id_order' => $this->id_order, 'reference_order' => $this->reference, 'id_order_formatted' => sprintf('#%06d', $this->id_order), 'name' => $this->context->customer->firstname, 'amount' => $order->total_paid)); } $order = new Order($this->id_order); $products = $order->getProducts(); $this->context->smarty->assign(array('order' => $order, 'products' => $products)); $this->setTemplate(_PS_THEME_DIR_ . 'order-confirmation.tpl'); }
/** * Convert the entities data into an xml object and return the xml object as a string * * @param array $aEntity Entity data */ public function formatEntityToXML($aEntity) { $dom = new DOMDocument('1.0', 'utf-8'); // Set the root of the XML $root = $dom->createElement($this->sEntity); $dom->appendChild($root); $oOrder = new Order((int) $aEntity['id_order']); $root->setAttribute("isodate", date('c', strtotime($oOrder->invoice_date))); $userid = $dom->createElement('userid', (int) $oOrder->id_customer); $root->appendChild($userid); $transactionid = $dom->createElement('transactionid', (int) $oOrder->id); $root->appendChild($transactionid); $aOrderProducts = $oOrder->getProducts(); $sReturn = false; if (is_array($aOrderProducts) && count($aOrderProducts) > 0) { foreach ($aOrderProducts as $aOrderProduct) { $item = $dom->createElement('item'); $root->appendChild($item); $itemid = $dom->createElement('itemid', (int) $aOrderProduct['product_id']); $item->appendChild($itemid); $profile = $dom->createElement('profile', (int) $aEntity['id_shop']); $item->appendChild($profile); if ($oOrder->getTaxCalculationMethod() == PS_TAX_EXC) { $product_price = $aOrderProduct['product_price'] + $aOrderProduct['ecotax']; } else { $product_price = $aOrderProduct['product_price_wt']; } $price = $dom->createElement('price', number_format(Tools::ps_round($product_price, 2), 2, '.', '')); $item->appendChild($price); $quantity = $dom->createElement('quantity', (int) $aOrderProduct['product_quantity']); $item->appendChild($quantity); } $sReturn = $dom->saveHTML(); } unset($dom); unset($oOrder); unset($aOrderProducts); return $sReturn; }
/** * Finds purchased items for the order. * * @param Context $context the context. * @param Order $order the order object. * @return NostoTaggingOrderPurchasedItem[] the purchased items. */ protected function findPurchasedItems(Context $context, Order $order) { $purchased_items = array(); $currency = new Currency($order->id_currency); if (!Validate::isLoadedObject($currency)) { return $purchased_items; } $products = array(); $total_discounts_tax_incl = 0; $total_shipping_tax_incl = 0; $total_wrapping_tax_incl = 0; $total_gift_tax_incl = 0; // Cart rules and split orders are available from prestashop 1.5 onwards. if (_PS_VERSION_ >= '1.5') { // One order can be split into multiple orders, so we need to combine their data. $order_collection = Order::getByReference($order->reference); foreach ($order_collection as $item) { /** @var $item Order */ $products = array_merge($products, $item->getProducts()); $total_discounts_tax_incl = Tools::ps_round($total_discounts_tax_incl + $item->total_discounts_tax_incl, 2); $total_shipping_tax_incl = Tools::ps_round($total_shipping_tax_incl + $item->total_shipping_tax_incl, 2); $total_wrapping_tax_incl = Tools::ps_round($total_wrapping_tax_incl + $item->total_wrapping_tax_incl, 2); } // We need the cart rules used for the order to check for gift products and free shipping. // The cart is the same even if the order is split into many objects. $cart = new Cart($order->id_cart); if (Validate::isLoadedObject($cart)) { $cart_rules = (array) $cart->getCartRules(); } else { $cart_rules = array(); } $gift_products = array(); foreach ($cart_rules as $cart_rule) { if ((int) $cart_rule['gift_product']) { foreach ($products as $key => &$product) { if (empty($product['gift']) && (int) $product['product_id'] === (int) $cart_rule['gift_product'] && (int) $product['product_attribute_id'] === (int) $cart_rule['gift_product_attribute']) { $product['product_quantity'] = (int) $product['product_quantity']; $product['product_quantity']--; if (!($product['product_quantity'] > 0)) { unset($products[$key]); } $total_gift_tax_incl = Tools::ps_round($total_gift_tax_incl + $product['product_price_wt'], 2); $gift_product = $product; $gift_product['product_quantity'] = 1; $gift_product['product_price_wt'] = 0; $gift_product['gift'] = true; $gift_products[] = $gift_product; break; // One gift product per cart rule } } unset($product); } } $items = array_merge($products, $gift_products); } else { $products = $order->getProducts(); $total_discounts_tax_incl = $order->total_discounts; $total_shipping_tax_incl = $order->total_shipping; $total_wrapping_tax_incl = $order->total_wrapping; $items = $products; } $id_lang = (int) $context->language->id; foreach ($items as $item) { $p = new Product($item['product_id'], false, $context->language->id); if (Validate::isLoadedObject($p)) { $product_name = $p->name; $id_attribute = (int) $item['product_attribute_id']; $attribute_combinations = $this->getProductAttributeCombinationsById($p, $id_attribute, $id_lang); if (!empty($attribute_combinations)) { $attribute_combination_names = array(); foreach ($attribute_combinations as $attribute_combination) { $attribute_combination_names[] = $attribute_combination['attribute_name']; } if (!empty($attribute_combination_names)) { $product_name .= ' (' . implode(', ', $attribute_combination_names) . ')'; } } $purchased_item = new NostoTaggingOrderPurchasedItem(); $purchased_item->setProductId((int) $p->id); $purchased_item->setQuantity((int) $item['product_quantity']); $purchased_item->setName((string) $product_name); $purchased_item->setUnitPrice(Nosto::helper('price')->format($item['product_price_wt'])); $purchased_item->setCurrencyCode((string) $currency->iso_code); $purchased_items[] = $purchased_item; } } if ($this->include_special_items && !empty($purchased_items)) { // Add special items for discounts, shipping and gift wrapping. if ($total_discounts_tax_incl > 0) { // Subtract possible gift product price from total as gifts are tagged with price zero (0). $total_discounts_tax_incl = Tools::ps_round($total_discounts_tax_incl - $total_gift_tax_incl, 2); if ($total_discounts_tax_incl > 0) { $purchased_item = new NostoTaggingOrderPurchasedItem(); $purchased_item->setProductId(-1); $purchased_item->setQuantity(1); $purchased_item->setName('Discount'); // Note the negative value. $purchased_item->setUnitPrice(Nosto::helper('price')->format(-$total_discounts_tax_incl)); $purchased_item->setCurrencyCode((string) $currency->iso_code); $purchased_items[] = $purchased_item; } } // Check is free shipping applies to the cart. $free_shipping = false; if (isset($cart_rules)) { foreach ($cart_rules as $cart_rule) { if ((int) $cart_rule['free_shipping']) { $free_shipping = true; break; } } } if (!$free_shipping && $total_shipping_tax_incl > 0) { $purchased_item = new NostoTaggingOrderPurchasedItem(); $purchased_item->setProductId(-1); $purchased_item->setQuantity(1); $purchased_item->setName('Shipping'); $purchased_item->setUnitPrice(Nosto::helper('price')->format($total_shipping_tax_incl)); $purchased_item->setCurrencyCode((string) $currency->iso_code); $purchased_items[] = $purchased_item; } if ($total_wrapping_tax_incl > 0) { $purchased_item = new NostoTaggingOrderPurchasedItem(); $purchased_item->setProductId(-1); $purchased_item->setQuantity(1); $purchased_item->setName('Gift Wrapping'); $purchased_item->setUnitPrice(Nosto::helper('price')->format($total_wrapping_tax_incl)); $purchased_item->setCurrencyCode((string) $currency->iso_code); $purchased_items[] = $purchased_item; } } return $purchased_items; }
public function hookPaymentReturn($params) { global $cookie, $smarty; include dirname(__FILE__) . '/includes/Shop.php'; // dados do cliente $customer = new Customer(intval($cookie->id_customer)); $ArrayCliente = $customer->getFields(); // dados do pedido $DadosOrder = new Order($params['objOrder']->id); $ArrayListaProdutos = $DadosOrder->getProducts(); // gera descri�?o foreach ($ArrayListaProdutos as $info) { $item = array($zb[] = $info['product_name'] . ' * ' . $info['product_quantity']); } $descricao = implode(" + ", $zb); $currency = new Currency($DadosOrder->id_currency); $dados = array("external_reference" => $params['objOrder']->id, "currency" => $currency->iso_code, "title" => $descricao, "description" => $descricao, 'quantity' => 1, 'image' => '', 'amount' => $params['total_to_pay'], 'payment_firstname' => $ArrayCliente['firstname'], 'payment_lastname' => $ArrayCliente['lastname'], 'email' => $ArrayCliente['email'], 'pending' => Configuration::get('mercadopago_URLPROCESS'), 'approved' => Configuration::get('mercadopago_URLSUCCESFULL')); $client = Configuration::get('mercadopago_CLIENT_ID'); $secret = Configuration::get('mercadopago_CLIENT_SECRET'); $exclude = Configuration::get('mercadopago_METHODS'); $pagamento = new MPShop($client, $secret); $botton = $pagamento->GetCheckout($dados, $exclude); $country = Configuration::get('mercadopago_COUNTRY'); switch ($country) { case 'MLA': $banner = 'modules/mercadopago/imagens/mercadopagoar.jpg'; break; case 'MLB': $banner = 'modules/mercadopago/imagens/mercadopagobr.jpg'; break; case 'MLM': $banner = 'modules/mercadopago/imagens/mercadopagomx.jpg'; break; case 'MLV': $banner = 'modules/mercadopago/imagens/mercadopagov.jpg'; break; default: $banner = 'modules/mercadopago/imagens/mercadopagobr.jpg'; } $smarty->assign(array('totalApagar' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false, false), 'status' => 'ok', 'seller_op_id' => $params['objOrder']->id, 'secure_key' => $params['objOrder']->secure_key, 'id_module' => $this->id, 'formmercadopago' => $botton, 'imgBnr' => $banner)); return $this->display(__FILE__, 'payment_return.tpl'); }
private function get_flux_xml_products() { $flux_xml = ''; $order = new Order((int) $this->id_order); $products = $order->getProducts(); foreach ($products as $product) { $data = Db::getInstance()->getRow(' SELECT sac.`category_id`, pl.`name` FROM `' . _DB_PREFIX_ . 'secuvad_assoc_category` sac JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = sac.`id_category`) JOIN `' . _DB_PREFIX_ . 'category` c ON (c.`id_category` = cp.`id_category`) JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (cp.`id_product` = pl.`id_product`' . $this->context->shop->addSqlRestrictionOnLang('pl') . ') JOIN `' . _DB_PREFIX_ . 'lang` l ON (l.`id_lang` = pl.`id_lang` AND l.`id_lang` = ' . (int) Context::getContext()->language->id . ') WHERE pl.`id_product` = ' . (int) $product['product_id'] . ' ORDER BY c.`level_depth` DESC ', true); $flux_xml .= '<produit categorie="' . (int) $data['category_id'] . '" reference="' . (int) $product['product_id'] . '-' . (int) $product['product_attribute_id'] . '" modele="' . addslashes($data['name']) . '" prix="' . (double) $product['product_price_wt'] . '" quantite="' . (int) $product['product_quantity'] . '"></produit>' . "\n"; } $flux_xml = '<caddie nbproduit="' . sizeof($products) . '">' . "\n" . $flux_xml . '</caddie>' . "\n"; return $flux_xml; }
include dirname(__FILE__) . '/../../../config/config.inc.php'; include dirname(__FILE__) . '/../../../init.php'; header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); $now = date("Y-m-d"); $period = Configuration::get('PS_COLLECT_REVIEW_PERIOD_DAY'); $minus = date('Y-m-d', strtotime($now . ' - ' . $period . ' day')); if ($orders = CollectReview::getAllOrderByDay($minus)) { $link = new Link(); foreach ($orders as $value) { $order = new Order($value); $customer = new Customer($order->id_customer); $emailTo = $customer->email; $products_order = $order->getProducts(); $products = array(); foreach ($products_order as $item) { $cover = Product::getCover($item['product_id']); array_push($products, array('name' => $item['product_name'], 'price' => Tools::displayPrice($item['price']), 'quantity' => StockAvailable::getQuantityAvailableByProduct($item['product_id']), 'link' => $link->getProductLink($item['product_id']) . '#reviews', 'image' => $link->getImageLink($item['image']->id, $cover['id_image'], 'large_default'))); } $template = 'collectReview'; $subject = 'Оставьте отзыв'; $product_list_html = CollectReview::getEmailTemplateContent('collectReview.tpl', Mail::TYPE_HTML, $products); $templateVars = array('{products}' => $product_list_html); $admin_mails = Configuration::get('PS_SHOP_EMAIL'); $te = Mail::Send(1, $template, $subject, $templateVars, $emailTo); } $r = CollectReview::deactivate($orders); echo 'Письма отправлены'; } else {
/** * Displays the delivery dates on the invoice * * @param $params contains an instance of OrderInvoice * @return string * */ public function hookDisplayPDFInvoice($params) { $order_invoice = $params['object']; if (!$order_invoice instanceof OrderInvoice) { return; } $order = new Order((int) $order_invoice->id_order); $oos = false; // For out of stock management foreach ($order->getProducts() as $product) { if ($product['product_quantity_in_stock'] < 1) { $oos = true; } } $id_carrier = (int) OrderInvoice::getCarrierId($order_invoice->id); $return = ''; if ($datesDelivery = $this->_getDatesOfDelivery($id_carrier, $oos, $order_invoice->date_add)) { $return = sprintf($this->l('Approximate date of delivery is between %1$s and %2$s'), $datesDelivery[0], $datesDelivery[1]); } return $return; }
public function hookActionPaymentConfirmation($params) { $order = new Order($params['id_order']); $products = $order->getProducts(); $ids = array(); foreach ($products as $product) { $ids[] = $product['product_id']; } $event_params = array('ProductId' => Tools::jsonEncode($ids)); $convermax = new ConvermaxAPI(); $convermax->track('ConfirmOrder', $event_params); }
/** * @param int $order_return_id * @param Order $order * @return array */ public static function getOrdersReturnProducts($order_return_id, $order) { $products_ret = OrderReturn::getOrdersReturnDetail($order_return_id); $products = $order->getProducts(); $tmp = array(); foreach ($products_ret as $return_detail) { $tmp[$return_detail['id_order_detail']]['quantity'] = isset($tmp[$return_detail['id_order_detail']]['quantity']) ? $tmp[$return_detail['id_order_detail']]['quantity'] + (int) $return_detail['product_quantity'] : (int) $return_detail['product_quantity']; $tmp[$return_detail['id_order_detail']]['customizations'] = (int) $return_detail['id_customization']; } $res_tab = array(); foreach ($products as $key => $product) { if (isset($tmp[$product['id_order_detail']])) { $res_tab[$key] = $product; $res_tab[$key]['product_quantity'] = $tmp[$product['id_order_detail']]['quantity']; $res_tab[$key]['customizations'] = $tmp[$product['id_order_detail']]['customizations']; } } return $res_tab; }
/** * \brief Order detail hook * \retval void */ public function hookOrderDetailDisplayed() { // Only if uploader is activated if (Configuration::get('AIMD_FILE_UPLOAD_TIME') != '-1') { $orderId = (int) Tools::getValue('id_order'); $order = new Order($orderId); $products = $order->getProducts(); // Show interface return showOrderUpload($this, $products, false); } }
/** * To track transactions */ public function hookOrderConfirmation($params) { if (!Configuration::get('CHANNELENGINE_LIVE_MODE')) { return; } $id_order = Tools::getValue('id_order'); $order = new Order((int) $id_order); $total = $order->total_paid; $shippingCost = $order->total_shipping; $vat = $order->total_paid_tax_incl - $order->total_paid_tax_excl; $invoiceAddress = new Address((int) $order->id_address_invoice); $city = $invoiceAddress->city; $country = $invoiceAddress->country; $products = $order->getProducts(); $country_obj = new Country((int) $invoiceAddress->id_country); $country_code = $country_obj->iso_code; //push products to channel //$this->putPrestaProductsToChannelEngine($products); $order_items_array_full = array(); foreach ($products as $key => $items) { $prestaProducts = array($items['id_product']); $order_items_array['name'] = $items['product_name']; $order_items_array['price'] = $items['product_price']; $order_items_array['quantity'] = $items['product_quantity']; $order_items_array['category'] = $this->getProductCategories($items['id_product']); $order_items_array['merchantProductNo'] = $items['product_reference']; array_push($order_items_array_full, $order_items_array); } $script = "<script>ce('track:order', {\n merchantOrderNo: '" . $id_order . "',\n total: " . $total . ",\n vat: " . $vat . ",\n shippingCost: " . $shippingCost . ",\n city: '" . $city . "',\n country: '" . $country_code . "',\n orderLines: " . json_encode($order_items_array_full) . "\n }); </script>"; return $script; }
/** * print PDF order * @param Order $order */ private function printPDFOrder(Order $order){ global $lang; $product_items = $order->getProducts(); $shop = new ShopInfo($this->module_srl); $this->model->includeTCPDF(); // create new PDF document $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, TRUE, 'UTF-8', FALSE); // set document information $pdf->SetCreator($shop->getShopTitle()); $pdf->SetTitle(sprintf($lang->order_with_number, $order->order_srl)); $pdf->SetSubject(sprintf($lang->order_with_number, $order->order_srl)); $pdf->setPrintHeader(FALSE); $pdf->setPrintFooter(FALSE); // set font $pdf->SetFont('dejavusans', '', 10); // add a page $pdf->AddPage(); // create HTML content $html = ' <div style="float:left; text-align: center;">'.$shop->getShopTitle().'</div> <h1>'.sprintf($lang->order_with_number, $order->order_srl).'</h1> <p></p> Order date: '.zdate($order->regdate,'d-M-y').' <p></p><h3>'.$lang->shipping_address.'</h3>'.$order->shipping_address.' <p></p><h3>'.$lang->billing_address.'</h3>'.$order->billing_address.' <p></p><h3>'.$lang->payment_method_used.'</h3>'.ucwords(str_replace('_', ' ', $order->payment_method)).' <p></p><h3>'.$lang->shipping_method_used.'</h3>'.ucwords(str_replace('_', ' ', $order->shipping_method)).' <p></p><h3>'.$lang->items_ordered.'</h3></br>'; // output the HTML content $pdf->writeHTML($html, TRUE, FALSE, TRUE, FALSE, ''); // Colors, line width and bold font $pdf->SetFillColor(38, 74, 108); $pdf->SetTextColor(255); $pdf->SetDrawColor(38, 74, 108); $pdf->SetLineWidth(0.3); $pdf->SetFont('', 'B'); // Header $w = array(15, 70, 20, 45, 45); $header= $header = array($lang->product_no_dot, $lang->title, $lang->quantity, $lang->price, $lang->subtotal); $num_headers = count($header); for($i = 0; $i < $num_headers; ++$i) { $pdf->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1); } $pdf->Ln(); // Color and font restoration $pdf->SetFillColor(224, 235, 255); $pdf->SetTextColor(0); $pdf->SetFont(''); // Data $fill = 0; $i = 0; foreach($product_items as $product){ $i++; $pdf->Cell($w[0], 6, $i, 'LR', 0, 'C', $fill); $pdf->Cell($w[1], 6, $product->getTitle(), 'LR', 0, 'L', $fill); $pdf->Cell($w[2], 6, $product->getQuantity(), 'LR', 0, 'R', $fill); $pdf->Cell($w[3], 6, ShopDisplay::priceFormat($product->getPrice(), $shop->getCurrencySymbol()), 'LR', 0, 'R', $fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat($product->getPrice() * $product->getQuantity(), $shop->getCurrencySymbol()), 'LR', 0, 'R', $fill); $pdf->Ln(); $fill=!$fill; } $pdf->Cell(array_sum($w) - $w[4], 6, $lang->total, 1, 0, 'R',$fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat($order->getTotalBeforeDiscount(), $shop->getCurrencySymbol()), 1, 0, 'R',$fill); $fill=!$fill; $pdf->Ln(); if($order->getDiscountAmount()){ $pdf->Cell(array_sum($w) - $w[4], 6, $lang->discount, 1, 0, 'R',$fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat(-1 * $order->getDiscountAmount(), $shop->getCurrencySymbol()), 1, 0, 'R',$fill); $fill=!$fill; $pdf->Ln(); } if($order->getShippingMethodName()){ $pdf->Cell(array_sum($w) - $w[4], 6, $lang->shipping, 1, 0, 'R',$fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat($order->getShippingCost(), $shop->getCurrencySymbol()), 1, 0, 'R',$fill); $fill=!$fill; $pdf->Ln(); } $pdf->SetFont('', 'B'); $pdf->Cell(array_sum($w) - $w[4], 6, $lang->grand_total, 1, 0, 'R',$fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat($order->getTotal(), $shop->getCurrencySymbol()), 1, 0, 'R',$fill); $fill=!$fill; $pdf->Ln(); $pdf->SetFont(''); if($shop->showVAT()){ $pdf->Cell(array_sum($w) - $w[4], 6, $lang->taxes, 1, 0, 'R',$fill); $pdf->Cell($w[4], 6, ShopDisplay::priceFormat($order->getVAT(), $shop->getCurrencySymbol()), 1, 0, 'R',$fill); $fill=!$fill; $pdf->Ln(); } $pdf->Cell(array_sum($w), 0, '', 'T'); //Close and output PDF document $pdf->Output(sprintf($lang->order_with_number, $order->order_srl), 'I'); }
public function hookadminOrder($params) { if (!$this->active) { return false; } global $currentIndex, $smarty; $table = 'order'; $token = Tools::safeOutput(Tools::getValue('token')); $errorShipping = 0; if ($currentIndex == '') { $currentIndex = 'index.php?controller=' . Tools::safeOutput(Tools::getValue('controller')); } $currentIndex .= "&id_order=" . (int) $params['id_order']; $carrierName = Db::getInstance()->getRow('SELECT c.external_module_name FROM `' . _DB_PREFIX_ . 'carrier` as c, `' . _DB_PREFIX_ . 'orders` as o WHERE c.id_carrier = o.id_carrier AND o.id_order = "' . (int) $params['id_order'] . '"'); if ($carrierName != null && $carrierName['external_module_name'] != $this->_moduleName) { return false; } if (!Configuration::get('TNT_CARRIER_LOGIN') || !Configuration::get('TNT_CARRIER_PASSWORD') || !Configuration::get('TNT_CARRIER_NUMBER_ACCOUNT')) { $var = array("error" => $this->l("You don't have a TNT account"), 'shipping_numbers' => '', 'sticker' => ''); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } if (!Configuration::get('TNT_CARRIER_SHIPPING_COMPANY') || !Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS1') || !Configuration::get('TNT_CARRIER_SHIPPING_ZIPCODE') || !Configuration::get('TNT_CARRIER_SHIPPING_CITY') || !Configuration::get('TNT_CARRIER_SHIPPING_EMAIL') || !Configuration::get('TNT_CARRIER_SHIPPING_PHONE') || !Configuration::get('TNT_CARRIER_SHIPPING_CLOSING')) { $errorShipping = 1; } if ($errorShipping) { $var = array("error" => $this->l("You didn't give a collect address in the TNT module configuration"), 'shipping_numbers' => '', 'sticker' => ''); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } $order = new Order($params['id_order']); $orderInfoTnt = new OrderInfoTnt((int) $params['id_order']); $info = $orderInfoTnt->getInfo(); if (is_array($info) && isset($info[3]) && (strlen($info[3]['option']) == 1 || substr($info[3]['option'], 1, 1) == 'S')) { $smarty->assign('weight', '30'); } else { $smarty->assign('weight', '20'); } $products = $order->getProducts(); $productWeight = array(); foreach ($products as $product) { $p = new Product($product['product_id']); if ((double) $p->weight == 0 && (!isset($_POST['product_weight_' . $product['product_id']]) || (double) $_POST['product_weight_' . $product['product_id']] <= 0)) { $productWeight[] = array('id' => $product['product_id'], 'name' => $product['product_name']); } else { if (isset($_POST['product_weight_' . $product['product_id']]) && (double) $_POST['product_weight_' . $product['product_id']] > 0) { $p->weight = (double) $_POST['product_weight_' . $product['product_id']]; $p->update(); } } } if (count($productWeight) > 0) { $var = array('currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); $smarty->assign('productWeight', $productWeight); return $this->display(__FILE__, 'tpl/weightForm.tpl'); } if (!is_array($info) && $info != false) { $var = array("error" => $info, "date" => '', "dateHidden" => '1', 'currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/formerror.tpl'); } $pack = new PackageTnt((int) $params['id_order']); if ($info[0]['shipping_number'] == '' && $pack->getOrder()->hasBeenShipped()) { $tntWebService = new TntWebService(); try { if (!isset($_POST['dateErrorOrder'])) { $orderInfoTnt->getDeleveryDate((int) $params['id_order'], $info); } $package = $tntWebService->getPackage($info); } catch (SoapFault $e) { $errorFriendly = ''; if (strrpos($e->faultstring, "shippingDate")) { $dateError = date("Y-m-d"); } if (strrpos($e->faultstring, "receiver")) { $receiverError = 1; $errorFriendly = $this->l('Can you please modify the field') . ' ' . substr($e->faultstring, strpos($e->faultstring, "receiver") + 9, strpos($e->faultstring, "'", strpos($e->faultstring, "receiver") - strpos($e->faultstring, "receiver")) + 1) . ' ' . $this->l('in the box "shipping address" below.'); } if (strrpos($e->faultstring, "sender")) { $senderError = 1; $errorFriendly = $this->l('Can you please modify the field') . ' ' . substr($e->faultstring, strpos($e->faultstring, "sender") + 7, strpos($e->faultstring, "'", strpos($e->faultstring, "sender") - strpos($e->faultstring, "sender")) + 1) . ' ' . $this->l('in your tnt module configuration.'); } $error = $this->l("Problem : ") . $e->faultstring; $var = array("error" => $error, "errorFriendly" => $errorFriendly, "date" => isset($dateError) ? $dateError : '', 'currentIndex' => $currentIndex, 'table' => $table, 'token' => $token); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/formerror.tpl'); } if (isset($package->Expedition->parcelResponses->parcelNumber)) { $pack->setShippingNumber($package->Expedition->parcelResponses->parcelNumber); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'tnt_package_history` (`id_order`, `pickup_date`) VALUES ("' . (int) $params['id_order'] . '", "' . pSQL($info[2]['delivery_date']) . '")'); } else { foreach ($package->Expedition->parcelResponses as $k => $v) { $pack->setShippingNumber($v->parcelNumber); } } file_put_contents("../modules/" . $this->_moduleName . '/pdf/' . $pack->getOrder()->shipping_number . '.pdf', $package->Expedition->PDFLabels); } if ($pack->getShippingNumber() != '') { $var = array('error' => '', 'shipping_numbers' => $pack->getShippingNumber(), 'sticker' => "../modules/" . $this->_moduleName . '/pdf/' . $pack->getOrder()->shipping_number . '.pdf', 'date' => Db::getInstance()->getValue('SELECT `pickup_date` FROM `' . _DB_PREFIX_ . 'tnt_package_history` WHERE `id_order` = "' . (int) $params['id_order'] . '"'), 'relay' => isset($info[4]) ? $info[4]['name'] . '<br/>' . $info[4]['address'] . '<br/>' . $info[4]['zipcode'] . ' ' . $info[4]['city'] : '', 'place' => Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS1') . " " . Configuration::get('TNT_CARRIER_SHIPPING_ADDRESS2') . "<br/>" . Configuration::get('TNT_CARRIER_SHIPPING_ZIPCODE') . " " . $this->putCityInNormeTnt(Configuration::get('TNT_CARRIER_SHIPPING_CITY'))); $smarty->assign('var', $var); return $this->display(__FILE__, 'tpl/shippingNumber.tpl'); } return false; }
/** * Returns the template's HTML content * * @return string HTML content */ public function getContent() { $invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true); $deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true); $invoice_address = new Address((int) $this->order->id_address_invoice); $country = new Country((int) $invoice_address->id_country); if ($this->order_invoice->invoice_address) { $formatted_invoice_address = $this->order_invoice->invoice_address; } else { $formatted_invoice_address = AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />', ' '); } $delivery_address = null; $formatted_delivery_address = ''; if (isset($this->order->id_address_delivery) && $this->order->id_address_delivery) { if ($this->order_invoice->delivery_address) { $formatted_delivery_address = $this->order_invoice->delivery_address; } else { $delivery_address = new Address((int) $this->order->id_address_delivery); $formatted_delivery_address = AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />', ' '); } } $customer = new Customer((int) $this->order->id_customer); $order_details = $this->order_invoice->getProducts(); $has_discount = false; foreach ($order_details as $id => &$order_detail) { // Find out if column 'price before discount' is required if ($order_detail['reduction_amount_tax_excl'] > 0) { $has_discount = true; $order_detail['unit_price_tax_excl_before_specific_price'] = $order_detail['unit_price_tax_excl_including_ecotax'] + $order_detail['reduction_amount_tax_excl']; } elseif ($order_detail['reduction_percent'] > 0) { $has_discount = true; $order_detail['unit_price_tax_excl_before_specific_price'] = 100 * $order_detail['unit_price_tax_excl_including_ecotax'] / (100 - 15); } // Set tax_code $taxes = OrderDetail::getTaxListStatic($id); $tax_temp = array(); foreach ($taxes as $tax) { $obj = new Tax($tax['id_tax']); $tax_temp[] = sprintf($this->l('%1$s%2$s%%'), $obj->rate + 0, ' '); } $order_detail['order_detail_tax'] = $taxes; $order_detail['order_detail_tax_label'] = implode(', ', $tax_temp); } unset($tax_temp); unset($order_detail); if (Configuration::get('PS_PDF_IMG_INVOICE')) { foreach ($order_details as &$order_detail) { if ($order_detail['image'] != null) { $name = 'product_mini_' . (int) $order_detail['product_id'] . (isset($order_detail['product_attribute_id']) ? '_' . (int) $order_detail['product_attribute_id'] : '') . '.jpg'; $path = _PS_PROD_IMG_DIR_ . $order_detail['image']->getExistingImgPath() . '.jpg'; $order_detail['image_tag'] = preg_replace('/\\.*' . preg_quote(__PS_BASE_URI__, '/') . '/', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR, ImageManager::thumbnail($path, $name, 45, 'jpg', false), 1); if (file_exists(_PS_TMP_IMG_DIR_ . $name)) { $order_detail['image_size'] = getimagesize(_PS_TMP_IMG_DIR_ . $name); } else { $order_detail['image_size'] = false; } } } unset($order_detail); // don't overwrite the last order_detail later } $cart_rules = $this->order->getCartRules($this->order_invoice->id); $free_shipping = false; foreach ($cart_rules as $key => $cart_rule) { if ($cart_rule['free_shipping']) { $free_shipping = true; /** * Adjust cart rule value to remove the amount of the shipping. * We're not interested in displaying the shipping discount as it is already shown as "Free Shipping". */ $cart_rules[$key]['value_tax_excl'] -= $this->order_invoice->total_shipping_tax_excl; $cart_rules[$key]['value'] -= $this->order_invoice->total_shipping_tax_incl; /** * Don't display cart rules that are only about free shipping and don't create * a discount on products. */ if ($cart_rules[$key]['value'] == 0) { unset($cart_rules[$key]); } } } $product_taxes = 0; foreach ($this->order_invoice->getProductTaxesBreakdown($this->order) as $details) { $product_taxes += $details['total_amount']; } $product_discounts_tax_excl = $this->order_invoice->total_discount_tax_excl; $product_discounts_tax_incl = $this->order_invoice->total_discount_tax_incl; if ($free_shipping) { $product_discounts_tax_excl -= $this->order_invoice->total_shipping_tax_excl; $product_discounts_tax_incl -= $this->order_invoice->total_shipping_tax_incl; } $products_after_discounts_tax_excl = $this->order_invoice->total_products - $product_discounts_tax_excl; $products_after_discounts_tax_incl = $this->order_invoice->total_products_wt - $product_discounts_tax_incl; $shipping_tax_excl = $free_shipping ? 0 : $this->order_invoice->total_shipping_tax_excl; $shipping_tax_incl = $free_shipping ? 0 : $this->order_invoice->total_shipping_tax_incl; $shipping_taxes = $shipping_tax_incl - $shipping_tax_excl; $wrapping_taxes = $this->order_invoice->total_wrapping_tax_incl - $this->order_invoice->total_wrapping_tax_excl; $total_taxes = $this->order_invoice->total_paid_tax_incl - $this->order_invoice->total_paid_tax_excl; $footer = array('products_before_discounts_tax_excl' => $this->order_invoice->total_products, 'product_discounts_tax_excl' => $product_discounts_tax_excl, 'products_after_discounts_tax_excl' => $products_after_discounts_tax_excl, 'products_before_discounts_tax_incl' => $this->order_invoice->total_products_wt, 'product_discounts_tax_incl' => $product_discounts_tax_incl, 'products_after_discounts_tax_incl' => $products_after_discounts_tax_incl, 'product_taxes' => $product_taxes, 'shipping_tax_excl' => $shipping_tax_excl, 'shipping_taxes' => $shipping_taxes, 'shipping_tax_incl' => $shipping_tax_incl, 'wrapping_tax_excl' => $this->order_invoice->total_wrapping_tax_excl, 'wrapping_taxes' => $wrapping_taxes, 'wrapping_tax_incl' => $this->order_invoice->total_wrapping_tax_incl, 'ecotax_taxes' => $total_taxes - $product_taxes - $wrapping_taxes - $shipping_taxes, 'total_taxes' => $total_taxes, 'total_paid_tax_excl' => $this->order_invoice->total_paid_tax_excl, 'total_paid_tax_incl' => $this->order_invoice->total_paid_tax_incl); foreach ($footer as $key => $value) { $footer[$key] = Tools::ps_round($value, _PS_PRICE_COMPUTE_PRECISION_, $this->order->round_mode); } /** * Need the $round_mode for the tests. */ $round_type = null; switch ($this->order->round_type) { case Order::ROUND_TOTAL: $round_type = 'total'; break; case Order::ROUND_LINE: $round_type = 'line'; break; case Order::ROUND_ITEM: $round_type = 'item'; break; default: $round_type = 'line'; break; } $display_product_images = Configuration::get('PS_PDF_IMG_INVOICE'); $tax_excluded_display = Group::getPriceDisplayMethod($customer->id_default_group); $layout = $this->computeLayout(array('has_discount' => $has_discount)); $legal_free_text = Hook::exec('displayInvoiceLegalFreeText', array('order' => $this->order)); if (!$legal_free_text) { $legal_free_text = Configuration::get('PS_INVOICE_LEGAL_FREE_TEXT', (int) Context::getContext()->language->id, null, (int) $this->order->id_shop); } $order_obj = new Order($this->order->id); $this->context = Context::getContext(); $products = $order_obj->getProducts(); if (Module::isInstalled('hotelreservationsystem')) { require_once _PS_MODULE_DIR_ . 'hotelreservationsystem/define.php'; $obj_cart_bk_data = new HotelCartBookingData(); $obj_htl_bk_dtl = new HotelBookingDetail(); $obj_rm_type = new HotelRoomType(); $customer = new Customer($this->order->id_customer); if (!empty($products)) { $cart_bk_data = array(); foreach ($products as $type_key => $type_value) { $product = new Product($type_value['product_id'], false, $this->context->language->id); $unit_price = Product::getPriceStatic($type_value['product_id'], true, null, 6, null, false, true, 1); $cover_image_arr = $product->getCover($type_value['product_id']); if (!empty($cover_image_arr)) { $cover_img = $this->context->link->getImageLink($product->link_rewrite, $product->id . '-' . $cover_image_arr['id_image'], 'small_default'); } else { $cover_img = $this->context->link->getImageLink($product->link_rewrite, $this->context->language->iso_code . "-default", 'small_default'); } if (isset($customer->id)) { $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->order->id_cart, (new Cart($this->order->id_cart))->id_guest, $type_value['product_id'], $customer->id); } else { $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->order->id_cart, $customer->id_guest, $type_value['product_id']); } $rm_dtl = $obj_rm_type->getRoomTypeInfoByIdProduct($type_value['product_id']); $cart_htl_data[$type_key]['id_product'] = $type_value['product_id']; $cart_htl_data[$type_key]['cover_img'] = $cover_img; $cart_htl_data[$type_key]['name'] = $product->name; $cart_htl_data[$type_key]['unit_price'] = Tools::convertPrice($unit_price, $this->order->id_currency); $cart_htl_data[$type_key]['adult'] = $rm_dtl['adult']; $cart_htl_data[$type_key]['children'] = $rm_dtl['children']; foreach ($cart_bk_data as $data_k => $data_v) { $date_join = strtotime($data_v['date_from']) . strtotime($data_v['date_to']); if (isset($cart_htl_data[$type_key]['date_diff'][$date_join])) { $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] += 1; $num_days = $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days']; $vart_quant = (int) $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] * $num_days; $amount = Product::getPriceStatic($type_value['product_id'], true, null, 6, null, false, true, 1); $amount *= $vart_quant; $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = Tools::convertPrice($amount, $this->order->id_currency); } else { $num_days = $obj_htl_bk_dtl->getNumberOfDays($data_v['date_from'], $data_v['date_to']); $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] = 1; $cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = $data_v['date_from']; $cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = $data_v['date_to']; $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'] = $num_days; $amount = Product::getPriceStatic($type_value['product_id'], true, null, 6, null, false, true, 1); $amount *= $num_days; $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = Tools::convertPrice($amount, $this->order->id_currency); } } } } } $data = array('cart_htl_data' => $cart_htl_data, 'order' => $this->order, 'order_invoice' => $this->order_invoice, 'order_details' => $order_details, 'cart_rules' => $cart_rules, 'delivery_address' => $formatted_delivery_address, 'invoice_address' => $formatted_invoice_address, 'addresses' => array('invoice' => $invoice_address, 'delivery' => $delivery_address), 'tax_excluded_display' => $tax_excluded_display, 'display_product_images' => $display_product_images, 'layout' => $layout, 'tax_tab' => $this->getTaxTabContent(), 'customer' => $customer, 'footer' => $footer, 'ps_price_compute_precision' => _PS_PRICE_COMPUTE_PRECISION_, 'round_type' => $round_type, 'legal_free_text' => $legal_free_text); if (Tools::getValue('debug')) { die(json_encode($data)); } $this->smarty->assign($data); $tpls = array('style_tab' => $this->smarty->fetch($this->getTemplate('invoice.style-tab')), 'addresses_tab' => $this->smarty->fetch($this->getTemplate('invoice.addresses-tab')), 'summary_tab' => $this->smarty->fetch($this->getTemplate('invoice.summary-tab')), 'product_tab' => $this->smarty->fetch($this->getTemplate('invoice.product-tab')), 'tax_tab' => $this->getTaxTabContent(), 'payment_tab' => $this->smarty->fetch($this->getTemplate('invoice.payment-tab')), 'total_tab' => $this->smarty->fetch($this->getTemplate('invoice.total-tab'))); $this->smarty->assign($tpls); return $this->smarty->fetch($this->getTemplateByCountry($country->iso_code)); }
public function initReservation($klarna, $cart, $customer, $house = null, $ext = null) { $address_invoice = new Address((int) $cart->id_address_invoice); $carrier = new Carrier((int) $cart->id_carrier); $country = new Country((int) $address_invoice->id_country); $id_currency = (int) Validate::isLoadedObject($this->context->currency) ? (int) $this->context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT'); $order_id = Order::getOrderByCartId((int) $cart->id); if ($order_id) { $order = new Order((int) $order_id); foreach ($order->getProducts() as $article) { $price_wt = (double) $article['product_price_wt']; $price = (double) $article['product_price']; if (empty($article['tax_rate'])) { $rate = round(($price_wt / $price - 1.0) * 100); } else { $rate = $article['tax_rate']; } $klarna->addArticle((int) $article['product_quantity'], $this->klarnaEncode($article['product_id']), $this->klarnaEncode($article['product_name']), $price_wt, $rate, 0, KlarnaFlags::INC_VAT | (substr($article['product_name'], 0, 10) == 'invoiceFee' ? KlarnaFlags::IS_HANDLING : 0)); } } else { foreach ($cart->getProducts() as $article) { $price_wt = (double) $article['price_wt']; $price = (double) $article['price']; if (empty($article['rate'])) { $rate = round(($price_wt / $price - 1.0) * 100); } else { $rate = $article['rate']; } $klarna->addArticle((int) $article['cart_quantity'], $this->klarnaEncode((int) $article['id_product']), $this->klarnaEncode($article['name'] . (isset($article['attributes']) ? $article['attributes'] : '')), $price_wt, $rate, 0, KlarnaFlags::INC_VAT | (substr($article['name'], 0, 10) == 'invoiceFee' ? KlarnaFlags::IS_HANDLING : 0)); } } // Add discounts if (_PS_VERSION_ >= 1.5) { $discounts = $cart->getCartRules(); } else { $discounts = $cart->getDiscounts(); } foreach ($discounts as $discount) { $rate = 0; $incvat = 0; // Free shipping has a real value of '!'. if ($discount['value_real'] !== '!') { $incvat = $discount['value_real']; $extvat = $discount['value_tax_exc']; $rate = round(($incvat / $extvat - 1.0) * 100); } $klarna->addArticle(1, '', $this->klarnaEncode($discount['description']), $incvat * -1, $rate, 0, KlarnaFlags::INC_VAT); } $carrier = new Carrier((int) $cart->id_carrier); if ($carrier->active) { $taxrate = Tax::getCarrierTaxRate((int) $carrier->id, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); // Next we might want to add a shipment fee for the product if ($order_id) { $order = new Order((int) $order_id); $shippingPrice = $order->total_shipping_tax_incl; } else { $shippingPrice = $cart->getTotalShippingCost(); } $klarna->addArticle(1, $this->klarnaEncode((int) $cart->id_carrier), $this->klarnaEncode($carrier->name), $shippingPrice, $taxrate, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT); } if ($cart->gift == 1) { $rate = 0; $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); if ($wrapping_fees_tax->rate !== null) { $rate = $wrapping_fees_tax->rate; } $klarna->addArticle(1, '', $this->klarnaEncode($this->l('Gift wrapping fee')), $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), $rate, 0, KlarnaFlags::INC_VAT); } // Create the address object and specify the values. $address_delivery = new Address((int) $cart->id_address_delivery); // Next we tell the Klarna instance to use the address in the next order. $address = str_replace($house, '', $address_invoice->address1); $address = str_replace($ext, '', $address); $address2 = str_replace($house, '', $address_invoice->address2); $address2 = str_replace($ext, '', $address2); $klarna->setAddress(KlarnaFlags::IS_BILLING, new KlarnaAddr($this->klarnaEncode($customer->email), $this->klarnaEncode($address_invoice->phone), $this->klarnaEncode($address_invoice->phone_mobile), $this->klarnaEncode($address_invoice->firstname), $this->klarnaEncode($address_invoice->lastname), $this->klarnaEncode($address_invoice->company), $this->klarnaEncode(trim($address) . ($address2 != '' ? ' ' . trim($address2) : '')), $this->klarnaEncode($address_invoice->postcode), $this->klarnaEncode($address_invoice->city), $this->klarnaEncode($this->countries[$country->iso_code]['code']), trim($house), trim($ext))); // Billing / invoice address $address = str_replace($house, '', $address_delivery->address1); $address = str_replace($ext, '', $address); $address2 = str_replace($house, '', $address_delivery->address2); $address2 = str_replace($ext, '', $address2); $klarna->setAddress(KlarnaFlags::IS_SHIPPING, new KlarnaAddr($this->klarnaEncode($customer->email), $this->klarnaEncode($address_delivery->phone), $this->klarnaEncode($address_delivery->phone_mobile), $this->klarnaEncode($address_delivery->firstname), $this->klarnaEncode($address_delivery->lastname), $this->klarnaEncode($address_delivery->company), $this->klarnaEncode(trim($address) . ($address2 != '' ? ' ' . trim($address2) : '')), $this->klarnaEncode($address_delivery->postcode), $this->klarnaEncode($address_delivery->city), $this->klarnaEncode($this->countries[$country->iso_code]['code']), trim($house), trim($ext))); // Billing / invoice address }
public function preProcess() { parent::preProcess(); if (self::$cookie->isLogged()) { self::$smarty->assign('isLogged', 1); $customer = new Customer((int) self::$cookie->id_customer); if (!Validate::isLoadedObject($customer)) { die(Tools::displayError('Customer not found')); } $products = array(); $orders = array(); $getOrders = Db::getInstance()->ExecuteS(' SELECT id_order FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . (int) $customer->id . ' ORDER BY date_add'); foreach ($getOrders as $row) { $order = new Order($row['id_order']); $date = explode(' ', $order->date_add); $orders[$row['id_order']] = Tools::displayDate($date[0], self::$cookie->id_lang); $tmp = $order->getProducts(); foreach ($tmp as $key => $val) { $products[$val['product_id']] = $val['product_name']; } } $orderList = ''; foreach ($orders as $key => $val) { $orderList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_order') == $key ? 'selected' : '') . ' >' . $key . ' -- ' . $val . '</option>'; } $orderedProductList = ''; foreach ($products as $key => $val) { $orderedProductList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_product') == $key ? 'selected' : '') . ' >' . $val . '</option>'; } self::$smarty->assign('orderList', $orderList); self::$smarty->assign('orderedProductList', $orderedProductList); } if (Tools::isSubmit('submitMessage')) { $fileAttachment = NULL; if (isset($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['tmp_name'])) { $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg'); $filename = uniqid() . substr($_FILES['fileUpload']['name'], -5); $fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']); $fileAttachment['name'] = $_FILES['fileUpload']['name']; $fileAttachment['mime'] = $_FILES['fileUpload']['type']; } $message = Tools::htmlentitiesUTF8(Tools::getValue('message')); if (!($from = trim(Tools::getValue('from'))) or !Validate::isEmail($from)) { $this->errors[] = Tools::displayError('Invalid e-mail address'); } elseif (!($message = nl2br2($message))) { $this->errors[] = Tools::displayError('Message cannot be blank'); } elseif (!Validate::isCleanHtml($message)) { $this->errors[] = Tools::displayError('Invalid message'); } elseif (!($id_contact = (int) Tools::getValue('id_contact')) or !Validate::isLoadedObject($contact = new Contact((int) $id_contact, (int) self::$cookie->id_lang))) { $this->errors[] = Tools::displayError('Please select a subject on the list.'); } elseif (!empty($_FILES['fileUpload']['name']) and $_FILES['fileUpload']['error'] != 0) { $this->errors[] = Tools::displayError('An error occurred during the file upload'); } elseif (!empty($_FILES['fileUpload']['name']) and !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) and !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)) { $this->errors[] = Tools::displayError('Bad file extension'); } else { if ((int) self::$cookie->id_customer) { $customer = new Customer((int) self::$cookie->id_customer); } else { $customer = new Customer(); $customer->getByEmail($from); } $contact = new Contact($id_contact, self::$cookie->id_lang); if (!($id_customer_thread = (int) Tools::getValue('id_customer_thread') and (int) Db::getInstance()->getValue(' SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') or $id_customer_thread = (int) Db::getInstance()->getValue(' SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm WHERE cm.email = \'' . pSQL($from) . '\' AND cm.id_order = ' . (int) Tools::getValue('id_order') . ''))) { $fields = Db::getInstance()->ExecuteS(' SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email FROM ' . _DB_PREFIX_ . 'customer_thread cm WHERE email = \'' . pSQL($from) . '\' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . ' id_order = ' . (int) Tools::getValue('id_order') . ')'); $score = 0; foreach ($fields as $key => $row) { $tmp = 0; if ((int) $row['id_customer'] and $row['id_customer'] != $customer->id and $row['email'] != $from) { continue; } if ($row['id_order'] != 0 and Tools::getValue('id_order') != $row['id_order']) { continue; } if ($row['email'] == $from) { $tmp += 4; } if ($row['id_contact'] == $id_contact) { $tmp++; } if (Tools::getValue('id_product') != 0 and $row['id_product'] == Tools::getValue('id_product')) { $tmp += 2; } if ($tmp >= 5 and $tmp >= $score) { $score = $tmp; $id_customer_thread = $row['id_customer_thread']; } } } $old_message = Db::getInstance()->getValue(' SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' ORDER BY date_add DESC'); if ($old_message == htmlentities($message, ENT_COMPAT, 'UTF-8')) { self::$smarty->assign('alreadySent', 1); $contact->email = ''; $contact->customer_service = 0; } if (!empty($contact->email)) { if (Mail::Send((int) self::$cookie->id_lang, 'contact', Mail::l('Message from contact form'), array('{email}' => $from, '{message}' => stripslashes($message)), $contact->email, $contact->name, $from, (int) self::$cookie->id_customer ? $customer->firstname . ' ' . $customer->lastname : '', $fileAttachment) and Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from)) { self::$smarty->assign('confirmation', 1); } else { $this->errors[] = Tools::displayError('An error occurred while sending message.'); } } if ($contact->customer_service) { if ((int) $id_customer_thread) { $ct = new CustomerThread($id_customer_thread); $ct->status = 'open'; $ct->id_lang = (int) self::$cookie->id_lang; $ct->id_contact = (int) $id_contact; if ($id_order = (int) Tools::getValue('id_order')) { $ct->id_order = $id_order; } if ($id_product = (int) Tools::getValue('id_product')) { $ct->id_product = $id_product; } $ct->update(); } else { $ct = new CustomerThread(); if (isset($customer->id)) { $ct->id_customer = (int) $customer->id; } if ($id_order = (int) Tools::getValue('id_order')) { $ct->id_order = $id_order; } if ($id_product = (int) Tools::getValue('id_product')) { $ct->id_product = $id_product; } $ct->id_contact = (int) $id_contact; $ct->id_lang = (int) self::$cookie->id_lang; $ct->email = $from; $ct->status = 'open'; $ct->token = Tools::passwdGen(12); $ct->add(); } if ($ct->id) { $cm = new CustomerMessage(); $cm->id_customer_thread = $ct->id; $cm->message = htmlentities($message, ENT_COMPAT, 'UTF-8'); if (isset($filename) and rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_ . '../upload/' . $filename)) { $cm->file_name = $filename; } $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']); $cm->user_agent = $_SERVER['HTTP_USER_AGENT']; if ($cm->add()) { if (empty($contact->email)) { Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from); } self::$smarty->assign('confirmation', 1); } else { $this->errors[] = Tools::displayError('An error occurred while sending message.'); } } else { $this->errors[] = Tools::displayError('An error occurred while sending message.'); } } if (count($this->errors) > 1) { array_unique($this->errors); } } } }
/** * @return array */ private function transformObject2Array() { $this->internalArray = array(); $this->internalArray['MERCHANT'] = $this->merchantConfig->getMerchantCode(); $this->internalArray['ORDER_REF'] = $this->order->getOrderRef(); $this->internalArray['ORDER_DATE'] = $this->order->getOrderDate(); $cnt = 0; /** * @var Product $product */ foreach ($this->order->getProducts() as $product) { $this->internalArray['ORDER_PNAME'][$cnt] = $product->getName(); $this->internalArray['ORDER_PGROUP'][$cnt] = $product->getProductGroup(); $this->internalArray['ORDER_PCODE'][$cnt] = $product->getCode(); $this->internalArray['ORDER_PINFO'][$cnt] = $product->getInfo(); $this->internalArray['ORDER_PRICE'][$cnt] = $product->getPrice(); $this->internalArray['ORDER_QTY'][$cnt] = $product->getQuantity(); $this->internalArray['ORDER_MPLACE_MERCHANT'][$cnt] = $product->getMarketPlaceMerchantCode(); $this->internalArray['ORDER_VER'][$cnt] = $product->getProductVersion(); $cnt++; } $this->internalArray['ORDER_SHIPPING'] = $this->order->getShippingCost(); $this->internalArray['PRICES_CURRENCY'] = $this->order->getCurrency(); $this->internalArray['DISCOUNT'] = $this->order->getDiscount(); $this->internalArray['PAY_METHOD'] = $this->order->getPayMethod(); if (!is_null($this->card) && is_null($this->cardToken)) { $this->internalArray['CC_NUMBER'] = $this->card->getCardNumber(); $this->internalArray['EXP_MONTH'] = $this->card->getCardExpirationMonth(); $this->internalArray['EXP_YEAR'] = $this->card->getCardExpirationYear(); $this->internalArray['CC_CVV'] = $this->card->getCardCVV(); $this->internalArray['CC_OWNER'] = $this->card->getCardOwnerName(); if ($this->card->isEnableTokenCreation()) { $this->internalArray['LU_ENABLE_TOKEN'] = '1'; } } $this->internalArray['SELECTED_INSTALLMENTS_NUMBER'] = $this->order->getInstallmentsNumber(); $this->internalArray['CARD_PROGRAM_NAME'] = $this->order->getCardProgramName(); if (is_null($this->card) && !is_null($this->cardToken)) { $this->internalArray['CC_TOKEN'] = $this->cardToken->getToken(); if ($this->cardToken->hasCvv()) { $this->internalArray['CC_CVV'] = $this->cardToken->getCvv(); } } $this->internalArray['BACK_REF'] = $this->order->getBackRef(); $this->internalArray['ALIAS'] = $this->order->getAlias(); if (!empty($this->user)) { $this->internalArray['CLIENT_IP'] = $this->user->getUserIPAddress(); $this->internalArray['CLIENT_TIME'] = $this->user->getClientTime(); } $this->internalArray['BILL_LNAME'] = $this->billingData->getLastName(); $this->internalArray['BILL_FNAME'] = $this->billingData->getFirstName(); $this->internalArray['BILL_CISERIAL'] = $this->billingData->getIdentityCardSeries(); $this->internalArray['BILL_CINUMBER'] = $this->billingData->getIdentityCardNumber(); $this->internalArray['BILL_CIISSUER'] = $this->billingData->getIdentityCardIssuer(); $this->internalArray['BILL_CNP'] = $this->billingData->getPersonalNumericCode(); $this->internalArray['BILL_COMPANY'] = $this->billingData->getCompany(); $this->internalArray['BILL_FISCALCODE'] = $this->billingData->getCompanyFiscalCode(); $this->internalArray['BILL_REGNUMBER'] = $this->billingData->getCompanyRegistrationNumber(); $this->internalArray['BILL_BANK'] = $this->billingData->getCompanyBank(); $this->internalArray['BILL_BANKACCOUNT'] = $this->billingData->getCompanyBankAccountNumber(); $this->internalArray['BILL_EMAIL'] = $this->billingData->getEmail(); $this->internalArray['BILL_PHONE'] = $this->billingData->getPhoneNumber(); $this->internalArray['BILL_FAX'] = $this->billingData->getFaxNumber(); $this->internalArray['BILL_ADDRESS'] = $this->billingData->getAddressLine1(); $this->internalArray['BILL_ADDRESS2'] = $this->billingData->getAddressLine2(); $this->internalArray['BILL_ZIPCODE'] = $this->billingData->getZipCode(); $this->internalArray['BILL_CITY'] = $this->billingData->getCity(); $this->internalArray['BILL_STATE'] = $this->billingData->getState(); $this->internalArray['BILL_COUNTRYCODE'] = $this->billingData->getCountryCode(); if (!empty($this->deliveryData)) { $this->internalArray['DELIVERY_LNAME'] = $this->deliveryData->getLastName(); $this->internalArray['DELIVERY_FNAME'] = $this->deliveryData->getFirstName(); $this->internalArray['DELIVERY_COMPANY'] = $this->deliveryData->getCompany(); $this->internalArray['DELIVERY_PHONE'] = $this->deliveryData->getPhoneNumber(); $this->internalArray['DELIVERY_ADDRESS'] = $this->deliveryData->getAddressLine1(); $this->internalArray['DELIVERY_ADDRESS2'] = $this->deliveryData->getAddressLine2(); $this->internalArray['DELIVERY_ZIPCODE'] = $this->deliveryData->getZipCode(); $this->internalArray['DELIVERY_CITY'] = $this->deliveryData->getState(); $this->internalArray['DELIVERY_STATE'] = $this->deliveryData->getState(); $this->internalArray['DELIVERY_COUNTRYCODE'] = $this->deliveryData->getCountryCode(); $this->internalArray['DELIVERY_EMAIL'] = $this->deliveryData->getEmail(); } $this->internalArray['CC_NUMBER_RECIPIENT'] = $this->order->getCcNumberRecipient(); $this->internalArray['USE_LOYALTY_POINTS'] = $this->order->getUseLoyaltyPoints(); $this->internalArray['LOYALTY_POINTS_AMOUNT'] = $this->order->getLoyaltyPointsAmount(); $this->internalArray['CAMPAIGN_TYPE'] = $this->order->getCampaignType(); if (is_array($this->order->getCustomParams())) { foreach ($this->order->getCustomParams() as $paramName => $paramValue) { $this->internalArray[$paramName] = $paramValue; } } ksort($this->internalArray); return $this->internalArray; }
/** * Get orders * * @param $query : $post_data * @return orders (array) */ function getOrders(&$post_data) { // Permet de rendre optionel la demande d'avis pour les id produit contenu dans ce tableau. $Product_exception = array(); $reponse = array(); $post_message = Tools::jsonDecode(NetReviewsModel::acDecodeBase64($post_data['message']), true); if (!empty($post_message['id_shop'])) { if (Configuration::get('AV_MULTILINGUE', null, null, $post_message['id_shop']) == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n WHERE value = '" . pSQL($post_message['idWebsite']) . "'\n AND name like 'AV_IDWEBSITE_%'\n AND id_shop = " . (int) $post_message['id_shop']; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $allowed_products = Configuration::get('AV_GETPRODREVIEWS' . $group_name, null, null, $post_message['id_shop']); $process_choosen = Configuration::get('AV_PROCESSINIT' . $group_name, null, null, $post_message['id_shop']); $order_status_choosen = Configuration::get('AV_ORDERSTATESCHOOSEN' . $group_name, null, null, $post_message['id_shop']); $forbidden_mail_extensions = explode(';', Configuration::get('AV_FORBIDDEN_EMAIL' . $group_name, null, null, $post_message['id_shop'])); } else { $allowed_products = Configuration::get('AV_GETPRODREVIEWS', null, null, $post_message['id_shop']); $process_choosen = Configuration::get('AV_PROCESSINIT', null, null, $post_message['id_shop']); $order_status_choosen = Configuration::get('AV_ORDERSTATESCHOOSEN', null, null, $post_message['id_shop']); $forbidden_mail_extensions = explode(';', Configuration::get('AV_FORBIDDEN_EMAIL', null, null, $post_message['id_shop'])); } } else { if (Configuration::get('AV_MULTILINGUE') == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n WHERE value = '" . pSQL($post_message['idWebsite']) . "'\n AND name like 'AV_IDWEBSITE_%'\n AND id_shop is null"; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $allowed_products = Configuration::get('AV_GETPRODREVIEWS' . $group_name); $process_choosen = Configuration::get('AV_PROCESSINIT' . $group_name); $order_status_choosen = Configuration::get('AV_ORDERSTATESCHOOSEN' . $group_name); $forbidden_mail_extensions = explode(';', Configuration::get('AV_FORBIDDEN_EMAIL' . $group_name)); } else { $allowed_products = Configuration::get('AV_GETPRODREVIEWS'); $process_choosen = Configuration::get('AV_PROCESSINIT'); $order_status_choosen = Configuration::get('AV_ORDERSTATESCHOOSEN'); $forbidden_mail_extensions = explode(';', Configuration::get('AV_FORBIDDEN_EMAIL')); } } $query_iso_lang = ''; $query_id_shop = ''; $query_status = ''; if ($process_choosen == 'onorderstatuschange' && !empty($order_status_choosen)) { $order_status_choosen = str_replace(';', ',', $order_status_choosen); $query_status = ' AND oh.id_order_state IN (' . pSQL($order_status_choosen) . ')'; } if (isset($post_message['iso_lang'])) { $o_lang = new Language(); $id_lang = $o_lang->getIdByIso(Tools::strtolower($post_message['iso_lang'])); $query_iso_lang .= ' AND o.id_lang = ' . (int) $id_lang; } if (!empty($post_message['id_shop']) && Configuration::get('AV_MULTILINGUE', null, null, $post_message['id_shop']) == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n WHERE value = '" . pSQL($post_message['idWebsite']) . "'\n AND name like 'AV_IDWEBSITE_%'\n AND id_shop = " . (int) $post_message['id_shop']; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $sql2 = 'SELECT value FROM ' . _DB_PREFIX_ . "configuration\n WHERE name = 'AV_GROUP_CONF" . pSQL($group_name) . "'\n AND id_shop like " . (int) $post_message['id_shop']; if ($row = Db::getInstance()->getRow($sql2)) { $list_iso_lang_multilingue = unserialize($row['value']); } $ids_lang = '('; foreach ($list_iso_lang_multilingue as $code_iso) { $o_lang = new Language(); $id_lang = $o_lang->getIdByIso(Tools::strtolower($code_iso)); $ids_lang .= (int) $id_lang . ','; } $ids_lang = Tools::substr($ids_lang, 0, -1) . ')'; $query_iso_lang .= ' AND o.id_lang in ' . pSQL($ids_lang); } else { if (Configuration::get('AV_MULTILINGUE') == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n WHERE value = '" . pSQL($post_message['idWebsite']) . "'\n AND name like 'AV_IDWEBSITE_%'\n AND id_shop is null "; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $sql2 = 'SELECT value FROM ' . _DB_PREFIX_ . "configuration where name = 'AV_GROUP_CONF" . pSQL($group_name) . "' and id_shop is null"; if ($row = Db::getInstance()->getRow($sql2)) { $list_iso_lang_multilingue = unserialize($row['value']); } $ids_lang = '('; foreach ($list_iso_lang_multilingue as $code_iso) { $o_lang = new Language(); $id_lang = $o_lang->getIdByIso(Tools::strtolower($code_iso)); $ids_lang .= (int) $id_lang . ','; } $ids_lang = Tools::substr($ids_lang, 0, -1) . ')'; $query_iso_lang .= ' AND o.id_lang in ' . pSQL($ids_lang); } } if (!empty($post_message['id_shop'])) { $query_id_shop = ' AND oav.id_shop = ' . (int) $post_message['id_shop']; } $query = ' SELECT oav.id_order, o.date_add as date_order,o.id_customer,o.total_paid,o.id_lang,o.id_shop FROM ' . _DB_PREFIX_ . 'av_orders oav LEFT JOIN ' . _DB_PREFIX_ . 'orders o ON oav.id_order = o.id_order LEFT JOIN ' . _DB_PREFIX_ . 'order_history oh ON oh.id_order = o.id_order WHERE (oav.flag_get IS NULL OR oav.flag_get = 0)' . $query_status . $query_id_shop . $query_iso_lang; $orders_list = Db::getInstance()->ExecuteS($query); $reponse['debug'][] = $query; $reponse['debug']['mode'] = '[' . $process_choosen . '] ' . Db::getInstance()->numRows() . ' commandes récupérées'; $orders_list_toreturn = array(); foreach ($orders_list as $order) { // Test if customer email domain is forbidden (marketplaces case) $o_customer = new Customer($order['id_customer']); $customer_email_extension = explode('@', $o_customer->email); if (!in_array($customer_email_extension[1], $forbidden_mail_extensions)) { $array_order = array('id_order' => $order['id_order'], 'id_lang' => $order['id_lang'], 'iso_lang' => pSQL(Language::getIsoById($order['id_lang'])), 'id_shop' => $order['id_shop'], 'amount_order' => $order['total_paid'], 'id_customer' => $order['id_customer'], 'date_order' => strtotime($order['date_order']), 'date_order_formatted' => $order['date_order'], 'firstname_customer' => $o_customer->firstname, 'lastname_customer' => $o_customer->lastname, 'email_customer' => $o_customer->email, 'products' => array()); // Add products to array if (!empty($allowed_products) && $allowed_products == 'yes') { $o_order = new Order($order['id_order']); $products_in_order = $o_order->getProducts(); $array_products = array(); foreach ($products_in_order as $element) { if (!in_array($element['product_id'], $Product_exception)) { $array_url = NetReviewsModel::getUrlsProduct($element['product_id']); $product = array('id_product' => $element['product_id'], 'name_product' => $element['product_name'], 'url_image' => $array_url['url_image_product'], 'url' => $array_url['url_product']); array_push($array_products, $product); unset($product); } } $array_order['products'] = $array_products; unset($array_products); } $orders_list_toreturn[$order['id_order']] = $array_order; } else { $reponse['message']['Emails_Interdits'][] = 'Commande n°' . $order['id_order'] . ' Email:' . $o_customer->email; } // Set orders as getted but do not if it's a test request if (!isset($post_message['no_flag']) || $post_message['no_flag'] == 0) { Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'av_orders SET horodate_get = "' . time() . '", flag_get = 1 WHERE id_order = ' . (int) $order['id_order']); } } // Purge Table $nb_orders_purge = Db::getInstance()->getValue('SELECT count(id_order) FROM ' . _DB_PREFIX_ . 'av_orders WHERE horodate_now < DATE_SUB(NOW(), INTERVAL 6 MONTH)'); $reponse['debug']['purge'] = '[purge] ' . $nb_orders_purge . ' commandes purgées'; Db::getinstance()->Execute('DELETE FROM ' . _DB_PREFIX_ . 'av_orders WHERE horodate_now < DATE_SUB(NOW(), INTERVAL 6 MONTH)'); $reponse['return'] = 1; $reponse['query'] = $post_message['query']; $reponse['message']['nb_orders'] = count($orders_list_toreturn); $reponse['message']['list_orders'] = $orders_list_toreturn; $reponse['debug']['force'] = $post_message['force']; $reponse['debug']['no_flag'] = $post_message['no_flag']; if (!empty($post_message['id_shop'])) { if (Configuration::get('AV_MULTILINGUE', null, null, $post_message['id_shop']) == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n where value = '" . pSQL($post_message['idWebsite']) . "'\n and name like 'AV_IDWEBSITE_%'\n and id_shop = " . (int) $post_message['id_shop']; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $reponse['message']['delay'] = Configuration::get('AV_DELAY' . $group_name, null, null, $post_message['id_shop']); $reponse['sign'] = SHA1($post_message['query'] . Configuration::get('AV_IDWEBSITE' . $group_name, null, null, $post_message['id_shop']) . Configuration::get('AV_CLESECRETE' . $group_name, null, null, $post_message['id_shop'])); } else { $reponse['message']['delay'] = Configuration::get('AV_DELAY', null, null, $post_message['id_shop']); $reponse['sign'] = SHA1($post_data['query'] . Configuration::get('AV_IDWEBSITE', null, null, $post_message['id_shop']) . Configuration::get('AV_CLESECRETE', null, null, $post_message['id_shop'])); } } else { if (Configuration::get('AV_MULTILINGUE') == 'checked') { $sql = 'SELECT name FROM ' . _DB_PREFIX_ . "configuration\n where value = '" . pSQL($post_message['idWebsite']) . "'\n and name like 'AV_IDWEBSITE_%'\n and id_shop is null "; if ($row = Db::getInstance()->getRow($sql)) { $group_name = '_' . Tools::substr($row['name'], 13); } $reponse['message']['delay'] = Configuration::get('AV_DELAY' . $group_name); $reponse['sign'] = SHA1($post_data['query'] . Configuration::get('AV_IDWEBSITE' . $group_name) . Configuration::get('AV_CLESECRETE' . $group_name)); } else { $reponse['message']['delay'] = Configuration::get('AV_DELAY'); $reponse['sign'] = SHA1($post_data['query'] . Configuration::get('AV_IDWEBSITE') . Configuration::get('AV_CLESECRETE')); } } return $reponse; }
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; }
/** * Assign template vars related to order list and product list ordered by the customer */ protected function assignOrderList() { if ($this->context->customer->isLogged()) { $this->context->smarty->assign('isLogged', 1); $products = array(); $result = Db::getInstance()->executeS(' SELECT id_order FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . (int) $this->context->customer->id . ' ORDER BY date_add'); $orders = array(); foreach ($result as $row) { $order = new Order($row['id_order']); $date = explode(' ', $order->date_add); $tmp = $order->getProducts(); foreach ($tmp as $key => $val) { $products[$row['id_order']][$val['product_id']] = array('value' => $val['product_id'], 'label' => $val['product_name']); } $orders[] = array('value' => $order->id, 'label' => $order->getUniqReference() . ' - ' . Tools::displayDate($date[0], $this->context->language->id), 'selected' => (int) Tools::getValue('id_order') == $order->id); } $this->context->smarty->assign('orderList', $orders); $this->context->smarty->assign('orderedProductList', $products); } }
/** * @param int $orderSlipId * @param Order $order * @return array */ public static function getOrdersSlipProducts($orderSlipId, $order) { $cart_rules = $order->getCartRules(true); $productsRet = OrderSlip::getOrdersSlipDetail($orderSlipId); $order_details = $order->getProductsDetail(); $slip_quantity = array(); foreach ($productsRet as $slip_detail) { $slip_quantity[$slip_detail['id_order_detail']] = $slip_detail; } $products = array(); foreach ($order_details as $key => $product) { if (isset($slip_quantity[$product['id_order_detail']]) && $slip_quantity[$product['id_order_detail']]['product_quantity']) { $products[$key] = $product; $products[$key] = array_merge($products[$key], $slip_quantity[$product['id_order_detail']]); } } return $order->getProducts($products); }
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true); } if (!isset($this->context)) { $this->context = Context::getContext(); } $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); // The tax cart is loaded before the customer so re-cache the tax calculation method $this->context->cart->setTaxCalculationMethod(); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); ShopUrl::resetMainDomainCache(); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $context_country = $this->context->country; } $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id); if (!Validate::isLoadedObject($order_status)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t load Order status'); } if (!$this->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) { if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) { foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } } } $order_list = array(); $order_detail_list = array(); do { $reference = Order::generateReference(); } while (Order::getByReference($reference)->count()); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) { foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) { foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } } } // Make sure CartRule caches are empty CartRule::cleanCache(); $cart_rules = $this->context->cart->getCartRules(); foreach ($cart_rules as $cart_rule) { if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) { if ($error = $rule->checkValidity($this->context, true, true)) { $this->context->cart->removeCartRule((int) $rule->id); if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) { if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } else { $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code; $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name)); PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id); } } } } foreach ($package_list as $id_address => $packageByAddress) { foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); if (!$this->context->country->active) { throw new PrestaShopException('The delivery address country is not active.'); } } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int) $carrier->id; $id_carrier = (int) $carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_address_delivery = (int) $id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int) $this->context->cart->id_lang; $order->id_cart = (int) $this->context->cart->id; $order->reference = $reference; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key); $order->payment = $payment_method; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $this->context->cart->recyclable; $order->gift = (int) $this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) { $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid = $order->total_paid_tax_incl; $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE'); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Creating order $result = $order->add(); if (!$result) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order'); } // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } $order_list[] = $order; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl; $order_carrier->add(); } } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $this->context->country = $context_country; } if (!$this->context->country->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('The order address country is not active.'); } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) { $transaction_id = $extra_vars['transaction_id']; } else { $transaction_id = null; } if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order Payment'); } } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) { $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true); } $msg->message = $message; $msg->id_order = (int) $order->id; $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; $ppropertiessmartprice_hook1 = null; $product_var_tpl_list = array(); foreach ($order->product_list as $product) { PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency)); $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $ppropertiessmartprice_hook2 = ''; $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array()); $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart); $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas); if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { $product_var_tpl['customization'] = array(); foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { if ($product['id_cart_product'] == $customization['id_cart_product']) { $customization_text = ''; if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) { foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) { $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) { $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />'; } $customization_quantity = (int) $product['customization_quantity']; $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total'))); } } } $product_var_tpl_list[] = $product_var_tpl; // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) { $virtual_product &= false; } } // end foreach ($products) PP::smartyPPAssign(); $product_list_txt = ''; $product_list_html = ''; if (count($product_var_tpl_list) > 0) { $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list); $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list); } $cart_rules_list = array(); $total_reduction_value_ti = 0; $total_reduction_value_tex = 0; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) { continue; } // IF // This is not multi-shipping // The value of the voucher is greater than the total of the order // Partial use is allowed // This is an "amount" reduction, not a reduction in % or a gift // THEN // The voucher is cloned with a new value corresponding to the remainder if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2'; if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) { $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code); } // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) { $voucher->reduction_amount -= $order->total_shipping_tax_incl; } } else { $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) { $voucher->reduction_amount -= $order->total_shipping_tax_excl; } } if ($voucher->reduction_amount <= 0) { continue; } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->free_shipping = 0; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference()); Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti; $values['tax_excl'] = $order->total_products - $total_reduction_value_tex; } $total_reduction_value_ti += $values['tax_incl']; $total_reduction_value_tex += $values['tax_excl']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false)); } $cart_rules_list_txt = ''; $cart_rules_list_html = ''; if (count($cart_rules_list) > 0) { $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list); $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list); } // Specify order id for message $old_message = Message::getMessageByCartId((int) $this->context->cart->id); if ($old_message) { $update_message = new Message((int) $old_message['id_message']); $update_message->id_order = (int) $order->id; $update_message->update(); // Add this message in the customer thread $customer_thread = new CustomerThread(); $customer_thread->id_contact = 0; $customer_thread->id_customer = (int) $order->id_customer; $customer_thread->id_shop = (int) $this->context->shop->id; $customer_thread->id_order = (int) $order->id; $customer_thread->id_lang = (int) $this->context->language->id; $customer_thread->email = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) { $this->errors[] = Tools::displayError('An error occurred while saving message'); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true); } // Hook validate order Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status)); foreach ($this->context->cart->getProducts() as $product) { if ($order_status->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true); $history->addWithemail(); } unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)); if (is_array($extra_vars)) { $data = array_merge($data, $extra_vars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement = array(); $file_attachement['content'] = $pdf->render(false); $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf'; $file_attachement['mime'] = 'application/pdf'; } else { $file_attachement = null; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true); } if (Validate::isEmail($this->context->customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart); die($error); } } // End foreach $order_detail_list // Update Order Details Tax in case cart rules have free shipping foreach ($order->getOrderDetailList() as $detail) { $order_detail = new OrderDetail($detail['id_order_detail']); $order_detail->updateTaxAmount($order); } // Use the last order as currentOrder if (isset($order) && $order->id) { $this->currentOrder = (int) $order->id; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true); } return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id); die($error); } }
/** * @param Order $order * @return array */ protected function getProducts($order) { $products = $order->getProducts(); foreach ($products as &$product) { if ($product['image'] != null) { $name = 'product_mini_' . (int) $product['product_id'] . (isset($product['product_attribute_id']) ? '_' . (int) $product['product_attribute_id'] : '') . '.jpg'; // generate image cache, only for back office $product['image_tag'] = ImageManager::thumbnail(_PS_IMG_DIR_ . 'p/' . $product['image']->getExistingImgPath() . '.jpg', $name, 45, 'jpg'); if (file_exists(_PS_TMP_IMG_DIR_ . $name)) { $product['image_size'] = getimagesize(_PS_TMP_IMG_DIR_ . $name); } else { $product['image_size'] = false; } } } ksort($products); return $products; }
public function hookPaymentReturn($params) { global $cookie, $smarty; // dados do cliente $customer = new Customer(intval($cookie->id_customer)); $ArrayCliente = $customer->getFields(); // dados do pedido $DadosOrder = new Order($params['objOrder']->id); $ArrayListaProdutos = $DadosOrder->getProducts(); //Get shipment $address_delivery = new Address(intval($params['cart']->id_address_delivery)); $shipments = array("receiver_address" => array("floor" => "-", "zip_code" => $address_delivery->postcode, "street_name" => $address_delivery->address1 . " - " . $address_delivery->address2 . " - " . $address_delivery->city . "/" . $address_delivery->country, "apartment" => "-", "street_number" => "-")); //Force format YYYY-DD-MMTH:i:s $date_creation_user = date('Y-m-d', strtotime($ArrayCliente['date_add'])) . "T" . date('H:i:s', strtotime($ArrayCliente['date_add'])); $address_invoice = new Address(intval($params['cart']->id_address_invoice)); $phone = $address_invoice->phone; $phone .= $phone == "" ? "" : "|"; $phone .= $address_invoice->phone_mobile; $payer = array("name" => $ArrayCliente['firstname'], "surname" => $ArrayCliente['lastname'], "email" => $ArrayCliente['email'], "date_created" => $date_creation_user, "phone" => array("area_code" => "-", "number" => $phone), "address" => array("zip_code" => $address_invoice->postcode, "street_name" => $address_invoice->address1 . " - " . $address_delivery->address2 . " - " . $address_delivery->city . "/" . $address_delivery->country, "street_number" => "-"), "identification" => array("number" => "null", "type" => "null")); //items $image_url = ""; // gera descrição foreach ($ArrayListaProdutos as $info) { $item = array($zb[] = $info['product_name'] . ' * ' . $info['product_quantity']); //get object image on product object $id_image = $info['image']; // get Image by id if (sizeof($id_image) > 0) { $image = new Image($id_image->id_image); // get image full URL $image_url = _PS_BASE_URL_ . _THEME_PROD_DIR_ . $image->getExistingImgPath() . "." . $image->image_format; } } $descricao = implode(" + ", $zb); $item_price = number_format($params['total_to_pay'], 2, '.', ''); $currency = new Currency($DadosOrder->id_currency); $items = array(array("id" => $params['objOrder']->id, "title" => utf8_encode($descricao), "description" => utf8_encode($descricao), "quantity" => 1, "unit_price" => round($item_price, 2), "currency_id" => $currency->iso_code, "picture_url" => $image_url, "category_id" => Configuration::get('mercadopago_CATEGORY'))); //excludes_payment_methods $exclude = Configuration::get('mercadopago_METHODS'); $installments = Configuration::get('mercadopago_INSTALLMENTS'); $installments = str_replace("inst-", "", $installments); $installments = (int) $installments; if ($exclude != '') { //case exist exclude methods $methods_excludes = preg_split("/[\\s,]+/", $exclude); $excludemethods = array(); foreach ($methods_excludes as $exclude) { if ($exclude != "") { $excludemethods[] = array('id' => $exclude); } } $payment_methods = array("installments" => $installments, "excluded_payment_methods" => $excludemethods); } else { //case not exist exclude methods $payment_methods = array("installments" => $installments); } //set back url $back_urls = array("pending" => Configuration::get('mercadopago_URLPROCESS'), "success" => Configuration::get('mercadopago_URLSUCCESFULL')); //mount array pref $pref = array(); $pref['external_reference'] = $params['objOrder']->id; $pref['payer'] = $payer; $pref['shipments'] = $shipments; $pref['items'] = $items; $pref['back_urls'] = $back_urls; $pref['payment_methods'] = $payment_methods; $client_id = Configuration::get('mercadopago_CLIENT_ID'); $client_secret = Configuration::get('mercadopago_CLIENT_SECRET'); $mp = new MP($client_id, $client_secret); $preferenceResult = $mp->create_preference($pref); $sandbox = Configuration::get('mercadopago_SANDBOX') == "active" ? true : false; $url = ""; if ($sandbox) { $url = $preferenceResult['response']['sandbox_init_point']; } else { $url = $preferenceResult['response']['init_point']; } switch (Configuration::get('mercadopago_TYPECHECKOUT')) { case "Iframe": $botton = ' <iframe src="' . $url . '" name="MP-Checkout" width="740" height="600" frameborder="0"></iframe> <script type="text/javascript"> (function(){function $MPBR_load(){window.$MPBR_loaded !== true && (function(){var s = document.createElement("script");s.type = "text/javascript";s.async = true; s.src = ("https:"==document.location.protocol?"https://www.mercadopago.com/org-img/jsapi/mptools/buttons/":"http://mp-tools.mlstatic.com/buttons/")+"render.js"; var x = document.getElementsByTagName("script")[0];x.parentNode.insertBefore(s, x);window.$MPBR_loaded = true;})();} window.$MPBR_loaded !== true ? (window.attachEvent ? window.attachEvent("onload", $MPBR_load) : window.addEventListener("load", $MPBR_load, false)) : null;})(); </script> '; break; case "Redirect": header("location: " . $url); break; case "Lightbox": default: $botton = ' <a href="' . $url . '" name="MP-Checkout" class="blue-L-Rn" mp-mode="modal" onreturn="execute_my_onreturn">Pagar</a> <script type="text/javascript"> (function(){function $MPBR_load(){window.$MPBR_loaded !== true && (function(){var s = document.createElement("script");s.type = "text/javascript";s.async = true; s.src = ("https:"==document.location.protocol?"https://www.mercadopago.com/org-img/jsapi/mptools/buttons/":"http://mp-tools.mlstatic.com/buttons/")+"render.js"; var x = document.getElementsByTagName("script")[0];x.parentNode.insertBefore(s, x);window.$MPBR_loaded = true;})();} window.$MPBR_loaded !== true ? (window.attachEvent ? window.attachEvent("onload", $MPBR_load) : window.addEventListener("load", $MPBR_load, false)) : null;})(); </script> '; break; } $smarty->assign(array('totalApagar' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false), 'status' => 'ok', 'seller_op_id' => $params['objOrder']->id, 'secure_key' => $params['objOrder']->secure_key, 'id_module' => $this->id, 'formmercadopago' => $botton, 'imgBanner' => $this->getBanner())); return $this->display(__FILE__, 'payment_return.tpl'); }
/** * @deprecated 1.5.0.1 * @param Order $order * @return Discount */ public static function createOrderDiscount($order, $productList, $qtyList, $name, $shipping_cost = false, $id_category = 0, $subcategory = 0) { $products = $order->getProducts(false, $productList, $qtyList); // Totals are stored in the order currency (or at least should be) $total = $order->getTotalProductsWithTaxes($products); $discounts = $order->getDiscounts(true); $total_tmp = $total; foreach ($discounts as $discount) { if ($discount['id_discount_type'] == Discount::PERCENT) { $total -= $total_tmp * ($discount['value'] / 100); } elseif ($discount['id_discount_type'] == Discount::AMOUNT) { $total -= $discount['value'] * ($total_tmp / $order->total_products_wt); } } if ($shipping_cost) { $total += $order->total_shipping; } // create discount $voucher = new Discount(); $voucher->id_discount_type = Discount::AMOUNT; foreach (Language::getIDs((bool) $order) as $id_lang) { $voucher->description[$id_lang] = strval($name) . (int) $order->id; } $voucher->value = (double) $total; $voucher->name = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->id_customer = (int) $order->id_customer; $voucher->id_currency = (int) $order->id_currency; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->cumulable = 1; $voucher->cumulable_reduction = 1; $voucher->minimal = (double) $voucher->value; $voucher->active = 1; $voucher->cart_display = 1; $now = time(); $voucher->date_from = date('Y-m-d H:i:s', $now); $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25); /* 1 year */ if (!$voucher->validateFieldsLang(false) || !$voucher->add()) { return false; } // set correct name $voucher->name = 'V' . (int) $voucher->id . 'C' . (int) $order->id_customer . 'O' . $order->id; if (!$voucher->update()) { return false; } return $voucher; }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amount_paid Amount really paid by customer (in the default currency) * @param string $payment_method Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $context_country = $this->context->country; } $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id); if (!Validate::isLoadedObject($order_status)) { throw new PrestaShopException('Can\'t load Order state status'); } if (!$this->active) { die(Tools::displayError()); } // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) { die(Tools::displayError()); } // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) { if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) { foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } } } $order_list = array(); $order_detail_list = array(); $reference = Order::generateReference(); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) { foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) { foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } } } // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($package_list as $id_address => $packageByAddress) { foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int) $carrier->id; $id_carrier = (int) $carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_address_delivery = (int) $id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int) $this->context->cart->id_lang; $order->id_cart = (int) $this->context->cart->id; $order->reference = $reference; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key); $order->payment = $payment_method; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $this->context->cart->recyclable; $order->gift = (int) $this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) { $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid = $order->total_paid_tax_incl; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Creating order $result = $order->add(); if (!$result) { throw new PrestaShopException('Can\'t save Order'); } // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, 2) != number_format($amount_paid, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } $order_list[] = $order; // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl; $order_carrier->add(); } } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $this->context->country = $context_country; } // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) { $transaction_id = $extra_vars['transaction_id']; } else { $transaction_id = null; } if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) { throw new PrestaShopException('Can\'t save Order Payment'); } } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); $cart_rules = $this->context->cart->getCartRules(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) { $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; foreach ($products as $key => $product) { $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $customization_quantity = 0; $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart); if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { $customization_text = ''; foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) { foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) { $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) { $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />'; } $customization_text .= '---<br />'; } $customization_text = rtrim($customization_text, '---<br />'); $customization_quantity = (int) $product['customization_quantity']; $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . Tools::displayError('Customized') . (!empty($customization_text) ? ' - ' . $customization_text : '') . '</strong></td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td> <td style="padding: 0.6em 0.4em; width: 15%;">' . $customization_quantity . '</td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice($customization_quantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td> </tr>'; } if (!$customization_quantity || (int) $product['cart_quantity'] > $customization_quantity) { $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $this->context->currency, false) . '</td> <td style="padding: 0.6em 0.4em; width: 15%;">' . ((int) $product['cart_quantity'] - $customization_quantity) . '</td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customization_quantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $this->context->currency, false) . '</td> </tr>'; } // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) { $virtual_product &= false; } } // end foreach ($products) $cart_rules_list = ''; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) { continue; } /* IF ** - This is not multi-shipping ** - The value of the voucher is greater than the total of the order ** - Partial use is allowed ** - This is an "amount" reduction, not a reduction in % or a gift ** THEN ** The voucher is cloned with a new value corresponding to the remainder */ if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2'; if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) { $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (intval($matches[1]) + 1), $voucher->code); } // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $values['tax_incl'] - $order->total_products_wt; } else { $voucher->reduction_amount = $values['tax_excl'] - $order->total_products; } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference()); Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $values['tax_incl'] -= $values['tax_incl'] - $order->total_products_wt; $values['tax_excl'] -= $values['tax_excl'] - $order->total_products; } $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list .= ' <tr> <td colspan="4" style="padding:0.6em 0.4em;text-align:right">' . Tools::displayError('Voucher name:') . ' ' . $cart_rule['obj']->name . '</td> <td style="padding:0.6em 0.4em;text-align:right">' . ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false) . '</td> </tr>'; } // Specify order id for message $old_message = Message::getMessageByCartId((int) $this->context->cart->id); if ($old_message) { $update_message = new Message((int) $old_message['id_message']); $update_message->id_order = (int) $order->id; $update_message->update(); // Add this message in the customer thread $customer_thread = new CustomerThread(); $customer_thread->id_contact = 0; $customer_thread->id_customer = (int) $order->id_customer; $customer_thread->id_shop = (int) $this->context->shop->id; $customer_thread->id_order = (int) $order->id; $customer_thread->id_lang = (int) $this->context->language->id; $customer_thread->email = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) { $this->errors[] = Tools::displayError('An error occurred while saving message'); } } // Hook validate order Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status)); foreach ($this->context->cart->getProducts() as $product) { if ($order_status->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), $order, true); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $virtual_product ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $this->formatProductAndVoucherForEmail($products_list), '{discounts}' => $this->formatProductAndVoucherForEmail($cart_rules_list), '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false)); if (is_array($extra_vars)) { $data = array_merge($data, $extra_vars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement['content'] = $pdf->render(false); $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf'; $file_attachement['mime'] = 'application/pdf'; } else { $file_attachement = null; } if (Validate::isEmail($this->context->customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); Logger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart)); die($error); } } // End foreach $order_detail_list // Use the last order as currentOrder $this->currentOrder = (int) $order->id; return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); Logger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id)); die($error); } }
protected function createShopOrder($order) { if (!is_array($order)) { $order = $this->getOrder($order); } $order_id = $order['id_order']; $currency = Currency::getCurrencyInstance((int) $order['id_currency']); $shop_order = YousticeShopOrder::create(); $shop_order->setDescription(''); if (empty($order)) { exit('Operation not allowed'); } $shop_order->setName('#' . $order['reference']); $shop_order->setCurrency($currency->iso_code); $shop_order->setPrice((double) $order['total_paid']); $shop_order->setId($order_id); $shop_order->setDeliveryDate($order['delivery_date']); $shop_order->setOrderDate($order['date_add']); $shop_order->setHref($this->createOrderReportHref($order_id)); $shop_order->setOrderDetailHref($this->createOrderDetailHref($order_id)); if ($order['total_paid_real'] >= $order['total_paid']) { $shop_order->setPaymentState(YousticeShopOrder::PAID); } if (strtotime($order['delivery_date']) > 0) { $shop_order->setDeliveryState(YousticeShopOrder::DELIVERED); } $shop_order->setOtherInfo(''); $order_object = new Order((int) $order_id); $products = $order_object->getProducts(); foreach ($products as $product) { $shop_product = $this->createShopProduct($product, $order_id); $shop_product->setCurrency($currency->iso_code); $shop_product->setDeliveryDate($order['delivery_date']); $shop_product->setOrderDate($order['date_add']); $shop_order->addProduct($shop_product); } return $shop_order; }
public function hookUpdateOrderStatus($var1) { /* Configuration status is reached */ if ($var1['newOrderStatus']->id == Configuration::get('feedaty_status_request')) { /* Load the order */ $order = new Order($var1['id_order']); /* Gets all products on order */ $products = $order->getProducts(); $final_products = array(); /* For each product we get picture, id, name, url */ foreach ($products as $product) { $tmp = array(); $id_image = Product::getCover($product['product_id']); if (count($id_image) > 0) { $image = new Image($id_image['id_image']); $tmp['ImageUrl'] = _PS_BASE_URL_ . _THEME_PROD_DIR_ . $image->getExistingImgPath() . '.jpg'; } $tmp['Id'] = $product['product_id']; $tmp['Name'] = $product['product_name']; $tmp['Brand'] = ''; $link = new Link(); $tmp['Url'] = $link->getProductLink((int) $product['product_id']); $final_products[] = $tmp; } /* Gets information about customer who made the order */ $customer = new Customer((int) $order->id_customer); /* Retrive also order date, customer email, id order, prestashop version and plugin version */ $tmp_order = array(); $tmp_order['OrderId'] = $var1['id_order']; $tmp_order['OrderDate'] = $order->date_add; $tmp_order['CustomerEmail'] = $customer->email; $tmp_order['CustomerId'] = $customer->email; $tmp_order['Platform'] = 'PrestaShop ' . _PS_VERSION_ . ' / ' . $this->version; $tmp_order['Products'] = $final_products; $js_data = array(); $js_data['merchantCode'] = Configuration::get('feedaty_code'); $js_data['orders'][] = $tmp_order; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://' . 'www.zoorate.com/ws/feedatyapi.svc/SubmitOrders'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, '60'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, Tools::jsonEncode($js_data)); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:')); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_exec($ch); curl_close($ch); /* We don't need any responce, if worked ok so otherwise no problem */ } }