Esempio n. 1
0
 /**
  * (non-PHPdoc)
  * @see DetailsPageAbstract::saveItem()
  */
 public function saveItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->id)) {
             throw new Exception('Invalid supplier ID passed in!');
         }
         $supplier = ($id = trim($param->CallbackParameter->id)) === '' ? new Supplier() : Supplier::get($id);
         if (!$supplier instanceof Supplier) {
             throw new Exception('Invalid supplier passed in!');
         }
         $contactName = trim($param->CallbackParameter->address->contactName);
         $contactNo = trim($param->CallbackParameter->address->contactNo);
         $street = trim($param->CallbackParameter->address->street);
         $city = trim($param->CallbackParameter->address->city);
         $region = trim($param->CallbackParameter->address->region);
         $postCode = trim($param->CallbackParameter->address->postCode);
         $country = trim($param->CallbackParameter->address->country);
         $address = $supplier->getAddress();
         $supplier->setName(trim($param->CallbackParameter->name))->setDescription(trim($param->CallbackParameter->description))->setContactNo(trim($param->CallbackParameter->contactNo))->setEmail(trim($param->CallbackParameter->email))->setAddress(Address::create($street, $city, $region, $country, $postCode, $contactName, $contactNo, $address))->save();
         $results['url'] = '/supplier/' . $supplier->getId() . '.html' . (isset($_REQUEST['blanklayout']) ? '?blanklayout=' . $_REQUEST['blanklayout'] : '');
         $results['item'] = $supplier->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 2
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);
 }
Esempio n. 3
0
 /**
  *
  * @param unknown $sender
  * @param unknown $params
  */
 public function addComments($sender, $params)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($params->CallbackParameter->entityName) || ($entityName = trim($params->CallbackParameter->entityName)) === '') {
             throw new Exception('System Error: EntityName is not provided!');
         }
         if (!isset($params->CallbackParameter->entityId) || ($entityId = trim($params->CallbackParameter->entityId)) === '') {
             throw new Exception('System Error: entityId is not provided!');
         }
         if (!($entity = $entityName::get($entityId)) instanceof $entityName) {
             throw new Exception('System Error: no such a entity exisits!');
         }
         if (!isset($params->CallbackParameter->comments) || ($comments = trim($params->CallbackParameter->comments)) === '') {
             throw new Exception('System Error: invalid comments passed in!');
         }
         $comment = Comments::addComments($entity, $comments, Comments::TYPE_NORMAL);
         $results['item'] = $comment->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $params->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 4
0
 public function updateSetting($sender, $param)
 {
     $result = $errors = array();
     try {
         $result = $products = array();
         $systemSetting = SystemSettings::getByType(SystemSettings::TYPE_SYSTEM_BUILD_PRODUCTS_ID);
         foreach ($param->CallbackParameter as $type => $ids) {
             $result[$type] = array();
             $products[$type] = array();
             foreach ($ids as $index => $id) {
                 $id = intval(trim($id));
                 if (($product = Product::get($id)) instanceof Product) {
                     $result[$type][] = $id;
                     $products[$type][] = $product->getJson();
                 }
             }
         }
         Dao::beginTransaction();
         $systemSetting->setValue(json_encode($result))->save();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         // 			Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($products, $errors);
 }
Esempio n. 5
0
 public static function run()
 {
     try {
         Dao::beginTransaction();
         $start = self::_logMsg("== START: processing Product Ageing ==", __CLASS__, __FUNCTION__);
         self::_emptyProductAgeingLog();
         $productCount = 0;
         $products = self::_getProducts();
         if (self::DEBUG === true) {
             self::_logMsg('ProductCount: ' . count($products), __CLASS__, __FUNCTION__);
         }
         foreach ($products as $product) {
             $productCount++;
             if (self::DEBUG === true) {
                 self::_logMsg('ProductId: ' . $product->getId(), __CLASS__, __FUNCTION__);
             }
             $lastPurchase = self::_getLastPurchase($product);
             if ($lastPurchase instanceof ProductQtyLog) {
                 self::_recordProductAgeingLog($lastPurchase);
             }
         }
         $end = new UDate();
         self::_logMsg("== FINISHED: process product ageing, (productCount: " . $productCount . ", ProductAgeingLogCount: " . ProductAgeingLog::countByCriteria('active = 1') . ")", __CLASS__, __FUNCTION__);
         Dao::commitTransaction();
     } catch (Exception $e) {
         Dao::rollbackTransaction();
         echo "\n" . $e->getMessage() . "\n" . $e->getTraceAsString();
     }
 }
Esempio n. 6
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;
    }
}
Esempio n. 7
0
 /**
  * runner
  * @param string $debug
  */
 public static function run($debug = false)
 {
     try {
         self::$_debug = $debug;
         Dao::beginTransaction();
         Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
         $start = self::_debug("Start to run " . __CLASS__ . ' =================== ');
         $assetIds = self::_findAllOverdueAssets();
         $assetIds = array_merge($assetIds, self::_findAllZombieAssets());
         self::_deleteAssets($assetIds);
         self::_debug("Finished to run " . __CLASS__ . ' =================== ', self::NEW_LINE, "", $start);
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         self::_debug("***** ERROR: " . $ex->getMessage());
         self::_debug($ex->getTraceAsString());
     }
 }
Esempio n. 8
0
 /**
  * create product
  *
  * @param string $sku			The sku of product
  * @param string $name			The name of product
  * @param array $categoryPaths	The category paths of product (e.g. $categories = array(array('cate2', 'cate3'), array('cate4', 'cate5', 'cate6'));
  * @param string $mageProductId //TODO
  * @param string $isFromB2B
  * @param string $shortDescr
  * @param string $fullDescr
  * @param string $brandName
  *
  * @throws Exception
  * @return string
  * @soapmethod
  */
 public function createProduct($sku, $name, $categoryPaths = array(), $mageProductId = '', $isFromB2B = false, $shortDescr = '', $fullDescr = '', $brandName = '')
 {
     $response = $this->_getResponse(UDate::now());
     try {
         Dao::beginTransaction();
         Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
         //TODO
         if (Product::getBySku(trim($sku)) instanceof Product) {
             throw new Exception('sku "' . $sku . '" already exists');
         }
         $categories = array();
         if (is_array($categoryPaths)) {
             foreach ($categoryPaths as $categoryPath) {
                 $parentCategory = null;
                 foreach ($categoryPath as $categoryName) {
                     if (count($i = ProductCategory::getAllByCriteria('name = ?', array(trim($categoryName)), true, 1, 1)) > 0) {
                         $categories[$i[0]->getId()] = $category = $i[0];
                     } else {
                         $category = ProductCategory::create(trim($categoryName), trim($categoryName), $parentCategory);
                         $categories[$category->getId()] = $category;
                     }
                     $parentCategory = $category;
                 }
             }
         }
         // create product
         $product = Product::create(trim($sku), trim($name));
         // TODO
         foreach ($categories as $category) {
             $product->addCategory($category);
         }
         $response['status'] = self::RESULT_CODE_SUCC;
         $this->addCData('product', json_encode($product->getJson()), $response);
         Dao::commitTransaction();
     } catch (Exception $e) {
         Dao::rollbackTransaction();
         $response['status'] = self::RESULT_CODE_FAIL;
         $this->addCData('error', $e->getMessage(), $response);
     }
     return trim($response->asXML());
 }
Esempio n. 9
0
 /**
  * Creating a new Memo
  *
  * @param unknown $sender
  * @param unknown $params
  *
  * @throws Exception
  */
 public function addMemo($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->entity) || !isset($param->CallbackParameter->entityId) || ($entityName = trim($param->CallbackParameter->entity)) === '' || !($entity = $entityName::get(trim($param->CallbackParameter->entityId))) instanceof $entityName) {
             throw new Exception('System Error: no entity provided for the Memo');
         }
         if (!isset($param->CallbackParameter->data) || !isset($param->CallbackParameter->data->comments) || ($comments = trim($param->CallbackParameter->data->comments)) === '') {
             throw new Exception('You can NOT create a Memo with a blank message.');
         }
         $newComments = null;
         $entity->addComment($comments, Comments::TYPE_MEMO, '', $newComments);
         $results['item'] = $newComments->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 10
0
 public static function run()
 {
     $start = self::_logMsg("== START: processing Messages ==", __CLASS__, __FUNCTION__);
     $messages = self::_getAndMarkMessages();
     self::_logMsg("GOT " . count($messages) . ' Message(s): ', __CLASS__, __FUNCTION__);
     foreach ($messages as $message) {
         self::_logMsg("    Looping message(ID=" . $message->getId() . ': ', __CLASS__, __FUNCTION__);
         try {
             Dao::beginTransaction();
             EmailSender::sendEmail($message->getFrom(), $message->getTo(), $message->getSubject(), $message->getBody(), $message->getAttachmentAssetIdArray());
             $message->setStatus(Message::STATUS_SENT)->save();
             Dao::commitTransaction();
             self::_logMsg("    SUCCESS sending message(ID=" . $message->getId() . ').', __CLASS__, __FUNCTION__);
         } catch (Exception $ex) {
             Dao::rollbackTransaction();
             $message->setStatus(Message::STATUS_FAILED)->save();
             self::_logMsg("    ERROR sending message(ID=" . $message->getId() . ': ' . $ex->getMessage(), __CLASS__, __FUNCTION__);
             self::_logMsg("    ERROR sending message(ID=" . $message->getId() . ': ' . $ex->getTraceAsString(), __CLASS__, __FUNCTION__);
         }
     }
     $end = new UDate();
     self::_logMsg("== FINISHED: " . count($messages) . " Message(s) == ", __CLASS__, __FUNCTION__);
 }
Esempio n. 11
0
 /**
  *
  * @param unknown $sender
  * @param unknown $params
  */
 public function addComments($sender, $params)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($params->CallbackParameter->creditNote) || !($creditNote = CreditNote::get($params->CallbackParameter->creditNote->id)) instanceof CreditNote) {
             throw new Exception('System Error: invalid CreditNote passed in!');
         }
         if (!isset($params->CallbackParameter->comments) || ($comments = trim($params->CallbackParameter->comments)) === '') {
             throw new Exception('System Error: invalid comments passed in!');
         }
         $comment = Comments::addComments($creditNote, $comments, Comments::TYPE_NORMAL);
         $results = $comment->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $params->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 12
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);
 }
Esempio n. 13
0
 public function importProductManufacturers()
 {
     $productAttributes = ProductAttribute::getAllByCriteria('code = ? and isFromB2B = 1 and mageId <> 0', array('manufacturer'), true, 1, 1, array("id" => "desc"));
     if (count($productAttributes) === 0) {
         return;
     }
     $productAttribute = $productAttributes[0];
     try {
         $transStarted = false;
         try {
             Dao::beginTransaction();
         } catch (Exception $e) {
             $transStarted = true;
         }
         foreach ($this->getProductAttributeOptions($productAttribute->getMageId()) as $productAttributeOption) {
             $label = isset($productAttributeOption->label) ? trim($productAttributeOption->label) : '';
             $value = isset($productAttributeOption->value) ? trim($productAttributeOption->value) : '';
             // mageId
             if ($label === '' || $value === '') {
                 echo "ingore product manufacturer options due to empty label or value (" . 'label="' . $label . '", value="' . $value . '")' . "\n";
                 continue;
             }
             $manufacturer = Manufacturer::create($label, '', true, $value);
             echo 'Imported manufacture (name="' . $label . '", mageId=' . $value . ')' . "\n";
         }
         if ($transStarted === false) {
             Dao::commitTransaction();
         }
     } catch (Exception $e) {
         if ($transStarted === false) {
             Dao::commitTransaction();
         }
         throw $e;
     }
     return $this;
 }
Esempio n. 14
0
 /**
  * (non-PHPdoc)
  * @see DetailsPageAbstract::saveItem()
  */
 public function saveItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $perchaseorder = !isset($param->CallbackParameter->id) ? new PurchaseOrder() : PurchaseOrder::get(trim($param->CallbackParameter->id));
         if (!$perchaseorder instanceof PurchaseOrder) {
             throw new Exception('Invalid Purchase Order passed in!');
         }
         $purchaseOrderNo = trim($param->CallbackParameter->purchaseOrderNo);
         $supplierId = trim($param->CallbackParameter->supplierId);
         $supplier = Supplier::get($supplierId);
         $orderDate = trim($param->CallbackParameter->orderDate);
         $totalAmount = trim($param->CallbackParameter->totalAmount);
         $totalPaid = trim($param->CallbackParameter->totalPaid);
         if (isset($param->CallbackParameter->id)) {
             $perchaseorder->setPurchaseOrderNo($purchaseOrderNo)->setSupplier($supplier)->setSupplierRefNo($supplierId)->setOrderDate($orderDate)->setTotalAmount($totalAmount)->setTotalPaid($totalPaid)->save();
         } else {
             // 				PurchaseOrder::
         }
         $results['url'] = '/purchase/' . $perchaseorder->getId() . '.html';
         $results['item'] = $perchaseorder->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 15
0
 /**
  * deleting a payment
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  */
 public function delPayment($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->paymentId) || !($payment = Payment::get($param->CallbackParameter->paymentId)) instanceof Payment) {
             throw new Exception('System Error: invalid payment provided!');
         }
         if (!isset($param->CallbackParameter->reason) || ($reason = trim($param->CallbackParameter->reason)) === '') {
             throw new Exception('The reason for the deletion is needed!');
         }
         $comments = 'A payment [Value: ' . StringUtilsAbstract::getCurrency($payment->getValue()) . ', Method: ' . $payment->getMethod()->getName() . '] is DELETED: ' . $reason;
         $payment->setActive(false)->addComment($comments, Comments::TYPE_ACCOUNTING)->save();
         $entityFor = $payment->getOrder() instanceof Order ? $payment->getOrder() : $payment->getCreditNote();
         if ($entityFor instanceof Order || $entityFor instanceof CreditNote) {
             $entityFor->addComment($comments, Comments::TYPE_ACCOUNTING);
         }
         $results['item'] = $payment->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
<?php

require_once dirname(__FILE__) . '/../main/bootstrap.php';
try {
    echo "Begin" . "\n";
    Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
    Dao::beginTransaction();
    foreach (Product::getAllByCriteria('stockOnOrder < 0') as $product) {
        echo $product->getSku() . "\n";
        $product->setStockOnOrder(0)->snapshotQty(null, ProductQtyLog::TYPE_STOCK_ADJ, 'stock adjustment for negative stock on order')->save();
    }
    Dao::commitTransaction();
} catch (Exception $e) {
    echo $e->getTraceAsString();
    Dao::rollbackTransaction();
    throw $e;
}
Esempio n. 17
0
 /**
  * saveOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function saveOrder($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $items = array();
         $purchaseOrder = PurchaseOrder::get(trim($param->CallbackParameter->purchaseOrder->id));
         if (!$purchaseOrder instanceof PurchaseOrder) {
             throw new Exception('Invalid PurchaseOrder passed in!');
         }
         $comment = trim($param->CallbackParameter->comments);
         $purchaseOrder->addComment(Comments::TYPE_WAREHOUSE, $comment);
         $products = $param->CallbackParameter->products;
         $outStandingOrders = array();
         $invoiceNos = array();
         foreach ($products->matched as $item) {
             $product = Product::get(trim($item->product->id));
             if (!$product instanceof Product) {
                 throw new Exception('Invalid Product passed in!');
             }
             if (isset($item->product->EANcode)) {
                 $EANcode = trim($item->product->EANcode);
                 $productcodes = ProductCode::getAllByCriteria('pro_code.productId = :productId and pro_code.typeId = :typeId', array('productId' => $product->getId(), 'typeId' => ProductCodeType::ID_EAN), true, 1, 1);
                 if (count($productcodes) > 0) {
                     $productcodes[0]->setCode($EANcode)->save();
                 } else {
                     ProductCode::create($product, ProductCodeType::get(ProductCodeType::ID_EAN), $EANcode);
                 }
             }
             if (isset($item->product->UPCcode)) {
                 $UPCcode = trim($item->product->UPCcode);
                 $productcodes = ProductCode::getAllByCriteria('pro_code.productId = :productId and pro_code.typeId = :typeId', array('productId' => $product->getId(), 'typeId' => ProductCodeType::ID_UPC), true, 1, 1);
                 if (sizeof($productcodes)) {
                     $productcodes[0]->setCode($UPCcode)->save();
                 } else {
                     ProductCode::create($product, ProductCodeType::get(ProductCodeType::ID_UPC), $UPCcode);
                 }
             }
             if (isset($item->product->warehouseLocation) && ($locationName = trim($item->product->warehouseLocation)) !== '') {
                 $locs = Location::getAllByCriteria('name = ?', array($locationName), true, 1, 1);
                 $loc = count($locs) > 0 ? $locs[0] : Location::create($locationName, $locationName);
                 $product->addLocation(PreferredLocationType::get(PreferredLocationType::ID_WAREHOUSE), $loc);
             }
             $serials = $item->serial;
             $totalQty = 0;
             foreach ($serials as $serial) {
                 $qty = trim($serial->qty);
                 $totalQty += intval($qty);
                 $serialNo = trim($serial->serialNo);
                 $unitPrice = trim($serial->unitPrice);
                 $invoiceNo = trim($serial->invoiceNo);
                 $invoiceNos[] = $invoiceNo;
                 $comments = trim($serial->comments);
                 ReceivingItem::create($purchaseOrder, $product, $unitPrice, $qty, $serialNo, $invoiceNo, $comments);
             }
             OrderItem::getQuery()->eagerLoad('OrderItem.order', 'inner join', 'ord', 'ord.id = ord_item.orderId and ord.active = 1 and ord.type = :ordType and ord_item.productId = :productId and ord.statusId in ( :statusId1, :statusId2, :statusId3)');
             $orderItems = OrderItem::getAllByCriteria('ord_item.active = 1', array('ordType' => Order::TYPE_INVOICE, 'productId' => $product->getId(), 'statusId1' => OrderStatus::ID_INSUFFICIENT_STOCK, 'statusId2' => OrderStatus::ID_ETA, 'statusId3' => OrderStatus::ID_STOCK_CHECKED_BY_PURCHASING));
             if (count($orderItems) > 0) {
                 $orders = array();
                 foreach ($orderItems as $orderItem) {
                     if (!array_key_exists($orderItem->getOrder()->getId(), $orders)) {
                         $orders[$orderItem->getOrder()->getId()] = $orderItem->getOrder()->getJson();
                     }
                 }
                 $outStandingOrders[$product->getId()] = array('product' => $product->getJson(), 'recievedQty' => $totalQty, 'outStandingOrders' => array_values($orders));
             }
         }
         $results['outStandingOrders'] = count($outStandingOrders) > 0 ? array_values($outStandingOrders) : array();
         $results['item'] = PurchaseOrder::get($purchaseOrder->getId())->getJson();
         $invoiceNos = array_unique($invoiceNos);
         $results['invoiceNos'] = $invoiceNos;
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 18
0
 public function saveUser($sender, $params)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($params->CallbackParameter->firstName) || ($firstName = trim($params->CallbackParameter->firstName)) === '') {
             throw new Exception('System Error: firstName is mandatory!');
         }
         if (!isset($params->CallbackParameter->lastName) || ($lastName = trim($params->CallbackParameter->lastName)) === '') {
             throw new Exception('System Error: lastName is mandatory!');
         }
         if (!isset($params->CallbackParameter->userName) || ($userName = trim($params->CallbackParameter->userName)) === '') {
             throw new Exception('System Error: userName is mandatory!');
         }
         if (!isset($params->CallbackParameter->roleid) || !($role = Role::get($params->CallbackParameter->roleid)) instanceof Role) {
             throw new Exception('System Error: role is mandatory!');
         }
         $newpassword = trim($params->CallbackParameter->newpassword);
         if (!isset($params->CallbackParameter->userid) || !($userAccount = UserAccount::get($params->CallbackParameter->userid)) instanceof UserAccount) {
             $userAccount = new UserAccount();
             $person = new Person();
             if ($newpassword === '') {
                 throw new Exception('System Error: new password is mandatory!');
             }
             $newpassword = sha1($newpassword);
         } else {
             $person = $userAccount->getPerson();
             if ($newpassword === '') {
                 $newpassword = $userAccount->getPassword();
             } else {
                 $newpassword = sha1($newpassword);
             }
         }
         //double check whether the username has been used
         $users = UserAccount::getAllByCriteria('username=? and id!=?', array($userName, $userAccount->getId()), false, 1, 1);
         if (count($users) > 0) {
             throw new Exception('Username(=' . $userName . ') has been used by another user, please choose another one!');
         }
         $person->setFirstName($firstName)->setLastName($lastName)->save();
         $userAccount->setUserName($userName)->setPassword($newpassword)->setPerson($person)->save();
         $results = $userAccount->clearRoles()->addRole($role)->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $params->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 19
0
 /**
  * deleteItem
  *
  * @param unknown $sender
  * @param unknown $param
  * @throws Exception
  *
  */
 public function deleteItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->id) || !($recievingItem = ReceivingItem::get(trim($param->CallbackParameter->id))) instanceof ReceivingItem) {
             throw new Exception('System Error: invalid item provided');
         }
         $recievingItem->setActive(false)->save();
         $results['item'] = $recievingItem->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 20
0
 /**
  * Getting the items
  *
  * @param unknown $sender
  * @param unknown $param
  * @throws Exception
  *
  */
 public function actionTask($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->taskId) || !($task = Task::get(trim($param->CallbackParameter->taskId))) instanceof Task) {
             throw new Exception('Invalid Task provided!');
         }
         if (!isset($param->CallbackParameter->method) || ($method = trim(trim($param->CallbackParameter->method))) === '' || !method_exists($task, $method)) {
             throw new Exception('Invalid Action Method!');
         }
         $comments = isset($param->CallbackParameter->comments) ? trim($param->CallbackParameter->comments) : '';
         $results['item'] = $task->{$method}(Core::getUser(), $comments)->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 21
0
 /**
  * saveOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function saveQuantities($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $items = array();
         var_dump($param->CallbackParameter->products);
         $products = array();
         foreach ($param->CallbackParameter->products as $item) {
             if (!($product = Product::get(trim($item->productId))) instanceof Product) {
                 throw new Exception('Invalid Product passed in!');
             }
             if (($stockOnPO = trim($item->stockOnPO)) !== $product->getstockOnPO()) {
                 $product->setStockOnPO($stockOnPO);
             }
             if (($stockOnHand = trim($item->stockOnHand)) !== $product->getStockOnHand()) {
                 $product->setStockOnHand($stockOnHand);
             }
             if (($stockOnOrder = trim($item->stockOnOrder)) !== $product->getStockOnOrder()) {
                 $product->setStockOnOrder($stockOnOrder);
             }
             if (($stockInRMA = trim($item->stockInRMA)) !== $product->getStockInRMA()) {
                 $product->setStockInRMA($stockInRMA);
             }
             if (($stockInParts = trim($item->stockInParts)) !== $product->getStockInParts()) {
                 $product->setStockInParts($stockInParts);
             }
             if (($totalInPartsValue = trim($item->totalInPartsValue)) !== $product->getTotalInPartsValue()) {
                 $product->setTotalInPartsValue($totalInPartsValue);
             }
             if (($totalOnHandValue = trim($item->totalOnHandValue)) !== $product->getTotalOnHandValue()) {
                 $product->setTotalOnHandValue($totalOnHandValue);
             }
             $product->snapshotQty(null, ProductQtyLog::TYPE_STOCK_ADJ, 'Manual Adjusted by ' . Core::getUser()->getPerson()->getFullName())->save();
             $products[] = $product->getJson();
         }
         $results['items'] = $products;
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 22
0
 public function updateStockLevel($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $id = isset($param->CallbackParameter->productId) ? $param->CallbackParameter->productId : '';
         if (!($product = Product::get($id)) instanceof Product) {
             throw new Exception('Invalid product!');
         }
         if (!isset($param->CallbackParameter->newValue)) {
             throw new Exception('No New ' . $param->CallbackParameter->type . ' Provided!');
         } else {
             $newValue = intval($param->CallbackParameter->newValue);
         }
         if (!isset($param->CallbackParameter->type)) {
             throw new Exception('Invalue Type "' . $param->CallbackParameter->type . '" Provided!');
         } else {
             $type = $param->CallbackParameter->type;
         }
         switch ($param->CallbackParameter->type) {
             case 'stockMinLevel':
                 $msg = 'Update ' . $type . ' for product(SKU=' . $product->getSku() . ') to ' . $param->CallbackParameter->newValue;
                 $product->setStockMinLevel($newValue)->addComment($msg, Comments::TYPE_NORMAL)->addLog($msg, Log::TYPE_SYSTEM);
                 break;
             case 'stockReorderLevel':
                 $msg = 'Update ' . $type . ' for product(SKU=' . $product->getSku() . ') to ' . $param->CallbackParameter->newValue;
                 $product->setStockReorderLevel($newValue)->addComment($msg, Comments::TYPE_NORMAL)->addLog($msg, Log::TYPE_SYSTEM);
                 break;
             default:
                 throw new Exception('Invalue Type "' . $param->CallbackParameter->type . '" Provided!');
         }
         $product->save();
         $results['item'] = $product->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 23
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);
 }
Esempio n. 24
0
 /**
  * cancelOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function cancelOrder($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->orderId) || !($order = Order::get($param->CallbackParameter->orderId)) instanceof Order) {
             throw new Exception('Invalid Order to CANCEL!');
         }
         if (!isset($param->CallbackParameter->reason) || !($reason = trim($param->CallbackParameter->reason)) === '') {
             throw new Exception('An reason for CANCELLING this ' . $order->getType() . ' is needed!');
         }
         $order->setStatus(OrderStatus::get(OrderStatus::ID_CANCELLED))->save()->addComment($msg = $order->getType() . ' is cancelled: ' . $reason, Comments::TYPE_SALES)->addLog($msg, Log::TYPE_SYSTEM, 'AUTO_GEN', __CLASS__ . '::' . __FUNCTION__);
         $results['item'] = $order->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
 /**
  * Update the changeShippingMethod
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  */
 public function changeShippingMethod($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->shippingMethod) || ($shippingMethod = trim($param->CallbackParameter->shippingMethod)) === '') {
             throw new Exception('System Error: invalid shippingMethod provided!');
         }
         $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $shippingMethod, true)->save()->addComment($msg = 'Changed Shipping Method to "' . $shippingMethod . '"', Comments::TYPE_NORMAL)->addLog($msg, Log::TYPE_SYSTEM, '', __CLASS__ . '::' . __FUNCTION__);
         $results['item'] = $order->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 26
0
 /**
  * (non-PHPdoc)
  * @see DetailsPageAbstract::saveItem()
  */
 public function saveItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $name = trim($param->CallbackParameter->name);
         $id = !is_numeric($param->CallbackParameter->id) ? '' : trim($param->CallbackParameter->id);
         $active = !is_numeric($param->CallbackParameter->id) ? '' : trim($param->CallbackParameter->active);
         $email = trim($param->CallbackParameter->email);
         $contactNo = trim($param->CallbackParameter->contactNo);
         $billingCompanyName = trim($param->CallbackParameter->billingCompanyName);
         $billingName = trim($param->CallbackParameter->billingName);
         $billingContactNo = trim($param->CallbackParameter->billingContactNo);
         $billingStreet = trim($param->CallbackParameter->billingStreet);
         $billingCity = trim($param->CallbackParameter->billingCity);
         $billingState = trim($param->CallbackParameter->billingState);
         $billingCountry = trim($param->CallbackParameter->billingCountry);
         $billingPostcode = trim($param->CallbackParameter->billingPosecode);
         $shippingCompanyName = trim($param->CallbackParameter->shippingCompanyName);
         $shippingName = trim($param->CallbackParameter->shippingName);
         $shippingContactNo = trim($param->CallbackParameter->shippingContactNo);
         $shippingStreet = trim($param->CallbackParameter->shippingStreet);
         $shippingCity = trim($param->CallbackParameter->shippingCity);
         $shippingState = trim($param->CallbackParameter->shippingState);
         $shippingCountry = trim($param->CallbackParameter->shippingCountry);
         $shippingPosecode = trim($param->CallbackParameter->shippingPosecode);
         if (is_numeric($param->CallbackParameter->id)) {
             $customer = Customer::get(trim($param->CallbackParameter->id));
             if (!$customer instanceof Customer) {
                 throw new Exception('Invalid Customer passed in!');
             }
             $customer->setName($name)->setEmail($email)->setContactNo($contactNo)->setActive($active);
             $billingAddress = $customer->getBillingAddress();
             if ($billingAddress instanceof Address) {
                 $billingAddress->setStreet($billingStreet)->setCity($billingCity)->setRegion($billingState)->setCountry($billingCountry)->setPostCode($billingPostcode)->setContactName($billingName)->setContactNo($billingContactNo)->setCompanyName($billingCompanyName)->save();
             } else {
                 if (trim($billingStreet) !== '' || trim($billingCity) !== '' || trim($billingState) !== '' || trim($billingCountry) !== '' || trim($billingPostcode) !== '' || trim($billingName) !== '' || trim($billingContactNo) !== '' || trim($billingCompanyName) !== '') {
                     $customer->setBillingAddress(Address::create($billingStreet, $billingCity, $billingState, $billingCountry, $billingPostcode, $billingName, $billingContactNo, $billingCompanyName));
                 }
             }
             $shippingAddress = $customer->getShippingAddress();
             if ($shippingAddress instanceof Address && $billingAddress instanceof Address && $shippingAddress->getId() !== $billingAddress->getId()) {
                 $shippingAddress->setStreet($shippingStreet)->setCity($shippingCity)->setRegion($shippingState)->setCountry($shippingCountry)->setPostCode($shippingPosecode)->setContactName($shippingName)->setContactNo($shippingContactNo)->setCompanyName($shippingCompanyName)->save();
             } else {
                 if (trim($shippingStreet) !== '' || trim($shippingCity) !== '' || trim($shippingState) !== '' || trim($shippingCountry) !== '' || trim($shippingPosecode) !== '' || trim($shippingName) !== '' || trim($shippingContactNo) !== '' || trim($shippingCompanyName) !== '') {
                     $customer->setShippingAddress(Address::create($shippingStreet, $shippingCity, $shippingState, $shippingCountry, $shippingPosecode, $shippingName, $shippingContactNo, $shippingCompanyName));
                 }
             }
             $customer->save();
         } else {
             if (trim($billingStreet) === '' && trim($billingCity) === '' && trim($billingState) === '' && trim($billingCountry) === '' && trim($billingPostcode) === '' && trim($billingName) === '' && trim($billingContactNo) === '' && trim($billingCompanyName) === '') {
                 $billingAdressFull = null;
             } else {
                 $billingAdressFull = Address::create($billingStreet, $billingCity, $billingState, $billingCountry, $billingPostcode, $billingName, $billingContactNo, $billingCompanyName);
             }
             if (trim($shippingStreet) === '' && trim($shippingCity) === '' && trim($shippingState) === '' && trim($shippingCountry) === '' && trim($shippingPosecode) === '' && trim($shippingName) === '' && trim($shippingContactNo) === '' && trim($shippingCompanyName) === '') {
                 $shippingAdressFull = null;
             } else {
                 $shippingAdressFull = Address::create($shippingStreet, $shippingCity, $shippingState, $shippingCountry, $shippingPosecode, $shippingName, $shippingContactNo, $shippingCompanyName);
             }
             $customer = Customer::create($name, $contactNo, $email, $billingAdressFull, false, '', $shippingAdressFull);
             if (!$customer instanceof Customer) {
                 throw new Exception('Error creating customer!');
             }
         }
         $results['url'] = '/customer/' . $customer->getId() . '.html';
         $results['item'] = $customer->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 27
0
 /**
  * Update product code
  *
  * @param Product $product
  * @param unknown $myobCode
  * @param ProductCodeType $productCodeType
  * @param string $assetAccNo
  * @param string $revenueAccNo
  * @param string $costAccNo
  *
  * @return Product
  */
 private function updateProductCode(Product $product, $myobCode, ProductCodeType $productCodeType, $assetAccNo = '', $revenueAccNo = '', $costAccNo = '')
 {
     try {
         Dao::beginTransaction();
         // only take the myobCode (myob item#) after the first dash
         $position = strpos($myobCode, '-');
         if ($position) {
             $myobCodeAfter = substr($myobCode, $position + 1);
             // get everything after first dash
             $myobCodeAfter = str_replace(' ', '', $myobCodeAfter);
             // remove all whitespace
         } else {
             $myobCodeAfter = $myobCode;
         }
         $result = array();
         $result['product'] = $product->getJson();
         $result['code'] = $myobCodeAfter;
         $result['MYOBcode'] = $myobCode;
         $result['assetAccNo'] = $assetAccNo;
         $result['revenueAccNo'] = $revenueAccNo;
         $result['costAccNo'] = $costAccNo;
         // if such code type for such product exist, update it to the new one
         if (!empty($myobCode)) {
             if (count($productCodes = ProductCode::getAllByCriteria('pro_code.typeId = ? and pro_code.productId = ?', array($productCodeType->getId(), $product->getId()), true, 1, 1)) > 0) {
                 $productCodes[0]->setCode($myobCodeAfter)->save();
                 $result['codeNew'] = false;
             } else {
                 $newCode = ProductCode::create($product, $productCodeType, trim($myobCodeAfter));
                 $result['codeNew'] = true;
             }
         }
         // do the same for MYOB code (NOTE: have to have MYOB code in code type !!!)
         if (!empty($myobCode)) {
             if (count($productCodes = ProductCode::getAllByCriteria('pro_code.typeId = ? and pro_code.productId = ?', array(ProductCodeType::ID_MYOB, $product->getId()), true, 1, 1)) > 0) {
                 $productCodes[0]->setCode($myobCode)->save();
                 $result['MYOBcodeNew'] = false;
             } else {
                 ProductCode::create($product, ProductCodeType::get(ProductCodeType::ID_MYOB), trim($myobCode));
                 $result['MYOBcodeNew'] = true;
             }
         }
         if (!empty($assetAccNo)) {
             $product->setAssetAccNo($assetAccNo)->save();
         }
         if (!empty($revenueAccNo)) {
             $product->setRevenueAccNo($revenueAccNo)->save();
         }
         if (!empty($costAccNo)) {
             $product->setCostAccNo($costAccNo)->save();
         }
         Dao::commitTransaction();
         return $product;
     } catch (Exception $e) {
         Dao::rollbackTransaction();
         echo $e;
         exit;
     }
 }
Esempio n. 28
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;
     }
 }
Esempio n. 29
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;
 }
Esempio n. 30
0
 /**
  * (non-PHPdoc)
  * @see DetailsPageAbstract::saveItem()
  */
 public function saveItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $kit = !isset($param->CallbackParameter->id) ? new Kit() : Kit::get(trim($param->CallbackParameter->id));
         if (!$kit instanceof Kit) {
             throw new Exception('Invalid Kit passed in!');
         }
         if (!isset($param->CallbackParameter->productId) || !($product = Product::get(trim($param->CallbackParameter->productId))) instanceof Product) {
             throw new Exception('Invalid Kit Product passed in!');
         }
         if (!isset($param->CallbackParameter->items) || count($items = $param->CallbackParameter->items) === 0) {
             throw new Exception('No Kit Components passed in!');
         }
         $task = null;
         if (isset($param->CallbackParameter->taskId) && !($task = Task::get(trim($param->CallbackParameter->taskId))) instanceof Task) {
             throw new Exception('Invalid Task passed in!');
         }
         $underCostReason = '';
         if (isset($param->CallbackParameter->underCostReason) && ($underCostReason = trim($param->CallbackParameter->underCostReason)) === '') {
             throw new Exception('UnderCostReason is Required!');
         }
         $isNewKit = false;
         if (trim($kit->getId()) === '') {
             $kit = Kit::create($product, $task);
             $isNewKit = true;
         } else {
             $kit->setTask($task)->save();
         }
         //add all the components
         foreach ($items as $item) {
             if (!($componentProduct = Product::get(trim($item->productId))) instanceof Product) {
                 continue;
             }
             if (($componentId = trim($item->id)) === '' && intval($item->active) === 1) {
                 $kit->addComponent($componentProduct, intval($item->qty));
             } else {
                 if (($kitComponent = KitComponent::get($componentId)) instanceof KitComponent) {
                     if ($kitComponent->getKit()->getId() !== $kit->getId()) {
                         continue;
                     }
                     if (intval($item->active) === 0) {
                         //deactivation
                         $kitComponent->setActive(false)->save();
                     } else {
                         $kitComponent->setQty(intval($item->qty))->save();
                     }
                 }
             }
         }
         if (trim($underCostReason) !== '') {
             $kit->addComment('The reason for continuing bulding this kit, when its cost is greater than its unit price: ' . $underCostReason, Comments::TYPE_WORKSHOP);
         }
         if ($isNewKit === true) {
             $kit->finishedAddingComponents();
         }
         $results['url'] = '/kit/' . $kit->getId() . '.html' . (trim($_SERVER['QUERY_STRING']) === '' ? '' : '?' . $_SERVER['QUERY_STRING']);
         if ($isNewKit === true) {
             $results['printUrl'] = '/print/kit/' . $kit->getId() . '.html?printlater=1';
         }
         $results['createdFromNew'] = $isNewKit;
         $results['item'] = $kit->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage() . '<pre>' . $ex->getTraceAsString() . '</pre>';
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }