Exemplo n.º 1
0
 /**
  * Gets the name of a given product, in the given lang
  * HAI : override method to record product name with sort
  * 
  * @since 1.5.0
  * @param int $id_product
  * @param int $id_product_attribute Optional
  * @param int $id_lang Optional
  * @return string
  */
 public static function getProductName($id_product, $id_product_attribute = null, $id_lang = null)
 {
     // use the lang in the context if $id_lang is not defined
     if (!$id_lang) {
         $id_lang = (int) Context::getContext()->language->id;
     }
     // creates the query object
     $query = new DbQuery();
     // selects different names, if it is a combination
     if ($id_product_attribute) {
         $query->select('IFNULL(CONCAT(pl.name, \' : \', GROUP_CONCAT(DISTINCT agl.`name`, \' - \', al.name ORDER BY agl.`name`, \' - \', al.name ASC SEPARATOR \', \')),pl.name) as name');
     } else {
         $query->select('DISTINCT pl.name as name');
     }
     // adds joins & where clauses for combinations
     if ($id_product_attribute) {
         $query->from('product_attribute', 'pa');
         $query->join(Shop::addSqlAssociation('product_attribute', 'pa'));
         $query->innerJoin('product_lang', 'pl', 'pl.id_product = pa.id_product AND pl.id_lang = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl'));
         $query->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pa.id_product_attribute');
         $query->leftJoin('attribute', 'atr', 'atr.id_attribute = pac.id_attribute');
         $query->leftJoin('attribute_lang', 'al', 'al.id_attribute = atr.id_attribute AND al.id_lang = ' . (int) $id_lang);
         $query->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = atr.id_attribute_group AND agl.id_lang = ' . (int) $id_lang);
         $query->where('pa.id_product = ' . (int) $id_product . ' AND pa.id_product_attribute = ' . (int) $id_product_attribute);
     } else {
         $query->from('product_lang', 'pl');
         $query->where('pl.id_product = ' . (int) $id_product);
         $query->where('pl.id_lang = ' . (int) $id_lang . Shop::addSqlRestrictionOnLang('pl'));
     }
     return Db::getInstance()->getValue($query);
 }
 /**
  * Launch sql query to create collection of objects
  *
  * @param bool $display_query If true, query will be displayed (for debug purpose)
  * @return PrestaShopCollection
  */
 public function getAll($display_query = false)
 {
     if ($this->is_hydrated) {
         return $this;
     }
     $this->is_hydrated = true;
     $alias = $this->generateAlias();
     //$this->query->select($alias.'.*');
     $this->query->from($this->definition['table'], $alias);
     // If multilang, create association to lang table
     if (!empty($this->definition['multilang'])) {
         $this->join(self::LANG_ALIAS);
         if ($this->id_lang) {
             $this->where(self::LANG_ALIAS . '.id_lang', '=', $this->id_lang);
         }
     }
     // Add join clause
     foreach ($this->join_list as $data) {
         $on = '(' . implode(') AND (', $data['on']) . ')';
         switch ($data['type']) {
             case self::LEFT_JOIN:
                 $this->query->leftJoin($data['table'], $data['alias'], $on);
                 break;
             case self::INNER_JOIN:
                 $this->query->innerJoin($data['table'], $data['alias'], $on);
                 break;
             case self::LEFT_OUTER_JOIN:
                 $this->query->leftOuterJoin($data['table'], $data['alias'], $on);
                 break;
         }
     }
     // All limit clause
     if ($this->page_size) {
         $this->query->limit($this->page_size, $this->page_number * $this->page_size);
     }
     // Shall we display query for debug ?
     if ($display_query) {
         echo $this->query . '<br />';
     }
     $this->results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query);
     if ($this->results && is_array($this->results)) {
         $this->results = ObjectModel::hydrateCollection($this->classname, $this->results, $this->id_lang);
     }
     return $this;
 }
Exemplo n.º 3
0
 /**
  * Returns all menu items for a given shop
  *
  * @param int $id_lang
  * @param int $id_shop
  *
  * @return array
  */
 public static function getMenuItems($id_lang, $id_shop)
 {
     $sql = new DbQuery();
     $sql->select('i.*, il.url, il.title, il.name');
     $sql->from('ct_top_menu_item', 'i');
     $sql->leftJoin('ct_top_menu_item_lang', 'il', 'i.id_ct_top_menu_item = il.id_ct_top_menu_item AND il.id_lang = ' . (int) $id_lang);
     $sql->innerJoin('ct_top_menu_item_shop', 'ishop', 'i.id_ct_top_menu_item = ishop.id_ct_top_menu_item AND ishop.id_shop = ' . (int) $id_shop);
     $sql->orderBy('ishop.position ASC');
     return (array) Db::getInstance()->executeS($sql);
 }
Exemplo n.º 4
0
    private function getAbandonedCartInfo()
    {
        if ((int) $this->cart_id < 1) {
            return false;
        }
        $query_limit = 0;
        $query_offset = 0;
        $cart_products = array();
        if ($this->page !== null && !empty($this->page) && $this->show !== null && !empty($this->show)) {
            $query_limit = ((int) $this->page - 1) * (int) $this->show;
            $query_offset = (int) $this->show;
        }
        // Get cart information
        $cart_info_obj = new DbQuery();
        $cart_info_obj->select("\r\n\t\t\tc.id_cart,\r\n\t\t\tc.date_add,\r\n\t\t\tc.id_currency,\r\n\t\t\tc.id_customer,\r\n\t\t\tcus.date_add AS account_registered,\r\n\t\t\tcus.email,\r\n\t\t\ta.phone,\r\n\t\t\tCONCAT(cus.firstname, ' ', cus.lastname) AS customer,\r\n\t\t\ts.name AS shop_name,\r\n\t\t\tcar.name AS carrier_name,\r\n\t\t\tSUM((ps.price + pas.price) * cp.quantity) AS cart_total\r\n\t\t");
        $cart_info_obj->from('cart', 'c');
        $cart_info_obj->innerJoin('cart_product', 'cp', 'cp.id_cart = c.id_cart');
        $cart_info_obj->leftJoin('product_shop', 'ps', 'ps.id_product = cp.id_product AND ps.id_shop = cp.id_shop');
        $cart_info_obj->leftJoin('product_attribute_shop', 'pas', 'pas.id_product_attribute = cp.id_product_attribute AND pas.id_shop = cp.id_shop');
        $cart_info_obj->leftJoin('customer', 'cus', 'c.id_customer = cus.id_customer');
        $cart_info_obj->leftJoin('address', 'a', 'a.id_customer = cus.id_customer');
        $cart_info_obj->leftJoin('shop', 's', 's.id_shop = c.id_shop');
        $cart_info_obj->leftJoin('carrier', 'car', 'car.id_carrier = c.id_carrier');
        $cart_info_obj->where('c.id_cart = ' . (int) $this->cart_id);
        $cart_info_obj->groupBy('c.id_cart');
        $cart_info_sql = $cart_info_obj->build();
        $cart_info = Db::getInstance()->executeS($cart_info_sql);
        $cart_info = array_shift($cart_info);
        if (trim($cart_info['customer']) == '') {
            $cart_info['customer'] = self::GUEST;
        }
        // Convert and format price data
        if ($this->currency_code != $cart_info['id_currency']) {
            $cart_info['cart_total'] = $this->convertPrice($cart_info['cart_total'], $this->def_currency, $cart_info['id_currency']);
        }
        $cart_info['cart_total'] = $this->displayPrice($cart_info['cart_total'], $cart_info['id_currency']);
        // Get cart products
        $cart_products_obj = new DbQuery();
        $cart_products_obj->select('
			cp.id_product,
			cp.id_product_attribute,
			cp.quantity AS product_quantity,
			p.reference AS sku,
			(ps.price + pas.price) AS product_price,
			(ps.wholesale_price + pas.wholesale_price) AS wholesale_price,
			c.id_currency,
			pl.name AS product_name,
			pl.link_rewrite
		');
        $cart_products_obj->from('cart_product', 'cp');
        $cart_products_obj->leftJoin('product_shop', 'ps', 'ps.id_product = cp.id_product AND ps.id_shop = cp.id_shop');
        $cart_products_obj->leftJoin('product_attribute_shop', 'pas', 'pas.id_product_attribute = cp.id_product_attribute AND pas.id_shop = cp.id_shop');
        $cart_products_obj->leftJoin('product', 'p', 'p.id_product = cp.id_product');
        $cart_products_obj->leftJoin('cart', 'c', 'c.id_cart = cp.id_cart');
        $cart_products_obj->leftJoin('product_lang', 'pl', 'pl.id_product = cp.id_product AND pl.id_shop = cp.id_shop AND pl.id_lang = ' . (int) $this->def_lang);
        $cart_products_obj->where('cp.id_cart = ' . (int) $this->cart_id);
        $cart_products_obj->limit($query_offset, $query_limit);
        $cart_products_sql = $cart_products_obj->build();
        $cart_products_res = Db::getInstance()->executeS($cart_products_sql);
        // Get attribute values
        foreach ($cart_products_res as $product) {
            $product_attributes_obj = new DbQuery();
            $product_attributes_obj->select('
				al.name AS attribute_value,
				agl.public_name AS attribute_name
			');
            $product_attributes_obj->from('product_attribute_combination', 'pac');
            $product_attributes_obj->leftJoin('attribute_lang', 'al', 'al.id_attribute = pac.id_attribute AND al.id_lang = ' . (int) $this->def_lang);
            $product_attributes_obj->leftJoin('attribute', 'a', 'a.id_attribute = pac.id_attribute');
            $product_attributes_obj->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = a.id_attribute_group AND agl.id_lang = ' . (int) $this->def_lang);
            $product_attributes_obj->where('pac.id_product_attribute = ' . (int) $product['id_product_attribute']);
            $product_attributes_obj->orderBy('attribute_name');
            $product_attributes_sql = $product_attributes_obj->build();
            $product_attributes = Db::getInstance()->executeS($product_attributes_sql);
            $product_attr = array();
            foreach ($product_attributes as $product_attribute) {
                $product_attr[] = $product_attribute['attribute_name'] . ' : ' . $product_attribute['attribute_value'];
            }
            $product['combination'] = !empty($product_attr) ? implode(', ', $product_attr) : '';
            // Convert and form price data
            if ($this->currency_code != $this->def_currency) {
                $product['product_price'] = $this->convertPrice($product['product_price'], $this->def_currency, $product['id_currency']);
                $product['wholesale_price'] = $this->convertPrice($product['wholesale_price'], $this->def_currency, $product['id_currency']);
            }
            $product['product_price'] = $this->displayPrice($product['product_price'], $product['id_currency']);
            $product['wholesale_price'] = $this->displayPrice($product['wholesale_price'], $product['id_currency']);
            // Get url of product image
            $image_url = $this->getProductImageUrl($product['id_product'], $product['link_rewrite']);
            if ($image_url) {
                $product['product_image'] = $image_url;
            }
            $cart_products[] = $product;
        }
        // Get cart product count
        $cart_product_count_obj = new DbQuery();
        $cart_product_count_obj->select('
			COUNT(cp.id_product) AS product_count
		');
        $cart_product_count_obj->from('cart_product', 'cp');
        $cart_product_count_obj->where('cp.id_cart = ' . (int) $this->cart_id);
        $cart_product_count_sql = $cart_product_count_obj->build();
        $cart_product_count_res = Db::getInstance()->executeS($cart_product_count_sql);
        $cart_product_count_res = array_shift($cart_product_count_res);
        return array('cart_info' => $cart_info, 'cart_products' => $cart_products, 'cart_products_count' => $cart_product_count_res['product_count']);
    }
Exemplo n.º 5
0
 /**
  * For a given {product, warehouse}, gets the carrier available
  *
  * @param JeproshopProductModelProduct $product The id of the product, or an array with at least the package size and weight
  * @param int $warehouse_id
  * @param int $address_delivery_id
  * @param int $shop_id
  * @param $cart
  * @return array
  */
 public static function getAvailableCarrierList(JeproshopProductModelProduct $product, $warehouse_id, $address_delivery_id = null, $shop_id = null, $cart = null)
 {
     if (is_null($shop_id)) {
         $shop_id = JeproshopContext::getContext()->shop->shop_id;
     }
     if (is_null($cart)) {
         $cart = JeproshopContext::getContext()->cart;
     }
     $address_id = (int) (!is_null($address_delivery_id) && $address_delivery_id != 0 ? $address_delivery_id : $cart->address_delivery_id);
     if ($address_id) {
         $address = new JeproshopAddressModelAddress($address_id);
         $zone_id = JeproshopAddressModelAddress::getZoneIdByAddressId($address->address_id);
         // Check the country of the address is activated
         if (!JeproshopAddressModelAddress::isCountryActiveById($address->address_id)) {
             return array();
         }
     } else {
         $country = new JeproshopCountryModelCountry(JeproshopSettingModelSetting::getValue('default_country'));
         $izone_id = $country->zone_id;
     }
     // Does the product is linked with carriers?
     $query = new DbQuery();
     $query->select('id_carrier');
     $query->from('product_carrier', 'pc');
     $query->innerJoin('carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0');
     $query->where('pc.id_product = ' . (int) $product->product_id);
     $query->where('pc.id_shop = ' . (int) $shop_id);
     $cache_id = 'Carrier::getAvailableCarrierList_' . (int) $product->id . '-' . (int) $id_shop;
     if (!Cache::isStored($cache_id)) {
         $carriers_for_product = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
         Cache::store($cache_id, $carriers_for_product);
     }
     $carriers_for_product = Cache::retrieve($cache_id);
     $carrier_list = array();
     if (!empty($carriers_for_product)) {
         //the product is linked with carriers
         foreach ($carriers_for_product as $carrier) {
             //check if the linked carriers are available in current zone
             if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone)) {
                 $carrier_list[] = $carrier['id_carrier'];
             }
         }
         if (empty($carrier_list)) {
             return array();
         }
         //no linked carrier are available for this zone
     }
     // The product is not directly linked with a carrier
     // Get all the carriers linked to a warehouse
     if ($warehouse_id) {
         $warehouse = new JeproshopWarehouseModelWarehouse($warehouse_id);
         $warehouse_carrier_list = $warehouse->getCarriers();
     }
     $available_carrier_list = array();
     $customer = new JeproshopCustomerModelCustomer($cart->customer_id);
     $carriers = JeproshopCarrierModelCarrier::getCarriersForOrder($zone_id, $customer->getGroups(), $cart);
     foreach ($carriers as $carrier) {
         $available_carrier_list[] = $carrier->carrier_id;
     }
     if ($carrier_list) {
         $carrier_list = array_intersect($available_carrier_list, $carrier_list);
     } else {
         $carrier_list = $available_carrier_list;
     }
     if (isset($warehouse_carrier_list)) {
         $carrier_list = array_intersect($carrier_list, $warehouse_carrier_list);
     }
     if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0) {
         foreach ($carrier_list as $key => $carrier_id) {
             $carrier = new JeproshopCarrierModelCarrier($carrier_id);
             if ($carrier->max_width > 0 && $carrier->max_width < $product->width || $carrier->max_height > 0 && $carrier->max_height < $product->height || $carrier->max_depth > 0 && $carrier->max_depth < $product->depth || $carrier->max_weight > 0 && $carrier->max_weight < $product->weight) {
                 unset($carrier_list[$key]);
             }
         }
     }
     return $carrier_list;
 }
Exemplo n.º 6
0
 /**
  * For a given {product, warehouse}, gets the carrier available
  *
  * @since 1.5.0
  *
  * @param Product $product             The id of the product, or an array with at least the package size and weight
  * @param int     $id_warehouse        Warehouse ID
  * @param int     $id_address_delivery Delivery Address ID
  * @param int     $id_shop             Shop ID
  * @param Cart    $cart                Cart object
  * @param array   &$error              contain an error message if an error occurs
  *
  * @return array Available Carriers
  * @throws PrestaShopDatabaseException
  */
 public static function getAvailableCarrierList(Product $product, $id_warehouse, $id_address_delivery = null, $id_shop = null, $cart = null, &$error = array())
 {
     static $ps_country_default = null;
     if ($ps_country_default === null) {
         $ps_country_default = Configuration::get('PS_COUNTRY_DEFAULT');
     }
     if (is_null($id_shop)) {
         $id_shop = Context::getContext()->shop->id;
     }
     if (is_null($cart)) {
         $cart = Context::getContext()->cart;
     }
     if (is_null($error) || !is_array($error)) {
         $error = array();
     }
     $id_address = (int) (!is_null($id_address_delivery) && $id_address_delivery != 0 ? $id_address_delivery : $cart->id_address_delivery);
     if ($id_address) {
         $id_zone = Address::getZoneById($id_address);
         // Check the country of the address is activated
         if (!Address::isCountryActiveById($id_address)) {
             return array();
         }
     } else {
         $country = new Country($ps_country_default);
         $id_zone = $country->id_zone;
     }
     // Does the product is linked with carriers?
     $cache_id = 'Carrier::getAvailableCarrierList_' . (int) $product->id . '-' . (int) $id_shop;
     if (!Cache::isStored($cache_id)) {
         $query = new DbQuery();
         $query->select('id_carrier');
         $query->from('product_carrier', 'pc');
         $query->innerJoin('carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0 AND c.active = 1');
         $query->where('pc.id_product = ' . (int) $product->id);
         $query->where('pc.id_shop = ' . (int) $id_shop);
         $carriers_for_product = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
         Cache::store($cache_id, $carriers_for_product);
     } else {
         $carriers_for_product = Cache::retrieve($cache_id);
     }
     $carrier_list = array();
     if (!empty($carriers_for_product)) {
         //the product is linked with carriers
         foreach ($carriers_for_product as $carrier) {
             //check if the linked carriers are available in current zone
             if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone)) {
                 $carrier_list[$carrier['id_carrier']] = $carrier['id_carrier'];
             }
         }
         if (empty($carrier_list)) {
             return array();
         }
         //no linked carrier are available for this zone
     }
     // The product is not directly linked with a carrier
     // Get all the carriers linked to a warehouse
     if ($id_warehouse) {
         $warehouse = new Warehouse($id_warehouse);
         $warehouse_carrier_list = $warehouse->getCarriers();
     }
     $available_carrier_list = array();
     $cache_id = 'Carrier::getAvailableCarrierList_getCarriersForOrder_' . (int) $id_zone . '-' . (int) $cart->id;
     if (!Cache::isStored($cache_id)) {
         $customer = new Customer($cart->id_customer);
         $carrier_error = array();
         $carriers = Carrier::getCarriersForOrder($id_zone, $customer->getGroups(), $cart, $carrier_error);
         Cache::store($cache_id, array($carriers, $carrier_error));
     } else {
         list($carriers, $carrier_error) = Cache::retrieve($cache_id);
     }
     $error = array_merge($error, $carrier_error);
     foreach ($carriers as $carrier) {
         $available_carrier_list[$carrier['id_carrier']] = $carrier['id_carrier'];
     }
     if ($carrier_list) {
         $carrier_list = array_intersect($available_carrier_list, $carrier_list);
     } else {
         $carrier_list = $available_carrier_list;
     }
     if (isset($warehouse_carrier_list)) {
         $carrier_list = array_intersect($carrier_list, $warehouse_carrier_list);
     }
     $cart_quantity = 0;
     $cart_weight = 0;
     foreach ($cart->getProducts(false, false) as $cart_product) {
         if ($cart_product['id_product'] == $product->id) {
             $cart_quantity += $cart_product['cart_quantity'];
         }
         if (isset($cart_product['weight_attribute']) && $cart_product['weight_attribute'] > 0) {
             $cart_weight += $cart_product['weight_attribute'] * $cart_product['cart_quantity'];
         } else {
             $cart_weight += $cart_product['weight'] * $cart_product['cart_quantity'];
         }
     }
     if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0 || $cart_weight > 0) {
         foreach ($carrier_list as $key => $id_carrier) {
             $carrier = new Carrier($id_carrier);
             // Get the sizes of the carrier and the product and sort them to check if the carrier can take the product.
             $carrier_sizes = array((int) $carrier->max_width, (int) $carrier->max_height, (int) $carrier->max_depth);
             $product_sizes = array((int) $product->width, (int) $product->height, (int) $product->depth);
             rsort($carrier_sizes, SORT_NUMERIC);
             rsort($product_sizes, SORT_NUMERIC);
             if ($carrier_sizes[0] > 0 && $carrier_sizes[0] < $product_sizes[0] || $carrier_sizes[1] > 0 && $carrier_sizes[1] < $product_sizes[1] || $carrier_sizes[2] > 0 && $carrier_sizes[2] < $product_sizes[2]) {
                 $error[$carrier->id] = Carrier::SHIPPING_SIZE_EXCEPTION;
                 unset($carrier_list[$key]);
             }
             if ($carrier->max_weight > 0 && ($carrier->max_weight < $product->weight * $cart_quantity || $carrier->max_weight < $cart_weight)) {
                 $error[$carrier->id] = Carrier::SHIPPING_WEIGHT_EXCEPTION;
                 unset($carrier_list[$key]);
             }
         }
     }
     return $carrier_list;
 }
Exemplo n.º 7
0
 /**
  * Gets available warehouses
  * It is possible via ignore_shop and id_shop to filter the list with shop id
  *
  * @param bool $ignore_shop Optional, false by default - Allows to get only the warehouses that are associated to one/some shops (@see $id_shop)
  * @param int $id_shop Optional, Context::shop::Id by default - Allows to define a specific shop to filter.
  * @return array Warehouses (ID, reference/name concatenated)
  */
 public static function getWarehouses($ignore_shop = false, $id_shop = null)
 {
     if (!$ignore_shop) {
         if (is_null($id_shop)) {
             $id_shop = Context::getContext()->shop->id;
         }
     }
     $query = new DbQuery();
     $query->select('w.id_warehouse, CONCAT(reference, \' - \', name) as name');
     $query->from('warehouse', 'w');
     $query->where('deleted = 0');
     $query->orderBy('reference ASC');
     if (!$ignore_shop) {
         $query->innerJoin('warehouse_shop', 'ws', 'ws.id_warehouse = w.id_warehouse AND ws.id_shop = ' . (int) $id_shop);
     }
     return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
 }
Exemplo n.º 8
0
 /**
  * For a given {product, warehouse}, gets the carrier available
  *
  * @since 1.5.0
  * @param Product $product The id of the product, or an array with at least the package size and weight
  * @return array
  */
 public static function getAvailableCarrierList(Product $product, $id_warehouse, $id_address_delivery = null, $id_shop = null, $cart = null)
 {
     if (is_null($id_shop)) {
         $id_shop = Context::getContext()->shop->id;
     }
     if (is_null($cart)) {
         $cart = Context::getContext()->cart;
     }
     $id_address = (int) (!is_null($id_address_delivery) && $id_address_delivery != 0 ? $id_address_delivery : $cart->id_address_delivery);
     if ($id_address) {
         $address = new Address($id_address);
         $id_zone = Address::getZoneById($address->id);
         // Check the country of the address is activated
         if (!Address::isCountryActiveById($address->id)) {
             return array();
         }
     } else {
         $country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'));
         $id_zone = $country->id_zone;
     }
     // Does the product is linked with carriers?
     $query = new DbQuery();
     $query->select('id_carrier');
     $query->from('product_carrier', 'pc');
     $query->innerJoin('carrier', 'c', 'c.id_reference = pc.id_carrier_reference AND c.deleted = 0');
     $query->where('pc.id_product = ' . (int) $product->id);
     $query->where('pc.id_shop = ' . (int) $id_shop);
     $carriers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
     if (!empty($carriers)) {
         //the product is linked with carriers
         $carrier_list = array();
         foreach ($carriers as $carrier) {
             //check if the linked carriers are available in current zone
             if (Carrier::checkCarrierZone($carrier['id_carrier'], $id_zone)) {
                 $carrier_list[] = $carrier['id_carrier'];
             }
         }
         if (!empty($carrier_list)) {
             return $carrier_list;
         } else {
             return array();
         }
         //no linked carrier are available for this zone
     }
     $carrier_list = array();
     // The product is not dirrectly linked with a carrier
     // Get all the carriers linked to a warehouse
     if ($id_warehouse) {
         $warehouse = new Warehouse($id_warehouse);
         $warehouse_carrier_list = $warehouse->getCarriers();
     }
     $available_carrier_list = array();
     $customer = new Customer($cart->id_customer);
     $carriers = Carrier::getCarriersForOrder($id_zone, $customer->getGroups(), $cart);
     foreach ($carriers as $carrier) {
         $available_carrier_list[] = $carrier['id_carrier'];
     }
     if (empty($warehouse_carrier_list)) {
         $carrier_list = $available_carrier_list;
     } else {
         $carrier_list = array_intersect($warehouse_carrier_list, $available_carrier_list);
     }
     if ($product->width > 0 || $product->height > 0 || $product->depth > 0 || $product->weight > 0) {
         foreach ($carrier_list as $key => $id_carrier) {
             $carrier = new Carrier($id_carrier);
             if ($carrier->max_width > 0 && $carrier->max_width < $product->width || $carrier->max_height > 0 && $carrier->max_height < $product->height || $carrier->max_depth > 0 && $carrier->max_depth < $product->depth || $carrier->max_weight > 0 && $carrier->max_weight < $product->weight) {
                 unset($carrier_list[$key]);
             }
         }
     }
     return $carrier_list;
 }
Exemplo n.º 9
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, 
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.`wholesale_price`, product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('p.`id_product`, cp.`id_product_attribute`, cp.`date_add` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            //                        $quantityDiscount = SpecificPrice::getQuantityDiscount((int)$row['id_product'], $row['id_shop'],
            //			(int)$cart->id_currency, (int)$this->vat_address->id_country,
            //			(int)$this->customer->id_default_group, (int)$row['cart_quantity'], false, null, null, $null, true, true, $this->context);
            //
            //                        echo '<pre>';
            //                        print_r($quantityDiscount);
            //                        echo '</pre>';
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            if ($this->_taxCalculationMethod == PS_TAX_EXC) {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                // Here taxes are computed only once the quantity has been applied to the product price
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, true, (int) $row['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, $cart_shop_context);
                $tax_rate = Tax::getProductTaxRate((int) $row['id_product'], (int) $address_id);
                $row['total_wt'] = Tools::ps_round($row['price'] * (double) $row['cart_quantity'] * (1 + (double) $tax_rate / 100), 2);
                $row['total'] = $row['price'] * (int) $row['cart_quantity'];
            } else {
                $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, (int) $row['id_product_attribute'], 2, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, (int) $address_id ? (int) $address_id : null, $specific_price_output, true, true, $cart_shop_context);
                $row['price_wt'] = Product::getPriceStatic((int) $row['id_product'], true, (int) $row['id_product_attribute'], 2, null, false, true, $row['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, $cart_shop_context);
                // In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals
                $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
                $row['total_wt'] = $row['price_wt'] * (int) $row['cart_quantity'];
                $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], 2);
                $row['description_short'] = Tools::nl2br($row['description_short']);
            }
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            if (Context::getContext()->language->id != 1) {
                $row['name'] = Tools::rus2translit($row['name']);
            }
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
    public function ajaxGetProductsForSupplyOrder()
    {
        require_once _PS_MODULE_DIR_ . 'erpillicopresta/classes/stock/ErpSupplyOrderClasses.php';
        require_once _PS_MODULE_DIR_ . 'erpillicopresta/erpillicopresta.php';
        /* manage advanced stock */
        $stock_management_active = Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT');
        $sales_forecast_type = Configuration::get('ERP_SALES_FORECAST_CHOICE');
        $id_supplier = (int) Tools::getValue('id_supplier', false);
        $id_currency = (int) Tools::getValue('id_currency', false);
        $id_categorie = (int) Tools::getValue('id_categorie', false);
        $id_manufacturer = (int) Tools::getValue('id_manufacturer', false);
        $id_warehouse = (int) Tools::getValue('id_warehouse', null);
        $existing_ids = Tools::getValue('ids');
        //$token_get_product      = Tools::getValue('token');
        $products = ErpSupplyOrderClasses::searchProduct($id_supplier, $id_categorie, $id_manufacturer, $id_currency);
        if (!empty($products)) {
            $advanced_stock_token = Tools::getAdminToken('AdminAdvancedStock' . (int) Tab::getIdFromClassName('AdminAdvancedStock') . (int) $this->context->employee->id);
            foreach ($products as $product) {
                // If product already in destination array, continue
                if (strrpos($existing_ids, $product['id']) !== false) {
                    continue;
                }
                $ids = explode('_', $product['id']);
                $id_product = $ids[0];
                $id_product_attribute = $ids[1];
                // If the advanced stock manager is activated
                if ($stock_management_active == '1') {
                    // Get the physical and usable quantities
                    $query = new DbQuery();
                    $query->select('physical_quantity');
                    $query->select('usable_quantity');
                    $query->from('stock');
                    $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute);
                    $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
                    /* the two quantities */
                    $physical_quantity = (int) $res['physical_quantity'];
                    $usable_quantity = (int) $res['usable_quantity'];
                    // The real quantity depends of the warehouse
                    $manager = StockManagerFactory::getManager();
                    $product['stock'] = $real_quantity = (int) $manager->getProductRealQuantities($id_product, $id_product_attribute, $id_warehouse, true);
                } else {
                    // get the free quantities
                    $product['stock'] = $usable_quantity = (int) Product::getQuantity($id_product, $id_product_attribute);
                }
                /*  TAX */
                /*  Get the current tax */
                $query = new DbQuery();
                $query->select('rate');
                $query->from('tax', 't');
                $query->innerJoin('tax_rule', 'tr', 'tr.id_tax = t.id_tax');
                $query->innerJoin('product', 'p', 'p.id_tax_rules_group = tr.id_tax_rules_group');
                $query->where('p.id_product = ' . (int) $id_product);
                $query->where('tr.id_country IN (SELECT id_country
                                                FROM ' . _DB_PREFIX_ . 'address
                                                WHERE id_supplier = ' . (int) $id_supplier . ')');
                $product['tax_rate'] = round(Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query), 1);
                $prices = ErpSupplyOrderClasses::getWholesalePrice((int) $id_product, (int) $id_product_attribute, (int) $id_supplier);
                $product['unit_price_te'] = Tools::convertPriceFull($prices, new Currency((int) $id_currency));
                // sales quantity for X rolling month
                $quantity_sales = ErpSupplyOrderClasses::getQuantitySales((int) $id_product, (int) $id_product_attribute);
                // if sale forecast is activ
                if ($sales_forecast_type != 0) {
                    // if we use the 6 month rolling method
                    if ($sales_forecast_type == 1) {
                        $sales_forecasts = round(ErpSupplyOrderClasses::getProductSalesForecasts($id_product, $id_product_attribute), 1);
                    } else {
                        $sales_forecasts = round(ErpSupplyOrderClasses::getProductSalesForecastsByPeriod($id_product, $id_product_attribute), 1);
                    }
                } else {
                    $sales_forecasts = 'NA';
                }
                // Sales gain
                $sales_gains = ErpSupplyOrderClasses::getProductSalesGains($id_product, $id_product_attribute);
                // Prepare the hidden json foreach line
                $product['comment'] = '';
                $product_json = Tools::jsonEncode($product);
                echo '<tr>
                                        <td class="product_json hide">' . $product_json . '</td>
                                        <td><input type="checkbox" class="select_product" name="select_product"/></td>
                                        <td>' . $product['supplier_reference'] . '</td>
                                        <td>' . $product['reference'] . '</td>
                                        <td>
                                                         <a href="#" class="cluetip-supply-price" title="' . $this->l('Supplier Price') . '"
                                                                                        rel="index.php?controller=AdminAdvancedStock&ajax=1&id_product=' . $id_product . '&id_product_attribute=' . $id_product_attribute . '&id_currency=' . $id_currency . '&task=getProductSupplierPrice&token=' . $advanced_stock_token . '" >
                                                                                                                           <img src="themes/default/img/icon-search.png">
                                                        </a>
                                                        ' . $product['name'] . '
                                        </td>';
                if (Configuration::get(ErpIllicopresta::getControllerStatusName('AdminAdvancedSupplyOrder'))) {
                    echo '<td align="center"> <p style="background-color:' . ErpSupplyOrderClasses::getStockLevelColor($real_quantity) . '; width:16px; height:16px"></p> </td>';
                }
                echo '<td align="center">' . $usable_quantity . '</td>
                                        ' . ($stock_management_active == '1' ? '
                                                                        <td align="center">' . $physical_quantity . '</td>
                                                                        <td align="center">' . $real_quantity . '</td>' : '') . '';
                if (Configuration::get(ErpIllicopresta::getControllerStatusName('AdminAdvancedSupplyOrder'))) {
                    echo '<td align="center">' . $quantity_sales . '</td>
                                                <td align="center">' . $sales_gains . '</td>';
                    if (Configuration::get('ERP_SALES_FORECAST_CHOICE') != 0) {
                        echo '<td>' . $sales_forecasts . '</td>';
                    }
                }
                echo '<td align="center"><input type="text" class="quantity_ordered" size="2" /></td>
                                        <td align="center"> <input type="text" name="comment" class="comment"/></td>
                                        
				</tr>';
            }
        } else {
            echo '<div class="list-empty-msg">
				<i class="icon-warning-sign list-empty-icon"></i>
				' . $this->l('No product found !') . '
			</div>';
        }
    }
 public static function getWholesalePrice($id_product, $id_product_attribute = 0, $id_supplier = 0)
 {
     // If there's a supplier
     if (!empty($id_supplier)) {
         // Getting supplier's price first
         $prices = ErpProductSupplier::getProductSupplierPrice($id_product, $id_product_attribute, $id_supplier, true);
         $price = $prices['product_supplier_price_te'];
     }
     // If no supplier's price, or supplier's price null, we look for the price of the product or variation
     if (empty($price) || $price == '0.000000') {
         // No variation, looking for product's price
         if ($id_product_attribute == 0) {
             $query = new DbQuery();
             $query->select('wholesale_price');
             $query->from('product');
             $query->where('id_product = ' . (int) $id_product);
             $price = Db::getInstance()->getValue($query);
         } else {
             $query = new DbQuery();
             $query->select('p.wholesale_price as wholesale_price_product, pa.wholesale_price as wholesale_price_product_attribute');
             $query->from('product_attribute', 'pa');
             $query->where('pa.id_product = ' . (int) $id_product);
             $query->where('pa.id_product_attribute = ' . (int) $id_product_attribute);
             $query->innerJoin('product', 'p', ' p.id_product = pa.id_product');
             $prices = Db::getInstance()->getRow($query);
             // if variation's price
             if (!empty($prices['wholesale_price_product_attribute']) && $prices['wholesale_price_product_attribute'] != '0.000000') {
                 $price = $prices['wholesale_price_product_attribute'];
             } elseif (!empty($prices['wholesale_price_product']) && $prices['wholesale_price_product'] != '0.000000') {
                 $price = $prices['wholesale_price_product'];
             } else {
                 $price = '0.00000';
             }
         }
     }
     return $price;
 }
Exemplo n.º 12
0
 public static function getWholesalePrice($id_product, $id_product_attribute = 0, $id_supplier = 0)
 {
     // If there is a supplier
     if (!empty($id_supplier)) {
         //On récupère tout d'abord le prix du fournisseur
         $prices = ErpProductSupplier::getProductSupplierPrice($id_product, $id_product_attribute, $id_supplier, true);
         if (isset($prices['product_supplier_price_te'])) {
             $price = $prices['product_supplier_price_te'];
         }
     }
     // If no price for this supplier, or supplier price null,
     // get the price of the product or variation
     if (empty($price) || $price == '0.000000') {
         // pas de décliaison, on cherche le prix du produit
         if ($id_product_attribute == 0) {
             $query = new DbQuery();
             $query->select('wholesale_price');
             $query->from('product');
             $query->where('id_product = ' . (int) $id_product);
             $price = Db::getInstance()->getValue($query);
         } else {
             $query = new DbQuery();
             $query->select('p.wholesale_price as wholesale_price_product, pa.wholesale_price as wholesale_price_product_attribute');
             $query->from('product_attribute', 'pa');
             $query->where('pa.id_product = ' . (int) $id_product);
             $query->where('pa.id_product_attribute = ' . (int) $id_product_attribute);
             $query->innerJoin('product', 'p', ' p.id_product = pa.id_product');
             $prices = Db::getInstance()->getRow($query);
             //If variation has a price
             if ($prices['wholesale_price_product_attribute'] == '0.000000') {
                 $price = $prices['wholesale_price_product'];
             } elseif ($prices['wholesale_price_product_attribute'] != '0.000000') {
                 $price = $prices['wholesale_price_product_attribute'];
             } else {
                 $price = '0.00000';
             }
         }
     }
     return $price;
 }
Exemplo n.º 13
0
 public static function getblogPages($id_lang = null, $id_leoblogcat = null, $active = true, $id_shop = null)
 {
     $sql = new DbQuery();
     $sql->select('*');
     $sql->from('blog', 'c');
     if ($id_lang) {
         $sql->innerJoin('blog_lang', 'l', 'c.id_leoblog_blog = l.id_leoblog_blog AND l.id_lang = ' . (int) $id_lang);
     }
     if ($id_shop) {
         $sql->innerJoin('blog_shop', 'cs', 'c.id_leoblog_blog = cs.id_leoblog_blog AND cs.id_shop = ' . (int) $id_shop);
     }
     if ($active) {
         $sql->where('c.active = 1');
     }
     if ($id_leoblogcat) {
         $sql->where('c.id_leoblogcat = ' . (int) $id_leoblogcat);
     }
     $sql->orderBy('position');
     return Db::getInstance()->executeS($sql);
 }
Exemplo n.º 14
0
    public static function getCustomersSmsRequest($campaign_id, $checked_langs, $checked_groups, $checked_campaign_active, $checked_products, $checked_categories, $limit = 0, &$list_total = null)
    {
        $sql_calc_found = is_null($list_total) ? '' : 'SQL_CALC_FOUND_ROWS ';
        $req = new DbQuery();
        $req->select($sql_calc_found . (int) $campaign_id . ' as campaign_id, address.phone_mobile as target,
				address.phone_mobile as col_0, customer.lastname as col_1, customer.firstname as col_2,address.postcode as col_3,
				address.city as col_4, \'prestashop\' as source');
        $req->from('customer', 'customer');
        $req->leftJoin('customer_group', 'customer_group', 'customer_group.id_customer = customer.id_customer');
        $req->leftJoin('guest', 'guest', 'guest.id_customer = customer.id_customer');
        $req->leftJoin('connections', 'connections', 'connections.id_guest = guest.id_guest');
        $req->innerJoin('address', 'address', 'address.id_customer = customer.id_customer AND address.phone_mobile <> \'\'');
        $req->leftJoin('country', 'country', 'address.id_country = country.id_country');
        $where = array();
        $where[] = 'address.phone_mobile IS NOT NULL AND address.phone_mobile <> \'\'';
        if (!empty($checked_langs)) {
            $where[] = 'customer.id_lang IN(' . implode(', ', array_map('intval', $checked_langs)) . ')';
        }
        if (!empty($checked_groups)) {
            $where[] = 'customer_group.id_group IN(' . implode(', ', array_map('intval', $checked_groups)) . ')';
        }
        if ($checked_campaign_active) {
            $where[] = 'customer.active = 1';
        }
        if (!empty($checked_products) || !empty($checked_categories)) {
            $where_products_categories = array();
            $req->leftJoin('cart', 'cart', 'cart.id_customer = customer.id_customer');
            $req->leftJoin('cart_product', 'cart_product', 'cart_product.id_cart = cart.id_cart');
            if (!empty($checked_products)) {
                $where_products_categories[] = 'cart_product.id_product IN(' . implode(', ', array_map('intval', $checked_products)) . ')';
            }
            if (!empty($checked_categories)) {
                $req->leftJoin('category_product', 'category_product', 'category_product.id_product = cart_product.id_product');
                $where_products_categories[] = 'category_product.id_category IN(' . implode(', ', array_map('intval', $checked_categories)) . ')';
            }
            $where[] = implode(' OR ', $where_products_categories);
        }
        $req->where(implode(' AND ', $where));
        $req->orderby('customer.id_customer');
        $req->groupby('customer.id_customer');
        $limit = (int) $limit;
        if ($limit) {
            $req->limit($limit);
        }
        return $req;
    }
Exemplo n.º 15
0
 /**
  * Get list of modules we can execute per hook
  *
  * @since 1.5.0
  * @param string $hook_name Get list of modules for this hook if given
  * @return array
  */
 public static function getHookModuleExecList($hook_name = null)
 {
     $context = Context::getContext();
     $cache_id = 'hook_module_exec_list_' . (isset($context->shop->id) ? '_' . $context->shop->id : '') . (isset($context->customer) ? '_' . $context->customer->id : '');
     if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment' || $hook_name == 'displayPaymentEU' || $hook_name == 'displayBackOfficeHeader') {
         $frontend = true;
         $groups = array();
         $use_groups = Group::isFeatureActive();
         if (isset($context->employee)) {
             $frontend = false;
         } else {
             // Get groups list
             if ($use_groups) {
                 if (isset($context->customer) && $context->customer->isLogged()) {
                     $groups = $context->customer->getGroups();
                 } elseif (isset($context->customer) && $context->customer->isLogged(true)) {
                     $groups = array((int) Configuration::get('PS_GUEST_GROUP'));
                 } else {
                     $groups = array((int) Configuration::get('PS_UNIDENTIFIED_GROUP'));
                 }
             }
         }
         // SQL Request
         $sql = new DbQuery();
         $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module, h.`live_edit`');
         $sql->from('module', 'm');
         if ($hook_name != 'displayBackOfficeHeader') {
             $sql->join(Shop::addSqlAssociation('module', 'm', true, 'module_shop.enable_device & ' . (int) Context::getContext()->getDevice()));
             $sql->innerJoin('module_shop', 'ms', 'ms.`id_module` = m.`id_module`');
         }
         $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');
         $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');
         if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU') {
             $sql->where('h.`name` != "displayPayment" AND h.`name` != "displayPaymentEU"');
         } elseif ($frontend) {
             if (Validate::isLoadedObject($context->country)) {
                 $sql->where('((h.`name` = "displayPayment" OR h.`name` = "displayPaymentEU") AND (SELECT `id_country` FROM `' . _DB_PREFIX_ . 'module_country` mc WHERE mc.`id_module` = m.`id_module` AND `id_country` = ' . (int) $context->country->id . ' AND `id_shop` = ' . (int) $context->shop->id . ' LIMIT 1) = ' . (int) $context->country->id . ')');
             }
             if (Validate::isLoadedObject($context->currency)) {
                 $sql->where('((h.`name` = "displayPayment" OR h.`name` = "displayPaymentEU") AND (SELECT `id_currency` FROM `' . _DB_PREFIX_ . 'module_currency` mcr WHERE mcr.`id_module` = m.`id_module` AND `id_currency` IN (' . (int) $context->currency->id . ', -1, -2) LIMIT 1) IN (' . (int) $context->currency->id . ', -1, -2))');
             }
         }
         if (Validate::isLoadedObject($context->shop)) {
             $sql->where('hm.`id_shop` = ' . (int) $context->shop->id);
         }
         if ($frontend) {
             if ($use_groups) {
                 $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');
                 if (Validate::isLoadedObject($context->shop)) {
                     $sql->where('mg.`id_shop` = ' . (int) $context->shop->id . (count($groups) ? ' AND  mg.`id_group` IN (' . implode(', ', $groups) . ')' : ''));
                 } elseif (count($groups)) {
                     $sql->where('mg.`id_group` IN (' . implode(', ', $groups) . ')');
                 }
             }
         }
         $sql->groupBy('hm.id_hook, hm.id_module');
         $sql->orderBy('hm.`position`');
         $list = array();
         if ($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)) {
             foreach ($result as $row) {
                 $row['hook'] = strtolower($row['hook']);
                 if (!isset($list[$row['hook']])) {
                     $list[$row['hook']] = array();
                 }
                 $list[$row['hook']][] = array('id_hook' => $row['id_hook'], 'module' => $row['module'], 'id_module' => $row['id_module'], 'live_edit' => $row['live_edit']);
             }
         }
         if ($hook_name != 'displayPayment' && $hook_name != 'displayPaymentEU' && $hook_name != 'displayBackOfficeHeader') {
             Cache::store($cache_id, $list);
             // @todo remove this in 1.6, we keep it in 1.5 for backward compatibility
             self::$_hook_modules_cache_exec = $list;
         }
     } else {
         $list = Cache::retrieve($cache_id);
     }
     // If hook_name is given, just get list of modules for this hook
     if ($hook_name) {
         $retro_hook_name = strtolower(Hook::getRetroHookName($hook_name));
         $hook_name = strtolower($hook_name);
         $return = array();
         $inserted_modules = array();
         if (isset($list[$hook_name])) {
             $return = $list[$hook_name];
         }
         foreach ($return as $module) {
             $inserted_modules[] = $module['id_module'];
         }
         if (isset($list[$retro_hook_name])) {
             foreach ($list[$retro_hook_name] as $retro_module_call) {
                 if (!in_array($retro_module_call['id_module'], $inserted_modules)) {
                     $return[] = $retro_module_call;
                 }
             }
         }
         return count($return) > 0 ? $return : false;
     } else {
         return $list;
     }
 }
Exemplo n.º 16
0
                    $id_supplier = Tools::getValue('id_supplier');
                    $id_currency = Tools::isSubmit('id_currency') ? Tools::getValue('id_currency') : Context::getContext()->id_currency;
                    /*  get lang from context */
                    $id_lang = (int) Context::getContext()->language->id;
                    $query = new DbQuery();
                    $query->select('
						CONCAT(p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\')) as id,
						ps.product_supplier_reference as supplier_reference,
						IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
						IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
						IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc,
						md5(CONCAT(\'' . _COOKIE_KEY_ . '\', p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\'))) as checksum,
						IFNULL(CONCAT(pl.name, \' : \', GROUP_CONCAT(DISTINCT agl.name, \' - \', al.name SEPARATOR \', \')), pl.name) as name
					');
                    $query->from('product', 'p');
                    $query->innerJoin('product_lang', 'pl', 'pl.id_product = p.id_product AND pl.id_lang = ' . (int) $id_lang);
                    $query->leftJoin('product_attribute', 'pa', 'pa.id_product = p.id_product');
                    $query->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pa.id_product_attribute');
                    $query->leftJoin('attribute', 'atr', 'atr.id_attribute = pac.id_attribute');
                    $query->leftJoin('attribute_lang', 'al', 'al.id_attribute = atr.id_attribute AND al.id_lang = ' . (int) $id_lang);
                    $query->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = atr.id_attribute_group AND agl.id_lang = ' . (int) $id_lang);
                    $query->leftJoin('product_supplier', 'ps', 'ps.id_product = p.id_product AND ps.id_product_attribute = IFNULL(pa.id_product_attribute, 0)');
                    $query->where('p.id_product NOT IN (SELECT pd.id_product FROM `' . _DB_PREFIX_ . 'product_download` pd WHERE (pd.id_product = p.id_product))');
                    $query->where('p.is_virtual = 0 AND p.cache_is_pack = 0');
                    $query->where('p.id_product = ' . (int) $id_product . '');
                    $query->groupBy('p.id_product, pa.id_product_attribute');
                    $item = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query);
                    $ids = explode('_', $item['id']);
                    if ($item) {
                        die(Tools::jsonEncode($item));
                    }
Exemplo n.º 17
0
    /**
     * Loads products which quantity (hysical quantity) is equal or less than $threshold
     * @param int $threshold
     */
    protected function loadProducts($threshold)
    {
        // if there is already an order
        if (Tools::getValue('id_supply_order')) {
            $supply_order = new SupplyOrder((int) Tools::getValue('id_supply_order'));
        } else {
            // else, we just created a new order
            $supply_order = $this->object;
        }
        // if order is not valid, return;
        if (!Validate::isLoadedObject($supply_order)) {
            return;
        }
        // resets products if needed
        if (Tools::getValue('id_supply_order')) {
            $supply_order->resetProducts();
        }
        // gets products
        $query = new DbQuery();
        $query->select('
			ps.id_product,
			ps.id_product_attribute,
			ps.product_supplier_reference as supplier_reference,
			ps.product_supplier_price_te as unit_price_te,
			ps.id_currency,
			IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
			IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
			IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc');
        $query->from('product_supplier', 'ps');
        $query->leftJoin('stock', 's', '
			s.id_product = ps.id_product
			AND s.id_product_attribute = ps.id_product_attribute
			AND s.id_warehouse = ' . (int) $supply_order->id_warehouse);
        $query->innerJoin('warehouse_product_location', 'wpl', '
			wpl.id_product = ps.id_product
			AND wpl.id_product_attribute = ps.id_product_attribute
			AND wpl.id_warehouse = ' . (int) $supply_order->id_warehouse . '
		');
        $query->leftJoin('product', 'p', 'p.id_product = ps.id_product');
        $query->leftJoin('product_attribute', 'pa', '
			pa.id_product_attribute = ps.id_product_attribute
			AND p.id_product = ps.id_product
		');
        $query->where('ps.id_supplier = ' . (int) $supply_order->id_supplier);
        // gets items
        $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
        // loads order currency
        $order_currency = new Currency($supply_order->id_currency);
        if (!Validate::isLoadedObject($order_currency)) {
            return;
        }
        $manager = StockManagerFactory::getManager();
        foreach ($items as $item) {
            $diff = (int) $threshold;
            if ($supply_order->is_template != 1) {
                $real_quantity = (int) $manager->getProductRealQuantities($item['id_product'], $item['id_product_attribute'], $supply_order->id_warehouse, true);
                $diff = (int) $threshold - (int) $real_quantity;
            }
            if ($diff >= 0) {
                // sets supply_order_detail
                $supply_order_detail = new SupplyOrderDetail();
                $supply_order_detail->id_supply_order = $supply_order->id;
                $supply_order_detail->id_currency = $order_currency->id;
                $supply_order_detail->id_product = $item['id_product'];
                $supply_order_detail->id_product_attribute = $item['id_product_attribute'];
                $supply_order_detail->reference = $item['reference'];
                $supply_order_detail->supplier_reference = $item['supplier_reference'];
                $supply_order_detail->name = Product::getProductName($item['id_product'], $item['id_product_attribute'], $supply_order->id_lang);
                $supply_order_detail->ean13 = $item['ean13'];
                $supply_order_detail->upc = $item['upc'];
                $supply_order_detail->quantity_expected = (int) $diff == 0 ? 1 : (int) $diff;
                $supply_order_detail->exchange_rate = $order_currency->conversion_rate;
                $product_currency = new Currency($item['id_currency']);
                if (Validate::isLoadedObject($product_currency)) {
                    $supply_order_detail->unit_price_te = Tools::convertPriceFull($item['unit_price_te'], $product_currency, $order_currency);
                } else {
                    $supply_order_detail->unit_price_te = 0;
                }
                $supply_order_detail->save();
                unset($product_currency);
            }
        }
        // updates supply order
        $supply_order->update();
    }
Exemplo n.º 18
0
	/**
	* Price calculation / Get product price
	*
	* @param integer $id_shop Shop id
	* @param integer $id_product Product id
	* @param integer $id_product_attribute Product attribute id
	* @param integer $id_country Country id
	* @param integer $id_state State id
	* @param integer $id_currency Currency id
	* @param integer $id_group Group id
	* @param integer $quantity Quantity Required for Specific prices : quantity discount application
	* @param boolean $use_tax with (1) or without (0) tax
	* @param integer $decimals Number of decimals returned
	* @param boolean $only_reduc Returns only the reduction amount
	* @param boolean $use_reduc Set if the returned amount will include reduction
	* @param boolean $with_ecotax insert ecotax in price output.
	* @param variable_reference $specific_price_output
	* 	If a specific price applies regarding the previous parameters, this variable is filled with the corresponding SpecificPrice object
	* @return float Product price
	**/
	public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency,
		$id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction,
		$id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0)
	{
		static $address = null;
		static $context = null;

		if ($address === null)
			$address = new Address();
		
		if ($context == null)
			$context = Context::getContext()->cloneContext();

		if ($id_shop !== null && $context->shop->id != (int)$id_shop)
			$context->shop = new Shop((int)$id_shop);
		
		if (!$use_customer_price)
			$id_customer = 0;

		if ($id_product_attribute === null)
			$id_product_attribute = Product::getDefaultAttribute($id_product);

		$cache_id = $id_product.'-'.$id_shop.'-'.$id_currency.'-'.$id_country.'-'.$id_state.'-'.$zipcode.'-'.$id_group.
			'-'.$quantity.'-'.$id_product_attribute.'-'.($use_tax?'1':'0').'-'.$decimals.'-'.($only_reduc?'1':'0').
			'-'.($use_reduc?'1':'0').'-'.$with_ecotax.'-'.$id_customer.'-'.(int)$use_group_reduction.'-'.(int)$id_cart.'-'.(int)$real_quantity;

		// reference parameter is filled before any returns
		$specific_price = SpecificPrice::getSpecificPrice(
			(int)$id_product,
			$id_shop,
			$id_currency,
			$id_country,
			$id_group,
			$quantity,
			$id_product_attribute,
			$id_customer,
			$id_cart,
			$real_quantity
		);
                
		if (isset(self::$_prices[$cache_id]))
			return self::$_prices[$cache_id];

		// fetch price & attribute price
		$cache_id_2 = $id_product.'-'.$id_shop;
		if (!isset(self::$_pricesLevel2[$cache_id_2]))
		{
			$sql = new DbQuery();
			$sql->select('product_shop.`price`, product_shop.`ecotax`');
			$sql->from('product', 'p');
			$sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = '.(int)$id_shop.')');
			$sql->where('p.`id_product` = '.(int)$id_product);
			if (Combination::isFeatureActive())
			{
				$sql->select('product_attribute_shop.id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on');
				$sql->leftJoin('product_attribute', 'pa', 'pa.`id_product` = p.`id_product`');
				$sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product_attribute = pa.id_product_attribute AND product_attribute_shop.id_shop = '.(int)$id_shop.')');
			}
			else
				$sql->select('0 as id_product_attribute');

			$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

			foreach ($res as $row)
			{
				$array_tmp = array(
					'price' => $row['price'], 
					'ecotax' => $row['ecotax'],
					'attribute_price' => (isset($row['attribute_price']) ? $row['attribute_price'] : null)
				);
				self::$_pricesLevel2[$cache_id_2][(int)$row['id_product_attribute']] = $array_tmp;
				
				if (isset($row['default_on']) && $row['default_on'] == 1)
					self::$_pricesLevel2[$cache_id_2][0] = $array_tmp;
			}
		}
		if (!isset(self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute]))
			return;

		$result = self::$_pricesLevel2[$cache_id_2][(int)$id_product_attribute];

		if (!$specific_price || $specific_price['price'] < 0)
			$price = (float)$result['price'];
		else
			$price = (float)$specific_price['price'];
		// convert only if the specific price is in the default currency (id_currency = 0)
		if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency']))
			$price = Tools::convertPrice($price, $id_currency);

		// Attribute price
		if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0))
		{
			$attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (float)$result['attribute_price'] : 0, $id_currency);
			// If you want the default combination, please use NULL value instead
			if ($id_product_attribute !== false)
				$price += $attribute_price;
		}

		// Tax
		$address->id_country = $id_country;
		$address->id_state = $id_state;
		$address->postcode = $zipcode;

		$tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int)$id_product, $context));
		$product_tax_calculator = $tax_manager->getTaxCalculator();

		// Add Tax
		if ($use_tax)
			$price = $product_tax_calculator->addTaxes($price);

		// Reduction
		$specific_price_reduction = 0;
		if (($only_reduc || $use_reduc) && $specific_price)
		{
			if ($specific_price['reduction_type'] == 'amount')
			{
				$reduction_amount = $specific_price['reduction'];

				if (!$specific_price['id_currency'])
					$reduction_amount = Tools::convertPrice($reduction_amount, $id_currency);
				$specific_price_reduction = !$use_tax ? $product_tax_calculator->removeTaxes($reduction_amount) : $reduction_amount;
			}
			else
				$specific_price_reduction = $price * $specific_price['reduction'];
		}

		if ($use_reduc)
			$price -= $specific_price_reduction;

		// Group reduction
		if ($use_group_reduction)
		{
			$reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group);
                        if($context->customer->id){
                            $id_group = array();
                            $customer_groups = Db::getInstance()->executeS("SELECT id_group FROM ps_customer_group WHERE id_customer={$context->customer->id}"); 
                            foreach ($customer_groups as $row_group)
                                $id_group[] = $row_group['id_group'];
                            
                        }else
                            $id_group = array($id_group);
			if ($reduction_from_category !== false)
				$group_reduction = $price * (float)$reduction_from_category;
			else // apply group reduction if there is no group reduction for this category
				$group_reduction = (($reduc = Group::getReductionByIdGroup($id_group)) != 0) ? ($price * $reduc / 100) : 0;
		}
		else
			$group_reduction = 0;
		if ($only_reduc)
			return Tools::ps_round($group_reduction + $specific_price_reduction, $decimals);

		if ($use_reduc)
			$price -= $group_reduction;

		// Eco Tax
		if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax)
		{
			$ecotax = $result['ecotax'];
			if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0)
				$ecotax = $result['attribute_ecotax'];

			if ($id_currency)
				$ecotax = Tools::convertPrice($ecotax, $id_currency);
			if ($use_tax)
			{
				// reinit the tax manager for ecotax handling
				$tax_manager = TaxManagerFactory::getManager(
					$address,
					(int)Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID')
				);
				$ecotax_tax_calculator = $tax_manager->getTaxCalculator();
				$price += $ecotax_tax_calculator->addTaxes($ecotax);
			}
			else
				$price += $ecotax;
		}
		$price = Tools::ps_round($price, $decimals);
		if ($price < 0)
			$price = 0;

		self::$_prices[$cache_id] = $price;
		return self::$_prices[$cache_id];
	}
Exemplo n.º 19
0
 /**
  * For a given product, gets the last positive stock mvt
  *
  * @since 1.5.0
  * @param int $id_product
  * @param int $id_product_attribute Use 0 if the product does not have attributes
  * @return bool|array
  */
 public static function getLastPositiveStockMvt($id_product, $id_product_attribute)
 {
     $query = new DbQuery();
     $query->select('sm.*, w.id_currency, (s.usable_quantity = sm.physical_quantity) as is_usable');
     $query->from('stock_mvt', 'sm');
     $query->innerJoin('stock', 's', 's.id_stock = sm.id_stock');
     $query->innerJoin('warehouse', 'w', 'w.id_warehouse = s.id_warehouse');
     $query->where('sm.sign = 1');
     if ($id_product_attribute) {
         $query->where('s.id_product = ' . (int) $id_product . ' AND s.id_product_attribute = ' . (int) $id_product_attribute);
     } else {
         $query->where('s.id_product = ' . (int) $id_product);
     }
     $query->orderBy('date_add DESC');
     $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
     if ($res != false) {
         return $res['0'];
     }
     return false;
 }
Exemplo n.º 20
0
 public static function getPosts($id_lang, $limit = 10, $id_simpleblog_category = null, $page = null, $active = true, $orderby = false, $orderway = false, $exclude = null, $featured = false, $author = false, $id_shop = null, $filter = false, $selected = array())
 {
     $context = Context::getContext();
     $start = $limit * ($page == 0 ? 0 : $page - 1);
     $sql = new DbQuery();
     $sql->select('*');
     $sql->from('simpleblog_post', 'sbp');
     if ($id_lang) {
         $sql->innerJoin('simpleblog_post_lang', 'l', 'sbp.id_simpleblog_post = l.id_simpleblog_post AND l.id_lang = ' . (int) $id_lang);
     }
     if (!$id_shop) {
         $id_shop = $context->shop->id;
     }
     $sql->innerJoin('simpleblog_post_shop', 'sbps', 'sbp.id_simpleblog_post = sbps.id_simpleblog_post AND sbps.id_shop = ' . (int) $id_shop);
     if ($active) {
         $sql->where('sbp.active = 1');
     }
     if (isset($id_simpleblog_category) && (int) $id_simpleblog_category > 0) {
         $sql->where('sbp.id_simpleblog_category = ' . (int) $id_simpleblog_category);
     }
     if ($exclude) {
         $sql->where('sbp.id_simpleblog_post != ' . (int) $exclude);
     }
     if ($featured) {
         $sql->where('sbp.is_featured = 1');
     }
     if ($author && Configuration::get('PH_BLOG_POST_BY_AUTHOR')) {
         $sql->where('sbp.author = \'' . pSQL($author) . '\'');
     }
     if ($filter) {
         $sql->where('sbp.id_simpleblog_post ' . $filter . ' (' . join(',', $selected) . ')');
     }
     if (isset($context->customer) && !$context->customer->isLogged()) {
         $sql->where('sbp.logged = 0');
     }
     if (!$orderby) {
         $orderby = 'sbp.id_simpleblog_post';
     }
     if (!$orderway) {
         $orderway = 'DESC';
     }
     $sql->orderBy($orderby . ' ' . $orderway);
     $sql->limit($limit, $start);
     $result = Db::getInstance()->executeS($sql);
     if (sizeof($result)) {
         foreach ($result as &$row) {
             $category_rewrite = SimpleBlogCategory::getRewriteByCategory($row['id_simpleblog_category'], $id_lang);
             $category_obj = new SimpleBlogCategory($row['id_simpleblog_category'], $id_lang);
             $category_url = SimpleBlogCategory::getLink($category_obj->link_rewrite, $id_lang);
             if (file_exists(_PS_MODULE_DIR_ . 'ph_simpleblog/covers/' . $row['id_simpleblog_post'] . '.' . $row['cover'])) {
                 $row['banner'] = _MODULE_DIR_ . 'ph_simpleblog/covers/' . $row['id_simpleblog_post'] . '.' . $row['cover'];
                 $row['banner_thumb'] = _MODULE_DIR_ . 'ph_simpleblog/covers/' . $row['id_simpleblog_post'] . '-thumb.' . $row['cover'];
                 $row['banner_wide'] = _MODULE_DIR_ . 'ph_simpleblog/covers/' . $row['id_simpleblog_post'] . '-wide.' . $row['cover'];
             }
             if (file_exists(_PS_MODULE_DIR_ . 'ph_simpleblog/featured/' . $row['id_simpleblog_post'] . '.' . $row['featured'])) {
                 $row['featured'] = _MODULE_DIR_ . 'ph_simpleblog/featured/' . $row['id_simpleblog_post'] . '.' . $row['featured'];
             }
             $row['url'] = self::getLink($row['link_rewrite'], $category_obj->link_rewrite, $id_lang);
             $row['category'] = $category_obj->name;
             $row['category_url'] = $category_url;
             $tags = SimpleBlogTag::getPostTags($row['id_simpleblog_post']);
             $row['tags'] = isset($tags[$id_lang]) && sizeof($tags[$id_lang] > 0) ? $tags[$id_lang] : false;
         }
     } else {
         return;
     }
     return $result;
 }
Exemplo n.º 21
0
 /**
  * Return total to paid of sibling invoices
  *
  * @param int $mod TAX_EXCL, TAX_INCL, DETAIL
  *
  * @since 1.5.0.14
  */
 public function getSiblingTotal($mod = OrderInvoice::TAX_INCL)
 {
     $query = new DbQuery();
     $query->select('SUM(oi.total_paid_tax_incl) as total_paid_tax_incl, SUM(oi.total_paid_tax_excl) as total_paid_tax_excl');
     $query->from('order_invoice_payment', 'oip1');
     $query->innerJoin('order_invoice_payment', 'oip2', 'oip2.id_order_payment = oip1.id_order_payment AND oip2.id_order_invoice <> oip1.id_order_invoice');
     $query->leftJoin('order_invoice', 'oi', 'oi.id_order_invoice = oip2.id_order_invoice');
     $query->where('oip1.id_order_invoice = ' . $this->id);
     $row = Db::getInstance()->getRow($query);
     switch ($mod) {
         case OrderInvoice::TAX_EXCL:
             return $row['total_paid_tax_excl'];
         case OrderInvoice::TAX_INCL:
             return $row['total_paid_tax_incl'];
         default:
             return $row;
     }
 }
Exemplo n.º 22
0
 public static function priceCalculation($id_shop, $id_product, $id_product_attribute, $id_country, $id_state, $zipcode, $id_currency, $id_group, $quantity, $use_tax, $decimals, $only_reduc, $use_reduc, $with_ecotax, &$specific_price, $use_group_reduction, $id_customer = 0, $use_customer_price = true, $id_cart = 0, $real_quantity = 0, $service_date = null, $service_time_from = null, $service_time_to = null)
 {
     require_once dirname(__FILE__) . '/../../modules/aphrodinet/classes/AphCustomPrice.php';
     static $address = null;
     static $context = null;
     if ($address === null) {
         $address = new Address();
     }
     if ($context == null) {
         $context = Context::getContext()->cloneContext();
     }
     if ($id_shop !== null && $context->shop->id != (int) $id_shop) {
         $context->shop = new Shop((int) $id_shop);
     }
     if (!$use_customer_price) {
         $id_customer = 0;
     }
     if ($id_product_attribute === null) {
         $id_product_attribute = Product::getDefaultAttribute($id_product);
     }
     if (!empty($id_cart)) {
         $res = Db::getInstance()->executeS('SELECT `delivery_date`, `delivery_time_from`, `delivery_time_to` ' . 'FROM ' . _DB_PREFIX_ . 'cart_product ' . 'WHERE `id_cart` = ' . (int) $id_cart . ' AND `id_product` = ' . (int) $id_product . ' AND `id_product_attribute` = ' . (int) $id_product_attribute . ' ' . 'LIMIT 1');
         if (!empty($res) && empty($service_date)) {
             $res = $res[0];
             if (!empty($res)) {
                 $service_date = $res['delivery_date'];
                 $service_time_from = $res['delivery_time_from'];
                 $service_time_to = $res['delivery_time_to'];
             }
         }
     }
     if (!empty($service_time_from) && strlen($service_time_from) == 5) {
         $service_time_from .= ':00';
     }
     if (!empty($service_time_to) && strlen($service_time_to) == 5) {
         $service_time_to .= ':00';
     }
     $cache_id = (int) $id_product . '-' . (int) $id_shop . '-' . (int) $id_currency . '-' . (int) $id_country . '-' . $id_state . '-' . $zipcode . '-' . (int) $id_group . '-' . (int) $quantity . '-' . (int) $id_product_attribute . '-' . (int) $with_ecotax . '-' . (int) $id_customer . '-' . (int) $use_group_reduction . '-' . (int) $id_cart . '-' . (int) $real_quantity . '-' . ($only_reduc ? '1' : '0') . '-' . ($use_reduc ? '1' : '0') . '-' . ($use_tax ? '1' : '0') . '-' . (int) $decimals . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : '');
     // reference parameter is filled before any returns
     $specific_price = SpecificPrice::getSpecificPrice((int) $id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity, $id_product_attribute, $id_customer, $id_cart, $real_quantity);
     if (isset(self::$_prices[$cache_id])) {
         if (isset($specific_price['price']) && $specific_price['price'] > 0) {
             $specific_price['price'] = self::$_prices[$cache_id];
         }
         return self::$_prices[$cache_id];
     }
     $cache_id_2 = $id_product . '-' . $id_shop . (!empty($service_date) && $service_date != '0000-00-00' ? '-' . $service_date : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_from : '') . (!empty($service_time_to) && $service_time_to != '00:00:00' ? '-' . $service_time_to : '');
     if (!isset(self::$_pricesLevel2[$cache_id_2])) {
         $base_price_wt = 0;
         $service_date_ts = strtotime($service_date);
         $service_date_week_day = date('w', $service_date_ts);
         if (!empty($service_date) && $service_date != '0000-00-00') {
             // cerco il prezzo del giorno
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, NULL, 1);
             if (!empty($custom_prices)) {
                 $base_price_wt = $custom_prices[0]['price_wt'];
             }
         }
         if (!empty($service_date) && $service_date != '0000-00-00') {
             $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, 0, 1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00') {
             $offer_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, 0, 1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate($id_shop, $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, -1, $service_time_from);
         }
         if (!empty($service_date) && $service_date != '0000-00-00' && !empty($service_time_to) && $service_time_to != '00:00:00' && empty($custom_prices) && empty($offer_prices)) {
             $custom_prices = AphCustomPrice::getByDate(Configuration::get('PS_SHOP_DEFAULT'), $id_currency, $id_country, $id_group, $service_date, $id_customer, (int) $id_product, $service_date_week_day, $service_time_from);
         }
         if (!empty($offer_prices)) {
             $res = $offer_prices;
         } elseif (!empty($custom_prices)) {
             $res = $custom_prices;
         } else {
             $sql = new DbQuery();
             $sql->select('product_shop.`price`, product_shop.`ecotax`');
             $sql->from('product', 'p');
             $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_product=p.id_product AND product_shop.id_shop = ' . (int) $id_shop . ')');
             $sql->where('p.`id_product` = ' . (int) $id_product);
             if (Combination::isFeatureActive()) {
                 $sql->select('IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute, product_attribute_shop.`price` AS attribute_price, product_attribute_shop.default_on');
                 $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_product = p.id_product AND product_attribute_shop.id_shop = ' . (int) $id_shop . ')');
             } else {
                 $sql->select('0 as id_product_attribute');
             }
             $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
         }
         if (is_array($res) && count($res)) {
             foreach ($res as $row) {
                 if ($row['price'] < 0) {
                     if ($row['reduction_type'] == 'amount') {
                         $row['price'] = 0;
                         //$base_price_wt - $row['reduction'];
                     } else {
                         $row['price'] = 0;
                         //$base_price_wt - (($row['reduction'] * $base_price_wt) / 100);
                     }
                 } else {
                     $row['price'] = 0;
                     //$row['price_wt'];
                 }
                 $array_tmp = array('price' => $row['price'], 'ecotax' => !empty($row['ecotax']), 'attribute_price' => isset($row['attribute_price']) ? $row['attribute_price'] : null);
                 self::$_pricesLevel2[$cache_id_2][(int) $row['id_product_attribute']] = $array_tmp;
                 if (isset($row['default_on']) && $row['default_on'] == 1) {
                     self::$_pricesLevel2[$cache_id_2][0] = $array_tmp;
                 }
             }
         }
     }
     if (!isset(self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute])) {
         return;
     }
     $result = self::$_pricesLevel2[$cache_id_2][(int) $id_product_attribute];
     if (!$specific_price || $specific_price['price'] < 0) {
         $price = (double) $result['price'];
     } else {
         $price = (double) $specific_price['price'];
     }
     if (!$specific_price || !($specific_price['price'] >= 0 && $specific_price['id_currency'])) {
         $price = Tools::convertPrice($price, $id_currency);
         if (isset($specific_price['price'])) {
             $specific_price['price'] = $price;
         }
     }
     if (is_array($result) && (!$specific_price || !$specific_price['id_product_attribute'] || $specific_price['price'] < 0)) {
         $attribute_price = Tools::convertPrice($result['attribute_price'] !== null ? (double) $result['attribute_price'] : 0, $id_currency);
         if ($id_product_attribute !== false) {
             $price += $attribute_price;
         }
     }
     $address->id_country = $id_country;
     $address->id_state = $id_state;
     $address->postcode = $zipcode;
     $tax_manager = TaxManagerFactory::getManager($address, Product::getIdTaxRulesGroupByIdProduct((int) $id_product, $context));
     $product_tax_calculator = $tax_manager->getTaxCalculator();
     if ($use_tax) {
         $price = $product_tax_calculator->addTaxes($price);
     }
     if (($result['ecotax'] || isset($result['attribute_ecotax'])) && $with_ecotax) {
         $ecotax = $result['ecotax'];
         if (isset($result['attribute_ecotax']) && $result['attribute_ecotax'] > 0) {
             $ecotax = $result['attribute_ecotax'];
         }
         if ($id_currency) {
             $ecotax = Tools::convertPrice($ecotax, $id_currency);
         }
         if ($use_tax) {
             $tax_manager = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'));
             $ecotax_tax_calculator = $tax_manager->getTaxCalculator();
             $price += $ecotax_tax_calculator->addTaxes($ecotax);
         } else {
             $price += $ecotax;
         }
     }
     $specific_price_reduction = 0;
     if (($only_reduc || $use_reduc) && $specific_price) {
         if ($specific_price['reduction_type'] == 'amount') {
             $reduction_amount = $specific_price['reduction'];
             if (!$specific_price['id_currency']) {
                 $reduction_amount = Tools::convertPrice($reduction_amount, $id_currency);
             }
             $specific_price_reduction = $reduction_amount;
             if (!$use_tax && $specific_price['reduction_tax']) {
                 $specific_price_reduction = $product_tax_calculator->removeTaxes($specific_price_reduction);
             }
             if ($use_tax && !$specific_price['reduction_tax']) {
                 $specific_price_reduction = $product_tax_calculator->addTaxes($specific_price_reduction);
             }
         } else {
             $specific_price_reduction = $price * $specific_price['reduction'];
         }
     }
     if ($use_reduc) {
         $price -= $specific_price_reduction;
     }
     if ($use_group_reduction) {
         $reduction_from_category = GroupReduction::getValueForProduct($id_product, $id_group);
         if ($reduction_from_category !== false) {
             $group_reduction = $price * (double) $reduction_from_category;
         } else {
             // apply group reduction if there is no group reduction for this category
             $group_reduction = ($reduc = Group::getReductionByIdGroup($id_group)) != 0 ? $price * $reduc / 100 : 0;
         }
         $price -= $group_reduction;
     }
     if ($only_reduc) {
         return Tools::ps_round($specific_price_reduction, $decimals);
     }
     $price = Tools::ps_round($price, $decimals);
     if ($price < 0) {
         $price = 0;
     }
     self::$_prices[$cache_id] = $price;
     return self::$_prices[$cache_id];
 }
Exemplo n.º 23
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        /* 
         * EU-Legal
         * 1) correct calculation of prices -> Problem with inaccuracy at high number of items 
         * 2) assign standard delivery times to products
         */
        if (!$this->id) {
            return array();
        }
        // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
        if ($this->_products !== null && !$refresh) {
            // Return product row with specified ID if it exists
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        // Build query
        $sql = new DbQuery();
        // Build SELECT
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`delivery_now`, pl.`delivery_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`, 
						stock.`quantity` AS quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						CONCAT(LPAD(cp.`id_product`, 10, 0), LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
						product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
        // Build FROM
        $sql->from('cart_product', 'cp');
        // Build JOIN
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        $sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`');
        // AND 'sp.`id_shop` = cp.`id_shop`
        // @todo test if everything is ok, then refactorise call of this method
        $sql->join(Product::sqlStock('cp', 'cp'));
        // Build WHERE clauses
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        // Build GROUP BY
        $sql->groupBy('unique_id');
        // Build ORDER BY
        $sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
            $sql->leftJoin('customization', 'cu', 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = ' . (int) $this->id);
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity,
				IF(product_attribute_shop.wholesale_price > 0,  product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price');
        }
        $result = Db::getInstance()->executeS($sql);
        // Reset the cache before the following return, or else an empty cart will add dozens of queries
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (int) $row['quantity'];
            // for compatibility with 1.2 themes
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            $address = Address::initialize($address_id, true);
            $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context);
            $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $row['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, false, true, $cart_shop_context);
            switch (Configuration::get('PS_ROUND_TYPE')) {
                case Order::ROUND_TOTAL:
                    $row['total'] = $row['price'] * (int) $row['cart_quantity'];
                    $row['total_wt'] = $tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'];
                    break;
                case Order::ROUND_LINE:
                    $row['total'] = Tools::ps_round($row['price'] * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']) * (int) $row['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_);
                    break;
                case Order::ROUND_ITEM:
                default:
                    $row['total'] = Tools::ps_round($row['price'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    $row['total_wt'] = Tools::ps_round($tax_calculator->addTaxes($row['price']), _PS_PRICE_COMPUTE_PRECISION_) * (int) $row['cart_quantity'];
                    break;
            }
            $row['price_wt'] = $tax_calculator->addTaxes($row['price']);
            $row['description_short'] = Tools::nl2br($row['description_short']);
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && $row['cart_quantity'] >= (int) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            /* 
             * EU-Legal
             * assign standard delivery times to products
             */
            $row['delivery_now'] = !empty($row['delivery_now']) ? $row['delivery_now'] : Configuration::get('LEGAL_DELIVERY_NOW', $this->id_lang);
            $row['delivery_later'] = !empty($row['delivery_later']) ? $row['delivery_later'] : Configuration::get('LEGAL_DELIVERY_LATER', $this->id_lang);
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            $this->_products[] = $row;
        }
        return $this->_products;
    }
Exemplo n.º 24
0
 /**
  * Get list of modules we can execute per hook
  *
  * @since 1.5.0
  * @param string $hook_name Get list of modules for this hook if given
  * @return array
  */
 public static function getHookModuleExecList($hook_name = null)
 {
     $context = Context::getContext();
     $cache_id = 'hook_module_exec_list' . (isset($context->customer) ? '_' . $context->customer->id : '');
     if (!Cache::isStored($cache_id) || $hook_name == 'displayPayment') {
         $frontend = true;
         $groups = array();
         if (isset($context->employee)) {
             $shop_list = array((int) $context->shop->id);
             $frontend = false;
         } else {
             // Get shops and groups list
             $shop_list = Shop::getContextListShopID();
             if (isset($context->customer) && $context->customer->isLogged()) {
                 $groups = $context->customer->getGroups();
             } elseif (isset($context->customer) && $context->customer->isLogged(true)) {
                 $groups = array((int) Configuration::get('PS_GUEST_GROUP'));
             } else {
                 $groups = array((int) Configuration::get('PS_UNIDENTIFIED_GROUP'));
             }
         }
         // SQL Request
         $sql = new DbQuery();
         $sql->select('h.`name` as hook, m.`id_module`, h.`id_hook`, m.`name` as module, h.`live_edit`');
         $sql->from('module', 'm');
         $sql->innerJoin('hook_module', 'hm', 'hm.`id_module` = m.`id_module`');
         $sql->innerJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`');
         $sql->where('(SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'module_shop ms WHERE ms.id_module = m.id_module AND ms.id_shop IN (' . implode(', ', $shop_list) . ')) = ' . count($shop_list));
         if ($hook_name != 'displayPayment') {
             $sql->where('h.name != "displayPayment"');
         } elseif ($frontend) {
             if (Validate::isLoadedObject($context->country)) {
                 $sql->where('(h.name = "displayPayment" AND (SELECT id_country FROM ' . _DB_PREFIX_ . 'module_country mc WHERE mc.id_module = m.id_module AND id_country = ' . (int) $context->country->id . ' LIMIT 1) = ' . (int) $context->country->id . ')');
             }
             if (Validate::isLoadedObject($context->currency)) {
                 $sql->where('(h.name = "displayPayment" AND (SELECT id_currency FROM ' . _DB_PREFIX_ . 'module_currency mcr WHERE mcr.id_module = m.id_module AND id_currency IN (' . (int) $context->currency->id . ', -2) LIMIT 1) IN (' . (int) $context->currency->id . ', -2))');
             }
         }
         if (Validate::isLoadedObject($context->shop)) {
             $sql->where('hm.id_shop = ' . (int) $context->shop->id);
         }
         if ($frontend) {
             $sql->leftJoin('module_group', 'mg', 'mg.`id_module` = m.`id_module`');
             $sql->where('mg.`id_group` IN (' . implode(', ', $groups) . ')');
             $sql->groupBy('hm.id_hook, hm.id_module');
         }
         $sql->orderBy('hm.`position`');
         // Store results per hook name
         $results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
         $list = array();
         // Get all available payment module
         $payment_modules = array();
         if (isset($context->shop->id)) {
             foreach (Module::getPaymentModules() as $module) {
                 $payment_modules[] = $module['name'];
             }
         }
         if ($results) {
             foreach ($results as $row) {
                 if ($row['hook'] == 'displayPayment' && !in_array($row['module'], $payment_modules)) {
                     continue;
                 }
                 $row['hook'] = strtolower($row['hook']);
                 if (!isset($list[$row['hook']])) {
                     $list[$row['hook']] = array();
                 }
                 $list[$row['hook']][] = array('id_hook' => $row['id_hook'], 'module' => $row['module'], 'id_module' => $row['id_module'], 'live_edit' => $row['live_edit']);
             }
         }
         if ($hook_name != 'displayPayment') {
             Cache::store($cache_id, $list);
             // @todo remove this in 1.6, we keep it in 1.5 for retrocompatibility
             self::$_hook_modules_cache_exec = $list;
         }
     } else {
         $list = Cache::retrieve($cache_id);
     }
     // If hook_name is given, just get list of modules for this hook
     if ($hook_name) {
         $retro_hook_name = Hook::getRetroHookName($hook_name);
         $hook_name = strtolower($hook_name);
         $return = array();
         if (isset($list[$hook_name])) {
             $return = $list[$hook_name];
         }
         if (isset($list[$retro_hook_name])) {
             $return = array_merge($return, $list[$retro_hook_name]);
         }
         if (count($return) > 0) {
             return $return;
         }
         return false;
     } else {
         return $list;
     }
 }
Exemplo n.º 25
0
 public static function getCMSPages($id_lang = null, $id_cms_category = null, $active = true)
 {
     $sql = new DbQuery();
     $sql->select('*');
     $sql->from('cms', 'c');
     if ($id_lang) {
         $sql->innerJoin('cms_lang', 'l', 'c.id_cms = l.id_cms AND l.id_lang = ' . (int) $id_lang);
     }
     if ($active) {
         $sql->where('c.active = 1');
     }
     if ($id_cms_category) {
         $sql->where('c.id_cms_category = ' . (int) $id_cms_category);
     }
     $sql->orderBy('position');
     return Db::getInstance()->executeS($sql);
 }
Exemplo n.º 26
0
    public function getProducts($refresh = false, $id_product = false, $id_country = null)
    {
        if (!$this->id) {
            return array();
        }
        if ($this->_products !== null && !$refresh) {
            if (is_int($id_product)) {
                foreach ($this->_products as $product) {
                    if ($product['id_product'] == $id_product) {
                        return array($product);
                    }
                }
                return array();
            }
            return $this->_products;
        }
        $sql = new DbQuery();
        $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
						cp.`id_cart_product`, cp.`quantity_fractional` AS cart_quantity_fractional, p.id_pp_template,
						pl.`description_short`, pl.`available_now`, pl.`available_later`, product_shop.`id_category_default`, p.`id_supplier`,
						p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`,
						product_shop.`available_for_order`, product_shop.`price`, product_shop.`active`, product_shop.`unity`, product_shop.`unit_price_ratio`,
						stock.`quantity` + stock.`quantity_remainder` AS quantity_available, p.`unit_price_ratio`, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, p.`weight`,
						p.`date_add`, p.`date_upd`, IFNULL(stock.quantity, 0) + IFNULL(stock.quantity_remainder, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
						cp.`id_cart_product` AS unique_id, cp.id_address_delivery,
						product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
        $sql->from('cart_product', 'cp');
        $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
        $sql->innerJoin('product_shop', 'product_shop', '(product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)');
        $sql->leftJoin('product_lang', 'pl', '
			p.`id_product` = pl.`id_product`
			AND pl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop'));
        $sql->leftJoin('category_lang', 'cl', '
			product_shop.`id_category_default` = cl.`id_category`
			AND cl.`id_lang` = ' . (int) $this->id_lang . Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop'));
        $sql->leftJoin('product_supplier', 'ps', 'ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`');
        $sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`');
        $sql->join(Product::sqlStock('cp', 'cp'));
        $sql->where('cp.`id_cart` = ' . (int) $this->id);
        if ($id_product) {
            $sql->where('cp.`id_product` = ' . (int) $id_product);
        }
        $sql->where('p.`id_product` IS NOT NULL');
        $sql->groupBy('unique_id');
        $sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
        if (Customization::isFeatureActive()) {
            $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity, cu.`quantity_fractional` AS customization_quantity_fractional');
            $sql->leftJoin('customization', 'cu', 'cp.`id_cart_product` = cu.`id_cart_product`');
        } else {
            $sql->select('NULL AS customization_quantity, NULL AS customization_quantity_fractional, NULL AS id_customization');
        }
        if (Combination::isFeatureActive()) {
            $sql->select('
				product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
				IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
				(p.`weight`+ pa.`weight`) weight_attribute,
				IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
				IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
				pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
				IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity,
				IFNULL(product_attribute_shop.`minimal_quantity_fractional`, product_shop.`minimal_quantity_fractional`) as minimal_quantity_fractional,
				IF(product_attribute_shop.wholesale_price > 0,  product_attribute_shop.wholesale_price, product_shop.`wholesale_price`) wholesale_price
			');
            $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
            $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.`id_shop` = cp.`id_shop` AND product_attribute_shop.`id_product_attribute` = pa.`id_product_attribute`)');
            $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
            $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang);
        } else {
            $sql->select('p.`reference` AS reference, p.`ean13`,
				p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity, product_shop.`wholesale_price` wholesale_price');
        }
        $result = Db::getInstance()->executeS($sql);
        $products_ids = array();
        $pa_ids = array();
        if ($result) {
            foreach ($result as $row) {
                $products_ids[] = $row['id_product'];
                $pa_ids[] = $row['id_product_attribute'];
            }
        }
        Product::cacheProductsFeatures($products_ids);
        Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
        $this->_products = array();
        if (empty($result)) {
            return array();
        }
        $cart_shop_context = Context::getContext()->cloneContext();
        foreach ($result as &$row) {
            if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0) {
                $row['ecotax'] = (double) $row['ecotax_attr'];
            }
            $row['stock_quantity'] = (double) $row['quantity'];
            $row['quantity'] = (int) $row['cart_quantity'];
            if (isset($row['id_product_attribute']) && (int) $row['id_product_attribute'] && isset($row['weight_attribute'])) {
                $row['weight'] = (double) $row['weight_attribute'];
            }
            if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
                $address_id = (int) $this->id_address_invoice;
            } else {
                $address_id = (int) $row['id_address_delivery'];
            }
            if (!Address::addressExists($address_id)) {
                $address_id = null;
            }
            if ($cart_shop_context->shop->id != $row['id_shop']) {
                $cart_shop_context->shop = new Shop((int) $row['id_shop']);
            }
            $address = Address::initialize($address_id, true);
            $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $row['id_product'], $cart_shop_context);
            $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
            $specific_price_output = null;
            $row['price'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, array($row['cart_quantity'], $row['cart_quantity_fractional']), false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $address_id, $specific_price_output, false, true, $cart_shop_context);
            switch (Configuration::get('PS_ROUND_TYPE')) {
                case Order::ROUND_TOTAL:
                    $row['total'] = PP::calcPrice($row['price'], $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], false);
                    $row['total_wt'] = PP::calcPrice($tax_calculator->addTaxes($row['price']), $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], false);
                    $ppropertiessmartprice_hook1 = null;
                    break;
                case Order::ROUND_LINE:
                    $row['total'] = PP::calcPrice($row['price'], $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], false);
                    $row['total_wt'] = PP::calcPrice($tax_calculator->addTaxes($row['price']), $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], false);
                    $ppropertiessmartprice_hook1 = null;
                    $row['total'] = Tools::ps_round($row['total'], _PS_PRICE_COMPUTE_PRECISION_);
                    $row['total_wt'] = Tools::ps_round($row['total_wt'], _PS_PRICE_COMPUTE_PRECISION_);
                    break;
                case Order::ROUND_ITEM:
                default:
                    $row['total'] = PP::calcPrice($row['price'], $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], Order::ROUND_ITEM);
                    $row['total_wt'] = PP::calcPrice($tax_calculator->addTaxes($row['price']), $row['cart_quantity'], $row['cart_quantity_fractional'], (int) $row['id_product'], Order::ROUND_ITEM);
                    $ppropertiessmartprice_hook2 = null;
                    break;
            }
            $row['price_wt'] = $tax_calculator->addTaxes($row['price']);
            $row['description_short'] = Tools::nl2br($row['description_short']);
            if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0) {
                $cache_id = 'Cart::getProducts_' . '-pai_id_image-' . (int) $row['id_product'] . '-' . (int) $this->id_lang . '-' . (int) $row['id_shop'];
                if (!Cache::isStored($cache_id)) {
                    $row2 = Db::getInstance()->getRow('
						SELECT image_shop.`id_image` id_image, il.`legend`
						FROM `' . _DB_PREFIX_ . 'image` i
						JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop ON (i.id_image = image_shop.id_image AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $row['id_shop'] . ')
						LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = ' . (int) $this->id_lang . ')
						WHERE i.`id_product` = ' . (int) $row['id_product'] . ' AND image_shop.`cover` = 1');
                    Cache::store($cache_id, $row2);
                }
                $row2 = Cache::retrieve($cache_id);
                if (!$row2) {
                    $row2 = array('id_image' => false, 'legend' => false);
                } else {
                    $row = array_merge($row, $row2);
                }
            } else {
                $row['id_image'] = $row['pai_id_image'];
                $row['legend'] = $row['pai_legend'];
            }
            $row['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction'];
            $row['quantity_discount_applies'] = $specific_price_output && PP::resolveQty($row['cart_quantity'], $row['cart_quantity_fractional']) >= (double) $specific_price_output['from_quantity'];
            $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
            $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
            $row['features'] = Product::getFeaturesStatic((int) $row['id_product']);
            if (array_key_exists($row['id_product_attribute'] . '-' . $this->id_lang, self::$_attributesLists)) {
                $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'] . '-' . $this->id_lang]);
            }
            $row = Product::getTaxesInformations($row, $cart_shop_context);
            Product::amendProduct($row);
            $this->_products[] = $row;
        }
        return $this->_products;
    }