Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Product Controller
- *
- * @author Edgar Kuskov <ekuskov@gmail.com>
- * @version 1.0
- * @package Modules.Project.Controller
- */
- class ProductController extends Controller {
- /**
- *
- * @return array action filters
- */
- public function filters() {
- return array(
- 'accessControl', // perform access control for CRUD
- // operations
- 'postOnly + delete'
- );
- // we only allow deletion via POST request
- }
- /**
- * Specifies the access control rules.
- * This method is used by the 'accessControl' filter.
- *
- * @return array access control rules
- */
- public function accessRules() {
- return array(
- array(
- 'allow',
- 'users' => array(
- '@'
- )
- ),
- array(
- 'deny', //
- // deny all users
- 'users' => array(
- '*'
- )
- )
- );
- }
- /**
- * Show products modal view
- */
- public function actionProductsModal() {
- $model = new Product('search');
- $model->unsetAttributes();
- $checkbox = false;
- $resultFunction = $grid_id = '';
- if (isset($_POST['resultFunction']))
- $resultFunction = $_POST['resultFunction'];
- if (isset($_POST['checkbox']) && $_POST['checkbox'] === 'true')
- $checkbox = true;
- if (isset($_GET['Product'])) {
- $model->attributes = $_GET['Product'];
- $model->title = $_GET['Product']['title'];
- }
- if (isset($_GET['ajax']))
- $grid_id = $_GET['ajax'];
- echo $this->renderPartial('_table', array(
- 'model' => $model,
- 'function' => $resultFunction,
- 'checkbox' => $checkbox,
- 'grid_id' => $grid_id
- ), false, true);
- }
- /**
- * Show products modal view
- */
- public function actionCustomProductModal() {
- $function = $_POST['resultFunction'];
- $model = new Size('customSize');
- $unity = new FoilTypeUnity();
- echo $this->renderPartial('_customProduct', array(
- 'model' => $model,
- 'unity' => $unity,
- 'function' => $function
- ), false, true);
- }
- /**
- * Lists all models.
- */
- public function actionIndex() {
- $model = new Product('search');
- $model->unsetAttributes();
- if (isset($_GET['Product'])) {
- $model->attributes = $_GET['Product'];
- $model->title = $_GET['Product']['title'];
- $model->manufacturer = $_GET['Product']['manufacturer'];
- }
- if (isset($_GET['searchValue'])) {
- $model->searchValue = $_GET['searchValue'];
- // Add search parts to product details
- if (is_numeric($model->searchValue) && strlen($model->searchValue) == 13) {
- $model->ean = $model->searchValue;
- } elseif (is_numeric($model->searchValue) && strlen($model->searchValue) < 13) {
- $model->id = $model->searchValue;
- $model->title = '';
- } else {
- $model->title = $model->searchValue;
- }
- }
- $this->render('index', array(
- 'model' => $model
- ));
- }
- /**
- * Create product manually
- */
- public function actionCreate() {
- $model = new Product('customCreate');
- $pProduct = new PhysicalProduct();
- $model->physicalProduct = $pProduct;
- if (isset($_POST['Product']) && isset($_POST['PhysicalProduct'])) {
- $model->attributes = $_POST['Product'];
- $model->physicalProduct_id = '1';
- $model->project_id = 1;
- $model->createDate = date('Y-m-d H:i:s');
- $model->editOwnerUser_id = Yii::app()->user->id;
- $pProduct->attributes = $_POST['PhysicalProduct'];
- // Check if EAN code is needed
- if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
- $model->ean = Ean::getFreeEANCode();
- if ($model->validate() && $pProduct->validate()) {
- $pProduct->save(false);
- $model->physicalProduct_id = $pProduct->getPrimaryKey();
- if (!empty($model->availableFromDate))
- $model->availableFromDate = date('Y-m-d H:i:s', strtotime($model->availableFromDate));
- if (!empty($model->availableToDate))
- $model->availableToDate = date('Y-m-d H:i:s', strtotime($model->availableToDate));
- $model->save(false);
- // Block ean code
- if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
- Ean::blockEANCode($model->ean);
- if (isset($_POST['Product']['productERPGroups'])) {
- $erpGroups = $_POST['Product']['productERPGroups'];
- $erpGroups = array_filter($erpGroups);
- $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- foreach($erpGroups as $group) {
- $endGroup = 0;
- if ($group == end($erpGroups))
- $endGroup = 1;
- $sql = 'INSERT INTO product_has_productERPGroup VALUES (' . $group . ', ' . $model->primaryKey . ', 0 , ' . $endGroup . ')';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- if (isset($_POST['Product']['productCategories'])) {
- $categories = $_POST['Product']['productCategories'];
- $categories = array_filter($categories);
- $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- foreach($categories as $category) {
- $endCategory = 0;
- if ($category == end($categories))
- $endCategory = 1;
- $sql = 'INSERT INTO product_has_productCategory VALUES (' . $category . ', ' . $model->primaryKey . ', 0 , ' . $endCategory . ')';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- } else {
- if (isset($_POST['Product']) && $_POST['Product']['needsEAN'] == 1)
- Ean::freeEan($model->ean);
- $pProduct->validate();
- }
- Helper::ajaxReturn(array_merge($pProduct->errors, $model->errors), null, array(
- 'productID' => $model->getPrimaryKey()
- ));
- }
- $this->render('createForm', array(
- 'model' => $model
- ));
- }
- /**
- * This function generates a category tree for the product
- *
- * @param Product $product
- * @param String $categories
- * @param Array $params
- * @return boolean if the categories were generated
- */
- public static function generateCategories($product, $categoriesFormula, $params, $updateReturn = false) {
- $currentParent = null;
- $languages = Language::model()->findAll('active=1');
- if ($languages) {
- // Remove all previous categories
- if ($updateReturn == false) {
- $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $product->id;
- Yii::app()->db->createCommand($sql)->query();
- }
- // Generate categories for each language
- $productCategories = array();
- foreach($languages as $language) {
- $categories = Helper::decodeModuleValues($categoriesFormula, $params, $language->isoCode);
- if ($categories === false)
- return false;
- // Add category for custom sizes
- if ($params['size']->sizeType_id == Yii::app()->params['customSize'])
- $type = SizeType::model()->findByPk(Yii::app()->params['customSize']);
- elseif ($params['size']->sizeType_id == Yii::app()->params['customerSize'])
- $type = SizeType::model()->findByPk(Yii::app()->params['customerSize']);
- if (!empty($type))
- $categories .= ' ##separator## ' . $type->title[Yii::app()->language];
- $categories = explode('##separator##', $categories);
- if ($categories) {
- foreach($categories as $key=>$category)
- $productCategories[$key][$language->isoCode] = trim($category);
- }
- }
- // Generate the categories
- $addedCategories = array();
- $categoriesTranslations = array();
- $currentParent = null;
- foreach($productCategories as $key=>$category) {
- $emptyError = false;
- if (empty($category))
- $emptyError = true;
- foreach($category as &$trans) {
- if (strlen($trans) == 0) {
- $emptyError = true;
- $trans = '----';
- }
- }
- if ($emptyError) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'One part of product categories is empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
- $error->save(false);
- }
- $sql = 'SELECT pc.id AS id
- FROM productCategory AS pc, productCategory_translation AS pct
- WHERE pct.productCategory_id=pc.id
- AND pct.title="' . addslashes(reset($category)) . '"
- AND pct.isoCode="' . key($category) . '"';
- if ($currentParent)
- $sql .= 'AND pc.productCategory_id="' . $currentParent . '"';
- else
- $sql .= 'AND pc.productCategory_id IS NULL';
- $exist = Yii::app()->db->createCommand($sql)->queryRow();
- if ($exist) {
- $currentParent = $exist['id'];
- } else {
- $productCategory = new ProductCategory();
- $productCategory->position = 0;
- $productCategory->productCategory_id = $currentParent;
- $productCategory->save(false);
- $currentParent = $productCategory->id;
- foreach($category as $key=>$title) {
- $categoriesTranslations[] = '(' . $productCategory->id . ',"' . $key . '","' . addslashes($title) . '")';
- }
- }
- $endCategory = ($category == end($productCategories)) ? 1 : 0;
- $addedCategories[] = '(' . $currentParent . ',"' . $product->id . '",0,' . $endCategory . ')';
- if ($endCategory == 1)
- $finalCategory = $currentParent;
- }
- $categoriesTranslations = array_unique($categoriesTranslations);
- $addedCategories = array_unique($addedCategories);
- // Add category translations
- if (!empty($categoriesTranslations)) {
- $sql = 'INSERT INTO productCategory_translation VALUES ' . implode(',', $categoriesTranslations);
- Yii::app()->db->createCommand($sql)->query();
- }
- if ($updateReturn == false) {
- if (!empty($addedCategories)) {
- $sql = 'INSERT INTO product_has_productCategory VALUES ' . implode(',', $addedCategories);
- Yii::app()->db->createCommand($sql)->query();
- }
- } else {
- return $finalCategory;
- }
- }
- return true;
- }
- /**
- * This function generates a erp group tree for the product
- *
- * @param Product $product
- * @param String $ERPGroupFormula
- * @param Array $params
- * @return boolean if the erp groups were generated
- */
- public static function generateERPGroups($product, $ERPGroupFormula, $params, $updateReturn = false) {
- $currentParent = null;
- $languages = Language::model()->findAll('active=1');
- if ($languages) {
- // Remove all previous categories
- if ($updateReturn == false) {
- $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $product->id;
- Yii::app()->db->createCommand($sql)->query();
- }
- // Generate categories for each language
- $productERPGroups = array();
- foreach($languages as $language) {
- $ERPGroups = Helper::decodeModuleValues($ERPGroupFormula, $params, $language->isoCode);
- if ($ERPGroups === false)
- return false;
- // Add erp group for custom sizes
- if ($params['size']->sizeType_id == Yii::app()->params['customSize'])
- $type = SizeType::model()->findByPk(Yii::app()->params['customSize']);
- elseif ($params['size']->sizeType_id == Yii::app()->params['customerSize'])
- $type = SizeType::model()->findByPk(Yii::app()->params['customerSize']);
- if (!empty($type))
- $ERPGroups .= ' ##separator## ' . $type->title[Yii::app()->language];
- $ERPGroups = explode('##separator##', $ERPGroups);
- if ($ERPGroups) {
- foreach($ERPGroups as $key=>$group)
- $productERPGroups[$key][$language->isoCode] = trim($group);
- }
- }
- // Generate ERP groups
- $addedERPGroups = array();
- $ERPGroupTranslations = array();
- $currentParent = null;
- foreach($productERPGroups as $key=>$group) {
- $emptyError = false;
- if (empty($group))
- $emptyError = true;
- foreach($group as &$trans) {
- if (strlen($trans) == 0) {
- $emptyError = true;
- $trans = '----';
- }
- }
- if ($emptyError) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'One part of product erp groups is empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
- $error->save(false);
- }
- $sql = 'SELECT pc.id AS id
- FROM productERPGroup AS pc, productERPGroup_translation AS pct
- WHERE pct.productERPGroup_id=pc.id
- AND pct.title="' . addslashes(reset($group)) . '"
- AND pct.isoCode="' . key($group) . '"';
- if ($currentParent)
- $sql .= 'AND pc.productERPGroup_id="' . $currentParent . '"';
- $exist = Yii::app()->db->createCommand($sql)->queryRow();
- if ($exist) {
- $currentParent = $exist['id'];
- } else {
- $erpGroup = new ProductERPGroup();
- $erpGroup->position = 0;
- $erpGroup->productERPGroup_id = $currentParent;
- $erpGroup->save(false);
- $currentParent = $erpGroup->id;
- foreach($group as $key=>$title) {
- $ERPGroupTranslations[] = '(' . $erpGroup->id . ',"' . $key . '","' . addslashes($title) . '")';
- }
- }
- $endCategory = ($group == end($productERPGroups)) ? 1 : 0;
- $addedERPGroups[] = '(' . $currentParent . ',"' . $product->id . '",0,' . $endCategory . ')';
- if ($endCategory == 1)
- $finalGroup = $currentParent;
- }
- $ERPGroupTranslations = array_unique($ERPGroupTranslations);
- $addedERPGroups = array_unique($addedERPGroups);
- if (!empty($ERPGroupTranslations)) {
- $sql = 'INSERT INTO productERPGroup_translation VALUES ' . implode(',', $ERPGroupTranslations);
- Yii::app()->db->createCommand($sql)->query();
- }
- if ($updateReturn == false) {
- if (!empty($addedERPGroups)) {
- $sql = 'INSERT INTO product_has_productERPGroup VALUES ' . implode(',', $addedERPGroups);
- Yii::app()->db->createCommand($sql)->query();
- }
- } else {
- return $finalGroup;
- }
- }
- return true;
- }
- /**
- * This function calculates costs in film protection project
- * Addition UC = unitCosts
- * Addition PC = processCosts
- * Addition OC = overheadCosts
- */
- public static function calculateCostsFromPackage($product, $foilTypeUnity, $packageSize, $sizes, $priceCondition) {
- $costRates = $product->project->costRates[0];
- if (empty($costRates))
- return $product->costPrice = null;
- $foilType = $foilTypeUnity->foilType;
- $foilArea = 0;
- $cuttingTime = 0;
- foreach($sizes as $size) {
- $foilArea += $size->heightWithPullTab * $size->widthWithPullTab;
- $cuttingTime += $size->cuttingTime;
- }
- // quntity needed
- $foilArea = $foilArea * $foilTypeUnity->unity;
- $cuttingTime = $cuttingTime * $foilTypeUnity->unity;
- // change area from mm² to m²
- $foilArea = $foilArea / 1000000;
- // change time from sec to hour
- $cuttingTime = $cuttingTime / 3600;
- $inspectionTime = $foilType->inspectionTime / 3600;
- $packagingTime = $packageSize->packagingTime / 3600;
- $foilTypeCosts_UC = $foilArea * $foilType->price * (1 + $foilType->clipping * 0.01) * (1 + $foilType->faulty * 0.01);
- $foilTypeCosts_PC = $foilArea * $inspectionTime * $costRates->inspectionProcess;
- $foilTypeCosts_OC = $foilTypeCosts_UC * $costRates->procurementOverheadPercent * 0.01;
- $packageParts_UC = 0;
- if (!empty($packageSize->packageParts)) {
- foreach($packageSize->packageParts as $packagePart) {
- $packageParts_UC += $packagePart->price;
- }
- }
- $packageParts_OC = $packageParts_UC * $costRates->procurementOverheadPercent * 0.01;
- $cuttingCosts_PC = $cuttingTime * $costRates->cuttingProcess;
- $cuttingCosts_OC = $cuttingCosts_PC * $costRates->productionOverheadPercent * 0.01;
- $packagingCosts_PC = $packagingTime * $costRates->packagingProcess;
- $packagingCosts_OC = $packagingCosts_PC * $costRates->packagingOverheadPercent * 0.01;
- $hourRate = 0;
- // here nothing set
- $foilTypeSizes = FoilTypeSize::model()->findAll('foilType_id=' . $foilType->id);
- if (!empty($foilTypeSizes)) {
- foreach($foilTypeSizes as $fts) {
- $productionDeviceSizeMats = ProductionDeviceSizeMat::model()->findAll('foilTypeSize_id=' . $fts->id);
- if (!empty($productionDeviceSizeMats)) {
- foreach($productionDeviceSizeMats as $productionDeviceSizeMat) {
- if ($productionDeviceSizeMat->productionDevice->hourRate > $hourRate)
- $hourRate = $productionDeviceSizeMat->productionDevice->hourRate;
- }
- }
- }
- }
- if ($hourRate == 0)
- $hourRate = 50;
- $machineCosts_PC = $cuttingTime * $hourRate;
- $machineCosts_OC = $machineCosts_PC * $costRates->productionOverheadPercent * 0.01;
- // production specific overhead costs
- $productionCosts = $cuttingCosts_PC + $cuttingCosts_OC + $packagingCosts_PC + $packagingCosts_OC + $machineCosts_PC + $machineCosts_OC;
- $production_OC = $productionCosts * $costRates->administrationOverheadPercent * 0.01;
- $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;
- // general part of price calculation (not foil specific)
- $sql = "SELECT pickingCosts
- FROM carrierProductFormat
- WHERE maxHeight>=" . $product->physicalProduct->height . " AND maxWidth>=" . $product->physicalProduct->width . " AND maxDepth>=" . $product->physicalProduct->depth . "
- ORDER BY pickingCosts ASC;";
- $carrierProductFormats = Yii::app()->db->createCommand($sql)->queryAll();
- $pickingCosts_PC = 0;
- if (empty($carrierProductFormats)) {
- $pickingCosts_PC = 0;
- } else {
- $pickingCosts_PC = $carrierProductFormats[0]['pickingCosts'];
- }
- $pickingCosts_OC = $pickingCosts_PC * $costRates->pickingOverheadPercent * 0.01;
- $sales_PC = $costRates->salesProcessPiece + ($costRates->salesProcessPercent * 0.01 * $manufacturingCosts) + $costRates->customerServiceProcessPiece + ($costRates->customerServiceProcessPercent * 0.01 * $manufacturingCosts);
- $sales_OC = $sales_PC * $costRates->salesOverheadPercent * 0.01;
- $administrationCosts = $pickingCosts_PC + $pickingCosts_OC + $sales_PC + $sales_OC;
- $administration_OC = $administrationCosts * $costRates->administrationOverheadPercent * 0.01;
- $unitCosts = $foilTypeCosts_UC + $packageParts_UC;
- $processCosts = $foilTypeCosts_PC + $cuttingCosts_PC + $packagingCosts_PC + $machineCosts_PC + $pickingCosts_PC + $sales_PC;
- $overheadCosts = $foilTypeCosts_OC + $packageParts_OC + $cuttingCosts_OC + $packagingCosts_OC + $machineCosts_OC + $production_OC + $pickingCosts_OC + $sales_OC + $administration_OC;
- $costPriceWithoutSurcharges = $unitCosts + $processCosts + $overheadCosts;
- $costPrice = $costPriceWithoutSurcharges * (1 + $costRates->processLossPercent * 0.01) + $costPriceWithoutSurcharges * (1 + $costRates->warrantyPercent * 0.01);
- // set costs to product
- $product->costPrice = $costPrice;
- // $priceCondition->unitCosts = $unitCosts;
- // $priceCondition->processCosts = $processCosts;
- // $priceCondition->overheadCosts = $overheadCosts;
- }
- /**
- * This function iterates throw all calculation model to calculate costs
- * (price conditions)
- * for every calculation model, that linked to erp group in which the given
- * product is.
- * After that price conditions will be saved (in savePriceConditions
- * function).
- * Used by create products cronjob.
- * Used for film protectors project.
- * Addition UC = unitCosts
- * Addition PC = processCosts
- * Addition OC = overheadCosts
- */
- public static function changePriceConditions($product, $fromDate = NULL, $testPrice = false, $priceCondition) {
- // Get Main ERP Group for the product
- $productHasERPGroups = ProductHasProductERPGroup::model()->findAll('product_id=' . $product->id . ' AND endGroup=1 ORDER BY standard DESC');
- if (!empty($productHasERPGroups))
- $productERPGroup_id = $productHasERPGroups[0]->productERPGroup_id;
- else
- $productERPGroup_id = NULL;
- // Loop all ERP Groups for most specific pricing models for rrp and all
- // marketplaces
- while ( !is_null($productERPGroup_id) ) {
- $productERPGroup = ProductERPGroup::model()->findByPk($productERPGroup_id);
- if (!$productERPGroup)
- break;
- // get next ERP Group (parent)
- $productERPGroup_id = $productERPGroup->productERPGroup_id;
- $calculationModels = $productERPGroup->calculationModels;
- if (!empty($calculationModels)) {
- foreach($calculationModels as $calculationModel) {
- self::calculatePriceCondition($product, $calculationModel, $fromDate, $testPrice, $priceCondition);
- }
- }
- }
- }
- /**
- * This function calculates price condition for given product and calculation
- * model.
- *
- * @param Product $product
- * @param CalculationModel $calculationModel
- * @param Date $fromDate
- * @param boolean $testPrice
- */
- public static function calculatePriceCondition($product, $calculationModel, $fromDate, $testPrice, $priceCondition) {
- $costPrice = $product->costPrice;
- $costRates = $product->project->costRates[0];
- if (empty($fromDate))
- $fromDate = date('Y-m-d H:i:s');
- if ($testPrice)
- $calculationModel = CalculationModel::model()->findByPk($calculationModel);
- $foundRRP = false;
- $foundSalesThirdPartyMarketplaces = array();
- // check if model is needed for pricing (rrp)
- $saveRRP = false;
- if (!$foundRRP && $calculationModel->priceConditionType_id == 1)
- $saveRRP = true;
- // check if model is needed for pricing (marketplaces)
- $salesThirdPartyMarketplaces = $calculationModel->salesThirdPartyMarketplaces;
- if (!empty($salesThirdPartyMarketplaces)) {
- for($i = 0; $i < count($salesThirdPartyMarketplaces); $i++) {
- // remove from array if already done
- if (in_array($salesThirdPartyMarketplaces[$i]->id, $foundSalesThirdPartyMarketplaces))
- unset($salesThirdPartyMarketplaces[$i]);
- }
- }
- if (!$saveRRP && count($salesThirdPartyMarketplaces) == 0)
- continue;
- // costRangeRate = Percentage of costRange // min = 1% // max = 80% for
- // discount and margin
- $costRange = $calculationModel->costsTo - $calculationModel->costsFrom;
- if ($costRange <= 0) {
- $costRangeRate = 0.8;
- } else {
- $costRangeRate = max(min($costPrice, $calculationModel->costsTo), $calculationModel->costsFrom);
- $costRangeRate = max(min($costRangeRate / $costRange, 0.8), 0.01);
- }
- // Calculate dynamical marginRate (within range max marginFrom - min
- // marginTo)
- if ($calculationModel->marginFrom > $calculationModel->marginTo) {
- $marginFrom = $calculationModel->marginTo * 0.01;
- $marginTo = $calculationModel->marginFrom * 0.01;
- } else {
- $marginFrom = $calculationModel->marginFrom * 0.01;
- $marginTo = $calculationModel->marginTo * 0.01;
- }
- $marginRange = $marginFrom - $marginTo;
- $exponent = (1 - $marginFrom) * 0.1 / $costRangeRate;
- $marginRate = $marginFrom - $marginRange * pow($costRangeRate, $exponent);
- $margin = $costPrice * $marginRate;
- // Calculate dynamical discountRate (within range max marginFrom - min
- // discountTo)
- if ($calculationModel->discountFrom > $calculationModel->discountTo) {
- $discountFrom = $calculationModel->discountTo * 0.01;
- $discountTo = $calculationModel->discountFrom * 0.01;
- } else {
- $discountFrom = $calculationModel->discountFrom * 0.01;
- $discountTo = $calculationModel->discountTo * 0.01;
- }
- $discountRange = $discountFrom - $discountTo;
- $exponent = (1 - $discountFrom) * 0.1 / $costRangeRate;
- $discountRate = $discountFrom - $discountRange * pow($costRangeRate, $exponent);
- // select all exchange rules for this calculation model
- $sql = "SELECT exchangeRule_id
- FROM exchangeRule_has_calculationModel
- WHERE calculationModel_id=" . $calculationModel->id;
- $exchangeRuleIDs = Yii::app()->db->createCommand($sql)->queryAll();
- if (empty($exchangeRuleIDs))
- continue;
- $exchangeRules = array();
- foreach($exchangeRuleIDs as $exchangeRuleID) {
- $exchangeRules[] = ExchangeRule::model()->findByPk($exchangeRuleID['exchangeRule_id']);
- }
- if ($saveRRP) {
- $additionalCosts = $costPrice * $costRates->paymentCostsPercent * 0.01 + $costPrice * $costRates->sellingFeesPercent * 0.01;
- $targetPrice = $product->costPrice + $margin + $additionalCosts;
- $discountSurcharge = $targetPrice * $discountRate;
- $price = $targetPrice * (1 + $discountRate);
- // echo 'Selbstkosten: ' . $product->costPrice . '<br>';
- // echo '$price: ' . $price . '<br>';
- foreach($exchangeRules as $exchangeRule) {
- if ($testPrice) {
- if ($exchangeRule->currency_id == 0)
- return Helper::moneyForm(self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition), 2, NULL, true, "€");
- } else {
- self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition);
- }
- }
- }
- foreach($salesThirdPartyMarketplaces as $salesThirdPartyMarketplace) {
- $additionalCosts = max($product->costPrice * $salesThirdPartyMarketplace->sellingFeePercent, $salesThirdPartyMarketplace->sellingFeeMin);
- $additionalCosts += $product->costPrice * $salesThirdPartyMarketplace->paymentCostsPercent;
- $targetPrice = $costPrice + $margin + $additionalCosts;
- $discountSurcharge = $targetPrice * $discountRate;
- $price = $targetPrice * (1 + $discountRate);
- foreach($exchangeRules as $exchangeRule) {
- if ($salesThirdPartyMarketplace->currency_id != $exchangeRule->currency_id) {
- // currency not needed for marcet place
- // continue;
- }
- if ($testPrice) {
- if ($exchangeRule->currency_id == 0)
- return Helper::moneyForm(self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, NULL, $fromDate, $testPrice, $priceCondition), 2, NULL, true, "€");
- } else {
- self::savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, $salesThirdPartyMarketplace, $fromDate, $testPrice, $priceCondition);
- }
- }
- }
- }
- private static function savePriceCondition($product, $exchangeRule, $calculationModel, $price, $discountSurcharge, $margin, $salesThirdPartyMarketplace, $fromDate, $testPrice = false, $priceCondition) {
- if (!isset($priceCondition))
- $priceCondition = new PriceCondition();
- $priceCondition->active = 1;
- $priceCondition->product_id = $product->id;
- $priceCondition->currency_id = $exchangeRule->currency_id;
- $priceCondition->priceConditionType_id = $calculationModel->priceConditionType_id;
- $priceCondition->calculationModel_id = $calculationModel->id;
- $priceCondition->exchangeRate = $exchangeRule->currency->exchangeRate;
- $price = $price * (1 + $exchangeRule->surchargePercent * 0.01) * $priceCondition->exchangeRate;
- if ($testPrice) {
- return round($exchangeRule->minPrice + ceil(($price - $exchangeRule->minPrice) / $exchangeRule->priceSteps) * $exchangeRule->priceSteps, 4);
- } else {
- $priceCondition->price = round($exchangeRule->minPrice + ceil(($price - $exchangeRule->minPrice) / $exchangeRule->priceSteps) * $exchangeRule->priceSteps, 4);
- }
- $priceCondition->costPrice = round($product->costPrice, 4);
- $priceCondition->discountSurcharge = round($discountSurcharge, 4);
- $priceCondition->margin = round($margin, 4);
- // costRangeRate = Percentage of costRange // min = 1% // max = 80% for
- // shippingCosts
- $costRange = $calculationModel->priceTo - $calculationModel->priceFrom;
- if ($costRange <= 0) {
- $costRangeRate = 0.8;
- } else {
- $costRangeRate = max(min($priceCondition->price, $calculationModel->priceTo), $calculationModel->priceFrom);
- $costRangeRate = max(min($costRangeRate / $costRange, 0.8), 0.01);
- }
- // Calculate dynamical shippingCosts (within range max shippingCostsFrom
- // - min shippingCostsTo)
- if ($calculationModel->shippingCostsFrom > $calculationModel->shippingCostsTo) {
- $shippingCostsFrom = $calculationModel->shippingCostsTo;
- $shippingCostsTo = $calculationModel->shippingCostsFrom;
- } else {
- $shippingCostsFrom = $calculationModel->shippingCostsFrom;
- $shippingCostsTo = $calculationModel->shippingCostsTo;
- }
- $shippingCostsRange = $shippingCostsFrom - $shippingCostsTo;
- $exponent = (1 - $shippingCostsFrom) * 0.1 / $costRangeRate;
- $shippingCosts = $shippingCostsFrom - $shippingCostsRange * pow($costRangeRate, $exponent);
- $priceCondition->shippingCosts = round($shippingCosts, 4);
- $priceCondition->fromDate = $fromDate;
- $oldPriceCondition = null;
- if (!empty($salesThirdPartyMarketplaces)) {
- $sql = 'SELECT p.id AS id
- FROM priceCondition p
- LEFT JOIN priceCondition_has_salesThirdPartyMarketplace pchs ON phs.priceCondition_id = p.id
- WHERE p.product_id = ' . $priceCondition->product_id . ' AND p.currency_id=' . $priceCondition->currency_id . '
- AND p.priceConditionTyp_id=' . $priceCondition->priceConditionTyp_id . '
- AND phs.salesThirdPartyMarketplace_id = ' . $salesThirdPartyMarketplaces[0]->id;
- $oldPriceConditionIDs = Yii::app()->db->createCommand($sql)->queryAll();
- if (empty($oldPriceConditionIDs))
- $oldPriceCondition = PriceCondition::model()->findByPk($oldPriceConditionIDs[0]['id']);
- } else {
- $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');
- }
- // check if new or relevant changes to price condition
- 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) {
- if ($priceCondition->validate()) {
- // save new one
- $priceCondition->save(false);
- // add marketplace connection
- if (!empty($salesThirdPartyMarketplaces)) {
- foreach($salesThirdPartyMarketplaces as $salesThirdPartyMarketplace) {
- $sql = 'INSERT INTO priceCondition_has_salesThirdPartyMarketplace (priceCondition_id, salesThirdPartyMarketplace_id)
- VALUES (' . $priceCondition->id . ', ' . $salesThirdPartyMarketplace->id . ')';
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- if (!empty($oldPriceCondition)) {
- // end old price condition
- $oldPriceCondition->toDate = $fromDate;
- $oldPriceCondition->save(false);
- }
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Pricing invalid. Product: <a target="_blank" href="/project/product/update?id=' . $product->id . '">' . $product->id . '</a>';
- $error->save(false);
- return false;
- }
- }
- }
- /**
- * Function to create a product in film protection project
- *
- * @param int $packageID
- * @param string $custom
- * @param string $return
- * @return boolean|string|Product|number
- */
- public static function createProductFromPackage($packageID, $return = false) {
- // Setup time sheet for testing
- exec('rm -rf ' . Yii::app()->basePath . '/../times.csv');
- $path = Yii::app()->basePath . '/../times.csv';
- $fp = fopen($path, "a+");
- $times = array();
- $allTime = microtime(true);
- $time = microtime(true);
- $product = new Product();
- $package = Package::model()->findByPk($packageID);
- if (empty($package)) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Package ' . $packageID . ' doesnt exist!';
- $error->save(false);
- return false;
- }
- $sql = 'SELECT mhp.product_id AS pid
- FROM module AS m
- LEFT JOIN module_has_product AS mhp ON mhp.module_id = m.id
- WHERE m.id=' . $packageID . '
- AND mhp.product_id IS NOT NULL';
- $eProduct = Yii::app()->db->createCommand($sql)->queryRow();
- if (!empty($eProduct)) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Package ' . $packageID . ' already has a product <a target="_blank" href="/project/product/update?id=' . $eProduct['pid'] . '">' . $eProduct['pid'] . '</a>!';
- $error->save(false);
- return false;
- }
- /**
- * If product from previous system get the old EAN code
- * TODO: remove after migration to new platform
- */
- if (!$package->old_ean) {
- $product->ean = Ean::model()->getFreeEANCode();
- if ($product->ean == 0)
- die('No free EAN Codes!');
- } else {
- $product->ean = $package->old_ean;
- }
- // Init help values
- $createDate = $package->module->createDate;
- $project = $package->module->moduleGroup->projects[0];
- $productActive = true;
- // will be false if not active later
- // Get product parts
- $foilTypeUnity = $package->foilTypeUnityModule;
- if ($foilTypeUnity->module->active == 0)
- $productActive = false;
- $foilType = $foilTypeUnity->foilType;
- if ($foilType->active == 0)
- $productActive = false;
- $sizes = array();
- $sizesIDs = array();
- $standardSize = null;
- $deviceSize = null;
- $device = null;
- $phs = PackageHasSize::model()->findAll('package_module_id=' . $packageID);
- foreach($phs as $ps) {
- $size = Size::model()->findByPk($ps->size_module_id);
- if ($size->module->active == 0)
- $productActive = false;
- // Skip products, that are connected to blocked sizes or size doesnt
- // have size version
- if ($size->blocked || empty($size->sizeVersions))
- return false;
- $sizes[] = $size;
- $sizeIDs[] = $ps->size_module_id;
- if ($standardSize == null || $size->sizeType_id == Yii::app()->params['standardSize'])
- $standardSize = $size;
- if ($size->sizeType_id == Yii::app()->params['deviceSize'])
- $deviceSize = $size;
- if ($ps->device_module_id) {
- $device = Device::model()->findByPk($ps->device_module_id);
- if ($device->module->active == 0)
- $productActive = false;
- }
- }
- if (!empty($device)) {
- $standardSize = $deviceSize;
- }
- // Change the ID of the product from the old system
- if ($foilTypeUnity->module_id != 2 && $device) {
- $product->id = $package->old_package_id;
- } elseif ($foilTypeUnity->module_id == 2 && $device) {
- $product->id = 1300000 + $device->old_device_id;
- }
- $times['Initialise'] = microtime(true) - $time;
- $time = microtime(true);
- /**
- * Check if the same physical product for selected
- * sizes and foil type unity already exists
- */
- $sql = 'SELECT p.physicalProduct_id AS pid
- FROM module AS m
- LEFT JOIN module_has_product AS mhp ON mhp.module_id = m.id
- LEFT JOIN product AS p ON mhp.product_id=p.id
- WHERE (m.id IN (' . implode(',', $sizeIDs) . ') AND m.moduleGroup_id=2)
- OR (m.id=' . $foilTypeUnity->module_id . ' AND m.moduleGroup_id=3)
- GROUP BY mhp.product_id HAVING COUNT(*)=' . (count($sizeIDs) + 1);
- $existPProduct = Yii::app()->db->createCommand($sql)->queryRow();
- $times['Check existing'] = microtime(true) - $time;
- $time = microtime(true);
- if (!empty($existPProduct))
- $pProduct = PhysicalProduct::model()->findByPk($existPProduct['pid']);
- if (empty($pProduct))
- $pProduct = new PhysicalProduct();
- $packageSize = $package->packageSize;
- $pProduct->width = $packageSize->width;
- $pProduct->height = $packageSize->height;
- $pProduct->depth = $packageSize->depth;
- $pProduct->weight = ceil(($foilTypeUnity->unity * $foilType->weight)) + $packageSize->weight;
- $pProduct->manufacturer_id = $foilType->productManufacturer_id;
- $pProduct->manufacturerSKU = '##reload##';
- $pProduct->getsLabel = 0;
- $pProduct->ownProduction = 1;
- if ($pProduct->validate()) {
- $pProduct->save(false);
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $pError = var_export($pProduct->errors, true);
- $pValues = var_export($pProduct->attributes, true);
- $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;
- $error->save(false);
- return false;
- }
- if ($pProduct->manufacturerSKU == '##reload##') {
- $pProduct->manufacturerSKU = $pProduct->getPrimaryKey();
- $pProduct->save(false);
- }
- switch ($standardSize->sizeType_id) {
- case Yii::app()->params['deviceSize'] :
- $titleValue = 'deviceProductTitleFormula';
- $shortTitleValue = 'deviceProductShortTitleFormula';
- break;
- case Yii::app()->params['standardSize'] :
- $titleValue = 'standardProductTitleFormula';
- $shortTitleValue = 'standardProductShortTitleFormula';
- break;
- case Yii::app()->params['customSize'] :
- $titleValue = 'customProductTitleFormula';
- $shortTitleValue = 'customProductShortTitleFormula';
- break;
- case Yii::app()->params['customerSize'] :
- $titleValue = 'customerProductTitleFormula';
- $shortTitleValue = 'customerProductShortTitleFormula';
- break;
- default :
- $titleValue = 'standardProductTitleFormula';
- $shortTitleValue = 'standardProductShortTitleFormula';
- break;
- }
- $product->title = array();
- $product->shortTitle = array();
- // ***
- $product->description = array();
- $product->shortDescription = array();
- $product->deliveryScope = array();
- $product->langActive = $foilType->langActive;
- $decodeParams = array();
- $decodeParams['project'] = $project;
- if (!empty($device)) {
- $decodeParams['device'] = $device;
- $decodeParams['deviceType'] = $device->deviceType;
- }
- $decodeParams['foilType'] = $foilType;
- $decodeParams['bulletPoints'] = $foilType->bulletPoints;
- $decodeParams['foilTypeUnity'] = $foilTypeUnity;
- $decodeParams['size'] = $standardSize;
- $decodeParams['sizes'] = $sizes;
- $foilTypeTitles = $foilType->$titleValue;
- $foilTypeShortTitles = $foilType->$shortTitleValue;
- $languages = Language::model()->findAll('active=1');
- if (!empty($languages)) {
- foreach($languages as $lang) {
- $product->title[$lang->isoCode] = Helper::decodeModuleValues($foilTypeTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
- // ***
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $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;
- $error->save(false);
- return false;
- }
- $product->shortTitle[$lang->isoCode] = Helper::decodeModuleValues($foilTypeShortTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $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;
- $error->save(false);
- return false;
- }
- $product->description[$lang->isoCode] = Helper::decodeModuleValues($foilType->productDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $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;
- $error->save(false);
- return false;
- }
- $product->shortDescription[$lang->isoCode] = Helper::decodeModuleValues($foilType->productShortDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $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;
- $error->save(false);
- return false;
- }
- $product->deliveryScope[$lang->isoCode] = Helper::decodeModuleValues($foilType->deliveryScope[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $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;
- $error->save(false);
- return false;
- }
- }
- }
- $product->project_id = $project->id;
- $product->physicalProduct_id = $pProduct->getPrimaryKey();
- $product->createDate = $createDate;
- $product->lastUpdate = date('Y-m-d H:i:s');
- $product->active = intval($productActive);
- $product->availableFromDate = date('Y-m-d H:i:s', max(array(
- strtotime($standardSize->saleStartDate),
- time() + 60 * 60 * 2
- )));
- if (!empty($standardSize->saleEndDate))
- $product->availableToDate = date('Y-m-d H:i:s', strtotime($standardSize->saleEndDate));
- if (strtotime($product->availableFromDate) > time())
- $product->available = 0;
- else
- $product->available = 1;
- $product->originCountry_id = $foilType->productCountry_id;
- $product->brand_id = $foilType->brand_id;
- $product->productType_id = 1;
- $product->productLine_id = $foilType->productLine_id;
- $times['Creating metas'] = microtime(true) - $time;
- $time = microtime(true);
- $priceCondition = new PriceCondition();
- self::calculateCostsFromPackage($product, $foilTypeUnity, $packageSize, $sizes, $priceCondition);
- if ($product->validate() && $product->save(false)) {
- Helper::saveMultiligualParameter($product, array(
- 'langActive',
- 'title',
- 'shortTitle',
- 'description',
- 'shortDescription',
- 'deliveryScope'
- ));
- Ean::model()->blockEANCode($product->ean);
- } else {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $pError = var_export($product->errors, true);
- $pValues = var_export($product->attributes, true);
- $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;
- $error->save(false);
- return false;
- }
- $times['Saving product'] = microtime(true) - $time;
- $time = microtime(true);
- // Create categories
- $categories = self::generateCategories($product, $foilType->categoryFormula, $decodeParams);
- if ($categories === false) {
- $sql = 'DELETE FROM `module_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `projectNote` WHERE product_id=product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_bulletPoints` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_keywords` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productCategory` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productERPGroup` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productFeatureValue` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_media` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_translation` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product` WHERE id=' . $product->getPrimaryKey() . ';';
- Yii::app()->db->createCommand($sql)->execute();
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Product categories have errors';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- return false;
- }
- $times['Create categories'] = microtime(true) - $time;
- $time = microtime(true);
- // Create ERP Groups
- $erpGroups = self::generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams);
- if ($erpGroups === false) {
- $sql = 'DELETE FROM `module_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `projectNote` WHERE product_id=product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_bulletPoints` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_keywords` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_product` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productCategory` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productERPGroup` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_productFeatureValue` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_has_media` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product_translation` WHERE product_id=' . $product->getPrimaryKey() . ';
- DELETE FROM `product` WHERE id=' . $product->getPrimaryKey() . ';';
- Yii::app()->db->createCommand($sql)->execute();
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'ERP Groups have errors';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- return false;
- }
- $times['Create ERP groups'] = microtime(true) - $time;
- $time = microtime(true);
- // Connect keywords
- $keywords = $foilType->keywords;
- if (!empty($device)) {
- if (is_array($keywords))
- $keywords = array_merge($keywords, $device->keywords);
- else
- $keywords = $device->keywords;
- }
- if (!empty($keywords)) {
- $values = ' VALUES ';
- foreach($keywords as $key=>$word) {
- $values .= '(' . $product->id . ', ' . $word->id . ')';
- if ($key < count($keywords) - 1)
- $values .= ',';
- }
- $sql = 'INSERT INTO product_has_keywords ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Products keywords are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- }
- $times['Connect keywords'] = microtime(true) - $time;
- $time = microtime(true);
- // Connect bulletpoints
- $bulletPoints = $foilType->bulletPoints;
- if (!empty($bulletPoints)) {
- $values = ' VALUES ';
- foreach($bulletPoints as $key=>$point) {
- $values .= '(' . $product->id . ', ' . $point->id . ')';
- if ($key < count($bulletPoints) - 1)
- $values .= ',';
- }
- $sql = 'INSERT INTO product_has_bulletPoints ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Products bulletpoints are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- }
- $times['Connect bulletpoints'] = microtime(true) - $time;
- $time = microtime(true);
- // Connect product features
- $productFeatureValues = $foilType->productFeatureValues;
- if (!empty($productFeatureValues)) {
- $values = ' VALUES ';
- foreach($productFeatureValues as $value) {
- $values .= '(' . $product->id . ', ' . $value->id . ', 0)';
- if ($value != end($productFeatureValues))
- $values .= ',';
- }
- $sql = 'INSERT INTO product_has_productFeatureValue ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->text = 'Products features are empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- }
- $times['Connect product features'] = microtime(true) - $time;
- $time = microtime(true);
- // Get all product modules
- $pModulesIDs = array(
- $packageID
- );
- if ($device != null && $device->module_id)
- $pModulesIDs[] = $device->module_id;
- foreach($sizes as $size)
- $pModulesIDs[] = $size->module_id;
- $pModulesIDs[] = $foilTypeUnity->module_id;
- $pModulesIDs = array_filter($pModulesIDs);
- // Create medias for product
- $sql = 'SELECT mm.media_id as id
- FROM module_has_media AS mm
- LEFT JOIN media AS m ON m.id=mm.media_id
- LEFT JOIN mediaType AS mt ON mt.id=m.mediaType_id
- WHERE mm.module_id IN(' . implode(',', $pModulesIDs) . ')
- AND mt.productSpecific=1';
- $medias = Yii::app()->db->createCommand($sql)->queryAll();
- if (!empty($medias)) {
- foreach($medias as $media) {
- $sql = 'INSERT INTO product_has_media(media_id,product_id) VALUES(' . $media['id'] . ',' . $product->id . ')';
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- $times['Bind medias to product'] = microtime(true) - $time;
- $time = microtime(true);
- // Bind product with modules
- $values = ' VALUES ';
- foreach($pModulesIDs as $pm) {
- $values .= '(' . $pm . ',' . $product->id . ')';
- if ($pm != end($pModulesIDs))
- $values .= ',';
- }
- $sql = 'INSERT INTO module_has_product ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- $times['Bind modules to product'] = microtime(true) - $time;
- $time = microtime(true);
- // create or update price conditions
- self::changePriceConditions($product, null, false, $priceCondition);
- $times['Price conditions generation'] = microtime(true) - $time;
- $time = microtime(true);
- $times[] = microtime(true) - $allTime;
- $times[] = $product->id;
- fputcsv($fp, $times);
- fclose($fp);
- if (!empty($product->editOwnerUser_id) && $standardSize->sizeType_id == Yii::app()->params['customerSize']) {
- $conversation = new ChatConversation();
- $conversation->subject = 'Product is ready';
- $conversation->senderRead = 1;
- $conversation->recipientRead = 0;
- $conversation->sender_id = 0;
- $conversation->recipient_id = $product->editOwnerUser_id;
- $conversation->save(false);
- $message = new ChatMessage();
- $message->text = 'Product has been created: <a target="_blank" href="/project/product/update/id/' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $message->chatConversation_id = $conversation->getPrimaryKey();
- $message->sender_id = 0;
- $message->save(false);
- }
- if ($return)
- return $product;
- else
- return $product->id;
- }
- /**
- * Update product
- */
- public function updateProductFromPackageById($id, $return = false) {
- $product = Product::model()->findByPk($id);
- $_product = $product->attributes;
- if (empty($product)) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Product doesnt exist';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- return false;
- }
- $pProduct = $product->physicalProduct;
- $_pProduct = $pProduct->attributes;
- if (empty($pProduct)) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Physical product doesnt exist';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- return false;
- }
- // Remove old changes and create new changes array
- $sql = 'DELETE FROM productManualChanges WHERE product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->execute();
- $productChanges = array();
- // Get product parts
- $productActive = 1;
- $pParts = $product->getParts();
- if (empty($pParts)) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Modules are missing';
- $error->text = 'Product modules empty. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>';
- $error->save(false);
- return false;
- }
- $package = $pParts['package'];
- if ($package->module->active == 0)
- $productActive = 0;
- $foilTypeUnity = $pParts['unity'];
- if ($foilTypeUnity->module->active == 0)
- $productActive = 0;
- $foilType = $pParts['foilType'];
- if ($foilType->active == 0)
- $productActive = 0;
- $sizes = $pParts['sizes'];
- $standardSize = $pParts['standardSize'];
- $sizesIDs = array();
- foreach($sizes as $size) {
- if ($size->module->active == 0)
- $productActive = 0;
- if ($size->blocked || empty($size->sizeVersions))
- continue;
- if ($standardSize == null || $size->sizeType_id == Yii::app()->params['standardSize'])
- $standardSize = $size;
- $sizeIDs[] = $size->module_id;
- }
- if (isset($pParts['device'])) {
- $device = $pParts['device'];
- if ($device->module->active == 0)
- $productActive = 0;
- $standardSize = $pParts['deviceSize'];
- }
- $product->active = $productActive;
- $packageSize = $package->packageSize;
- $pProduct->width = $packageSize->width;
- $pProduct->height = $packageSize->height;
- $pProduct->depth = $packageSize->depth;
- $pProduct->weight = ceil(($foilTypeUnity->unity * $foilType->weight)) + $packageSize->weight;
- $pProduct->manufacturer_id = $foilType->productManufacturer_id;
- $pProduct->getsLabel = 0;
- $pProduct->ownProduction = 1;
- switch ($standardSize->sizeType_id) {
- case Yii::app()->params['deviceSize'] :
- $titleValue = 'deviceProductTitleFormula';
- $shortTitleValue = 'deviceProductShortTitleFormula';
- break;
- case Yii::app()->params['standardSize'] :
- $titleValue = 'standardProductTitleFormula';
- $shortTitleValue = 'standardProductShortTitleFormula';
- break;
- case Yii::app()->params['customSize'] :
- $titleValue = 'customProductTitleFormula';
- $shortTitleValue = 'customProductShortTitleFormula';
- break;
- case Yii::app()->params['customerSize'] :
- $titleValue = 'customerProductTitleFormula';
- $shortTitleValue = 'customerProductShortTitleFormula';
- break;
- default :
- $titleValue = 'standardProductTitleFormula';
- $shortTitleValue = 'standardProductShortTitleFormula';
- break;
- }
- // Save old values for metas
- $_product['title'] = $product->title;
- $_product['shortTitle'] = $product->shortTitle;
- $_product['description'] = $product->description;
- $_product['shortDescription'] = $product->shortDescription;
- $_product['deliveryScope'] = $product->deliveryScope;
- $product->title = array();
- $product->shortTitle = array();
- $product->description = array();
- $product->shortDescription = array();
- $product->deliveryScope = array();
- $_product['langActive'] = $product->langActive;
- $product->langActive = $foilType->langActive;
- $decodeParams = array();
- $decodeParams['project'] = $product->project;
- if (!empty($device)) {
- $decodeParams['device'] = $device;
- $decodeParams['deviceType'] = $device->deviceType;
- }
- $decodeParams['foilType'] = $foilType;
- $decodeParams['bulletPoints'] = $foilType->bulletPoints;
- $decodeParams['foilTypeUnity'] = $foilTypeUnity;
- $decodeParams['size'] = $standardSize;
- $decodeParams['sizes'] = $sizes;
- $foilTypeTitles = $foilType->$titleValue;
- $foilTypeShortTitles = $foilType->$shortTitleValue;
- $metaSave = array();
- $languages = Language::model()->findAll('active=1');
- if (!empty($languages)) {
- foreach($languages as $lang) {
- $product->title[$lang->isoCode] = Helper::decodeModuleValues($foilTypeTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->title[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error = 'Product texts error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in title for language: ' . $lang->isoCode;
- $error->save(false);
- } else {
- $metaSave[] = 'title';
- }
- $product->shortTitle[$lang->isoCode] = Helper::decodeModuleValues($foilTypeShortTitles[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->shortTitle[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error = 'Product texts error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in shortTitle for language: ' . $lang->isoCode;
- $error->save(false);
- } else {
- $metaSave[] = 'shortTitle';
- }
- $product->description[$lang->isoCode] = Helper::decodeModuleValues($foilType->productDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->description[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error = 'Product texts error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in description for language: ' . $lang->isoCode;
- $error->save(false);
- } else {
- $metaSave[] = 'description';
- }
- $product->shortDescription[$lang->isoCode] = Helper::decodeModuleValues($foilType->productShortDescriptionFormula[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->shortDescription[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error = 'Product texts error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in shortDescription for language: ' . $lang->isoCode;
- $error->save(false);
- } else {
- $metaSave[] = 'shortDescription';
- }
- $product->deliveryScope[$lang->isoCode] = Helper::decodeModuleValues($foilType->deliveryScope[$lang->isoCode], $decodeParams, $lang->isoCode);
- if ($product->deliveryScope[$lang->isoCode] === false) {
- if (empty($existPProduct))
- $pProduct->delete();
- $error = new ErrorLog();
- $error = 'Product texts error';
- $error->errorLogType_id = 4;
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> has error in deliveryScope for language: ' . $lang->isoCode;
- $error->save(false);
- } else {
- $metaSave[] = 'deliveryScope';
- }
- }
- }
- if (empty($product->editOwnerUser_id))
- $product->lastUpdate = date('Y-m-d H:i:s');
- $product->availableFromDate = $standardSize->saleStartDate;
- if (!empty($standardSize->saleEndDate))
- $product->availableToDate = $standardSize->saleEndDate;
- if (strtotime($product->availableFromDate) > time())
- $product->available = 0;
- else
- $product->available = 1;
- $product->originCountry_id = $foilType->productCountry_id;
- $product->brand_id = $foilType->brand_id;
- $product->productType_id = 1;
- $product->productLine_id = $foilType->productLine_id;
- if ($pProduct->validate() == false) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Physical product has errors';
- $pError = var_export($pProduct->errors, true);
- $pValues = var_export($pProduct->attributes, true);
- $error->text = 'Physical product has errors. Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a><br/>' . $pError . ' values: ' . $pValues;
- $error->save(false);
- return false;
- }
- if ($product->validate() == false) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Product has errors';
- $pError = var_export($product->errors, true);
- $pValues = var_export($product->attributes, true);
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a><br/>error: ' . $pError . ' values: ' . $pValues;
- $error->save(false);
- return false;
- }
- if (empty($product->editOwnerUser_id)) {
- $product->save(false);
- $pProduct->save(false);
- if (!empty($metaSave))
- Helper::saveMultiligualParameter($product, $metaSave);
- } else {
- // Manual physical product attributes changes
- foreach($pProduct->attributes as $key=>$val) {
- if ($_pProduct[$key] != $pProduct->$key) {
- $change = new ProductManualChanges();
- $change->field = 'PhysicalProduct_' . $key;
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = $_pProduct[$key];
- $change->newValue = $pProduct->$key;
- $change->save(false);
- }
- }
- // Manual product attributes changes
- foreach($product->attributes as $key=>$val) {
- if ($_product[$key] != $product->$key) {
- $change = new ProductManualChanges();
- $change->field = 'Product_' . $key;
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = $_product[$key];
- $change->newValue = $product->$key;
- $change->save(false);
- }
- }
- if (json_encode($product->langActive) != json_encode($_product['langActive'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_langActive';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['langActive']);
- $change->newValue = json_encode($product['langActive']);
- $change->save(false);
- }
- if (json_encode($product->title) != json_encode($_product['title'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_title';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['title']);
- $change->newValue = json_encode($product['title']);
- $change->save(false);
- }
- if (json_encode($product->shortTitle) != json_encode($_product['shortTitle'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_shortTitle';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['shortTitle']);
- $change->newValue = json_encode($product['shortTitle']);
- $change->save(false);
- }
- if (json_encode($product->description) != json_encode($_product['description'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_description';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['description']);
- $change->newValue = json_encode($product['description']);
- $change->save(false);
- }
- if (json_encode($product->shortDescription) != json_encode($_product['shortDescription'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_shortDescription';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['shortDescription']);
- $change->newValue = json_encode($product['shortDescription']);
- $change->save(false);
- }
- if (json_encode($product->deliveryScope) != json_encode($_product['deliveryScope'])) {
- $change = new ProductManualChanges();
- $change->field = 'Product_deliveryScope';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($_product['deliveryScope']);
- $change->newValue = json_encode($product['deliveryScope']);
- $change->save(false);
- }
- }
- // Create categories
- $_product['endCategory'] = $product->getEndCategory();
- if (empty($product->editOwnerUser_id)) {
- $categories = $product->generateCategories($foilType->categoryFormula, $decodeParams);
- } else {
- $categories = $product->generateCategories($foilType->categoryFormula, $decodeParams, true);
- if (!is_numeric($categories)) {
- $categories = false;
- } else {
- if ($_product['endCategory'] != $categories) {
- $change = new ProductManualChanges();
- $change->field = 'Product_endCategory';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = $_product['endCategory'];
- $change->newValue = $categories;
- $change->save(false);
- }
- }
- }
- if ($categories === false) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Categories have error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>has error in categories';
- $error->save(false);
- }
- // Create ERP Groups
- $_product['endERPGroup'] = $product->getEndGroup();
- if (empty($product->editOwnerUser_id)) {
- $erpGroups = $this->generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams);
- } else {
- $erpGroups = $this->generateERPGroups($product, $foilType->ERPGroupFormula, $decodeParams, true);
- if (!is_numeric($erpGroups)) {
- $erpGroups = false;
- } else {
- if ($_product['endERPGroup'] != $erpGroups) {
- $change = new ProductManualChanges();
- $change->field = 'Product_endERPGroup';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = $_product['endERPGroup'];
- $change->newValue = $erpGroups;
- $change->save(false);
- }
- }
- }
- if ($erpGroups === false) {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'ERP groups have error';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a>has error in ERP groups';
- $error->save(false);
- }
- // Connect keywords
- $keywords = $foilType->keywords;
- if (!empty($device)) {
- if (is_array($keywords))
- $keywords = array_merge($keywords, $device->keywords);
- else
- $keywords = $device->keywords;
- }
- if (!empty($keywords)) {
- $newKeywordIDs = array();
- $values = ' VALUES ';
- foreach($keywords as $key=>$word) {
- $values .= '(' . $product->id . ', ' . $word->id . ')';
- if ($key < count($keywords) - 1)
- $values .= ',';
- if ($word->manual == 0)
- $newKeywordIDs[] = $word->id;
- }
- if (empty($product->editOwnerUser_id)) {
- // Delete old ones and insert new one
- $sql = 'DELETE pk FROM product_has_keywords AS pk
- LEFT JOIN keywords AS k ON k.id=pk.keywords_id
- WHERE k.manual=0 AND pk.product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->query();
- $sql = 'INSERT INTO product_has_keywords ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $oldKeywordIDs = array();
- if (!empty($product->keywords)) {
- foreach($product->keywords as $word) {
- if ($word->manual == 0)
- $oldKeywordIDs[] = $word->id;
- }
- }
- $dif1 = array_diff($oldKeywordIDs, $newKeywordIDs);
- $dif2 = array_diff($newKeywordIDs, $oldKeywordIDs);
- if (!empty($dif1) || !empty($dif2)) {
- $change = new ProductManualChanges();
- $change->field = 'Product_keywords';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($oldKeywordIDs);
- $change->newValue = json_encode($newKeywordIDs);
- $change->save(false);
- }
- }
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Keywords are missing';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> keywords are empty';
- $error->save(false);
- }
- // Connect bulletpoints
- $bulletPoints = $foilType->bulletPoints;
- if (!empty($bulletPoints)) {
- $newBulletPointsIDs = array();
- $values = ' VALUES ';
- foreach($bulletPoints as $key=>$point) {
- $values .= '(' . $product->id . ', ' . $point->id . ')';
- if ($key < count($bulletPoints) - 1)
- $values .= ',';
- if ($point->manual == 0)
- $newBulletPointsIDs[] = $point->id;
- }
- if (empty($product->editOwnerUser_id)) {
- // Delete old ones and insert new one
- $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
- LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
- WHERE b.manual=0 AND pb.product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->query();
- $sql = 'INSERT INTO product_has_bulletPoints ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $oldBulletPointsIDs = array();
- if (!empty($product->bulletPoints)) {
- foreach($product->bulletPoints as $point) {
- if ($point->manual == 0)
- $oldBulletPointsIDs[] = $point->id;
- }
- }
- $dif1 = array_diff($oldBulletPointsIDs, $newBulletPointsIDs);
- $dif2 = array_diff($newBulletPointsIDs, $oldBulletPointsIDs);
- if (!empty($dif1) || !empty($dif2)) {
- $change = new ProductManualChanges();
- $change->field = 'Product_bulletpoints';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($oldBulletPointsIDs);
- $change->newValue = json_encode($newBulletPointsIDs);
- $change->save(false);
- }
- }
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = 'Bulletpoints missing';
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> bulletpoints are empty';
- $error->save(false);
- }
- // Connect product features
- $productFeatureValues = $foilType->productFeatureValues;
- if (!empty($productFeatureValues)) {
- $values = ' VALUES ';
- $newFeatureValues = array();
- foreach($productFeatureValues as $value) {
- $values .= '(' . $product->id . ', ' . $value->id . ', 0)';
- if ($value != end($productFeatureValues))
- $values .= ',';
- $newFeatureValues[] = $value->id;
- }
- if (empty($product->editOwnerUser_id)) {
- // Delete old ones and insert new one
- $sql = 'DELETE FROM product_has_productFeatureValue
- WHERE product_id=' . $model->id . ' AND manual=0';
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_productFeatureValue ' . $values;
- Yii::app()->db->createCommand($sql)->query();
- } else {
- $oldFeatureValues = array();
- if (!empty($product->productFeatureValues)) {
- foreach($product->productFeatureValues as $value) {
- $sql = 'SELECT manual
- FROM product_has_productFeatureValue
- WHERE product_id=' . $product->getPrimaryKey() . '
- AND productFeatureValue_id=' . $value->getPrimaryKey();
- $manual = Yii::app()->db->createCommand($sql)->queryScalar();
- if ($manual == 0)
- $oldFeatureValues[] = $value->id;
- }
- }
- $dif1 = array_diff($oldFeatureValues, $newFeatureValues);
- $dif2 = array_diff($newFeatureValues, $oldFeatureValues);
- if (!empty($dif1) || !empty($dif2)) {
- $change = new ProductManualChanges();
- $change->field = 'Product_featureValues';
- $change->product_id = $product->getPrimaryKey();
- $change->user_id = $product->editOwnerUser_id;
- $eChange = ProductManualChanges::model()->find('field="' . $change->field . '" AND product_id="' . $product->getPrimaryKey() . '" AND user_id="' . $product->editOwnerUser_id . '"');
- if (!empty($eChange))
- $change = $eChange;
- $change->oldValue = json_encode($oldFeatureValues);
- $change->newValue = json_encode($newFeatureValues);
- $change->save(false);
- }
- }
- } else {
- $error = new ErrorLog();
- $error->errorLogType_id = 4;
- $error->subject = "Product features are missing";
- $error->text = 'Product: <a target="_blank" href="/project/product/update?id=' . $product->getPrimaryKey() . '">' . $product->getPrimaryKey() . '</a> features are empty';
- $error->save(false);
- }
- // Get all product modules
- $pModulesIDs = array(
- $package->module_id,
- $foilTypeUnity->module_id
- );
- foreach($sizes as $size)
- $pModulesIDs[] = $size->module_id;
- if ($device != null && $device->module_id)
- $pModulesIDs[] = $device->module_id;
- $pModulesIDs = array_filter($pModulesIDs);
- $sql = 'SELECT media_id as id
- FROM module_has_media AS mm
- LEFT JOIN media AS m ON mm.media_id=m.id
- WHERE m.mediaType_id IN (1,3)
- AND mm.module_id IN(' . implode(',', $pModulesIDs) . ')';
- $medias = Yii::app()->db->createCommand($sql)->queryAll();
- // Delete old ones and insert new one
- $sql = 'DELETE pm FROM product_has_media AS pm
- LEFT JOIN media AS m ON m.id=pm.media_id
- WHERE m.manual=0
- AND pm.product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->query();
- // Create medias for product
- if (!empty($medias)) {
- foreach($medias as $media) {
- $sql = 'INSERT INTO product_has_media (media_id, product_id) VALUES(' . $media['id'] . ',' . $product->getPrimaryKey() . ')';
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- if ($return)
- return $product;
- else
- return $product->id;
- }
- /**
- * Action to update a Foil Type
- */
- public function actionUpdate($id) {
- $model = $this->loadModel($id);
- $this->render('form', array(
- 'model' => $model
- ));
- }
- /**
- * Action to update a Product Master Data
- */
- public function actionUpdateMasterData() {
- if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
- $model = $this->loadModel($_POST['Product']['id']);
- $pProduct = $model->physicalProduct;
- $model->attributes = $_POST['Product'];
- if ($model->validate()) {
- if (isset($_POST['PhysicalProduct'])) {
- $pProduct->attributes = $_POST['PhysicalProduct'];
- if ($pProduct->validate()) {
- $pProduct->save(false);
- if (!empty($model->availableFromDate))
- $model->availableFromDate = date('Y-m-d H:i:s', strtotime($model->availableFromDate));
- if (!empty($model->availableToDate))
- $model->availableToDate = date('Y-m-d H:i:s', strtotime($model->availableToDate));
- // Set updates owner user
- if (empty($model->editOwnerUser_id))
- $model->editOwnerUser_id = Yii::app()->user->id;
- $model->save(false);
- if (isset($_POST['Product']['productERPGroups'])) {
- $erpGroups = $_POST['Product']['productERPGroups'];
- $erpGroups = array_filter($erpGroups);
- $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- foreach($erpGroups as $group) {
- $endGroup = 0;
- if ($group == end($erpGroups))
- $endGroup = 1;
- $sql = 'INSERT INTO product_has_productERPGroup VALUES (' . $group . ', ' . $model->primaryKey . ', 0 , ' . $endGroup . ')';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- if (isset($_POST['Product']['productCategories'])) {
- $categories = $_POST['Product']['productCategories'];
- $categories = array_filter($categories);
- $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- foreach($categories as $category) {
- $endCategory = 0;
- if ($category == end($categories))
- $endCategory = 1;
- $sql = 'INSERT INTO product_has_productCategory VALUES (' . $category . ', ' . $model->primaryKey . ', 0 , ' . $endCategory . ')';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- }
- }
- }
- Helper::ajaxReturn(array_merge($pProduct->errors, $model->errors), $model);
- }
- }
- /**
- * Action to update a Foil Type Texts
- */
- public function actionUpdateTexts() {
- if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
- $model = $this->loadModel($_POST['Product']['id']);
- $model->scenario = 'texts';
- // Set updates owner user
- if (empty($model->editOwnerUser_id)) {
- $model->editOwnerUser_id = Yii::app()->user->id;
- $model->save(false);
- }
- $model->title = $_POST['Product']['title'];
- $model->shortTitle = $_POST['Product']['shortTitle'];
- $model->description = $_POST['Product']['description'];
- $model->shortDescription = $_POST['Product']['shortDescription'];
- $model->deliveryScope = $_POST['Product']['deliveryScope'];
- $model->langActive = $_POST['Product']['langActive'];
- $bulletPoints = array();
- if (isset($_POST['BulletPoints']))
- $bulletPoints = $_POST['BulletPoints'];
- if ($model->validate()) {
- Helper::saveMultiligualParameter($model, array(
- 'langActive',
- 'title',
- 'shortTitle',
- 'description',
- 'shortDescription',
- 'deliveryScope'
- ));
- }
- if (!empty($model->errors))
- Helper::ajaxReturn($model->errors, $model);
- // Bulletpoints
- $newBulletPoints = array();
- $errors = array();
- if (!empty($bulletPoints)) {
- foreach($bulletPoints as $position=>$bullet) {
- if ($bullet['id']) {
- $newBullet = BulletPoints::model()->findByPk($bullet['id']);
- } else {
- $newBullet = new BulletPoints();
- }
- $newBullet->attributes = $bullet;
- if ($newBullet->isNewRecord)
- $newBullet->manual = 1;
- if ($newBullet->validate() == false)
- break;
- else
- $newBulletPoints[] = $newBullet;
- }
- if (empty($newBullet->errors)) {
- $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
- LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
- WHERE b.manual=1 AND pb.product_id=' . $model->id;
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_bulletPoints VALUES ';
- $i = 0;
- foreach($newBulletPoints as $bullet) {
- $i++;
- $bullet->save();
- $sql .= '(' . $model->getPrimaryKey() . ',' . $bullet->getPrimaryKey() . ')';
- if ($i < count($newBulletPoints))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- } else {
- foreach($newBullet->errors as $key=>$err) {
- $errors[$position . '_' . $key] = '[Bulletpoints ' . $position . '] ' . $err[0];
- }
- }
- } else {
- $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
- LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
- WHERE b.manual=1 AND pb.product_id=' . $model->id;
- Yii::app()->db->createCommand($sql)->execute();
- }
- Helper::ajaxReturn($errors, new BulletPoints());
- }
- }
- /**
- * Action to update product keywords
- */
- public function actionUpdateKeywords() {
- if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
- $model = $this->loadModel($_POST['Product']['id']);
- $newKeywords = array();
- $errors = array();
- if (isset($_POST['Keywords']) && !empty($_POST['Keywords'])) {
- $keywords = $_POST['Keywords'];
- foreach($keywords as $position=>$keyword) {
- if ($keyword['id'])
- $newKeyword = Keywords::model()->findByPk($keyword['id']);
- else
- $newKeyword = new Keywords();
- $newKeyword->attributes = $keyword;
- if ($newKeyword->validate() == false)
- break;
- else
- $newKeywords[] = $newKeyword;
- }
- if (empty($newKeyword->errors)) {
- $sql = 'DELETE pk FROM product_has_keywords AS pk
- LEFT JOIN keywords AS k ON k.id=pk.keywords_id
- WHERE k.manual=1 AND pk.product_id=' . $model->id;
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_keywords VALUES ';
- $i = 0;
- foreach($newKeywords as $keyword) {
- $i++;
- $keyword->sort *= 10;
- $keyword->save();
- $sql .= '(' . $model->primaryKey . ',' . $keyword->primaryKey . ')';
- if ($i < count($newKeywords))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- } else {
- foreach($newKeyword->errors as $key=>$err) {
- $errors[$position . '_' . $key] = '[Keywords ' . $position . '] ' . $err[0];
- }
- }
- } else {
- $sql = 'DELETE pk FROM product_has_keywords AS pk
- LEFT JOIN keywords AS k ON k.id=pk.keywords_id
- WHERE k.manual=1 AND pk.product_id=' . $model->id;
- Yii::app()->db->createCommand($sql)->execute();
- }
- if (!isset($newKeyword))
- $newKeyword = new Keywords();
- Helper::ajaxReturn($errors, $newKeyword);
- }
- }
- /**
- * Action to update a Foil Type Product Features
- */
- public function actionUpdateFeatures() {
- if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
- $model = $this->loadModel($_POST['Product']['id']);
- $newFeatures = array();
- $errors = array();
- if (isset($_POST['ProductFeatureValue']) && !empty($_POST['ProductFeatureValue'])) {
- $features = $_POST['ProductFeatureValue'];
- foreach($features as $position=>$feature) {
- $newFeature = new ProductFeatureValue();
- $newFeature->attributes = $feature;
- $newFeature->value = $feature['value'];
- $featureType = ProductFeature::model()->findByPk($newFeature->productFeature_id);
- if (!empty($featureType)) {
- // Translate value to all languages if not text and not
- // selectbox
- if ($featureType->inputType != 0 && $featureType->inputType != 3) {
- $sql = 'SELECT isoCode FROM language WHERE active=1';
- $langs = Yii::app()->db->createCommand($sql)->queryAll();
- $tempValue = $newFeature->value;
- $newFeature->value = array();
- foreach($langs as $lang)
- $newFeature->value[$lang['isoCode']] = $tempValue;
- // Check if value exists already
- $sql = 'SELECT pfv.id
- FROM productFeatureValue AS pfv
- LEFT JOIN productFeatureValue_translation AS pfvt ON pfv.id=pfvt.productFeatureValue_id
- WHERE pfv.productFeature_id=' . $newFeature->productFeature_id . '
- AND pfvt.value="' . $feature['value'] . '"
- GROUP BY pfvt.productFeatureValue_id';
- $existFeature = Yii::app()->db->createCommand($sql)->queryRow();
- if (!empty($existFeature)) {
- $newFeature = ProductFeatureValue::model()->findByPk($existFeature['id']);
- }
- }
- // Check if value has changed
- if (isset($feature['id'])) {
- $oldFeature = ProductFeatureValue::model()->findByPk($feature['id']);
- if ($oldFeature->value == $newFeature->value)
- $newFeature = $oldFeature;
- }
- // Find feature value if dropdown list
- if ($featureType->inputType == 3) {
- $newFeature = ProductFeatureValue::model()->findByPk($feature['value']);
- if (empty($newFeature)) {
- $newFeature = new ProductFeatureValue();
- $newFeature->addError('id', Translate::t('errors', Translate::t('yii', '{attribute} cannot be blank.', array(
- '{attribute}' => $newFeature->getAttributeLabel('value')
- ))));
- break;
- }
- }
- if ($newFeature->validate() == false)
- break;
- else
- $newFeatures[] = $newFeature;
- } else {
- $newFeature->addError('id', Translate::t('errors', 'Object doesnt exist'));
- }
- }
- if (empty($newFeature->errors)) {
- $sql = 'DELETE FROM product_has_productFeatureValue
- WHERE product_id=' . $model->id . ' AND manual=1';
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_productFeatureValue VALUES ';
- $i = 0;
- foreach($newFeatures as $feature) {
- $i++;
- $feature->save();
- Helper::saveMultiligualParameter($feature, array(
- 'value'
- ));
- $sql .= '(' . $model->getPrimaryKey() . ',' . $feature->getPrimaryKey() . ', 1)';
- if ($i < count($newFeatures))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- } else {
- foreach($newFeature->errors as $key=>$err) {
- $errors['_' . $position . '_productFeature_id'] = '[' . Translate::t('project', 'Product feature') . ' ' . $position . '] ' . $err[0];
- }
- }
- } else {
- $sql = 'DELETE FROM product_has_productFeatureValue
- WHERE product_id=' . $model->id . ' AND manual=1';
- Yii::app()->db->createCommand($sql)->execute();
- }
- Helper::ajaxReturn($errors, new BulletPoints());
- }
- }
- /**
- * Action to update a product notes
- */
- public function actionUpdateProductNotes() {
- if (Yii::app()->request->isAjaxRequest && isset($_POST['Product']['id'])) {
- $model = $this->loadModel($_POST['Product']['id']);
- $productNotes = $_POST['ProductNote'];
- $newNotes = array();
- $errors = array();
- if (!empty($productNotes)) {
- foreach($productNotes as $position=>$note) {
- if (isset($note['id']) && $note['id'] != false)
- $newNote = ProductNote::model()->findByPk($note['id']);
- else
- $newNote = new ProductNote();
- $newNote->attributes = $note;
- $newNote->product_id = $model->primaryKey;
- if ($newNote->validate() == false)
- break;
- else
- $newNotes[] = $newNote;
- }
- if (empty($newNote->errors)) {
- $sql = 'DELETE FROM productNote WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO productNote VALUES ';
- $i = 0;
- foreach($newNotes as $note) {
- $i++;
- $sql .= '(NULL,"' . $note->isoCode . '",' . $model->primaryKey . ',"' . addslashes($note->note) . '",' . $note->productNoteType_id . ')';
- if ($i < count($newNotes))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- } else {
- foreach($newNote->errors as $key=>$err) {
- $errors['ProductNote_' . $position . '_' . $key] = '[ProductNote ' . $position . '] ' . $err[0];
- }
- }
- } else {
- $sql = 'DELETE FROM productNote WHERE product_id=' . $model->primaryKey;
- Yii::app()->db->createCommand($sql)->execute();
- }
- if (!isset($newNote) || !$newNote)
- $newNote = new ProductNote();
- Helper::ajaxReturn($errors, $newNote);
- }
- }
- /**
- * Returns the data model based on the primary key given in the GET variable.
- * If the data model is not found, an HTTP exception will be raised.
- *
- * @param integer $id the ID of the model to be loaded
- * @return ProductERPGroup the loaded model
- * @throws CHttpException
- */
- public function loadModel($id) {
- $model = Product::model()->findByPk($id);
- if ($model === null)
- throw new CHttpException(404, 'The requested page does not exist.');
- return $model;
- }
- /**
- *
- * @param product $model product model to block for
- * @param array $sizes ids of sizes to block for
- */
- public function blockStock($model = null, $sizes = null, $block = 1) {
- if ($model) {
- $modules = $model->modules;
- $sizes = array();
- foreach($modules as $module) {
- if ($module->moduleGroup_id == 2)
- $sizes[] = $module->id;
- }
- }
- if (!empty($sizes)) {
- $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';
- $physicalProducts = Yii::app()->db->createCommand($sql)->queryAll();
- if (!empty($physicalProducts)) {
- foreach($physicalProducts as $product) {
- $sql = 'UPDATE stockPoint SET locked=' . $block . ' WHERE physicalProduct_id=' . $product['id'] . ';';
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- }
- }
- /**
- * Action to update a Foil Type
- */
- public function actionManualChanges() {
- if (isset($_POST['ProductManualChanges'])) {
- $changes = $_POST['ProductManualChanges']['id'];
- if (is_array($changes)) {
- $changesIDs = array();
- foreach($changes as $id=>$toChange) {
- $change = ProductManualChanges::model()->findByPk($id);
- if (is_object($change)) {
- $product = $change->product;
- $pProduct = $product->physicalProduct;
- $field = substr($change->field, strpos($change->field, '_') + 1);
- if ($toChange == 0) {
- $change->delete();
- } else {
- if (strpos($change->field, 'Product_') == 0) {
- if ($field == 'endCategory') {
- $pCategory = ProductCategory::model()->findByPk($change->newValue);
- $categories = $pCategory->getPath();
- if (!empty($categories)) {
- $sql = 'DELETE FROM product_has_productCategory WHERE product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->query();
- $addedCategories = array();
- foreach($categories as $cat) {
- $endCategory = 0;
- if ($cat->id == $pCategory->id)
- $endCategory = 1;
- $addedCategories[] = '(' . $cat->id . ',' . $product->getPrimaryKey() . ',0,' . $endCategory . ')';
- }
- if (is_array($addedCategories)) {
- $sql = 'INSERT INTO product_has_productCategory VALUES ' . implode(',', $addedCategories);
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- } elseif ($field == 'endERPGroup') {
- $erpGroup = ProductERPGroup::model()->findByPk($change->newValue);
- $groups = $erpGroup->getPath();
- if (!empty($groups)) {
- $sql = 'DELETE FROM product_has_productERPGroup WHERE product_id=' . $product->getPrimaryKey();
- Yii::app()->db->createCommand($sql)->query();
- $addedGroups = array();
- foreach($groups as $group) {
- $endGroup = 0;
- if ($group->id == $erpGroup->id)
- $endGroup = 1;
- $addedGroups[] = '(' . $group->id . ',' . $product->getPrimaryKey() . ',0,' . $endGroup . ')';
- }
- if (is_array($addedGroups)) {
- $sql = 'INSERT INTO product_has_productERPGroup VALUES ' . implode(',', $addedGroups);
- Yii::app()->db->createCommand($sql)->query();
- }
- }
- } elseif ($field == 'keywords') {
- $newKeywords = json_decode($change->newValue, true);
- if (is_array($newKeywords)) {
- $sql = 'DELETE pk FROM product_has_keywords AS pk
- LEFT JOIN keywords AS k ON k.id=pk.keywords_id
- WHERE k.manual=0 AND pk.product_id=' . $change->product_id;
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_keywords VALUES ';
- $i = 0;
- foreach($newKeywords as $keywordID) {
- $i++;
- $sql .= '(' . $change->product_id . ',' . $keywordID . ')';
- if ($i < count($newKeywords))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- }
- } elseif ($field == 'bulletpoints') {
- $newBulletPoints = json_decode($change->newValue, true);
- if (is_array($newBulletPoints)) {
- $sql = 'DELETE pb FROM product_has_bulletPoints AS pb
- LEFT JOIN bulletPoints AS b ON b.id=pb.bulletPoints_id
- WHERE b.manual=0 AND pb.product_id=' . $change->product_id;
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_bulletPoints VALUES ';
- $i = 0;
- foreach($newBulletPoints as $bulletID) {
- $i++;
- $sql .= '(' . $change->product_id . ',' . $bulletID . ')';
- if ($i < count($newBulletPoints))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- }
- } elseif ($field == 'featureValues') {
- $newFeatureValues = json_decode($change->newValue, true);
- if (is_array($newFeatureValues)) {
- $sql = 'DELETE FROM product_has_productFeatureValue
- WHERE product_id=' . $change->product_id . ' AND manual=0';
- Yii::app()->db->createCommand($sql)->execute();
- $sql = 'INSERT INTO product_has_productFeatureValue VALUES ';
- $i = 0;
- foreach($newFeatureValues as $featureID) {
- $i++;
- $sql .= '(' . $change->product_id . ',' . $featureID . ', 0)';
- if ($i < count($newFeatureValues))
- $sql .= ',';
- }
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- } elseif (strpos($change->field, 'PhysicalProduct_') == 0) {
- $pProduct->$field = $change->newValue;
- }
- }
- if ($product->validate() && $pProduct->validate()) {
- $product->lastUpdate = date('Y-m-d H:i:s');
- $product->save(false);
- Helper::saveMultiligualParameter($product, array(
- 'langActive',
- 'title',
- 'shortTitle',
- 'description',
- 'shortDescription',
- 'deliveryScope'
- ));
- $pProduct->save();
- $changesIDs[] = $change->getPrimaryKey();
- }
- }
- }
- if (!empty($changesIDs)) {
- $sql = 'DELETE FROM productManualChanges WHERE id IN (' . implode(',', $changesIDs) . ')';
- Yii::app()->db->createCommand($sql)->execute();
- }
- }
- }
- $productChanges = array();
- $sql = 'SELECT product_id AS id
- FROM productManualChanges
- WHERE user_id=' . Yii::app()->user->id . '
- GROUP BY product_id';
- $products = Yii::app()->db->createCommand($sql)->queryAll();
- if (!empty($products)) {
- foreach($products as $prod)
- $productChanges[$prod['id']] = ProductManualChanges::model()->findAll('product_id="' . $prod['id'] . '" AND user_id="' . Yii::app()->user->id . '"');
- }
- $this->render('manualChanges', array(
- 'productChanges' => $productChanges
- ));
- }
- /**
- * Updates the search words, given by the products titles, for the given
- * product(s).
- * Creates searchwords if they arent already in DB.
- *
- * @param int|array(int) $productId
- * @return boolean true if update has completed, false if no valid parameter
- * was given.
- */
- public static function updateProductSearchWord($productId) {
- $productIdArray;
- // create array with all product ids for iteration
- if (!is_array($productId) && is_numeric($productId)) {
- $productIdArray = array(
- $productId
- );
- } else if (is_array($productId))
- $productIdArray = $productId;
- else
- return false;
- // no valid parameter
- // holds each distinct word found for inserts
- $distinctWordsInsert = array();
- // holds product ids with word mapping for inserts
- $productWordsMapping = array();
- // foreach product given
- foreach($productIdArray as $prodId) {
- $productTranslations = ProductTranslation::model()->findAll('product_id=' . $prodId);
- if (empty($productTranslations)) {
- echo '<p> No product translation for productId: ' . $prodId . ' was found! Continuing...</p>';
- continue;
- }
- // foreach translation of the product
- foreach($productTranslations as $transl) {
- $translString = $transl->title;
- $prodId = $transl->product_id;
- // echo '<p> '. $translString .' </p>';
- $titleArray = explode(' ', $translString);
- // foreach word in the translation
- foreach($titleArray as $titleWord) {
- $replaceArray = array(
- '//',
- '(',
- ')',
- "™",
- '"',
- "'"
- );
- $titleWord = str_replace($replaceArray, '', $titleWord);
- $titleWord = preg_replace("/(™|®|©|™|®|©|™|®|©)/", "", $titleWord);
- $titleWord = trim($titleWord);
- if ($titleWord === '' || $titleWord === null || $titleWord === false) {
- continue;
- }
- $titleWord = strtolower($titleWord);
- $searchWord = SearchWord::model()->find('searchWord="' . $titleWord . '"');
- if (!$searchWord) {
- if (!in_array($titleWord, $distinctWordsInsert, true))
- $distinctWordsInsert[] = $titleWord;
- } elseif (ProductHasSearchWords::model()->find('product_id=' . $prodId . ' AND searchWord_id=' . $searchWord->getPrimaryKey()))
- continue;
- if (!isset($productWordsMapping[$prodId]))
- $productWordsMapping[$prodId] = array();
- if (!in_array($titleWord, $productWordsMapping[$prodId]))
- $productWordsMapping[$prodId][] = $titleWord;
- }
- }
- }
- // insert searchwords which are new
- if (!empty($distinctWordsInsert)) {
- $wordChunks = array_chunk($distinctWordsInsert, 1000);
- foreach($wordChunks as $wordChunk) {
- $size = count($wordChunk);
- $insertWordsSQL = 'INSERT INTO searchWord (searchWord) VALUES';
- $i = 1;
- foreach($wordChunk as $w) {
- $insertWordsSQL .= ' ("' . $w . '")';
- if ($i != $size)
- $insertWordsSQL .= ' , ';
- $i++;
- }
- $insertWordsSQL .= ' ;';
- Yii::app()->db->createCommand($insertWordsSQL)->execute();
- }
- }
- $productWordsMappingChunk = array_chunk($productWordsMapping, 100, true);
- $mappingCount = 1;
- // insert matching dor product id and search words
- foreach($productWordsMappingChunk as $prodCh) {
- $query = false;
- // FIXME: duplicated and when update remove old searchWords and
- // insert new ones
- $insertMappingSQL = "INSERT IGNORE INTO product_has_searchWords (product_id, searchWord_id) VALUES ";
- $sizeChunk = count($prodCh);
- $currChunk = 1;
- foreach($prodCh as $productId=>$words) {
- $j = 1;
- $size = count($words);
- foreach($words as $word) {
- $insertMappingSQL .= ' (' . $productId . ', (Select id from searchWord where searchWord="' . $word . '")) ';
- if ($j != $size)
- $insertMappingSQL .= ', ';
- $j++;
- $query = true;
- }
- // only , if not the last insert before execution
- if ($currChunk != $sizeChunk)
- $insertMappingSQL .= ', ';
- $currChunk++;
- }
- if ($query) {
- $insertMappingSQL .= ';';
- Yii::app()->db->createCommand($insertMappingSQL)->execute();
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement