コード例 #1
0
 private function _getNewPrice($updateMagento)
 {
     $result = null;
     $sku = $this->sku;
     $updateMagento = $updateMagento === true ? true : false;
     $product = Product::getBySku($sku);
     if (!$product instanceof Product) {
         throw new Exception('Invalid sku passed in, "' . $sku . '" given');
     }
     $min = PriceMatchMin::getBySku($sku);
     $rule = ProductPriceMatchRule::getByProduct($product);
     $prices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
     if (count($prices) === 0) {
         $newPrice = ProductPrice::create($product, ProductPriceType::get(ProductPriceType::ID_RRP), 0);
         $prices = array($newPrice);
     }
     // 		if(($magePrice = $this->_getMagentoProductPrice($sku)) !== null)
     // 			$prices[0]->setPrice($magePrice)->save();
     $myPrice = $prices[0]->getPrice();
     if (!$min instanceof PriceMatchMin) {
         $min = PriceMatchMin::create($this->sku);
     }
     if ($rule instanceof ProductPriceMatchRule) {
         $company = $rule->getCompany();
         $price_from = $rule->getPrice_from();
         $price_to = $rule->getPrice_to();
         $offset = $rule->getOffset();
         $where = array(1);
         $params = array();
         $where[] = "minId = ? ";
         $params[] = $min->getId();
         $from_date = UDate::now('Australia/Melbourne')->setTime(0, 0, 0)->setTimeZone('UTC');
         $to_date = UDate::now('Australia/Melbourne')->setTime(23, 59, 59)->setTimeZone('UTC');
         $where[] = "created >= ? ";
         $params[] = $from_date;
         $where[] = "created <= ? ";
         $params[] = $to_date;
         $companies = $company->getAllAlias();
         $companyIds = array_map(create_function('$a', 'return $a->getId();'), $companies);
         $where[] = 'companyId IN (' . implode(", ", array_fill(0, count($companyIds), "?")) . ')';
         $params = array_merge($params, $companyIds);
         //calculate target compatitor price
         $records = PriceMatchRecord::getAllByCriteria(implode(' AND ', $where), $params, true, null, DaoQuery::DEFAUTL_PAGE_SIZE, array('price' => 'asc'));
         $base_price = null;
         foreach ($records as $record) {
             if ($base_price === null || doubleval($record->getPrice()) !== doubleval(0) && doubleval($record->getPrice()) < doubleval($base_price)) {
                 $base_price = doubleval($record->getPrice());
             }
         }
         if ($base_price !== null) {
             if ($price_from !== null) {
                 if (strpos($price_from, '%') !== false) {
                     $price_from = $base_price - $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_from)));
                 } else {
                     $price_from = $base_price - doubleval($price_from);
                 }
                 if (doubleval($price_from) <= doubleval(0)) {
                     $price_from = doubleval(0);
                 }
             }
             if ($price_to !== null) {
                 if (strpos($price_to, '%') !== false) {
                     $price_to = $base_price + $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_to)));
                 } else {
                     $price_to = $base_price + doubleval($price_to);
                 }
             }
             // check if in range
             if (($price_from === null || $myPrice >= $price_from) && ($price_to === null || $myPrice <= $price_to)) {
                 $result = $base_price;
                 // apply offset
                 if ($offset !== null) {
                     if (strpos($offset, '%') !== false) {
                         $result = $result + $result * doubleval(0.01 * doubleval(str_replace('%', '', $offset)));
                     } else {
                         $result = $result + doubleval($offset);
                     }
                 }
                 // set product price
                 if (isset($prices[0]) && $prices[0] instanceof ProductPrice) {
                     $newmatchprice = doubleval($result);
                     if ($newmatchprice > 0) {
                         $oldPrice = $prices[0]->getPrice();
                         echo 'update price from old price : ' . $oldPrice . ' to new price :' . $newmatchprice . "\n";
                         $prices[0]->setPrice(doubleval($result))->save()->addLog('PriceMatch change price from $' . $oldPrice . 'to new price $' . $result, Log::TYPE_SYSTEM);
                         // 						if($updateMagento === true)
                         // 							$this->updateMagentoPrice(doubleval($result));
                     } else {
                         echo 'not update price because new match price is 0 ( ' . $newmatchprice . ' )' . "\n";
                     }
                 }
             }
         } else {
             if ($this->debug === true) {
                 echo "cannot find price for PriceMatchCompany " . $company->getCompanyName() . ', ' . $product->getSku() . '(id=' . $product->getId() . ', min(id=' . $min->getId() . '), records found:' . count($records) . "\n";
             }
         }
         if ($this->debug === true) {
             echo 'new price= ' . ($result === null ? 'N/A' : $result) . ', my price= ' . (isset($myPrice) ? $myPrice : 'N/A') . ', ' . $company->getCompanyName() . ' price= ' . $base_price . ', matching range=[' . $price_from . ',' . $price_to . '], offset=' . ($offset === null ? 'null' : $offset) . "\n";
         }
     } elseif ($this->debug === true) {
         echo ($min instanceof PriceMatchMin ? '' : 'Cannot find result on StaticIce for all known PriceMatchCompanies') . ($rule instanceof ProductPriceMatchRule ? '' : 'cannot find ProductPriceMatchRule for product ' . $product->getSku() . '(id=' . $product->getId() . ')') . "\n";
     }
     return $result;
 }
コード例 #2
0
 public function newRule($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $results = $param->CallbackParameter;
         if (!isset($param->CallbackParameter->productId) || !($product = Product::get(trim($param->CallbackParameter->productId))) instanceof Product) {
             throw new Exception('Invalid Product Id passed in, "' . $param->CallbackParameter->productId . '" given');
         }
         if (!isset($param->CallbackParameter->rule)) {
             throw new Exception('Invalid PriceMatchRule passed in, "' . $param->CallbackParameter->rule . '" given');
         }
         if (!isset($param->CallbackParameter->rule->active)) {
             throw new Exception('Must pass in active (bool) for PriceMatchRule, "' . $param->CallbackParameter->rule->active . '" given');
         } else {
             $active = $param->CallbackParameter->rule->active;
         }
         if ($active === true && (!isset($param->CallbackParameter->rule->company_id) || !($company = PriceMatchCompany::get(trim($param->CallbackParameter->rule->company_id))) instanceof PriceMatchCompany)) {
             throw new Exception('Invalid PriceMatchCompany Id passed in, "' . $param->CallbackParameter->rule->company_id . '" given');
         }
         if ($active === false && ($rule = ProductPriceMatchRule::getByProduct($product)) instanceof ProductPriceMatchRule) {
             $rule->setActive($active)->save();
             $results = $rule->getJson();
         } elseif ($active === true) {
             $rule = ProductPriceMatchRule::create($product, $company, trim($param->CallbackParameter->rule->price_from), trim($param->CallbackParameter->rule->price_to), trim($param->CallbackParameter->rule->offset));
             //file_put_contents('/tmp/datafeed/web.log', __FILE__ .':' . __FUNCTION__ . ':' . __LINE__ . ': run' . date('Y-m-d\TH:i:sP') . PHP_EOL, FILE_APPEND | LOCK_EX);
             PriceMatchConnector::run($product->getSku(), true);
             //file_put_contents('/tmp/datafeed/web.log', __FILE__ .':' . __FUNCTION__ . ':' . __LINE__ . ': getMinRecord' . date('Y-m-d\TH:i:sP'). PHP_EOL, FILE_APPEND | LOCK_EX);
             PriceMatchConnector::getMinRecord($product->getSku(), true);
             //file_put_contents('/tmp/datafeed/web.log', __FILE__ .':' . __FUNCTION__ . ':' . __LINE__ . ': getNewPrice' . date('Y-m-d\TH:i:sP') . PHP_EOL, FILE_APPEND | LOCK_EX);
             PriceMatchConnector::getNewPrice($product->getSku(), true, true);
             //file_put_contents('/tmp/datafeed/web.log', __FILE__ .':' . __FUNCTION__ . ':' . __LINE__ . ': end' . date('Y-m-d\TH:i:sP'). PHP_EOL, FILE_APPEND | LOCK_EX);
             $results = $rule->getJson();
         }
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
コード例 #3
0
 /**
  * create/update product via datafeed.
  *
  * @param array $params
  *
  * @return array
  */
 private function _dataFeedImport($params)
 {
     try {
         Dao::beginTransaction();
         $this->_runner->log('dataFeedImport: ', __CLASS__ . '::' . __FUNCTION__);
         $sku = $this->_getPram($params, 'sku', null, true);
         $name = $this->_getPram($params, 'name', null, true);
         $shortDesc = $this->_getPram($params, 'short_description', $name);
         $fullDesc = $this->_getPram($params, 'description', '');
         $price = StringUtilsAbstract::getValueFromCurrency($this->_getPram($params, 'price', null, true));
         $supplierName = $this->_getPram($params, 'supplier', null, true);
         $supplierCode = $this->_getPram($params, 'supplier_code', null, true);
         $supplier = $this->_getEntityByName($supplierName, 'Supplier');
         if (!$supplier instanceof Supplier) {
             throw new Exception("invalid supplier:" . $supplierName);
         }
         $manufacturerId = $this->_getPram($params, 'manufacturer_id', null, true);
         $manufacturer = Manufacturer::get($manufacturerId);
         if (!$manufacturer instanceof Manufacturer) {
             throw new Exception("invalid Manufacturer:" . $manufacturerId);
         }
         $statusName = $this->_getPram($params, 'availability', null, true);
         $status = $this->_getEntityByName($statusName, 'ProductStatus');
         if (!$status instanceof ProductStatus) {
             throw new Exception("invalid ProductStatus:" . $statusName);
         }
         $assetAccNo = $this->_getPram($params, 'assetAccNo', null);
         $revenueAccNo = $this->_getPram($params, 'revenueAccNo', null);
         $costAccNo = $this->_getPram($params, 'costAccNo', null);
         $categoryIds = $this->_getPram($params, 'category_ids', array());
         $canSupplyQty = $this->_getPram($params, 'qty', 0);
         $weight = $this->_getPram($params, 'weight', 0);
         $images = $this->_getPram($params, 'images', array());
         $showOnWeb = $this->_getPram($params, 'showonweb', true);
         $attributesetId = $this->_getPram($params, 'attributesetId', null);
         $canUpdate = false;
         //if we have this product already, then skip
         if (!($product = Product::getBySku($sku)) instanceof Product) {
             $this->_runner->log('new SKU(' . $sku . ') for import, creating ...', '', APIService::TAB);
             $product = Product::create($sku, $name, '', null, null, false, $shortDesc, $fullDesc, $manufacturer, $assetAccNo, $revenueAccNo, $costAccNo, null, null, true, $weight, $attributesetId);
             $this->log_product("NEW", "=== new === sku={$sku}, name={$name}, shortDesc={$shortDesc}, fullDesc={$fullDesc}, category=" . implode(', ', $categoryIds), '', APIService::TAB);
             $canUpdate = true;
         } else {
             //$this->log_product("UPDATE", "=== update === sku=$sku, name=$name, shortDesc=$shortDesc, fullDesc=$fullDesc, category=" . implode(', ', $categoryIds),  '', APIService::TAB);
             //if there is no price matching rule for this product
             if (($rulesCount = intval(ProductPriceMatchRule::countByCriteria('active = 1 and productId = ?', array($product->getId())))) === 0) {
                 $this->_runner->log('Found SKU(' . $sku . '): ', '', APIService::TAB);
                 $fullAsset = Asset::getAsset($product->getFullDescAssetId());
                 $this->_runner->log('Finding asset for full description, assetId:' . ($fullAsset instanceof Asset ? $fullAsset->getAssetId() : ''), '', APIService::TAB . APIService::TAB);
                 $fullAssetContent = '';
                 if ($fullAsset instanceof Asset) {
                     $fullAssetContent = file_get_contents($fullAsset->getPath());
                     $this->_runner->log('Got full asset content before html_decode: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB);
                     $fullAssetContent = trim(str_replace('&nbsp;', '', $fullAssetContent));
                     $this->_runner->log('Got full asset content after html_code: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB);
                 }
                 if ($fullAssetContent === '') {
                     $this->_runner->log('GOT BLANK FULL DESD. Updating full description.', '', APIService::TAB . APIService::TAB . APIService::TAB);
                     if ($fullAsset instanceof Asset) {
                         Asset::removeAssets(array($fullAsset->getAssetId()));
                         $this->_runner->log('REMOVED old empty asset for full description', '', APIService::TAB . APIService::TAB . APIService::TAB);
                     }
                     $fullAsset = Asset::registerAsset('full_description_for_product.txt', $fullDesc, Asset::TYPE_PRODUCT_DEC);
                     $product->setFullDescAssetId($fullAsset->getAssetId())->save();
                     $this->_runner->log('Added a new full description with assetId: ' . $fullAsset->getAssetId(), '', APIService::TAB . APIService::TAB);
                     $canUpdate = true;
                     $this->log_product("UPDATE", "=== updating === sku={$sku} Found ", '', APIService::TAB);
                 } else {
                     $this->log_product("SKIP", "=== SKIP updating === sku={$sku} for full description not null", '', APIService::TAB);
                 }
             } else {
                 $this->_runner->log('SKIP updating. Found ProductPriceMatchRule count:' . $rulesCount, '', APIService::TAB);
                 $this->log_product("SKIP", "=== SKIP updating === sku={$sku} Found ProductPriceMatchRule count:{$rulesCount}", '', APIService::TAB);
             }
         }
         $json = $product->getJson();
         //only update categories and status when there is no pricematching rule or created new
         if ($canUpdate === true) {
             //short description, name, manufacturer
             $this->_runner->log('Updating the price to: ' . StringUtilsAbstract::getCurrency($price), '', APIService::TAB . APIService::TAB);
             $product->setShortDescription($shortDesc)->setName($name)->setManufacturer($manufacturer)->setWeight($weight)->setSellOnWeb($showOnWeb)->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price);
             //show on web
             if (is_array($categoryIds) && count($categoryIds) > 0) {
                 $this->_runner->log('Updating the categories: ' . implode(', ', $categoryIds), '', APIService::TAB . APIService::TAB);
                 foreach ($categoryIds as $categoryId) {
                     if (!($category = ProductCategory::get($categoryId)) instanceof ProductCategory) {
                         continue;
                     }
                     if (count($ids = explode(ProductCategory::POSITION_SEPARATOR, trim($category->getPosition()))) > 0) {
                         foreach (ProductCategory::getAllByCriteria('id in (' . implode(',', $ids) . ')') as $cate) {
                             $product->addCategory($cate);
                             $this->_runner->log('Updated Category ID: ' . $cate->getId(), '', APIService::TAB . APIService::TAB . APIService::TAB);
                         }
                     }
                 }
             }
             //updating the images
             if (is_array($images) && count($images) > 0) {
                 $this->_runner->log('Processing ' . count($images) . ' image(s) ...', '', APIService::TAB . APIService::TAB);
                 $exisitingImgsKeys = array();
                 $this->_runner->log('Checking exsiting images...', '', APIService::TAB . APIService::TAB . APIService::TAB);
                 $exisitingImgs = $product->getImages();
                 $this->_runner->log('Got ' . count($exisitingImgs) . ' exisiting image(s), keys: ', '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB);
                 foreach ($exisitingImgs as $image) {
                     if (($asset = Asset::getAsset($image->getImageAssetId())) instanceof Asset) {
                         $imgKey = md5($asset->read());
                         $exisitingImgsKeys[] = $imgKey;
                         $this->_runner->log($imgKey, '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB);
                     }
                 }
                 $this->_runner->log('Checking ' . count($images) . ' new image(s) ...', '', APIService::TAB . APIService::TAB);
                 foreach ($images as $image) {
                     //if haven't got any content at all
                     if (!isset($image['content'])) {
                         $this->_runner->log('No Content, SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB);
                         continue;
                     }
                     $newImageContent = base64_decode($image['content']);
                     $newImgKey = md5($newImageContent);
                     //if we've got the image already
                     if (in_array($newImgKey, $exisitingImgsKeys)) {
                         $this->_runner->log('Same Image Exists[' . $newImgKey . '], SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB);
                         continue;
                     }
                     $asset = Asset::registerAsset($image['name'], $newImageContent, Asset::TYPE_PRODUCT_IMG);
                     $this->_runner->log('Registered a new Asset [AssetID=' . $asset->getAssetId() . '].', '', APIService::TAB . APIService::TAB . APIService::TAB);
                     $product->addImage($asset);
                     $this->_runner->log('Added to product(SKU=' . $product->getSku() . ')', '', APIService::TAB . APIService::TAB . APIService::TAB);
                 }
             }
             $product->setStatus($status);
             $this->_runner->log('Updated Status to: ' . $status->getName(), '', APIService::TAB . APIService::TAB);
             $product->addSupplier($supplier, $supplierCode, $canSupplyQty);
             $this->_runner->log('Updated Supplier(ID' . $supplier->getId() . ', name=' . $supplier->getName() . ') with code: ' . $supplierCode . 'canSupplyQty=' . $canSupplyQty, '', APIService::TAB . APIService::TAB);
             $json = $product->save()->getJson();
             $this->_runner->log('Saved Product ID: ' . $product->getId(), '', APIService::TAB . APIService::TAB);
         }
         Dao::commitTransaction();
         return $json;
     } catch (Exception $e) {
         Dao::rollbackTransaction();
         throw $e;
     }
 }
コード例 #4
0
ファイル: Product.php プロジェクト: larryu/magento-b2b
 /**
  * (non-PHPdoc)
  * @see BaseEntityAbstract::getJson()
  */
 public function getJson($extra = array(), $reset = false)
 {
     try {
         $array = $extra;
         if (!$this->isJsonLoaded($reset)) {
             $array['prices'] = array_map(create_function('$a', 'return $a->getJson();'), $this->getPrices());
             $array['manufacturer'] = $this->getManufacturer() instanceof Manufacturer ? $this->getManufacturer()->getJson() : null;
             $array['supplierCodes'] = array_map(create_function('$a', 'return $a->getJson();'), SupplierCode::getAllByCriteria('productId = ?', array($this->getId())));
             $array['productCodes'] = array_map(create_function('$a', 'return $a->getJson();'), ProductCode::getAllByCriteria('productId = ?', array($this->getId())));
             $array['images'] = array_map(create_function('$a', 'return $a->getJson();'), $this->getImages());
             $array['categories'] = array_map(create_function('$a', '$json = $a->getJson(); return $json["category"];'), Product_Category::getCategories($this));
             $array['fullDescriptionAsset'] = ($asset = Asset::getAsset($this->getFullDescAssetId())) instanceof Asset ? $asset->getJson() : null;
             $array['locations'] = array_map(create_function('$a', 'return $a->getJson();'), PreferredLocation::getPreferredLocations($this));
             $array['unitCost'] = $this->getUnitCost();
             $array['priceMatchRule'] = ($i = ProductPriceMatchRule::getByProduct($this)) instanceof ProductPriceMatchRule ? $i->getJson() : null;
             $array['attributeSet'] = ($i = $this->getAttributeSet()) instanceof ProductAttributeSet ? $i->getJson() : null;
             $array['status'] = ($i = $this->getStatus()) instanceof ProductStatus ? $i->getJson() : null;
         }
     } catch (Exception $ex) {
         throw new Exception(' ********** getJson exception :' . $ex->getMessage());
     }
     return parent::getJson($array, $reset);
 }