Advertisement
Guest User

Untitled

a guest
Apr 27th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 128.36 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Product Controller
  5.  *
  6.  * @author Edgar Kuskov <ekuskov@gmail.com>
  7.  * @version 1.0
  8.  * @package Modules.Project.Controller
  9.  */
  10. class ProductController extends Controller {
  11.  
  12.     /**
  13.      *
  14.      * @return array action filters
  15.      */
  16.     public function filters() {
  17.         return array(
  18.             'accessControl', // perform access control for CRUD
  19.                                           // operations
  20.             'postOnly + delete'
  21.         );
  22.         // we only allow deletion via POST request
  23.    
  24.     }
  25.  
  26.     /**
  27.      * Specifies the access control rules.
  28.      * This method is used by the 'accessControl' filter.
  29.      *
  30.      * @return array access control rules
  31.      */
  32.     public function accessRules() {
  33.         return array(
  34.             array(
  35.                 'allow',
  36.                 'users' => array(
  37.                     '@'
  38.                 )
  39.             ),
  40.             array(
  41.                 'deny', //
  42.                                                                                    // deny all users
  43.                 'users' => array(
  44.                     '*'
  45.                 )
  46.             )
  47.         );
  48.     }
  49.  
  50.     /**
  51.      * Show products modal view
  52.      */
  53.     public function actionProductsModal() {
  54.         $model = new Product('search');
  55.         $model->unsetAttributes();
  56.         $checkbox = false;
  57.         $resultFunction = $grid_id = '';
  58.        
  59.         if (isset($_POST['resultFunction']))
  60.             $resultFunction = $_POST['resultFunction'];
  61.         if (isset($_POST['checkbox']) && $_POST['checkbox'] === 'true')
  62.             $checkbox = true;
  63.         if (isset($_GET['Product'])) {
  64.             $model->attributes = $_GET['Product'];
  65.             $model->title = $_GET['Product']['title'];
  66.         }
  67.         if (isset($_GET['ajax']))
  68.             $grid_id = $_GET['ajax'];
  69.         echo $this->renderPartial('_table', array(
  70.             'model' => $model,
  71.             'function' => $resultFunction,
  72.             'checkbox' => $checkbox,
  73.             'grid_id' => $grid_id
  74.         ), false, true);
  75.     }
  76.  
  77.     /**
  78.      * Show products modal view
  79.      */
  80.     public function actionCustomProductModal() {
  81.         $function = $_POST['resultFunction'];
  82.         $model = new Size('customSize');
  83.         $unity = new FoilTypeUnity();
  84.         echo $this->renderPartial('_customProduct', array(
  85.             'model' => $model,
  86.             'unity' => $unity,
  87.             'function' => $function
  88.         ), false, true);
  89.     }
  90.  
  91.     /**
  92.      * Lists all models.
  93.      */
  94.     public function actionIndex() {
  95.         $model = new Product('search');
  96.         $model->unsetAttributes();
  97.        
  98.         if (isset($_GET['Product'])) {
  99.             $model->attributes = $_GET['Product'];
  100.             $model->title = $_GET['Product']['title'];
  101.             $model->manufacturer = $_GET['Product']['manufacturer'];
  102.         }
  103.         if (isset($_GET['searchValue'])) {
  104.             $model->searchValue = $_GET['searchValue'];
  105.             // Add search parts to product details
  106.             if (is_numeric($model->searchValue) && strlen($model->searchValue) == 13) {
  107.                 $model->ean = $model->searchValue;
  108.             } elseif (is_numeric($model->searchValue) && strlen($model->searchValue) < 13) {
  109.                 $model->id = $model->searchValue;
  110.                 $model->title = '';
  111.             } else {
  112.                 $model->title = $model->searchValue;
  113.             }
  114.         }
  115.         $this->render('index', array(
  116.             'model' => $model
  117.         ));
  118.     }
  119.  
  120.     /**
  121.      * Create product manually
  122.      */
  123.     public function actionCreate() {
  124.         $model = new Product('customCreate');
  125.         $pProduct = new PhysicalProduct();
  126.         $model->physicalProduct = $pProduct;
  127.        
  128.         if (isset($_POST['Product']) && isset($_POST['PhysicalProduct'])) {
  129.             $model->attributes = $_POST['Product'];
  130.             $model->physicalProduct_id = '1';
  131.             $model->project_id = 1;
  132.             $model->createDate = date('Y-m-d H:i:s');
  133.             $model->editOwnerUser_id = Yii::app()->user->id;
  134.            
  135.             $pProduct->attributes = $_POST['PhysicalProduct'];
  136.             // Check if EAN code is needed
  137.             if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
  138.                 $model->ean = Ean::getFreeEANCode();
  139.            
  140.             if ($model->validate() && $pProduct->validate()) {
  141.                 $pProduct->save(false);
  142.                 $model->physicalProduct_id = $pProduct->getPrimaryKey();
  143.                 if (!empty($model->availableFromDate))
  144.                     $model->availableFromDate = date('Y-m-d H:i:s', strtotime($model->availableFromDate));
  145.                 if (!empty($model->availableToDate))
  146.                     $model->availableToDate = date('Y-m-d H:i:s', strtotime($model->availableToDate));
  147.                 $model->save(false);
  148.                
  149.                 // Block ean code
  150.                 if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
  151.                     Ean::blockEANCode($model->ean);
  152.                
  153.                 if (isset($_POST['Product']['productERPGroups'])) {
  154.                     $erpGroups = $_POST['Product']['productERPGroups'];
  155.                     $erpGroups = array_filter($erpGroups);
  156.                     $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $model->primaryKey;
  157.                     Yii::app()->db->createCommand($sql)->execute();
  158.                     foreach($erpGroups as $group) {
  159.                         $endGroup = 0;
  160.                         if ($group == end($erpGroups))
  161.                             $endGroup = 1;
  162.                         $sql = 'INSERT INTO product_has_productERPGroup VALUES (' . $group . ', ' . $model->primaryKey . ', 0 , ' . $endGroup . ')';
  163.                         Yii::app()->db->createCommand($sql)->execute();
  164.                     }
  165.                 }
  166.                
  167.                 if (isset($_POST['Product']['productCategories'])) {
  168.                     $categories = $_POST['Product']['productCategories'];
  169.                     $categories = array_filter($categories);
  170.                     $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $model->primaryKey;
  171.                     Yii::app()->db->createCommand($sql)->execute();
  172.                     foreach($categories as $category) {
  173.                         $endCategory = 0;
  174.                         if ($category == end($categories))
  175.                             $endCategory = 1;
  176.                         $sql = 'INSERT INTO product_has_productCategory VALUES (' . $category . ', ' . $model->primaryKey . ', 0 , ' . $endCategory . ')';
  177.                         Yii::app()->db->createCommand($sql)->execute();
  178.                     }
  179.                 }
  180.             } else {
  181.                 if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
  182.                     Ean::freeEan($model->ean);
  183.                 $pProduct->validate();
  184.             }
  185.             Helper::ajaxReturn(array_merge($pProduct->errors, $model->errors), null, array(
  186.                 'productID' => $model->getPrimaryKey()
  187.             ));
  188.         }
  189.        
  190.         $this->render('createForm', array(
  191.             'model' => $model
  192.         ));
  193.     }
  194.  
  195.     /**
  196.      * This function generates a category tree for the product
  197.      *
  198.      * @param Product $product
  199.      * @param String $categories
  200.      * @param Array $params
  201.      * @return boolean if the categories were generated
  202.      */
  203.     public static function generateCategories($product, $categoriesFormula, $params, $updateReturn = false) {
  204.         $currentParent = null;
  205.         $languages = Language::model()->findAll('active=1');
  206.         if ($languages) {
  207.            
  208.             // Remove all previous categories
  209.             if ($updateReturn == false) {
  210.                 $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $product->id;
  211.                 Yii::app()->db->createCommand($sql)->query();
  212.             }
  213.            
  214.             // Generate categories for each language
  215.             $productCategories = array();
  216.             foreach($languages as $language) {
  217.                 $categories = Helper::decodeModuleValues($categoriesFormula, $params, $language->isoCode);
  218.                 if ($categories === false)
  219.                     return false;
  220.                    
  221.                     // Add category for custom sizes
  222.                 if ($params['size']->sizeType_id == Yii::app()->params['customSize'])
  223.                     $type = SizeType::model()->findByPk(Yii::app()->params['customSize']);
  224.                 elseif ($params['size']->sizeType_id == Yii::app()->params['customerSize'])
  225.                     $type = SizeType::model()->findByPk(Yii::app()->params['customerSize']);
  226.                 if (!empty($type))
  227.                     $categories .= ' ##separator## ' . $type->title[Yii::app()->language];
  228.                
  229.                 $categories = explode('##separator##', $categories);
  230.                 if ($categories) {
  231.                     foreach($categories as $key=>$category)
  232.                         $productCategories[$key][$language->isoCode] = trim($category);
  233.                 }
  234.             }
  235.            
  236.             // Generate the categories
  237.             $addedCategories = array();
  238.             $categoriesTranslations = array();
  239.             $currentParent = null;
  240.             foreach($productCategories as $key=>$category) {
  241.                 $emptyError = false;
  242.                 if (empty($category))
  243.                     $emptyError = true;
  244.                 foreach($category as &$trans) {
  245.                     if (strlen($trans) == 0) {
  246.                         $emptyError = true;
  247.                         $trans = '----';
  248.                     }
  249.                 }
  250.                 if ($emptyError) {
  251.                     $error = new ErrorLog();
  252.                     $error->errorLogType_id = 4;
  253.                     $error->text = 'One part of product categories is empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
  254.                     $error->save(false);
  255.                 }
  256.                
  257.                 $sql = 'SELECT pc.id AS id
  258.                FROM productCategory AS pc, productCategory_translation AS pct
  259.                WHERE pct.productCategory_id=pc.id
  260.                AND pct.title="' . addslashes(reset($category)) . '"
  261.                AND pct.isoCode="' . key($category) . '"';
  262.                 if ($currentParent)
  263.                     $sql .= 'AND pc.productCategory_id="' . $currentParent . '"';
  264.                 else
  265.                     $sql .= 'AND pc.productCategory_id IS NULL';
  266.                
  267.                 $exist = Yii::app()->db->createCommand($sql)->queryRow();
  268.                 if ($exist) {
  269.                     $currentParent = $exist['id'];
  270.                 } else {
  271.                     $productCategory = new ProductCategory();
  272.                     $productCategory->position = 0;
  273.                     $productCategory->productCategory_id = $currentParent;
  274.                     $productCategory->save(false);
  275.                     $currentParent = $productCategory->id;
  276.                     foreach($category as $key=>$title) {
  277.                         $categoriesTranslations[] = '(' . $productCategory->id . ',"' . $key . '","' . addslashes($title) . '")';
  278.                     }
  279.                 }
  280.                 $endCategory = ($category == end($productCategories)) ? 1 : 0;
  281.                 $addedCategories[] = '(' . $currentParent . ',"' . $product->id . '",0,' . $endCategory . ')';
  282.                 if ($endCategory == 1)
  283.                     $finalCategory = $currentParent;
  284.             }
  285.             $categoriesTranslations = array_unique($categoriesTranslations);
  286.             $addedCategories = array_unique($addedCategories);
  287.            
  288.             // Add category translations
  289.             if (!empty($categoriesTranslations)) {
  290.                 $sql = 'INSERT INTO productCategory_translation VALUES ' . implode(',', $categoriesTranslations);
  291.                 Yii::app()->db->createCommand($sql)->query();
  292.             }
  293.            
  294.             if ($updateReturn == false) {
  295.                 if (!empty($addedCategories)) {
  296.                     $sql = 'INSERT INTO product_has_productCategory VALUES ' . implode(',', $addedCategories);
  297.                     Yii::app()->db->createCommand($sql)->query();
  298.                 }
  299.             } else {
  300.                 return $finalCategory;
  301.             }
  302.         }
  303.         return true;
  304.     }
  305.  
  306.     /**
  307.      * This function generates a erp group tree for the product
  308.      *
  309.      * @param Product $product
  310.      * @param String $ERPGroupFormula
  311.      * @param Array $params
  312.      * @return boolean if the erp groups were generated
  313.      */
  314.     public static function generateERPGroups($product, $ERPGroupFormula, $params, $updateReturn = false) {
  315.         $currentParent = null;
  316.         $languages = Language::model()->findAll('active=1');
  317.         if ($languages) {
  318.            
  319.             // Remove all previous categories
  320.             if ($updateReturn == false) {
  321.                 $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $product->id;
  322.                 Yii::app()->db->createCommand($sql)->query();
  323.             }
  324.            
  325.             // Generate categories for each language
  326.             $productERPGroups = array();
  327.             foreach($languages as $language) {
  328.                 $ERPGroups = Helper::decodeModuleValues($ERPGroupFormula, $params, $language->isoCode);
  329.                 if ($ERPGroups === false)
  330.                     return false;
  331.                    
  332.                     // Add erp group for custom sizes
  333.                 if ($params['size']->sizeType_id == Yii::app()->params['customSize'])
  334.                     $type = SizeType::model()->findByPk(Yii::app()->params['customSize']);
  335.                 elseif ($params['size']->sizeType_id == Yii::app()->params['customerSize'])
  336.                     $type = SizeType::model()->findByPk(Yii::app()->params['customerSize']);
  337.                 if (!empty($type))
  338.                     $ERPGroups .= ' ##separator## ' . $type->title[Yii::app()->language];
  339.                
  340.                 $ERPGroups = explode('##separator##', $ERPGroups);
  341.                 if ($ERPGroups) {
  342.                     foreach($ERPGroups as $key=>$group)
  343.                         $productERPGroups[$key][$language->isoCode] = trim($group);
  344.                 }
  345.             }
  346.            
  347.             // Generate ERP groups
  348.             $addedERPGroups = array();
  349.             $ERPGroupTranslations = array();
  350.             $currentParent = null;
  351.             foreach($productERPGroups as $key=>$group) {
  352.                 $emptyError = false;
  353.                 if (empty($group))
  354.                     $emptyError = true;
  355.                 foreach($group as &$trans) {
  356.                     if (strlen($trans) == 0) {
  357.                         $emptyError = true;
  358.                         $trans = '----';
  359.                     }
  360.                 }
  361.                 if ($emptyError) {
  362.                     $error = new ErrorLog();
  363.                     $error->errorLogType_id = 4;
  364.                     $error->text = 'One part of product erp groups is empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
  365.                     $error->save(false);
  366.                
  367.                 }
  368.                
  369.                 $sql = 'SELECT pc.id AS id
  370.                FROM productERPGroup AS pc, productERPGroup_translation AS pct
  371.                WHERE pct.productERPGroup_id=pc.id
  372.                AND pct.title="' . addslashes(reset($group)) . '"
  373.                AND pct.isoCode="' . key($group) . '"';
  374.                 if ($currentParent)
  375.                     $sql .= 'AND pc.productERPGroup_id="' . $currentParent . '"';
  376.                 $exist = Yii::app()->db->createCommand($sql)->queryRow();
  377.                 if ($exist) {
  378.                     $currentParent = $exist['id'];
  379.                 } else {
  380.                     $erpGroup = new ProductERPGroup();
  381.                     $erpGroup->position = 0;
  382.                     $erpGroup->productERPGroup_id = $currentParent;
  383.                     $erpGroup->save(false);
  384.                     $currentParent = $erpGroup->id;
  385.                     foreach($group as $key=>$title) {
  386.                         $ERPGroupTranslations[] = '(' . $erpGroup->id . ',"' . $key . '","' . addslashes($title) . '")';
  387.                     }
  388.                 }
  389.                 $endCategory = ($group == end($productERPGroups)) ? 1 : 0;
  390.                 $addedERPGroups[] = '(' . $currentParent . ',"' . $product->id . '",0,' . $endCategory . ')';
  391.                 if ($endCategory == 1)
  392.                     $finalGroup = $currentParent;
  393.             }
  394.             $ERPGroupTranslations = array_unique($ERPGroupTranslations);
  395.             $addedERPGroups = array_unique($addedERPGroups);
  396.            
  397.             if (!empty($ERPGroupTranslations)) {
  398.                 $sql = 'INSERT INTO productERPGroup_translation VALUES ' . implode(',', $ERPGroupTranslations);
  399.                 Yii::app()->db->createCommand($sql)->query();
  400.             }
  401.            
  402.             if ($updateReturn == false) {
  403.                 if (!empty($addedERPGroups)) {
  404.                     $sql = 'INSERT INTO product_has_productERPGroup VALUES ' . implode(',', $addedERPGroups);
  405.                     Yii::app()->db->createCommand($sql)->query();
  406.                 }
  407.             } else {
  408.                 return $finalGroup;
  409.             }
  410.         }
  411.         return true;
  412.     }
  413.  
  414.     /**
  415.      * This function calculates costs in film protection project
  416.      * Addition UC = unitCosts
  417.      * Addition PC = processCosts
  418.      * Addition OC = overheadCosts
  419.      */
  420.    
  421.     public static function calculateCostsFromPackage($product, $foilTypeUnity, $packageSize, $sizes, $priceCondition) {
  422.         $costRates = $product->project->costRates[0];
  423.         if (empty($costRates))
  424.             return $product->costPrice = null;
  425.        
  426.         $foilType = $foilTypeUnity->foilType;
  427.        
  428.         $foilArea = 0;
  429.         $cuttingTime = 0;
  430.         foreach($sizes as $size) {
  431.             $foilArea += $size->heightWithPullTab * $size->widthWithPullTab;
  432.             $cuttingTime += $size->cuttingTime;
  433.         }
  434.         // quntity needed
  435.         $foilArea = $foilArea * $foilTypeUnity->unity;
  436.         $cuttingTime = $cuttingTime * $foilTypeUnity->unity;
  437.         // change area from mm² to m²
  438.         $foilArea = $foilArea / 1000000;
  439.         // change time from sec to hour
  440.         $cuttingTime = $cuttingTime / 3600;
  441.         $inspectionTime = $foilType->inspectionTime / 3600;
  442.         $packagingTime = $packageSize->packagingTime / 3600;
  443.        
  444.         $foilTypeCosts_UC = $foilArea * $foilType->price * (1 + $foilType->clipping * 0.01) * (1 + $foilType->faulty * 0.01);
  445.         $foilTypeCosts_PC = $foilArea * $inspectionTime * $costRates->inspectionProcess;
  446.         $foilTypeCosts_OC = $foilTypeCosts_UC * $costRates->procurementOverheadPercent * 0.01;
  447.        
  448.         $packageParts_UC = 0;
  449.         if (!empty($packageSize->packageParts)) {
  450.             foreach($packageSize->packageParts as $packagePart) {
  451.                 $packageParts_UC += $packagePart->price;
  452.             }
  453.         }
  454.         $packageParts_OC = $packageParts_UC * $costRates->procurementOverheadPercent * 0.01;
  455.        
  456.         $cuttingCosts_PC = $cuttingTime * $costRates->cuttingProcess;
  457.         $cuttingCosts_OC = $cuttingCosts_PC * $costRates->productionOverheadPercent * 0.01;
  458.        
  459.         $packagingCosts_PC = $packagingTime * $costRates->packagingProcess;
  460.         $packagingCosts_OC = $packagingCosts_PC * $costRates->packagingOverheadPercent * 0.01;
  461.        
  462.         $hourRate = 0;
  463.        
  464.         // here nothing set
  465.         $foilTypeSizes = FoilTypeSize::model()->findAll('foilType_id=' . $foilType->id);
  466.         if (!empty($foilTypeSizes)) {
  467.             foreach($foilTypeSizes as $fts) {
  468.                 $productionDeviceSizeMats = ProductionDeviceSizeMat::model()->findAll('foilTypeSize_id=' . $fts->id);
  469.                 if (!empty($productionDeviceSizeMats)) {
  470.                     foreach($productionDeviceSizeMats as $productionDeviceSizeMat) {
  471.                         if ($productionDeviceSizeMat->productionDevice->hourRate > $hourRate)
  472.                             $hourRate = $productionDeviceSizeMat->productionDevice->hourRate;
  473.                     }
  474.                 }
  475.             }
  476.         }
  477.         if ($hourRate == 0)
  478.             $hourRate = 50;
  479.        
  480.         $machineCosts_PC = $cuttingTime * $hourRate;
  481.         $machineCosts_OC = $machineCosts_PC * $costRates->productionOverheadPercent * 0.01;
  482.        
  483.         // production specific overhead costs
  484.         $productionCosts = $cuttingCosts_PC + $cuttingCosts_OC + $packagingCosts_PC + $packagingCosts_OC + $machineCosts_PC + $machineCosts_OC;
  485.         $production_OC = $productionCosts * $costRates->administrationOverheadPercent * 0.01;
  486.        
  487.         $manufacturingCosts = $foilTypeCosts_UC + $foilTypeCosts_PC + $foilTypeCosts_OC + $packageParts_UC + $packageParts_OC + $cuttingCosts_PC + $cuttingCosts_OC + $packagingCosts_PC + $packagingCosts_OC + $machineCosts_PC + $machineCosts_OC + $production_OC;
  488.        
  489.         // general part of price calculation (not foil specific)
  490.         $sql = "SELECT pickingCosts
  491.                FROM carrierProductFormat
  492.                WHERE maxHeight>=" . $product->physicalProduct->height . " AND maxWidth>=" . $product->physicalProduct->width . " AND maxDepth>=" . $product->physicalProduct->depth . "
  493.                ORDER BY pickingCosts ASC;";
  494.         $carrierProductFormats = Yii::app()->db->createCommand($sql)->queryAll();
  495.         $pickingCosts_PC = 0;
  496.        
  497.         if (empty($carrierProductFormats)) {
  498.             $pickingCosts_PC = 0;
  499.         } else {
  500.             $pickingCosts_PC = $carrierProductFormats[0]['pickingCosts'];
  501.         }
  502.        
  503.         $pickingCosts_OC = $pickingCosts_PC * $costRates->pickingOverheadPercent * 0.01;
  504.        
  505.         $sales_PC = $costRates->salesProcessPiece + ($costRates->salesProcessPercent * 0.01 * $manufacturingCosts) + $costRates->customerServiceProcessPiece + ($costRates->customerServiceProcessPercent * 0.01 * $manufacturingCosts);
  506.         $sales_OC = $sales_PC * $costRates->salesOverheadPercent * 0.01;
  507.        
  508.         $administrationCosts = $pickingCosts_PC + $pickingCosts_OC + $sales_PC + $sales_OC;
  509.         $administration_OC = $administrationCosts * $costRates->administrationOverheadPercent * 0.01;
  510.        
  511.         $unitCosts = $foilTypeCosts_UC + $packageParts_UC;
  512.         $processCosts = $foilTypeCosts_PC + $cuttingCosts_PC + $packagingCosts_PC + $machineCosts_PC + $pickingCosts_PC + $sales_PC;
  513.         $overheadCosts = $foilTypeCosts_OC + $packageParts_OC + $cuttingCosts_OC + $packagingCosts_OC + $machineCosts_OC + $production_OC + $pickingCosts_OC + $sales_OC + $administration_OC;
  514.        
  515.         $costPriceWithoutSurcharges = $unitCosts + $processCosts + $overheadCosts;
  516.        
  517.         $costPrice = $costPriceWithoutSurcharges * (1 + $costRates->processLossPercent * 0.01) + $costPriceWithoutSurcharges * (1 + $costRates->warrantyPercent * 0.01);
  518.        
  519.         // set costs to product
  520.         $product->costPrice = $costPrice;
  521.        
  522. //         $priceCondition->unitCosts = $unitCosts;
  523. //         $priceCondition->processCosts = $processCosts;
  524. //         $priceCondition->overheadCosts = $overheadCosts;
  525.    
  526.     }
  527.  
  528.     /**
  529.      * This function iterates throw all calculation model to calculate costs
  530.      * (price conditions)
  531.      * for every calculation model, that linked to erp group in which the given
  532.      * product is.
  533.      * After that price conditions will be saved (in savePriceConditions
  534.      * function).
  535.      * Used by create products cronjob.
  536.      * Used for film protectors project.
  537.      * Addition UC = unitCosts
  538.      * Addition PC = processCosts
  539.      * Addition OC = overheadCosts
  540.      */
  541.    
  542.     public static function changePriceConditions($product, $fromDate = NULL, $testPrice = false, $priceCondition) {
  543.        
  544.         // Get Main ERP Group for the product
  545.         $productHasERPGroups = ProductHasProductERPGroup::model()->findAll('product_id=' . $product->id . ' AND endGroup=1 ORDER BY standard DESC');
  546.         if (!empty($productHasERPGroups))
  547.             $productERPGroup_id = $productHasERPGroups[0]->productERPGroup_id;
  548.         else
  549.             $productERPGroup_id = NULL;
  550.            
  551.             // Loop all ERP Groups for most specific pricing models for rrp and all
  552.             // marketplaces
  553.         while ( !is_null($productERPGroup_id) ) {
  554.             $productERPGroup = ProductERPGroup::model()->findByPk($productERPGroup_id);
  555.             if (!$productERPGroup)
  556.                 break;
  557.                
  558.                 // get next ERP Group (parent)
  559.             $productERPGroup_id = $productERPGroup->productERPGroup_id;
  560.            
  561.             $calculationModels = $productERPGroup->calculationModels;
  562.             if (!empty($calculationModels)) {
  563.                 foreach($calculationModels as $calculationModel) {
  564.                     self::calculatePriceCondition($product, $calculationModel, $fromDate, $testPrice, $priceCondition);
  565.                 }
  566.             }
  567.         }
  568.    
  569.     }
  570.  
  571.     /**
  572.      * This function calculates price condition for given product and calculation
  573.      * model.
  574.      *
  575.      * @param Product $product
  576.      * @param CalculationModel $calculationModel
  577.      * @param Date $fromDate
  578.      * @param boolean $testPrice
  579.      */
  580.     public static function calculatePriceCondition($product, $calculationModel, $fromDate, $testPrice, $priceCondition) {
  581.        
  582.         $costPrice = $product->costPrice;
  583.         $costRates = $product->project->costRates[0];
  584.         if (empty($fromDate))
  585.             $fromDate = date('Y-m-d H:i:s');
  586.        
  587.         if ($testPrice)
  588.             $calculationModel = CalculationModel::model()->findByPk($calculationModel);
  589.        
  590.         $foundRRP = false;
  591.         $foundSalesThirdPartyMarketplaces = array();
  592.         // check if model is needed for pricing (rrp)
  593.         $saveRRP = false;
  594.         if (!$foundRRP && $calculationModel->priceConditionType_id == 1)
  595.             $saveRRP = true;
  596.            
  597.             // check if model is needed for pricing (marketplaces)
  598.         $salesThirdPartyMarketplaces = $calculationModel->salesThirdPartyMarketplaces;
  599.         if (!empty($salesThirdPartyMarketplaces)) {
  600.             for($i = 0; $i < count($salesThirdPartyMarketplaces); $i++) {
  601.                 // remove from array if already done
  602.                 if (in_array($salesThirdPartyMarketplaces[$i]->id, $foundSalesThirdPartyMarketplaces))
  603.                     unset($salesThirdPartyMarketplaces[$i]);
  604.             }
  605.         }
  606.        
  607.         if (!$saveRRP && count($salesThirdPartyMarketplaces) == 0)
  608.             continue;
  609.            
  610.             // costRangeRate = Percentage of costRange // min = 1% // max = 80% for
  611.             // discount and margin
  612.         $costRange = $calculationModel->costsTo - $calculationModel->costsFrom;
  613.         if ($costRange <= 0) {
  614.             $costRangeRate = 0.8;
  615.         } else {
  616.             $costRangeRate = max(min($costPrice, $calculationModel->costsTo), $calculationModel->costsFrom);
  617.             $costRangeRate = max(min($costRangeRate / $costRange, 0.8), 0.01);
  618.         }
  619.        
  620.         // Calculate dynamical marginRate (within range max marginFrom - min
  621.         // marginTo)
  622.         if ($calculationModel->marginFrom > $calculationModel->marginTo) {
  623.             $marginFrom = $calculationModel->marginTo * 0.01;
  624.             $marginTo = $calculationModel->marginFrom * 0.01;
  625.         } else {
  626.             $marginFrom = $calculationModel->marginFrom * 0.01;
  627.             $marginTo = $calculationModel->marginTo * 0.01;
  628.         }
  629.         $marginRange = $marginFrom - $marginTo;
  630.         $exponent = (1 - $marginFrom) * 0.1 / $costRangeRate;
  631.         $marginRate = $marginFrom - $marginRange * pow($costRangeRate, $exponent);
  632.         $margin = $costPrice * $marginRate;
  633.        
  634.         // Calculate dynamical discountRate (within range max marginFrom - min
  635.         // discountTo)
  636.         if ($calculationModel->discountFrom > $calculationModel->discountTo) {
  637.             $discountFrom = $calculationModel->discountTo * 0.01;
  638.             $discountTo = $calculationModel->discountFrom * 0.01;
  639.         } else {
  640.             $discountFrom = $calculationModel->discountFrom * 0.01;
  641.             $discountTo = $calculationModel->discountTo * 0.01;
  642.         }
  643.         $discountRange = $discountFrom - $discountTo;
  644.         $exponent = (1 - $discountFrom) * 0.1 / $costRangeRate;
  645.         $discountRate = $discountFrom - $discountRange * pow($costRangeRate, $exponent);
  646.        
  647.         // select all exchange rules for this calculation model
  648.         $sql = "SELECT exchangeRule_id
  649.                        FROM exchangeRule_has_calculationModel
  650.                        WHERE calculationModel_id=" . $calculationModel->id;
  651.         $exchangeRuleIDs = Yii::app()->db->createCommand($sql)->queryAll();
  652.         if (empty($exchangeRuleIDs))
  653.             continue;
  654.         $exchangeRules = array();
  655.         foreach($exchangeRuleIDs as $exchangeRuleID) {
  656.             $exchangeRules[] = ExchangeRule::model()->findByPk($exchangeRuleID['exchangeRule_id']);
  657.         }
  658.        
  659.         if ($saveRRP) {
  660.            
  661.             $additionalCosts = $costPrice * $costRates->paymentCostsPercent * 0.01 + $costPrice * $costRates->sellingFeesPercent * 0.01;
  662.             $targetPrice = $product->costPrice + $margin + $additionalCosts;
  663.             $discountSurcharge = $targetPrice * $discountRate;
  664.             $price = $targetPrice * (1 + $discountRate);
  665.            
  666.             // echo 'Selbstkosten: ' . $product->costPrice . '<br>';
  667.             // echo '$price: ' . $price . '<br>';
  668.             foreach($exchangeRules as $exchangeRule) {
  669.                 if ($testPrice) {
  670.                     if ($exchangeRule->currency_id == 0)
  671.                         return Helper::moneyForm(self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition), 2, NULL, true, "€");
  672.                 } else {
  673.                     self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition);
  674.                 }
  675.             }
  676.         }
  677.        
  678.         foreach($salesThirdPartyMarketplaces as $salesThirdPartyMarketplace) {
  679.            
  680.             $additionalCosts = max($product->costPrice * $salesThirdPartyMarketplace->sellingFeePercent, $salesThirdPartyMarketplace->sellingFeeMin);
  681.             $additionalCosts += $product->costPrice * $salesThirdPartyMarketplace->paymentCostsPercent;
  682.             $targetPrice = $costPrice + $margin + $additionalCosts;
  683.             $discountSurcharge = $targetPrice * $discountRate;
  684.             $price = $targetPrice * (1 + $discountRate);
  685.             foreach($exchangeRules as $exchangeRule) {
  686.                 if ($salesThirdPartyMarketplace->currency_id != $exchangeRule->currency_id) {
  687.                     // currency not needed for marcet place
  688.                     // continue;
  689.                 }
  690.                 if ($testPrice) {
  691.                     if ($exchangeRule->currency_id == 0)
  692.                         return Helper::moneyForm(self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition), 2, NULL, true, "€");
  693.                 } else {
  694.                     self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, $salesThirdPartyMarketplace, $fromDate, $testPrice, $priceCondition);
  695.                 }
  696.            
  697.             }
  698.         }
  699.    
  700.     }
  701.  
  702.     private static function savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, $salesThirdPartyMarketplace, $fromDate, $testPrice = false, $priceCondition) {
  703.         if (!isset($priceCondition))
  704.             $priceCondition = new PriceCondition();
  705.        
  706.         $priceCondition->active = 1;
  707.         $priceCondition->product_id = $product->id;
  708.         $priceCondition->currency_id = $exchangeRule->currency_id;
  709.         $priceCondition->priceConditionType_id = $calculationModel->priceConditionType_id;
  710.         $priceCondition->calculationModel_id = $calculationModel->id;
  711.         $priceCondition->exchangeRate = $exchangeRule->currency->exchangeRate;
  712.         $price = $price * (1 + $exchangeRule->surchargePercent * 0.01) * $priceCondition->exchangeRate;
  713.        
  714.         if ($testPrice) {
  715.             return round($exchangeRule->minPrice + ceil(($price - $exchangeRule->minPrice) / $exchangeRule->priceSteps) * $exchangeRule->priceSteps, 4);
  716.         } else {
  717.             $priceCondition->price = round($exchangeRule->minPrice + ceil(($price - $exchangeRule->minPrice) / $exchangeRule->priceSteps) * $exchangeRule->priceSteps, 4);
  718.         }
  719.        
  720.         $priceCondition->costPrice = round($product->costPrice, 4);
  721.        
  722.         $priceCondition->discountSurcharge = round($discountSurcharge, 4);
  723.         $priceCondition->margin = round($margin, 4);
  724.        
  725.         // costRangeRate = Percentage of costRange // min = 1% // max = 80% for
  726.         // shippingCosts
  727.         $costRange = $calculationModel->priceTo - $calculationModel->priceFrom;
  728.         if ($costRange <= 0) {
  729.             $costRangeRate = 0.8;
  730.         } else {
  731.             $costRangeRate = max(min($priceCondition->price, $calculationModel->priceTo), $calculationModel->priceFrom);
  732.             $costRangeRate = max(min($costRangeRate / $costRange, 0.8), 0.01);
  733.         }
  734.        
  735.         // Calculate dynamical shippingCosts (within range max shippingCostsFrom
  736.         // - min shippingCostsTo)
  737.         if ($calculationModel->shippingCostsFrom > $calculationModel->shippingCostsTo) {
  738.             $shippingCostsFrom = $calculationModel->shippingCostsTo;
  739.             $shippingCostsTo = $calculationModel->shippingCostsFrom;
  740.         } else {
  741.             $shippingCostsFrom = $calculationModel->shippingCostsFrom;
  742.             $shippingCostsTo = $calculationModel->shippingCostsTo;
  743.         }
  744.         $shippingCostsRange = $shippingCostsFrom - $shippingCostsTo;
  745.         $exponent = (1 - $shippingCostsFrom) * 0.1 / $costRangeRate;
  746.         $shippingCosts = $shippingCostsFrom - $shippingCostsRange * pow($costRangeRate, $exponent);
  747.        
  748.         $priceCondition->shippingCosts = round($shippingCosts, 4);
  749.        
  750.         $priceCondition->fromDate = $fromDate;
  751.        
  752.         $oldPriceCondition = null;
  753.         if (!empty($salesThirdPartyMarketplaces)) {
  754.             $sql = 'SELECT p.id AS id
  755.                    FROM priceCondition p
  756.                    LEFT JOIN priceCondition_has_salesThirdPartyMarketplace pchs ON phs.priceCondition_id = p.id
  757.                    WHERE p.product_id = ' . $priceCondition->product_id . ' AND p.currency_id=' . $priceCondition->currency_id . '
  758.                        AND p.priceConditionTyp_id=' . $priceCondition->priceConditionTyp_id . '
  759.                        AND phs.salesThirdPartyMarketplace_id = ' . $salesThirdPartyMarketplaces[0]->id;
  760.             $oldPriceConditionIDs = Yii::app()->db->createCommand($sql)->queryAll();
  761.             if (empty($oldPriceConditionIDs))
  762.                 $oldPriceCondition = PriceCondition::model()->findByPk($oldPriceConditionIDs[0]['id']);
  763.         } else {
  764.             $oldPriceCondition = PriceCondition::model()->find('product_id=' . $priceCondition->product_id . ' AND currency_id=' . $priceCondition->currency_id . ' AND priceConditionType_id=' . $priceCondition->priceConditionType_id . ' AND toDate IS NULL');
  765.         }
  766.        
  767.         // check if new or relevant changes to price condition
  768.         if (empty($oldPriceCondition) || $oldPriceCondition->exchangeRate != $priceCondition->exchangeRate || $oldPriceCondition->price != $priceCondition->price || $oldPriceCondition->costPrice != $priceCondition->costPrice || $oldPriceCondition->discountSurcharge != $priceCondition->discountSurcharge || $oldPriceCondition->margin != $priceCondition->margin || $oldPriceCondition->shippingCosts != $priceCondition->shippingCosts) {
  769.             if ($priceCondition->validate()) {
  770.                 // save new one
  771.                 $priceCondition->save(false);
  772.                 // add marketplace connection
  773.                 if (!empty($salesThirdPartyMarketplaces)) {
  774.                     foreach($salesThirdPartyMarketplaces as $salesThirdPartyMarketplace) {
  775.                         $sql = 'INSERT INTO priceCondition_has_salesThirdPartyMarketplace (priceCondition_id, salesThirdPartyMarketplace_id)
  776.                            VALUES (' . $priceCondition->id . ', ' . $salesThirdPartyMarketplace->id . ')';
  777.                         Yii::app()->db->createCommand($sql)->query();
  778.                     }
  779.                 }
  780.                
  781.                 if (!empty($oldPriceCondition)) {
  782.                     // end old price condition
  783.                     $oldPriceCondition->toDate = $fromDate;
  784.                     $oldPriceCondition->save(false);
  785.                 }
  786.             } else {
  787.                 $error = new ErrorLog();
  788.                 $error->errorLogType_id = 4;
  789.                 $error->text = 'Pricing invalid. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
  790.                 $error->save(false);
  791.                 return false;
  792.             }
  793.         }
  794.     }
  795.  
  796.     /**
  797.      * Function to create a product in film protection project
  798.      *
  799.      * @param int $packageID
  800.      * @param string $custom
  801.      * @param string $return
  802.      * @return boolean|string|Product|number
  803.      */
  804.     public static function createProductFromPackage($packageID, $return = false) {
  805.         // Setup time sheet for testing
  806.         exec('rm -rf ' . Yii::app()->basePath . '/../times.csv');
  807.         $path = Yii::app()->basePath . '/../times.csv';
  808.         $fp = fopen($path, "a+");
  809.        
  810.         $times = array();
  811.         $allTime = microtime(true);
  812.         $time = microtime(true);
  813.        
  814.         $product = new Product();
  815.         $package = Package::model()->findByPk($packageID);
  816.         if (empty($package)) {
  817.             $error = new ErrorLog();
  818.             $error->errorLogType_id = 4;
  819.             $error->text = 'Package ' . $packageID . ' doesnt exist!';
  820.             $error->save(false);
  821.             return false;
  822.         }
  823.        
  824.         $sql = 'SELECT mhp.product_id AS pid
  825.        FROM module AS m
  826.        LEFT JOIN module_has_product AS mhp ON mhp.module_id = m.id
  827.        WHERE m.id=' . $packageID . '
  828.        AND mhp.product_id IS NOT NULL';
  829.         $eProduct = Yii::app()->db->createCommand($sql)->queryRow();
  830.         if (!empty($eProduct)) {
  831.             $error = new ErrorLog();
  832.             $error->errorLogType_id = 4;
  833.             $error->text = 'Package ' . $packageID . ' already has a product <a target="_blank" href="/project/product/update?id=' . $eProduct['pid'] . '">' . $eProduct['pid'] . '</a>!';
  834.             $error->save(false);
  835.             return false;
  836.         }
  837.        
  838.         /**
  839.          * If product from previous system get the old EAN code
  840.          * TODO: remove after migration to new platform
  841.          */
  842.         if (!$package->old_ean) {
  843.             $product->ean = Ean::model()->getFreeEANCode();
  844.             if ($product->ean == 0)
  845.                 die('No free EAN Codes!');
  846.         } else {
  847.             $product->ean = $package->old_ean;
  848.         }
  849.        
  850.         // Init help values
  851.         $createDate = $package->module->createDate;
  852.         $project = $package->module->moduleGroup->projects[0];
  853.         $productActive = true;
  854.         // will be false if not active later
  855.        
  856.         // Get product parts
  857.         $foilTypeUnity = $package->foilTypeUnityModule;
  858.         if ($foilTypeUnity->module->active == 0)
  859.             $productActive = false;
  860.         $foilType = $foilTypeUnity->foilType;
  861.         if ($foilType->active == 0)
  862.             $productActive = false;
  863.         $sizes = array();
  864.         $sizesIDs = array();
  865.         $standardSize = null;
  866.         $deviceSize = null;
  867.         $device = null;
  868.         $phs = PackageHasSize::model()->findAll('package_module_id=' . $packageID);
  869.         foreach($phs as $ps) {
  870.             $size = Size::model()->findByPk($ps->size_module_id);
  871.             if ($size->module->active == 0)
  872.                 $productActive = false;
  873.                 // Skip products, that are connected to blocked sizes or size doesnt
  874.                 // have size version
  875.             if ($size->blocked || empty($size->sizeVersions))
  876.                 return false;
  877.             $sizes[] = $size;
  878.             $sizeIDs[] = $ps->size_module_id;
  879.             if ($standardSize == null || $size->sizeType_id == Yii::app()->params['standardSize'])
  880.                 $standardSize = $size;
  881.             if ($size->sizeType_id == Yii::app()->params['deviceSize'])
  882.                 $deviceSize = $size;
  883.             if ($ps->device_module_id) {
  884.                 $device = Device::model()->findByPk($ps->device_module_id);
  885.                 if ($device->module->active == 0)
  886.                     $productActive = false;
  887.             }
  888.         }
  889.         if (!empty($device)) {
  890.             $standardSize = $deviceSize;
  891.         }
  892.        
  893.         // Change the ID of the product from the old system
  894.         if ($foilTypeUnity->module_id != 2 && $device) {
  895.             $product->id = $package->old_package_id;
  896.         } elseif ($foilTypeUnity->module_id == 2 && $device) {
  897.             $product->id = 1300000 + $device->old_device_id;
  898.         }
  899.        
  900.         $times['Initialise'] = microtime(true) - $time;
  901.         $time = microtime(true);
  902.        
  903.         /**
  904.          * Check if the same physical product for selected
  905.          * sizes and foil type unity already exists
  906.          */
  907.         $sql = 'SELECT p.physicalProduct_id AS pid
  908.        FROM module AS m
  909.        LEFT JOIN module_has_product AS mhp ON mhp.module_id = m.id
  910.        LEFT JOIN product AS p ON mhp.product_id=p.id
  911.        WHERE (m.id IN (' . implode(',', $sizeIDs) . ') AND m.moduleGroup_id=2)
  912.        OR (m.id=' . $foilTypeUnity->module_id . ' AND m.moduleGroup_id=3)
  913.        GROUP BY mhp.product_id HAVING COUNT(*)=' . (count($sizeIDs) + 1);
  914.         $existPProduct = Yii::app()->db->createCommand($sql)->queryRow();
  915.        
  916.         $times['Check existing'] = microtime(true) - $time;
  917.         $time = microtime(true);
  918.        
  919.         if (!empty($existPProduct))
  920.             $pProduct = PhysicalProduct::model()->findByPk($existPProduct['pid']);
  921.         if (empty($pProduct))
  922.             $pProduct = new PhysicalProduct();
  923.         $packageSize = $package->packageSize;
  924.         $pProduct->width = $packageSize->width;
  925.         $pProduct->height = $packageSize->height;
  926.         $pProduct->depth = $packageSize->depth;
  927.         $pProduct->weight = ceil(($foilTypeUnity->unity * $foilType->weight)) + $packageSize->weight;
  928.         $pProduct->manufacturer_id = $foilType->productManufacturer_id;
  929.         $pProduct->manufacturerSKU = '##reload##';
  930.         $pProduct->getsLabel = 0;
  931.         $pProduct->ownProduction = 1;
  932.         if ($pProduct->validate()) {
  933.             $pProduct->save(false);
  934.         } else {
  935.             $error = new ErrorLog();
  936.             $error->errorLogType_id = 4;
  937.             $pError = var_export($pProduct->errors, true);
  938.             $pValues = var_export($pProduct->attributes, true);
  939.             $error->text = "Physical product has errors. Package: " . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>' . $pError . ' values: ' . $pValues;
  940.             $error->save(false);
  941.             return false;
  942.         }
  943.         if ($pProduct->manufacturerSKU == '##reload##') {
  944.             $pProduct->manufacturerSKU = $pProduct->getPrimaryKey();
  945.             $pProduct->save(false);
  946.         }
  947.        
  948.         switch ($standardSize->sizeType_id) {
  949.             case Yii::app()->params['deviceSize'] :
  950.                 $titleValue = 'deviceProductTitleFormula';
  951.                 $shortTitleValue = 'deviceProductShortTitleFormula';
  952.                 break;
  953.             case Yii::app()->params['standardSize'] :
  954.                 $titleValue = 'standardProductTitleFormula';
  955.                 $shortTitleValue = 'standardProductShortTitleFormula';
  956.                 break;
  957.             case Yii::app()->params['customSize'] :
  958.                 $titleValue = 'customProductTitleFormula';
  959.                 $shortTitleValue = 'customProductShortTitleFormula';
  960.                 break;
  961.             case Yii::app()->params['customerSize'] :
  962.                 $titleValue = 'customerProductTitleFormula';
  963.                 $shortTitleValue = 'customerProductShortTitleFormula';
  964.                 break;
  965.             default :
  966.                 $titleValue = 'standardProductTitleFormula';
  967.                 $shortTitleValue = 'standardProductShortTitleFormula';
  968.                 break;
  969.         }
  970.        
  971.         $product->title = array();
  972.         $product->shortTitle = array();
  973.         // ***
  974.         $product->description = array();
  975.         $product->shortDescription = array();
  976.         $product->deliveryScope = array();
  977.         $product->langActive = $foilType->langActive;
  978.        
  979.         $decodeParams = array();
  980.         $decodeParams['project'] = $project;
  981.         if (!empty($device)) {
  982.             $decodeParams['device'] = $device;
  983.             $decodeParams['deviceType'] = $device->deviceType;
  984.         }
  985.         $decodeParams['foilType'] = $foilType;
  986.         $decodeParams['bulletPoints'] = $foilType->bulletPoints;
  987.         $decodeParams['foilTypeUnity'] = $foilTypeUnity;
  988.         $decodeParams['size'] = $standardSize;
  989.         $decodeParams['sizes'] = $sizes;
  990.        
  991.         $foilTypeTitles = $foilType->$titleValue;
  992.         $foilTypeShortTitles = $foilType->$shortTitleValue;
  993.        
  994.         $languages = Language::model()->findAll('active=1');
  995.         if (!empty($languages)) {
  996.             foreach($languages as $lang) {
  997.                 $product->title[$lang->isoCode] = Helper::decodeModuleValues($foilTypeTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
  998.                 // ***
  999.                 if ($product->title[$lang->isoCode] === false) {
  1000.                     if (empty($existPProduct))
  1001.                         $pProduct->delete();
  1002.                     $error = new ErrorLog();
  1003.                     $error->errorLogType_id = 4;
  1004.                     $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>has error in title for language: ' . $lang->isoCode;
  1005.                     $error->save(false);
  1006.                     return false;
  1007.                 }
  1008.                 $product->shortTitle[$lang->isoCode] = Helper::decodeModuleValues($foilTypeShortTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
  1009.                 if ($product->title[$lang->isoCode] === false) {
  1010.                     if (empty($existPProduct))
  1011.                         $pProduct->delete();
  1012.                     $error = new ErrorLog();
  1013.                     $error->errorLogType_id = 4;
  1014.                     $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>has error in shortTitle for language: ' . $lang->isoCode;
  1015.                     $error->save(false);
  1016.                     return false;
  1017.                 }
  1018.                 $product->description[$lang->isoCode] = Helper::decodeModuleValues($foilType->productDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
  1019.                 if ($product->title[$lang->isoCode] === false) {
  1020.                     if (empty($existPProduct))
  1021.                         $pProduct->delete();
  1022.                     $error = new ErrorLog();
  1023.                     $error->errorLogType_id = 4;
  1024.                     $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>has error in description for language: ' . $lang->isoCode;
  1025.                     $error->save(false);
  1026.                     return false;
  1027.                 }
  1028.                 $product->shortDescription[$lang->isoCode] = Helper::decodeModuleValues($foilType->productShortDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
  1029.                 if ($product->title[$lang->isoCode] === false) {
  1030.                     if (empty($existPProduct))
  1031.                         $pProduct->delete();
  1032.                     $error = new ErrorLog();
  1033.                     $error->errorLogType_id = 4;
  1034.                     $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>has error in shortDescription for language: ' . $lang->isoCode;
  1035.                     $error->save(false);
  1036.                     return false;
  1037.                 }
  1038.                 $product->deliveryScope[$lang->isoCode] = Helper::decodeModuleValues($foilType->deliveryScope[$lang->isoCode], $decodeParams, $lang->isoCode);
  1039.                 if ($product->title[$lang->isoCode] === false) {
  1040.                     if (empty($existPProduct))
  1041.                         $pProduct->delete();
  1042.                     $error = new ErrorLog();
  1043.                     $error->errorLogType_id = 4;
  1044.                     $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/>has error in deliveryScope for language: ' . $lang->isoCode;
  1045.                     $error->save(false);
  1046.                     return false;
  1047.                 }
  1048.             }
  1049.         }
  1050.         $product->project_id = $project->id;
  1051.         $product->physicalProduct_id = $pProduct->getPrimaryKey();
  1052.         $product->createDate = $createDate;
  1053.         $product->lastUpdate = date('Y-m-d H:i:s');
  1054.         $product->active = intval($productActive);
  1055.         $product->availableFromDate = date('Y-m-d H:i:s', max(array(
  1056.             strtotime($standardSize->saleStartDate),
  1057.             time() + 60 * 60 * 2
  1058.         )));
  1059.         if (!empty($standardSize->saleEndDate))
  1060.             $product->availableToDate = date('Y-m-d H:i:s', strtotime($standardSize->saleEndDate));
  1061.         if (strtotime($product->availableFromDate) > time())
  1062.             $product->available = 0;
  1063.         else
  1064.             $product->available = 1;
  1065.        
  1066.         $product->originCountry_id = $foilType->productCountry_id;
  1067.         $product->brand_id = $foilType->brand_id;
  1068.        
  1069.         $product->productType_id = 1;
  1070.         $product->productLine_id = $foilType->productLine_id;
  1071.        
  1072.         $times['Creating metas'] = microtime(true) - $time;
  1073.         $time = microtime(true);
  1074.        
  1075.        
  1076.         $priceCondition = new PriceCondition();
  1077.         self::calculateCostsFromPackage($product, $foilTypeUnity, $packageSize, $sizes, $priceCondition);
  1078.        
  1079.         if ($product->validate() && $product->save(false)) {
  1080.             Helper::saveMultiligualParameter($product, array(
  1081.                 'langActive',
  1082.                 'title',
  1083.                 'shortTitle',
  1084.                 'description',
  1085.                 'shortDescription',
  1086.                 'deliveryScope'
  1087.             ));
  1088.             Ean::model()->blockEANCode($product->ean);
  1089.         } else {
  1090.             if (empty($existPProduct))
  1091.                 $pProduct->delete();
  1092.             $error = new ErrorLog();
  1093.             $error->errorLogType_id = 4;
  1094.             $pError = var_export($product->errors, true);
  1095.             $pValues = var_export($product->attributes, true);
  1096.             $error->text = 'Package: ' . $packageID . ', Size: <a target="_blank" href="/project/size/update/id/' . $standardSize->module_id . '">' . $standardSize->module_id . '</a><br/> Product has error: ' . $pError . ' values: ' . $pValues;
  1097.             $error->save(false);
  1098.             return false;
  1099.         }
  1100.        
  1101.         $times['Saving product'] = microtime(true) - $time;
  1102.         $time = microtime(true);
  1103.        
  1104.         // Create categories
  1105.         $categories = self::generateCategories($product, $foilType->categoryFormula, $decodeParams);
  1106.         if ($categories === false) {
  1107.             $sql = 'DELETE FROM `module_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
  1108.                    DELETE FROM `projectNote` WHERE product_id=product_id=' . $product->getPrimaryKey() . ';
  1109.                    DELETE FROM `product_has_bulletPoints` WHERE product_id=' . $product->getPrimaryKey() . ';
  1110.                    DELETE FROM `product_has_keywords` WHERE product_id=' . $product->getPrimaryKey() . ';
  1111.                    DELETE FROM `product_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
  1112.                    DELETE FROM `product_has_productCategory` WHERE product_id=' . $product->getPrimaryKey() . ';
  1113.                    DELETE FROM `product_has_productERPGroup` WHERE product_id=' . $product->getPrimaryKey() . ';
  1114.                    DELETE FROM `product_has_productFeatureValue` WHERE product_id=' . $product->getPrimaryKey() . ';
  1115.                    DELETE FROM `product_has_media` WHERE product_id=' . $product->getPrimaryKey() . ';
  1116.                    DELETE FROM `product_translation` WHERE product_id=' . $product->getPrimaryKey() . ';
  1117.                    DELETE FROM `product` WHERE id=' . $product->getPrimaryKey() . ';';
  1118.             Yii::app()->db->createCommand($sql)->execute();
  1119.             if (empty($existPProduct))
  1120.                 $pProduct->delete();
  1121.             $error = new ErrorLog();
  1122.             $error->errorLogType_id = 4;
  1123.             $error->subject = 'Product categories have errors';
  1124.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1125.             $error->save(false);
  1126.             return false;
  1127.         }
  1128.        
  1129.         $times['Create categories'] = microtime(true) - $time;
  1130.         $time = microtime(true);
  1131.        
  1132.         // Create ERP Groups
  1133.         $erpGroups = self::generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams);
  1134.         if ($erpGroups === false) {
  1135.             $sql = 'DELETE FROM `module_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
  1136.                    DELETE FROM `projectNote` WHERE product_id=product_id=' . $product->getPrimaryKey() . ';
  1137.                    DELETE FROM `product_has_bulletPoints` WHERE product_id=' . $product->getPrimaryKey() . ';
  1138.                    DELETE FROM `product_has_keywords` WHERE product_id=' . $product->getPrimaryKey() . ';
  1139.                    DELETE FROM `product_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
  1140.                    DELETE FROM `product_has_productCategory` WHERE product_id=' . $product->getPrimaryKey() . ';
  1141.                    DELETE FROM `product_has_productERPGroup` WHERE product_id=' . $product->getPrimaryKey() . ';
  1142.                    DELETE FROM `product_has_productFeatureValue` WHERE product_id=' . $product->getPrimaryKey() . ';
  1143.                    DELETE FROM `product_has_media` WHERE product_id=' . $product->getPrimaryKey() . ';
  1144.                    DELETE FROM `product_translation` WHERE product_id=' . $product->getPrimaryKey() . ';
  1145.                    DELETE FROM `product` WHERE id=' . $product->getPrimaryKey() . ';';
  1146.             Yii::app()->db->createCommand($sql)->execute();
  1147.             if (empty($existPProduct))
  1148.                 $pProduct->delete();
  1149.             $error = new ErrorLog();
  1150.             $error->errorLogType_id = 4;
  1151.             $error->subject = 'ERP Groups have errors';
  1152.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1153.             $error->save(false);
  1154.             return false;
  1155.         }
  1156.        
  1157.         $times['Create ERP groups'] = microtime(true) - $time;
  1158.         $time = microtime(true);
  1159.        
  1160.         // Connect keywords
  1161.         $keywords = $foilType->keywords;
  1162.         if (!empty($device)) {
  1163.             if (is_array($keywords))
  1164.                 $keywords = array_merge($keywords, $device->keywords);
  1165.             else
  1166.                 $keywords = $device->keywords;
  1167.         }
  1168.         if (!empty($keywords)) {
  1169.             $values = ' VALUES ';
  1170.             foreach($keywords as $key=>$word) {
  1171.                 $values .= '(' . $product->id . ', ' . $word->id . ')';
  1172.                 if ($key < count($keywords) - 1)
  1173.                     $values .= ',';
  1174.             }
  1175.             $sql = 'INSERT INTO product_has_keywords ' . $values;
  1176.             Yii::app()->db->createCommand($sql)->query();
  1177.         } else {
  1178.             $error = new ErrorLog();
  1179.             $error->errorLogType_id = 4;
  1180.             $error->text = 'Products keywords are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1181.             $error->save(false);
  1182.         }
  1183.        
  1184.         $times['Connect keywords'] = microtime(true) - $time;
  1185.         $time = microtime(true);
  1186.        
  1187.         // Connect bulletpoints
  1188.         $bulletPoints = $foilType->bulletPoints;
  1189.         if (!empty($bulletPoints)) {
  1190.             $values = ' VALUES ';
  1191.             foreach($bulletPoints as $key=>$point) {
  1192.                 $values .= '(' . $product->id . ', ' . $point->id . ')';
  1193.                 if ($key < count($bulletPoints) - 1)
  1194.                     $values .= ',';
  1195.             }
  1196.             $sql = 'INSERT INTO product_has_bulletPoints ' . $values;
  1197.             Yii::app()->db->createCommand($sql)->query();
  1198.         } else {
  1199.             $error = new ErrorLog();
  1200.             $error->errorLogType_id = 4;
  1201.             $error->text = 'Products bulletpoints are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1202.             $error->save(false);
  1203.         }
  1204.        
  1205.         $times['Connect bulletpoints'] = microtime(true) - $time;
  1206.         $time = microtime(true);
  1207.        
  1208.         // Connect product features
  1209.         $productFeatureValues = $foilType->productFeatureValues;
  1210.         if (!empty($productFeatureValues)) {
  1211.             $values = ' VALUES ';
  1212.             foreach($productFeatureValues as $value) {
  1213.                 $values .= '(' . $product->id . ', ' . $value->id . ', 0)';
  1214.                 if ($value != end($productFeatureValues))
  1215.                     $values .= ',';
  1216.             }
  1217.             $sql = 'INSERT INTO product_has_productFeatureValue ' . $values;
  1218.             Yii::app()->db->createCommand($sql)->query();
  1219.         } else {
  1220.             $error = new ErrorLog();
  1221.             $error->errorLogType_id = 4;
  1222.             $error->text = 'Products features are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1223.             $error->save(false);
  1224.         }
  1225.        
  1226.         $times['Connect product features'] = microtime(true) - $time;
  1227.         $time = microtime(true);
  1228.        
  1229.         // Get all product modules
  1230.         $pModulesIDs = array(
  1231.             $packageID
  1232.         );
  1233.         if ($device != null && $device->module_id)
  1234.             $pModulesIDs[] = $device->module_id;
  1235.         foreach($sizes as $size)
  1236.             $pModulesIDs[] = $size->module_id;
  1237.         $pModulesIDs[] = $foilTypeUnity->module_id;
  1238.         $pModulesIDs = array_filter($pModulesIDs);
  1239.        
  1240.         // Create medias for product
  1241.         $sql = 'SELECT mm.media_id as id
  1242.                FROM module_has_media AS mm
  1243.                LEFT JOIN media AS m ON m.id=mm.media_id
  1244.                LEFT JOIN mediaType AS mt ON mt.id=m.mediaType_id
  1245.                WHERE mm.module_id IN(' . implode(',', $pModulesIDs) . ')
  1246.                    AND mt.productSpecific=1';
  1247.         $medias = Yii::app()->db->createCommand($sql)->queryAll();
  1248.         if (!empty($medias)) {
  1249.             foreach($medias as $media) {
  1250.                 $sql = 'INSERT INTO product_has_media(media_id,product_id) VALUES(' . $media['id'] . ',' . $product->id . ')';
  1251.                 Yii::app()->db->createCommand($sql)->query();
  1252.             }
  1253.         }
  1254.        
  1255.         $times['Bind medias to product'] = microtime(true) - $time;
  1256.         $time = microtime(true);
  1257.        
  1258.         // Bind product with modules
  1259.         $values = ' VALUES ';
  1260.         foreach($pModulesIDs as $pm) {
  1261.             $values .= '(' . $pm . ',' . $product->id . ')';
  1262.             if ($pm != end($pModulesIDs))
  1263.                 $values .= ',';
  1264.         }
  1265.         $sql = 'INSERT INTO module_has_product ' . $values;
  1266.         Yii::app()->db->createCommand($sql)->query();
  1267.        
  1268.         $times['Bind modules to product'] = microtime(true) - $time;
  1269.         $time = microtime(true);
  1270.        
  1271.         // create or update price conditions
  1272.         self::changePriceConditions($product, null, false, $priceCondition);
  1273.        
  1274.         $times['Price conditions generation'] = microtime(true) - $time;
  1275.         $time = microtime(true);
  1276.        
  1277.         $times[] = microtime(true) - $allTime;
  1278.         $times[] = $product->id;
  1279.        
  1280.         fputcsv($fp, $times);
  1281.         fclose($fp);
  1282.        
  1283.         if (!empty($product->editOwnerUser_id) && $standardSize->sizeType_id == Yii::app()->params['customerSize']) {
  1284.             $conversation = new ChatConversation();
  1285.             $conversation->subject = 'Product is ready';
  1286.             $conversation->senderRead = 1;
  1287.             $conversation->recipientRead = 0;
  1288.             $conversation->sender_id = 0;
  1289.             $conversation->recipient_id = $product->editOwnerUser_id;
  1290.             $conversation->save(false);
  1291.             $message = new ChatMessage();
  1292.             $message->text = 'Product has been created: <a target="_blank" href="/project/product/update/id/' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1293.             $message->chatConversation_id = $conversation->getPrimaryKey();
  1294.             $message->sender_id = 0;
  1295.             $message->save(false);
  1296.         }
  1297.        
  1298.         if ($return)
  1299.             return $product;
  1300.         else
  1301.             return $product->id;
  1302.     }
  1303.  
  1304.     /**
  1305.      * Update product
  1306.      */
  1307.     public function updateProductFromPackageById($id, $return = false) {
  1308.         $product = Product::model()->findByPk($id);
  1309.         $_product = $product->attributes;
  1310.         if (empty($product)) {
  1311.             $error = new ErrorLog();
  1312.             $error->errorLogType_id = 4;
  1313.             $error->subject = 'Product doesnt exist';
  1314.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1315.             $error->save(false);
  1316.             return false;
  1317.         }
  1318.         $pProduct = $product->physicalProduct;
  1319.         $_pProduct = $pProduct->attributes;
  1320.         if (empty($pProduct)) {
  1321.             $error = new ErrorLog();
  1322.             $error->errorLogType_id = 4;
  1323.             $error->subject = 'Physical product doesnt exist';
  1324.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1325.             $error->save(false);
  1326.             return false;
  1327.         }
  1328.        
  1329.         // Remove old changes and create new changes array
  1330.         $sql = 'DELETE FROM productManualChanges WHERE product_id=' . $product->getPrimaryKey();
  1331.         Yii::app()->db->createCommand($sql)->execute();
  1332.         $productChanges = array();
  1333.        
  1334.         // Get product parts
  1335.         $productActive = 1;
  1336.         $pParts = $product->getParts();
  1337.         if (empty($pParts)) {
  1338.             $error = new ErrorLog();
  1339.             $error->errorLogType_id = 4;
  1340.             $error->subject = 'Modules are missing';
  1341.             $error->text = 'Product modules empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
  1342.             $error->save(false);
  1343.             return false;
  1344.         }
  1345.         $package = $pParts['package'];
  1346.         if ($package->module->active == 0)
  1347.             $productActive = 0;
  1348.         $foilTypeUnity = $pParts['unity'];
  1349.         if ($foilTypeUnity->module->active == 0)
  1350.             $productActive = 0;
  1351.         $foilType = $pParts['foilType'];
  1352.         if ($foilType->active == 0)
  1353.             $productActive = 0;
  1354.         $sizes = $pParts['sizes'];
  1355.         $standardSize = $pParts['standardSize'];
  1356.         $sizesIDs = array();
  1357.         foreach($sizes as $size) {
  1358.             if ($size->module->active == 0)
  1359.                 $productActive = 0;
  1360.             if ($size->blocked || empty($size->sizeVersions))
  1361.                 continue;
  1362.             if ($standardSize == null || $size->sizeType_id == Yii::app()->params['standardSize'])
  1363.                 $standardSize = $size;
  1364.             $sizeIDs[] = $size->module_id;
  1365.         }
  1366.         if (isset($pParts['device'])) {
  1367.             $device = $pParts['device'];
  1368.             if ($device->module->active == 0)
  1369.                 $productActive = 0;
  1370.             $standardSize = $pParts['deviceSize'];
  1371.         }
  1372.         $product->active = $productActive;
  1373.        
  1374.         $packageSize = $package->packageSize;
  1375.         $pProduct->width = $packageSize->width;
  1376.         $pProduct->height = $packageSize->height;
  1377.         $pProduct->depth = $packageSize->depth;
  1378.         $pProduct->weight = ceil(($foilTypeUnity->unity * $foilType->weight)) + $packageSize->weight;
  1379.         $pProduct->manufacturer_id = $foilType->productManufacturer_id;
  1380.         $pProduct->getsLabel = 0;
  1381.         $pProduct->ownProduction = 1;
  1382.        
  1383.         switch ($standardSize->sizeType_id) {
  1384.             case Yii::app()->params['deviceSize'] :
  1385.                 $titleValue = 'deviceProductTitleFormula';
  1386.                 $shortTitleValue = 'deviceProductShortTitleFormula';
  1387.                 break;
  1388.             case Yii::app()->params['standardSize'] :
  1389.                 $titleValue = 'standardProductTitleFormula';
  1390.                 $shortTitleValue = 'standardProductShortTitleFormula';
  1391.                 break;
  1392.             case Yii::app()->params['customSize'] :
  1393.                 $titleValue = 'customProductTitleFormula';
  1394.                 $shortTitleValue = 'customProductShortTitleFormula';
  1395.                 break;
  1396.             case Yii::app()->params['customerSize'] :
  1397.                 $titleValue = 'customerProductTitleFormula';
  1398.                 $shortTitleValue = 'customerProductShortTitleFormula';
  1399.                 break;
  1400.             default :
  1401.                 $titleValue = 'standardProductTitleFormula';
  1402.                 $shortTitleValue = 'standardProductShortTitleFormula';
  1403.                 break;
  1404.         }
  1405.        
  1406.         // Save old values for metas
  1407.         $_product['title'] = $product->title;
  1408.         $_product['shortTitle'] = $product->shortTitle;
  1409.         $_product['description'] = $product->description;
  1410.         $_product['shortDescription'] = $product->shortDescription;
  1411.         $_product['deliveryScope'] = $product->deliveryScope;
  1412.        
  1413.         $product->title = array();
  1414.         $product->shortTitle = array();
  1415.         $product->description = array();
  1416.         $product->shortDescription = array();
  1417.         $product->deliveryScope = array();
  1418.         $_product['langActive'] = $product->langActive;
  1419.         $product->langActive = $foilType->langActive;
  1420.        
  1421.         $decodeParams = array();
  1422.         $decodeParams['project'] = $product->project;
  1423.         if (!empty($device)) {
  1424.             $decodeParams['device'] = $device;
  1425.             $decodeParams['deviceType'] = $device->deviceType;
  1426.         }
  1427.         $decodeParams['foilType'] = $foilType;
  1428.         $decodeParams['bulletPoints'] = $foilType->bulletPoints;
  1429.         $decodeParams['foilTypeUnity'] = $foilTypeUnity;
  1430.         $decodeParams['size'] = $standardSize;
  1431.         $decodeParams['sizes'] = $sizes;
  1432.        
  1433.         $foilTypeTitles = $foilType->$titleValue;
  1434.         $foilTypeShortTitles = $foilType->$shortTitleValue;
  1435.        
  1436.         $metaSave = array();
  1437.         $languages = Language::model()->findAll('active=1');
  1438.         if (!empty($languages)) {
  1439.             foreach($languages as $lang) {
  1440.                 $product->title[$lang->isoCode] = Helper::decodeModuleValues($foilTypeTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
  1441.                 if ($product->title[$lang->isoCode] === false) {
  1442.                     if (empty($existPProduct))
  1443.                         $pProduct->delete();
  1444.                     $error = new ErrorLog();
  1445.                     $error->errorLogType_id = 4;
  1446.                     $error = 'Product texts error';
  1447.                     $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in title for language: ' . $lang->isoCode;
  1448.                     $error->save(false);
  1449.                 } else {
  1450.                     $metaSave[] = 'title';
  1451.                 }
  1452.                 $product->shortTitle[$lang->isoCode] = Helper::decodeModuleValues($foilTypeShortTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
  1453.                 if ($product->shortTitle[$lang->isoCode] === false) {
  1454.                     if (empty($existPProduct))
  1455.                         $pProduct->delete();
  1456.                     $error = new ErrorLog();
  1457.                     $error->errorLogType_id = 4;
  1458.                     $error = 'Product texts error';
  1459.                     $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in shortTitle for language: ' . $lang->isoCode;
  1460.                     $error->save(false);
  1461.                 } else {
  1462.                     $metaSave[] = 'shortTitle';
  1463.                 }
  1464.                 $product->description[$lang->isoCode] = Helper::decodeModuleValues($foilType->productDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
  1465.                 if ($product->description[$lang->isoCode] === false) {
  1466.                     if (empty($existPProduct))
  1467.                         $pProduct->delete();
  1468.                     $error = new ErrorLog();
  1469.                     $error->errorLogType_id = 4;
  1470.                     $error = 'Product texts error';
  1471.                     $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in description for language: ' . $lang->isoCode;
  1472.                     $error->save(false);
  1473.                 } else {
  1474.                     $metaSave[] = 'description';
  1475.                 }
  1476.                 $product->shortDescription[$lang->isoCode] = Helper::decodeModuleValues($foilType->productShortDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
  1477.                 if ($product->shortDescription[$lang->isoCode] === false) {
  1478.                     if (empty($existPProduct))
  1479.                         $pProduct->delete();
  1480.                     $error = new ErrorLog();
  1481.                     $error->errorLogType_id = 4;
  1482.                     $error = 'Product texts error';
  1483.                     $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in shortDescription for language: ' . $lang->isoCode;
  1484.                     $error->save(false);
  1485.                 } else {
  1486.                     $metaSave[] = 'shortDescription';
  1487.                 }
  1488.                 $product->deliveryScope[$lang->isoCode] = Helper::decodeModuleValues($foilType->deliveryScope[$lang->isoCode], $decodeParams, $lang->isoCode);
  1489.                 if ($product->deliveryScope[$lang->isoCode] === false) {
  1490.                     if (empty($existPProduct))
  1491.                         $pProduct->delete();
  1492.                     $error = new ErrorLog();
  1493.                     $error = 'Product texts error';
  1494.                     $error->errorLogType_id = 4;
  1495.                     $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in deliveryScope for language: ' . $lang->isoCode;
  1496.                     $error->save(false);
  1497.                 } else {
  1498.                     $metaSave[] = 'deliveryScope';
  1499.                 }
  1500.             }
  1501.         }
  1502.         if (empty($product->editOwnerUser_id))
  1503.             $product->lastUpdate = date('Y-m-d H:i:s');
  1504.         $product->availableFromDate = $standardSize->saleStartDate;
  1505.         if (!empty($standardSize->saleEndDate))
  1506.             $product->availableToDate = $standardSize->saleEndDate;
  1507.         if (strtotime($product->availableFromDate) > time())
  1508.             $product->available = 0;
  1509.         else
  1510.             $product->available = 1;
  1511.         $product->originCountry_id = $foilType->productCountry_id;
  1512.         $product->brand_id = $foilType->brand_id;
  1513.         $product->productType_id = 1;
  1514.         $product->productLine_id = $foilType->productLine_id;
  1515.        
  1516.         if ($pProduct->validate() == false) {
  1517.             $error = new ErrorLog();
  1518.             $error->errorLogType_id = 4;
  1519.             $error->subject = 'Physical product has errors';
  1520.             $pError = var_export($pProduct->errors, true);
  1521.             $pValues = var_export($pProduct->attributes, true);
  1522.             $error->text = 'Physical product has errors. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a><br/>' . $pError . ' values: ' . $pValues;
  1523.             $error->save(false);
  1524.             return false;
  1525.         }
  1526.        
  1527.         if ($product->validate() == false) {
  1528.             $error = new ErrorLog();
  1529.             $error->errorLogType_id = 4;
  1530.             $error->subject = 'Product has errors';
  1531.             $pError = var_export($product->errors, true);
  1532.             $pValues = var_export($product->attributes, true);
  1533.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a><br/>error: ' . $pError . ' values: ' . $pValues;
  1534.             $error->save(false);
  1535.             return false;
  1536.         }
  1537.        
  1538.         if (empty($product->editOwnerUser_id)) {
  1539.             $product->save(false);
  1540.             $pProduct->save(false);
  1541.             if (!empty($metaSave))
  1542.                 Helper::saveMultiligualParameter($product, $metaSave);
  1543.         } else {
  1544.             // Manual physical product attributes changes
  1545.             foreach($pProduct->attributes as $key=>$val) {
  1546.                 if ($_pProduct[$key] != $pProduct->$key) {
  1547.                     $change = new ProductManualChanges();
  1548.                     $change->field = 'PhysicalProduct_' . $key;
  1549.                     $change->product_id = $product->getPrimaryKey();
  1550.                     $change->user_id = $product->editOwnerUser_id;
  1551.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1552.                     if (!empty($eChange))
  1553.                         $change = $eChange;
  1554.                     $change->oldValue = $_pProduct[$key];
  1555.                     $change->newValue = $pProduct->$key;
  1556.                     $change->save(false);
  1557.                 }
  1558.             }
  1559.             // Manual product attributes changes
  1560.             foreach($product->attributes as $key=>$val) {
  1561.                 if ($_product[$key] != $product->$key) {
  1562.                     $change = new ProductManualChanges();
  1563.                     $change->field = 'Product_' . $key;
  1564.                     $change->product_id = $product->getPrimaryKey();
  1565.                     $change->user_id = $product->editOwnerUser_id;
  1566.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1567.                     if (!empty($eChange))
  1568.                         $change = $eChange;
  1569.                     $change->oldValue = $_product[$key];
  1570.                     $change->newValue = $product->$key;
  1571.                     $change->save(false);
  1572.                 }
  1573.             }
  1574.             if (json_encode($product->langActive) != json_encode($_product['langActive'])) {
  1575.                 $change = new ProductManualChanges();
  1576.                 $change->field = 'Product_langActive';
  1577.                 $change->product_id = $product->getPrimaryKey();
  1578.                 $change->user_id = $product->editOwnerUser_id;
  1579.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1580.                 if (!empty($eChange))
  1581.                     $change = $eChange;
  1582.                 $change->oldValue = json_encode($_product['langActive']);
  1583.                 $change->newValue = json_encode($product['langActive']);
  1584.                 $change->save(false);
  1585.             }
  1586.             if (json_encode($product->title) != json_encode($_product['title'])) {
  1587.                 $change = new ProductManualChanges();
  1588.                 $change->field = 'Product_title';
  1589.                 $change->product_id = $product->getPrimaryKey();
  1590.                 $change->user_id = $product->editOwnerUser_id;
  1591.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1592.                 if (!empty($eChange))
  1593.                     $change = $eChange;
  1594.                 $change->oldValue = json_encode($_product['title']);
  1595.                 $change->newValue = json_encode($product['title']);
  1596.                 $change->save(false);
  1597.             }
  1598.             if (json_encode($product->shortTitle) != json_encode($_product['shortTitle'])) {
  1599.                 $change = new ProductManualChanges();
  1600.                 $change->field = 'Product_shortTitle';
  1601.                 $change->product_id = $product->getPrimaryKey();
  1602.                 $change->user_id = $product->editOwnerUser_id;
  1603.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1604.                 if (!empty($eChange))
  1605.                     $change = $eChange;
  1606.                 $change->oldValue = json_encode($_product['shortTitle']);
  1607.                 $change->newValue = json_encode($product['shortTitle']);
  1608.                 $change->save(false);
  1609.             }
  1610.             if (json_encode($product->description) != json_encode($_product['description'])) {
  1611.                 $change = new ProductManualChanges();
  1612.                 $change->field = 'Product_description';
  1613.                 $change->product_id = $product->getPrimaryKey();
  1614.                 $change->user_id = $product->editOwnerUser_id;
  1615.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1616.                 if (!empty($eChange))
  1617.                     $change = $eChange;
  1618.                 $change->oldValue = json_encode($_product['description']);
  1619.                 $change->newValue = json_encode($product['description']);
  1620.                 $change->save(false);
  1621.             }
  1622.             if (json_encode($product->shortDescription) != json_encode($_product['shortDescription'])) {
  1623.                 $change = new ProductManualChanges();
  1624.                 $change->field = 'Product_shortDescription';
  1625.                 $change->product_id = $product->getPrimaryKey();
  1626.                 $change->user_id = $product->editOwnerUser_id;
  1627.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1628.                 if (!empty($eChange))
  1629.                     $change = $eChange;
  1630.                 $change->oldValue = json_encode($_product['shortDescription']);
  1631.                 $change->newValue = json_encode($product['shortDescription']);
  1632.                 $change->save(false);
  1633.             }
  1634.             if (json_encode($product->deliveryScope) != json_encode($_product['deliveryScope'])) {
  1635.                 $change = new ProductManualChanges();
  1636.                 $change->field = 'Product_deliveryScope';
  1637.                 $change->product_id = $product->getPrimaryKey();
  1638.                 $change->user_id = $product->editOwnerUser_id;
  1639.                 $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1640.                 if (!empty($eChange))
  1641.                     $change = $eChange;
  1642.                 $change->oldValue = json_encode($_product['deliveryScope']);
  1643.                 $change->newValue = json_encode($product['deliveryScope']);
  1644.                 $change->save(false);
  1645.             }
  1646.         }
  1647.        
  1648.         // Create categories
  1649.         $_product['endCategory'] = $product->getEndCategory();
  1650.        
  1651.         if (empty($product->editOwnerUser_id)) {
  1652.             $categories = $product->generateCategories($foilType->categoryFormula, $decodeParams);
  1653.         } else {
  1654.             $categories = $product->generateCategories($foilType->categoryFormula, $decodeParams, true);
  1655.             if (!is_numeric($categories)) {
  1656.                 $categories = false;
  1657.             } else {
  1658.                 if ($_product['endCategory'] != $categories) {
  1659.                     $change = new ProductManualChanges();
  1660.                     $change->field = 'Product_endCategory';
  1661.                     $change->product_id = $product->getPrimaryKey();
  1662.                     $change->user_id = $product->editOwnerUser_id;
  1663.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1664.                     if (!empty($eChange))
  1665.                         $change = $eChange;
  1666.                     $change->oldValue = $_product['endCategory'];
  1667.                     $change->newValue = $categories;
  1668.                     $change->save(false);
  1669.                 }
  1670.             }
  1671.         }
  1672.         if ($categories === false) {
  1673.             $error = new ErrorLog();
  1674.             $error->errorLogType_id = 4;
  1675.             $error->subject = 'Categories have error';
  1676.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>has error in categories';
  1677.             $error->save(false);
  1678.         }
  1679.        
  1680.         // Create ERP Groups
  1681.         $_product['endERPGroup'] = $product->getEndGroup();
  1682.         if (empty($product->editOwnerUser_id)) {
  1683.             $erpGroups = $this->generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams);
  1684.         } else {
  1685.             $erpGroups = $this->generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams, true);
  1686.             if (!is_numeric($erpGroups)) {
  1687.                 $erpGroups = false;
  1688.             } else {
  1689.                 if ($_product['endERPGroup'] != $erpGroups) {
  1690.                     $change = new ProductManualChanges();
  1691.                     $change->field = 'Product_endERPGroup';
  1692.                     $change->product_id = $product->getPrimaryKey();
  1693.                     $change->user_id = $product->editOwnerUser_id;
  1694.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1695.                     if (!empty($eChange))
  1696.                         $change = $eChange;
  1697.                     $change->oldValue = $_product['endERPGroup'];
  1698.                     $change->newValue = $erpGroups;
  1699.                     $change->save(false);
  1700.                 }
  1701.             }
  1702.         }
  1703.         if ($erpGroups === false) {
  1704.             $error = new ErrorLog();
  1705.             $error->errorLogType_id = 4;
  1706.             $error->subject = 'ERP groups have error';
  1707.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>has error in ERP groups';
  1708.             $error->save(false);
  1709.         }
  1710.        
  1711.         // Connect keywords
  1712.         $keywords = $foilType->keywords;
  1713.         if (!empty($device)) {
  1714.             if (is_array($keywords))
  1715.                 $keywords = array_merge($keywords, $device->keywords);
  1716.             else
  1717.                 $keywords = $device->keywords;
  1718.         }
  1719.         if (!empty($keywords)) {
  1720.             $newKeywordIDs = array();
  1721.             $values = ' VALUES ';
  1722.             foreach($keywords as $key=>$word) {
  1723.                 $values .= '(' . $product->id . ', ' . $word->id . ')';
  1724.                 if ($key < count($keywords) - 1)
  1725.                     $values .= ',';
  1726.                 if ($word->manual == 0)
  1727.                     $newKeywordIDs[] = $word->id;
  1728.             }
  1729.             if (empty($product->editOwnerUser_id)) {
  1730.                 // Delete old ones and insert new one
  1731.                 $sql = 'DELETE pk FROM product_has_keywords AS pk
  1732.                    LEFT JOIN keywords AS k ON k.id=pk.keywords_id
  1733.                    WHERE k.manual=0 AND pk.product_id=' . $product->getPrimaryKey();
  1734.                 Yii::app()->db->createCommand($sql)->query();
  1735.                 $sql = 'INSERT INTO product_has_keywords ' . $values;
  1736.                 Yii::app()->db->createCommand($sql)->query();
  1737.             } else {
  1738.                 $oldKeywordIDs = array();
  1739.                 if (!empty($product->keywords)) {
  1740.                     foreach($product->keywords as $word) {
  1741.                         if ($word->manual == 0)
  1742.                             $oldKeywordIDs[] = $word->id;
  1743.                     }
  1744.                 }
  1745.                 $dif1 = array_diff($oldKeywordIDs, $newKeywordIDs);
  1746.                 $dif2 = array_diff($newKeywordIDs, $oldKeywordIDs);
  1747.                 if (!empty($dif1) || !empty($dif2)) {
  1748.                     $change = new ProductManualChanges();
  1749.                     $change->field = 'Product_keywords';
  1750.                     $change->product_id = $product->getPrimaryKey();
  1751.                     $change->user_id = $product->editOwnerUser_id;
  1752.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1753.                     if (!empty($eChange))
  1754.                         $change = $eChange;
  1755.                     $change->oldValue = json_encode($oldKeywordIDs);
  1756.                     $change->newValue = json_encode($newKeywordIDs);
  1757.                     $change->save(false);
  1758.                 }
  1759.             }
  1760.         } else {
  1761.             $error = new ErrorLog();
  1762.             $error->errorLogType_id = 4;
  1763.             $error->subject = 'Keywords are missing';
  1764.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> keywords are empty';
  1765.             $error->save(false);
  1766.         }
  1767.        
  1768.         // Connect bulletpoints
  1769.         $bulletPoints = $foilType->bulletPoints;
  1770.         if (!empty($bulletPoints)) {
  1771.             $newBulletPointsIDs = array();
  1772.             $values = ' VALUES ';
  1773.             foreach($bulletPoints as $key=>$point) {
  1774.                 $values .= '(' . $product->id . ', ' . $point->id . ')';
  1775.                 if ($key < count($bulletPoints) - 1)
  1776.                     $values .= ',';
  1777.                 if ($point->manual == 0)
  1778.                     $newBulletPointsIDs[] = $point->id;
  1779.             }
  1780.             if (empty($product->editOwnerUser_id)) {
  1781.                 // Delete old ones and insert new one
  1782.                 $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
  1783.                        LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
  1784.                        WHERE b.manual=0 AND pb.product_id=' . $product->getPrimaryKey();
  1785.                 Yii::app()->db->createCommand($sql)->query();
  1786.                 $sql = 'INSERT INTO product_has_bulletPoints ' . $values;
  1787.                 Yii::app()->db->createCommand($sql)->query();
  1788.             } else {
  1789.                 $oldBulletPointsIDs = array();
  1790.                 if (!empty($product->bulletPoints)) {
  1791.                     foreach($product->bulletPoints as $point) {
  1792.                         if ($point->manual == 0)
  1793.                             $oldBulletPointsIDs[] = $point->id;
  1794.                     }
  1795.                 }
  1796.                 $dif1 = array_diff($oldBulletPointsIDs, $newBulletPointsIDs);
  1797.                 $dif2 = array_diff($newBulletPointsIDs, $oldBulletPointsIDs);
  1798.                 if (!empty($dif1) || !empty($dif2)) {
  1799.                     $change = new ProductManualChanges();
  1800.                     $change->field = 'Product_bulletpoints';
  1801.                     $change->product_id = $product->getPrimaryKey();
  1802.                     $change->user_id = $product->editOwnerUser_id;
  1803.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1804.                     if (!empty($eChange))
  1805.                         $change = $eChange;
  1806.                     $change->oldValue = json_encode($oldBulletPointsIDs);
  1807.                     $change->newValue = json_encode($newBulletPointsIDs);
  1808.                     $change->save(false);
  1809.                 }
  1810.             }
  1811.         } else {
  1812.             $error = new ErrorLog();
  1813.             $error->errorLogType_id = 4;
  1814.             $error->subject = 'Bulletpoints missing';
  1815.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> bulletpoints are empty';
  1816.             $error->save(false);
  1817.         }
  1818.        
  1819.         // Connect product features
  1820.         $productFeatureValues = $foilType->productFeatureValues;
  1821.         if (!empty($productFeatureValues)) {
  1822.             $values = ' VALUES ';
  1823.             $newFeatureValues = array();
  1824.             foreach($productFeatureValues as $value) {
  1825.                 $values .= '(' . $product->id . ', ' . $value->id . ', 0)';
  1826.                 if ($value != end($productFeatureValues))
  1827.                     $values .= ',';
  1828.                 $newFeatureValues[] = $value->id;
  1829.             }
  1830.             if (empty($product->editOwnerUser_id)) {
  1831.                 // Delete old ones and insert new one
  1832.                 $sql = 'DELETE FROM product_has_productFeatureValue
  1833.                    WHERE product_id=' . $model->id . ' AND  manual=0';
  1834.                 Yii::app()->db->createCommand($sql)->execute();
  1835.                 $sql = 'INSERT INTO product_has_productFeatureValue ' . $values;
  1836.                 Yii::app()->db->createCommand($sql)->query();
  1837.             } else {
  1838.                 $oldFeatureValues = array();
  1839.                 if (!empty($product->productFeatureValues)) {
  1840.                     foreach($product->productFeatureValues as $value) {
  1841.                         $sql = 'SELECT manual
  1842.                                FROM product_has_productFeatureValue
  1843.                                WHERE product_id=' . $product->getPrimaryKey() . '
  1844.                                AND productFeatureValue_id=' . $value->getPrimaryKey();
  1845.                         $manual = Yii::app()->db->createCommand($sql)->queryScalar();
  1846.                         if ($manual == 0)
  1847.                             $oldFeatureValues[] = $value->id;
  1848.                     }
  1849.                 }
  1850.                 $dif1 = array_diff($oldFeatureValues, $newFeatureValues);
  1851.                 $dif2 = array_diff($newFeatureValues, $oldFeatureValues);
  1852.                 if (!empty($dif1) || !empty($dif2)) {
  1853.                     $change = new ProductManualChanges();
  1854.                     $change->field = 'Product_featureValues';
  1855.                     $change->product_id = $product->getPrimaryKey();
  1856.                     $change->user_id = $product->editOwnerUser_id;
  1857.                     $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
  1858.                     if (!empty($eChange))
  1859.                         $change = $eChange;
  1860.                     $change->oldValue = json_encode($oldFeatureValues);
  1861.                     $change->newValue = json_encode($newFeatureValues);
  1862.                     $change->save(false);
  1863.                 }
  1864.             }
  1865.         } else {
  1866.             $error = new ErrorLog();
  1867.             $error->errorLogType_id = 4;
  1868.             $error->subject = "Product features are missing";
  1869.             $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> features are empty';
  1870.             $error->save(false);
  1871.         }
  1872.        
  1873.         // Get all product modules
  1874.         $pModulesIDs = array(
  1875.             $package->module_id,
  1876.             $foilTypeUnity->module_id
  1877.         );
  1878.         foreach($sizes as $size)
  1879.             $pModulesIDs[] = $size->module_id;
  1880.         if ($device != null && $device->module_id)
  1881.             $pModulesIDs[] = $device->module_id;
  1882.         $pModulesIDs = array_filter($pModulesIDs);
  1883.         $sql = 'SELECT media_id as id
  1884.                FROM module_has_media AS mm
  1885.                LEFT JOIN media AS m ON mm.media_id=m.id
  1886.                WHERE m.mediaType_id IN (1,3)
  1887.                AND mm.module_id IN(' . implode(',', $pModulesIDs) . ')';
  1888.         $medias = Yii::app()->db->createCommand($sql)->queryAll();
  1889.         // Delete old ones and insert new one
  1890.         $sql = 'DELETE pm FROM product_has_media AS pm
  1891.                LEFT JOIN media AS m ON m.id=pm.media_id
  1892.                WHERE m.manual=0
  1893.                AND pm.product_id=' . $product->getPrimaryKey();
  1894.         Yii::app()->db->createCommand($sql)->query();
  1895.         // Create medias for product
  1896.         if (!empty($medias)) {
  1897.             foreach($medias as $media) {
  1898.                 $sql = 'INSERT INTO product_has_media (media_id, product_id) VALUES(' . $media['id'] . ',' . $product->getPrimaryKey() . ')';
  1899.                 Yii::app()->db->createCommand($sql)->query();
  1900.             }
  1901.         }
  1902.        
  1903.         if ($return)
  1904.             return $product;
  1905.         else
  1906.             return $product->id;
  1907.     }
  1908.  
  1909.     /**
  1910.      * Action to update a Foil Type
  1911.      */
  1912.     public function actionUpdate($id) {
  1913.         $model = $this->loadModel($id);
  1914.         $this->render('form', array(
  1915.             'model' => $model
  1916.         ));
  1917.     }
  1918.  
  1919.     /**
  1920.      * Action to update a Product Master Data
  1921.      */
  1922.     public function actionUpdateMasterData() {
  1923.         if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
  1924.             $model = $this->loadModel($_POST['Product']['id']);
  1925.             $pProduct = $model->physicalProduct;
  1926.             $model->attributes = $_POST['Product'];
  1927.             if ($model->validate()) {
  1928.                 if (isset($_POST['PhysicalProduct'])) {
  1929.                     $pProduct->attributes = $_POST['PhysicalProduct'];
  1930.                     if ($pProduct->validate()) {
  1931.                         $pProduct->save(false);
  1932.                         if (!empty($model->availableFromDate))
  1933.                             $model->availableFromDate = date('Y-m-d H:i:s', strtotime($model->availableFromDate));
  1934.                         if (!empty($model->availableToDate))
  1935.                             $model->availableToDate = date('Y-m-d H:i:s', strtotime($model->availableToDate));
  1936.                             // Set updates owner user
  1937.                         if (empty($model->editOwnerUser_id))
  1938.                             $model->editOwnerUser_id = Yii::app()->user->id;
  1939.                         $model->save(false);
  1940.                        
  1941.                         if (isset($_POST['Product']['productERPGroups'])) {
  1942.                             $erpGroups = $_POST['Product']['productERPGroups'];
  1943.                             $erpGroups = array_filter($erpGroups);
  1944.                             $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $model->primaryKey;
  1945.                             Yii::app()->db->createCommand($sql)->execute();
  1946.                             foreach($erpGroups as $group) {
  1947.                                 $endGroup = 0;
  1948.                                 if ($group == end($erpGroups))
  1949.                                     $endGroup = 1;
  1950.                                 $sql = 'INSERT INTO product_has_productERPGroup VALUES (' . $group . ', ' . $model->primaryKey . ', 0 , ' . $endGroup . ')';
  1951.                                 Yii::app()->db->createCommand($sql)->execute();
  1952.                             }
  1953.                         }
  1954.                        
  1955.                         if (isset($_POST['Product']['productCategories'])) {
  1956.                             $categories = $_POST['Product']['productCategories'];
  1957.                             $categories = array_filter($categories);
  1958.                             $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $model->primaryKey;
  1959.                             Yii::app()->db->createCommand($sql)->execute();
  1960.                             foreach($categories as $category) {
  1961.                                 $endCategory = 0;
  1962.                                 if ($category == end($categories))
  1963.                                     $endCategory = 1;
  1964.                                 $sql = 'INSERT INTO product_has_productCategory VALUES (' . $category . ', ' . $model->primaryKey . ', 0 , ' . $endCategory . ')';
  1965.                                 Yii::app()->db->createCommand($sql)->execute();
  1966.                             }
  1967.                         }
  1968.                     }
  1969.                 }
  1970.             }
  1971.             Helper::ajaxReturn(array_merge($pProduct->errors, $model->errors), $model);
  1972.         }
  1973.     }
  1974.  
  1975.     /**
  1976.      * Action to update a Foil Type Texts
  1977.      */
  1978.     public function actionUpdateTexts() {
  1979.         if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
  1980.             $model = $this->loadModel($_POST['Product']['id']);
  1981.             $model->scenario = 'texts';
  1982.            
  1983.             // Set updates owner user
  1984.             if (empty($model->editOwnerUser_id)) {
  1985.                 $model->editOwnerUser_id = Yii::app()->user->id;
  1986.                 $model->save(false);
  1987.             }
  1988.            
  1989.             $model->title = $_POST['Product']['title'];
  1990.             $model->shortTitle = $_POST['Product']['shortTitle'];
  1991.             $model->description = $_POST['Product']['description'];
  1992.             $model->shortDescription = $_POST['Product']['shortDescription'];
  1993.             $model->deliveryScope = $_POST['Product']['deliveryScope'];
  1994.             $model->langActive = $_POST['Product']['langActive'];
  1995.             $bulletPoints = array();
  1996.             if (isset($_POST['BulletPoints']))
  1997.                 $bulletPoints = $_POST['BulletPoints'];
  1998.             if ($model->validate()) {
  1999.                 Helper::saveMultiligualParameter($model, array(
  2000.                     'langActive',
  2001.                     'title',
  2002.                     'shortTitle',
  2003.                     'description',
  2004.                     'shortDescription',
  2005.                     'deliveryScope'
  2006.                 ));
  2007.             }
  2008.             if (!empty($model->errors))
  2009.                 Helper::ajaxReturn($model->errors, $model);
  2010.                
  2011.                 // Bulletpoints
  2012.             $newBulletPoints = array();
  2013.             $errors = array();
  2014.             if (!empty($bulletPoints)) {
  2015.                 foreach($bulletPoints as $position=>$bullet) {
  2016.                     if ($bullet['id']) {
  2017.                         $newBullet = BulletPoints::model()->findByPk($bullet['id']);
  2018.                     } else {
  2019.                         $newBullet = new BulletPoints();
  2020.                     }
  2021.                     $newBullet->attributes = $bullet;
  2022.                     if ($newBullet->isNewRecord)
  2023.                         $newBullet->manual = 1;
  2024.                     if ($newBullet->validate() == false)
  2025.                         break;
  2026.                     else
  2027.                         $newBulletPoints[] = $newBullet;
  2028.                 }
  2029.                 if (empty($newBullet->errors)) {
  2030.                     $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
  2031.                            LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
  2032.                            WHERE b.manual=1 AND pb.product_id=' . $model->id;
  2033.                     Yii::app()->db->createCommand($sql)->execute();
  2034.                     $sql = 'INSERT INTO product_has_bulletPoints VALUES ';
  2035.                     $i = 0;
  2036.                     foreach($newBulletPoints as $bullet) {
  2037.                         $i++;
  2038.                         $bullet->save();
  2039.                         $sql .= '(' . $model->getPrimaryKey() . ',' . $bullet->getPrimaryKey() . ')';
  2040.                         if ($i < count($newBulletPoints))
  2041.                             $sql .= ',';
  2042.                     }
  2043.                     Yii::app()->db->createCommand($sql)->execute();
  2044.                 } else {
  2045.                     foreach($newBullet->errors as $key=>$err) {
  2046.                         $errors[$position . '_' . $key] = '[Bulletpoints ' . $position . '] ' . $err[0];
  2047.                     }
  2048.                 }
  2049.             } else {
  2050.                 $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
  2051.                        LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
  2052.                        WHERE b.manual=1 AND pb.product_id=' . $model->id;
  2053.                 Yii::app()->db->createCommand($sql)->execute();
  2054.             }
  2055.             Helper::ajaxReturn($errors, new BulletPoints());
  2056.         }
  2057.     }
  2058.  
  2059.     /**
  2060.      * Action to update product keywords
  2061.      */
  2062.     public function actionUpdateKeywords() {
  2063.         if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
  2064.             $model = $this->loadModel($_POST['Product']['id']);
  2065.             $newKeywords = array();
  2066.             $errors = array();
  2067.             if (isset($_POST['Keywords']) && !empty($_POST['Keywords'])) {
  2068.                 $keywords = $_POST['Keywords'];
  2069.                 foreach($keywords as $position=>$keyword) {
  2070.                     if ($keyword['id'])
  2071.                         $newKeyword = Keywords::model()->findByPk($keyword['id']);
  2072.                     else
  2073.                         $newKeyword = new Keywords();
  2074.                     $newKeyword->attributes = $keyword;
  2075.                     if ($newKeyword->validate() == false)
  2076.                         break;
  2077.                     else
  2078.                         $newKeywords[] = $newKeyword;
  2079.                 }
  2080.                 if (empty($newKeyword->errors)) {
  2081.                     $sql = 'DELETE pk FROM product_has_keywords AS pk
  2082.                            LEFT JOIN keywords AS k ON k.id=pk.keywords_id
  2083.                            WHERE k.manual=1 AND pk.product_id=' . $model->id;
  2084.                     Yii::app()->db->createCommand($sql)->execute();
  2085.                     $sql = 'INSERT INTO product_has_keywords VALUES ';
  2086.                     $i = 0;
  2087.                     foreach($newKeywords as $keyword) {
  2088.                         $i++;
  2089.                         $keyword->sort *= 10;
  2090.                         $keyword->save();
  2091.                         $sql .= '(' . $model->primaryKey . ',' . $keyword->primaryKey . ')';
  2092.                         if ($i < count($newKeywords))
  2093.                             $sql .= ',';
  2094.                     }
  2095.                     Yii::app()->db->createCommand($sql)->execute();
  2096.                 } else {
  2097.                     foreach($newKeyword->errors as $key=>$err) {
  2098.                         $errors[$position . '_' . $key] = '[Keywords ' . $position . '] ' . $err[0];
  2099.                     }
  2100.                 }
  2101.             } else {
  2102.                 $sql = 'DELETE pk FROM product_has_keywords AS pk
  2103.                        LEFT JOIN keywords AS k ON k.id=pk.keywords_id
  2104.                        WHERE k.manual=1 AND pk.product_id=' . $model->id;
  2105.                 Yii::app()->db->createCommand($sql)->execute();
  2106.             }
  2107.             if (!isset($newKeyword))
  2108.                 $newKeyword = new Keywords();
  2109.             Helper::ajaxReturn($errors, $newKeyword);
  2110.         }
  2111.     }
  2112.  
  2113.     /**
  2114.      * Action to update a Foil Type Product Features
  2115.      */
  2116.     public function actionUpdateFeatures() {
  2117.         if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
  2118.             $model = $this->loadModel($_POST['Product']['id']);
  2119.             $newFeatures = array();
  2120.             $errors = array();
  2121.             if (isset($_POST['ProductFeatureValue']) && !empty($_POST['ProductFeatureValue'])) {
  2122.                 $features = $_POST['ProductFeatureValue'];
  2123.                 foreach($features as $position=>$feature) {
  2124.                     $newFeature = new ProductFeatureValue();
  2125.                     $newFeature->attributes = $feature;
  2126.                     $newFeature->value = $feature['value'];
  2127.                     $featureType = ProductFeature::model()->findByPk($newFeature->productFeature_id);
  2128.                     if (!empty($featureType)) {
  2129.                         // Translate value to all languages if not text and not
  2130.                         // selectbox
  2131.                         if ($featureType->inputType != 0 && $featureType->inputType != 3) {
  2132.                             $sql = 'SELECT isoCode FROM language WHERE active=1';
  2133.                             $langs = Yii::app()->db->createCommand($sql)->queryAll();
  2134.                             $tempValue = $newFeature->value;
  2135.                             $newFeature->value = array();
  2136.                             foreach($langs as $lang)
  2137.                                 $newFeature->value[$lang['isoCode']] = $tempValue;
  2138.                                
  2139.                                 // Check if value exists already
  2140.                             $sql = 'SELECT pfv.id
  2141.                                FROM productFeatureValue AS pfv
  2142.                                LEFT JOIN productFeatureValue_translation AS pfvt ON pfv.id=pfvt.productFeatureValue_id
  2143.                                WHERE pfv.productFeature_id=' . $newFeature->productFeature_id . '
  2144.                                AND pfvt.value="' . $feature['value'] . '"
  2145.                                GROUP BY pfvt.productFeatureValue_id';
  2146.                             $existFeature = Yii::app()->db->createCommand($sql)->queryRow();
  2147.                             if (!empty($existFeature)) {
  2148.                                 $newFeature = ProductFeatureValue::model()->findByPk($existFeature['id']);
  2149.                             }
  2150.                         }
  2151.                        
  2152.                         // Check if value has changed
  2153.                         if (isset($feature['id'])) {
  2154.                             $oldFeature = ProductFeatureValue::model()->findByPk($feature['id']);
  2155.                             if ($oldFeature->value == $newFeature->value)
  2156.                                 $newFeature = $oldFeature;
  2157.                         }
  2158.                        
  2159.                         // Find feature value if dropdown list
  2160.                         if ($featureType->inputType == 3) {
  2161.                             $newFeature = ProductFeatureValue::model()->findByPk($feature['value']);
  2162.                             if (empty($newFeature)) {
  2163.                                 $newFeature = new ProductFeatureValue();
  2164.                                 $newFeature->addError('id', Translate::t('errors', Translate::t('yii', '{attribute} cannot be blank.', array(
  2165.                                     '{attribute}' => $newFeature->getAttributeLabel('value')
  2166.                                 ))));
  2167.                                 break;
  2168.                             }
  2169.                         }
  2170.                         if ($newFeature->validate() == false)
  2171.                             break;
  2172.                         else
  2173.                             $newFeatures[] = $newFeature;
  2174.                     } else {
  2175.                         $newFeature->addError('id', Translate::t('errors', 'Object doesnt exist'));
  2176.                     }
  2177.                 }
  2178.                 if (empty($newFeature->errors)) {
  2179.                     $sql = 'DELETE FROM product_has_productFeatureValue
  2180.                            WHERE product_id=' . $model->id . ' AND  manual=1';
  2181.                     Yii::app()->db->createCommand($sql)->execute();
  2182.                     $sql = 'INSERT INTO product_has_productFeatureValue VALUES ';
  2183.                     $i = 0;
  2184.                     foreach($newFeatures as $feature) {
  2185.                         $i++;
  2186.                         $feature->save();
  2187.                         Helper::saveMultiligualParameter($feature, array(
  2188.                             'value'
  2189.                         ));
  2190.                         $sql .= '(' . $model->getPrimaryKey() . ',' . $feature->getPrimaryKey() . ', 1)';
  2191.                         if ($i < count($newFeatures))
  2192.                             $sql .= ',';
  2193.                     }
  2194.                     Yii::app()->db->createCommand($sql)->execute();
  2195.                 } else {
  2196.                     foreach($newFeature->errors as $key=>$err) {
  2197.                         $errors['_' . $position . '_productFeature_id'] = '[' . Translate::t('project', 'Product feature') . ' ' . $position . '] ' . $err[0];
  2198.                     }
  2199.                 }
  2200.             } else {
  2201.                 $sql = 'DELETE FROM product_has_productFeatureValue
  2202.                        WHERE product_id=' . $model->id . ' AND manual=1';
  2203.                 Yii::app()->db->createCommand($sql)->execute();
  2204.             }
  2205.             Helper::ajaxReturn($errors, new BulletPoints());
  2206.         }
  2207.     }
  2208.  
  2209.     /**
  2210.      * Action to update a product notes
  2211.      */
  2212.     public function actionUpdateProductNotes() {
  2213.         if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
  2214.             $model = $this->loadModel($_POST['Product']['id']);
  2215.             $productNotes = $_POST['ProductNote'];
  2216.             $newNotes = array();
  2217.             $errors = array();
  2218.             if (!empty($productNotes)) {
  2219.                 foreach($productNotes as $position=>$note) {
  2220.                     if (isset($note['id']) && $note['id'] != false)
  2221.                         $newNote = ProductNote::model()->findByPk($note['id']);
  2222.                     else
  2223.                         $newNote = new ProductNote();
  2224.                     $newNote->attributes = $note;
  2225.                     $newNote->product_id = $model->primaryKey;
  2226.                     if ($newNote->validate() == false)
  2227.                         break;
  2228.                     else
  2229.                         $newNotes[] = $newNote;
  2230.                 }
  2231.                 if (empty($newNote->errors)) {
  2232.                     $sql = 'DELETE FROM productNote WHERE product_id=' . $model->primaryKey;
  2233.                     Yii::app()->db->createCommand($sql)->execute();
  2234.                     $sql = 'INSERT INTO productNote VALUES ';
  2235.                     $i = 0;
  2236.                     foreach($newNotes as $note) {
  2237.                         $i++;
  2238.                         $sql .= '(NULL,"' . $note->isoCode . '",' . $model->primaryKey . ',"' . addslashes($note->note) . '",' . $note->productNoteType_id . ')';
  2239.                         if ($i < count($newNotes))
  2240.                             $sql .= ',';
  2241.                     }
  2242.                     Yii::app()->db->createCommand($sql)->execute();
  2243.                 } else {
  2244.                     foreach($newNote->errors as $key=>$err) {
  2245.                         $errors['ProductNote_' . $position . '_' . $key] = '[ProductNote ' . $position . '] ' . $err[0];
  2246.                     }
  2247.                 }
  2248.             } else {
  2249.                 $sql = 'DELETE FROM productNote WHERE product_id=' . $model->primaryKey;
  2250.                 Yii::app()->db->createCommand($sql)->execute();
  2251.             }
  2252.             if (!isset($newNote) || !$newNote)
  2253.                 $newNote = new ProductNote();
  2254.             Helper::ajaxReturn($errors, $newNote);
  2255.         }
  2256.     }
  2257.  
  2258.     /**
  2259.      * Returns the data model based on the primary key given in the GET variable.
  2260.      * If the data model is not found, an HTTP exception will be raised.
  2261.      *
  2262.      * @param integer $id the ID of the model to be loaded
  2263.      * @return ProductERPGroup the loaded model
  2264.      * @throws CHttpException
  2265.      */
  2266.     public function loadModel($id) {
  2267.         $model = Product::model()->findByPk($id);
  2268.         if ($model === null)
  2269.             throw new CHttpException(404, 'The requested page does not exist.');
  2270.         return $model;
  2271.     }
  2272.  
  2273.     /**
  2274.      *
  2275.      * @param product $model product model to block for
  2276.      * @param array $sizes ids of sizes to block for
  2277.      */
  2278.     public function blockStock($model = null, $sizes = null, $block = 1) {
  2279.         if ($model) {
  2280.             $modules = $model->modules;
  2281.             $sizes = array();
  2282.             foreach($modules as $module) {
  2283.                 if ($module->moduleGroup_id == 2)
  2284.                     $sizes[] = $module->id;
  2285.             }
  2286.         }
  2287.        
  2288.         if (!empty($sizes)) {
  2289.             $sql = 'SELECT p.physicalProduct_id AS id FROM module_has_product AS mhp, product AS p WHERE mhp.module_id IN (' . implode(',', $sizes) . ') AND mhp.product_id=p.id';
  2290.             $physicalProducts = Yii::app()->db->createCommand($sql)->queryAll();
  2291.             if (!empty($physicalProducts)) {
  2292.                 foreach($physicalProducts as $product) {
  2293.                     $sql = 'UPDATE stockPoint SET locked=' . $block . ' WHERE physicalProduct_id=' . $product['id'] . ';';
  2294.                     Yii::app()->db->createCommand($sql)->query();
  2295.                 }
  2296.             }
  2297.         }
  2298.     }
  2299.  
  2300.     /**
  2301.      * Action to update a Foil Type
  2302.      */
  2303.     public function actionManualChanges() {
  2304.         if (isset($_POST['ProductManualChanges'])) {
  2305.             $changes = $_POST['ProductManualChanges']['id'];
  2306.             if (is_array($changes)) {
  2307.                 $changesIDs = array();
  2308.                 foreach($changes as $id=>$toChange) {
  2309.                     $change = ProductManualChanges::model()->findByPk($id);
  2310.                     if (is_object($change)) {
  2311.                         $product = $change->product;
  2312.                         $pProduct = $product->physicalProduct;
  2313.                         $field = substr($change->field, strpos($change->field, '_') + 1);
  2314.                         if ($toChange == 0) {
  2315.                             $change->delete();
  2316.                         } else {
  2317.                             if (strpos($change->field, 'Product_') == 0) {
  2318.                                 if ($field == 'endCategory') {
  2319.                                     $pCategory = ProductCategory::model()->findByPk($change->newValue);
  2320.                                     $categories = $pCategory->getPath();
  2321.                                     if (!empty($categories)) {
  2322.                                         $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $product->getPrimaryKey();
  2323.                                         Yii::app()->db->createCommand($sql)->query();
  2324.                                         $addedCategories = array();
  2325.                                         foreach($categories as $cat) {
  2326.                                             $endCategory = 0;
  2327.                                             if ($cat->id == $pCategory->id)
  2328.                                                 $endCategory = 1;
  2329.                                             $addedCategories[] = '(' . $cat->id . ',' . $product->getPrimaryKey() . ',0,' . $endCategory . ')';
  2330.                                         }
  2331.                                         if (is_array($addedCategories)) {
  2332.                                             $sql = 'INSERT INTO product_has_productCategory VALUES ' . implode(',', $addedCategories);
  2333.                                             Yii::app()->db->createCommand($sql)->query();
  2334.                                         }
  2335.                                     }
  2336.                                 } elseif ($field == 'endERPGroup') {
  2337.                                     $erpGroup = ProductERPGroup::model()->findByPk($change->newValue);
  2338.                                     $groups = $erpGroup->getPath();
  2339.                                     if (!empty($groups)) {
  2340.                                         $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $product->getPrimaryKey();
  2341.                                         Yii::app()->db->createCommand($sql)->query();
  2342.                                         $addedGroups = array();
  2343.                                         foreach($groups as $group) {
  2344.                                             $endGroup = 0;
  2345.                                             if ($group->id == $erpGroup->id)
  2346.                                                 $endGroup = 1;
  2347.                                             $addedGroups[] = '(' . $group->id . ',' . $product->getPrimaryKey() . ',0,' . $endGroup . ')';
  2348.                                         }
  2349.                                         if (is_array($addedGroups)) {
  2350.                                             $sql = 'INSERT INTO product_has_productERPGroup VALUES ' . implode(',', $addedGroups);
  2351.                                             Yii::app()->db->createCommand($sql)->query();
  2352.                                         }
  2353.                                     }
  2354.                                 } elseif ($field == 'keywords') {
  2355.                                     $newKeywords = json_decode($change->newValue, true);
  2356.                                     if (is_array($newKeywords)) {
  2357.                                         $sql = 'DELETE pk FROM product_has_keywords AS pk
  2358.                                        LEFT JOIN keywords AS k ON k.id=pk.keywords_id
  2359.                                        WHERE k.manual=0 AND pk.product_id=' . $change->product_id;
  2360.                                         Yii::app()->db->createCommand($sql)->execute();
  2361.                                         $sql = 'INSERT INTO product_has_keywords VALUES ';
  2362.                                         $i = 0;
  2363.                                         foreach($newKeywords as $keywordID) {
  2364.                                             $i++;
  2365.                                             $sql .= '(' . $change->product_id . ',' . $keywordID . ')';
  2366.                                             if ($i < count($newKeywords))
  2367.                                                 $sql .= ',';
  2368.                                         }
  2369.                                         Yii::app()->db->createCommand($sql)->execute();
  2370.                                     }
  2371.                                 } elseif ($field == 'bulletpoints') {
  2372.                                     $newBulletPoints = json_decode($change->newValue, true);
  2373.                                     if (is_array($newBulletPoints)) {
  2374.                                         $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
  2375.                                        LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
  2376.                                        WHERE b.manual=0 AND pb.product_id=' . $change->product_id;
  2377.                                         Yii::app()->db->createCommand($sql)->execute();
  2378.                                         $sql = 'INSERT INTO product_has_bulletPoints VALUES ';
  2379.                                         $i = 0;
  2380.                                         foreach($newBulletPoints as $bulletID) {
  2381.                                             $i++;
  2382.                                             $sql .= '(' . $change->product_id . ',' . $bulletID . ')';
  2383.                                             if ($i < count($newBulletPoints))
  2384.                                                 $sql .= ',';
  2385.                                         }
  2386.                                         Yii::app()->db->createCommand($sql)->execute();
  2387.                                     }
  2388.                                 } elseif ($field == 'featureValues') {
  2389.                                     $newFeatureValues = json_decode($change->newValue, true);
  2390.                                     if (is_array($newFeatureValues)) {
  2391.                                         $sql = 'DELETE FROM product_has_productFeatureValue
  2392.                                        WHERE product_id=' . $change->product_id . ' AND  manual=0';
  2393.                                         Yii::app()->db->createCommand($sql)->execute();
  2394.                                         $sql = 'INSERT INTO product_has_productFeatureValue VALUES ';
  2395.                                         $i = 0;
  2396.                                         foreach($newFeatureValues as $featureID) {
  2397.                                             $i++;
  2398.                                             $sql .= '(' . $change->product_id . ',' . $featureID . ', 0)';
  2399.                                             if ($i < count($newFeatureValues))
  2400.                                                 $sql .= ',';
  2401.                                         }
  2402.                                         Yii::app()->db->createCommand($sql)->execute();
  2403.                                     }
  2404.                                 }
  2405.                             } elseif (strpos($change->field, 'PhysicalProduct_') == 0) {
  2406.                                 $pProduct->$field = $change->newValue;
  2407.                             }
  2408.                         }
  2409.                         if ($product->validate() && $pProduct->validate()) {
  2410.                             $product->lastUpdate = date('Y-m-d H:i:s');
  2411.                             $product->save(false);
  2412.                             Helper::saveMultiligualParameter($product, array(
  2413.                                 'langActive',
  2414.                                 'title',
  2415.                                 'shortTitle',
  2416.                                 'description',
  2417.                                 'shortDescription',
  2418.                                 'deliveryScope'
  2419.                             ));
  2420.                             $pProduct->save();
  2421.                             $changesIDs[] = $change->getPrimaryKey();
  2422.                         }
  2423.                     }
  2424.                 }
  2425.                 if (!empty($changesIDs)) {
  2426.                     $sql = 'DELETE FROM productManualChanges WHERE id IN (' . implode(',', $changesIDs) . ')';
  2427.                     Yii::app()->db->createCommand($sql)->execute();
  2428.                 }
  2429.             }
  2430.         }
  2431.         $productChanges = array();
  2432.         $sql = 'SELECT product_id AS id
  2433.                FROM productManualChanges
  2434.                WHERE user_id=' . Yii::app()->user->id . '
  2435.                GROUP BY product_id';
  2436.         $products = Yii::app()->db->createCommand($sql)->queryAll();
  2437.         if (!empty($products)) {
  2438.             foreach($products as $prod)
  2439.                 $productChanges[$prod['id']] = ProductManualChanges::model()->findAll('product_id="' . $prod['id'] . '" AND user_id="' . Yii::app()->user->id . '"');
  2440.         }
  2441.         $this->render('manualChanges', array(
  2442.             'productChanges' => $productChanges
  2443.         ));
  2444.     }
  2445.  
  2446.     /**
  2447.      * Updates the search words, given by the products titles, for the given
  2448.      * product(s).
  2449.      * Creates searchwords if they arent already in DB.
  2450.      *
  2451.      * @param int|array(int) $productId
  2452.      * @return boolean true if update has completed, false if no valid parameter
  2453.      *         was given.
  2454.      */
  2455.     public static function updateProductSearchWord($productId) {
  2456.         $productIdArray;
  2457.         // create array with all product ids for iteration
  2458.         if (!is_array($productId) && is_numeric($productId)) {
  2459.             $productIdArray = array(
  2460.                 $productId
  2461.             );
  2462.         } else if (is_array($productId))
  2463.             $productIdArray = $productId;
  2464.         else
  2465.             return false;
  2466.             // no valid parameter
  2467.             // holds each distinct word found for inserts
  2468.         $distinctWordsInsert = array();
  2469.         // holds product ids with word mapping for inserts
  2470.         $productWordsMapping = array();
  2471.        
  2472.         // foreach product given
  2473.         foreach($productIdArray as $prodId) {
  2474.             $productTranslations = ProductTranslation::model()->findAll('product_id=' . $prodId);
  2475.             if (empty($productTranslations)) {
  2476.                 echo '<p> No product translation for productId: ' . $prodId . ' was found! Continuing...</p>';
  2477.                 continue;
  2478.             }
  2479.             // foreach translation of the product
  2480.             foreach($productTranslations as $transl) {
  2481.                 $translString = $transl->title;
  2482.                 $prodId = $transl->product_id;
  2483.                 // echo '<p> '. $translString .' </p>';
  2484.                 $titleArray = explode(' ', $translString);
  2485.                 // foreach word in the translation
  2486.                 foreach($titleArray as $titleWord) {
  2487.                     $replaceArray = array(
  2488.                         '//',
  2489.                         '(',
  2490.                         ')',
  2491.                         "™",
  2492.                         '"',
  2493.                         "'"
  2494.                     );
  2495.                     $titleWord = str_replace($replaceArray, '', $titleWord);
  2496.                     $titleWord = preg_replace("/(™|®|©|&trade;|&reg;|&copy;|&#8482;|&#174;|&#169;)/", "", $titleWord);
  2497.                     $titleWord = trim($titleWord);
  2498.                     if ($titleWord === '' || $titleWord === null || $titleWord === false) {
  2499.                         continue;
  2500.                     }
  2501.                     $titleWord = strtolower($titleWord);
  2502.                     $searchWord = SearchWord::model()->find('searchWord="' . $titleWord . '"');
  2503.                     if (!$searchWord) {
  2504.                         if (!in_array($titleWord, $distinctWordsInsert, true))
  2505.                             $distinctWordsInsert[] = $titleWord;
  2506.                     } elseif (ProductHasSearchWords::model()->find('product_id=' . $prodId . ' AND searchWord_id=' . $searchWord->getPrimaryKey()))
  2507.                         continue;
  2508.                     if (!isset($productWordsMapping[$prodId]))
  2509.                         $productWordsMapping[$prodId] = array();
  2510.                     if (!in_array($titleWord, $productWordsMapping[$prodId]))
  2511.                         $productWordsMapping[$prodId][] = $titleWord;
  2512.                 }
  2513.             }
  2514.         }
  2515.        
  2516.         // insert searchwords which are new
  2517.         if (!empty($distinctWordsInsert)) {
  2518.             $wordChunks = array_chunk($distinctWordsInsert, 1000);
  2519.             foreach($wordChunks as $wordChunk) {
  2520.                 $size = count($wordChunk);
  2521.                 $insertWordsSQL = 'INSERT INTO searchWord (searchWord) VALUES';
  2522.                 $i = 1;
  2523.                 foreach($wordChunk as $w) {
  2524.                     $insertWordsSQL .= ' ("' . $w . '")';
  2525.                     if ($i != $size)
  2526.                         $insertWordsSQL .= ' , ';
  2527.                     $i++;
  2528.                 }
  2529.                 $insertWordsSQL .= ' ;';
  2530.                 Yii::app()->db->createCommand($insertWordsSQL)->execute();
  2531.             }
  2532.         }
  2533.         $productWordsMappingChunk = array_chunk($productWordsMapping, 100, true);
  2534.         $mappingCount = 1;
  2535.        
  2536.         // insert matching dor product id and search words
  2537.         foreach($productWordsMappingChunk as $prodCh) {
  2538.             $query = false;
  2539.             // FIXME: duplicated and when update remove old searchWords and
  2540.             // insert new ones
  2541.             $insertMappingSQL = "INSERT IGNORE INTO product_has_searchWords (product_id, searchWord_id) VALUES ";
  2542.             $sizeChunk = count($prodCh);
  2543.             $currChunk = 1;
  2544.             foreach($prodCh as $productId=>$words) {
  2545.                 $j = 1;
  2546.                 $size = count($words);
  2547.                 foreach($words as $word) {
  2548.                     $insertMappingSQL .= ' (' . $productId . ', (Select id from searchWord where searchWord="' . $word . '")) ';
  2549.                     if ($j != $size)
  2550.                         $insertMappingSQL .= ', ';
  2551.                     $j++;
  2552.                     $query = true;
  2553.                 }
  2554.                 // only , if not the last insert before execution
  2555.                 if ($currChunk != $sizeChunk)
  2556.                     $insertMappingSQL .= ', ';
  2557.                 $currChunk++;
  2558.             }
  2559.             if ($query) {
  2560.                 $insertMappingSQL .= ';';
  2561.                 Yii::app()->db->createCommand($insertMappingSQL)->execute();
  2562.             }
  2563.         }
  2564.         return true;
  2565.     }
  2566.  
  2567. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement