/** * Output the debug message * * @param string $msg * */ private static function _debug($msg = "", $newLine = self::NEW_LINE, $prefix = "", UDate $start = null) { $now = UDate::now(SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE)); if (self::$_debug === true) { echo $prefix . '[' . $now . ']: ' . $msg . ($start instanceof UDate ? '[ Took ' . ($now->getUnixTimeStamp() - $start->getUnixTimeStamp()) . ' second(s)]' : '') . $newLine; } return $now; }
function disableProduct($sku) { $sku = trim($sku); $params = array(); $params['status'] = '2'; // '2' means Disable in magento $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->updateProductInfo($sku, $params); echo 'product with sku "' . $sku . '" disabled in magento' . "\n"; }
public static function sendEmail($from, $to, $subject, $body, array $attachmentAssetIds = array()) { $settings = json_decode(SystemSettings::getSettings(SystemSettings::TYPE_EMAIL_SENDING_SERVER), true); //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); $mail->isHTML(true); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = isset($settings['SMTPDebug']) ? $settings['SMTPDebug'] : 2; //Ask for HTML-friendly debug output $mail->Debugoutput = isset($settings['debugOutput']) ? $settings['debugOutput'] : 'html'; //Set the hostname of the mail server $mail->Host = isset($settings['host']) ? $settings['host'] : ""; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = isset($settings['port']) ? $settings['port'] : 25; //Whether to use SMTP authentication $mail->SMTPAuth = isset($settings['SMTPAuth']) ? $settings['SMTPAuth'] : true; //Username to use for SMTP authentication $mail->Username = isset($settings['username']) ? $settings['username'] : ""; //Password to use for SMTP authentication $mail->Password = isset($settings['password']) ? $settings['password'] : ""; //Set who the message is to be sent from $mail->setFrom($from); //Set an alternative reply-to address //$mail->addReplyTo('*****@*****.**', 'First Last'); //Set who the message is to be sent to $mail->addAddress($to); //Set the subject line $mail->Subject = $subject; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body //$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); //Replace the plain text body with one created manually //$mail->AltBody = 'This is a plain-text message body'; //html body $mail->Body = $body; if (count($attachmentAssetIds) > 0) { foreach (Asset::getAllByCriteria('assetId in (' . implode(', ', array_fill(0, count($attachmentAssetIds), '?')) . ')', $attachmentAssetIds) as $asset) { //Attach an image file $mail->addAttachment($asset->getPath(), $asset->getFilename()); } } //send the message, check for errors if (!$mail->send()) { throw new CoreException('SENDING EMAIL ERROR: ' . $mail->ErrorInfo); } return true; }
public function syncProductAndProductCategory() { $cronStartDateTime = UDate::now(); $criteria = array("(sku != '' OR (mageId != '' AND mageId != 0))"); $param = array(); if (($lastUpdateDateTime = trim(SystemSettings::getSettings(SystemSettings::TYPE_PRODUCT_LAST_UPDATED))) !== '') { $criteria[] = "updated >= ?"; $param[] = $lastUpdateDateTime; } $counter = Product::countByCriteria(implode(" and ", $criteria), $param); if ($counter > 0) { $this->_mySoapClient = $this->_connect(); $this->syncAllProductCategory(); $productArray = Product::findByCriteria(implode(" and ", $criteria), $param); foreach ($productArray as $product) { $linkedCategories = array(); $product_categoryArray = Product_Category::getCategories($product); if (is_array($product_categoryArray) && count($product_categoryArray) > 0) { $linkedCategories = array_map(create_function('$a', 'return $a->getCategory()->getMageId();'), $product_categoryArray); } /// if no category is found, set the default to 1 /// if (count($linkedCategories) <= 0) { $linkedCategories = array(1); } $productData = $this->_generateProductData($product, $linkedCategories); if (($productMageId = trim($product->getMageId())) === '' || $productMageId === '0') { $attributeSets = $this->_mySoapClient->catalogProductAttributeSetList($session); $attributeSet = current($attributeSets); $productType = 'simple'; $newMageId = $this->_mySoapClient->catalogProductCreate($this->_session, $productType, $attributeSet->set_id, trim($product->getSku()), $productData); if (is_numeric($newMageId)) { $product->setMageId($newMageId)->save(); } else { $this->_handle_failed_product($product, $cronStartDateTime); } } else { // update product on magento $updated = $this->_mySoapClient->catalogProductUpdate($this->_session, $productMageId, $productData); if ($updated === false) { $this->_handle_failed_product($product, $cronStartDateTime, "update"); } } } } SystemSettings::addSettings(SystemSettings::TYPE_PRODUCT_LAST_UPDATED, $cronStartDateTime); //Debug::inspect($products); die(); }
/** * @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; }
/** * updating the shipping details * * @param unknown $sender * @param unknown $param */ public function updateShippingDetails($sender, $params) { $result = $error = $shippingInfoArray = array(); try { Dao::beginTransaction(); if (!isset($params->CallbackParameter->order) || !($order = Order::getByOrderNo($params->CallbackParameter->order->orderNo)) instanceof Order) { throw new Exception('System Error: invalid order passed in!'); } if (!$order->getStatus() instanceof OrderStatus || trim($order->getStatus()->getId()) !== trim(OrderStatus::ID_PICKED)) { throw new Exception('System Error: Order [' . $order->getOrderNo() . '] Is Not is PICKED status. Current status is [' . ($order->getStatus() instanceof OrderStatus ? $order->getStatus()->getName() : 'NULL') . ']'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('Error: there is no payment or payments has been cancelled!'); } if (!isset($params->CallbackParameter->shippingInfo)) { throw new Exception('System Error: invalid Shipping Info Details passed in!'); } $shippingInfo = $params->CallbackParameter->shippingInfo; if (!($courier = Courier::get($shippingInfo->courierId)) instanceof Courier) { throw new Exception('Invalid Courier Id [' . $shippingInfo->courierId . '] provided'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('This ' . $order->getType() . ' has NOT pass payment check yet, please let the accounting department know before further actions!'); } $notifyCust = isset($shippingInfo->notifyCust) && intval($shippingInfo->notifyCust) === 1 ? true : false; //$companyName = $shippingInfo->companyName; $contactName = $shippingInfo->contactName; $contactNo = $shippingInfo->contactNo; $shippingAddress = Address::create(trim($shippingInfo->street), trim($shippingInfo->city), trim($shippingInfo->region), trim($shippingInfo->country), trim($shippingInfo->postCode), trim($contactName), trim($contactNo)); $shipment = Shippment::create($shippingAddress, $courier, trim($shippingInfo->conNoteNo), new UDate(), $order, $contactName, trim($contactNo), trim($shippingInfo->noOfCartons), '0', StringUtilsAbstract::getValueFromCurrency(trim($shippingInfo->actualShippingCost)), isset($shippingInfo->deliveryInstructions) ? trim($shippingInfo->deliveryInstructions) : ''); $order->setStatus(OrderStatus::get(OrderStatus::ID_SHIPPED))->save(); $result['shipment'] = $shipment->getJson(); //add shipment information if ($notifyCust === true && $order->getIsFromB2B() === true) { $templateName = trim($shipment->getCourier()->getId()) === trim(Courier::ID_LOCAL_PICKUP) ? 'local_pickup' : $order->getStatus()->getName(); $notificationMsg = trim(OrderNotificationTemplateControl::getMessage($templateName, $order)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_SHIP, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->shipOrder($order, $shipment, array(), $notificationMsg, false, false); //push the status of the order to SHIPPed $emailToCustomer = trim($shipment->getCourier()->getId()) !== trim(Courier::ID_LOCAL_PICKUP); B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($order, $order->getStatus()->getMageStatus(), $notificationMsg, $emailToCustomer); if ($emailToCustomer === true) { $order->addComment('An email notification contains shippment information has been sent to customer for: ' . $order->getStatus()->getName(), Comments::TYPE_SYSTEM); } } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $error[] = $ex->getMessage(); } $params->ResponseData = StringUtilsAbstract::getJson($result, $error); }
private function updateMagentoPrice($price) { $product = Product::getBySku($this->sku); if (!$product instanceof Product) { throw new Exception('Invalid Product passed in. "' . $product . '" given.'); } $connector = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY)); if ($this->debug) { echo 'Connecting to Magento for Product ' . $product->getSku() . '(id=' . $product->getId() . ')' . "\n"; } $result = $connector->updateProductPrice($product->getSku(), $price); if ($result !== true && $this->debug === true) { echo print_r($result, true); } if ($result === true && $this->debug === true) { echo 'Magento Price Successfully updated to $' . $price . "\n"; } return $this; }
<?php ini_set('memory_limit', '1024M'); require_once dirname(__FILE__) . '/../../bootstrap.php'; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); echo "Begin downloadProductInfo from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; $newOnly = true; $debug = true; $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY)); $script->downloadProductInfo($newOnly, $debug); echo "Done downloadProductInfo from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
/** * Getting the view preferences * * @return multitype: */ private function _getViewPreference() { $now = new UDate('now', SystemSettings::getSettings(SystemSettings::TYPE_SYSTEM_TIMEZONE)); return array('ord_item.eta.from' => $now->format('Y-m-d 00:00:00'), 'ord_item.eta.to' => $now->format('Y-m-d 23:59:59')); }
/** * A product is shipped * * @param unknown $qty * @param string $comments * @param BaseEntityAbstract $entity * * @return Product */ public function shipped($qty, $comments = '', BaseEntityAbstract $entity = null) { $order = $entity instanceof Order ? $entity : ($entity instanceof OrderItem ? $entity->getOrder() : null); $newQty = ($originStockOnOrder = $this->getStockOnOrder()) - $qty; if ($newQty < 0 && intval($qty) > 0 && intval(SystemSettings::getSettings(SystemSettings::TYPE_ALLOW_NEGTIVE_STOCK)) !== 1) { throw new Exception('Product (SKU:' . $this->getSKU() . ') can NOT be pick, as there is not enough stock.'); } return $this->setStockOnOrder($newQty)->snapshotQty($entity instanceof BaseEntityAbstract ? $entity : $this, ProductQtyLog::TYPE_STOCK_MOVE_INTERNAL, 'Stock shipped. ' . ($order instanceof Order ? '[' . $order->getOrderNo() . ']' : ''))->save()->addLog('StockOnOrder(' . $originStockOnOrder . ' => ' . $this->getStockOnOrder() . ')', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__); }
function importNewProduct() { $debug = true; $newOnly = true; $script = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->processDownloadedProductInfo($newOnly, $debug); }
/** * Getting the root path of the asset files * * @return Ambigous <string, multitype:> */ public static function getRootPath() { return SystemSettings::getSettings(SystemSettings::TYPE_ASSET_ROOT_DIR); }
/** * * @param unknown $sender * @param unknown $params * @throws Exception */ public function addPayment($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->againstEntity) || !isset($param->CallbackParameter->againstEntity->entity) || !isset($param->CallbackParameter->againstEntity->entityId) || ($entityName = trim($param->CallbackParameter->againstEntity->entity)) === '' || !($entity = $entityName::get(trim($param->CallbackParameter->againstEntity->entityId))) instanceof $entityName) { throw new Exception('System Error: invalid Order or CreditNote provided. Can NOT get any payments at all.'); } if (!$entity instanceof Order && !$entity instanceof CreditNote) { throw new Exception('System Error: you can ONLY add payments for a Order or a CreditNote'); } if (!isset($param->CallbackParameter->payment) || !isset($param->CallbackParameter->payment->paidAmount) || ($paidAmount = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->payment->paidAmount))) === '' || !is_numeric($paidAmount)) { throw new Exception('System Error: invalid Paid Amount passed in!'); } if (!isset($param->CallbackParameter->payment->payment_method_id) || ($paymentMethodId = trim($param->CallbackParameter->payment->payment_method_id)) === '' || !($paymentMethod = PaymentMethod::get($paymentMethodId)) instanceof PaymentMethod) { throw new Exception('System Error: invalid Payment Method passed in!'); } $notifyCust = isset($param->CallbackParameter->payment->notifyCust) && intval($param->CallbackParameter->payment->notifyCust) === 1 ? true : false; $extraComment = ''; if (!isset($param->CallbackParameter->payment->extraComments) || ($extraComment = trim($param->CallbackParameter->payment->extraComments)) === '') { throw new Exception('Some comments for this payment is required.'); } //save the payment $newPayment = null; $entity = $entity->addPayment($paymentMethod, $paidAmount, $extraComment, new UDate(), $newPayment); $results['item'] = $newPayment->getJson(); //notify the customer if ($entity instanceof Order && $notifyCust === true && $entity->getIsFromB2B() === true) { $notificationMsg = trim(OrderNotificationTemplateControl::getMessage('paid', $entity)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($entity, OrderStatus::get(OrderStatus::ID_PICKED)->getMageStatus(), $notificationMsg, true); $comments = 'An email notification contains payment checked info has been sent to customer for: ' . $entity->getStatus()->getName(); Comments::addComments($entity, $comments, Comments::TYPE_SYSTEM); } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function processDownloadedProductInfo($newOnly = false, $debug = false) { $systemSetting = $newOnly === true ? SystemSettings::getByType(SystemSettings::TYPE_LAST_NEW_PRODUCT_PULL) : SystemSettings::getByType(SystemSettings::TYPE_LAST_PULL_PRODUCT_PULL); if (!$systemSetting instanceof SystemSettings) { throw new Exception('cannot get ' . ($newOnly === true ? 'TYPE_LAST_NEW_PRODUCT_PULL' : 'TYPE_LAST_PULL_PRODUCT_PULL') . ' in system setting'); } $cacheFile = $newOnly === true ? self::MAGE_PULL_NEW_FILE : self::MAGE_PULL_ALL_FILE; $contents = file($cacheFile); // handle extra long sku from magento, exceeding mysql sku length limit DaoMap::loadMap('Product'); $skuSizeLimit = DaoMap::$map['product']['sku']['size']; $totalCount = count($contents); if ($totalCount === 0) { if ($debug === true) { echo 'nothing from downloaded product info file ' . $cacheFile . '. exitting' . "\n"; } return $this; } $rowCount = 0; $sessionRotation = 10; foreach ($contents as $line) { try { if ($rowCount === 0 || $rowCount % $sessionRotation == 0) { $connector = CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY), true); } $pro = json_decode($line, true); if (!isset($pro['product_id']) || intval($pro['product_id']) === 0 || !isset($pro['sku']) || trim($pro['sku']) === '') { if ($debug === true) { echo 'invalid product_id from magento, skip current line' . PHP_EOL; } continue; } $mageId = $pro['product_id']; $created_at = $pro['created_at']; $updated_at = $pro['updated_at']; $sku = $pro['sku']; if (strlen($sku) > $skuSizeLimit) { if ($debug === true) { echo '***warnning***Magento product [' . $pro['product_id'] . ']' . $sku . ' created at ' . $created_at . ' updated at ' . $updated_at . ' sku length exceed system sku length limit of' . $skuSizeLimit . ', skipped' . "\n"; } continue; } if ($newOnly === true && ($product = Product::getBySku($sku)) instanceof Product) { if ($debug === true) { echo 'Product[' . $product->getId() . '] ' . $sku . ' already exist' . PHP_EOL; } $connector->removeLineFromFile($cacheFile, $line); continue; } if ($debug === true) { echo $rowCount . '/' . $totalCount . PHP_EOL; echo print_r($line, true) . PHP_EOL; } $attributeSetId = intval($pro['set']); $attributeSet = ProductAttributeSet::getByMageId($attributeSetId); if (!$attributeSet instanceof ProductAttributeSet) { if ($debug === true) { echo 'Magento product [' . $pro['product_id'] . ']' . $sku . ' created at ' . $created_at . ' updated at ' . $updated_at . 'magento attributeSetId ' . $attributeSet . ' cannot find a match in system ProductAttributeSet, skipped' . "\n"; } continue; } if ($debug === true) { echo "\n" . 'mageSetId:' . $attributeSetId . ' => systemSetId:' . $attributeSet->getId() . ', systemSetName:' . $attributeSet->getName() . "\n"; } $name = trim($pro['name']); $short_description = trim($pro['short_description']); if ($name === '') { if ($debug === true) { echo 'Magento product [' . $pro['product_id'] . ']' . $sku . ' created at ' . $created_at . ' updated at ' . $updated_at . 'has empty produ name from magento, I use short description "' . $short_description . '" for product name ' . $attributeSet . ' cannot find a match in system ProductAttributeSet, skipped' . "\n"; } } if ($short_description === '') { $short_description = $name; } $description = trim($pro['description']); if ($description === '') { $description = $short_description; } $weight = doubleval(trim($pro['weight'])); $statusId = trim($pro['status']); $systemStatusId = intval($statusId) === 2 ? ProductStatus::ID_DISABLED : ProductStatus::ID_ENABLED; $price = doubleval(trim($pro['price'])); $specialPrice = isset($pro['special_price']) ? trim($pro['special_price']) : ''; $specialPrice_From = isset($pro['special_from_date']) ? trim($pro['special_from_date']) : null; $specialPrice_To = isset($pro['special_to_date']) ? trim($pro['special_to_date']) : null; $transStarted = false; try { Dao::beginTransaction(); } catch (Exception $e) { $transStarted = true; } if (!($product = Product::getBySku($sku)) instanceof Product) { $product = Product::create($sku, $name); Log::logging(0, get_class($connector), '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) . '" 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($systemStatusId)->getName() . '"' . "\n"; echo "\t" . 'Manufacturer: name="' . $connector->getManufacturerName(trim($pro['manufacturer']))->getName() . '"' . "\n"; echo "\t" . 'Price: "' . $price . '"' . "\n"; echo "\t" . 'Weight: "' . $weight . '"' . "\n"; } $product->setName($name)->setMageId($mageId)->setAttributeSet($attributeSet)->setShortDescription($short_description); $connector->_updateFullDescription($product, $description); $product->setIsFromB2B(true)->setStatus(ProductStatus::get($systemStatusId))->setSellOnWeb(true)->setManufacturer($connector->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 (isset($pro['supplier']) && ($supplierName = trim($pro['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) { if ($debug === true) { echo 'Magento product [' . $pro['product_id'] . ']' . $sku . ' created at ' . $created_at . ' updated at ' . $updated_at . 'magento category id ' . $cateMageId . ' cannot find a match in system ProductCategory, skipped' . "\n"; } continue; } $product->addCategory($category); } } if ($transStarted === false) { Dao::commitTransaction(); $connector->removeLineFromFile($cacheFile, $line); $systemSetting->setValue($newOnly === true ? $created_at : $updated_at)->save(); if ($debug === true) { echo 'system setting ' . trim($systemSetting->getType()) . ' changed to ' . trim($newOnly === true ? $created_at : $updated_at) . PHP_EOL; } $rowCount++; } else { echo "\n" . '***ERROR***' . "transStarted === true, nothing is commited! \n"; } if ($rowCount === 0 || $rowCount % $sessionRotation == 0) { if ($debug === true) { echo 'session => ' . $connector->_session . PHP_EOL; } } } catch (Exception $ex) { if ($transStarted === false) { Dao::rollbackTransaction(); } echo "\n" . '***ERROR***' . $ex->getMessage() . "\n" . $ex->getTraceAsString() . "\n"; } } }
<?php require_once dirname(__FILE__) . '/../../bootstrap.php'; echo "Begin importProductCategories from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); CatelogConnector::getConnector(B2BConnector::CONNECTOR_TYPE_CATELOG, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->importProductCategories(); echo "Done importProductCategories from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
/** * The row with default value * * @param UDate $lastUpdatedInDB * @param Product $product * @param string $preFix * @param bool $debug * * @return multitype:string number */ private static function _getRowWithDefaultValues(UDate $lastUpdatedInDB, Product $product = null, $preFix = '', $debug = false) { $attributeSetDefault = 'Default'; $attributeSetName = $attributeSetDefault; $enabled = true; $sku = $statusId = $productName = $rrpPrice = $weight = $shortDescription = $fullDecription = $supplierName = $supplierCode = $manufacturerName = $asNewFrom = $asNewTo = $specialPrice = $specialPriceFromDate = $specialPriceToDate = ''; $categoryIds = array(2); //default category if ($product instanceof Product) { $sku = trim($product->getSku()); $productName = trim($product->getName()); $shortDescription = trim($product->getShortDescription()); $asNewFrom = $product->getAsNewFromDate() instanceof UDate ? $product->getAsNewFromDate()->format('Y-m-d H:i:sP') : ''; $asNewTo = $product->getAsNewToDate() instanceof UDate ? $product->getAsNewToDate()->format('Y-m-d H:i:sP') : ''; $weight = trim($product->getWeight()); if ($product->getAttributeSet() instanceof ProductAttributeSet) { $attributeSetName = $product->getAttributeSet()->getName(); self::_log('-- attributeSetName ', __CLASS__ . '::' . __FUNCTION__ . " attributeSetName={$attributeSetName}", $preFix); } //RRP if (($rrp = $product->getRRP()) instanceof ProductPrice) { $rrpPrice = StringUtilsAbstract::getValueFromCurrency($rrp->getPrice()); } //special price if (($specialPriceObj = $product->getNearestSpecialPrice()) instanceof ProductPrice) { $specialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); if ($specialPrice == 0) { $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } } else { // delete the special price //$specialPrice = StringUtilsAbstract::getValueFromCurrency('99999999'); //$specialPrice = '9999999'; $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } // if it is the daily promotion time then overwrite the special price with the daily special price $isDailyPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISDAILYPROMOTIONTIME)); if ($isDailyPromotionTime === 1) { // get daily promotion price if (($specialPriceObj = $product->getDailySpecialPrice()) instanceof ProductPrice) { $dailySpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($dailySpecialPrice != 0) { $specialPrice = $dailySpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } // if it is the daily promotion time then overwrite the special price with the daily special price $isWeekendPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISWEEKENDPROMOTIONTIME)); if ($isWeekendPromotionTime === 1) { // get weekend promotion price if (($specialPriceObj = $product->getWeekendSpecialPrice()) instanceof ProductPrice) { $weekendSpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($weekendSpecialPrice != 0) { $specialPrice = $weekendSpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } //full description if (($asset = Asset::getAsset($product->getFullDescAssetId())) instanceof Asset) { //$fullDecription = '"' . $asset->read() . '"'; $fullDecription = $asset->read(); } //supplier if (count($supplierCodes = SupplierCode::getAllByCriteria('productId = ?', array($product->getId()), true, 1, 1)) > 0) { $supplierName = ($supplier = $supplierCodes[0]->getSupplier()) instanceof Supplier ? $supplier->getName() : ''; $supplierCode = trim($supplierCodes[0]->getCode()); } //Manufacturer if ($product->getManufacturer() instanceof Manufacturer) { $manufacturerName = trim($product->getManufacturer()->getName()); } //disable or enabled if (intval($product->getActive()) === 0 || intval($product->getSellOnWeb()) === 0) { $enabled = false; } else { if ($product->getStatus() instanceof ProductStatus && intval($product->getStatus()->getId()) === ProductStatus::ID_DISABLED) { $enabled = false; } } //categories if (count($categories = Product_Category::getAllByCriteria('productId = ?', array($product->getId()))) > 0) { foreach ($categories as $category) { if (!$category->getCategory() instanceof ProductCategory || ($mageCateId = trim($category->getCategory()->getMageId())) === '') { continue; } if (trim($attributeSetName) === $attributeSetDefault && ($productAttributeSet = $category->getCategory()->getProductAttributeSet()) instanceof ProductAttributeSet) { $attributeSetName = trim($productAttributeSet->getName()); } $categoryIds[] = $mageCateId; } } //ProductStatus if ($product->getStatus() instanceof ProductStatus) { $statusId = $product->getStatus()->getName(); } } $categoryIds = array_unique($categoryIds); return array("store" => 'default', "websites" => 'base', "attribute_set" => $attributeSetName, "type" => 'simple', "category_ids" => implode(',', $categoryIds), "sku" => $sku, "name" => $productName, "price" => $rrpPrice, "special_from_date" => $specialPriceFromDate, "special_to_date" => $specialPriceToDate, "special_price" => $specialPrice, "news_from_date" => $asNewFrom, "news_to_date" => $asNewTo, "status" => intval($enabled) === 1 ? 1 : 2, "visibility" => 4, "tax_class_id" => 2, "description" => $fullDecription, "short_description" => $shortDescription, "supplier" => $supplierName, "man_code" => '', "sup_code" => $supplierCode, "meta_title" => '', "meta_description" => '', "manufacturer" => $manufacturerName, "url_key" => '', "url_path" => '', "custom_design" => '', "page_layout" => '', "country_of_manufacture" => '', "msrp_enabled" => '', "msrp_display_actual_price_type" => '', "meta_keyword" => '', "custom_layout_update" => '', "custom_design_from" => '', "custom_design_to" => '', "weight" => $weight, "msrp" => 'Use config', "gift_wrapping_price" => '', "qty" => 99, "min_qty" => 99, "use_config_min_qty" => 99, "is_qty_decimal" => '', "backorders" => '', "use_config_backorders" => '', "min_sale_qty" => '', "use_config_min_sale_qty" => '', "max_sale_qty" => '', "use_config_max_sale_qty" => '', "all_ln_stock" => $statusId, "is_in_stock" => 1, "low_stock_date" => '', "notify_stock_qty" => '', "use_config_notify_stock_qty" => '', "manage_stock" => '', "use_config_manage_stock" => '', "stock_status_changed_auto" => '', "use_config_qty_increments" => '', "qty_increments" => '', "use_config_enable_qty_inc" => '', "enable_qty_increments" => '', "is_decimal_divided" => '', "stock_status_changed_automatically" => '', "use_config_enable_qty_increments" => '', "image" => '', "small_image" => '', "thumbnail" => '', "media_gallery" => '', "is_recurring" => '', "media_gallery_reset" => 0); }
/** * 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; }
function importOrder() { $script = B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->importOrders(); echo implode($script->getLogs()); }