Beispiel #1
0
 /**
  * Sending the email out
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  */
 public function sendEmail($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->orderId) || !($order = Order::get($param->CallbackParameter->orderId)) instanceof Order) {
             throw new Exception('System Error: invalid order provided!');
         }
         if (!isset($param->CallbackParameter->emailAddress) || ($emailAddress = trim($param->CallbackParameter->emailAddress)) === '') {
             throw new Exception('System Error: invalid emaill address provided!');
         }
         $emailBody = '';
         if (isset($param->CallbackParameter->emailBody) && ($emailBody = trim($param->CallbackParameter->emailBody)) !== '') {
             $emailBody = str_replace("\n", "<br />", $emailBody);
         }
         $pdfFile = EntityToPDF::getPDF($order);
         $asset = Asset::registerAsset($order->getOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP);
         $type = $order->getType();
         EmailSender::addEmail('*****@*****.**', $emailAddress, 'BudgetPC ' . $type . ':' . $order->getOrderNo(), (trim($emailBody) === '' ? '' : $emailBody . "<br /><br />") . 'Please find attached ' . $type . ' (' . $order->getOrderNo() . '.pdf) from Budget PC Pty Ltd.', array($asset));
         $order->addComment('An email sent to "' . $emailAddress . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM);
         $results['item'] = $order->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Beispiel #2
0
 public static function run($debug = false, $mailOut = true)
 {
     try {
         self::$_debug = $debug;
         if ($debug) {
             echo '<pre>';
         }
         $objPHPExcel = self::_getOutput();
         if (!$objPHPExcel instanceof PHPExcel) {
             throw new Exception('System Error: can NOT generate CSV without PHPExcel object!');
         }
         // Set document properties
         $filePath = self::$_rootDir . '/' . md5(new UDate()) . '.csv';
         $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setDelimiter(',')->setEnclosure('"')->setLineEnding("\r\n")->setSheetIndex(0);
         ob_start();
         $objWriter->save('php://output');
         $excelOutput = ob_get_clean();
         $class = get_called_class();
         $asset = Asset::registerAsset($class::_getAttachedFileName(), $excelOutput, Asset::TYPE_TMP);
         if ($mailOut === true) {
             self::_mailOut($asset);
         }
         return $asset;
     } catch (Exception $ex) {
         echo $ex->getMessage();
         die('ERROR!');
     }
 }
Beispiel #3
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;
    }
}
 /**
  * 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;
 }
 /**
  * @return PHPExcel
  */
 private function _getExcel($data)
 {
     $phpexcel = new PHPExcel();
     $activeSheet = $phpexcel->setActiveSheetIndex(0);
     $columnNo = 0;
     $rowNo = 1;
     // excel start at 1 NOT 0
     // header row
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'SKU');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Product Name');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last Week');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last Fortnight');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 1 Month');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 3 Month');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 6 Month');
     $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, 'Last 12 Month');
     $rowNo++;
     foreach ($data as $productId => $rowNoData) {
         $columnNo = 0;
         // excel start at 1 NOT 0
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['proSku']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['proName']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['7days']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['14days']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['1month']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['3month']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['6month']);
         $activeSheet->setCellValueByColumnAndRow($columnNo++, $rowNo, $rowNoData['12month']);
         $rowNo++;
     }
     // Set document properties
     $now = UDate::now();
     $objWriter = new PHPExcel_Writer_Excel2007($phpexcel);
     $filePath = '/tmp/' . md5($now);
     $objWriter->save($filePath);
     $fileName = 'RunRate_' . str_replace(':', '_', str_replace('-', '_', str_replace(' ', '_', $now->setTimeZone(SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE))))) . '.xlsx';
     $asset = Asset::registerAsset($fileName, file_get_contents($filePath), Asset::TYPE_TMP);
     return $asset;
 }
Beispiel #6
0
 /**
  * saveOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function saveOrder($sender, $param)
 {
     $results = $errors = array();
     $daoStart = false;
     try {
         Dao::beginTransaction();
         $daoStart = true;
         $supplier = Supplier::get(trim($param->CallbackParameter->supplier->id));
         if (!$supplier instanceof Supplier) {
             throw new Exception('Invalid Supplier passed in!');
         }
         $supplierContactName = trim($param->CallbackParameter->supplier->contactName);
         $supplierContactNo = trim($param->CallbackParameter->supplier->contactNo);
         $supplierEmail = trim($param->CallbackParameter->supplier->email);
         if (!empty($supplierContactName) && $supplierContactName !== $supplier->getContactName()) {
             $supplier->setContactName($supplierContactName);
         }
         if (!empty($supplierContactNo) && $supplierContactNo !== $supplier->getContactNo()) {
             $supplier->setContactNo($supplierContactNo);
         }
         if (!empty($supplierEmail) && $supplierEmail !== $supplier->getEmail()) {
             $supplier->setEmail($supplierEmail);
         }
         $supplier->save();
         $purchaseOrder = PurchaseOrder::create($supplier, trim($param->CallbackParameter->supplierRefNum), $supplierContactName, $supplierContactNo, StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->shippingCost)), StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->handlingCost)))->setTotalAmount(StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->totalPaymentDue)))->setEta(trim($param->CallbackParameter->eta))->setStatus(PurchaseOrder::STATUS_NEW)->save()->addComment(trim($param->CallbackParameter->comments), Comments::TYPE_PURCHASING);
         foreach ($param->CallbackParameter->items as $item) {
             if (!($product = Product::get(trim($item->productId))) instanceof Product) {
                 throw new Exception('Invalid Product passed in!');
             }
             $purchaseOrder->addItem($product, StringUtilsAbstract::getValueFromCurrency(trim($item->unitPrice)), intval(trim($item->qtyOrdered)));
         }
         if ($param->CallbackParameter->submitToSupplier === true) {
             $purchaseOrder->setStatus(PurchaseOrder::STATUS_ORDERED)->save();
         }
         $daoStart = false;
         Dao::commitTransaction();
         $results['item'] = $purchaseOrder->getJson();
         if (isset($param->CallbackParameter->confirmEmail) && trim($confirmEmail = trim($param->CallbackParameter->confirmEmail)) !== '') {
             $pdfFile = EntityToPDF::getPDF($purchaseOrder);
             $asset = Asset::registerAsset($purchaseOrder->getPurchaseOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP);
             EmailSender::addEmail('*****@*****.**', $confirmEmail, 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset));
             EmailSender::addEmail('*****@*****.**', '*****@*****.**', 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset));
             $purchaseOrder->addComment('An email sent to "' . $confirmEmail . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM);
         }
     } catch (Exception $ex) {
         if ($daoStart === true) {
             Dao::rollbackTransaction();
         }
         $errors[] = $ex->getMessage() . "<pre>" . $ex->getTraceAsString() . "</pre>";
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
 /**
  * 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;
     }
 }
 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;
 }
 /**
  * saveOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function saveOrder($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!($purchaseOrder = PurchaseOrder::get(trim($param->CallbackParameter->id))) instanceof PurchaseOrder) {
             throw new Exception('Invalid Purchase Order passed in!');
         }
         if (!($supplier = Supplier::get(trim($param->CallbackParameter->supplierId))) instanceof Supplier) {
             throw new Exception('Invalid Supplier passed in!');
         }
         $isSubmit = isset($param->CallbackParameter->isSubmit) && intval($param->CallbackParameter->isSubmit) === 1 ? true : false;
         $supplierRefNum = trim($param->CallbackParameter->supplierRefNum);
         $supplierContactName = trim($param->CallbackParameter->contactName);
         $supplierContactNo = trim($param->CallbackParameter->contactNo);
         $shippingCost = trim($param->CallbackParameter->shippingCost);
         $handlingCost = trim($param->CallbackParameter->handlingCost);
         $comment = trim($param->CallbackParameter->comments);
         $status = trim($param->CallbackParameter->status);
         $purchaseOrderTotalAmount = trim($param->CallbackParameter->totalAmount);
         $purchaseOrderTotalPaid = trim($param->CallbackParameter->totalPaid);
         $purchaseOrder->setTotalAmount($purchaseOrderTotalAmount)->setTotalPaid($purchaseOrderTotalPaid)->setSupplierRefNo($supplierRefNum)->setSupplierContact($supplierContactName)->setSupplierContactNumber($supplierContactNo)->setshippingCost($shippingCost)->sethandlingCost($handlingCost)->setStatus($status)->save();
         $purchaseOrder->addComment($comment, Comments::TYPE_PURCHASING);
         foreach ($param->CallbackParameter->items as $item) {
             $productUnitPrice = trim($item->unitPrice);
             $qtyOrdered = trim($item->qtyOrdered);
             $productTotalPrice = trim($item->totalPrice);
             if (!($product = Product::get(trim($item->productId))) instanceof Product) {
                 throw new Exception('Invalid Product passed in!');
             }
             if (!isset($item->id) || trim($item->id) === '') {
                 $poItem = null;
                 $purchaseOrder->addItem($product, $productUnitPrice, $qtyOrdered, '', '', $productTotalPrice, $poItem);
             } else {
                 if (($poItem = PurchaseOrderItem::get($item->id)) instanceof PurchaseOrderItem) {
                     $poItem->setProduct($product)->setUnitPrice($productUnitPrice)->setTotalPrice($productTotalPrice)->setQty($qtyOrdered);
                 }
             }
             $poItem->setActive(intval($item->active) === 1)->save();
         }
         $results['item'] = $purchaseOrder->getJson();
         if ($isSubmit === true) {
             $pdfFile = EntityToPDF::getPDF($purchaseOrder);
             $confirmEmail = trim($param->CallbackParameter->contactEmail);
             $asset = Asset::registerAsset($purchaseOrder->getPurchaseOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP);
             EmailSender::addEmail('*****@*****.**', $confirmEmail, 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset));
             EmailSender::addEmail('*****@*****.**', '*****@*****.**', 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset));
             $purchaseOrder->addComment('An email sent to "' . $confirmEmail . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM);
         }
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Beispiel #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;
 }
Beispiel #11
0
 /**
  * Creating the product based on sku
  *
  * @param string $sku           	The sku of the product
  * @param string $name          	The name of the product
  * @param string $mageProductId 	The magento id of the product
  * @param int    $stockOnHand   	The total quantity on hand for this product
  * @param int    $stockOnOrder  	The total quantity on order from supplier for this product
  * @param int    $stockMinLevel 	The minimum stock level for this product
  * @param int    $stockReorderLevel	The reorder stock level for this product
  * @param bool   $isFromB2B     	Whether this product is created via B2B?
  * @param string $shortDescr    	The short description of the product
  * @param string $fullDescr     	The assetId of the full description asset of the product
  *
  * @return Ambigous <Product, Ambigous, NULL, BaseEntityAbstract>
  */
 public static function create($sku, $name, $mageProductId = '', $stockOnHand = null, $stockOnOrder = null, $isFromB2B = false, $shortDescr = '', $fullDescr = '', Manufacturer $manufacturer = null, $assetAccNo = null, $revenueAccNo = null, $costAccNo = null, $stockMinLevel = null, $stockReorderLevel = null, $manualDatafeed = false, $weight = null, $attributesetId = null)
 {
     if (!($product = self::getBySku($sku)) instanceof Product) {
         $product = new Product();
     }
     $product->setSku(trim($sku))->setName($name)->setManualDatafeed(intval($manualDatafeed) === 1);
     if (($mageProductId = trim($mageProductId)) !== "") {
         $product->setMageId($mageProductId);
     }
     if (trim($product->getId()) === '') {
         $product->setIsFromB2B($isFromB2B)->setShortDescription($shortDescr);
         if ($stockOnOrder !== null && is_numeric($stockOnOrder)) {
             $product->setStockOnOrder(intval($stockOnOrder));
         }
         if ($stockOnHand !== null && is_numeric($stockOnHand)) {
             $product->setStockOnHand(intval($stockOnHand));
         }
         if ($stockMinLevel !== null && is_numeric($stockMinLevel)) {
             $product->setStockMinLevel(intval($stockMinLevel));
         }
         if ($stockReorderLevel !== null && is_numeric($stockReorderLevel)) {
             $product->setStockReorderLevel(intval($stockReorderLevel));
         }
         if ($assetAccNo !== null && is_string($assetAccNo)) {
             $product->setAssetAccNo(trim($assetAccNo));
         }
         if ($revenueAccNo !== null && is_string($revenueAccNo)) {
             $product->setRevenueAccNo(trim($revenueAccNo));
         }
         if ($costAccNo !== null && is_string($costAccNo)) {
             $product->setCostAccNo(trim($costAccNo));
         }
         if ((${$fullDescr} = trim($fullDescr)) !== '') {
             $asset = Asset::registerAsset('full_desc_' . $sku, $fullDescr, Asset::TYPE_PRODUCT_DEC);
             $product->setFullDescAssetId(trim($asset->getAssetId()));
         }
         if ($manufacturer instanceof Manufacturer) {
             $product->setManufacturer($manufacturer);
         }
         if ($weight !== null) {
             $product->setWeight($weight);
         }
         if ($attributesetId !== null && is_string($attributesetId)) {
             $product->setAttributeSet(ProductAttributeSet::get($attributesetId));
         }
     }
     return $product->save();
 }