public static function getProductQuantity($product, $id_product_attribute = false) { $allow_oosp = self::isAllowOOSP($product); $qty = Product::getQuantity($product->id, $id_product_attribute); if ($qty > 0) { return $qty; } if ($allow_oosp) { return 1000; } return $qty; }
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 isInStock($id_product) { if (!Pack::isFeatureActive()) { return true; } $items = Pack::getItems((int) $id_product, Configuration::get('PS_LANG_DEFAULT')); foreach ($items as $item) { /** @var Product $item */ // Updated for 1.5.0 if (Product::getQuantity($item->id) < $item->pack_quantity && !$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) { return false; } } return true; }
$this->context->smarty->assign(array('order' => $order, 'price' => Tools::displayPrice($order['total_paid'], $this->context->currency), 'use_mobile' => $this->context->getMobileDevice())); if (!$order) { $this->context->smarty->assign('errors', array($this->paypal->l('Payment error'))); } echo $this->paypal->fetchTemplate('/views/templates/front/', 'order-confirmation'); } } if (Tools::getValue('id_module') && Tools::getValue('key') && Tools::getValue('id_cart') && Tools::getValue('id_order')) { if (_PS_VERSION_ < '1.5') { new PayPalExpressCheckoutSubmit(); } } elseif (Tools::getValue('get_qty')) { /* Ajax response */ $id_product = (int) Tools::getValue('id_product'); $id_product_attribute = (int) Tools::getValue('id_product_attribute'); if (Product::getQuantity((int) $id_product, (int) $id_product_attribute) <= 0) { $paypal = new Paypal(); die($paypal->l('This product is no longer in stock with those attributes but is available with others')); } die(true); } else { $request_type = Tools::getValue('express_checkout'); $ppec = new PaypalExpressCheckout($request_type); if ($request_type && $ppec->type) { $id_product = (int) Tools::getValue('id_product'); $id_product_attribute = (int) Tools::getValue('id_p_attr'); $product_quantity = (int) Tools::getValue('quantity'); if ($id_product > 0 && $id_product_attribute !== false && $product_quantity > 0) { // Create new Cart to avoid any refresh or other bad manipulations $ppec->context->cart = new Cart(); $ppec->context->cart->id_currency = (int) $ppec->context->currency->id;
protected function insertOrderItems(ShopgateOrder $order) { $this->log('start insertOrderItems()', ShopgateLogger::LOGTYPE_DEBUG); $products = array(); //Check product quantitys $settings = Configuration::getMultiple(array('SHOPGATE_MIN_QUANTITY_CHECK', 'SHOPGATE_OUT_OF_STOCK_CHECK')); // complete weight of the order foreach ($order->getItems() as $i) { list($id_product, $id_product_attribute) = $this->getProductIdentifiers($i); if ($id_product == 0) { continue; } $wantedQty = (int) $i->getQuantity(); $product = new Product($id_product, true, (int) Configuration::get('PS_LANG_DEFAULT')); $minQty = 1; if ((int) $id_product_attribute) { $stockQty = (int) Product::getQuantity((int) $id_product, (int) $id_product_attribute); if (version_compare(_PS_VERSION_, '1.4.0.7', '>=')) { // this attribute doesn't exist before 1.4.0.7 $minQty = Attribute::getAttributeMinimalQty((int) $id_product_attribute); } } else { $stockQty = (int) Product::getQuantity((int) $id_product, NULL); if (version_compare(_PS_VERSION_, '1.4.0.2', '>=')) { // this attribute doesn't exist before 1.4.0.2 $minQty = (int) $product->minimal_quantity; } } $oos_available = Product::isAvailableWhenOutOfStock($product->out_of_stock); $qtyDifference = 0; if (!$oos_available && $wantedQty > $stockQty) { $qtyDifference = $wantedQty - $stockQty; } $p = array(); $p['id_product'] = (int) $id_product; $p['id_product_attribute'] = (int) $id_product_attribute; $p['name'] = $product->name; $p['quantity'] = $wantedQty; $p['quantity_in_stock'] = $stockQty; $p['quantity_difference'] = $qtyDifference; if (empty($p['name'])) { $p['name'] = $i->getName(); } if ($oos_available) { $stockQty = $wantedQty; } if ((bool) $settings['SHOPGATE_MIN_QUANTITY_CHECK'] && $wantedQty < $minQty) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Minimum quantity required', true); } if ((bool) $settings['SHOPGATE_OUT_OF_STOCK_CHECK'] && $wantedQty > $stockQty) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Out of stock', true); } array_push($products, $p); } $this->log('end insertOrderItems()', ShopgateLogger::LOGTYPE_DEBUG); return $products; }
public static function getProductProperties($id_lang, $row) { if (!$row['id_product']) { return false; } // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) { $row['id_product_attribute'] = $ipa_default; } if (!isset($row['id_product_attribute'])) { $row['id_product_attribute'] = 0; } // Tax $usetax = Tax::excludeTaxeOption(); $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax; if (array_key_exists($cacheKey, self::$producPropertiesCache)) { return self::$producPropertiesCache[$cacheKey]; } // Datas $link = new Link(); $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang); $row['link'] = $link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']); $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? (double) Product::getProductAttributePrice($row['id_product_attribute']) : 0; $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6); if (self::$_taxCalculationMethod == PS_TAX_EXC) { $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2); $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2, NULL, false, false); } else { $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 2), 2); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? (int) $row['id_product_attribute'] : NULL, 6, NULL, false, false); } $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices); $row['specific_prices'] = $specific_prices; if ($row['id_product_attribute']) { $row['quantity_all_versions'] = $row['quantity']; $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL); } $row['id_image'] = Product::defineProductImage($row, $id_lang); $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']); $row['attachments'] = (!isset($row['cache_has_attachments']) or $row['cache_has_attachments']) ? Product::getAttachmentsStatic((int) $id_lang, $row['id_product']) : array(); // Pack management $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack']; $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; if ($row['pack'] and !Pack::isInStock($row['id_product'])) { $row['quantity'] = 0; } self::$producPropertiesCache[$cacheKey] = $row; return self::$producPropertiesCache[$cacheKey]; }
$offer_price_in_rs = Tools::convertPrice($offer_price_in, 4); $mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID); $mrp_in_rs = Tools::convertPrice($mrp_in, 4); $color = ''; if (isset($productObj->generic_color) && !empty($productObj->generic_color)) { $colors = explode(',', $productObj->generic_color); foreach ($colors as $c) { $color = strtolower(preg_replace('/\\s+/', '-', trim($c))); } } $fabric = ''; if (isset($productObj->fabric) && !empty($productObj->fabric)) { $fabric = $productObj->fabric; } $availability = 'TRUE'; $quantity = Product::getQuantity($id_product); if ((int) $quantity < 1) { $availability = 'FALSE'; } $catIds = $productObj->getCategories(); $category_names = array(); foreach ($catIds as $catID) { $category = new Category((int) $catID); $category_names[] = $category->getName(1); } $category_names = array_diff($category_names, array('Home')); $categories = implode(',', $category_names); $category = 'Other'; if (in_array(CAT_SAREE, $catIds)) { $category = 'Saree'; } elseif (in_array(CAT_SKD, $catIds)) {
public function initContent() { parent::initContent(); $token = Tools::getValue('token'); $module = new BlockWishList(); if ($token) { $wishlist = WishList::getByToken($token); WishList::refreshWishList($wishlist['id_wishlist']); $products = WishList::getProductByIdCustomer((int) $wishlist['id_wishlist'], (int) $wishlist['id_customer'], $this->context->language->id, null, true); $nb_products = count($products); $priority_names = array(0 => $module->l('High'), 1 => $module->l('Medium'), 2 => $module->l('Low')); for ($i = 0; $i < $nb_products; ++$i) { $obj = new Product((int) $products[$i]['id_product'], true, $this->context->language->id); if (!Validate::isLoadedObject($obj)) { continue; } else { $products[$i]['priority_name'] = $priority_names[$products[$i]['priority']]; $quantity = Product::getQuantity((int) $products[$i]['id_product'], $products[$i]['id_product_attribute']); $products[$i]['attribute_quantity'] = $quantity; $products[$i]['product_quantity'] = $quantity; $products[$i]['allow_oosp'] = $obj->isAvailableWhenOutOfStock((int) $obj->out_of_stock); if ($products[$i]['id_product_attribute'] != 0) { $combination_imgs = $obj->getCombinationImages($this->context->language->id); if (isset($combination_imgs[$products[$i]['id_product_attribute']][0])) { $products[$i]['cover'] = $obj->id . '-' . $combination_imgs[$products[$i]['id_product_attribute']][0]['id_image']; } else { $cover = Product::getCover($obj->id); $products[$i]['cover'] = $obj->id . '-' . $cover['id_image']; } } else { $images = $obj->getImages($this->context->language->id); foreach ($images as $image) { if ($image['cover']) { $products[$i]['cover'] = $obj->id . '-' . $image['id_image']; break; } } } if (!isset($products[$i]['cover'])) { $products[$i]['cover'] = $this->context->language->iso_code . '-default'; } } $products[$i]['bought'] = false; /* for ($j = 0, $k = 0; $j < sizeof($bought); ++$j) { if ($bought[$j]['id_product'] == $products[$i]['id_product'] AND $bought[$j]['id_product_attribute'] == $products[$i]['id_product_attribute'] ) $products[$i]['bought'][$k++] = $bought[$j]; }*/ } WishList::incCounter((int) $wishlist['id_wishlist']); $ajax = Configuration::get('PS_BLOCK_CART_AJAX'); $wishlists = WishList::getByIdCustomer((int) $wishlist['id_customer']); foreach ($wishlists as $key => $item) { if ($item['id_wishlist'] == $wishlist['id_wishlist']) { unset($wishlists[$key]); break; } } $this->context->smarty->assign(array('current_wishlist' => $wishlist, 'token' => $token, 'ajax' => isset($ajax) && (int) $ajax == 1 ? '1' : '0', 'wishlists' => $wishlists, 'products' => $products)); } $this->setTemplate('view.tpl'); }
public static function getProductProperties($id_lang, $row) { if (!$row['id_product']) { return false; } $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])) { $row['id_product_attribute'] = $ipa_default; } if (!isset($row['id_product_attribute'])) { $row['id_product_attribute'] = 0; } // Tax $usetax = true; $tax = floatval(Tax::getApplicableTax(intval($row['id_tax']), floatval($row['rate']))); if (Tax::excludeTaxeOption() or !$tax) { $usetax = false; } $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . intval($usetax); if (array_key_exists($cacheKey, self::$producPropertiesCache)) { return self::$producPropertiesCache[$cacheKey]; } // Datas $link = new Link(); $row['category'] = Category::getLinkRewrite($row['id_category_default'], intval($id_lang)); $row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']); $row['attribute_price'] = (isset($row['id_product_attribute']) and $row['id_product_attribute']) ? floatval(Product::getProductAttributePrice($row['id_product_attribute'])) : 0; $row['price_tax_exc'] = Product::getPriceStatic($row['id_product'], false, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6); if (self::$_taxCalculationMethod == PS_TAX_EXC) { $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2); $row['price'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6); } else { $row['price'] = Tools::ps_round(Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6), 2); } $row['reduction'] = self::getReductionValue($row['reduction_price'], $row['reduction_percent'], $row['reduction_from'], $row['reduction_to'], $row['price'], $usetax, floatval($row['rate'])); $row['price_without_reduction'] = Product::getPriceStatic($row['id_product'], true, (isset($row['id_product_attribute']) and !empty($row['id_product_attribute'])) ? intval($row['id_product_attribute']) : NULL, 6, NULL, false, false); $row['quantity'] = Product::getQuantity($row['id_product']); $row['id_image'] = Product::defineProductImage($row); $row['features'] = Product::getFrontFeaturesStatic(intval($id_lang), $row['id_product']); $row['attachments'] = Product::getAttachmentsStatic(intval($id_lang), $row['id_product']); $row['pack'] = Pack::isPack($row['id_product']); $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; self::$producPropertiesCache[$cacheKey] = $row; return self::$producPropertiesCache[$cacheKey]; }
protected function restoreOrderToCart(Cart $cart) { if (!$cart || !ValidateCore::isLoadedObject($cart)) { return null; } Db::getInstance()->execute('BEGIN'); $new_cart = null; try { /** @var CartCore $new_cart */ /** @noinspection PhpUndefinedClassInspection */ $new_cart = new Cart(); /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_customer = (int) $cart->id_customer; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_address_delivery = (int) $cart->id_address_delivery; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_address_invoice = (int) $cart->id_address_invoice; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_lang = (int) $cart->id_lang; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_currency = (int) $cart->id_currency; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_carrier = (int) $cart->id_carrier; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->recyclable = (int) $cart->recyclable; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->gift = (int) $cart->gift; $new_cart->add(); /** @noinspection PhpUndefinedMethodInspection */ $products = $cart->getProducts(); if ($products) { foreach ($products as $p) { $idProduct = $p['id_product']; $idProductAttribute = $p['id_product_attribute']; $qty = $p['cart_quantity']; /** @noinspection PhpUndefinedClassInspection */ /** @noinspection PhpUndefinedFieldInspection */ $producToAdd = new Product((int) $idProduct, true, (int) $cart->id_lang); /** @noinspection PhpUndefinedFieldInspection */ if (!$producToAdd->id || !$producToAdd->active) { continue; } /* Check the quantity availability */ if ($idProductAttribute > 0 and is_numeric($idProductAttribute)) { /** @noinspection PhpUndefinedClassInspection */ /** @noinspection PhpUndefinedMethodInspection */ /** @noinspection PhpUndefinedFieldInspection */ if (!$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) { /* There is not enough product attribute in stock - set customer qty to current stock on hand */ /** @noinspection PhpUndefinedFunctionInspection */ $qty = getAttributeQty($idProductAttribute); } } elseif (!$producToAdd->checkQty((int) $qty)) { /* There is not enough product in stock - set customer qty to current stock on hand */ /** @noinspection PhpUndefinedMethodInspection */ $qty = $producToAdd->getQuantity($idProduct); } $new_cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, NULL, 'up'); unset($p); } } $new_cart->update(); Db::getInstance()->execute('COMMIT'); } catch (Exception $e) { Db::getInstance()->execute('ROLLBACK'); throw $e; } /** @noinspection PhpUndefinedFieldInspection */ $this->context->cookie->id_cart = (int) $new_cart->id; return $new_cart; }
public function hookProductFooter($params) { $product_quantity = Product::getQuantity((int) Tools::getValue('id_product')); if ($product_quantity == 0) { return; } if (Configuration::get('PAYPAL_USA_EXPRESS_CHECKOUT') == 1 && Configuration::get('PAYPAL_USA_EXP_CHK_PRODUCT')) { $this->smarty->assign('paypal_usa_action', $this->context->link->getModuleLink('paypalusa', 'expresscheckout', array('pp_exp_initial' => 1))); $this->smarty->assign('paypal_usa_merchant_country_is_mx', Validate::isLoadedObject($this->_shop_country) && $this->_shop_country->iso_code == 'MX'); return $this->display(__FILE__, 'views/templates/hooks/express-checkout.tpl'); } }
public static function getProductProperties($id_lang, $row) { if (!$row['id_product']) { return false; } // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: consider adding it in order to avoid unnecessary queries $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if ((!isset($row['id_product_attribute']) or !$row['id_product_attribute']) and (isset($row['cache_default_attribute']) and ($ipa_default = $row['cache_default_attribute']) !== NULL or $ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp']))) { $row['id_product_attribute'] = $ipa_default; } if (!isset($row['id_product_attribute'])) { $row['id_product_attribute'] = 0; } // Tax $usetax = Tax::excludeTaxeOption(); $cacheKey = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax; if (array_key_exists($cacheKey, self::$producPropertiesCache)) { return self::$producPropertiesCache[$cacheKey]; } // Datas $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang); if (!preg_match("/^1.3.*/", _PS_VERSION_)) { // Not available in Prestashop 1.3.x $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, NULL, true, true, 1, true, NULL, NULL, NULL, $specific_prices); $row['specific_prices'] = $specific_prices; } if ($row['id_product_attribute']) { $row['quantity_all_versions'] = $row['quantity']; $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : NULL); } $row['id_image'] = Product::defineProductImage($row, $id_lang); $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']); // Pack management $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack']; $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; if ($row['pack'] and !Pack::isInStock($row['id_product'])) { $row['quantity'] = 0; } $sql_combination = ' SELECT pa.id_product_attribute, pa.price, pa.quantity, pa.id_product FROM `' . _DB_PREFIX_ . 'product` p LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`) WHERE p.`id_product` =' . $row['id_product']; $result_combination = ProductExtended::getDbInstance()->ExecuteS($sql_combination); $row['combinations'] = array(); if ($result_combination) { foreach ($result_combination as $combination) { $combination['attributes'] = array(); /* New combinations system Prestashop 1.5.x */ if (!preg_match("/^1.(3|4).*/", _PS_VERSION_)) { $combination['quantity'] = StockAvailable::getQuantityAvailableByProduct($row['id_product'], $combination['id_product_attribute']); } if (isset($combination['id_product_attribute'])) { $sql_attribute = ' SELECT pa.id_product_attribute, agl.id_attribute_group, al.name as name_value, agl.name as name_option FROM `' . _DB_PREFIX_ . 'product_attribute` pa LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute` = pac.`id_attribute`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute` = a.`id_attribute` AND al.`id_lang` = ' . $id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`) LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group` = ag.`id_attribute_group` AND agl.`id_lang` = ' . $id_lang . ') WHERE pa.`id_product_attribute` =' . $combination['id_product_attribute']; $result_attribute = ProductExtended::getDbInstance()->ExecuteS($sql_attribute); if ($result_attribute) { foreach ($result_attribute as $attribute) { array_push($combination['attributes'], $attribute); } } array_push($row['combinations'], $combination); } } } $sql_image = ' SELECT DISTINCT i.*, pl.link_rewrite FROM `' . _DB_PREFIX_ . 'product` p LEFT JOIN `' . _DB_PREFIX_ . 'image` i ON (p.`id_product` = i.`id_product`) LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product`) WHERE p.`id_product` =' . $row['id_product']; $result_image = ProductExtended::getDbInstance()->ExecuteS($sql_image); $row['images'] = array(); $lang = new Language($id_lang); $row['url_locale'] = $lang->iso_code; if ($result_image) { $link = preg_match("/^1.(3|4).*/", _PS_VERSION_) ? new Link() : Context::getContext()->link; foreach ($result_image as $image) { if (!preg_match("/^1.3.*/", _PS_VERSION_)) { // Image URL gives relative version using 1.3.x- $image['image_url'] = $link->getImageLink($image['link_rewrite'], $image['id_product'] . '-' . $image['id_image']); } array_push($row['images'], $image); } } self::$producPropertiesCache[$cacheKey] = $row; return self::$producPropertiesCache[$cacheKey]; }
protected function getInventoryObj($divaProduct, $sku, &$quantity, &$shipping_sla, $zero = false) { $id_product = $sku["id_product"]; $is_parent = $sku["is_parent"]; $has_children = empty($sku["attribute"]) ? false : true; $size = empty($sku["attribute"]) ? "One Size" : $sku["attribute"]["attribute_name"]; $id_sku = $sku['id_sku']; $inventoryData = new MarketplaceWebService_XML_Data_Inventory(); $inventoryData->setSKU($id_sku); if ($is_parent === false && $has_children === false) { $quantity = (int) Product::getQuantity($id_product); if ($quantity < 0) { $inventoryData->setQuantity(0); } else { $inventoryData->setQuantity($quantity); } } else { if ($is_parent) { $quantity = (int) Product::getQuantity($id_product); if ($quantity < 0) { $inventoryData->setQuantity(0); } else { $inventoryData->setQuantity($quantity); } } else { $quantity = (int) Product::getQuantity($id_product, $sku['attribute']['id_product_attribute']); if ($quantity < 0) { $inventoryData->setQuantity(0); } else { $inventoryData->setQuantity($quantity); } } } if ($zero) { $inventoryData->setQuantity(0); } $shipping_sla = (int) $divaProduct->shipping_sla; $inventoryData->setFulfillmentLatency($shipping_sla); return $inventoryData; }
/** * @global object $cookie Employee cookie necessary to keep trace of his/her actions */ public function postProcess() { global $currentIndex, $cookie; /* Update shipping number */ if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { if (!$order->hasBeenShipped()) { die(Tools::displayError('The shipping number can only be set once the order has been shipped.')); } $_GET['view' . $this->table] = true; $shipping_number = pSQL(Tools::getValue('shipping_number')); $order->shipping_number = $shipping_number; $order->update(); if ($shipping_number) { global $_LANGMAIL; $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id); @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { $_GET['view' . $this->table] = true; if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) { $this->_errors[] = Tools::displayError('Invalid new order status'); } else { $history = new OrderHistory(); $history->id_order = (int) $id_order; $history->id_employee = (int) $cookie->id_employee; $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order); $order = new Order((int) $order->id); $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang); $templateVars = array(); if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') and $order->shipping_number) { $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); } elseif ($history->id_order_state == Configuration::get('PS_OS_CHEQUE')) { $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : ''); } elseif ($history->id_order_state == Configuration::get('PS_OS_BANKWIRE')) { $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : ''); } if ($history->addWithemail(true, $templateVars)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token); } $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_POST['submitMessage'])) { $_GET['view' . $this->table] = true; if ($this->tabAccess['edit'] === '1') { if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) { $this->_errors[] = Tools::displayError('An error occurred before sending message'); } elseif (!Tools::getValue('message')) { $this->_errors[] = Tools::displayError('Message cannot be blank'); } else { /* Get message rules and and check fields validity */ $rules = call_user_func(array('Message', 'getValidationRules'), 'Message'); foreach ($rules['required'] as $field) { if (($value = Tools::getValue($field)) == false and (string) $value != '0') { if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.'); } } } foreach ($rules['size'] as $field => $maxLength) { if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')'; } } foreach ($rules['validate'] as $field => $function) { if (Tools::getValue($field)) { if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.'); } } } if (!sizeof($this->_errors)) { $message = new Message(); $message->id_employee = (int) $cookie->id_employee; $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8'); $message->id_order = $id_order; $message->private = Tools::getValue('visibility'); if (!$message->add()) { $this->_errors[] = Tools::displayError('An error occurred while sending message.'); } elseif ($message->private) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) { $order = new Order((int) $message->id_order); if (Validate::isLoadedObject($order)) { $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)); if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } } } $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { if ($this->tabAccess['delete'] === '1') { $productList = Tools::getValue('id_order_detail'); $customizationList = Tools::getValue('id_customization'); $qtyList = Tools::getValue('cancelQuantity'); $customizationQtyList = Tools::getValue('cancelCustomizationQuantity'); $full_product_list = $productList; $full_quantity_list = $qtyList; if ($customizationList) { foreach ($customizationList as $key => $id_order_detail) { $full_product_list[$id_order_detail] = $id_order_detail; $full_quantity_list[$id_order_detail] = $customizationQtyList[$key]; } } if ($productList or $customizationList) { if ($productList) { $id_cart = Cart::getCartIdByOrderId($order->id); $customization_quantities = Customization::countQuantityByCart($id_cart); foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } // check actionable quantity $order_detail = new OrderDetail($id_order_detail); $customization_quantity = 0; if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) { $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id]; } if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if ($customizationList) { $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList)); foreach ($customizationList as $id_customization => $id_order_detail) { $qtyCancelProduct = abs($customizationQtyList[$id_customization]); $customization_quantity = $customization_quantities[$id_customization]; if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if (!sizeof($this->_errors) and $productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); $orderDetail = new OrderDetail((int) $id_order_detail); // Reinject product if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) { $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected; $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct; if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) { $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } else { $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL; $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID); $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang)); if (!empty($orderDetail->product_attribute_id)) { $updProduct['quantity_attribute'] = (int) $newProductQty; $product['quantity_attribute'] = $updProduct['quantity_attribute']; } else { $updProduct['stock_quantity'] = (int) $newProductQty; $product['stock_quantity'] = $updProduct['stock_quantity']; } Hook::updateQuantity($product, $order); } } // Delete product if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail)); } } if (!sizeof($this->_errors) and $customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $orderDetail = new OrderDetail((int) $id_order_detail); $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization; } } } // E-mail params if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) { $customer = new Customer((int) $order->id_customer); $params['{lastname}'] = $customer->lastname; $params['{firstname}'] = $customer->firstname; $params['{id_order}'] = $order->id; } // Generate credit slip if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) { if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) { $this->_errors[] = Tools::displayError('Cannot generate credit slip'); } else { Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list)); @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } // Generate voucher if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) { if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) { $this->_errors[] = Tools::displayError('Cannot generate voucher'); } else { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true); } } } else { $this->_errors[] = Tools::displayError('No product or quantity selected.'); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (isset($_GET['messageReaded'])) { Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee); } parent::postProcess(); }
/** * @global object $cookie Employee cookie necessary to keep trace of his/her actions */ public function postProcess() { global $currentIndex, $cookie; /* Update shipping number */ if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { if (!$order->hasBeenShipped()) { die(Tools::displayError('The shipping number can only be set once the order has been shipped.')); } $_GET['view' . $this->table] = true; $shipping_number = pSQL(Tools::getValue('shipping_number')); $order->shipping_number = $shipping_number; $order->update(); if ($shipping_number) { global $_LANGMAIL; $customer = new Customer((int) $order->id_customer); $carrier = new Carrier((int) $order->id_carrier); if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } $templateVars = array('{order_amount}' => Tools::displayPrice($order->total_paid, $currency, false), '{carrier_name}' => $carrier->name, '{tracking_number}' => $order->shipping_number, '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id); if (strpos($order->payment, 'COD') === false) { @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } else { @Mail::Send((int) $order->id_lang, 'in_transit_cod', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } //Send SMS $delivery = new Address((int) $order->id_address_delivery); if (strpos($order->payment, 'COD') === false) { $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped via ' . $carrier->name . '. The airway bill no is ' . $order->shipping_number . '. www.indusdiva.com'; } else { $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped. Carrier: ' . $carrier->name . ', AWB No. : ' . $order->shipping_number . ', Amount payable:' . Tools::displayPrice($order->total_paid, $currency, false) . '. www.indusdiva.com'; } Tools::sendSMS($delivery->phone_mobile, $smsText); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitExpectedShippingDate') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { $dateshipping = new DateTime(Tools::getValue('expected_shipping_date')); $order->expected_shipping_date = pSQL($dateshipping->format('Y-m-d H:i:s')); $order->update(); $order = new Order($id_order); } elseif (Tools::isSubmit('submitCarrier') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { $order->shipping_number = ''; $order->id_carrier = (int) Tools::getValue('id_carrier'); $order->update(); $order = new Order($id_order); } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) { if ($this->tabAccess['edit'] === '1') { $_GET['view' . $this->table] = true; if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) { $this->_errors[] = Tools::displayError('Invalid new order status'); } else { if ($newOrderStatusId == _PS_OS_DELIVERED_ && strpos($order->payment, 'COD')) { $paymentHistory = new OrderPaymentHistory(); $paymentHistory->id_order = (int) $id_order; $paymentHistory->id_employee = (int) $cookie->id_employee; $paymentHistory->changeIdOrderPaymentState(_PS_PS_PAYMENT_WITH_CARRIER_, (int) $id_order); $paymentHistory->addState(); } $history = new OrderHistory(); $history->id_order = (int) $id_order; $history->id_employee = (int) $cookie->id_employee; $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order); $order = new Order((int) $order->id); $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang); $templateVars = array(); if ($history->id_order_state == _PS_OS_SHIPPING_ and $order->shipping_number) { $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); } elseif ($history->id_order_state == _PS_OS_CHEQUE_) { $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : ''); } elseif ($history->id_order_state == _PS_OS_BANKWIRE_) { $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : ''); } if ($history->id_order_state == _PS_OS_CANCELED_) { $this->cancelOrder($id_order); } if ($history->addWithemail(true, $templateVars)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token); } $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_POST['submitMessage'])) { $_GET['view' . $this->table] = true; if ($this->tabAccess['edit'] === '1') { if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) { $this->_errors[] = Tools::displayError('An error occurred before sending message'); } elseif (!Tools::getValue('message')) { $this->_errors[] = Tools::displayError('Message cannot be blank'); } else { /* Get message rules and and check fields validity */ $rules = call_user_func(array('Message', 'getValidationRules'), 'Message'); foreach ($rules['required'] as $field) { if (($value = Tools::getValue($field)) == false and (string) $value != '0') { if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.'); } } } foreach ($rules['size'] as $field => $maxLength) { if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')'; } } foreach ($rules['validate'] as $field => $function) { if (Tools::getValue($field)) { if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) { $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.'); } } } if (!sizeof($this->_errors)) { $message = new Message(); $message->id_employee = (int) $cookie->id_employee; $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8'); $message->id_order = $id_order; $message->private = Tools::getValue('visibility'); if (!$message->add()) { $this->_errors[] = Tools::displayError('An error occurred while sending message.'); } elseif ($message->private) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) { $order = new Order((int) $message->id_order); if (Validate::isLoadedObject($order)) { $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)); if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token); } } } $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { if ($this->tabAccess['delete'] === '1') { $productList = Tools::getValue('id_order_detail'); $customizationList = Tools::getValue('id_customization'); $qtyList = Tools::getValue('cancelQuantity'); $customizationQtyList = Tools::getValue('cancelCustomizationQuantity'); $full_product_list = $productList; $full_quantity_list = $qtyList; if ($customizationList) { foreach ($customizationList as $key => $id_order_detail) { $full_product_list[$id_order_detail] = $id_order_detail; $full_quantity_list[$id_order_detail] = $customizationQtyList[$key]; } } if ($productList or $customizationList) { if ($productList) { $id_cart = Cart::getCartIdByOrderId($order->id); $customization_quantities = Customization::countQuantityByCart($id_cart); foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } // check actionable quantity $order_detail = new OrderDetail($id_order_detail); $customization_quantity = 0; if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) { $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id]; } if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if ($customizationList) { $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList)); foreach ($customizationList as $id_customization => $id_order_detail) { $qtyCancelProduct = abs($customizationQtyList[$id_customization]); $customization_quantity = $customization_quantities[$id_customization]; if (!$qtyCancelProduct) { $this->_errors[] = Tools::displayError('No quantity selected for product.'); } if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) { $this->_errors[] = Tools::displayError('Invalid quantity selected for product.'); } } } if (!sizeof($this->_errors) and $productList) { foreach ($productList as $key => $id_order_detail) { $qtyCancelProduct = abs($qtyList[$key]); $orderDetail = new OrderDetail((int) $id_order_detail); // Reinject product if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) { $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected; $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct; if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) { $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } else { $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL; $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID); $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang)); if (!empty($orderDetail->product_attribute_id)) { $updProduct['quantity_attribute'] = (int) $newProductQty; $product['quantity_attribute'] = $updProduct['quantity_attribute']; } else { $updProduct['stock_quantity'] = (int) $newProductQty; $product['stock_quantity'] = $updProduct['stock_quantity']; } Hook::updateQuantity($product, $order); } } // Delete product if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>'; } Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail)); } } if (!sizeof($this->_errors) and $customizationList) { foreach ($customizationList as $id_customization => $id_order_detail) { $orderDetail = new OrderDetail((int) $id_order_detail); $qtyCancelProduct = abs($customizationQtyList[$id_customization]); if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) { $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization; } } } // E-mail params if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) { $customer = new Customer((int) $order->id_customer); $params['{lastname}'] = $customer->lastname; $params['{firstname}'] = $customer->firstname; $params['{id_order}'] = $order->id; } // Generate credit slip if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) { if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) { $this->_errors[] = Tools::displayError('Cannot generate credit slip'); } else { Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list)); @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } // Generate voucher if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) { if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) { $this->_errors[] = Tools::displayError('Cannot generate voucher'); } else { $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } } else { $this->_errors[] = Tools::displayError('No product or quantity selected.'); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('updateOrder') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) { $cart = Cart::getCartByOrderId($order->id); $update = false; if ($discountValue = Tools::getValue('addDiscount')) { $discountVoucher = new Discount(); $discountVoucher->name = 'ADMIND-' . $order->id . date('mdHis'); $discountVoucher->id_discount_type = 2; $discountVoucher->id_customer = $order->id_customer; $discountVoucher->cumulable = 1; $discountVoucher->cumulable_reduction = 1; $discountVoucher->date_from = $order->date_add; $discountVoucher->date_to = date('Y-m-d', time() + 86400); $discountVoucher->quantity = 1; $discountVoucher->quantity_per_user = 1; $discountVoucher->value = (double) $discountValue; $discountVoucher->minimal = 0; $discountVoucher->id_currency = 4; $discountVoucher->behavior_not_exhausted = 1; $discountVoucher->add(true); $cart->addDiscount($discountVoucher->id); $order->addDiscount($discountVoucher->id, $discountVoucher->name, $discountVoucher->value); $cart->update(); $update = true; } //waive shipping, create a free shipping voucher, apply, reload the order object if (Tools::getValue('waiveShipping')) { $freeShipVoucher = new Discount(); $freeShipVoucher->name = 'ADMINFS-' . $order->id . date('mdHis'); $freeShipVoucher->id_discount_type = 3; $freeShipVoucher->id_customer = $order->id_customer; $freeShipVoucher->cumulable = 1; $freeShipVoucher->cumulable_reduction = 1; $freeShipVoucher->date_from = $order->date_add; $freeShipVoucher->date_to = date('Y-m-d', time() + 86400); $freeShipVoucher->quantity = 0; $freeShipVoucher->quantity_per_user = 1; $freeShipVoucher->value = 0; $freeShipVoucher->add(true); $cart->addDiscount($freeShipVoucher->id); $order->addDiscount($freeShipVoucher->id, $freeShipVoucher->name, $freeShipVoucher->value); $cart->update(); $update = true; } $id_product = false; if ($id_product = Tools::getValue('addProductID')) { $product = new Product((int) $id_product, true, (int) $cookie->id_lang); if ($product->quantity > 0 && $product->available_for_order) { $cart->updateQty(1, $id_product); } $orderDetail = null; $db = Db::getInstance(); $res = $db->getRow('select id_order_detail from ps_order_detail where id_order = ' . $order->id . ' and product_id = ' . $id_product); $vat_address = new Address((int) $order->id_address_delivery); $customer = new Customer((int) $order->id_customer); $unitPrice = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); if ($res) { $orderDetail = new OrderDetail($res['id_order_detail']); $orderDetail->product_quantity = $orderDetail->product_quantity + 1; } else { $productName = $product->name; $orderDetail = new OrderDetail(); $orderDetail->product_quantity = 1; $orderDetail->id_order = $order->id; $orderDetail->product_id = $id_product; $orderDetail->product_name = $productName; $orderDetail->product_ean13 = $product->ean13; $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $specificPrice = 0; $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity); $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE); $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0); $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0); $orderDetail->tax_rate = $tax_rate; $orderDetail->tax_name = 'default_tax'; $orderDetail->group_reduction = 0; $orderDetail->product_quantity_in_stock = (int) Product::getQuantity((int) $id_product, NULL); $orderDetail->product_quantity_refunded = 0; $orderDetail->product_quantity_reinjected = 0; $orderDetail->ecotax = 0; $orderDetail->ecotax_tax_rate = 0; $orderDetail->discount_quantity_applied = 0; $orderDetail->add(true, true); } $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity); $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE); $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0); $orderDetail->reduction_amount = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0); $orderDetail->update(); $product->addStockMvt(-1, _STOCK_MOVEMENT_ORDER_REASON_, NULL, $order->id, (int) $cookie->id_employee); $update = true; } if ($update) { //Recalculate product prices with and without tax from order detail $detailIds = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT id_order_detail FROM `' . _DB_PREFIX_ . 'order_detail` od WHERE od.`id_order` = ' . (int) $order->id); $totalProducts = 0.0; $totalProductsWT = 0.0; foreach ($detailIds as $id) { $reduction_amount = 0.0; $orderDetail = new OrderDetail($id['id_order_detail']); $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01); if ($orderDetail->reduction_percent != 0.0) { $reduction_amount = $price * $orderDetail->reduction_percent / 100; } elseif ($orderDetail->reduction_amount != 0.0) { $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2); } if (isset($reduction_amount) and $reduction_amount) { $price = Tools::ps_round($price - $reduction_amount, 2); } $productPriceWithoutTax = $price / (1 + $orderDetail->tax_rate * 0.01); //Update order $totalProducts += $orderDetail->product_quantity * $productPriceWithoutTax; $totalProductsWT += $orderDetail->product_quantity * $price; } $order->total_products = Tools::ps_round($totalProducts, 2); $order->total_products_wt = Tools::ps_round($totalProductsWT, 2); $order->total_shipping = $cart->getOrderShippingCost(); //$order->total_products = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_discounts = abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_paid = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod; $order->total_paid_real = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod; //$order->total_products_wt = (float)($cart->getOrderTotal(true, Cart::ONLY_PRODUCTS)); $order->update(); } // Redirect if no errors if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token); } } elseif (isset($_GET['messageReaded'])) { Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee); } parent::postProcess(); }
* http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <*****@*****.**> * @copyright 2007-2014 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ include_once dirname(__FILE__) . '/../../../config/config.inc.php'; include_once dirname(__FILE__) . '/../../../init.php'; include_once dirname(__FILE__) . '/../paypal.php'; // Ajax query $quantity = Tools::getValue('get_qty'); if ($quantity && $quantity > 0) { /* Ajax response */ $id_product = (int) Tools::getValue('id_product'); $id_product_attribute = (int) Tools::getValue('id_product_attribute'); $product_quantity = Product::getQuantity($id_product, $id_product_attribute); if ($product_quantity > 0) { die('1'); } } die('0');
$id_product = $row['id_product']; $product = new Product($id_product, true, 1); $attributeGroups = $product->getAttributesGroups(1); foreach ($attributeGroups as $group) { $data = array(); $data[] = "TODO"; $data[] = $id_product . '-' . $group['attribute_name']; $data[] = $product->name; $data[] = ""; $data[] = (int) round(Tools::convertPrice($product->getPriceWithoutReduct(false, $group['id_product_attribute']))); $data[] = (int) round(Tools::convertPrice($product->getPriceWithoutReduct(true, $group['id_product_attribute']))); $data[] = ""; $data[] = ""; $data[] = "No"; $data[] = ""; $data[] = (int) Product::getQuantity($id_product, $group['id_product_attribute']); $data[] = (int) $product->shipping_sla; $cdata .= tocsv($data) . "\n"; } } echo $cdata = str_replace("\r", "", $cdata); exit; function tocsv($data) { $line = ''; foreach ($data as $value) { if (!isset($value) || $value == "") { $value = ","; } else { $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . ",";
public static function getProductProperties($id_lang, $row, Context $context = null) { Hook::exec('actionGetProductPropertiesBefore', ['id_lang' => $id_lang, 'product' => $row, 'context' => $context]); if (!$row['id_product']) { return false; } if ($context == null) { $context = Context::getContext(); } $id_product_attribute = $row['id_product_attribute'] = !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null; // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: // consider adding it in order to avoid unnecessary queries $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if (Combination::isFeatureActive() && $id_product_attribute === null && (isset($row['cache_default_attribute']) && ($ipa_default = $row['cache_default_attribute']) !== null || ($ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])))) { $id_product_attribute = $row['id_product_attribute'] = $ipa_default; } if (!Combination::isFeatureActive() || !isset($row['id_product_attribute'])) { $id_product_attribute = $row['id_product_attribute'] = 0; } // Tax $usetax = !Tax::excludeTaxeOption(); $cache_key = $row['id_product'] . '-' . $id_product_attribute . '-' . $id_lang . '-' . (int) $usetax; if (isset($row['id_product_pack'])) { $cache_key .= '-pack' . $row['id_product_pack']; } if (isset(self::$producPropertiesCache[$cache_key])) { return array_merge($row, self::$producPropertiesCache[$cache_key]); } // Datas $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang); $row['category_name'] = Db::getInstance()->getValue('SELECT name FROM ' . _DB_PREFIX_ . 'category_lang WHERE id_shop = ' . (int) $context->shop->id . ' AND id_lang = ' . (int) $id_lang . ' AND id_category = ' . (int) $row['id_category_default']); $row['link'] = $context->link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']); $row['attribute_price'] = 0; if ($id_product_attribute) { $row['attribute_price'] = (double) Combination::getPrice($id_product_attribute); } if (isset($row['quantity_wanted'])) { // 'quantity_wanted' may very well be zero even if set $quantity = max((int) $row['minimal_quantity'], (int) $row['quantity_wanted']); } else { $quantity = (int) $row['minimal_quantity']; } $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, $id_product_attribute, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6, null, false, true, $quantity); if (self::$_taxCalculationMethod == PS_TAX_EXC) { $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2); $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, true, $quantity); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, $id_product_attribute, 2, null, false, false, $quantity); } else { $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, true, $quantity), (int) Configuration::get('PS_PRICE_DISPLAY_PRECISION')); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, $id_product_attribute, 6, null, false, false, $quantity); } $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, $id_product_attribute, 6, null, true, true, $quantity, true, null, null, null, $specific_prices); $row['specific_prices'] = $specific_prices; $row['quantity'] = Product::getQuantity((int) $row['id_product'], 0, isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null); $row['quantity_all_versions'] = $row['quantity']; if ($row['id_product_attribute']) { $row['quantity'] = Product::getQuantity((int) $row['id_product'], $id_product_attribute, isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null); $row['available_date'] = Product::getAvailableDate((int) $row['id_product'], $id_product_attribute); } $row['id_image'] = Product::defineProductImage($row, $id_lang); $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']); $row['attachments'] = array(); if (!isset($row['cache_has_attachments']) || $row['cache_has_attachments']) { $row['attachments'] = Product::getAttachmentsStatic((int) $id_lang, $row['id_product']); } $row['virtual'] = !isset($row['is_virtual']) || $row['is_virtual'] ? 1 : 0; // Pack management $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack']; $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; if ($row['pack'] && !Pack::isInStock($row['id_product'])) { $row['quantity'] = 0; } $row['customization_required'] = false; if (isset($row['customizable']) && $row['customizable'] && Customization::isFeatureActive()) { if (count(Product::getRequiredCustomizableFieldsStatic((int) $row['id_product']))) { $row['customization_required'] = true; } } $attributes = Product::getAttributesParams($row['id_product'], $row['id_product_attribute']); foreach ($attributes as $attribute) { $row['attributes'][$attribute['id_attribute_group']] = $attribute; } $row = Product::getTaxesInformations($row, $context); $row['ecotax_rate'] = (double) Tax::getProductEcotaxRate($context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); Hook::exec('actionGetProductPropertiesAfter', ['id_lang' => $id_lang, 'product' => $row, 'context' => $context]); $combination = new Combination($id_product_attribute); if (0 != $combination->unit_price_impact && 0 != $row['unit_price_ratio']) { $unitPrice = $row['price_tax_exc'] / $row['unit_price_ratio'] + $combination->unit_price_impact; $row['unit_price_ratio'] = $row['price_tax_exc'] / $unitPrice; } $row['unit_price'] = $row['unit_price_ratio'] != 0 ? $row['price'] / $row['unit_price_ratio'] : 0; self::$producPropertiesCache[$cache_key] = $row; return self::$producPropertiesCache[$cache_key]; }
public static function getProductProperties($id_lang, $row, Context $context = null) { if (!$row['id_product']) { return false; } if ($context == null) { $context = Context::getContext(); } // Product::getDefaultAttribute is only called if id_product_attribute is missing from the SQL query at the origin of it: // consider adding it in order to avoid unnecessary queries $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']); if (Combination::isFeatureActive() && (!isset($row['id_product_attribute']) || !$row['id_product_attribute']) && (isset($row['cache_default_attribute']) && ($ipa_default = $row['cache_default_attribute']) !== null || ($ipa_default = Product::getDefaultAttribute($row['id_product'], !$row['allow_oosp'])))) { $row['id_product_attribute'] = $ipa_default; } if (!Combination::isFeatureActive() || !isset($row['id_product_attribute'])) { $row['id_product_attribute'] = 0; } // Tax $usetax = Tax::excludeTaxeOption(); $cache_key = $row['id_product'] . '-' . $row['id_product_attribute'] . '-' . $id_lang . '-' . (int) $usetax; if (isset($row['id_product_pack'])) { $cache_key .= '-pack' . $row['id_product_pack']; } if (isset(self::$producPropertiesCache[$cache_key])) { return self::$producPropertiesCache[$cache_key]; } // Datas $row['category'] = Category::getLinkRewrite((int) $row['id_category_default'], (int) $id_lang); $row['link'] = $context->link->getProductLink((int) $row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']); $row['attribute_price'] = 0; if (isset($row['id_product_attribute']) && $row['id_product_attribute']) { $row['attribute_price'] = (double) Product::getProductAttributePrice($row['id_product_attribute']); } $row['price_tax_exc'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, self::$_taxCalculationMethod == PS_TAX_EXC ? 2 : 6); if (self::$_taxCalculationMethod == PS_TAX_EXC) { $row['price_tax_exc'] = Tools::ps_round($row['price_tax_exc'], 2); $row['price'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], false, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2, null, false, false); } else { $row['price'] = Tools::ps_round(Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 2), 2); $row['price_without_reduction'] = Product::getPriceStatic((int) $row['id_product'], true, isset($row['id_product_attribute']) && !empty($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, false); } $row['reduction'] = Product::getPriceStatic((int) $row['id_product'], (bool) $usetax, (int) $row['id_product_attribute'], 6, null, true, true, 1, true, null, null, null, $specific_prices); $row['specific_prices'] = $specific_prices; if ($row['id_product_attribute']) { $row['quantity_all_versions'] = $row['quantity']; $row['quantity'] = Product::getQuantity((int) $row['id_product'], $row['id_product_attribute'], isset($row['cache_is_pack']) ? $row['cache_is_pack'] : null); } else { $row['quantity'] = Product::getQuantity((int) $row['id_product']); } $row['id_image'] = Product::defineProductImage($row, $id_lang); $row['features'] = Product::getFrontFeaturesStatic((int) $id_lang, $row['id_product']); $row['attachments'] = array(); if (!isset($row['cache_has_attachments']) || $row['cache_has_attachments']) { $row['attachments'] = Product::getAttachmentsStatic((int) $id_lang, $row['id_product']); } $row['virtual'] = !isset($row['is_virtual']) || $row['is_virtual'] ? 1 : 0; // Pack management $row['pack'] = !isset($row['cache_is_pack']) ? Pack::isPack($row['id_product']) : (int) $row['cache_is_pack']; $row['packItems'] = $row['pack'] ? Pack::getItemTable($row['id_product'], $id_lang) : array(); $row['nopackprice'] = $row['pack'] ? Pack::noPackPrice($row['id_product']) : 0; if ($row['pack'] && !Pack::isInStock($row['id_product'])) { $row['quantity'] = 0; } self::$producPropertiesCache[$cache_key] = $row; return self::$producPropertiesCache[$cache_key]; }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit card') * @param string $message Message to attach to order */ public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false) { global $cart; $cart = new Cart((int) $id_cart); // Does order already exists ? if (!$this->active) { die(Tools::displayError()); } if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $cart->secure_key) { die(Tools::displayError()); } // Copying data from cart $order = new Order(); $order->id_carrier = (int) $cart->id_carrier; $order->id_customer = (int) $cart->id_customer; $order->id_address_invoice = (int) $cart->id_address_invoice; $order->id_address_delivery = (int) $cart->id_address_delivery; $vat_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency; $order->id_lang = (int) $cart->id_lang; $order->id_cart = (int) $cart->id; $customer = new Customer((int) $order->id_customer); $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key); $order->payment = $paymentMethod; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = (int) $cart->gift; $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $order->conversion_rate = $currency->conversion_rate; $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_shipping = (double) $cart->getOrderShippingCost(); $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } // Creating order if ($cart->OrderExists() == false) { $result = $order->add(); } else { $errorMessage = Tools::displayError('An order has already been placed using this cart.'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart)); die($errorMessage); } // Next ! if ($result and isset($order->id)) { if (!$secure_key) { $message .= $this->l('Warning : the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart); Product::addCustomizationPrice($products, $customizedDatas); $outOfStock = false; $store_all_taxes = array(); foreach ($products as $key => $product) { $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL); $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity']; if ($id_order_state != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('PS_OS_ERROR')) { if (Product::updateQuantity($product, (int) $order->id)) { $product['stock_quantity'] -= $product['cart_quantity']; } if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) { $outOfStock = true; } Product::updateDefaultAttribute($product['id_product']); } $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 2, NULL, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); /* Store tax info */ $id_country = (int) Country::getDefaultCountryId(); $id_state = 0; $id_county = 0; $rate = 0; $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}; $address_infos = Address::getCountryAndState($id_address); if ($address_infos['id_country']) { $id_country = (int) $address_infos['id_country']; $id_state = (int) $address_infos['id_state']; $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']); } $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county); // If its a freeOrder, there will be no calculation if ($order->total_products > 0) { // remove order discount quotepart on product price in order to obtain the real tax $ratio = $price / $order->total_products; $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio; $tmp_price = $price - $order_reduction_amount; foreach ($allTaxes as $res) { if (!isset($store_all_taxes[$res->id])) { $store_all_taxes[$res->id] = array(); $store_all_taxes[$res->id]['amount'] = 0; } $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang]; $store_all_taxes[$res->id]['rate'] = $res->rate; $unit_tax_amount = $tmp_price * ($res->rate * 0.01); $tmp_price = $tmp_price + $unit_tax_amount; $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity']; } } /* End */ // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = null; if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) { $productDownload = new ProductDownload((int) $id_product_download); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (!_PS_TAX_) { $product['tax'] = 0; $product['rate'] = 0; $tax_rate = 0; } else { $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $ecotaxTaxRate = 0; if (!empty($product['ecotax'])) { $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } $product_price = (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, false, false); $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100; if (!$group_reduction) { $group_reduction = (double) Group::getReduction((int) $order->id_customer); } $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']); $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0; $query .= '(' . (int) $order->id . ', ' . (int) $product['id_product'] . ', ' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . (int) $product['cart_quantity'] . ', ' . $quantityInStock . ', ' . $product_price . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ', ' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ', ' . $group_reduction . ', ' . $quantityDiscountValue . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\', ' . (double) $tax_rate . ', ' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ', ' . (double) $ecotaxTaxRate . ', ' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\'),'; $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][_CUSTOMIZE_FILE_])) { $customizationText .= count($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />'; } $customizationText .= '---<br />'; } $customizationText = rtrim($customizationText, '---<br />'); $customizationQuantity = (int) $product['customizationQuantityTotal']; $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : ' ') . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); /* Add carrier tax */ $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false); $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county); $nTax = 0; foreach ($allTaxes as $tax) { if (!isset($tax->id)) { continue; } if (!isset($store_all_taxes[$tax->id])) { $store_all_taxes[$tax->id] = array(); } if (!isset($store_all_taxes[$tax->id]['amount'])) { $store_all_taxes[$tax->id]['amount'] = 0; } $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang]; $store_all_taxes[$tax->id]['rate'] = $tax->rate; if (!$nTax++) { $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl; } else { $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01); } } /* Store taxes */ foreach ($store_all_taxes as $tax) { Db::getInstance()->Execute(' INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`) VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')'); } // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; $total_discount_value = 0; $shrunk = false; foreach ($discounts as $discount) { $objDiscount = new Discount((int) $discount['id_discount']); $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id); if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) { $shrunk = true; } if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) { $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value; if ($objDiscount->id_discount_type == 2 and $objDiscount->behavior_not_exhausted == 2) { $voucher = new Discount(); foreach ($objDiscount as $key => $discountValue) { $voucher->{$key} = $discountValue; } $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id; $voucher->value = (double) $value - $amount_to_add; $voucher->add(); $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); $params['{voucher_num}'] = $voucher->name; $params['{firstname}'] = $customer->firstname; $params['{lastname}'] = $customer->lastname; $params['{id_order}'] = $order->id; $params['{order_name}'] = sprintf("#%06d", (int) $order->id); @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $order->id), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $amount_to_add = $value; } $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add); $total_discount_value += $amount_to_add; if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED')) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId((int) $cart->id); if ($oldMessage) { $message = new Message((int) $oldMessage['id_message']); $message->id_order = (int) $order->id; $message->update(); } // Hook new order $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } } if (isset($outOfStock) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id); $new_history->addWithemail(true, $extraVars); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) { $invoice = new Address((int) $order->id_address_invoice); $delivery = new Address((int) $order->id_address_delivery); $carrier = new Carrier((int) $order->id_carrier, $order->id_lang); $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false; $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", (int) $order->id), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = null; } if (Validate::isEmail($customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } } $this->currentOrder = (int) $order->id; return true; } else { $errorMessage = Tools::displayError('Order creation failed'); Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart)); die($errorMessage); } } else { $errorMessage = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id)); die($errorMessage); } }
public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false) { parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop); $nb_items = count($this->_list); for ($i = 0; $i < $nb_items; ++$i) { $item =& $this->_list[$i]; if (Tools::isSubmit('ajax') && isset($item['id_order_detail'])) { // no details for this row $this->addRowActionSkipList('details', array($item['id_order_detail'])); if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $manager = StockManagerFactory::getManager(); $quantity_stock = (int) $manager->getProductRealQuantities((int) $item['product_id'], (int) $item['product_attribute_id'], null, true); } else { $quantity_stock = (int) Product::getQuantity((int) $item['product_id'], (int) $item['product_attribute_id']); } // ges stock level color $item['stock_level_color'] = ErpSupplyOrderClasses::getStockLevelColor($quantity_stock); } else { // add view link for each row $item['href_view_link'] = Tools::safeOutput('index.php?controller=AdminOrders&' . $this->identifier . '=' . $item['id_order'] . '&view' . $this->table . '&token=' . Tools::getAdminTokenLite('AdminOrders')); } } }
$header = array("Web page Number", "SKU Code", "Product Name", "MRP", "SELLING PRICE", "FULFILLMENT MODE", "COURIER TYPE", "Inventory", "Shipping Time in Days"); $cdata = tocsv($header) . "\n"; $number = 1; foreach ($res as $row) { $id_product = $row['id_product']; $product = new Product($id_product, true, 1); $data = array(); $data[] = $number++; $data[] = $product->reference; $data[] = $product->name; $data[] = ""; $data[] = (int) round(Tools::convertPrice($product->getPriceWithoutReduct(), 4)); $data[] = (int) round(Tools::convertPrice($product->getPrice(), 4)); $data[] = ""; $data[] = ""; $data[] = (int) Product::getQuantity($id_product); $data[] = (int) $product->shipping_sla; $cdata .= tocsv($data) . "\n"; } echo $cdata = str_replace("\r", "", $cdata); exit; function tocsv($data) { $line = ''; foreach ($data as $value) { if (!isset($value) || $value == "") { $value = ","; } else { $value = str_replace('"', '""', $value); $value = '"' . $value . '"' . ","; }
public function initFormQuantities($obj) { if (!$this->default_form_language) { $this->getLanguages(); } $data = $this->createTemplate($this->tpl_form); $data->assign('default_form_language', $this->default_form_language); if ($obj->id) { if ($this->product_exists_in_shop) { // Get all id_product_attribute $attributes = $obj->getAttributesResume($this->context->language->id); if (empty($attributes)) { $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => ''); } // Get available quantities $available_quantity = array(); $product_designation = array(); foreach ($attributes as $attribute) { // Get available quantity for the current product attribute in the current shop $available_quantity[$attribute['id_product_attribute']] = StockAvailable::getQuantityAvailableByProduct((int) $obj->id, $attribute['id_product_attribute']); // Get all product designation $product_designation[$attribute['id_product_attribute']] = rtrim($obj->name[$this->context->language->id] . ' - ' . $attribute['attribute_designation'], ' - '); } $show_quantities = true; $shop_context = Shop::getContext(); $shop_group = new ShopGroup((int) Shop::getContextShopGroupID()); // if we are in all shops context, it's not possible to manage quantities at this level if (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_ALL) { $show_quantities = false; } elseif (Shop::isFeatureActive() && $shop_context == Shop::CONTEXT_GROUP) { // if quantities are not shared between shops of the group, it's not possible to manage them at group level if (!$shop_group->share_stock) { $show_quantities = false; } } else { // if quantities are shared between shops of the group, it's not possible to manage them for a given shop if ($shop_group->share_stock) { $show_quantities = false; } } $data->assign('ps_stock_management', Configuration::get('PS_STOCK_MANAGEMENT')); $data->assign('has_attribute', $obj->hasAttributes()); // Check if product has combination, to display the available date only for the product or for each combination if (Combination::isFeatureActive()) { $data->assign('countAttributes', (int) Db::getInstance()->getValue('SELECT COUNT(id_product) FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int) $obj->id)); } else { $data->assign('countAttributes', false); } // if advanced stock management is active, checks associations $advanced_stock_management_warning = false; if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $obj->advanced_stock_management) { $p_attributes = Product::getProductAttributesIds($obj->id); $warehouses = array(); if (!$p_attributes) { $warehouses[] = Warehouse::getProductWarehouseList($obj->id, 0); } foreach ($p_attributes as $p_attribute) { $ws = Warehouse::getProductWarehouseList($obj->id, $p_attribute['id_product_attribute']); if ($ws) { $warehouses[] = $ws; } } $warehouses = Tools::arrayUnique($warehouses); if (empty($warehouses)) { $advanced_stock_management_warning = true; } } if ($advanced_stock_management_warning) { $this->displayWarning($this->l('If you wish to use the advanced stock management, you must:')); $this->displayWarning('- ' . $this->l('associate your products with warehouses.')); $this->displayWarning('- ' . $this->l('associate your warehouses with carriers.')); $this->displayWarning('- ' . $this->l('associate your warehouses with the appropriate shops.')); } $pack_quantity = null; // if product is a pack if (Pack::isPack($obj->id)) { $items = Pack::getItems((int) $obj->id, Configuration::get('PS_LANG_DEFAULT')); // gets an array of quantities (quantity for the product / quantity in pack) $pack_quantities = array(); foreach ($items as $item) { if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) { $pack_id_product_attribute = Product::getDefaultAttribute($item->id, 1); $pack_quantities[] = Product::getQuantity($item->id, $pack_id_product_attribute) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1); } } // gets the minimum if (count($pack_quantities)) { $pack_quantity = $pack_quantities[0]; foreach ($pack_quantities as $value) { if ($pack_quantity > $value) { $pack_quantity = $value; } } } if (!Warehouse::getPackWarehouses((int) $obj->id)) { $this->displayWarning($this->l('You must have a common warehouse between this pack and its product.')); } } $data->assign(array('attributes' => $attributes, 'available_quantity' => $available_quantity, 'pack_quantity' => $pack_quantity, 'stock_management_active' => Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'), 'product_designation' => $product_designation, 'product' => $obj, 'show_quantities' => $show_quantities, 'order_out_of_stock' => Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'token_preferences' => Tools::getAdminTokenLite('AdminPPreferences'), 'token' => $this->token, 'languages' => $this->_languages, 'id_lang' => $this->context->language->id)); } else { $this->displayWarning($this->l('You must save the product in this shop before managing quantities.')); } } else { $this->displayWarning($this->l('You must save this product before managing quantities.')); } $this->tpl_form_vars['custom_form'] = $data->fetch(); }
public function initContentForQuantities() { if ($this->object->id) { $tfowlgstly = "show_quantities"; ${"GLOBALS"}["ygzeqkb"] = "show_quantities"; $gmgclvkrjy = "attributes"; ${"GLOBALS"}["jhngqfjufp"] = "attributes"; $cggvbxsk = "attributes"; ${${"GLOBALS"}["jhngqfjufp"]} = $this->object->getAttributesResume($this->context->language->id); ${"GLOBALS"}["aofqmvff"] = "attribute"; ${"GLOBALS"}["vyyogyvfbtx"] = "attributes"; $nfdcluhk = "attributes"; $khzorwi = "shop_context"; if (empty(${$nfdcluhk})) { ${$cggvbxsk}[] = array("id_product_attribute" => 0, "attribute_designation" => ""); } ${"GLOBALS"}["klqbahrije"] = "shop_context"; ${${"GLOBALS"}["ldfuknydnzr"]} = array(); ${${"GLOBALS"}["ymshseez"]} = array(); ${"GLOBALS"}["lztnksxrb"] = "group_shop"; foreach (${${"GLOBALS"}["vyyogyvfbtx"]} as ${${"GLOBALS"}["aofqmvff"]}) { $rvrxkz = "product_designation"; $ycvvjwmxtnm = "attribute"; $dxuqsu = "available_quantity"; ${$dxuqsu}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = StockAvailable::getQuantityAvailableByProduct((int) $this->object->id, ${$ycvvjwmxtnm}["id_product_attribute"]); ${$rvrxkz}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = rtrim($this->object->name[$this->context->language->id] . " - " . ${${"GLOBALS"}["iixdipeiyldv"]}["attribute_designation"], " - "); } ${${"GLOBALS"}["ueicxl"]} = true; ${$khzorwi} = Shop::getContext(); ${${"GLOBALS"}["lztnksxrb"]} = $this->context->shop->getGroup(); $wktpughd = "pack_quantity"; ${"GLOBALS"}["eukvwdf"] = "advanced_stock_management_warning"; if (${${"GLOBALS"}["klqbahrije"]} == Shop::CONTEXT_ALL) { ${$tfowlgstly} = false; } elseif (${${"GLOBALS"}["ohyfjtkcy"]} == Shop::CONTEXT_GROUP) { if (!$group_shop->share_stock) { ${${"GLOBALS"}["ueicxl"]} = false; } } else { $eksumjgu = "show_quantities"; if ($group_shop->share_stock) { ${$eksumjgu} = false; } } self::$smarty->assign("ps_stock_management", Configuration::get("PS_STOCK_MANAGEMENT")); self::$smarty->assign("has_attribute", $this->object->hasAttributes()); if (Combination::isFeatureActive()) { self::$smarty->assign("countAttributes", (int) Db::getInstance()->getValue("SELECT COUNT(id_product) FROM " . _DB_PREFIX_ . "product_attribute WHERE id_product = " . (int) $this->object->id)); } ${${"GLOBALS"}["eukvwdf"]} = false; if (Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && $this->object->advanced_stock_management) { ${"GLOBALS"}["awunkp"] = "p_attributes"; ${"GLOBALS"}["qxobmbos"] = "warehouses"; ${"GLOBALS"}["cjtetqei"] = "warehouses"; $ukjfpwyojlf = "p_attribute"; ${${"GLOBALS"}["iczelyves"]} = Product::getProductAttributesIds($this->object->id); ${"GLOBALS"}["kcjlbgqb"] = "advanced_stock_management_warning"; ${"GLOBALS"}["dlsnuhn"] = "warehouses"; ${${"GLOBALS"}["qxobmbos"]} = array(); ${"GLOBALS"}["ojmjigmfve"] = "p_attributes"; if (!${${"GLOBALS"}["awunkp"]}) { ${${"GLOBALS"}["mdrvdmghqrtc"]}[] = Warehouse::getProductWarehouseList($this->object->id, 0); } foreach (${${"GLOBALS"}["ojmjigmfve"]} as ${$ukjfpwyojlf}) { ${"GLOBALS"}["uevlubu"] = "ws"; ${"GLOBALS"}["fpbyfow"] = "warehouses"; ${"GLOBALS"}["inddsyj"] = "ws"; ${${"GLOBALS"}["yrbmurnh"]} = Warehouse::getProductWarehouseList($this->object->id, ${${"GLOBALS"}["bhprusfblhn"]}["id_product_attribute"]); if (${${"GLOBALS"}["uevlubu"]}) { ${${"GLOBALS"}["fpbyfow"]}[] = ${${"GLOBALS"}["inddsyj"]}; } } ${${"GLOBALS"}["dlsnuhn"]} = array_unique(${${"GLOBALS"}["cjtetqei"]}); if (empty(${${"GLOBALS"}["mdrvdmghqrtc"]})) { ${${"GLOBALS"}["kcjlbgqb"]} = true; } } if (${${"GLOBALS"}["uucoxnutvd"]}) { $this->displayWarning($this->getMessage("If you wish to use the advanced stock management, you have to:")); $this->displayWarning("- " . $this->getMessage("associate your products with warehouses")); $this->displayWarning("- " . $this->getMessage("associate your warehouses with carriers")); $this->displayWarning("- " . $this->getMessage("associate your warehouses with the appropriate shops")); } ${${"GLOBALS"}["qbmqjuoutyh"]} = null; if (Pack::isPack($this->object->id)) { ${"GLOBALS"}["wdcmwsfvsft"] = "pack_quantity"; $mdjqucflf = "items"; ${${"GLOBALS"}["wfbswtei"]} = Pack::getItems((int) $this->object->id, Configuration::get("PS_LANG_DEFAULT")); $mhikkwxp = "pack_quantities"; ${"GLOBALS"}["kamnnzyptd"] = "pack_quantities"; ${${"GLOBALS"}["kamnnzyptd"]} = array(); foreach (${$mdjqucflf} as ${${"GLOBALS"}["gpnqjgaosuld"]}) { if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) { $gkwutr = "pack_id_product_attribute"; ${${"GLOBALS"}["wkyidmmlbbc"]} = Product::getDefaultAttribute($item->id, 1); ${${"GLOBALS"}["pnfrmcr"]}[] = Product::getQuantity($item->id, ${$gkwutr}) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1); } } $oissvbm = "pack_quantities"; ${${"GLOBALS"}["wdcmwsfvsft"]} = ${$oissvbm}[0]; foreach (${$mhikkwxp} as ${${"GLOBALS"}["kzwkbwmzgtl"]}) { ${"GLOBALS"}["iwrwjuvdmi"] = "value"; if (${${"GLOBALS"}["qbmqjuoutyh"]} > ${${"GLOBALS"}["iwrwjuvdmi"]}) { ${${"GLOBALS"}["qbmqjuoutyh"]} = ${${"GLOBALS"}["kzwkbwmzgtl"]}; } } if (!Warehouse::getPackWarehouses((int) $this->object->id)) { $this->displayWarning($this->getMessage("You must have a common warehouse between this pack and its product.")); } } ${${"GLOBALS"}["lixyhrpqnh"]} = new Language($this->id_language); self::$smarty->assign("iso_code", $lang->iso_code ? $lang->iso_code : "en"); self::$smarty->assign(array("attributes" => ${$gmgclvkrjy}, "available_quantity" => ${${"GLOBALS"}["ldfuknydnzr"]}, "pack_quantity" => ${$wktpughd}, "stock_management_active" => Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT"), "product_designation" => ${${"GLOBALS"}["ymshseez"]}, "show_quantities" => ${${"GLOBALS"}["ygzeqkb"]}, "order_out_of_stock" => Configuration::get("PS_ORDER_OUT_OF_STOCK"))); } else { $this->displayWarning($this->getMessage("You must save this product before managing quantities.")); } }
/** * Create an order detail liable to an id_order * @param object $order * @param object $cart * @param array $product * @param int $id_order_status * @param int $id_order_invoice * @param bool $use_taxes set to false if you don't want to use taxes */ protected function create(Order $order, Cart $cart, $product, $id_order_state, $id_order_invoice, $use_taxes = true, $id_warehouse = 0) { if ($use_taxes) { $this->tax_calculator = new TaxCalculator(); } $this->id = null; $this->product_id = (int) $product['id_product']; $this->product_attribute_id = $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : 0; $this->product_name = $product['name'] . (isset($product['attributes']) && $product['attributes'] != null ? ' - ' . $product['attributes'] : ''); $this->product_quantity = (int) $product['cart_quantity']; $this->product_ean13 = empty($product['ean13']) ? null : pSQL($product['ean13']); $this->product_upc = empty($product['upc']) ? null : pSQL($product['upc']); $this->product_reference = empty($product['reference']) ? null : pSQL($product['reference']); $this->product_supplier_reference = empty($product['supplier_reference']) ? null : pSQL($product['supplier_reference']); $this->product_weight = $product['id_product_attribute'] ? (double) $product['weight_attribute'] : (double) $product['weight']; $this->id_warehouse = $id_warehouse; $product_quantity = (int) Product::getQuantity($this->product_id, $this->product_attribute_id); $this->product_quantity_in_stock = $product_quantity - (int) $product['cart_quantity'] < 0 ? $product_quantity : (int) $product['cart_quantity']; $this->setVirtualProductInformation($product); $this->checkProductStock($product, $id_order_state); if ($use_taxes) { $this->setProductTax($order, $product); } $this->setShippingCost($order, $product); $this->setDetailProductPrice($order, $cart, $product); // Set order invoice id $this->id_order_invoice = (int) $id_order_invoice; // Set shop id $this->id_shop = (int) $product['id_shop']; // Add new entry to the table $this->save(); if ($use_taxes) { $this->saveTaxCalculator($order); } unset($this->tax_calculator); }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart Value * @param integer $id_order_state Value * @param float $amountPaid Amount really paid by customer (in the default currency) * @param string $paymentMethod Payment method (eg. 'Credit cart') * @param string $message Message to attach to order */ function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false) { global $cart; $cart = new Cart(intval($id_cart)); // Does order already exists ? if (Validate::isLoadedObject($cart) and $cart->OrderExists() === 0) { // Copying data from cart $order = new Order(); $order->id_carrier = intval($cart->id_carrier); $order->id_customer = intval($cart->id_customer); $order->id_address_invoice = intval($cart->id_address_invoice); $order->id_address_delivery = intval($cart->id_address_delivery); $vat_address = new Address(intval($order->id_address_delivery)); $id_zone = Address::getZoneById(intval($vat_address->id)); $order->id_currency = $currency_special ? intval($currency_special) : intval($cart->id_currency); $order->id_lang = intval($cart->id_lang); $order->id_cart = intval($cart->id); $customer = new Customer(intval($order->id_customer)); $order->secure_key = pSQL($customer->secure_key); $order->payment = Tools::substr($paymentMethod, 0, 32); if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $cart->recyclable; $order->gift = intval($cart->gift); $order->gift_message = $cart->gift_message; $currency = new Currency($order->id_currency); $amountPaid = !$dont_touch_amount ? Tools::ps_round(floatval($amountPaid), 2) : $amountPaid; $order->total_paid_real = $amountPaid; $order->total_products = floatval($cart->getOrderTotal(false, 1)); $order->total_products_wt = floatval($cart->getOrderTotal(true, 1)); $order->total_discounts = floatval(abs($cart->getOrderTotal(true, 2))); $order->total_shipping = floatval($cart->getOrderShippingCost()); $order->total_wrapping = floatval(abs($cart->getOrderTotal(true, 6))); $order->total_paid = floatval(Tools::ps_round(floatval($cart->getOrderTotal(true, 3)), 2)); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; // Amount paid by customer is not the right one -> Status = payment error if ($order->total_paid != $order->total_paid_real) { $id_order_state = _PS_OS_ERROR_; } // Creating order if ($cart->OrderExists() === 0) { $result = $order->add(); } else { die(Tools::displayError('An order has already been placed using this cart')); } // Next ! if ($result and isset($order->id)) { // Optional message to attach to this order if (isset($message) and !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (!Validate::isCleanHtml($message)) { $message = $this->l('Payment message is not valid, please check your module!'); } $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } // Insert products from cart into order_detail table $products = $cart->getProducts(); $productsList = ''; $db = Db::getInstance(); $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail` (`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `product_quantity_discount`, `product_ean13`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `discount_quantity_applied`, `download_deadline`, `download_hash`) VALUES '; $customizedDatas = Product::getAllCustomizedDatas(intval($order->id_cart)); Product::addCustomizationPrice($products, $customizedDatas); foreach ($products as $key => $product) { $outOfStock = false; $productQuantity = intval(Product::getQuantity(intval($product['id_product']), $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL)); $quantityInStock = $productQuantity - intval($product['cart_quantity']) < 0 ? $productQuantity : intval($product['cart_quantity']); if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) { if (($updateResult = Product::updateQuantity($product)) === false or $updateResult === -1) { $outOfStock = true; } if (!$outOfStock) { $product['stock_quantity'] -= $product['cart_quantity']; } Hook::updateQuantity($product, $order); } $price = Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 6, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery)); $price_wt = Product::getPriceStatic(intval($product['id_product']), true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery)); // Add some informations for virtual products $deadline = '0000-00-00 00:00:00'; $download_hash = NULL; if ($id_product_download = ProductDownload::getIdFromIdProduct(intval($product['id_product']))) { $productDownload = new ProductDownload(intval($id_product_download)); $deadline = $productDownload->getDeadLine(); $download_hash = $productDownload->getHash(); } // Exclude VAT if (Tax::excludeTaxeOption()) { $product['tax'] = 0; $product['rate'] = 0; $tax = 0; } else { $tax = Tax::getApplicableTax(intval($product['id_tax']), floatval($product['rate']), intval($order->id_address_delivery)); } $currentDate = date('Y-m-d H:m:i'); if ($product['reduction_from'] != $product['reduction_to'] and ($currentDate > $product['reduction_to'] or $currentDate < $product['reduction_from'])) { $reduction_percent = 0.0; $reduction_amount = 0.0; } else { $reduction_percent = floatval($product['reduction_percent']); $reduction_amount = Tools::ps_round(floatval($product['reduction_price']) / (1 + floatval($tax) / 100), 6); } // Quantity discount $reduc = 0.0; if ($product['cart_quantity'] > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($product['id_product'], $product['cart_quantity'])) { $reduc = QuantityDiscount::getValue($price_wt, $qtyD->id_discount_type, $qtyD->value, new Currency(intval($order->id_currency))); } $query .= '(' . intval($order->id) . ', ' . intval($product['id_product']) . ', ' . (isset($product['id_product_attribute']) ? intval($product['id_product_attribute']) : 'NULL') . ', \'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\', ' . intval($product['cart_quantity']) . ', ' . $quantityInStock . ', ' . floatval(Product::getPriceStatic(intval($product['id_product']), false, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, Product::getTaxCalculationMethod(intval($order->id_customer)) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, intval($order->id_customer), intval($order->id_cart), intval($order->id_address_delivery))) . ', ' . floatval($reduction_percent) . ', ' . floatval($reduction_amount) . ', ' . floatval($reduc) . ', ' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ', ' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ', ' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ', ' . floatval($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ', \'' . (!$tax ? '' : pSQL($product['tax'])) . '\', ' . floatval($tax) . ', ' . floatval($product['ecotax']) . ', ' . (int) QuantityDiscount::getDiscountFromQuantity(intval($product['id_product']), intval($product['cart_quantity'])) . ', \'' . pSQL($deadline) . '\', \'' . pSQL($download_hash) . '\'),'; $priceWithTax = number_format($price * (($tax + 100) / 100), 2, '.', ''); $customizationQuantity = 0; if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) { $customizationText = ''; foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) { foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) { $customizationText .= $text['name'] . $this->l(':') . ' ' . $text['value'] . ', '; } } } $customizationText = rtrim($customizationText, ', '); $customizationQuantity = intval($product['customizationQuantityTotal']); $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td> </tr>'; } if (!$customizationQuantity or intval($product['cart_quantity']) > $customizationQuantity) { $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false, false) . '</td> <td style="padding: 0.6em 0.4em; text-align: center;">' . (intval($product['cart_quantity']) - $customizationQuantity) . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice((intval($product['cart_quantity']) - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false, false) . '</td> </tr>'; } } // end foreach ($products) $query = rtrim($query, ','); $result = $db->Execute($query); // Insert discounts from cart into order_discount table $discounts = $cart->getDiscounts(); $discountsList = ''; foreach ($discounts as $discount) { $objDiscount = new Discount(intval($discount['id_discount'])); $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, 1), $order->total_shipping, $cart->id); $order->addDiscount($objDiscount->id, $objDiscount->name, $value); if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) { $objDiscount->quantity = $objDiscount->quantity - 1; } $objDiscount->update(); $discountsList .= '<tr style="background-color:#EBECEE;"> <td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td> <td style="padding: 0.6em 0.4em; text-align: right;">-' . Tools::displayPrice($value, $currency, false, false) . '</td> </tr>'; } // Specify order id for message $oldMessage = Message::getMessageByCartId(intval($cart->id)); if ($oldMessage) { $message = new Message(intval($oldMessage['id_message'])); $message->id_order = intval($order->id); $message->update(); } // Hook new order $orderStatus = new OrderState(intval($id_order_state)); if (Validate::isLoadedObject($orderStatus)) { Hook::newOrder($cart, $order, $customer, $currency, $orderStatus); foreach ($cart->getProducts() as $product) { if ($orderStatus->logable) { ProductSale::addProductSale(intval($product['id_product']), intval($product['cart_quantity'])); } } } if (isset($outOfStock) and $outOfStock) { $history = new OrderHistory(); $history->id_order = intval($order->id); $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, intval($order->id)); $history->addWithemail(); } // Set order state in order history ONLY even if the "out of stock" status has not been yet reached // So you migth have two order states $new_history = new OrderHistory(); $new_history->id_order = intval($order->id); $new_history->changeIdOrderState(intval($id_order_state), intval($order->id)); $new_history->addWithemail(true, $extraVars); // Send an e-mail to customer if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id) { $invoice = new Address(intval($order->id_address_invoice)); $delivery = new Address(intval($order->id_address_delivery)); $carrier = new Carrier(intval($order->id_carrier)); $delivery_state = $delivery->id_state ? new State(intval($delivery->id_state)) : false; $invoice_state = $invoice->id_state ? new State(intval($invoice->id_state)) : false; $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf("#%06d", intval($order->id)), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), intval($order->id_lang), 1), '{carrier}' => strval($carrier->name) != '0' ? $carrier->name : Configuration::get('PS_SHOP_NAME'), '{payment}' => $order->payment, '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false, false)); if (is_array($extraVars)) { $data = array_merge($data, $extraVars); } // Join PDF invoice if (intval(Configuration::get('PS_INVOICE')) and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) { $fileAttachment['content'] = PDF::invoice($order, 'S'); $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', intval($order->id_lang)) . sprintf('%06d', $order->invoice_number) . '.pdf'; $fileAttachment['mime'] = 'application/pdf'; } else { $fileAttachment = NULL; } if ($orderStatus->send_email and Validate::isEmail($customer->email)) { Mail::Send(intval($order->id_lang), 'order_conf', 'Order confirmation', $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment); } $this->currentOrder = intval($order->id); return true; } $this->currentOrder = intval($order->id); return true; } else { die(Tools::displayError('Order creation failed')); } } else { die(Tools::displayError('An order has already been placed using this cart')); } }
/** * @param Product $product to get the product properties * @param array $combination to get particular properties from a declination * @param int $lang id lang to take all text in good language * @param Link $link to set the link of the product and its images. * @param Carrier $carrier not used now, but usable for next version, needed for calculate the shipping cost, * But for now it's not sure enough. * @return array with good value for the XML. */ private function preparedValues(Product $product, $combination, $lang, Link $link, Carrier $carrier) { $arr_return = array(); $str_features = array(); $model = array(); $version = str_replace('.', '', _PS_VERSION_); // To build description and model tags. if (isset($combination['attributes'])) { foreach ($combination['attributes'] as $attribut) { $str_features[] = $attribut['group_name'] . ' : ' . $attribut['name']; $model[] = $attribut['name']; } } if (isset($combination['weight']) && (int) $combination['weight'] !== 0) { $str_features[] = 'weight : ' . $combination['weight']; } elseif ($product->weight !== 0) { $str_features[] = 'weight : ' . $product->weight; } $features = $product->getFrontFeatures($lang); foreach ($features as $feature) { $str_features[] = $feature['name'] . ' : ' . $feature['value']; } // Category tag $category = new Category((int) $product->id_category_default, $lang); $category_path = (isset($category->id) and $category->id) ? Tools::getFullPath((int) $category->id, $product->name[$lang]) : Tools::getFullPath((int) $product->id_category_default, $product->name[$lang]); $category_path = Configuration::get('PS_NAVIGATION_PIPE') != false && Configuration::get('PS_NAVIGATION_PIPE') !== '>' ? str_replace(Configuration::get('PS_NAVIGATION_PIPE'), '>', $category_path) : $category_path; // image tag $id_image = isset($combination['id_image']) ? $combination['id_image'] : 0; if ($id_image === 0 || $id_image < 0) { $image = $product->getCover((int) $product->id); $id_image = $image['id_image']; } $quantity = Product::getQuantity($product->id, isset($combination['id_combination']) ? $combination['id_combination'] : NULL); $condition = ''; if (strlen((string) $version) < 2) { $version = (string) $version . '0'; } if ((int) substr($version, 0, 2) >= 14) { $condition = $product->condition === 'new' ? 0 : 1; } $price = $product->getPrice(true, isset($combination['id_combination']) ? $combination['id_combination'] : NULL, 2); $upc_ean = strlen((string) $product->ean13) == 13 ? $product->ean13 : ''; $arr_return['product_url'] = $link->getProductLink((int) $product->id, $product->link_rewrite[$lang], $product->ean13, $lang); $arr_return['designation'] = Tools::htmlentitiesUTF8($product->name[$lang] . ' ' . Manufacturer::getNameById($product->id_manufacturer) . ' ' . implode(' ', $model)); $arr_return['price'] = $price; $arr_return['category'] = Tools::htmlentitiesUTF8(strip_tags($category_path)); if (substr(_PS_VERSION_, 0, 3) == '1.3') { if (!Configuration::get('PS_SHOP_DOMAIN')) { Configuration::updateValue('PS_SHOP_DOMAIN', $_SERVER['HTTP_HOST']); } $prefix = 'http://' . Configuration::get('PS_SHOP_DOMAIN') . '/'; $arr_return['image_url'] = $prefix . $link->getImageLink('', $product->id . '-' . $id_image, 'large'); } else { $arr_return['image_url'] = $link->getImageLink($product->link_rewrite[$lang], $product->id . '-' . $id_image, 'large'); } // Must description added since Twenga-module v1.1 $arr_return['description'] = is_array($product->description) ? strip_tags($product->description[$lang]) : strip_tags($product->description); $arr_return['description'] = trim($arr_return['description'] . ' ' . strip_tags(implode(', ', $str_features))); $arr_return['description'] = Tools::htmlentitiesUTF8($arr_return['description']); $arr_return['brand'] = Manufacturer::getNameById($product->id_manufacturer); $arr_return['merchant_id'] = $product->id; $arr_return['manufacturer_id'] = $product->id_manufacturer; $arr_return['shipping_cost'] = 'NC'; $arr_return['in_stock'] = $quantity > 0 ? 'Y' : 'N'; $arr_return['stock_detail'] = $quantity; $arr_return['condition'] = $condition; $arr_return['upc_ean'] = $upc_ean; $arr_return['eco_tax'] = $product->ecotax; // for prestashop 1.4 and previous version these fields are not managed. // So default values are set. $arr_return['product_type'] = '1'; $arr_return['isbn'] = ''; return $arr_return; }
<?php require_once 'autoload.php'; $p = new Product('da', 5); $c = new Car(); $p->addQuantity(2); $c->addQuantity(1); var_dump($p->getQuantity(), $c->getQuantity()); $per = new Person('Mr', 'Bean'); var_dump($per->getNameFromTrait(), $per->getName());
/** * Formatage des informations produit pour NetEven. * @param $t_product * @param bool $display * @return array */ private function getPropertiesForNetEven($products, $display = false) { if (!sizeof($products)) { return false; } global $cookie, $link; if (!$link) { $link = new Link(); } $products_temp = array(); $compteur_product_no_ean13 = 0; $compteur_product_no_ref = 0; foreach ($products as $product) { $product_reference = 'P' . $product['id_product']; if (!empty($product['id_product_attribute'])) { $product_reference = 'D' . $product['id_product_attribute']; } if (self::$type_sku == 'reference') { $product_reference = $product['product_reference']; if (!empty($product['id_product_attribute'])) { $product_reference = $product['product_attribute_reference']; } } $ean_ps = !empty($product['ean13_declinaison']) ? $product['ean13_declinaison'] : $product['ean13']; $codeEan = ""; if (!empty($ean_ps)) { $codeEan = sprintf('%013s', $ean_ps); } $id_product_attribute = NULL; if (!empty($product['id_product_attribute'])) { $id_product_attribute = (int) $product['id_product_attribute']; } $product_price = Product::getPriceStatic((int) $product['id_product'], true, (int) $id_product_attribute, 2, NULL, false, true); $product_price_without_reduction = Product::getPriceStatic((int) $product['id_product'], true, (int) $id_product_attribute, 2, NULL, false, false); $categories = $this->getProductCategories($product); $categories = array_reverse($categories); $classification = str_replace('//', '', implode('/', $categories)); $quantity = Product::getQuantity((int) $product['id_product'], !empty($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : NULL); $indice = count($products_temp); $weight = $product['weight']; if (!empty($id_product_attribute)) { $weight += $product['weight_product_attribute']; } $products_temp[$indice] = array('Title' => $product['name'], 'SKU' => $product_reference, 'Description' => strip_tags($product['description']), 'EAN' => $codeEan, 'Quantity' => $quantity, 'PriceFixed' => $product_price_without_reduction, 'PriceRetail' => $product_price, 'Etat' => 11, 'SKUFamily' => self::$type_sku == 'reference' ? $product['declinaison_default_ref'] : $product['declinaison_default'], 'Classification' => str_replace('Accueil/', '', $classification), 'shipping_delay' => $this->getValue('shipping_delay'), 'Comment' => $this->getValue('comment'), 'Height' => $product['height'], 'Width' => $product['width'], 'Depth' => $product['depth'], 'Weight' => $weight, 'Brand' => !empty($product['name_manufacturer']) ? $product['name_manufacturer'] : $this->getValue('default_brand')); $id_lang = isset($cookie->id_lang) ? (int) $cookie->id_lang : (int) Configuration::get('PS_LANG_DEFAULT'); $sql = 'SELECT t.name FROM ' . _DB_PREFIX_ . 'product_tag pt INNER JOIN ' . _DB_PREFIX_ . 'tag t ON (pt.id_tag = t.id_tag AND t.id_lang = ' . intval($id_lang) . ') WHERE pt.id_product = ' . intval($product['id_product']); $t_tags_bdd = Db::getInstance()->ExecuteS($sql); if ($t_tags_bdd && count($t_tags_bdd) > 0) { $t_tags_final = array(); foreach ($t_tags_bdd as $t_tag_bdd) { $t_tags_final[] = $t_tag_bdd['name']; } $products_temp[$indice]["Keywords"] = implode(',', $t_tags_final); } //shipping part $shipping_price_local = $this->getValue('shipping_price_local'); if (self::$shipping_by_product && !empty(self::$shipping_by_product_fieldname)) { $shipping_price_local = $product[self::$shipping_by_product_fieldname]; } $carrier_france = $this->getConfig('SHIPPING_CARRIER_FRANCE'); $carrier_zone_france = $this->getConfig('SHIPPING_ZONE_FRANCE'); if (!empty($carrier_france) && !empty($carrier_zone_france)) { $products_temp[$indice]['PriceShippingLocal1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_france, $carrier_zone_france); } elseif (!empty($shipping_price_local)) { $products_temp[$indice]['PriceShippingLocal1'] = $shipping_price_local; } $shipping_price_inter = $this->getValue('shipping_price_international'); $carrier_inter = $this->getConfig('SHIPPING_CARRIER_INTERNATIONAL'); $carrier_zone_inter = $this->getConfig('SHIPPING_ZONE_INTERNATIONAL'); if (!empty($carrier_france) && !empty($carrier_zone_france)) { $products_temp[$indice]['PriceShippingInt1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_inter, $carrier_zone_inter); } elseif (!empty($shipping_price_inter)) { $products_temp[$indice]['PriceShippingInt1'] = $shipping_price_inter; } if (!empty($carrier_france) && !empty($carrier_zone_france)) { $products_temp[$indice]['PriceShippingInt1'] = $this->getShippingPrice($product['id_product'], $id_product_attribute, $carrier_inter, $carrier_zone_inter); } $images = $this->getProductImages($product); foreach ($images as $key => $image) { if (is_object($link)) { $img_url = $link->getImageLink($product['link_rewrite'], (int) $product['id_product'] . '-' . (int) $image['id_image'], Gateway::getConfig('IMAGE_TYPE_NAME')); $products_temp[$indice]['Image' . ($key + 1)] = 'http://' . str_replace('http://', '', $img_url); } } // Attributes and fetures of product $category_default = new Category((int) $product['id_category_default'], (int) $cookie->id_lang); $products_temp[$indice]['ArrayOfSpecificFields'] = array(); $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => 'categorie', 'Value' => $category_default->name); $sql = ' SELECT GROUP_CONCAT(DISTINCT CONCAT(fl.`name`," {##} ",fvl.`value`) SEPARATOR "' . pSQL($this->getValue('separator')) . ' ") as feature_name FROM `' . _DB_PREFIX_ . 'feature_product` fp LEFT JOIN `' . _DB_PREFIX_ . 'feature_value_lang` fvl ON (fp.`id_feature_value` = fvl.`id_feature_value` AND fvl.id_lang=' . (int) $cookie->id_lang . ') LEFT JOIN `' . _DB_PREFIX_ . 'feature_value` fv ON (fv.`id_feature_value` = fvl.`id_feature_value`) LEFT JOIN `' . _DB_PREFIX_ . 'feature_lang` fl ON (fl.`id_feature` = fv.`id_feature` AND fl.`id_lang`=' . (int) $cookie->id_lang . ') WHERE fp.`id_product` = ' . (int) $product['id_product'] . ' '; $product['feature_name'] = Db::getInstance()->getValue($sql); if (empty($product['attribute_name']) && empty($product['feature_name'])) { continue; } $features_attributes = array(); if (!empty($product['attribute_name'])) { $features_attributes = explode($this->getValue('separator'), $product['attribute_name']); } if (!empty($product['feature_name'])) { $features_attributes = array_merge($features_attributes, explode($this->getValue('separator'), $product['feature_name'])); } $feature_links = $this->getValue('feature_links'); foreach ($features_attributes as $value) { $infos = explode(' {##} ', $value); if (count($infos) == 2 && !empty($infos[0]) && !empty($infos[1]) && !empty($feature_links[trim($infos[0])])) { $specific_name = $feature_links[trim($infos[0])]; $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => $specific_name, 'Value' => $infos[1]); } } if (count(self::$customizable_field) > 0) { foreach (self::$customizable_field as $key => $value) { $products_temp[$indice]['ArrayOfSpecificFields'][] = array('Name' => $key, 'Value' => $value); } } } return $products_temp; }
/** * Updates a product on Prestashop. * * @param array $product_attributes * @param integer $id_product * @param string $url_photo * @param array $triple_cod_col_siz * @param integer $language * @param array $array_combinations * @return array * @see $this->isOldNameProductEgualToNewNameProduct * @see $this->isOldOrNewValueForProduct * @see $this->controlCategoriesForActivateTheir * @see $this->updateCombinantionsForPrestashop * */ public function updateProductForPrestashop($product_attributes = array(), $id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language = 1) { $product = new Product($id_product); $is_change_product = false; $new_name_product = trim($product_attributes["Nome"]); if (!$this->isOldNameProductEgualToNewNameProduct($product->name, $new_name_product)) { $product->name = $this->setArrayElementForLinkRewrite($new_name_product, true, $language); $product->meta_keywords = $new_name_product; $product->link_rewrite = $this->setArrayElementForLinkRewrite($new_name_product, false, $language); $is_change_product = true; } $new_price = (double) $product_attributes["Prezzo"]; if (!$this->isOldOrNewValueForProduct((double) $product->price, $new_price)) { $product->price = $new_price; $is_change_product = true; } $new_active = (int) $product_attributes["Attivo"]; $control_category = $this->isOldOrNewValueForProduct((int) $product->active, $new_active); if (!$control_category) { $product->active = $new_active; $is_change_product = true; } $new_minimal_quantity = (int) $product_attributes["Qta_min"]; if (!$this->isOldOrNewValueForProduct((int) $product->minimal_quantity, $new_minimal_quantity)) { $product->minimal_quantity = $new_minimal_quantity; $is_change_product = true; } $new_quantity = (int) $product_attributes["Qta"]; if (!$this->isOldOrNewValueForProduct((int) $product->getQuantity($id_product), $new_quantity)) { StockAvailable::setQuantity($id_product, 0, $new_quantity); } $array_old_features = $product->getFeatures(); $array_features = $product_attributes["Feature"]; $height = false; $width = false; foreach ($array_old_features as $array_old_single_features) { $feature = new FeatureCore((int) $array_old_single_features['id_feature']); $tmp_feature = $feature->name; $single_old_feature = $tmp_feature[$language]; $feature_value = new FeatureValueCore((int) $array_old_single_features["id_feature_value"]); $tmp_feature_value = $feature_value->value; $single_old_feature_value = $tmp_feature_value[$language]; if ($this->isOldOrNewValueForProduct("Altezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Altezza"] . " cm")) { $feature_value->value = array($language => $array_features["Altezza"] . " cm"); $feature_value->update(); $height = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Larghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Larghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Larghezza"] . " cm"); $feature_value->update(); $width = true; $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Lunghezza", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Lunghezza"] . " cm")) { $feature_value->value = array($language => $array_features["Lunghezza"] . " cm"); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Modello", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Modello"])) { $feature_value->value = array($language => $array_features["Modello"]); $feature_value->update(); $is_change_product = true; } } if ($this->isOldOrNewValueForProduct("Linea", $single_old_feature)) { if (!$this->isOldOrNewValueForProduct($single_old_feature_value, $array_features["Linea"])) { $feature_value->value = array($language => $array_features["Linea"]); $feature_value->update(); $is_change_product = true; } } } if ($height) { $product->height = (double) $array_features["Altezza"]; $is_change_product = true; } if ($width) { $product->width = (double) $array_features["Larghezza"]; $is_change_product = true; } if ($is_change_product) { $product->update(); } if (!$control_category) { $ids_categories_array = $product->getWsCategories(); $this->controlCategoriesForActivateTheir($ids_categories_array); } $change_new_image = $this->updateCombinantionsForPrestashop($id_product, $url_photo, $triple_cod_col_siz, $array_combinations, $language); $string_triple = array(); $return = array(); array_push($return, $product->id); $array_images_combinations_of_the_product = $product->getImages($language); $element = array(); foreach ($array_images_combinations_of_the_product as $array_combo_image) { $name_of_the_image = $array_combo_image['legend']; $id_image_of_the_product = $array_combo_image['id_image']; array_push($element, $id_image_of_the_product . ";" . $name_of_the_image); } array_push($return, $element); foreach ($change_new_image as $array_combo_image) { $fetch_tmp = explode(";", $array_combo_image); $fetch_jpg = explode(".jpg", $fetch_tmp[1]); $fetch_image_name = explode(",", $fetch_jpg[0]); array_push($string_triple, $fetch_image_name[2]); } array_push($return, $change_new_image); array_push($return, $string_triple); return $return; }