Example #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;
    }
}
Example #2
0
 /**
  * get product info by sku
  *
  * @param string $sku
  * @param bool 	 $getMageInfo
  *
  * @return string
  * @soapmethod
  */
 public function getProductBySku($sku, $getMageInfo = false)
 {
     $response = $this->_getResponse(UDate::now());
     try {
         $sku = trim($sku);
         Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
         //TODO
         $obj = Product::getBySku($sku);
         if ($obj instanceof Product) {
             $response['status'] = self::RESULT_CODE_SUCC;
             // 				$response->product = json_encode($obj->getJson());
             $this->addCData('product', json_encode($obj->getJson($getMageInfo === true ? array('mageInfo' => $obj->getMageInfo()) : array())), $response);
             return trim($response->asXML());
         }
         $response['status'] = self::RESULT_CODE_FAIL;
         $response->addChild('error', 'product with sku "' . $sku . '" does not exist.');
     } catch (Exception $e) {
         $response['status'] = self::RESULT_CODE_FAIL;
         $this->addCData('error', $e->getMessage(), $response);
     }
     return trim($response->asXML());
 }
Example #3
0
 /**
  * Import Orders
  *
  * @param string $lastUpdatedTime The datatime string
  *
  * @return B2BConnector
  */
 public function importOrders($lastUpdatedTime = '')
 {
     $totalItems = 0;
     $this->_log(0, get_class($this), 'starting ...', self::LOG_TYPE, 'start', __FUNCTION__);
     if (($lastUpdatedTime = trim($lastUpdatedTime)) === '') {
         $this->_log(0, get_class($this), 'Getting the last updated time', self::LOG_TYPE, '$lastUpdatedTime is blank', __FUNCTION__);
         // 			$lastImportTime = new UDate(SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_TIMEZONE));
         $lastUpdatedTime = trim(SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME));
     }
     //getting the lastest order since last updated time
     $orders = $this->getlastestOrders($lastUpdatedTime);
     $this->_log(0, get_class($this), 'Found ' . count($orders) . ' order(s) since "' . $lastUpdatedTime . '".', self::LOG_TYPE, '', __FUNCTION__);
     if (is_array($orders) && count($orders) > 0) {
         $transStarted = false;
         try {
             try {
                 Dao::beginTransaction();
             } catch (Exception $e) {
                 $transStarted = true;
             }
             foreach ($orders as $index => $order) {
                 $this->_log(0, get_class($this), 'Found order from Magento with orderNo = ' . trim($order->increment_id) . '.', self::LOG_TYPE, '', __FUNCTION__);
                 $order = $this->getOrderInfo(trim($order->increment_id));
                 if (!is_object($order)) {
                     $this->_log(0, get_class($this), 'Found no object from $order, next element!', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                     continue;
                 }
                 if (($status = trim($order->state)) === '') {
                     $this->_log(0, get_class($this), 'Found no state Elment from $order, next element!', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                     continue;
                 }
                 //saving the order
                 $orderDate = new UDate(trim($order->created_at), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_TIMEZONE));
                 $orderDate->setTimeZone('UTC');
                 // 				$totalPaid = (!isset($order->total_paid) ? 0 : trim($order->total_paid));
                 $shippingAddr = $billingAddr = null;
                 if (($o = Order::getByOrderNo(trim($order->increment_id))) instanceof Order) {
                     //skip, if order exsits
                     $this->_log(0, get_class($this), 'Found order from DB, ID = ' . $o->getId(), self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                     continue;
                     // 					$shippingAddr = $o->getShippingAddr();
                     // 					$billingAddr = $o->getBillingAddr();
                 }
                 $o = new Order();
                 $this->_log(0, get_class($this), 'Found no order from DB, create new', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                 $customer = Customer::create(isset($order->billing_address) && isset($order->billing_address->company) && trim($order->billing_address->company) !== '' ? trim($order->billing_address->company) : (isset($order->customer_firstname) ? trim($order->customer_firstname) . ' ' . trim($order->customer_lastname) : ''), '', trim($order->customer_email), $this->_createAddr($order->billing_address, $billingAddr), true, '', $this->_createAddr($order->shipping_address, $shippingAddr), isset($order->customer_id) ? trim($order->customer_id) : 0);
                 $o->setOrderNo(trim($order->increment_id))->setOrderDate(trim($orderDate))->setTotalAmount(trim($order->grand_total))->setStatus(strtolower($status) === 'canceled' ? OrderStatus::get(OrderStatus::ID_CANCELLED) : OrderStatus::get(OrderStatus::ID_NEW))->setIsFromB2B(true)->setShippingAddr($customer->getShippingAddress())->setBillingAddr($customer->getBillingAddress())->setCustomer($customer)->save();
                 $this->_log(0, get_class($this), 'Saved the order, ID = ' . $o->getId(), self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                 $totalShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($order->shipping_amount)) * 1.1;
                 //create order info
                 $this->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_CUS_NAME), trim($customer->getName()))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_CUS_EMAIL), trim($customer->getEmail()))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_QTY_ORDERED), intval(trim($order->total_qty_ordered)))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_STATUS), trim($order->status))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_STATE), trim($order->state))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_TOTAL_AMOUNT), trim($order->grand_total))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD), trim($order->shipping_description))->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST), $totalShippingCost)->_createOrderInfo($o, OrderInfoType::get(OrderInfoType::ID_MAGE_ORDER_PAYMENT_METHOD), !isset($order->payment) ? '' : (!isset($order->payment->method) ? '' : trim($order->payment->method)));
                 $this->_log(0, get_class($this), 'Updated order info', self::LOG_TYPE, '$index = ' . $index, __FUNCTION__);
                 //saving the order item
                 $totalItemCost = 0;
                 foreach ($order->items as $item) {
                     $this->_createItem($o, $item);
                     $totalItemCost = $totalItemCost * 1 + StringUtilsAbstract::getValueFromCurrency($item->row_total) * 1.1;
                 }
                 if (($possibleSurchargeAmount = $o->getTotalAmount() - $totalShippingCost - $totalItemCost) > 0 && ($product = Product::getBySku('surcharge')) instanceof Product) {
                     OrderItem::create($o, $product, $possibleSurchargeAmount, 1, $possibleSurchargeAmount);
                 }
                 //record the last imported time for this import process
                 SystemSettings::addSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME, trim($order->created_at));
                 $this->_log(0, get_class($this), 'Updating the last updated time :' . trim($order->created_at), self::LOG_TYPE, '', __FUNCTION__);
                 $totalItems++;
             }
             if ($transStarted === false) {
                 Dao::commitTransaction();
             }
         } catch (Exception $e) {
             if ($transStarted === false) {
                 Dao::rollbackTransaction();
             }
             throw $e;
         }
     }
     $this->_log(0, get_class($this), $lastUpdatedTime . " => " . SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_LAST_IMPORT_TIME) . ' => ' . $totalItems, self::LOG_TYPE, '', __FUNCTION__);
     return $this;
 }
 public function getAllCodeForProduct($sender, $param)
 {
     $result = $errors = $item = array();
     try {
         if (!isset($param->CallbackParameter->importDataTypes) || ($type = trim($param->CallbackParameter->importDataTypes)) === '' || ($type = trim($param->CallbackParameter->importDataTypes)) === 'Select a Import Type') {
             throw new Exception('Invalid upload type passed in!');
         }
         switch ($type) {
             case 'myob_ean':
                 $index = $param->CallbackParameter->index;
                 if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) {
                     throw new Exception('Invalid sku passed in! (line ' . $index . ')');
                 }
                 if (!isset($param->CallbackParameter->itemNo) || ($itemNo = trim($param->CallbackParameter->itemNo)) === '') {
                     throw new Exception('Invalid itemNo passed in! (line ' . $index . ')');
                 }
                 $result['path'] = 'product';
                 $productType = ProductCodeType::get(ProductCodeType::ID_EAN);
                 $item = $this->updateProductCode($product, $itemNo, $productType);
                 $result['item'] = $item->getJson();
                 break;
             case 'myob_upc':
                 $index = $param->CallbackParameter->index;
                 if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) {
                     throw new Exception('Invalid sku passed in! (line ' . $index . ')');
                 }
                 if (!isset($param->CallbackParameter->itemNo) || ($itemNo = trim($param->CallbackParameter->itemNo)) === '') {
                     throw new Exception('Invalid itemNo passed in! (line ' . $index . ')');
                 }
                 $result['path'] = 'product';
                 $productType = ProductCodeType::get(ProductCodeType::ID_UPC);
                 $item = $this->updateProductCode($product, $itemNo, $productType);
                 $result['item'] = $item->getJson();
                 break;
             case 'stockAdjustment':
                 $index = $param->CallbackParameter->index;
                 if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) {
                     throw new Exception('Invalid sku passed in! (line ' . $index . ')');
                 }
                 $result['path'] = 'product';
                 $item = $this->updateStocktack($product, trim($param->CallbackParameter->stockOnPO), trim($param->CallbackParameter->stockOnHand), trim($param->CallbackParameter->stockInRMA), trim($param->CallbackParameter->stockInParts), trim($param->CallbackParameter->totalInPartsValue), trim($param->CallbackParameter->totalOnHandValue), $param->CallbackParameter->active, trim($param->CallbackParameter->comment));
                 $result['item'] = $item->getJson();
                 break;
             case 'accounting':
                 $index = $param->CallbackParameter->index;
                 if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '') {
                     throw new Exception('Invalid sku passed in! (line ' . $index . ')');
                 }
                 if (!($product = Product::getBySku($sku)) instanceof Product) {
                     $product = Product::create($sku, $sku);
                 }
                 $result['path'] = 'product';
                 $item = $this->updateAccountingInfo($product, trim($param->CallbackParameter->assetAccNo), trim($param->CallbackParameter->costAccNo), trim($param->CallbackParameter->revenueAccNo));
                 $result['item'] = $item->getJson();
                 break;
             case 'accountingCode':
                 $index = $param->CallbackParameter->index;
                 if (!isset($param->CallbackParameter->description) || ($description = trim($param->CallbackParameter->description)) === '') {
                     throw new Exception('Invalid description passed in! (line ' . $index . ')');
                 }
                 if (!isset($param->CallbackParameter->code) || ($code = trim($param->CallbackParameter->code)) === '' || !is_numeric($code)) {
                     throw new Exception('Invalid Code passed in! (line ' . $index . ')');
                 }
                 $result['path'] = '';
                 $item = $this->updateAccountingCode($description, $code);
                 $result['item'] = $item->getJson();
                 break;
             default:
                 throw new Exception('Invalid upload type passed in!');
         }
     } catch (Exception $ex) {
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($result, $errors);
 }
Example #5
0
 public function getMin()
 {
     $sku = trim($this->getSku());
     $product = Product::getBySku($sku);
     if ($product instanceof Product) {
         $where = array(1);
         $params = array();
         $where[] = "minId = ? ";
         $params[] = $this->getId();
         $companies = PriceMatchCompany::getAll();
         $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 real price range
         $records = PriceMatchRecord::getAllByCriteria(implode(' AND ', $where), $params, true, 1, 1, array('price' => 'asc'));
         if (count($records) > 0) {
             $this->setRecord($records[0])->setActive(true)->save();
         }
     }
     return $this->getRecord();
 }
 private function updateMagentoPrice($price)
 {
     $product = Product::getBySku($this->sku);
     if (!$product instanceof Product) {
         throw new Exception('Invalid Product passed in. "' . $product . '" given.');
     }
     $connector = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY));
     if ($this->debug) {
         echo 'Connecting to Magento for Product ' . $product->getSku() . '(id=' . $product->getId() . ')' . "\n";
     }
     $result = $connector->updateProductPrice($product->getSku(), $price);
     if ($result !== true && $this->debug === true) {
         echo print_r($result, true);
     }
     if ($result === true && $this->debug === true) {
         echo 'Magento Price Successfully updated to $' . $price . "\n";
     }
     return $this;
 }
Example #7
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;
     }
 }
Example #8
0
 /**
  * (non-PHPdoc)
  * @see DetailsPageAbstract::saveItem()
  */
 public function saveItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $product = !isset($param->CallbackParameter->id) ? new Product() : Product::get(trim($param->CallbackParameter->id));
         if (!$product instanceof Product) {
             throw new Exception('Invalid Product passed in!');
         }
         if (!($manufacturer = Manufacturer::get(trim($param->CallbackParameter->manufacturerId))) instanceof Manufacturer) {
             throw new Exception('Invalid Manufacturer/Brand!');
         }
         if (!($status = ProductStatus::get(trim($param->CallbackParameter->statusId))) instanceof ProductStatus) {
             throw new Exception('Invalid Status!');
         }
         $sku = trim($param->CallbackParameter->sku);
         if (!isset($param->CallbackParameter->id) && ($sku === '' || Product::getBySku($sku) instanceof Product)) {
             throw new Exception('Invalid SKU (' . $sku . ') passed in OR already exist.');
         }
         $name = trim($param->CallbackParameter->name);
         $shortDescription = trim($param->CallbackParameter->shortDescription);
         $sellOnWeb = trim($param->CallbackParameter->sellOnWeb) === '1';
         $weight = doubleval(trim($param->CallbackParameter->weight));
         $product->setName($name)->setSku($sku)->setShortDescription($shortDescription)->setStatus($status)->setManufacturer($manufacturer)->setSellOnWeb($sellOnWeb)->setAsNewFromDate(trim($param->CallbackParameter->asNewFromDate))->setAsNewToDate(trim($param->CallbackParameter->asNewToDate))->setAssetAccNo(trim($param->CallbackParameter->assetAccNo))->setRevenueAccNo(trim($param->CallbackParameter->revenueAccNo))->setCostAccNo(trim($param->CallbackParameter->costAccNo))->setWeight($weight);
         if (trim($product->getId()) === '') {
             $product->setIsFromB2B(false);
         }
         $product->save();
         $this->_updateFullDescription($product, $param)->_updateCategories($product, $param)->_uploadImages($product, $param)->_setSupplierCodes($product, $param)->_setBarcodes($product, $param)->_setPrices($product, $param)->_setLocation($product, $param);
         $product->save();
         $results['url'] = '/product/' . $product->getId() . '.html';
         $results['item'] = $product->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Example #9
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;
 }