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; } }
/** * Updating the full description of the product * * @param Product $product * @param unknown $param * * @return ProductController */ private function _updateFullDescription(Product &$product, $param) { //update full description if (isset($param->CallbackParameter->fullDescription) && ($fullDescription = trim($param->CallbackParameter->fullDescription)) !== '') { if (($fullAsset = Asset::getAsset($product->getFullDescAssetId())) instanceof Asset) { Asset::removeAssets(array($fullAsset->getAssetId())); } $fullAsset = Asset::registerAsset('full_description_for_product.txt', $fullDescription, Asset::TYPE_PRODUCT_DEC); $product->setFullDescAssetId($fullAsset->getAssetId()); } return $this; }
/** * 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())); }
/** * Getting the id * * @param array $params * * @return mix */ private function _get($params) { if (!isset($params['id']) || ($assetId = trim($params['id'])) === '') { throw new Exception('Nothing to get!'); } $asset = null; //try to use apc if (extension_loaded('apc') && ini_get('apc.enabled')) { if (!apc_exists($assetId)) { $asset = Asset::getAsset($assetId); apc_add($assetId, $asset); } else { $asset = apc_fetch($assetId); } } else { $asset = Asset::getAsset($assetId); } if (!$asset instanceof Asset) { throw new Exception('invalid id(' . $assetId . ') to get!'); } $this->getResponse()->writeFile($asset->getFileName(), file_get_contents($asset->getPath()), $asset->getMimeType(), null, false); }
$searchCode = $_GET["searchCode"]; $yearFull = $_GET["assetYear"]; $type = $_GET["assetTypeCode"]; $group = $_GET["assetGroupCode"]; //$year = $yearFull-543; $commandSearch = "AND CONCAT(SUBSTR(C.assetYear,3,4),'/',A.assetTypeCode,'-',A.assetTypeCode,B.assetGroupCode,'-',C.assetCode) LIKE '%" . $searchCode . "%'"; $commandYear = "AND C.assetYear = '" . $yearFull . "'"; $commandType = "AND A.assetTypeCode = '" . $type . "'"; $commandGroup = "AND B.assetGroupCode = '" . $group . "'"; $commandYT = "AND C.assetYear = '" . $yearFull . "' AND A.assetTypeCode = '" . $type . "'"; $commandYTG = "AND C.assetYear = '" . $yearFull . "' AND A.assetTypeCode = '" . $type . "' AND B.assetGroupCode = '" . $group . "'"; $commandTG = "AND C.assetTypeCode = '" . $type . "' AND B.assetGroupCode = '" . $group . "'"; $commandYG = "AND C.assetYear = '" . $yearFull . "' AND B.assetGroupCode = '" . $group . "'"; //$typeCode = $_GET["id"]; //$typeCode = $_GET["id"]; $arrAll = $asset->getAsset(); $arrYear = $asset->getAssetBy($commandYear); $arrType = $asset->getAssetBy($commandType); $arrGroup = $asset->getAssetBy($commandGroup); $arrYT = $asset->getAssetBy($commandYT); $arrTG = $asset->getAssetBy($commandTG); $arrYTG = $asset->getAssetBy($commandYTG); $arrYG = $asset->getAssetBy($commandYG); $arrSearch = $asset->getAssetBy($commandSearch); if ($searchCode != null) { $cmd = $arrSearch; } else { if ($yearFull == null && $type == null && $group == null) { $cmd = $arrAll; } else { if ($yearFull != "0000" && $type == "00" && $group == "00") {
<?php // Templates folder $folderId = '39ba0d27956aa05200c85bbbfba2a20b'; require_once '../../auth_user.php'; echo "<h3 style='font-family: helvetica, sans-serif; border-bottom: 1px dotted #000;'>\n Choose Template to Visualize:\n </h3>"; echo "\n<form action=\"index.php\">"; try { $folder = Asset::getAsset($service, T::FOLDER, $folderId); $at = $folder->getAssetTree(); $txt .= "\n \n <select id='templateId' name='templateId'>\n"; function assetTreeGetTemplateId(AssetOperationHandlerService $service, Child $child, $params = NULL, &$results = NULL) { // Make sure that the type of the $child is indeed Template::TYPE if ($child->getType() == Template::TYPE) { // Since you only need the path and ID strings, just store them in the array $results[$child->getPathPath()] = $child->getId(); } } $function_array = array(Template::TYPE => array(assetTreeGetTemplateId)); $results = array(); // When you call AssetTree::traverse, make sure you pass in an array as the third argument. $at->traverse($function_array, NULL, $results); // $results should have an array of key/value pairs allowing us to do this: foreach ($results as $path => $id) { $txt .= "\n \n <option value='{$id}'>{$path}</option>\n"; } $txt .= "\n \n </select>\n"; echo $txt; echo "\n \n <br />"; echo "\n \n <br />";
<?php // Original library //require_once('/Applications/MAMP/htdocs/cascade/auth_espanae.php'); // prod instance // Namespace version of library //require_once('/Applications/MAMP/htdocs/cascade/auth_ns_espanae_cascade.php'); // prod instance require_once '/Applications/MAMP/htdocs/cascade/auth_ns_espanae_oceania.php'; // test instance // Use reboot:/_scripts folder for testing //$folderID = '68250e75956aa078003f6ca45ac13246'; // Use /news/images/homepage/ folder for testing $folderID = '3a06b928956aa05200c85bbb843d7299'; $results = array(); Asset::getAsset($service, Folder::TYPE, $folderID)->getAssetTree()->traverse(array(File::TYPE => array(F::REPORT_ORPHANS)), NULL, $results); if (count($results[F::REPORT_ORPHANS]) > 0) { //echo S_UL; print_r($results); } else { echo "<p>else</p>\n"; }
/** * The row with default value * * @param UDate $lastUpdatedInDB * @param Product $product * @param string $preFix * @param bool $debug * * @return multitype:string number */ private static function _getRowWithDefaultValues(UDate $lastUpdatedInDB, Product $product = null, $preFix = '', $debug = false) { $attributeSetDefault = 'Default'; $attributeSetName = $attributeSetDefault; $enabled = true; $sku = $statusId = $productName = $rrpPrice = $weight = $shortDescription = $fullDecription = $supplierName = $supplierCode = $manufacturerName = $asNewFrom = $asNewTo = $specialPrice = $specialPriceFromDate = $specialPriceToDate = ''; $categoryIds = array(2); //default category if ($product instanceof Product) { $sku = trim($product->getSku()); $productName = trim($product->getName()); $shortDescription = trim($product->getShortDescription()); $asNewFrom = $product->getAsNewFromDate() instanceof UDate ? $product->getAsNewFromDate()->format('Y-m-d H:i:sP') : ''; $asNewTo = $product->getAsNewToDate() instanceof UDate ? $product->getAsNewToDate()->format('Y-m-d H:i:sP') : ''; $weight = trim($product->getWeight()); if ($product->getAttributeSet() instanceof ProductAttributeSet) { $attributeSetName = $product->getAttributeSet()->getName(); self::_log('-- attributeSetName ', __CLASS__ . '::' . __FUNCTION__ . " attributeSetName={$attributeSetName}", $preFix); } //RRP if (($rrp = $product->getRRP()) instanceof ProductPrice) { $rrpPrice = StringUtilsAbstract::getValueFromCurrency($rrp->getPrice()); } //special price if (($specialPriceObj = $product->getNearestSpecialPrice()) instanceof ProductPrice) { $specialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); if ($specialPrice == 0) { $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } } else { // delete the special price //$specialPrice = StringUtilsAbstract::getValueFromCurrency('99999999'); //$specialPrice = '9999999'; $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } // if it is the daily promotion time then overwrite the special price with the daily special price $isDailyPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISDAILYPROMOTIONTIME)); if ($isDailyPromotionTime === 1) { // get daily promotion price if (($specialPriceObj = $product->getDailySpecialPrice()) instanceof ProductPrice) { $dailySpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($dailySpecialPrice != 0) { $specialPrice = $dailySpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } // if it is the daily promotion time then overwrite the special price with the daily special price $isWeekendPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISWEEKENDPROMOTIONTIME)); if ($isWeekendPromotionTime === 1) { // get weekend promotion price if (($specialPriceObj = $product->getWeekendSpecialPrice()) instanceof ProductPrice) { $weekendSpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($weekendSpecialPrice != 0) { $specialPrice = $weekendSpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } //full description if (($asset = Asset::getAsset($product->getFullDescAssetId())) instanceof Asset) { //$fullDecription = '"' . $asset->read() . '"'; $fullDecription = $asset->read(); } //supplier if (count($supplierCodes = SupplierCode::getAllByCriteria('productId = ?', array($product->getId()), true, 1, 1)) > 0) { $supplierName = ($supplier = $supplierCodes[0]->getSupplier()) instanceof Supplier ? $supplier->getName() : ''; $supplierCode = trim($supplierCodes[0]->getCode()); } //Manufacturer if ($product->getManufacturer() instanceof Manufacturer) { $manufacturerName = trim($product->getManufacturer()->getName()); } //disable or enabled if (intval($product->getActive()) === 0 || intval($product->getSellOnWeb()) === 0) { $enabled = false; } else { if ($product->getStatus() instanceof ProductStatus && intval($product->getStatus()->getId()) === ProductStatus::ID_DISABLED) { $enabled = false; } } //categories if (count($categories = Product_Category::getAllByCriteria('productId = ?', array($product->getId()))) > 0) { foreach ($categories as $category) { if (!$category->getCategory() instanceof ProductCategory || ($mageCateId = trim($category->getCategory()->getMageId())) === '') { continue; } if (trim($attributeSetName) === $attributeSetDefault && ($productAttributeSet = $category->getCategory()->getProductAttributeSet()) instanceof ProductAttributeSet) { $attributeSetName = trim($productAttributeSet->getName()); } $categoryIds[] = $mageCateId; } } //ProductStatus if ($product->getStatus() instanceof ProductStatus) { $statusId = $product->getStatus()->getName(); } } $categoryIds = array_unique($categoryIds); return array("store" => 'default', "websites" => 'base', "attribute_set" => $attributeSetName, "type" => 'simple', "category_ids" => implode(',', $categoryIds), "sku" => $sku, "name" => $productName, "price" => $rrpPrice, "special_from_date" => $specialPriceFromDate, "special_to_date" => $specialPriceToDate, "special_price" => $specialPrice, "news_from_date" => $asNewFrom, "news_to_date" => $asNewTo, "status" => intval($enabled) === 1 ? 1 : 2, "visibility" => 4, "tax_class_id" => 2, "description" => $fullDecription, "short_description" => $shortDescription, "supplier" => $supplierName, "man_code" => '', "sup_code" => $supplierCode, "meta_title" => '', "meta_description" => '', "manufacturer" => $manufacturerName, "url_key" => '', "url_path" => '', "custom_design" => '', "page_layout" => '', "country_of_manufacture" => '', "msrp_enabled" => '', "msrp_display_actual_price_type" => '', "meta_keyword" => '', "custom_layout_update" => '', "custom_design_from" => '', "custom_design_to" => '', "weight" => $weight, "msrp" => 'Use config', "gift_wrapping_price" => '', "qty" => 99, "min_qty" => 99, "use_config_min_qty" => 99, "is_qty_decimal" => '', "backorders" => '', "use_config_backorders" => '', "min_sale_qty" => '', "use_config_min_sale_qty" => '', "max_sale_qty" => '', "use_config_max_sale_qty" => '', "all_ln_stock" => $statusId, "is_in_stock" => 1, "low_stock_date" => '', "notify_stock_qty" => '', "use_config_notify_stock_qty" => '', "manage_stock" => '', "use_config_manage_stock" => '', "stock_status_changed_auto" => '', "use_config_qty_increments" => '', "qty_increments" => '', "use_config_enable_qty_inc" => '', "enable_qty_increments" => '', "is_decimal_divided" => '', "stock_status_changed_automatically" => '', "use_config_enable_qty_increments" => '', "image" => '', "small_image" => '', "thumbnail" => '', "media_gallery" => '', "is_recurring" => '', "media_gallery_reset" => 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(' ', '', $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; } }
/** * (non-PHPdoc) * @see BaseEntityAbstract::getJson() */ public function getJson($extra = array(), $reset = false) { $array = $extra; if (!$this->isJsonLoaded($reset)) { $array['asset'] = ($asset = Asset::getAsset($this->getImageAssetId())) instanceof Asset ? $asset->getJson() : null; } return parent::getJson($array, $reset); }
private function _uploadImages(Product &$product, $param) { //upload images if (isset($param->CallbackParameter->images) && count($images = $param->CallbackParameter->images) > 0) { foreach ($images as $image) { if (($assetId = trim($image->imageAssetId)) === '') { if ($image->active === true) { $data = explode(',', $image->data); $asset = Asset::registerAsset(trim($image->filename), base64_decode($data[1]), Asset::TYPE_PRODUCT_IMG); ProductImage::create($product, $asset); } //if it's deactivated one, ignore } else { if (!($asset = Asset::getAsset($assetId)) instanceof Asset) { continue; } } if ($image->active === false) { ProductImage::remove($product, $asset); } } } return $this; }
<?php include 'classes/Asset.class.php'; include 'classes/DbHandler.class.php'; // Create an instance of Asset $asset = new Asset(); // Set properties echo "Setting properties\n"; echo "Asset : 56\n"; echo "Manufacturer: Gnumaker\n"; echo "Model : Supermodel\n"; $asset->setAsset(56); $asset->setManufacturer("Gnumaker"); $asset->setModel("Supermodel"); echo "Read back the properties\n"; echo "Asset : " . $asset->getAsset() . "\n"; echo "Manufacturer: " . $asset->getManufacturer() . "\n"; echo "Model : " . $asset->getModel() . "\n"; echo "\nOK, now let us connect to the database.\n"; $dbname = "asset_v3"; $dbuser = "******"; $dbpasswd = "g4dba103"; $dbhost = "localhost"; $dbtype = "mysql"; echo "dbname={$dbname}\n"; echo "dbuser={$dbuser}\n"; echo "dbhost={$dbhost}\n"; echo "dbtype={$dbtype}\n"; // Create an instance of DbHandler $dbh = new DbHandler($dbname, $dbuser, $dbpasswd, $dbtype, $dbhost); echo "Getting the last asset. It seem to be: " . $dbh->getLatestAsset() . "\n";
/** * 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; }
/** * (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); }