示例#1
0
function updateProduct($pro, $fileName, $line)
{
    $clientScript = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, getWSDL(), 'B2BUser', 'B2BUser');
    try {
        $transStarted = false;
        try {
            Dao::beginTransaction();
        } catch (Exception $e) {
            $transStarted = true;
        }
        $sku = trim($pro['sku']);
        $product = Product::getBySku($pro['sku']);
        $mageId = trim($pro['product_id']);
        $name = trim($pro['name']);
        $short_description = trim($pro['short_description']);
        $description = trim($pro['description']);
        $weight = trim($pro['weight']);
        $statusId = trim($pro['status']);
        $price = trim($pro['price']);
        $specialPrice = trim($pro['special_price']);
        $specialPrice_From = trim($pro['special_from_date']) === '' ? trim($pro['special_from_date']) : null;
        $specialPrice_To = trim($pro['special_to_date']) === '' ? trim($pro['special_to_date']) : null;
        $supplierName = trim($pro['supplier']);
        $attributeSet = ProductAttributeSet::get(trim($pro['attributeSetId']));
        if (!$product instanceof Product) {
            $product = Product::create($sku, $name);
        }
        $asset = ($assetId = trim($product->getFullDescAssetId())) === '' || !($asset = Asset::getAsset($assetId)) instanceof Asset ? Asset::registerAsset('full_desc_' . $sku, $description, Asset::TYPE_PRODUCT_DEC) : $asset;
        $product->setName($name)->setMageId($mageId)->setAttributeSet($attributeSet)->setShortDescription($short_description)->setFullDescAssetId(trim($asset->getAssetId()))->setIsFromB2B(true)->setStatus(ProductStatus::get($statusId))->setSellOnWeb(true)->setManufacturer($clientScript->getManufacturerName(trim($pro['manufacturer'])))->save()->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price)->addInfo(ProductInfoType::ID_WEIGHT, $weight);
        if ($specialPrice !== '') {
            $product->addPrice(ProductPriceType::get(ProductPriceType::ID_CASUAL_SPECIAL), $specialPrice, $specialPrice_From, $specialPrice_To);
        }
        if ($supplierName !== '') {
            $product->addSupplier(Supplier::create($supplierName, $supplierName, true));
        }
        if (isset($pro['categories']) && count($pro['categories']) > 0) {
            $product->clearAllCategory();
            foreach ($pro['categories'] as $cateMageId) {
                if (!($category = ProductCategory::getByMageId($cateMageId)) instanceof ProductCategory) {
                    continue;
                }
                $product->addCategory($category);
            }
        }
        if ($transStarted === false) {
            Dao::commitTransaction();
        }
        //TODO remove the file
        removeLineFromFile($fileName, $line);
        echo $product->getId() . " => done! \n";
    } catch (Exception $ex) {
        if ($transStarted === false) {
            Dao::rollbackTransaction();
        }
        throw $ex;
    }
}
 /**
  * This function generates the ProductData for a product to be used for inser/update of product on Magento
  * @param Product $product
  * @param unknown $linkedCategories
  * @return multitype:string number unknown multitype:number
  */
 private function _generateProductData(Product $product, array $linkedCategories)
 {
     $productDescription = '';
     $productDescAssetId = trim($product->getFullDescAssetId());
     if ($productDescAssetId !== '') {
         $asset = Asset::getAsset($productDescAssetId);
         if ($asset instanceof Asset && ($assetPath = trim($asset->getPath())) !== '') {
             $productDescription = Asset::readAssetFile($assetPath);
         }
     }
     $price = '0';
     $productPrices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
     if (count($productPrices) > 0) {
         $price = $productPrices[0]->getPrice();
     }
     $urlKey = strtolower(str_replace(' ', '-', trim($product->getName())));
     return array('categories' => $linkedCategories, 'websites' => array(1), 'name' => trim($product->getName()), 'description' => $productDescription, 'short_description' => trim($product->getShortDescription()), 'weight' => method_exists($product, 'getWeight') ? trim($product->getWeight()) : '1', 'status' => trim($product->getStatus()), 'url_key' => $urlKey, 'url_path' => $urlKey, 'visibility' => '4', 'price' => $price, 'tax_class_id' => 1, 'meta_title' => trim($product->getName()), 'meta_keyword' => trim($product->getSku()), 'meta_description' => trim($product->getShortDescription()));
 }
示例#3
0
 /**
  * Getting the price object via product or type
  *
  * @param Product          $product
  * @param ProductPriceType $type
  * @param string           $startS
  * @param string           $startE
  * @param string           $endS
  * @param string           $endE
  * @param int              $pageNo
  * @param int              $pageSize
  * @param array            $orderBy
  * @throws EntityException
  * @return Ambigous <multitype:, multitype:BaseEntityAbstract >
  */
 public static function getPrices(Product $product = null, ProductPriceType $type = null, $startS = '', $startE = '', $endS = '', $endE = '', $pageNo = null, $pageSize = DaoQuery::DEFAUTL_PAGE_SIZE, $orderBy = array(), &$stats = array())
 {
     $class = __CLASS__;
     if (!$product instanceof Product && !$type instanceof ProductPriceType) {
         throw new EntityException('At least one of them is required for getting the prices: Product or PriceType');
     }
     $where = array('active = 1');
     $params = array();
     if ($product instanceof Product) {
         $where[] = 'productId = ?';
         $params[] = $product->getId();
     }
     if ($type instanceof ProductPriceType) {
         $where[] = 'typeId = ?';
         $params[] = $type->getId();
     }
     if (($startS = trim($startS)) !== '') {
         $where[] = 'start >= ?';
         $params[] = $startS;
     }
     if (($startE = trim($startE)) !== '') {
         $where[] = 'start <= ?';
         $params[] = $startE;
     }
     if (($endS = trim($endS)) !== '') {
         $where[] = 'end >= ?';
         $params[] = $endS;
     }
     if (($endE = trim($endE)) !== '') {
         $where[] = 'end <= ?';
         $params[] = $endE;
     }
     return self::getAllByCriteria(implode(' AND ', $where), $params, true, $pageNo, $pageSize, $orderBy, $stats);
 }
示例#4
0
 /**
  * Getting price matching information
  *
  * @param unknown $sender
  * @param unknown $param
  */
 public function priceMatching($sender, $param)
 {
     $results = $errors = array();
     try {
         $id = isset($param->CallbackParameter->id) ? $param->CallbackParameter->id : '';
         $product = Product::get($id);
         $prices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
         $companies = PriceMatcher::getAllCompaniesForPriceMatching();
         $prices = PriceMatcher::getPrices($companies, $product->getSku(), count($prices) === 0 ? 0 : $prices[0]->getPrice());
         $myPrice = $prices['myPrice'];
         $minPrice = $prices['minPrice'];
         $msyPrice = $prices['companyPrices']['MSY'];
         $prices['id'] = $id;
         $results = $prices;
     } catch (Exception $ex) {
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
 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;
 }
示例#6
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;
     }
 }
示例#7
0
 /**
  * updateproduct price
  *
  * @param unknown $sender
  * @param unknown $param
  */
 public function updatePrice($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $id = isset($param->CallbackParameter->productId) ? $param->CallbackParameter->productId : '';
         if (!($product = Product::get($id)) instanceof Product) {
             throw new Exception('Invalid product!');
         }
         if (!isset($param->CallbackParameter->newPrice)) {
             throw new Exception('No New Price Provided!');
         }
         $isSpecial = 0;
         if (isset($param->CallbackParameter->isSpecial)) {
             $isSpecial = intval($param->CallbackParameter->isSpecial);
         }
         $newPrice = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->newPrice));
         if ($isSpecial === 0) {
             $priceType = ProductPriceType::ID_RRP;
         } else {
             $priceType = ProductPriceType::ID_CASUAL_SPECIAL;
         }
         $prices = ProductPrice::getAllByCriteria('productId = ? and typeId = ?', array($product->getId(), $priceType), true, 1, 1);
         if (count($prices) > 0) {
             $msg = 'Update price for product(SKU=' . $product->getSku() . ') to ' . StringUtilsAbstract::getCurrency($newPrice);
             $price = $prices[0];
         } else {
             $msg = 'New Price Created for product(SKU=' . $product->getSku() . '): ' . StringUtilsAbstract::getCurrency($newPrice);
             $price = new ProductPrice();
             $price->setProduct($product)->setType(ProductPriceType::get($priceType));
         }
         $price->setPrice($newPrice)->save()->addComment($msg, Comments::TYPE_NORMAL)->addLog($msg, Log::TYPE_SYSTEM);
         $product->addComment($msg, Log::TYPE_SYSTEM)->addLog($msg, Log::TYPE_SYSTEM);
         $results['item'] = $product->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
示例#8
0
 private function _setPrices(Product &$product, $param)
 {
     if (isset($param->CallbackParameter->prices) && count($prices = $param->CallbackParameter->prices) > 0) {
         //delete all price first
         $deleteIds = array();
         foreach ($prices as $price) {
             if (trim($price->active) === '0' && isset($price->id)) {
                 $deleteIds[] = trim($price->id);
             }
         }
         if (count($deleteIds) > 0) {
             ProductPrice::updateByCriteria('active = 0', 'id in (' . str_repeat('?', count($deleteIds)) . ')', $deleteIds);
         }
         //update or create new
         foreach ($prices as $price) {
             if (isset($price->id) && in_array(trim($price->id), $deleteIds)) {
                 continue;
             }
             if (!($type = ProductPriceType::get(trim($price->typeId))) instanceof ProductPriceType) {
                 continue;
             }
             $priceValue = trim($price->value);
             $start = trim($price->start);
             $end = trim($price->end);
             if (!is_numeric(StringUtilsAbstract::getValueFromCurrency($priceValue))) {
                 throw new Exception('Invalid price: ' . $priceValue);
             }
             if (!isset($price->id) || ($id = trim($price->id)) === '') {
                 if (trim($price->active) === '1') {
                     ProductPrice::create($product, $type, $priceValue, $start, $end);
                 }
                 //if it's deactivated one, ignore
             } else {
                 if (($productPrice = ProductPrice::get($id)) instanceof ProductPrice) {
                     $productPrice->setPrice($priceValue)->setType($type)->setProduct($product)->setStart($start)->setEnd($end)->save();
                 }
             }
         }
     }
     return $this;
 }
示例#9
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getProductPriceTypes()
 {
     return $this->hasMany(ProductPriceType::className(), ['currency_id' => 'id']);
 }
示例#10
0
 /**
  * import all products
  *
  * @return CatelogConnector
  */
 public function importProducts()
 {
     if (!($systemSetting = SystemSettings::getByType(SystemSettings::TYPE_LAST_NEW_PRODUCT_PULL)) instanceof SystemSettings) {
         throw new Exception('cannot get LAST_NEW_PRODUCT_PULL in system setting');
     }
     $fromDate = $systemSetting->getValue();
     $products = $this->getProductList($fromDate);
     if (count($products) === 0) {
         echo 'nothing from magento. exitting' . "\n";
         return $this;
     }
     try {
         $transStarted = false;
         try {
             Dao::beginTransaction();
         } catch (Exception $e) {
             $transStarted = true;
         }
         foreach ($products as $pro) {
             $mageId = trim($pro->product_id);
             $sku = trim($pro->sku);
             $pro = $this->getProductInfo($sku, $this->getInfoAttributes());
             $created_at = trim($pro->created_at);
             $updated_at = trim($pro->updated_at);
             $product_id = trim($pro->product_id);
             if (is_null($pro) || !isset($pro->additional_attributes)) {
                 continue;
             }
             // handle extra long sku from magento, exceeding mysql sku length limit
             DaoMap::loadMap('Product');
             $skuSizeLimit = DaoMap::$map['product']['sku']['size'];
             if (strlen($sku) > $skuSizeLimit) {
                 echo 'Product ' . $sku . '(id=' . $product->getId() . ', magento Product Creation Time=' . trim($pro->created_at) . ') magento sku length exceed system sku length limit of' . $skuSizeLimit . ', skipped' . "\n";
                 continue;
             }
             $additionAttrs = $this->_getAttributeFromAdditionAttr($pro->additional_attributes);
             $name = trim($additionAttrs['name']);
             $short_description = trim($additionAttrs['short_description']);
             $description = trim($additionAttrs['description']);
             $weight = trim($additionAttrs['weight']);
             $statusId = trim($additionAttrs['status']);
             $price = trim($additionAttrs['price']);
             $specialPrice = isset($additionAttrs['special_price']) ? trim($additionAttrs['special_price']) : '';
             $specialPrice_From = isset($additionAttrs['special_from_date']) ? trim($additionAttrs['special_from_date']) : null;
             $specialPrice_To = isset($additionAttrs['special_to_date']) ? trim($additionAttrs['special_to_date']) : null;
             if (!($product = Product::getBySku($sku)) instanceof Product) {
                 $product = Product::create($sku, $name);
                 Log::logging(0, get_class($this), 'Found New Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at, self::LOG_TYPE, '', __FUNCTION__);
                 echo 'Found New Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at . ', updated_at' . $updated_at . "\n";
             } elseif (Product::getBySku($sku) instanceof Product) {
                 $product = Product::getBySku($sku);
                 echo 'Found Existing Product from Magento with sku="' . trim($sku) . '" and name="' . $name . '", created_at="' . $created_at . ', updated_at' . $updated_at . '"' . "\n";
                 echo "\t" . 'Name: "' . $name . '"' . "\n";
                 echo "\t" . 'MageId: "' . $mageId . '"' . "\n";
                 echo "\t" . 'Short Description: "' . $short_description . '"' . "\n";
                 echo "\t" . 'Full Description: "' . $description . '"' . "\n";
                 echo "\t" . 'Status: "' . ProductStatus::get($statusId) . '"' . "\n";
                 echo "\t" . 'Manufacturer: id=' . $this->getManufacturerName(trim($additionAttrs['manufacturer']))->getId() . ', name="' . $this->getManufacturerName(trim($additionAttrs['manufacturer']))->getName() . '"' . "\n";
                 echo "\t" . 'Price: "' . $price . '"' . "\n";
                 echo "\t" . 'Weight: "' . $weight . '"' . "\n";
             }
             $asset = ($assetId = trim($product->getFullDescAssetId())) === '' || !($asset = Asset::getAsset($assetId)) instanceof Asset ? Asset::registerAsset('full_desc_' . $sku, $description, Asset::TYPE_PRODUCT_DEC) : $asset;
             $product->setName($name)->setMageId($mageId)->setShortDescription($short_description)->setFullDescAssetId(trim($asset->getAssetId()))->setIsFromB2B(true)->setStatus(ProductStatus::get($statusId))->setSellOnWeb(true)->setManufacturer($this->getManufacturerName(trim($additionAttrs['manufacturer'])))->save()->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price)->addInfo(ProductInfoType::ID_WEIGHT, $weight);
             if ($specialPrice !== '') {
                 $product->addPrice(ProductPriceType::get(ProductPriceType::ID_CASUAL_SPECIAL), $specialPrice, $specialPrice_From, $specialPrice_To);
             }
             if (isset($additionAttrs['supplier']) && ($supplierName = trim($additionAttrs['supplier'])) !== '') {
                 $product->addSupplier(Supplier::create($supplierName, $supplierName, true));
             }
             if (isset($pro->categories) && count($pro->categories) > 0) {
                 $product->clearAllCategory();
                 foreach ($pro->category_ids as $cateMageId) {
                     if (!($category = ProductCategory::getByMageId($cateMageId)) instanceof ProductCategory) {
                         continue;
                     }
                     $product->addCategory($category);
                 }
             }
         }
         $systemSetting->setValue($updated_at)->save();
         if ($transStarted === false) {
             Dao::commitTransaction();
         }
     } catch (Exception $ex) {
         if ($transStarted === false) {
             Dao::rollbackTransaction();
         }
         throw $ex;
     }
     return $this;
 }
示例#11
0
 /**
  * Getting the weekend special price for this product
  * @return ProductPrice|NULL
  */
 public function getWeekendSpecialPrice()
 {
     if (count($prices = ProductPrice::getPrices($this, ProductPriceType::get(ProductPriceType::ID_WEEKEND_SPECIAL), '', '', '', '', 1, 1)) > 0) {
         return $prices[0];
     }
     return null;
 }