Example #1
0
$id_category = 4;
$sql = "select cp.id_product from ps_category_product cp  \n                        inner join ps_product p on p.id_product = cp.id_product\n                        inner join temp on temp.code = p.reference\n                        where id_category = {$id_category} and p.active = 1 and p.quantity > 0 and p.is_exclusive = 1 and cp.id_product in (select t1.id_product  from (select cp.id_product from ps_category_product cp inner join ps_product p on p.id_product = cp.id_product inner join temp on temp.code = p.reference where id_category = {$id_category} and p.active = 1 and p.quantity > 0 and p.is_exclusive = 1 and is_customizable = 0) t1 left join ( select distinct id_product from ps_flipkart_feed_product_info) t2 on t1.id_product = t2.id_product where t2.id_product is NULL)";
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
$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";
foreach ($res as $row) {
    $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 = '';
Example #2
0
        }
        $doc->product_link = $productObj->getLink();
        $idImage = $productObj->getCoverWs();
        if ($idImage) {
            $idImage = $productObj->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $thickbox_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'thickbox');
        $large_image = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
        $id_manufacturer = $productObj->id_manufacturer;
        $manufacturer = '';
        if (!empty($id_manufacturer)) {
            $manufacturer = Manufacturer::getNameById($id_manufacturer);
        }
        $productRec = array($id_product, $productObj->reference, $productObj->supplier_reference, $productObj->name, $productObj->getLink(), $productObj->getPriceWithoutReduct(), round($productObj->getPrice()), round($mrp_in_rs), round($offer_price_in_rs), strip_tags($productObj->description), '0', $availability, $manufacturer, $category, $categories, $color, $fabric, (int) $productObj->active === 1 ? 'ACTIVE' : 'INACTIVE', $quantity, $productObj->shipping_sla, $productObj->is_customizable, $large_image, $thickbox_image, date('Y-m-d', strtotime($productObj->date_add)));
        $images = $productObj->getImages(1);
        foreach ($images as $image) {
            $oImage = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'thickbox');
            if ($thickbox_image !== $oImage) {
                array_push($productRec, $oImage);
            }
        }
        //echo '"'.implode($productRec,'","').'"';
        //echo PHP_EOL;
        fputcsv($outstream, $productRec, ',', '"');
        ob_flush();
        flush();
    }
    fclose($outstream);
} elseif (Tools::getValue('getPartnerProducts')) {
Example #3
0
function addProducts($client, $ids = array())
{
    //update currency
    // update_currency();
    $default_tz = date_default_timezone_get();
    date_default_timezone_set('UTC');
    $category = new Category(1, 1);
    $sql = "select p.id_product, DATEDIFF(NOW(), p.`date_add`) as 'age'\n            from ps_product p\n            where p.price > 0 and p.active = 1";
    $productScores = array();
    $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($products as $product) {
        $productScores[$product['id_product']] = array('age' => $product['age'], 'week_sold' => 0, 'month_sales' => 0, 'year_sales' => 0);
    }
    $sql = "select p.`id_product`, sum(od.product_quantity) as 'quantity'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 \n            and p.active = 1\n            and o.date_add > now() - INTERVAL 7 DAY\n            group by p.id_product";
    $week_quantities = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($week_quantities as $week_quantity) {
        $productScores[$week_quantity['id_product']]['week_sold'] = $week_quantity['quantity'];
    }
    $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'month_revenue'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 and p.active = 1\n            and o.date_add > now() - INTERVAL 30 DAY\n            group by p.id_product";
    $month_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($month_sales as $month_sale) {
        $productScores[$month_sale['id_product']]['month_sales'] = $month_sale['month_revenue'];
    }
    $sql = "select p.`id_product`, round(sum(od.product_quantity * od.product_price * 55 / o.`conversion_rate`)) as 'year_revenue'\n            from `ps_product` p\n            inner join `ps_order_detail` od on od.product_id = p.id_product\n            inner join ps_orders o on o.id_order = od.id_order\n            where p.price > 0 and p.active = 1\n            and o.date_add > now() - INTERVAL 365 DAY\n            group by p.id_product";
    $year_sales = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
    foreach ($year_sales as $year_sale) {
        $productScores[$year_sale['id_product']]['year_sales'] = $year_sale['year_revenue'];
    }
    foreach ($products as $product) {
        $productScores[$product['id_product']]['score'] = getWeekSalesScore($productScores[$product['id_product']]['week_sold']) + getAgeScore($productScores[$product['id_product']]['age']) + getMonthScore($productScores[$product['id_product']]['month_sales']) + getYearScore($productScores[$product['id_product']]['year_sales']);
    }
    $docs = array();
    $link = new Link();
    $count = 0;
    $update = $client->createUpdate();
    foreach ($products as $product) {
        if (!empty($ids) && !in_array((int) $product['id_product'], $ids)) {
            continue;
        }
        $productObj = new Product((int) $product['id_product'], true, 1);
        print_r('\\n' . 'reindexing ' . $product['id_product']);
        if (!$productObj->active) {
            deleteProduct($productObj->id, $client);
            continue;
        }
        $doc = $update->createDocument();
        $doc->id_product = $productObj->id;
        $doc->reference = $productObj->reference;
        $doc->name = $productObj->name;
        $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description);
        $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
        $doc->brand_id = $productObj->id_manufacturer;
        $doc->brand_name = $productObj->manufacturer_name;
        $doc->style_tips = $productObj->description_short;
        $doc->alphaNameSort = $productObj->name;
        $dbresult = $productObj->getWsCategories();
        $catIds = array();
        foreach ($dbresult as $catIdRow) {
            $catIds[] = $catIdRow['id'];
        }
        $category_names = array();
        foreach ($catIds as $catID) {
            $category = new Category((int) $catID);
            $category_names[] = $category->getName(1);
        }
        $doc->cat_name = $category_names;
        $doc->cat_id = $catIds;
        $doc->tags = $productObj->getTags(1);
        $doc->shipping_sla = $productObj->shipping_sla ? $productObj->shipping_sla : 0;
        $doc->weight = $productObj->weight ? $productObj->weight : 0.5;
        if (isset($productObj->work_type)) {
            $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : '');
        }
        if (isset($productObj->garment_type)) {
            $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : '');
        }
        if (isset($productObj->blouse_length)) {
            $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : '';
        }
        $doc->height = $productObj->height;
        $doc->width = $productObj->width;
        $atributeQty = Attribute::getAttributeQty($productObj->id);
        if ($productObj->quantity > 0 || $atributeQty > 0) {
            $doc->inStock = true;
        } else {
            $doc->inStock = false;
        }
        $doc->isPlusSize = $productObj->is_plussize ? true : false;
        $doc->isRTS = $productObj->is_rts ? true : false;
        $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0);
        //Indian Price
        $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID);
        $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4);
        $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID);
        if ($doc->mrp_in > $doc->offer_price_in) {
            $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100);
        }
        //Worldwide Price
        $doc->offer_price = $productObj->getPrice();
        $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4);
        $doc->mrp = $productObj->getPriceWithoutReduct();
        if ($doc->mrp > $doc->offer_price) {
            $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100);
        }
        $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add);
        $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z");
        $doc->product_link = $productObj->getLink();
        $idImage = $productObj->getCoverWs();
        if ($idImage) {
            $idImage = $productObj->id . '-' . $idImage;
        } else {
            $idImage = Language::getIsoById(1) . '-default';
        }
        $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list');
        $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium');
        $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
        $images = $productObj->getImages(1);
        $productImages = array();
        foreach ($images as $k => $image) {
            $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large');
        }
        $doc->image_links = $productImages;
        $doc->sales = $productScores[$product['id_product']]['score'];
        $productObj->fabric = trim($productObj->fabric);
        $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric);
        $doc->fabric = strtolower($productObj->fabric);
        $doc->is_customizable = $productObj->is_customizable;
        if (isset($productObj->generic_color) && !empty($productObj->generic_color)) {
            $colors = explode(',', $productObj->generic_color);
            $indexed_colors = array();
            foreach ($colors as $color) {
                $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color)));
            }
            $doc->color = $indexed_colors;
        }
        if (isset($productObj->stone) && !empty($productObj->stone)) {
            $stones = explode(',', $productObj->stone);
            $indexed_stones = array();
            foreach ($stones as $stone) {
                $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone)));
            }
            $doc->stone = $indexed_stones;
        }
        if (isset($productObj->plating) && !empty($productObj->plating)) {
            $platings = explode(',', $productObj->plating);
            $indexed_platings = array();
            foreach ($platings as $plating) {
                $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating)));
            }
            $doc->plating = $indexed_platings;
        }
        if (isset($productObj->material) && !empty($productObj->material)) {
            $materials = explode(',', $productObj->material);
            $indexed_materials = array();
            foreach ($materials as $material) {
                $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material)));
            }
            $doc->material = $indexed_materials;
        }
        if (isset($productObj->look) && !empty($productObj->look)) {
            $looks = explode(',', $productObj->look);
            $indexed_looks = array();
            foreach ($looks as $look) {
                $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look)));
            }
            $doc->look = $indexed_looks;
        }
        if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) {
            $handbag_occasions = explode(',', $productObj->handbag_occasion);
            $indexed_handbag_occasions = array();
            foreach ($handbag_occasions as $handbag_occasion) {
                $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion)));
            }
            $doc->handbag_occasion = $indexed_handbag_occasions;
        }
        if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) {
            $handbag_styles = explode(',', $productObj->handbag_style);
            $indexed_handbag_styles = array();
            foreach ($handbag_styles as $handbag_style) {
                $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style)));
            }
            $doc->handbag_style = $indexed_handbag_styles;
        }
        if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) {
            $handbag_materials = explode(',', $productObj->handbag_material);
            $indexed_handbag_materials = array();
            foreach ($handbag_materials as $handbag_material) {
                $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material)));
            }
            $doc->handbag_material = $indexed_handbag_materials;
        }
        $combinaisons = $productObj->getAttributeCombinaisons(1);
        $indexed_sizes = array();
        foreach ($combinaisons as $k => $combinaison) {
            if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') {
                $indexed_sizes[] = $combinaison['attribute_name'];
            }
        }
        $doc->size = $indexed_sizes;
        $doc->cashback_percentage = $productObj->cashback_percentage;
        $docs[] = $doc;
        if (++$count == 300) {
            $update->addDocuments($docs);
            $result = $client->update($update);
            echo 'Update query executed' . PHP_EOL;
            echo 'Query status: ' . $result->getStatus() . PHP_EOL;
            echo 'Query time: ' . $result->getQueryTime() . PHP_EOL;
            $count = 0;
            $docs = array();
            $update = $client->createUpdate();
        }
    }
    $update->addDocuments($docs);
    date_default_timezone_set($default_tz);
    $result = $client->update($update);
    $sql = "update ps_product set indexed = 1 where indexed = 0";
    Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
Example #4
0
//$db = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
$id_category = 2;
$sql = "select cp.id_product from ps_category_product cp  \n                        inner join ps_product p on p.id_product = cp.id_product\n                        inner join temp on temp.code = p.reference\n                        where id_category = {$id_category} and p.active = 1 and p.quantity > 0 and p.is_exclusive = 1 and cp.id_product in (select t1.id_product  from (select cp.id_product from ps_category_product cp inner join ps_product p on p.id_product = cp.id_product inner join temp on temp.code = p.reference where id_category = {$id_category} and p.active = 1 and p.quantity > 0 and p.is_exclusive = 1 ) t1 left join ( select distinct id_product from ps_flipkart_feed_product_info) t2 on t1.id_product = t2.id_product where t2.id_product is NULL)";
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
$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 = ",";
Example #5
0
 public function prepareFeed()
 {
     $this->echomsg("Start - New Feed Preparation");
     // select all EXLUSIVE products added since the last feed
     $sql = $this->getProductsSQL();
     //echo $sql; exit;
     $products = $this->db->ExecuteS($sql);
     //print_r($products);
     if (count($products) === 0) {
         $this->echomsg("No New Products pending to be added");
         $this->echomsg("End - Feed Preparation");
         return;
     }
     //Prepare SKUs
     $skus = $this->getSKUs($products);
     $this->echomsg("SKUs Count");
     $this->echomsg(count($skus));
     $prepareFeed = false;
     $atleastOneFailed = false;
     $atleastOneProdFailed = false;
     $atleastOnePriceFailed = false;
     $atleastOneInvFailed = false;
     $atleastOneImageFailed = false;
     $atleastOneProdSuccess = false;
     $atleastOnePriceSuccess = false;
     $atleastOneInvSuccess = false;
     $atleastOneImageSuccess = false;
     $newProductsAdded = array();
     foreach ($skus as &$sku) {
         $id_product = $sku["id_product"];
         $id_sku = $sku['id_sku'];
         $this->echomsg("Working on SKU #{$id_sku}");
         $is_parent = $sku["is_parent"];
         $has_children = empty($sku["attribute"]) ? false : true;
         $size = empty($sku["attribute"]) ? "One Size" : $sku["attribute"]["attribute_name"];
         $force_inactive = isset($sku['inactive']) && (int) $sku['inactive'] === 1 ? true : false;
         $priceData = null;
         $inventoryData = null;
         $imageDataArray = null;
         $amazonProduct = null;
         $deleted = false;
         $delete_list = array();
         $build_relationship_feed = false;
         $allSubFeedsSuccess = true;
         $divaProduct = new Product($id_product, true, 1);
         $this->echomsg("SKU #{$id_sku} - Start");
         //check to see if the product is on amazon already
         $sql = "select * from ps_affiliate_feed_product_info where id_sku = '{$id_sku}'";
         // $sql = "select * from ps_affiliate_feed_product_info where id_sku = 'ID-58709'";
         $res = $this->db->getRow($sql);
         if ($is_parent === false && $has_children === false) {
             $new_price = (int) round($divaProduct->getPriceWithoutReduct());
             $new_specific_price = (int) round($divaProduct->getAffiliatePrice($this->id_affiliate));
             $new_quantity = (int) Product::getQuantity($id_product);
         } else {
             if ($is_parent) {
                 $new_price = (int) round($divaProduct->getPriceWithoutReduct());
                 $new_specific_price = (int) round($divaProduct->getAffiliatePrice($this->id_affiliate));
                 $new_quantity = (int) Product::getQuantity($id_product);
             } else {
                 $new_price = (int) round($divaProduct->getPriceWithoutReduct(false, $sku['attribute']['id_product_attribute']));
                 $new_specific_price = (int) round($divaProduct->getAffiliatePrice($this->id_affiliate, true, $sku['attribute']['id_product_attribute']));
                 $new_quantity = (int) Product::getQuantity($id_product, $sku['attribute']['id_product_attribute']);
                 $build_relationship_feed = true;
             }
         }
         if (!empty($res)) {
             $new_shipping_sla = (int) $divaProduct->shipping_sla;
             $new_active = (int) $divaProduct->active;
             if ($force_inactive) {
                 $new_active = 0;
             }
             $new_exclusive = (int) $divaProduct->is_exclusive;
             $old_price = (int) $res['price'];
             $old_specific_price = (int) $res['specific_price'];
             $old_quantity = (int) $res['quantity'];
             $old_shipping_sla = (int) $res['shipping_sla'];
             $old_active = (int) $res['active'];
             $old_exclusive = (int) $res['exclusive'];
             if ($new_exclusive === 0) {
                 $this->echomsg("SKU #{$id_sku} - ... Preparing Delete product");
                 $this->initMainFeed();
                 $id_fp = MarketplaceWebService_DB::newFeedProduct($this->id_feed, $id_product, $id_sku);
                 $this->initSubFeed(MarketplaceWebService_DB::$PRODUCT_FEED);
                 $op_type = 'D';
                 $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_prod_feed, $id_product, $id_sku, $op_type);
                 try {
                     $amazonProduct = $this->getDeleteObj($divaProduct, $sku);
                     MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                     $atleastOneProdSuccess = true;
                     $deleted = true;
                     $this->echomsg("SKU #{$id_sku} - ... Success");
                     $sql = "delete from ps_affiliate_feed_product_info where id_sku = '{$id_sku}'";
                     array_push($delete_list, "{$id_sku}");
                     $this->db->ExecuteS($sql);
                 } catch (Exception $ex) {
                     MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                     $atleastOneProdFailed = true;
                     $allSubFeedsSuccess = false;
                     $this->echomsg("SKU #{$id_sku} - ... Failed");
                 }
             } else {
                 $change = false;
                 if ($new_active === 0 || $new_quantity < 1) {
                     //make product quantity 0 (inactive on amazon)
                     $this->echomsg("SKU #{$id_sku} - ... Preparing Inventory Feed(Quantity 0)");
                     $this->initMainFeed();
                     $id_fp = MarketplaceWebService_DB::newFeedProduct($this->id_feed, $id_product, $id_sku);
                     $this->initSubFeed(MarketplaceWebService_DB::$INVENTORY_FEED);
                     $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_inv_feed, $id_product, $id_sku);
                     try {
                         $inventoryData = $this->getInventoryObj($divaProduct, $sku, $new_quantity, $new_shipping_sla, true);
                         $date_upd = date('Y-m-d H:i:s');
                         $sql = "update ps_affiliate_feed_product_info set quantity = {$new_quantity},active = {$new_active},date_upd = '{$date_upd}' where id_sku = '{$id_sku}'";
                         $this->db->ExecuteS($sql);
                         MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                         $atleastOneInvSuccess = true;
                         $this->echomsg("SKU #{$id_sku} - ... Success");
                     } catch (Exception $ex) {
                         MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                         $allSubFeedsSuccess = false;
                         $atleastOneInvFailed = true;
                         $this->echomsg("SKU #{$id_sku} - ... Failed");
                     }
                     $change = true;
                 }
                 $make_active = false;
                 if ($old_active === 0 && $new_active === 1) {
                     $make_active = true;
                 }
                 if ($make_active || $old_price !== $new_price || $old_specific_price !== $new_specific_price || $old_quantity !== $new_quantity || $old_shipping_sla !== $new_shipping_sla) {
                     // Price and Inventory data on Amazon should be updated
                     $this->initMainFeed();
                     $id_fp = MarketplaceWebService_DB::newFeedProduct($this->id_feed, $id_product, $id_sku);
                     if ($old_price !== $new_price || $old_specific_price !== $new_specific_price) {
                         $this->echomsg("SKU #{$id_sku} - ... Preparing Price Feed");
                         $this->echomsg("SKU #{$new_specific_price} - ...new specific price");
                         $this->initSubFeed(MarketplaceWebService_DB::$PRICE_FEED);
                         $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_price_feed, $id_product, $id_sku);
                         try {
                             $priceData = $this->getPriceObj($divaProduct, $sku, $new_price, $new_specific_price);
                             $date_upd = date('Y-m-d H:i:s');
                             $sql = "update ps_affiliate_feed_product_info set price ='{$new_price}',specific_price='{$new_specific_price}', date_upd='{$date_upd}' where id_sku = '{$id_sku}'";
                             $this->db->ExecuteS($sql);
                             MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                             $atleastOnePriceSuccess = true;
                             $this->echomsg("SKU #{$id_sku} - ... Success");
                         } catch (Exception $ex) {
                             $allSubFeedsSuccess = false;
                             $atleastOnePriceFailed = true;
                             MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                             $this->echomsg("SKU #{$id_sku} - ... Failed");
                         }
                     }
                     if ($make_active || $old_quantity !== $new_quantity || $old_shipping_sla !== $new_shipping_sla) {
                         $this->echomsg("SKU #{$id_sku} - ... Preparing Inventory Feed");
                         $this->initSubFeed(MarketplaceWebService_DB::$INVENTORY_FEED);
                         $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_inv_feed, $id_product, $id_sku);
                         try {
                             $inventoryData = $this->getInventoryObj($divaProduct, $sku, $new_quantity, $new_shipping_sla);
                             $date_upd = date('Y-m-d H:i:s');
                             if ($make_active) {
                                 $csql = ",active = 1";
                             } else {
                                 $csql = "";
                             }
                             $sql = "update ps_affiliate_feed_product_info set quantity = {$new_quantity}, shipping_sla = {$new_shipping_sla} {$csql}, date_upd='{$date_upd}' where id_sku = '{$id_sku}'";
                             $this->db->ExecuteS($sql);
                             MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                             $atleastOneInvSuccess = true;
                             $this->echomsg("SKU #{$id_sku} - ... Success");
                         } catch (Exception $ex) {
                             MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                             $allSubFeedsSuccess = false;
                             $atleastOneInvFailed = true;
                             $this->echomsg("SKU #{$id_sku} - ... Failed");
                         }
                     }
                     $change = true;
                 }
                 if (!$change) {
                     $this->echomsg("SKU #{$id_sku} - ... No change in price and inventory - skip");
                     $this->echomsg("SKU #{$id_sku} - End");
                     continue;
                 }
             }
         } else {
             //this product is not on amazon - push full feed
             //   if( (((int)$divaProduct->active) === 0) || (((int)$divaProduct->is_exclusive) === 0) || ($divaProduct->quantity < 1) ) {
             if ((int) $divaProduct->active === 0 || (int) $divaProduct->is_exclusive === 0) {
                 $this->echomsg("SKU #{$id_sku} - ... Not Active or Not Exclusive product");
                 $this->echomsg("SKU #{$id_sku} - End");
                 continue;
             }
             $this->initMainFeed();
             $id_fp = MarketplaceWebService_DB::newFeedProduct($this->id_feed, $id_product, $id_sku);
             try {
                 $this->echomsg("SKU #{$id_sku} - ... Preparing Product Feed");
                 $this->initSubFeed(MarketplaceWebService_DB::$PRODUCT_FEED);
                 $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_prod_feed, $id_product, $id_sku);
                 $amazonProduct = $this->getProductObj($divaProduct, $sku);
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                 $atleastOneProdSuccess = true;
                 $this->echomsg("SKU #{$id_sku} - ... Success");
             } catch (Exception $ex) {
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                 $allSubFeedsSuccess = false;
                 $atleastOneProdFailed = true;
                 $this->echomsg("SKU #{$id_sku} - ... Failed");
             }
             try {
                 $this->echomsg("SKU #{$id_sku} - ... Preparing Image Feed");
                 $this->initSubFeed(MarketplaceWebService_DB::$IMAGE_FEED);
                 $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_image_feed, $id_product, $id_sku);
                 $imageDataArray = $this->getImageObj($divaProduct, $sku);
                 if (count($imageDataArray) === 0) {
                     throw new Exception("No Image(s) available for this Product");
                 }
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                 $atleastOneImageSuccess = true;
                 $this->echomsg("SKU #{$id_sku} - ... Success");
             } catch (Exception $ex) {
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                 $allSubFeedsSuccess = false;
                 $atleastOneImageFailed = true;
                 $this->echomsg("SKU #{$id_sku} - ... Failed");
             }
             $price = null;
             $specific_price = null;
             try {
                 $this->echomsg("SKU #{$id_sku} - ... Preparing Price Feed");
                 $this->initSubFeed(MarketplaceWebService_DB::$PRICE_FEED);
                 $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_price_feed, $id_product, $id_sku);
                 $priceData = $this->getPriceObj($divaProduct, $sku, $price, $specific_price);
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                 $atleastOnePriceSuccess = true;
                 $this->echomsg("SKU #{$id_sku} - ... Success");
             } catch (Exception $ex) {
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                 $allSubFeedsSuccess = false;
                 $atleastOnePriceFailed = true;
                 $this->echomsg("SKU #{$id_sku} - ... Failed");
             }
             $quantity = null;
             $shipping_sla = null;
             try {
                 $this->echomsg("SKU #{$id_sku} - ... Preparing Inventory Feed");
                 $this->initSubFeed(MarketplaceWebService_DB::$INVENTORY_FEED);
                 $id_sfp = MarketplaceWebService_DB::newSubFeedProduct($this->id_inv_feed, $id_product, $id_sku);
                 $inventoryData = $this->getInventoryObj($divaProduct, $sku, $quantity, $shipping_sla);
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
                 $atleastOneInvSuccess = true;
                 $this->echomsg("SKU #{$id_sku} - ... Success");
             } catch (Exception $ex) {
                 MarketplaceWebService_DB::updateSubFeedProduct($id_sfp, MarketplaceWebService_DB::$STATUS_PREP_FAILED, $ex->getMessage());
                 $allSubFeedsSuccess = false;
                 $atleastOneInvFailed = true;
                 $this->echomsg("SKU #{$id_sku} - ... Failed");
             }
             if ($allSubFeedsSuccess) {
                 if (!in_array($id_product, $newProductsAdded)) {
                     array_push($newProductsAdded, $id_product);
                 }
                 //Make a note that this product is on amazon
                 $date_add = date('Y-m-d H:i:s');
                 $date_upd = date('Y-m-d H:i:s');
                 $sql = "insert into ps_affiliate_feed_product_info(id_product, id_sku, price, specific_price, quantity, shipping_sla, active, exclusive, date_add, date_upd) \n                        values({$id_product}, '{$id_sku}',{$price},{$specific_price},{$quantity}, {$shipping_sla},1,1,'{$date_add}','{$date_upd}')";
                 $this->db->ExecuteS($sql);
             }
         }
         if ($allSubFeedsSuccess) {
             if ($amazonProduct !== null) {
                 $this->initFeedObject('Product');
                 if ($deleted) {
                     $this->productFeed->addProduct($amazonProduct, 'Delete');
                 } else {
                     $this->productFeed->addProduct($amazonProduct);
                 }
             }
             if ($inventoryData !== null) {
                 $this->initFeedObject('Inventory');
                 $this->inventoryFeed->addInventory($inventoryData);
             }
             if ($priceData !== null) {
                 $this->initFeedObject('Price');
                 $this->priceFeed->addPrice($priceData);
             }
             if ($imageDataArray !== null) {
                 $this->initFeedObject('ProductImage');
                 foreach ($imageDataArray as $imageData) {
                     $this->imageFeed->addImage($imageData);
                 }
             }
             MarketplaceWebService_DB::updateFeedProduct($id_fp, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
             $prepareFeed = true;
             $this->echomsg("SKU #{$id_sku} - ... All Feeds Success");
         } else {
             //Atleast one feed failed for this product
             //Do not push this product into XML Feed
             $atleastOneFailed = true;
             MarketplaceWebService_DB::updateFeedProduct($id_fp, MarketplaceWebService_DB::$STATUS_PREP_FAILED);
             $this->echomsg("SKU #{$id_sku} - ... Atleast One Feed Failed");
         }
         $this->echomsg("SKU #{$id_sku} - End");
         unset($divaProduct);
     }
     // End foreach products
     $id = time() . date('Y-m-d');
     if ($prepareFeed) {
         $data = array();
         //Prepare Feed Files
         if ($this->productFeed instanceof MarketplaceWebService_XML_Feed_Product) {
             $productFeedFile = "xmlfeeds/products-{$id}.xml";
             $this->productFeed->save($productFeedFile);
             $data['feed_file'] = $productFeedFile;
             if ($atleastOneProdFailed) {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_PARTIAL_SUCCESS;
             } else {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_SUCCESS;
             }
             MarketplaceWebService_DB::updateSubFeedStatus($this->id_prod_feed, $data);
         }
         if ($this->priceFeed instanceof MarketplaceWebService_XML_Feed_Price) {
             $priceFeedFile = "xmlfeeds/products-price-{$id}.xml";
             $this->priceFeed->save($priceFeedFile);
             $data['feed_file'] = $priceFeedFile;
             if ($atleastOnePriceFailed) {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_PARTIAL_SUCCESS;
             } else {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_SUCCESS;
             }
             MarketplaceWebService_DB::updateSubFeedStatus($this->id_price_feed, $data);
         }
         if ($this->inventoryFeed instanceof MarketplaceWebService_XML_Feed_Inventory) {
             $inventoryFeedFile = "xmlfeeds/products-inventory-{$id}.xml";
             $this->inventoryFeed->save($inventoryFeedFile);
             $data['feed_file'] = $inventoryFeedFile;
             if ($atleastOneInvFailed) {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_PARTIAL_SUCCESS;
             } else {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_SUCCESS;
             }
             MarketplaceWebService_DB::updateSubFeedStatus($this->id_inv_feed, $data);
         }
         if ($this->imageFeed instanceof MarketplaceWebService_XML_Feed_Image) {
             $imageFeedFile = "xmlfeeds/products-images-{$id}.xml";
             $this->imageFeed->save($imageFeedFile);
             $data['feed_file'] = $imageFeedFile;
             if ($atleastOneImageFailed) {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_PARTIAL_SUCCESS;
             } else {
                 $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_SUCCESS;
             }
             MarketplaceWebService_DB::updateSubFeedStatus($this->id_image_feed, $data);
         }
         if ($atleastOneFailed) {
             MarketplaceWebService_DB::updateFeedStatus($this->id_feed, MarketplaceWebService_DB::$STATUS_PREP_PARTIAL_SUCCESS);
         } else {
             MarketplaceWebService_DB::updateFeedStatus($this->id_feed, MarketplaceWebService_DB::$STATUS_PREP_SUCCESS);
         }
     } else {
         MarketplaceWebService_DB::updateFeedStatus($this->id_feed, MarketplaceWebService_DB::$STATUS_PREP_FAILED);
         MarketplaceWebService_DB::updateSubFeedStatus($this->id_prod_feed, array('status' => MarketplaceWebService_DB::$STATUS_PREP_FAILED));
         MarketplaceWebService_DB::updateSubFeedStatus($this->id_price_feed, array('status' => MarketplaceWebService_DB::$STATUS_PREP_FAILED));
         MarketplaceWebService_DB::updateSubFeedStatus($this->id_inv_feed, array('status' => MarketplaceWebService_DB::$STATUS_PREP_FAILED));
         MarketplaceWebService_DB::updateSubFeedStatus($this->id_image_feed, array('status' => MarketplaceWebService_DB::$STATUS_PREP_FAILED));
     }
     //If applicable, build relationship for this SKU
     if (count($newProductsAdded) > 0) {
         foreach ($newProductsAdded as $id_product) {
             $csql = "select id_product, id_sku from ps_affiliate_feed_product_info where id_product = {$id_product}";
             $cres = $this->db->ExecuteS($csql);
             if (count($cres) > 1) {
                 $id_parent_sku = null;
                 $child_skus = array();
                 foreach ($cres as $res) {
                     $id_parent_sku = "ID-" . $res['id_product'];
                     $id_sku = $res['id_sku'];
                     if ($id_parent_sku !== $id_sku) {
                         array_push($child_skus, $id_sku);
                     }
                 }
                 $relationshipData = null;
                 $this->echomsg("SKU #{$id_parent_sku} - ... Preparing Relationship Feed");
                 if ($id_parent_sku !== null && count($child_skus) > 0) {
                     $relationshipData = $this->getRelationshipObj($id_parent_sku, $child_skus);
                 }
                 $this->echomsg("SKU #{$id_parent_sku} - ... Success");
                 if ($relationshipData !== null) {
                     $this->initFeedObject('Relationship');
                     $this->relFeed->addRelationship($relationshipData);
                 }
             }
         }
         if ($this->relFeed instanceof MarketplaceWebService_XML_Feed_Relationship) {
             $this->initSubFeed(MarketplaceWebService_DB::$RELATIONSHIP_FEED);
             $relFeedFile = "xmlfeeds/products-relationship-{$id}.xml";
             $this->relFeed->save($relFeedFile);
             $data['feed_file'] = $relFeedFile;
             $data['status'] = MarketplaceWebService_DB::$STATUS_PREP_SUCCESS;
             MarketplaceWebService_DB::updateSubFeedStatus($this->id_rel_feed, $data);
         }
     }
     $n = false;
     //Notify all the updates
     $mail_text = "";
     if (count($delete_list)) {
         $n = true;
     }
     $mail_text .= "<h1>Deleted List</h1>";
     $mail_text .= "<ul><li>" . implode("</li><li>", $delete_list) . "</li></ul>";
     $mail_text .= "<h1>Updated List</h1>";
     $sql = "select id_sku, price, specific_price,quantity, shipping_sla,active, exclusive from ps_affiliate_feed_product_info where date_upd > '" . $this->date_res['last_date_add'] . "' order by id_sku desc";
     $skus = $this->db->ExecuteS($sql);
     $mail_text .= '<table border="1" style="border-collapse: collapse;">';
     $mail_text .= '<tr>';
     $mail_text .= '<td>SKU</td>';
     $mail_text .= '<td>Price</td>';
     $mail_text .= '<td>Discount Price</td>';
     $mail_text .= '<td>Quantity</td>';
     $mail_text .= '<td>Shipping SLA</td>';
     $mail_text .= '<td>Active</td>';
     $mail_text .= '<td>Exclusive</td>';
     $mail_text .= '</tr>';
     foreach ($skus as $u) {
         $n = true;
         $mail_text .= '<tr>';
         $mail_text .= '<td>' . $u['id_sku'] . '</td>';
         $mail_text .= '<td>' . $u['price'] . '</td>';
         $mail_text .= '<td>' . $u['specific_price'] . '</td>';
         $mail_text .= '<td>' . $u['quantity'] . '</td>';
         $mail_text .= '<td>' . $u['shipping_sla'] . '</td>';
         $mail_text .= '<td>' . $u['active'] . '</td>';
         $mail_text .= '<td>' . $u['exclusive'] . '</td>';
         $mail_text .= '</tr>';
     }
     $mail_text .= '</table>';
     $mail_text .= "<h1>New Additions</h1>";
     $sql = "select id_sku, price, specific_price,quantity, shipping_sla,active, exclusive from ps_affiliate_feed_product_info where date_add > '" . $this->date_res['last_date_add'] . "' order by id_sku desc";
     $skus = $this->db->ExecuteS($sql);
     $mail_text .= '<table border="1" style="border-collapse: collapse;">';
     $mail_text .= '<tr>';
     $mail_text .= '<td>SKU</td>';
     $mail_text .= '<td>Price</td>';
     $mail_text .= '<td>Discount Price</td>';
     $mail_text .= '<td>Quantity</td>';
     $mail_text .= '<td>Shipping SLA</td>';
     $mail_text .= '<td>Active</td>';
     $mail_text .= '<td>Exclusive</td>';
     $mail_text .= '</tr>';
     foreach ($skus as $u) {
         $n = true;
         $mail_text .= '<tr>';
         $mail_text .= '<td>' . $u['id_sku'] . '</td>';
         $mail_text .= '<td>' . $u['price'] . '</td>';
         $mail_text .= '<td>' . $u['specific_price'] . '</td>';
         $mail_text .= '<td>' . $u['quantity'] . '</td>';
         $mail_text .= '<td>' . $u['shipping_sla'] . '</td>';
         $mail_text .= '<td>' . $u['active'] . '</td>';
         $mail_text .= '<td>' . $u['exclusive'] . '</td>';
         $mail_text .= '</tr>';
     }
     $mail_text .= '</table>';
     if ($n) {
         $templateVars = array('event' => 'Amazon Stock Sync Updates', 'description' => $mail_text);
         @Mail::Send(1, 'alert', Mail::l('Amazon Stock Sync Update'), $templateVars, array("*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"), null, '*****@*****.**', 'Indusdiva Monitoring', NULL, NULL, _PS_MAIL_DIR_, false);
     }
 }
Example #6
0
 /**
  * Assign template vars related to page content.
  *
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     if (!$this->errors) {
         if (Pack::isPack((int) $this->product->id) && !Pack::isInStock((int) $this->product->id)) {
             $this->product->quantity = 0;
         }
         $this->product->description = $this->transformDescriptionWithImg($this->product->description);
         $priceDisplay = Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer);
         $productPrice = 0;
         $productPriceWithoutReduction = 0;
         if (!$priceDisplay || $priceDisplay == 2) {
             $productPrice = $this->product->getPrice(true, null, 6);
             $productPriceWithoutReduction = $this->product->getPriceWithoutReduct(false, null);
         } elseif ($priceDisplay == 1) {
             $productPrice = $this->product->getPrice(false, null, 6);
             $productPriceWithoutReduction = $this->product->getPriceWithoutReduct(true, null);
         }
         if (Tools::isSubmit('submitCustomizedData')) {
             // If cart has not been saved, we need to do it so that customization fields can have an id_cart
             // We check that the cookie exists first to avoid ghost carts
             if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
                 $this->context->cart->add();
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
             $this->pictureUpload();
             $this->textRecord();
         } elseif (Tools::getIsset('deletePicture') && !$this->context->cart->deleteCustomizationToProduct($this->product->id, Tools::getValue('deletePicture'))) {
             $this->errors[] = $this->trans('An error occurred while deleting the selected picture.', array(), 'Shop.Notifications.Error');
         }
         $pictures = array();
         $text_fields = array();
         if ($this->product->customizable) {
             $files = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_FILE, true);
             foreach ($files as $file) {
                 $pictures['pictures_' . $this->product->id . '_' . $file['index']] = $file['value'];
             }
             $texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
             foreach ($texts as $text_field) {
                 $text_fields['textFields_' . $this->product->id . '_' . $text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
             }
         }
         $this->context->smarty->assign(array('pictures' => $pictures, 'textFields' => $text_fields));
         $this->product->customization_required = false;
         $customization_fields = $this->product->customizable ? $this->product->getCustomizationFields($this->context->language->id) : false;
         if (is_array($customization_fields)) {
             foreach ($customization_fields as &$customization_field) {
                 if ($customization_field['type'] == 0) {
                     $customization_field['key'] = 'pictures_' . $this->product->id . '_' . $customization_field['id_customization_field'];
                 } elseif ($customization_field['type'] == 1) {
                     $customization_field['key'] = 'textFields_' . $this->product->id . '_' . $customization_field['id_customization_field'];
                 }
             }
             unset($customization_field);
         }
         // Assign template vars related to the category + execute hooks related to the category
         $this->assignCategory();
         // Assign template vars related to the price and tax
         $this->assignPriceAndTax();
         // Assign attributes combinations to the template
         $this->assignAttributesCombinations();
         // Pack management
         $pack_items = Pack::isPack($this->product->id) ? Pack::getItemTable($this->product->id, $this->context->language->id, true) : array();
         $assembler = new ProductAssembler($this->context);
         $presenter = new ProductListingPresenter(new ImageRetriever($this->context->link), $this->context->link, new PriceFormatter(), new ProductColorsRetriever(), $this->getTranslator());
         $presentationSettings = $this->getProductPresentationSettings();
         $presentedPackItems = array();
         foreach ($pack_items as $item) {
             $presentedPackItems[] = $presenter->present($this->getProductPresentationSettings(), $assembler->assembleProduct($item), $this->context->language);
         }
         $this->context->smarty->assign('packItems', $presentedPackItems);
         $this->context->smarty->assign('noPackPrice', $this->product->getNoPackPrice());
         $this->context->smarty->assign('displayPackPrice', $pack_items && $productPrice < $this->product->getNoPackPrice() ? true : false);
         $this->context->smarty->assign('packs', Pack::getPacksTable($this->product->id, $this->context->language->id, true, 1));
         $accessories = $this->product->getAccessories($this->context->language->id);
         if (is_array($accessories)) {
             foreach ($accessories as &$accessory) {
                 $accessory = $presenter->present($presentationSettings, Product::getProductProperties($this->context->language->id, $accessory, $this->context), $this->context->language);
             }
             unset($accessory);
         }
         if ($this->product->customizable) {
             $customization_datas = $this->context->cart->getProductCustomization($this->product->id, null, true);
         }
         $product_for_template = $this->getTemplateVarProduct();
         $this->context->smarty->assign(array('priceDisplay' => $priceDisplay, 'productPriceWithoutReduction' => $productPriceWithoutReduction, 'customizationFields' => $customization_fields, 'id_customization' => empty($customization_datas) ? null : $customization_datas[0]['id_customization'], 'accessories' => $accessories, 'product' => $product_for_template, 'displayUnitPrice' => !empty($this->product->unity) && $this->product->unit_price_ratio > 0.0 ? true : false, 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, $this->context->language->id)));
         // Assign attribute groups to the template
         $this->assignAttributesGroups($product_for_template);
     }
 }
Example #7
0
 /**
  * @param Solarium_Query_Update $update
  * @param Link $link
  * @param Product $productObj
  * @return Solarium_Document_ReadWrite
  */
 private static function getProductDoc($update, $link, $productObj)
 {
     $doc = $update->createDocument();
     $doc->id_product = $productObj->id;
     $doc->reference = $productObj->reference;
     $doc->name = $productObj->name;
     //$doc->description = $productObj->description;
     $doc->description = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description);
     $doc->description_short = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
     $doc->brand_id = $productObj->id_manufacturer;
     $doc->brand_name = $productObj->manufacturer_name;
     $doc->style_tips = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->description_short);
     $doc->alphaNameSort = $productObj->name;
     $dbresult = $productObj->getWsCategories();
     $catIds = array();
     foreach ($dbresult as $catIdRow) {
         $catIds[] = $catIdRow['id'];
     }
     $category_names = array();
     foreach ($catIds as $catID) {
         $category = new Category((int) $catID);
         $category_names[] = $category->getName(1);
     }
     $doc->cat_name = $category_names;
     $doc->cat_id = $catIds;
     $doc->tags = $productObj->getTags(1);
     $doc->shipping_sla = $productObj->shipping_sla;
     $doc->weight = $productObj->weight ? $productObj->weight : 0.5;
     $doc->cashback_percentage = $productObj->cashback_percentage;
     if (isset($productObj->work_type)) {
         $doc->work_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->work_type ? $productObj->work_type : '');
     }
     if (isset($productObj->garment_type)) {
         $doc->garment_type = preg_replace('@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@', ' ', $productObj->garment_type ? $productObj->garment_type : '');
     }
     if (isset($productObj->blouse_length)) {
         $doc->blouse_length = $productObj->blouse_length ? $productObj->blouse_length : '';
     }
     $doc->height = $productObj->height;
     $doc->width = $productObj->width;
     $atributeQty = Attribute::getAttributeQty($productObj->id);
     if ($productObj->quantity > 0 || $atributeQty > 0) {
         $doc->inStock = true;
     } else {
         $doc->inStock = false;
     }
     $doc->isPlusSize = $productObj->is_plussize ? true : false;
     $doc->isRTS = $productObj->is_rts ? true : false;
     $doc->quantity = $productObj->quantity ? $productObj->quantity : ($atributeQty ? $atributeQty : 0);
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $productObj->date_add);
     $doc->date_add = $date->format("Y-m-d\\TG:i:s\\Z");
     $productObj->fabric = trim($productObj->fabric);
     $productObj->fabric = preg_replace('/\\s+/', '-', $productObj->fabric);
     $doc->fabric = strtolower($productObj->fabric);
     $doc->is_customizable = $productObj->is_customizable;
     if (isset($productObj->generic_color) && !empty($productObj->generic_color)) {
         $colors = explode(',', $productObj->generic_color);
         $indexed_colors = array();
         foreach ($colors as $color) {
             $indexed_colors[] = strtolower(preg_replace('/\\s+/', '-', trim($color)));
         }
         $doc->color = $indexed_colors;
     }
     if (isset($productObj->stone) && !empty($productObj->stone)) {
         $stones = explode(',', $productObj->stone);
         $indexed_stones = array();
         foreach ($stones as $stone) {
             $indexed_stones[] = strtolower(preg_replace('/\\s+/', '-', trim($stone)));
         }
         $doc->stone = $indexed_stones;
     }
     if (isset($productObj->plating) && !empty($productObj->plating)) {
         $platings = explode(',', $productObj->plating);
         $indexed_platings = array();
         foreach ($platings as $plating) {
             $indexed_platings[] = strtolower(preg_replace('/\\s+/', '-', trim($plating)));
         }
         $doc->plating = $indexed_platings;
     }
     if (isset($productObj->material) && !empty($productObj->material)) {
         $materials = explode(',', $productObj->material);
         $indexed_materials = array();
         foreach ($materials as $material) {
             $indexed_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($material)));
         }
         $doc->material = $indexed_materials;
     }
     if (isset($productObj->look) && !empty($productObj->look)) {
         $looks = explode(',', $productObj->look);
         $indexed_looks = array();
         foreach ($looks as $look) {
             $indexed_looks[] = strtolower(preg_replace('/\\s+/', '-', trim($look)));
         }
         $doc->look = $indexed_looks;
     }
     if (isset($productObj->handbag_occasion) && !empty($productObj->handbag_occasion)) {
         $handbag_occasions = explode(',', $productObj->handbag_occasion);
         $indexed_handbag_occasions = array();
         foreach ($handbag_occasions as $handbag_occasion) {
             $indexed_handbag_occasions[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_occasion)));
         }
         $doc->handbag_occasion = $indexed_handbag_occasions;
     }
     if (isset($productObj->handbag_style) && !empty($productObj->handbag_style)) {
         $handbag_styles = explode(',', $productObj->handbag_style);
         $indexed_handbag_styles = array();
         foreach ($handbag_styles as $handbag_style) {
             $indexed_handbag_styles[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_style)));
         }
         $doc->handbag_style = $indexed_handbag_styles;
     }
     if (isset($productObj->handbag_material) && !empty($productObj->handbag_material)) {
         $handbag_materials = explode(',', $productObj->handbag_material);
         $indexed_handbag_materials = array();
         foreach ($handbag_materials as $handbag_material) {
             $indexed_handbag_materials[] = strtolower(preg_replace('/\\s+/', '-', trim($handbag_material)));
         }
         $doc->handbag_material = $indexed_handbag_materials;
     }
     $combinaisons = $productObj->getAttributeCombinaisons(1);
     $indexed_sizes = array();
     foreach ($combinaisons as $k => $combinaison) {
         if ($combinaison['group_name'] == 'size' || $combinaison['group_name'] == 'Size') {
             $indexed_sizes[] = $combinaison['attribute_name'];
         }
     }
     $doc->size = $indexed_sizes;
     //Indian Price
     $doc->offer_price_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, true, 1, false, NULL, NULL, IND_ADDRESS_ID);
     $doc->offer_price_in_rs = Tools::convertPrice($doc->offer_price_in, 4);
     $doc->mrp_in = Product::getPriceStatic($productObj->id, true, NULL, 6, NULL, false, false, 1, false, NULL, NULL, IND_ADDRESS_ID);
     if ($doc->mrp_in > $doc->offer_price_in) {
         $doc->discount_in = Tools::ps_round(($doc->mrp_in - $doc->offer_price_in) / $doc->mrp_in * 100);
     }
     //Worldwide Price
     $doc->offer_price = $productObj->getPrice();
     $doc->offer_price_rs = Tools::convertPrice($doc->offer_price, 4);
     $doc->mrp = $productObj->getPriceWithoutReduct();
     if ($doc->mrp > $doc->offer_price) {
         $doc->discount = Tools::ps_round(($doc->mrp - $doc->offer_price) / $doc->mrp * 100);
     }
     $doc->product_link = $productObj->getLink();
     $idImage = $productObj->getCoverWs();
     if ($idImage) {
         $idImage = $productObj->id . '-' . $idImage;
     } else {
         $idImage = Language::getIsoById(1) . '-default';
     }
     $doc->image_link_list = $link->getImageLink($productObj->link_rewrite, $idImage, 'list');
     $doc->image_link_medium = $link->getImageLink($productObj->link_rewrite, $idImage, 'medium');
     $doc->image_link_large = $link->getImageLink($productObj->link_rewrite, $idImage, 'large');
     $images = $productObj->getImages(1);
     $productImages = array();
     foreach ($images as $k => $image) {
         $productImages[] = $link->getImageLink($productObj->link_rewrite, $image['id_image'], 'large');
     }
     $doc->image_links = $productImages;
     return $doc;
 }
 private function getItemXML($product, $lang, $id_curr, $id_shop, $combination = false)
 {
     $xml_googleshopping = '';
     $id_lang = (int) $lang['id_lang'];
     $title_limit = 70;
     $description_limit = 4990;
     $languages = Language::getLanguages();
     $tailleTabLang = sizeof($languages);
     $this->context->language->id = $id_lang;
     $this->context->shop->id = $id_shop;
     $p = new Product($product['id_product'], true, $id_lang, $id_shop, $this->context);
     // Get module configuration for this shop
     if (!$combination) {
         $product['quantity'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], 0, $id_shop);
     }
     // Exclude non-available products
     if ($this->module_conf['export_nap'] === 0 && $product['quantity'] < 1) {
         $this->nb_not_exported_products++;
         return;
     }
     // Check minimum product price
     $price = Product::getPriceStatic((int) $product['id_product'], true);
     if ((double) $this->module_conf['export_min_price'] > 0 && (double) $this->module_conf['export_min_price'] > (double) $price) {
         return;
     }
     $cat_link_rew = Category::getLinkRewrite($product['id_gcategory'], (int) $lang);
     $product_link = $this->context->link->getProductLink((int) $product['id_product'], $product['link_rewrite'], $cat_link_rew, $product['ean13'], (int) $product['id_lang'], $id_shop, $combination, true);
     // Product name
     $title_crop = $product['name'];
     //  Product color attribute, if any
     if (!empty($product['color'])) {
         $title_crop .= ' ' . $product['color'];
     }
     if (!empty($product['material'])) {
         $title_crop .= ' ' . $product['material'];
     }
     if (!empty($product['pattern'])) {
         $title_crop .= ' ' . $product['pattern'];
     }
     if (!empty($product['size'])) {
         $title_crop .= ' ' . $product['size'];
     }
     if (Tools::strlen($product['name']) > $title_limit) {
         $title_crop = Tools::substr($title_crop, 0, $title_limit - 1);
         $title_crop = Tools::substr($title_crop, 0, strrpos($title_crop, " "));
     }
     // Description type
     if ($this->module_conf['description'] == 'long') {
         $description_crop = $product['description'];
     } else {
         if ($this->module_conf['description'] == 'short') {
             $description_crop = $product['description_short'];
         } else {
             if ($this->module_conf['description'] == 'meta') {
                 $description_crop = $product['meta_description'];
             }
         }
     }
     $description_crop = $this->rip_tags($description_crop);
     if (Tools::strlen($description_crop) > $description_limit) {
         $description_crop = Tools::substr($description_crop, 0, $description_limit - 1);
         $description_crop = Tools::substr($description_crop, 0, strrpos($description_crop, " ")) . ' ...';
     }
     $xml_googleshopping .= '<item>' . "\n";
     $xml_googleshopping .= '<g:id>' . $product['gid'] . '</g:id>' . "\n";
     $xml_googleshopping .= '<title><![CDATA[' . $title_crop . ']]></title>' . "\n";
     $xml_googleshopping .= '<description><![CDATA[' . $description_crop . ']]></description>' . "\n";
     $xml_googleshopping .= '<link><![CDATA[' . htmlspecialchars($product_link, self::REPLACE_FLAGS, self::CHARSET, false) . ']]></link>' . "\n";
     // Image links
     $images = Image::getImages($lang['id_lang'], $product['id_product'], $combination);
     $indexTabLang = 0;
     if ($tailleTabLang > 1) {
         while (sizeof($images) < 1 && $indexTabLang < $tailleTabLang) {
             if ($languages[$indexTabLang]['id_lang'] != $lang['id_lang']) {
                 $images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']);
             }
             $indexTabLang++;
         }
     }
     $nbimages = 0;
     $image_type = $this->module_conf['img_type'];
     if ($image_type == '') {
         $image_type = 'large_default';
     }
     foreach ($images as $im) {
         $image = $this->context->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $im['id_image'], $image_type);
         $image = preg_replace('*http://' . Tools::getHttpHost() . '/*', $this->uri, $image);
         if ($im['cover'] == 1) {
             $xml_googleshopping .= '<g:image_link><![CDATA[' . $image . ']]></g:image_link>' . "\n";
         } else {
             $xml_googleshopping .= '<g:additional_image_link><![CDATA[' . $image . ']]></g:additional_image_link>' . "\n";
         }
         // max images by product
         if (++$nbimages == 10) {
             break;
         }
     }
     // Product condition, or category's condition attribute, or its parent one...
     // Product condition = new, used, refurbished
     if (empty($product['condition'])) {
         $product['condition'] = $this->categories_values[$product['id_gcategory']]['gcat_condition'];
     }
     if (!empty($product['condition'])) {
         $xml_googleshopping .= '<g:condition><![CDATA[' . $product['condition'] . ']]></g:condition>' . "\n";
     }
     // Shop category
     $breadcrumb = GCategories::getPath($product['id_gcategory'], '', $id_lang, $id_shop, $this->id_root);
     $product_type = '';
     if (!empty($this->module_conf['product_type[]'][$id_lang])) {
         $product_type = $this->module_conf['product_type[]'][$id_lang];
         if (!empty($breadcrumb)) {
             $product_type .= " > ";
         }
     }
     $product_type .= $breadcrumb;
     $xml_googleshopping .= '<g:product_type><![CDATA[' . $product_type . ']]></g:product_type>' . "\n";
     // Matching Google category, or parent categories' one
     $product['gcategory'] = $this->categories_values[$product['category_default']]['gcategory'];
     $xml_googleshopping .= '<g:google_product_category><![CDATA[' . $product['gcategory'] . ']]></g:google_product_category>' . "\n";
     // Product quantity & availability
     if (empty($this->categories_values[$product['category_default']]['gcat_avail'])) {
         if ($this->module_conf['quantity'] == 1) {
             $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n";
         }
         if ($product['quantity'] > 0 && $product['available_for_order']) {
             $xml_googleshopping .= '<g:availability>in stock</g:availability>' . "\n";
         } elseif ($p->isAvailableWhenOutOfStock((int) $p->out_of_stock) && $product['available_for_order']) {
             $xml_googleshopping .= '<g:availability>preorder</g:availability>' . "\n";
         } else {
             $xml_googleshopping .= '<g:availability>out of stock</g:availability>' . "\n";
         }
     } else {
         if ($this->module_conf['quantity'] == 1 && $product['quantity'] > 0) {
             $xml_googleshopping .= '<g:quantity>' . $product['quantity'] . '</g:quantity>' . "\n";
         }
         $xml_googleshopping .= '<g:availability>' . $this->categories_values[$product['category_default']]['gcat_avail'] . '</g:availability>' . "\n";
     }
     // Price(s)
     $currency = new Currency((int) $id_curr);
     $use_tax = $product['tax_included'] ? true : false;
     $no_tax = !$use_tax ? true : false;
     $product['price'] = (double) $p->getPriceStatic($product['id_product'], $use_tax, $combination) * $currency->conversion_rate;
     $product['price_without_reduct'] = (double) $p->getPriceWithoutReduct($no_tax, $combination) * $currency->conversion_rate;
     $product['price'] = number_format(round($product['price'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' ');
     $product['price_without_reduct'] = number_format(round($product['price_without_reduct'], 2, PHP_ROUND_HALF_DOWN), 2, '.', ' ');
     if ((double) $product['price'] < (double) $product['price_without_reduct']) {
         $xml_googleshopping .= '<g:price>' . $product['price_without_reduct'] . ' ' . $currency->iso_code . '</g:price>' . "\n";
         $xml_googleshopping .= '<g:sale_price>' . $product['price'] . ' ' . $currency->iso_code . '</g:sale_price>' . "\n";
     } else {
         $xml_googleshopping .= '<g:price>' . $product['price'] . ' ' . $currency->iso_code . '</g:price>' . "\n";
     }
     $identifier_exists = 0;
     // GTIN (EAN, UPC, JAN, ISBN)
     if (!empty($product['ean13'])) {
         $xml_googleshopping .= '<g:gtin>' . $product['ean13'] . '</g:gtin>' . "\n";
         $identifier_exists++;
     }
     // Brand
     if ($this->module_conf['no_brand'] != 0 && !empty($product['id_manufacturer'])) {
         $xml_googleshopping .= '<g:brand><![CDATA[' . htmlspecialchars(Manufacturer::getNameById((int) $product['id_manufacturer']), self::REPLACE_FLAGS, self::CHARSET, false) . ']]></g:brand>' . "\n";
         $identifier_exists++;
     }
     // MPN
     if (empty($product['supplier_reference'])) {
         $product['supplier_reference'] = ProductSupplier::getProductSupplierReference($product['id_product'], 0, $product['id_supplier']);
     }
     if ($this->module_conf['mpn_type'] == 'reference' && !empty($product['reference'])) {
         $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['reference'] . ']]></g:mpn>' . "\n";
         $identifier_exists++;
     } else {
         if ($this->module_conf['mpn_type'] == 'supplier_reference' && !empty($product['supplier_reference'])) {
             $xml_googleshopping .= '<g:mpn><![CDATA[' . $product['supplier_reference'] . ']]></g:mpn>' . "\n";
             $identifier_exists++;
         }
     }
     // Tag "identifier_exists"
     if ($this->module_conf['id_exists_tag'] && $identifier_exists < 2) {
         $xml_googleshopping .= '<g:identifier_exists>FALSE</g:identifier_exists>' . "\n";
     }
     // Product gender and age_group attributes association
     $product_features = $this->getProductFeatures($product['id_product'], $id_lang, $id_shop);
     $product['gender'] = $this->categories_values[$product['category_default']]['gcat_gender'];
     $product['age_group'] = $this->categories_values[$product['category_default']]['gcat_age_group'];
     foreach ($product_features as $feature) {
         switch ($feature['id_feature']) {
             case $this->module_conf['gender']:
                 $product['gender'] = $feature['value'];
                 continue 2;
             case $this->module_conf['age_group']:
                 $product['age_group'] = $feature['value'];
                 continue 2;
         }
         if (!$product['color']) {
             foreach ($this->module_conf['color[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['color'] = $feature['value'];
                 }
             }
         }
         if (!$product['material']) {
             foreach ($this->module_conf['material[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['material'] = $feature['value'];
                 }
             }
         }
         if (!$product['pattern']) {
             foreach ($this->module_conf['pattern[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['pattern'] = $feature['value'];
                 }
             }
         }
         if (!$product['size']) {
             foreach ($this->module_conf['size[]'] as $id => $v) {
                 if ($v == $feature['id_feature']) {
                     $product['size'] = $feature['value'];
                 }
             }
         }
     }
     //  Product gender attribute, or category gender attribute, or parent's one
     if (!empty($product['gender'])) {
         $xml_googleshopping .= '<g:gender><![CDATA[' . $product['gender'] . ']]></g:gender>' . "\n";
     }
     // Product age_group attribute, or category age_group attribute, or parent's one
     if (!empty($product['age_group'])) {
         $xml_googleshopping .= '<g:age_group><![CDATA[' . $product['age_group'] . ']]></g:age_group>' . "\n";
     }
     // Product attributes combination groups
     if ($combination && !empty($product['item_group_id'])) {
         $xml_googleshopping .= '<g:item_group_id>' . $product['item_group_id'] . '</g:item_group_id>' . "\n";
     }
     // Product color attribute, or category color attribute, or parent's one
     if (!empty($product['color'])) {
         $xml_googleshopping .= '<g:color><![CDATA[' . $product['color'] . ']]></g:color>' . "\n";
     }
     // Product material attribute, or category material attribute, or parent's one
     if (!empty($product['material'])) {
         $xml_googleshopping .= '<g:material><![CDATA[' . $product['material'] . ']]></g:material>' . "\n";
     }
     // Product pattern attribute, or category pattern attribute, or parent's one
     if (!empty($product['pattern'])) {
         $xml_googleshopping .= '<g:pattern><![CDATA[' . $product['pattern'] . ']]></g:pattern>' . "\n";
     }
     // Product size attribute, or category size attribute, or parent's one
     if (!empty($product['size'])) {
         $xml_googleshopping .= '<g:size><![CDATA[' . $product['size'] . ']]></g:size>' . "\n";
     }
     // Featured products
     if ($this->module_conf['featured_products'] == 1 && $product['on_sale'] != '0') {
         $xml_googleshopping .= '<g:featured_product>true</g:featured_product>' . "\n";
     }
     // Shipping
     $xml_googleshopping .= '<g:shipping>' . "\n";
     $xml_googleshopping .= "\t" . '<g:country>' . $this->module_conf['shipping_country'] . '</g:country>' . "\n";
     $xml_googleshopping .= "\t" . '<g:service>Standard</g:service>' . "\n";
     $xml_googleshopping .= "\t" . '<g:price>' . number_format($this->module_conf['shipping_price'], 2, '.', ' ') . ' ' . $currency->iso_code . '</g:price>' . "\n";
     $xml_googleshopping .= '</g:shipping>' . "\n";
     // Shipping weight
     if ($product['weight'] != '0') {
         $xml_googleshopping .= '<g:shipping_weight>' . number_format($product['weight'], 2, '.', '') . ' ' . Configuration::get('PS_WEIGHT_UNIT') . '</g:shipping_weight>' . "\n";
     }
     $xml_googleshopping .= '</item>' . "\n\n";
     if ($combination) {
         $this->nb_combinations++;
         $this->nb_prd_w_attr[$product['id_product']] = 1;
     }
     $this->nb_total_products++;
     return $xml_googleshopping;
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $flag_pack = true;
     if (!$this->errors) {
         //                        if(!isset($_GET['quick_view']))
         //                            if (Pack::isPack((int)$this->product->id) && !Pack::isInStock((int)$this->product->id))
         //                        if (Pack::isPack((int)$this->product->id))
         //                            $this->product->quantity = 0;
         //                        else
         //                            $flag_pack = false;
         //                        else
         //                            $flag_pack = false;
         if (!Pack::isPack((int) $this->product->id)) {
             $flag_pack = false;
         }
         $this->product->description = $this->transformDescriptionWithImg($this->product->description);
         // Assign to the template the id of the virtual product. "0" if the product is not downloadable.
         $this->context->smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
         $this->context->smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
         if (Tools::isSubmit('submitCustomizedDatas')) {
             // If cart has not been saved, we need to do it so that customization fields can have an id_cart
             // We check that the cookie exists first to avoid ghost carts
             if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
                 $this->context->cart->add();
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
             $this->pictureUpload();
             $this->textRecord();
             $this->formTargetFormat();
         } else {
             if (Tools::getIsset('deletePicture') && !$this->context->cart->deleteCustomizationToProduct($this->product->id, Tools::getValue('deletePicture'))) {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture.');
             }
         }
         $pictures = array();
         $text_fields = array();
         if ($this->product->customizable) {
             $files = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_FILE, true);
             foreach ($files as $file) {
                 $pictures['pictures_' . $this->product->id . '_' . $file['index']] = $file['value'];
             }
             $texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
             foreach ($texts as $text_field) {
                 $text_fields['textFields_' . $this->product->id . '_' . $text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
             }
         }
         $this->context->smarty->assign(array('pictures' => $pictures, 'textFields' => $text_fields));
         // Assign template vars related to the category + execute hooks related to the category
         $this->assignCategory();
         // Assign template vars related to the price and tax
         $this->assignPriceAndTax();
         // Assign template vars related to the images
         $this->assignImages();
         $this->assign3dImages();
         // Assign attribute groups to the template
         $this->assignAttributesGroups();
         // Assign attributes combinations to the template
         $this->assignAttributesCombinations();
         // Pack management
         $pack_items = $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, $this->context->language->id, true) : array();
         if (is_array($pack_items) && count($pack_items)) {
             foreach ($pack_items as &$pack_item) {
                 $pack_item['features'] = Product::getFrontFeaturesStatic($this->context->language->id, $pack_item['id_product']);
             }
         }
         $this->context->smarty->assign('packItems', $pack_items);
         $this->context->smarty->assign('packs', Pack::getPacksTable($this->product->id, $this->context->language->id, true, 1));
         if (isset($this->category->id) && $this->category->id) {
             $return_link = Tools::safeOutput($this->context->link->getCategoryLink($this->category));
         } else {
             $return_link = 'javascript: history.back();';
         }
         //reviews
         //                        $average = ProductComment::getAverageGrade((int)Tools::getValue('id_product'));
         $nbComments = (int) ProductComment::getCommentNumber((int) Tools::getValue('id_product'));
         $act_pack = 0;
         //паки
         if (!$flag_pack) {
             $sql = "SELECT DISTINCT(id_product_pack) FROM " . _DB_PREFIX_ . "pack WHERE id_product_item={$this->product->id}";
             $pack_products = array();
             $result_packs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
             if (is_array($result_packs) && count($result_packs)) {
                 foreach ($result_packs as $k => $id_product_pack) {
                     $prod = new Product($id_product_pack['id_product_pack'], $this->context->language->id, true);
                     $cover = $prod->getCover((int) $prod->id);
                     if ($cover) {
                         $pack_products[$k]['id_image'] = $cover['id_image'];
                     } else {
                         $pack_products[$k]['id_image'] = null;
                     }
                     $price = $prod->getPrice(true, null, 2);
                     $price_old = $prod->getPriceWithoutReduct(false, null, 2);
                     if (isset($prod->specificPrice) && is_array($prod->specificPrice)) {
                         $pack_products[$k]['sale_percentage'] = $prod->specificPrice['reduction_type'] == 'percentage' ? $prod->specificPrice['reduction'] * 100 : $prod->specificPrice['reduction'] / $price_old * 100;
                     }
                     $pack_products[$k]['active'] = $prod->active;
                     if ($prod->active) {
                         $act_pack = 1;
                     }
                     $pack_products[$k]['count_reviews'] = (int) ProductComment::getCommentNumber((int) $prod->id);
                     $pack_products[$k]['star_reviews'] = ProductComment::getRatings((int) $prod->id);
                     $pack_products[$k]['price'] = $price;
                     $pack_products[$k]['price_old'] = $price_old;
                     $pack_products[$k]['on_sale'] = (bool) ($price != $price_old);
                     $pack_products[$k]['id_product_pack'] = $prod->id;
                     $pack_products[$k]['link'] = $this->context->link->getProductLink($prod);
                     $pack_products[$k]['name'] = $prod->name;
                     $pack_products[$k]['link_rewrite'] = $prod->link_rewrite;
                     $pack_products[$k]['items'] = Pack::getItemTable($prod->id, $this->context->language->id, true);
                     unset($prod);
                 }
             }
         } else {
             $pack_products = null;
         }
         //var_dump($pack_products);exit();
         //текстовой блок доставка
         $cms_block = '';
         $cms = new CMS($this->block_cms_id, $this->context->language->id);
         if (is_object($cms)) {
             $cms_block = $cms->content;
         }
         $sql = "SELECT id_category FROM ps_category_product WHERE id_product={$this->product->id}";
         $result_cats = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
         $params_image = null;
         foreach ($result_cats as $cat) {
             $params_image = file_exists(_PS_IMG_DIR_ . '/c_icon/' . $cat['id_category'] . '.png') ? '/img/c_icon/' . $cat['id_category'] . '.png' : null;
             if (!$params_image) {
                 $params_image = file_exists(_PS_IMG_DIR_ . '/c_icon/' . $cat['id_category'] . '.jpg') ? '/img/c_icon/' . $cat['id_category'] . '.jpg' : null;
             }
             if ($params_image) {
                 break;
             }
         }
         //{if $product->minimal_quantity > 1}{$product->minimal_quantity}{else}1{/if}
         $this->context->smarty->assign(array('is_bestsaler' => ProductSale::isBestsaler($this->product->id), 'og_type' => 'product', 'params_image' => $params_image, 'cms_block' => $cms_block, 'pack_products' => $pack_products, 'act_pack' => $act_pack, 'url' => $this->context->link->getProductLink($this->product), 'minimal_quantity' => $this->product->minimal_quantity > 1 ? $this->product->minimal_quantity : 1, 'nbComments' => $nbComments, 'stock_management' => Configuration::get('PS_STOCK_MANAGEMENT'), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields($this->context->language->id) : false, 'accessories' => $this->product->getAccessories($this->context->language->id), 'return_link' => $return_link, 'product' => $this->product, 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, $this->context->language->id), 'token' => Tools::getToken(false), 'features' => $this->product->getFrontFeatures($this->context->language->id), 'attachments' => $this->product->cache_has_attachments ? $this->product->getAttachments($this->context->language->id) : array(), 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'HOOK_EXTRA_LEFT' => Hook::exec('displayLeftColumnProduct'), 'HOOK_EXTRA_RIGHT' => Hook::exec('displayRightColumnProduct'), 'HOOK_PRODUCT_OOS' => Hook::exec('actionProductOutOfStock', array('product' => $this->product)), 'HOOK_PRODUCT_ACTIONS' => Hook::exec('displayProductButtons', array('product' => $this->product)), 'HOOK_PRODUCT_TAB' => Hook::exec('displayProductTab', array('product' => $this->product)), 'HOOK_PRODUCT_TAB_CONTENT' => Hook::exec('displayProductTabContent', array('product' => $this->product)), 'HOOK_PRODUCT_CONTENT' => Hook::exec('displayProductContent', array('product' => $this->product)), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'currencySign' => $this->context->currency->sign, 'currencyRate' => $this->context->currency->conversion_rate, 'currencyFormat' => $this->context->currency->format, 'currencyBlank' => $this->context->currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'), 'ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'body_classes' => array($this->php_self . '-' . $this->product->id, $this->php_self . '-' . $this->product->link_rewrite, 'category-' . (isset($this->category) ? $this->category->id : ''), 'category-' . (isset($this->category) ? $this->category->getFieldByLang('link_rewrite') : '')), 'display_discount_price' => Configuration::get('PS_DISPLAY_DISCOUNT_PRICE')));
     }
     if (isset($_GET['quick_view'])) {
         $this->ajax = true;
         if ($flag_pack) {
             $this->setTemplate(_PS_THEME_DIR_ . 'preview_pack.tpl');
         } else {
             $this->setTemplate(_PS_THEME_DIR_ . 'preview.tpl');
         }
     } else {
         if ($flag_pack) {
             $this->setTemplate(_PS_THEME_DIR_ . 'product-pack.tpl');
         } else {
             $this->setTemplate(_PS_THEME_DIR_ . 'product.tpl');
         }
     }
 }