public function getList($id_lang, $orderBy = NULL, $orderWay = NULL, $start = 0, $limit = NULL)
 {
     $orderByPriceFinal = empty($orderBy) ? Tools::getValue($this->table . 'Orderby', 'id_' . $this->table) : $orderBy;
     $orderWayPriceFinal = empty($orderWay) ? Tools::getValue($this->table . 'Orderway', 'ASC') : $orderWay;
     if ($orderByPriceFinal == 'price_final') {
         $orderBy = 'id_' . $this->table;
         $orderWay = 'ASC';
     }
     parent::getList($id_lang, $orderBy, $orderWay, $start, $limit);
     /* update product quantity with attributes ...*/
     if ($this->_list) {
         $nb = count($this->_list);
         for ($i = 0; $i < $nb; $i++) {
             Attribute::updateQtyProduct($this->_list[$i]);
         }
         /* update product final price */
         for ($i = 0; $i < $nb; $i++) {
             $this->_list[$i]['price_tmp'] = Product::getPriceStatic($this->_list[$i]['id_product'], $usetax = true, $id_product_attribute = NULL, $decimals = 6, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = true);
         }
     }
     if ($orderByPriceFinal == 'price_final') {
         if (strtolower($orderWayPriceFinal) == 'desc') {
             uasort($this->_list, 'cmpPriceDesc');
         } else {
             uasort($this->_list, 'cmpPriceAsc');
         }
     }
     for ($i = 0; $this->_list and $i < $nb; $i++) {
         $this->_list[$i]['price_final'] = $this->_list[$i]['price_tmp'];
         unset($this->_list[$i]['price_tmp']);
     }
 }
 public function getList($id_lang, $orderBy = NULL, $orderWay = NULL, $start = 0, $limit = NULL)
 {
     global $cookie;
     $orderByPriceFinal = empty($orderBy) ? $cookie->__get($this->table . 'Orderby') ? $cookie->__get($this->table . 'Orderby') : 'id_' . $this->table : $orderBy;
     $orderWayPriceFinal = empty($orderWay) ? $cookie->__get($this->table . 'Orderway') ? $cookie->__get($this->table . 'Orderby') : 'ASC' : $orderWay;
     if ($orderByPriceFinal == 'price_final') {
         $orderBy = 'id_' . $this->table;
         $orderWay = 'ASC';
     }
     parent::getList($id_lang, $orderBy, $orderWay, $start, $limit);
     /* update product quantity with attributes ...*/
     if ($this->_list) {
         $nb = count($this->_list);
         for ($i = 0; $i < $nb; $i++) {
             Attribute::updateQtyProduct($this->_list[$i]);
         }
         /* update product final price */
         for ($i = 0; $i < $nb; $i++) {
             $this->_list[$i]['price_tmp'] = Product::getPriceStatic($this->_list[$i]['id_product'], true, NULL, 6, NULL, false, true, 1, true);
         }
     }
     if ($orderByPriceFinal == 'price_final') {
         if (strtolower($orderWayPriceFinal) == 'desc') {
             uasort($this->_list, 'cmpPriceDesc');
         } else {
             uasort($this->_list, 'cmpPriceAsc');
         }
     }
     for ($i = 0; $this->_list and $i < $nb; $i++) {
         $this->_list[$i]['price_final'] = $this->_list[$i]['price_tmp'];
         unset($this->_list[$i]['price_tmp']);
     }
 }
Example #3
0
 public function setProduct($product, $combination)
 {
     // create the product
     $context = Context::getContext();
     $this->give_it_product = new GiveItSdkProduct();
     $this->give_it_product->setCurrency($context->currency->iso_code);
     $usetax = Product::getTaxCalculationMethod((int) $context->customer->id) != PS_TAX_EXC;
     if ($combination['id_product_attribute'] == 0) {
         $combination['attributes'] = '';
         $image = Product::getCover($product->id);
     } else {
         $comb = new Combination($combination['id_product_attribute']);
         if ($image = $comb->getWsImages()) {
             $image = $image[0];
             $image['id_image'] = $image['id'];
         }
     }
     $image['id_product'] = $product->id;
     $image['id_image'] = Product::defineProductImage($image, Context::getContext()->language->id);
     $img_profile = version_compare(_PS_VERSION_, '1.5', '<') ? 'home' : ImageType::getFormatedName('medium');
     $image = $image ? $context->link->getImageLink($product->link_rewrite, $image['id_image'], $img_profile) : '';
     // first, set the product details.
     $this->give_it_product->setProductDetails(array('code' => $product->id . '_' . $combination['id_product_attribute'], 'price' => (int) (Product::getPriceStatic((int) $product->id, $usetax, $combination['id_product_attribute']) * 100), 'name' => $product->name . ($combination['attributes'] ? ' : ' . $combination['attributes'] : ''), 'image' => $image));
     $delivery = $this->setDelivery();
     // add the delivery option to the product
     $this->give_it_product->addBuyerOption($delivery);
     //We should validate this product
     $this->product_valid = $this->give_it_product->validate();
 }
 protected function _assignSummaryInformations()
 {
     $summary = $this->context->cart->getSummaryDetails();
     $customizedDatas = Product::getAllCustomizedDatas($this->context->cart->id);
     // override customization tax rate with real tax (tax rules)
     if ($customizedDatas) {
         foreach ($summary['products'] as &$productUpdate) {
             $productId = (int) isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id'];
             $productAttributeId = (int) isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id'];
             if (isset($customizedDatas[$productId][$productAttributeId])) {
                 $productUpdate['tax_rate'] = Tax::getProductTaxRate($productId, $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             }
         }
         Product::addCustomizationPrice($summary['products'], $customizedDatas);
     }
     $cart_product_context = Context::getContext()->cloneContext();
     foreach ($summary['products'] as $key => &$product) {
         $product['quantity'] = $product['cart_quantity'];
         // for compatibility with 1.2 themes
         if ($cart_product_context->shop->id != $product['id_shop']) {
             $cart_product_context->shop = new Shop((int) $product['id_shop']);
         }
         $product['price_without_specific_price'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], _PS_PRICE_COMPUTE_PRECISION_, null, false, false, 1, false, null, null, null, $null, true, true, $cart_product_context);
         /**
          * ABU edit: variable is_discount set à 1 à tord, calcul foireux de presta
          * @bugfix: https://github.com/PrestaShop/PrestaShop/commit/379e28b341730ea95c0b2d6567817305ea841b23
          * @perso: soustraction de l'ecotax au price_without_specific_price @else
          */
         if (Product::getTaxCalculationMethod()) {
             // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_);
             $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_);
             $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'] - $product['ecotax'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_);
         }
     }
     // Get available cart rules and unset the cart rules already in the cart
     $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart);
     $cart_cart_rules = $this->context->cart->getCartRules();
     foreach ($available_cart_rules as $key => $available_cart_rule) {
         if (!$available_cart_rule['highlight'] || strpos($available_cart_rule['code'], CartRule::BO_ORDER_CODE_PREFIX) === 0) {
             unset($available_cart_rules[$key]);
             continue;
         }
         foreach ($cart_cart_rules as $cart_cart_rule) {
             if ($available_cart_rule['id_cart_rule'] == $cart_cart_rule['id_cart_rule']) {
                 unset($available_cart_rules[$key]);
                 continue 2;
             }
         }
     }
     $show_option_allow_separate_package = !$this->context->cart->isAllProductsInStock(true) && Configuration::get('PS_SHIP_WHEN_AVAILABLE');
     $this->context->smarty->assign($summary);
     $this->context->smarty->assign(array('token_cart' => Tools::getToken(false), 'isLogged' => $this->isLogged, 'isVirtualCart' => $this->context->cart->isVirtualCart(), 'productNumber' => $this->context->cart->nbProducts(), 'voucherAllowed' => CartRule::isFeatureActive(), 'shippingCost' => $this->context->cart->getOrderTotal(true, Cart::ONLY_SHIPPING), 'shippingCostTaxExc' => $this->context->cart->getOrderTotal(false, Cart::ONLY_SHIPPING), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => Product::CUSTOMIZE_FILE, 'CUSTOMIZE_TEXTFIELD' => Product::CUSTOMIZE_TEXTFIELD, 'lastProductAdded' => $this->context->cart->getLastProduct(), 'displayVouchers' => $available_cart_rules, 'show_option_allow_separate_package' => $show_option_allow_separate_package, 'smallSize' => Image::getSize(ImageType::getFormatedName('small'))));
     $this->context->smarty->assign(array('HOOK_SHOPPING_CART' => Hook::exec('displayShoppingCartFooter', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Hook::exec('displayShoppingCart', $summary)));
 }
Example #5
0
 public function pwa_order($data)
 {
     $prefix = _DB_PREFIX_;
     $pwa_order_status = $data['amznPmtsPaymentStatus'];
     $pwa_order_id = $data['amznPmtsOrderIds'];
     if (isset($data['refresh']) && $data['refresh'] != '') {
         $refresh = $data['refresh'];
     } else {
         $refresh = 'yes';
     }
     if (isset($data['CartId']) && $data['CartId'] > 0) {
         $CartId = $data['CartId'];
     } else {
         $CartId = 0;
     }
     $tablename = $prefix . 'pwa_orders';
     $sql = 'SELECT * from `' . $tablename . '` where `amazon_order_id` = "' . $pwa_order_id . '" ';
     $result = Db::getInstance()->ExecuteS($sql);
     if (empty($result)) {
         $tablename = $prefix . 'orders';
         $date = date('Y-m-d H:i:s');
         $sql = 'INSERT into `' . $tablename . '`  (`current_state` , `id_cart` ,  `payment` , `module` , `date_add` ) VALUES( 99, "' . $CartId . '", "Pay with Amazon", "pwapresta", "' . $date . '" )';
         Db::getInstance()->Execute($sql);
         $order_id = Db::getInstance()->Insert_ID();
         $tablename = $prefix . 'pwa_orders';
         $sql = 'INSERT into `' . $tablename . '`  (`prestashop_order_id` , `amazon_order_id` ) VALUES( "' . $order_id . '", "' . $pwa_order_id . '" )';
         Db::getInstance()->Execute($sql);
     } else {
         $order_id = $result[0]['prestashop_order_id'];
     }
     $products = $this->context->cart->getProducts();
     foreach ($products as $product) {
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
             $address_id = (int) $this->id_address_invoice;
         } else {
             $address_id = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!Address::addressExists($address_id)) {
             $address_id = null;
         }
         $virtual_context = Context::getContext()->cloneContext();
         $virtual_context->cart = $this->context->cart;
         $product_price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 2, null, false, true, $product['quantity'], false, (int) $this->context->cart->id_customer ? (int) $this->context->cart->id_customer : null, (int) $this->context->cart->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $virtual_context);
         $tablename = $prefix . 'pwa_order_products';
         $sql = 'INSERT into `' . $tablename . '`  (`id_cart` , `id_product` , `id_product_attribute` , `quantity` , `amount` , `amount_excl` , `sku` , `title` ) VALUES( "' . $this->context->cart->id . '", "' . $product["id_product"] . '",  "' . $product["id_product_attribute"] . '",  "' . $product["quantity"] . '", "' . $product["price_wt"] . '", "' . $product_price . '", "' . $product["reference"] . '", "' . $product["name"] . '" )';
         Db::getInstance()->Execute($sql);
         //$this->context->cart->deleteProduct($product["id_product"]);
     }
     $this->context->smarty->assign(array('order_id' => $order_id, 'pwa_order_id' => $pwa_order_id, 'pwa_order_status' => $pwa_order_status, 'refresh' => $refresh));
     $this->setTemplate('pwa_order.tpl');
 }
Example #6
0
    public function hookNewOrder($params)
    {
        if (!$this->_merchant_order or empty($this->_merchant_mails)) {
            return;
        }
        // Getting differents vars
        $id_lang = intval(Configuration::get('PS_LANG_DEFAULT'));
        $currency = $params['currency'];
        $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME'));
        $order = $params['order'];
        $customer = $params['customer'];
        $delivery = new Address(intval($order->id_address_delivery));
        $invoice = new Address(intval($order->id_address_invoice));
        $order_date_text = Tools::displayDate($order->date_add, intval($id_lang));
        $carrier = new Carrier(intval($order->id_carrier));
        $message = $order->getFirstMessage();
        if (!$message or empty($message)) {
            $message = $this->l('No message');
        }
        $itemsTable = '';
        foreach ($params['cart']->getProducts() as $key => $product) {
            $unit_price = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute']);
            $price = Product::getPriceStatic($product['id_product'], true, $product['id_product_attribute'], 6, NULL, false, true, $product['quantity']);
            $itemsTable .= '<tr style="background-color:' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
					<td style="padding:0.6em 0.4em;">' . $product['reference'] . '</td>
					<td style="padding:0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
					<td style="padding:0.6em 0.4em; text-align:right;">' . Tools::displayPrice($unit_price, $currency, false, false) . '</td>
					<td style="padding:0.6em 0.4em; text-align:center;">' . intval($product['quantity']) . '</td>
					<td style="padding:0.6em 0.4em; text-align:right;">' . Tools::displayPrice($price * $product['quantity'], $currency, false, false) . '</td>
				</tr>';
        }
        foreach ($params['cart']->getDiscounts() as $discount) {
            $itemsTable .= '<tr style="background-color:#EBECEE;">
					<td colspan="4" style="padding:0.6em 0.4em; text-align:right;">' . $this->l('Voucher code:') . ' ' . $discount['name'] . '</td>
					<td style="padding:0.6em 0.4em; text-align:right;">-' . Tools::displayPrice($discount['value_real'], $currency, false, false) . '</td>
			</tr>';
        }
        if ($delivery->id_state) {
            $delivery_state = new State(intval($delivery->id_state));
        }
        if ($invoice->id_state) {
            $invoice_state = new State(intval($invoice->id_state));
        }
        // Filling-in vars for email
        $template = 'new_order';
        $subject = $this->l('New order');
        $templateVars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{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_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{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_other}' => $invoice->other, '{order_name}' => sprintf("%06d", $order->id), '{shop_name}' => Configuration::get('PS_SHOP_NAME'), '{date}' => $order_date_text, '{carrier}' => $carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name, '{payment}' => $order->payment, '{items}' => $itemsTable, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency), '{total_products}' => Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency), '{currency}' => $currency->sign, '{message}' => $message);
        $iso = Language::getIsoById(intval($id_lang));
        if (file_exists(dirname(__FILE__) . '/mails/' . $iso . '/' . $template . '.txt') and file_exists(dirname(__FILE__) . '/mails/' . $iso . '/' . $template . '.html')) {
            Mail::Send($id_lang, $template, $subject, $templateVars, explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails), NULL, $configuration['PS_SHOP_EMAIL'], $configuration['PS_SHOP_NAME'], NULL, NULL, dirname(__FILE__) . '/mails/');
        }
    }
    public function sendCampaign()
    {
        // get abandoned cart :
        $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86400, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a  \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t) AS toto WHERE id_order='Abandoned cart'";
        $currency = Context::getContext()->currency->sign;
        $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
        $abandoned_carts = Db::getInstance()->ExecuteS($sql);
        // get all available campaigns
        $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
        $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
        // loop on all abandoned carts
        foreach ($abandoned_carts as $abncart) {
            // loop on all available campaigns
            foreach ($allCampaigns as $camp) {
                $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
                if ($cartIsOnCampaign) {
                    $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                    $customer = new Customer($abncart['id_customer']);
                    $cR = new CartRule($camp['id_voucher'], $id_lang);
                    $cart = new Cart($abncart['id_cart']);
                    $products = $cart->getProducts();
                    $campM = new Campaign($camp['id_campaign']);
                    if (!empty($products)) {
                        $cart_content = $campM->getCartContentHeader();
                    } else {
                        $cart_content = '';
                    }
                    foreach ($products as $prod) {
                        $p = new Product($prod['id_product'], true, $id_lang);
                        $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
                        $total_no_tax = $prod['cart_quantity'] * $price_no_tax;
                        $images = Image::getImages((int) $id_lang, (int) $p->id);
                        $link = new Link();
                        $cart_content .= '<tr >
										<td align="center" ><img src="' . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
										<td align="center" ><a href="' . $link->getProductLink($p) . '"/>' . $p->name . '</a></td>
										<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
										<td align="center" >' . $prod['cart_quantity'] . '</td>
										<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
									</tr>';
                    }
                    $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{coupon_name}' => $cR->name, '{coupon_code}' => $cR->code, '{cart_content}' => $cart_content, '{coupon_value}' => $camp['voucher_amount_type'] == 'percent' ? $cR->reduction_percent . '%' : $currency . $cR->reduction_amount, '{coupon_valid_to}' => date('d/m/Y', strtotime($cR->date_to)), '{campaign_name}' => $camp['name']);
                    $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
                    // send email to customer :
                    Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    // Email to admin :
                    Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    //	echo 'ID ' . $abncart['id_cart'];
                }
            }
        }
    }
Example #8
0
 function hookRightColumn($params)
 {
     global $smarty;
     $currency = new Currency(intval($params['cookie']->id_currency));
     $bestsellers = ProductSale::getBestSalesLight(intval($params['cookie']->id_lang), 0, 5);
     $best_sellers = array();
     foreach ($bestsellers as $bestseller) {
         $bestseller['price'] = Tools::displayPrice(Product::getPriceStatic(intval($bestseller['id_product'])), $currency);
         $best_sellers[] = $bestseller;
     }
     $smarty->assign(array('best_sellers' => $best_sellers, 'mediumSize' => Image::getSize('medium')));
     return $this->display(__FILE__, 'blockbestsellers.tpl');
 }
 protected function getBestSellers($params)
 {
     if (Configuration::get('PS_CATALOG_MODE')) {
         return false;
     }
     if (!($result = ProductSale::getBestSalesLight((int) $params['cookie']->id_lang, 0, 3))) {
         return Configuration::get('PS_BLOCK_BESTSELLERS_DISPLAY') ? array() : false;
     }
     $currency = new Currency($params['cookie']->id_currency);
     $usetax = Product::getTaxCalculationMethod((int) $this->context->customer->id) != PS_TAX_EXC;
     foreach ($result as &$row) {
         $row['price'] = Tools::displayPrice(Product::getPriceStatic((int) $row['id_product'], $usetax), $currency);
     }
     return $result;
 }
 /**
  * Assign price and tax to the template
  */
 protected function assignPriceAndTax()
 {
     die('coucou');
     $id_customer = isset($this->context->customer) ? (int) $this->context->customer->id : 0;
     $id_group = (int) Group::getCurrent()->id;
     $id_country = $id_customer ? (int) Customer::getCurrentCountry($id_customer) : (int) Tools::getCountry();
     $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
     if ($group_reduction === false) {
         $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
     }
     // Tax
     $tax = (double) $this->product->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
     $this->context->smarty->assign('tax_rate', $tax);
     $product_price_with_tax = Product::getPriceStatic($this->product->id, true, null, 6) * 10;
     if (Product::$_taxCalculationMethod == PS_TAX_INC) {
         $product_price_with_tax = Tools::ps_round($product_price_with_tax, 2);
     }
     $product_price_without_eco_tax = (double) $product_price_with_tax - $this->product->ecotax;
     $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $ecotax_tax_amount = Tools::ps_round($this->product->ecotax, 2);
     if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
         $ecotax_tax_amount = Tools::ps_round($ecotax_tax_amount * (1 + $ecotax_rate / 100), 2);
     }
     $id_currency = (int) $this->context->cookie->id_currency;
     $id_product = (int) $this->product->id;
     $id_shop = $this->context->shop->id;
     $quantity_discounts = SpecificPrice::getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group, null, true, (int) $this->context->customer->id);
     foreach ($quantity_discounts as &$quantity_discount) {
         if ($quantity_discount['id_product_attribute']) {
             $combination = new Combination((int) $quantity_discount['id_product_attribute']);
             $attributes = $combination->getAttributesName((int) $this->context->language->id);
             foreach ($attributes as $attribute) {
                 $quantity_discount['attributes'] = $attribute['name'] . ' - ';
             }
             $quantity_discount['attributes'] = rtrim($quantity_discount['attributes'], ' - ');
         }
         if ((int) $quantity_discount['id_currency'] == 0 && $quantity_discount['reduction_type'] == 'amount') {
             $quantity_discount['reduction'] = Tools::convertPriceFull($quantity_discount['reduction'], null, Context::getContext()->currency);
         }
     }
     $product_price = $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false) * 10;
     $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $this->context->smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (double) $tax, $ecotax_tax_amount), 'ecotax_tax_inc' => $ecotax_tax_amount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'productPriceWithoutEcoTax' => (double) $product_price_without_eco_tax, 'group_reduction' => $group_reduction, 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'ecotax' => !count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'), 'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group)));
 }
 /**
  * Get datas for return of request
  * @return array Datas
  */
 public function getSummary()
 {
     $this->getCurrency();
     list($id_cart, $id_order, $message) = $this->validateOrder();
     if (!$id_cart) {
         return false;
     }
     $det = $this->cart->getSummaryDetails();
     $detail = array();
     $total_discount = 0;
     foreach ($det['products'] as $key => &$product) {
         $product['price_without_quantity_discount'] = Product::getPriceStatic($product['id_product'], false, $product['id_product_attribute'], 6, null, false, false);
         // product price without tax
         $discount = $product['price_without_quantity_discount'] - $product["price"];
         $total_discount += $discount * $product["quantity"];
         $detail[] = array('code' => $product["id_product"], 'unitPrice' => array('amount' => $this->formatNumber($product["price_without_quantity_discount"], 2), 'currency' => $this->currency->iso_code), 'unitDiscount' => array('amount' => $this->formatNumber($discount, 2), 'currency' => $this->currency->iso_code), 'unitTax' => array('amount' => $this->formatNumber($product["price_wt"] - $product["price"], 2), 'currency' => $this->currency->iso_code), 'quantity' => $product["quantity"], 'total' => array('amount' => $this->formatNumber($product["total_wt"], 2), 'currency' => $this->currency->iso_code));
     }
     $shipping_tax = $det["total_shipping"] - $det["total_shipping_tax_exc"];
     $response = array('orderCostSummary' => array('subTotal' => array('amount' => $this->formatNumber($det["total_products"], 2), 'currency' => $this->currency->iso_code), 'discount' => array('amount' => $this->formatNumber($total_discount + $det["total_discounts"], 2), 'currency' => $this->currency->iso_code), 'shippingCost' => array('amount' => $this->formatNumber($det["total_shipping_tax_exc"], 2), 'currency' => $this->currency->iso_code), 'shippingDiscount' => array('amount' => $this->formatNumber(0, 2), 'currency' => $this->currency->iso_code), 'shippingTax' => array('amount' => $this->formatNumber($shipping_tax, 2), 'currency' => $this->currency->iso_code), 'tax' => array('amount' => $this->formatNumber($det["total_tax"], 2), 'currency' => $this->currency->iso_code), 'total' => array('amount' => $this->formatNumber($det["total_price"], 2), 'currency' => $this->currency->iso_code)), 'orderCostDetails' => $detail);
     return $response;
 }
 public function hookDisplayLeftColumn()
 {
     if ($this->context->controller->php_self == 'category') {
         $this->context->controller->addJS(_PS_MODULE_DIR_ . $this->name . '/views/js/wkhotelfilterblock.js');
         $this->context->controller->addCSS(_PS_MODULE_DIR_ . $this->name . '/views/css/wkhotelfilterblock.css');
         $all_feat = FeatureCore::getFeatures($this->context->language->id);
         $htl_id_category = Tools::getValue('id_category');
         $id_hotel = HotelBranchInformation::getHotelIdByIdCategory($htl_id_category);
         $max_adult = HotelRoomType::getMaxAdults($id_hotel);
         $max_child = HotelRoomType::getMaxChild($id_hotel);
         $category = new Category($htl_id_category);
         if (!($date_from = Tools::getValue('date_from'))) {
             $date_from = date('Y-m-d');
             $date_to = date('Y-m-d', strtotime($date_from) + 86400);
         }
         if (!($date_to = Tools::getValue('date_to'))) {
             $date_to = date('Y-m-d', strtotime($date_from) + 86400);
         }
         $obj_rm_type = new HotelRoomType();
         $room_types = $obj_rm_type->getIdProductByHotelId($id_hotel);
         $prod_price = array();
         if ($room_types) {
             foreach ($room_types as $key => $value) {
                 $prod_price[] = Product::getPriceStatic($value['id_product']);
             }
         }
         if (Configuration::get('PS_REWRITING_SETTINGS')) {
             $cat_link = $this->context->link->getCategoryLink($category) . '?date_from=' . $date_from . '&date_to=' . $date_to;
         } else {
             $cat_link = $this->context->link->getCategoryLink($category) . '&date_from=' . $date_from . '&date_to=' . $date_to;
         }
         $currency = $this->context->currency;
         $config = $this->getConfigFieldsValues();
         $obj_booking_detail = new HotelBookingDetail();
         $num_days = $obj_booking_detail->getNumberOfDays($date_from, $date_to);
         $ratting_img = _MODULE_DIR_ . $this->name . '/views/img/stars-sprite-image.png';
         $this->context->smarty->assign(array('all_feat' => $all_feat, 'max_adult' => $max_adult, 'max_child' => $max_child, 'cat_link' => $cat_link, 'ratting_img' => $ratting_img, 'currency' => $currency, 'date_from' => $date_from, 'date_to' => $date_to, 'num_days' => $num_days, 'config' => $config, 'min_price' => $prod_price ? min($prod_price) : 0, 'max_price' => $prod_price ? max($prod_price) : 0));
         return $this->display(__FILE__, 'htlfilterblock.tpl');
     }
 }
Example #13
0
 function smartyAssigns(&$smarty, &$params)
 {
     global $errors;
     // Set currency
     if (!intval($params['cart']->id_currency)) {
         $currency = new Currency(intval($params['cookie']->id_currency));
     } else {
         $currency = new Currency(intval($params['cart']->id_currency));
     }
     if (!Validate::isLoadedObject($currency)) {
         $currency = new Currency(intval(Configuration::get('PS_DEFAULT_CURRENCY')));
     }
     $products = $params['cart']->getProducts(true);
     foreach ($products as $k => $product) {
         $products[$k]['real_price'] = Product::getPriceStatic($product['id_product'], intval(Configuration::get('PS_PRICE_DISPLAY')) == 1 ? false : true, $product['id_product_attribute'], 6, NULL, false, true, $product['cart_quantity']) * $product['cart_quantity'];
     }
     $smarty->assign(array('products' => $products, 'customizedDatas' => Product::getAllCustomizedDatas(intval($params['cart']->id)), 'CUSTOMIZE_FILE' => _CUSTOMIZE_FILE_, 'CUSTOMIZE_TEXTFIELD' => _CUSTOMIZE_TEXTFIELD_, 'discounts' => $params['cart']->getDiscounts(false, true), 'nb_total_products' => $params['cart']->nbProducts(), 'shipping_cost' => Tools::displayPrice($params['cart']->getOrderTotal(intval(Configuration::get('PS_PRICE_DISPLAY')) == 1 ? false : true, 5), $currency), 'show_wrapping' => floatval($params['cart']->getOrderTotal(true, 6)) > 0 ? true : false, 'wrapping_cost' => Tools::displayPrice($params['cart']->getOrderTotal(intval(Configuration::get('PS_PRICE_DISPLAY')) == 1 ? false : true, 6), $currency), 'product_total' => Tools::displayPrice($params['cart']->getOrderTotal(intval(Configuration::get('PS_PRICE_DISPLAY')) == 1 ? false : true, 4), $currency), 'total' => Tools::displayPrice($params['cart']->getOrderTotal(intval(Configuration::get('PS_PRICE_DISPLAY')) == 1 ? false : true), $currency), 'id_carrier' => $params['cart']->id_carrier, 'ajax_allowed' => intval(Configuration::get('PS_BLOCK_CART_AJAX')) == 1 ? true : false));
     if (sizeof($errors)) {
         $smarty->assign('errors', $errors);
     }
     if (isset($params['cookie']->ajax_blockcart_display)) {
         $smarty->assign('colapseExpandStatus', $params['cookie']->ajax_blockcart_display);
     }
 }
Example #14
0
 protected function setDetailProductPrice(Order $order, Cart $cart, $product)
 {
     $this->setContext((int) $product['id_shop']);
     $specific_price = $null = null;
     Product::getPriceStatic((int) $product['id_product'], true, (int) $product['id_product_attribute'], 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')}, $specific_price, true, true, $this->context);
     $this->specificPrice = $specific_price;
     $this->original_product_price = Product::getPriceStatic($product['id_product'], false, (int) $product['id_product_attribute'], 6, null, false, false, 1, false, null, null, null, $null, true, true, $this->context);
     $this->product_price = $this->original_product_price;
     $this->unit_price_tax_incl = (double) $product['price_wt'];
     $this->unit_price_tax_excl = (double) $product['price'];
     $this->total_price_tax_incl = (double) $product['total_wt'];
     $this->total_price_tax_excl = (double) $product['total'];
     $this->purchase_supplier_price = (double) $product['wholesale_price'];
     if ($product['id_supplier'] > 0 && ($supplier_price = ProductSupplier::getProductPrice((int) $product['id_supplier'], $product['id_product'], $product['id_product_attribute'], true)) > 0) {
         $this->purchase_supplier_price = (double) $supplier_price;
     }
     $this->setSpecificPrice($order, $product);
     $this->group_reduction = (double) Group::getReduction((int) $order->id_customer);
     $shop_id = $this->context->shop->id;
     $quantity_discount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], $shop_id, (int) $cart->id_currency, (int) $this->vat_address->id_country, (int) $this->customer->id_default_group, (int) PP::resolveQty($product['cart_quantity'], $product['cart_quantity_fractional']), false, null, null, $null, true, true, $this->context);
     $unit_price = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, 1, false, (int) $order->id_customer, null, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $null, true, true, $this->context);
     $this->product_quantity_discount = 0.0;
     if ($quantity_discount) {
         $this->product_quantity_discount = $unit_price;
         if (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC) {
             $this->product_quantity_discount = Tools::ps_round($unit_price, 2);
         }
         if (isset($this->tax_calculator)) {
             $this->product_quantity_discount -= $this->tax_calculator->addTaxes($quantity_discount['price']);
         }
     }
     $this->discount_quantity_applied = $this->specificPrice && $this->specificPrice['from_quantity'] > PP::getSpecificPriceFromQty((int) $product['id_product']) ? 1 : 0;
     $this->id_cart_product = (int) $product['id_cart_product'];
     $this->product_quantity_fractional = (double) $product['cart_quantity_fractional'];
     $ppropertiessmartprice_hook3 = null;
 }
Example #15
0
 public static function orderbyPrice(&$array, $order_way)
 {
     foreach ($array as &$row) {
         $row['price_tmp'] = Product::getPriceStatic($row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2);
     }
     if (Tools::strtolower($order_way) == 'desc') {
         uasort($array, 'cmpPriceDesc');
     } else {
         uasort($array, 'cmpPriceAsc');
     }
     foreach ($array as &$row) {
         unset($row['price_tmp']);
     }
 }
Example #16
0
 public function displayAjax()
 {
     if ($this->errors) {
         $this->ajaxDie(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
     }
     if ($this->ajax_refresh) {
         $this->ajaxDie(Tools::jsonEncode(array('refresh' => true)));
     }
     $this->context->cookie->write();
     if (Tools::getIsset('summary')) {
         $result = array();
         if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
             $groups = Validate::isLoadedObject($this->context->customer) ? $this->context->customer->getGroups() : array(1);
             if ($this->context->cart->id_address_delivery) {
                 $delivery_address = new Address($this->context->cart->id_address_delivery);
             }
             $id_country = isset($delivery_address) && $delivery_address->id ? (int) $delivery_address->id_country : (int) Tools::getCountry();
             Cart::addExtraCarriers($result);
         }
         $result['summary'] = $this->context->cart->getSummaryDetails(null, true);
         $result['customizedDatas'] = Product::getAllCustomizedDatas($this->context->cart->id, null, true);
         $result['HOOK_SHOPPING_CART'] = Hook::exec('displayShoppingCartFooter', $result['summary']);
         $result['HOOK_SHOPPING_CART_EXTRA'] = Hook::exec('displayShoppingCart', $result['summary']);
         foreach ($result['summary']['products'] as $key => &$product) {
             $product['quantity_without_customization'] = $product['quantity'];
             if ($result['customizedDatas'] && isset($result['customizedDatas'][(int) $product['id_product']][(int) $product['id_product_attribute']])) {
                 foreach ($result['customizedDatas'][(int) $product['id_product']][(int) $product['id_product_attribute']] as $addresses) {
                     foreach ($addresses as $customization) {
                         if ($product['id_cart_product'] == $customization['id_cart_product']) {
                             $product['quantity_without_customization'] -= (int) $customization['quantity'];
                         }
                     }
                 }
             }
             $product['price_without_quantity_discount'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], 6, null, false, false);
             $ppropertiessmartprice_hook1 = null;
             if ($product['reduction_type'] == 'amount') {
                 $reduction = (double) $product['price_wt'] - (double) $product['price_without_quantity_discount'];
                 $product['reduction_formatted'] = Tools::displayPrice($reduction);
             }
         }
         if ($result['customizedDatas']) {
             Product::addCustomizationPrice($result['summary']['products'], $result['customizedDatas']);
         }
         $json = null;
         Hook::exec('actionCartListOverride', array('summary' => $result, 'json' => &$json));
         $this->ajaxDie(Tools::jsonEncode(array_merge($result, (array) Tools::jsonDecode($json, true))));
     } elseif (file_exists(_PS_MODULE_DIR_ . '/blockcart/blockcart-ajax.php')) {
         $context = Context::getContext();
         $cart = $context->cart;
         if ($cart && isset($cart->last_icp)) {
             $context->smarty->assign('last_icp', $cart->last_icp);
         }
         require_once _PS_MODULE_DIR_ . '/blockcart/blockcart-ajax.php';
     }
 }
 public static function getProducts($id_seller, Context $context, $nb_only = false, $p = 1, $n = 10, $orderby = '', $orderway = '', $extraConditions = '')
 {
     ${"GLOBALS"}["vrclqkr"] = "i";
     ${"GLOBALS"}["pbytiqghtow"] = "n";
     ${"GLOBALS"}["ltsfev"] = "orderway";
     $nwslymeftf = "n";
     $dofdwuybzvoc = "where";
     ${"GLOBALS"}["gpvwfaymmvk"] = "orderway";
     ${"GLOBALS"}["qrldutq"] = "orderby";
     ${"GLOBALS"}["seyfsbnox"] = "where";
     $hjbgtfixonq = "select";
     $lkrxunixc = "currency";
     ${"GLOBALS"}["ksintkloxpt"] = "extraConditions";
     $knllieqm = "where";
     $iuyficiewy = "res";
     ${$hjbgtfixonq} = "\n\t\t    SELECT distinct p.*, pl.name,pl.link_rewrite, cl.name `name_category`, i.`id_image`, 0 AS price_final, sav.`quantity` as sav_quantity\n\t\t        ,po.approved\n\t        ";
     $wdbndclu = "extraConditions";
     $zkhbgqxbt = "p";
     ${"GLOBALS"}["uhjxezafnxq"] = "id_seller";
     ${${"GLOBALS"}["ejkvrndxo"]} = "\n\t\t\t\tFROM `" . _DB_PREFIX_ . "product` p\n\t\t\t\tINNER JOIN " . _DB_PREFIX_ . "product_shop product_shop ON (product_shop.id_product = p.id_product AND product_shop.id_shop = " . Configuration::get("PS_SHOP_DEFAULT") . ")\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "product_lang` pl ON (pl.id_lang=" . $context->language->id . " AND p.`id_product` = pl.`id_product` " . Shop::addSqlRestrictionOnLang("pl") . ")\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "tax_rule` tr ON (product_shop.`id_tax_rules_group` = tr.`id_tax_rules_group`\n\t\t \t\t  AND tr.`id_country` = " . (int) $context->country->id . "\n\t\t \t\t  AND tr.`id_state` = 0)\n\t  \t\t \tLEFT JOIN `" . _DB_PREFIX_ . "tax` t ON (t.`id_tax` = tr.`id_tax`)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "supplier` s ON (s.`id_supplier` = p.`id_supplier`)\n\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)\n\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "stock_available` sav ON (sav.`id_product` = p.`id_product` AND sav.`id_product_attribute` = 0\n\t\t\t\tAND sav.`id_shop` = " . (int) $context->shop->id . ")\n\t\t    LEFT JOIN `" . _DB_PREFIX_ . "category_lang` cl ON (p.id_category_default=cl.id_category AND cl.id_lang=" . $context->language->id . ")\n\t\t    LEFT JOIN `" . _DB_PREFIX_ . "product_owner` po ON p.id_product=po.id_product\n\t\t";
     $glfdkvtum = "p";
     $qpmjux = "orderby";
     ${$dofdwuybzvoc} = " WHERE po.id_owner>0 AND po.id_owner = " . intval(${${"GLOBALS"}["uhjxezafnxq"]}) . " \n\t\t";
     $wvnwfslh = "sql";
     if (${${"GLOBALS"}["ksintkloxpt"]} != "") {
         ${${"GLOBALS"}["dmjivkgtcqq"]} = ${$knllieqm} . ${$wdbndclu};
     }
     if (${${"GLOBALS"}["armbnpyqs"]}) {
         return Db::getInstance()->getValue("SELECT COUNT(*) " . ${${"GLOBALS"}["ejkvrndxo"]} . ${${"GLOBALS"}["dmjivkgtcqq"]});
     }
     if (${$glfdkvtum} < 1) {
         ${${"GLOBALS"}["eadhxox"]} = 1;
     }
     if (${${"GLOBALS"}["pbytiqghtow"]} < 1) {
         ${$nwslymeftf} = 10;
     }
     if (empty(${$qpmjux})) {
         ${${"GLOBALS"}["qrldutq"]} = "p.date_add";
     }
     if (empty(${${"GLOBALS"}["ltsfev"]})) {
         ${${"GLOBALS"}["gpvwfaymmvk"]} = "DESC";
     }
     ${"GLOBALS"}["ketioqxhsm"] = "n";
     ${${"GLOBALS"}["ubgqiwk"]} = " ORDER BY " . ${${"GLOBALS"}["ejmgkwlhbp"]} . " " . ${${"GLOBALS"}["zzomqmcyjd"]} . " \n        ";
     ${"GLOBALS"}["bgbiyfppmhgw"] = "res";
     ${"GLOBALS"}["clbwndk"] = "sql";
     ${${"GLOBALS"}["nzpalqljyny"]} = "LIMIT " . ((int) ${$zkhbgqxbt} - 1) * (int) ${${"GLOBALS"}["ketioqxhsm"]} . "," . (int) ${${"GLOBALS"}["mmtkcpcxthp"]} . "\n\t\t";
     ${$wvnwfslh} = ${${"GLOBALS"}["ypljby"]} . ${${"GLOBALS"}["ejkvrndxo"]} . ${${"GLOBALS"}["seyfsbnox"]} . ${${"GLOBALS"}["ubgqiwk"]} . ${${"GLOBALS"}["nzpalqljyny"]};
     ${${"GLOBALS"}["bgbiyfppmhgw"]} = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(${${"GLOBALS"}["clbwndk"]});
     if (empty(${${"GLOBALS"}["nsginhlnhc"]})) {
         return ${${"GLOBALS"}["nsginhlnhc"]};
     }
     ${"GLOBALS"}["cphdwvwffwdp"] = "res";
     ${$lkrxunixc} = new Currency((int) Configuration::get("PS_CURRENCY_DEFAULT"));
     ${${"GLOBALS"}["nsginhlnhc"]} = Product::getProductsProperties(Context::getContext()->cookie->id_lang, ${${"GLOBALS"}["cphdwvwffwdp"]});
     for (${${"GLOBALS"}["jhgjtjy"]} = 0; ${${"GLOBALS"}["vrclqkr"]} < count(${$iuyficiewy}); ${${"GLOBALS"}["jhgjtjy"]}++) {
         ${${"GLOBALS"}["nsginhlnhc"]}[${${"GLOBALS"}["jhgjtjy"]}]["price_final"] = Product::getPriceStatic(${${"GLOBALS"}["nsginhlnhc"]}[${${"GLOBALS"}["jhgjtjy"]}]["id_product"], true, null, 6, null, false, true, 1, true) * $currency->conversion_rate / Context::getContext()->currency->conversion_rate;
     }
     return ${${"GLOBALS"}["nsginhlnhc"]};
 }
Example #18
0
 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);
     }
 }
 public function hookupdateProductAttribute($params)
 {
     if (Configuration::get('SHOPPING_FLUX_STOCKS') != '') {
         $data = Db::getInstance()->getRow('SELECT `id_product`,`quantity` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product_attribute` = ' . (int) $params['id_product_attribute']);
         $xml = '<?xml version="1.0" encoding="UTF-8"?>';
         $xml .= '<UpdateProduct>';
         $xml .= '<Product>';
         $xml .= '<SKU>' . (int) $data['id_product'] . '_' . (int) $params['id_product_attribute'] . '</SKU>';
         $xml .= '<Quantity>' . (int) $data['quantity'] . '</Quantity>';
         $xml .= '<Price>' . Product::getPriceStatic((int) $data['id_product'], true, (int) $params['id_product_attribute'], 2, null, false, true, 1) . '</Price>';
         $xml .= '<OldPrice>' . Product::getPriceStatic((int) $data['id_product'], true, (int) $params['id_product_attribute'], 2, null, false, false, 1) . '</OldPrice>';
         $xml .= '</Product>';
         $xml .= '</UpdateProduct>';
         $this->_callWebService('UpdateProduct', $xml);
     }
 }
Example #20
0
 /**
  * This function returns the total cart amount
  *
  * Possible values for $type:
  * Cart::ONLY_PRODUCTS
  * Cart::ONLY_DISCOUNTS
  * Cart::BOTH
  * Cart::BOTH_WITHOUT_SHIPPING
  * Cart::ONLY_SHIPPING
  * Cart::ONLY_WRAPPING
  * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  *
  * @param boolean $withTaxes With or without taxes
  * @param integer $type Total type
  * @param boolean $use_cache Allow using cache of the method CartRule::getContextualValue
  * @return float Order total
  */
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if ($with_shipping) {
         if (is_null($products) && is_null($id_carrier)) {
             $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
         } else {
             $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool) $with_taxes, null, $products);
         }
     } else {
         $shipping_fees = 0;
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     foreach ($products as $product) {
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
             $address_id = (int) $this->id_address_invoice;
         } else {
             $address_id = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!Address::addressExists($address_id)) {
             $address_id = null;
         }
         if ($this->_taxCalculationMethod == PS_TAX_EXC) {
             // Here taxes are computed only once the quantity has been applied to the product price
             $price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 2, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $null, true, true, $virtual_context);
             $total_ecotax = $product['ecotax'] * (int) $product['cart_quantity'];
             $total_price = $price * (int) $product['cart_quantity'];
             if ($with_taxes) {
                 $product_tax_rate = (double) Tax::getProductTaxRate((int) $product['id_product'], (int) $address_id, $virtual_context);
                 $product_eco_tax_rate = Tax::getProductEcotaxRate((int) $address_id);
                 $total_price = ($total_price - $total_ecotax) * (1 + $product_tax_rate / 100);
                 $total_ecotax = $total_ecotax * (1 + $product_eco_tax_rate / 100);
                 $total_price = Tools::ps_round($total_price + $total_ecotax, 2);
             }
         } else {
             if ($with_taxes) {
                 $price = Product::getPriceStatic((int) $product['id_product'], true, (int) $product['id_product_attribute'], 2, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $virtual_context);
             } else {
                 $price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 2, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $null, true, true, $virtual_context);
             }
             $total_price = Tools::ps_round($price * (int) $product['cart_quantity'], 2);
         }
         $order_total += $total_price;
     }
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     if ($this->gift) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), 2), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), 2);
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), 2);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), $wrapping_fees + $order_total_products + $shipping_fees);
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, 2);
 }
Example #21
0
    public static function getCrossSells($id_product, $id_lang, $limit = 12)
    {
        if (!$id_product || !$id_lang) {
            return;
        }
        $front = true;
        if (!in_array(Context::getContext()->controller->controller_type, array('front', 'modulefront'))) {
            $front = false;
        }
        $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT o.id_order
		FROM ' . _DB_PREFIX_ . 'orders o
		LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order)
		WHERE o.valid = 1 AND od.product_id = ' . (int) $id_product);
        if (count($orders)) {
            $list = '';
            foreach ($orders as $order) {
                $list .= (int) $order['id_order'] . ',';
            }
            $list = rtrim($list, ',');
            $order_products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
				SELECT DISTINCT od.product_id, p.id_product, pl.name, pl.link_rewrite, p.reference, i.id_image, product_shop.show_price,
				cl.link_rewrite category, p.ean13, p.out_of_stock, p.id_category_default ' . (Combination::isFeatureActive() ? ', IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute' : '') . '
				FROM ' . _DB_PREFIX_ . 'order_detail od
				LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id)
				' . Shop::addSqlAssociation('product', 'p') . (Combination::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop
				ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) Context::getContext()->shop->id . ')' : '') . '
				LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = od.product_id' . Shop::addSqlRestrictionOnLang('pl') . ')
				LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = product_shop.id_category_default' . Shop::addSqlRestrictionOnLang('cl') . ')
				LEFT JOIN ' . _DB_PREFIX_ . 'image i ON (i.id_product = od.product_id)
				WHERE od.id_order IN (' . $list . ')
					AND pl.id_lang = ' . (int) $id_lang . '
					AND cl.id_lang = ' . (int) $id_lang . '
					AND od.product_id != ' . (int) $id_product . '
					AND i.cover = 1
					AND product_shop.active = 1' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . '
				ORDER BY RAND()
				LIMIT ' . (int) $limit . '
			', true, false);
            $tax_calc = Product::getTaxCalculationMethod();
            if (is_array($order_products)) {
                foreach ($order_products as &$order_product) {
                    $order_product['image'] = Context::getContext()->link->getImageLink($order_product['link_rewrite'], (int) $order_product['product_id'] . '-' . (int) $order_product['id_image'], ImageType::getFormatedName('medium'));
                    $order_product['link'] = Context::getContext()->link->getProductLink((int) $order_product['product_id'], $order_product['link_rewrite'], $order_product['category'], $order_product['ean13']);
                    if ($tax_calc == 0 || $tax_calc == 2) {
                        $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], true, null);
                    } elseif ($tax_calc == 1) {
                        $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], false, null);
                    }
                }
                return Product::getProductsProperties($id_lang, $order_products);
            }
        }
    }
Example #22
0
 public function ajaxProcessLoadProductInformation()
 {
     $order_detail = new OrderDetail(Tools::getValue('id_order_detail'));
     if (!Validate::isLoadedObject($order_detail)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The OrderDetail object cannot be loaded.'))));
     }
     $product = new Product($order_detail->product_id);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     $address = new Address(Tools::getValue('id_address'));
     if (!Validate::isLoadedObject($address)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The address object cannot be loaded.'))));
     }
     die(Tools::jsonEncode(array('result' => true, 'product' => $product, 'tax_rate' => $product->getTaxesRate($address), 'price_tax_incl' => Product::getPriceStatic($product->id, true, $order_detail->product_attribute_id, 2), 'price_tax_excl' => Product::getPriceStatic($product->id, false, $order_detail->product_attribute_id, 2))));
 }
Example #23
0
 public function hookDisplayProductButtons($params)
 {
     $taxes = Product::getTaxCalculationMethod();
     $id_product = (int) Tools::getValue('id_product');
     if ($taxes == 0 || $taxes == 2) {
         $askforprice_product_price = Product::getPriceStatic($id_product, true, null, 2);
     } elseif ($taxes == 1) {
         $askforprice_product_price = Product::getPriceStatic($id_product, false, null, 2);
     }
     $this->context->smarty->assign(array('ASKFORPRICE_MINIMAL_PRICE' => Configuration::get('ASKFORPRICE_MINIMAL_PRICE', null), 'askforprice_product_price' => $askforprice_product_price, 'askforprice_form_url' => $this->context->link->getModuleLink('askforprice', 'form', array('id_product' => $id_product))));
     return $this->display($this->_path, 'views/templates/front/askforprice.tpl');
 }
 protected function searchProducts($search)
 {
     if ($products = Product::searchByName((int) $this->context->language->id, $search)) {
         foreach ($products as &$product) {
             $combinations = array();
             $productObj = new Product((int) $product['id_product'], false, (int) $this->context->language->id);
             $attributes = $productObj->getAttributesGroups((int) $this->context->language->id);
             $product['formatted_price'] = Tools::displayPrice(Tools::convertPrice($product['price_tax_incl'], $this->context->currency), $this->context->currency);
             foreach ($attributes as $attribute) {
                 if (!isset($combinations[$attribute['id_product_attribute']]['attributes'])) {
                     $combinations[$attribute['id_product_attribute']]['attributes'] = '';
                 }
                 $combinations[$attribute['id_product_attribute']]['attributes'] .= $attribute['attribute_name'] . ' - ';
                 $combinations[$attribute['id_product_attribute']]['id_product_attribute'] = $attribute['id_product_attribute'];
                 $combinations[$attribute['id_product_attribute']]['default_on'] = $attribute['default_on'];
                 if (!isset($combinations[$attribute['id_product_attribute']]['price'])) {
                     $price_tax_incl = Product::getPriceStatic((int) $product['id_product'], true, $attribute['id_product_attribute']);
                     $combinations[$attribute['id_product_attribute']]['formatted_price'] = Tools::displayPrice(Tools::convertPrice($price_tax_incl, $this->context->currency), $this->context->currency);
                 }
             }
             foreach ($combinations as &$combination) {
                 $combination['attributes'] = rtrim($combination['attributes'], ' - ');
             }
             $product['combinations'] = $combinations;
         }
         return array('products' => $products, 'found' => true);
     } else {
         return array('found' => false, 'notfound' => Tools::displayError('No product has been found.'));
     }
 }
 protected function _assignSummaryInformations()
 {
     $summary = $this->context->cart->getSummaryDetails();
     $customizedDatas = Product::getAllCustomizedDatas($this->context->cart->id);
     // override customization tax rate with real tax (tax rules)
     if ($customizedDatas) {
         foreach ($summary['products'] as &$productUpdate) {
             $productId = (int) (isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id']);
             $productAttributeId = (int) (isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id']);
             if (isset($customizedDatas[$productId][$productAttributeId])) {
                 $productUpdate['tax_rate'] = Tax::getProductTaxRate($productId, $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             }
         }
         Product::addCustomizationPrice($summary['products'], $customizedDatas);
     }
     $cart_product_context = Context::getContext()->cloneContext();
     foreach ($summary['products'] as $key => &$product) {
         $product['quantity'] = $product['cart_quantity'];
         // for compatibility with 1.2 themes
         if ($cart_product_context->shop->id != $product['id_shop']) {
             $cart_product_context->shop = new Shop((int) $product['id_shop']);
         }
         $product['price_without_specific_price'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], 2, null, false, false, 1, false, null, null, null, $null, true, true, $cart_product_context);
         if (Product::getTaxCalculationMethod()) {
             $product['is_discounted'] = $product['price_without_specific_price'] != $product['price'];
         } else {
             $product['is_discounted'] = $product['price_without_specific_price'] != $product['price_wt'];
         }
     }
     // Get available cart rules and unset the cart rules already in the cart
     $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart);
     $cart_cart_rules = $this->context->cart->getCartRules();
     foreach ($available_cart_rules as $key => $available_cart_rule) {
         if (!$available_cart_rule['highlight'] || strpos($available_cart_rule['code'], 'BO_ORDER_') === 0) {
             unset($available_cart_rules[$key]);
             continue;
         }
         foreach ($cart_cart_rules as $cart_cart_rule) {
             if ($available_cart_rule['id_cart_rule'] == $cart_cart_rule['id_cart_rule']) {
                 unset($available_cart_rules[$key]);
                 continue 2;
             }
         }
     }
     $show_option_allow_separate_package = !$this->context->cart->isAllProductsInStock(true) && Configuration::get('PS_SHIP_WHEN_AVAILABLE');
     $this->context->smarty->assign($summary);
     $this->context->smarty->assign(array('token_cart' => Tools::getToken(false), 'isLogged' => $this->isLogged, 'isVirtualCart' => $this->context->cart->isVirtualCart(), 'productNumber' => $this->context->cart->nbProducts(), 'voucherAllowed' => CartRule::isFeatureActive(), 'shippingCost' => $this->context->cart->getOrderTotal(true, Cart::ONLY_SHIPPING), 'shippingCostTaxExc' => $this->context->cart->getOrderTotal(false, Cart::ONLY_SHIPPING), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => Product::CUSTOMIZE_FILE, 'CUSTOMIZE_TEXTFIELD' => Product::CUSTOMIZE_TEXTFIELD, 'lastProductAdded' => $this->context->cart->getLastProduct(), 'displayVouchers' => $available_cart_rules, 'currencySign' => $this->context->currency->sign, 'currencyRate' => $this->context->currency->conversion_rate, 'currencyFormat' => $this->context->currency->format, 'currencyBlank' => $this->context->currency->blank, 'show_option_allow_separate_package' => $show_option_allow_separate_package, 'smallSize' => Image::getSize(ImageType::getFormatedName('small'))));
     $this->context->smarty->assign(array('HOOK_SHOPPING_CART' => Hook::exec('displayShoppingCartFooter', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Hook::exec('displayShoppingCart', $summary)));
 }
 /**
  * Assign template vars related to attribute groups and colors
  */
 protected function assignAttributesGroups()
 {
     $colors = array();
     $groups = array();
     // @todo (RM) should only get groups and not all declination ?
     $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);
     if (is_array($attributes_groups) && $attributes_groups) {
         $combination_images = $this->product->getCombinationImages($this->context->language->id);
         $combination_prices_set = array();
         foreach ($attributes_groups as $k => $row) {
             // Color management
             if (isset($row['attribute_color']) && $row['attribute_color'] || file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) {
                 $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                 $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                 if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                     $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                 }
                 $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
             }
             if (!isset($groups[$row['id_attribute_group']])) {
                 $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'group_type' => $row['group_type'], 'default' => -1);
             }
             $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
             if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                 $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
             }
             if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                 $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
             }
             $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
             if ($row['available_date'] != '0000-00-00 00:00:00' && $row['available_date'] != '0000-00-00') {
                 $available_date = Tools::displayDate($row['available_date'], $this->context->language->id);
             } else {
                 $available_date = $row['available_date'];
             }
             $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
             $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
             $combinations[$row['id_product_attribute']]['price'] = (double) $row['price'];
             // Call getPriceStatic in order to set $combination_specific_price
             if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {
                 Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);
                 $combination_prices_set[(int) $row['id_product_attribute']] = true;
                 $combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;
             }
             $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
             $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
             $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
             $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
             $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
             $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
             $combinations[$row['id_product_attribute']]['available_date'] = $available_date;
             if (isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {
                 $combinations[$row['id_product_attribute']]['id_image'] = $combination_images[$row['id_product_attribute']][0]['id_image'];
             } else {
                 $combinations[$row['id_product_attribute']]['id_image'] = -1;
             }
         }
         // wash attributes list (if some attributes are unavailables and if allowed to wash it)
         if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
             foreach ($groups as &$group) {
                 foreach ($group['attributes_quantity'] as $key => &$quantity) {
                     if (!$quantity) {
                         unset($group['attributes'][$key]);
                     }
                 }
             }
             foreach ($colors as $key => $color) {
                 if (!$color['attributes_quantity']) {
                     unset($colors[$key]);
                 }
             }
         }
         foreach ($combinations as $id_product_attribute => $comb) {
             $attribute_list = '';
             foreach ($comb['attributes'] as $id_attribute) {
                 $attribute_list .= '\'' . (int) $id_attribute . '\',';
             }
             $attribute_list = rtrim($attribute_list, ',');
             $combinations[$id_product_attribute]['list'] = $attribute_list;
         }
         $this->context->smarty->assign(array('groups' => $groups, 'combinations' => $combinations, 'colors' => count($colors) ? $colors : false, 'combinationImages' => $combination_images));
     }
 }
Example #27
0
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     /* 
      * EU-Legal
      * correct calculation of prices -> Problem with inaccuracy at high number of items
      */
     static $address = null;
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     $taxes = $this->getTaxDetails();
     $order_total_products_taxed = 0;
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if (!Configuration::get('LEGAL_SHIPTAXMETH')) {
         if ($with_shipping) {
             if (is_null($products) && is_null($id_carrier)) {
                 $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
             } else {
                 $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool) $with_taxes, null, $products);
             }
         } else {
             $shipping_fees = 0;
         }
     } else {
         if (!in_array($type, array(Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_PRODUCTS, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING))) {
             if (is_null($products) && is_null($id_carrier)) {
                 $shipping_fees_taxed = $this->getTotalShippingCost(null, false);
             } else {
                 $shipping_fees_taxed = $this->getPackageShippingCost($id_carrier, false, null, $products);
             }
         } else {
             $shipping_fees_taxed = 0;
         }
         $shipping_fees = Order::calculateCompundTaxPrice($shipping_fees_taxed, $taxes);
         if ($with_taxes) {
             $shipping_fees = $shipping_fees_taxed;
         }
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     $specific_price_output = false;
     $null = false;
     $products_total = array();
     $ecotax_total = 0;
     foreach ($products as $product) {
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
             $id_address = (int) $this->id_address_invoice;
         } else {
             $id_address = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!Address::addressExists($id_address)) {
             $id_address = null;
         }
         $price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 6, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $id_address, $null, false, true, $virtual_context);
         if (Configuration::get('PS_USE_ECOTAX')) {
             $ecotax = $product['ecotax'];
             if (isset($product['attribute_ecotax']) && $product['attribute_ecotax'] > 0) {
                 $ecotax = $product['attribute_ecotax'];
             }
         } else {
             $ecotax = 0;
         }
         $address = Address::initialize($id_address, true);
         if ($with_taxes) {
             $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
             $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
             if ($ecotax) {
                 $ecotax_tax_calculator = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'))->getTaxCalculator();
             }
         } else {
             $id_tax_rules_group = 0;
         }
         if (in_array(Configuration::get('PS_ROUND_TYPE'), array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($products_total[$id_tax_rules_group])) {
                 $products_total[$id_tax_rules_group] = 0;
             }
         } else {
             if (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
                 $products_total[$id_tax_rules_group . '_' . $id_address] = 0;
             }
         }
         switch (Configuration::get('PS_ROUND_TYPE')) {
             case Order::ROUND_TOTAL:
                 $products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_total += $ecotax * (int) $product['cart_quantity'];
                 }
                 break;
             case Order::ROUND_LINE:
                 $product_price = $price * $product['cart_quantity'];
                 if ($with_taxes) {
                     $products_total[$id_tax_rules_group] += Tools::ps_round($product_price + $tax_calculator->getTaxesTotalAmount($product_price), _PS_PRICE_COMPUTE_PRECISION_);
                 } else {
                     $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_);
                 }
                 if ($ecotax) {
                     $ecotax_price = $ecotax * (int) $product['cart_quantity'];
                     if ($with_taxes) {
                         $ecotax_total += Tools::ps_round($ecotax_price + $ecotax_tax_calculator->getTaxesTotalAmount($ecotax_price), _PS_PRICE_COMPUTE_PRECISION_);
                     } else {
                         $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_);
                     }
                 }
                 break;
             case Order::ROUND_ITEM:
             default:
                 $product_price = $with_taxes ? $tax_calculator->addTaxes($price) : $price;
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_price = $with_taxes ? $ecotax_tax_calculator->addTaxes($ecotax) : $ecotax;
                     $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 }
                 break;
         }
     }
     foreach ($products_total as $key => $price) {
         if ($with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
             $tmp = explode('_', $key);
             $address = Address::initialize((int) $tmp[1], true);
             $tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
             $order_total += Tools::ps_round($price + $tax_calculator->getTaxesTotalAmount($price), _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             $order_total += $price;
         }
     }
     if ($ecotax_total && $with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
         $ecotax_total = Tools::ps_round($ecotax_total, _PS_PRICE_COMPUTE_PRECISION_) + Tools::ps_round($ecotax_tax_calculator->getTaxesTotalAmount($ecotax_total), _PS_PRICE_COMPUTE_PRECISION_);
     }
     $order_total += $ecotax_total;
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     if ($this->gift) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), _PS_PRICE_COMPUTE_PRECISION_), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     $order_shipping_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         $flag = false;
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping && !$flag) {
                 $order_shipping_discount = (double) Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
                 $flag = true;
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent != 0 || $cart_rule['obj']->reduction_amount != 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), (double) $order_total_products) + (double) $order_shipping_discount;
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, _PS_PRICE_COMPUTE_PRECISION_);
 }
Example #28
0
 private static function filterProductsByPrice($filter_value, $product_collection)
 {
     if (empty($filter_value)) {
         return $product_collection;
     }
     foreach ($product_collection as $key => $product) {
         if (isset($filter_value) && $filter_value && isset($product['price_min']) && isset($product['id_product']) && ((int) $filter_value[0] > $product['price_min'] || (int) $filter_value[1] < $product['price_max'])) {
             $price = Product::getPriceStatic($product['id_product'], Configuration::get('PS_LAYERED_FILTER_PRICE_USETAX'));
             if ($price < $filter_value[0] || $price > $filter_value[1]) {
                 continue;
             }
             unset($product_collection[$key]);
         }
     }
     return $product_collection;
 }
    /**
     * Formatage des informations produit pour NetEven.
     * @param $t_product
     * @param bool $display
     * @return array
     */
    private function getPropertiesForNetEven($products, $display = false)
    {
        if (!sizeof($products)) {
            return false;
        }
        global $cookie, $link;
        if (!$link) {
            $link = new Link();
        }
        $products_temp = array();
        $compteur_product_no_ean13 = 0;
        $compteur_product_no_ref = 0;
        foreach ($products as $product) {
            $product_reference = 'P' . $product['id_product'];
            if (!empty($product['id_product_attribute'])) {
                $product_reference = 'D' . $product['id_product_attribute'];
            }
            if (self::$type_sku == 'reference') {
                $product_reference = $product['product_reference'];
                if (!empty($product['id_product_attribute'])) {
                    $product_reference = $product['product_attribute_reference'];
                }
            }
            $ean_ps = !empty($product['ean13_declinaison']) ? $product['ean13_declinaison'] : $product['ean13'];
            $codeEan = "";
            if (!empty($ean_ps)) {
                $codeEan = sprintf('%013s', $ean_ps);
            }
            $id_product_attribute = NULL;
            if (!empty($product['id_product_attribute'])) {
                $id_product_attribute = (int) $product['id_product_attribute'];
            }
            $product_price = Product::getPriceStatic((int) $product['id_product'], true, (int) $id_product_attribute, 2, NULL, false, true);
            $product_price_without_reduction = Product::getPriceStatic((int) $product['id_product'], true, (int) $id_product_attribute, 2, NULL, false, false);
            $categories = $this->getProductCategories($product);
            $categories = array_reverse($categories);
            $classification = str_replace('//', '', implode('/', $categories));
            $quantity = Product::getQuantity((int) $product['id_product'], !empty($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : NULL);
            $indice = count($products_temp);
            $weight = $product['weight'];
            if (!empty($id_product_attribute)) {
                $weight += $product['weight_product_attribute'];
            }
            $products_temp[$indice] = array('Title' => $product['name'], 'SKU' => $product_reference, 'Description' => strip_tags($product['description']), 'EAN' => $codeEan, 'Quantity' => $quantity, 'PriceFixed' => $product_price_without_reduction, 'PriceRetail' => $product_price, 'Etat' => 11, 'SKUFamily' => self::$type_sku == 'reference' ? $product['declinaison_default_ref'] : $product['declinaison_default'], 'Classification' => str_replace('Accueil/', '', $classification), 'shipping_delay' => $this->getValue('shipping_delay'), 'Comment' => $this->getValue('comment'), 'Height' => $product['height'], 'Width' => $product['width'], 'Depth' => $product['depth'], 'Weight' => $weight, 'Brand' => !empty($product['name_manufacturer']) ? $product['name_manufacturer'] : $this->getValue('default_brand'));
            $id_lang = isset($cookie->id_lang) ? (int) $cookie->id_lang : (int) Configuration::get('PS_LANG_DEFAULT');
            $sql = 'SELECT t.name
				FROM
				' . _DB_PREFIX_ . 'product_tag pt
				INNER JOIN ' . _DB_PREFIX_ . 'tag t ON (pt.id_tag = t.id_tag AND t.id_lang = ' . intval($id_lang) . ')
				WHERE pt.id_product = ' . intval($product['id_product']);
            $t_tags_bdd = Db::getInstance()->ExecuteS($sql);
            if ($t_tags_bdd && count($t_tags_bdd) > 0) {
                $t_tags_final = array();
                foreach ($t_tags_bdd as $t_tag_bdd) {
                    $t_tags_final[] = $t_tag_bdd['name'];
                }
                $products_temp[$indice]["Keywords"] = implode(',', $t_tags_final);
            }
            //shipping part
            $shipping_price_local = $this->getValue('shipping_price_local');
            if (self::$shipping_by_product && !empty(self::$shipping_by_product_fieldname)) {
                $shipping_price_local = $product[self::$shipping_by_product_fieldname];
            }
            $carrier_france = $this->getConfig('SHIPPING_CARRIER_FRANCE');
            $carrier_zone_france = $this->getConfig('SHIPPING_ZONE_FRANCE');
            if (!empty($carrier_france) && !empty($carrier_zone_france)) {
                $products_temp[$indice]['PriceShippingLocal1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_france, $carrier_zone_france);
            } elseif (!empty($shipping_price_local)) {
                $products_temp[$indice]['PriceShippingLocal1'] = $shipping_price_local;
            }
            $shipping_price_inter = $this->getValue('shipping_price_international');
            $carrier_inter = $this->getConfig('SHIPPING_CARRIER_INTERNATIONAL');
            $carrier_zone_inter = $this->getConfig('SHIPPING_ZONE_INTERNATIONAL');
            if (!empty($carrier_france) && !empty($carrier_zone_france)) {
                $products_temp[$indice]['PriceShippingInt1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_inter, $carrier_zone_inter);
            } elseif (!empty($shipping_price_inter)) {
                $products_temp[$indice]['PriceShippingInt1'] = $shipping_price_inter;
            }
            if (!empty($carrier_france) && !empty($carrier_zone_france)) {
                $products_temp[$indice]['PriceShippingInt1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_inter, $carrier_zone_inter);
            }
            $images = $this->getProductImages($product);
            foreach ($images as $key => $image) {
                if (is_object($link)) {
                    $img_url = $link->getImageLink($product['link_rewrite'], (int) $product['id_product'] . '-' . (int) $image['id_image'], Gateway::getConfig('IMAGE_TYPE_NAME'));
                    $products_temp[$indice]['Image' . ($key + 1)] = 'http://' . str_replace('http://', '', $img_url);
                }
            }
            // Attributes and fetures of product
            $category_default = new Category((int) $product['id_category_default'], (int) $cookie->id_lang);
            $products_temp[$indice]['ArrayOfSpecificFields'] = array();
            $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => 'categorie', 'Value' => $category_default->name);
            $sql = '
				SELECT GROUP_CONCAT(DISTINCT CONCAT(fl.`name`," {##} ",fvl.`value`) SEPARATOR "' . pSQL($this->getValue('separator')) . ' ") as feature_name
				FROM `' . _DB_PREFIX_ . 'feature_product` fp
				LEFT JOIN `' . _DB_PREFIX_ . 'feature_value_lang` fvl ON (fp.`id_feature_value` = fvl.`id_feature_value` AND fvl.id_lang=' . (int) $cookie->id_lang . ')
				LEFT JOIN `' . _DB_PREFIX_ . 'feature_value` fv ON (fv.`id_feature_value` = fvl.`id_feature_value`)
				LEFT JOIN `' . _DB_PREFIX_ . 'feature_lang` fl ON (fl.`id_feature` = fv.`id_feature` AND fl.`id_lang`=' . (int) $cookie->id_lang . ')
				WHERE fp.`id_product` = ' . (int) $product['id_product'] . '
			';
            $product['feature_name'] = Db::getInstance()->getValue($sql);
            if (empty($product['attribute_name']) && empty($product['feature_name'])) {
                continue;
            }
            $features_attributes = array();
            if (!empty($product['attribute_name'])) {
                $features_attributes = explode($this->getValue('separator'), $product['attribute_name']);
            }
            if (!empty($product['feature_name'])) {
                $features_attributes = array_merge($features_attributes, explode($this->getValue('separator'), $product['feature_name']));
            }
            $feature_links = $this->getValue('feature_links');
            foreach ($features_attributes as $value) {
                $infos = explode(' {##} ', $value);
                if (count($infos) == 2 && !empty($infos[0]) && !empty($infos[1]) && !empty($feature_links[trim($infos[0])])) {
                    $specific_name = $feature_links[trim($infos[0])];
                    $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => $specific_name, 'Value' => $infos[1]);
                }
            }
            if (count(self::$customizable_field) > 0) {
                foreach (self::$customizable_field as $key => $value) {
                    $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => $key, 'Value' => $value);
                }
            }
        }
        return $products_temp;
    }
Example #30
0
 public function generate($cron = false)
 {
     self::setCurrency();
     include 'classes/ymlCatalog.php';
     //Язык по умолчанию
     $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
     //Валюта по умолчанию
     $currency_default = new Currency($this->context->cookie->id_currency);
     $this->currency_iso = $currency_default->iso_code;
     //Адрес магазина
     $shop_url = 'http://' . Tools::getHttpHost(false, true) . __PS_BASE_URI__;
     //Категории для экспорта
     $yamarket_с_categories = unserialize(Configuration::get('yamarket_с_categories'));
     //$yamarket_с_suppliers = unserialize(Configuration::get('yamarket_с_supplier'));
     $yamarket_с_combinations = Configuration::get('yamarket_с_combinations');
     $this->yamarket_с_availability = Configuration::get('yamarket_с_availability');
     $this->yamarket_с_shipping = unserialize(Configuration::get('yamarket_с_shipping'));
     //создаем новый магазин
     $catalog = new ymlCatalog();
     $catalog->gzip = Configuration::get('yamarket_с_gzip');
     $shop = new ymlShop();
     $shop->name = Configuration::get('yamarket_с_shop');
     $shop->company = Configuration::get('yamarket_с_company');
     $shop->url = $shop_url;
     $shop->platform = 'PrestaShop';
     $shop->version = _PS_VERSION_;
     $shop->agency = 'PrestaLab';
     $shop->email = '*****@*****.**';
     //Валюты
     $shop->startTag(ymlCurrency::$collectionName);
     if (Configuration::get('yamarket_с_currencies')) {
         $currencies = Currency::getCurrencies();
         foreach ($currencies as $currency) {
             $shop->add(new ymlCurrency($currency['iso_code'], (double) $currency['conversion_rate']));
         }
         unset($currencies);
     } else {
         $shop->add(new ymlCurrency($currency_default->iso_code, (double) $currency_default->conversion_rate));
     }
     $shop->endTag(ymlCurrency::$collectionName);
     //Категории
     $categories = Category::getCategories($id_lang, false, false);
     $shop->startTag(ymlCategory::$collectionName);
     foreach ($categories as $category) {
         if ($category['active'] && in_array($category['id_category'], $yamarket_с_categories)) {
             $shop->add(new ymlCategory($category['id_category'], $category['name'], $category['id_parent']));
         }
     }
     $shop->endTag(ymlCategory::$collectionName);
     //Стоимость доставки
     $shop->addString('<local_delivery_cost>' . Configuration::get('yamarket_с_shippingcost') . '</local_delivery_cost>');
     //Товары
     $shop->startTag(ymlOffer::$collectionName);
     foreach ($categories as $category) {
         if ($category['active'] && in_array($category['id_category'], $yamarket_с_categories)) {
             $category_object = new Category($category['id_category']);
             $products = $category_object->getProducts($id_lang, 1, 10000);
             if ($products) {
                 foreach ($products as $product) {
                     if ($product['id_category_default'] != $category['id_category']) {
                         continue;
                     }
                     //						if (count($yamarket_с_suppliers)&&(!in_array($product['id_supplier'], $yamarket_с_suppliers)))
                     //							continue;
                     //Для комбинаций
                     if ($yamarket_с_combinations) {
                         $product_object = new Product($product['id_product'], false, $id_lang);
                         $combinations = $product_object->getAttributeCombinations($id_lang);
                     } else {
                         $combinations = false;
                     }
                     if (is_array($combinations) && count($combinations) > 0) {
                         $comb_array = array();
                         foreach ($combinations as $combination) {
                             $comb_array[$combination['id_product_attribute']]['id_product_attribute'] = $combination['id_product_attribute'];
                             $comb_array[$combination['id_product_attribute']]['price'] = Product::getPriceStatic($product['id_product'], true, $combination['id_product_attribute']);
                             $comb_array[$combination['id_product_attribute']]['reference'] = $combination['reference'];
                             $comb_array[$combination['id_product_attribute']]['ean13'] = $combination['ean13'];
                             $comb_array[$combination['id_product_attribute']]['quantity'] = $combination['quantity'];
                             $comb_array[$combination['id_product_attribute']]['attributes'][$combination['group_name']] = $combination['attribute_name'];
                             $comb_array[$combination['id_product_attribute']]['oldprice'] = $product['orderprice'] + $combination['price'];
                             if (!isset($comb_array[$combination['id_product_attribute']]['comb_url'])) {
                                 $comb_array[$combination['id_product_attribute']]['comb_url'] = '';
                             }
                             $comb_array[$combination['id_product_attribute']]['comb_url'] .= '/' . (self::combinationUrlPrepare($combination['group_name']) . '-' . self::combinationUrlPrepare($combination['attribute_name']));
                         }
                         foreach ($comb_array as $combination) {
                             self::_addProduct($shop, $product, $combination);
                         }
                     } else {
                         self::_addProduct($shop, $product);
                     }
                 }
             }
             unset($product);
         }
     }
     unset($categories);
     $shop->endTag(ymlOffer::$collectionName);
     $catalog->add($shop);
     if ($cron) {
         if ($fp = fopen(_PS_UPLOAD_DIR_ . 'yml.' . $this->context->shop->id . '.xml' . ($catalog->gzip ? '.gz' : ''), 'w')) {
             fwrite($fp, $catalog->generate());
             fclose($fp);
         }
     } else {
         if ($catalog->gzip) {
             header('Content-type:application/x-gzip');
             header('Content-Disposition: attachment; filename=yml.' . $this->context->shop->id . '.xml.gz');
         } else {
             header('Content-type:application/xml;  charset=utf-8');
         }
         echo $catalog->generate();
     }
 }