/** * * @param Product $product * @param unknown $cronStartDateTime * @param string $syncType */ private function _handle_failed_product(Product $product, $cronStartDateTime, $syncType = "insert") { $date = new UDate(trim($cronStartDateTime)); $date->modify('+1 second'); $product->setUpdated($date)->save(); Log::LogEntity($product, 'Product Sync failed with Magento. ' . $syncType . ' operation failed', Log::TYPE_SYSTEM); }
private function _getPurchaseSeries($productId, $from, $to, $type = null) { $sql = 'select unitPrice, created from `purchaseorderitem` where active = 1 AND productId = :pid AND created >=:from and created <= :to order by created asc'; $result = Dao::getResultsNative($sql, array('pid' => trim($productId), 'from' => trim($from), 'to' => trim($to))); $return = array(); foreach ($result as $row) { $created = new UDate(trim($row['created'])); $return[] = array($created->format('U') * 1000, (double) trim($row['unitPrice']) * 1.1); } return $return; }
private function _getXnames($from, $to, $step) { $names = array(); $dateFrom = new UDate(trim($from)); $dateTo = new UDate(trim($to)); do { $from = new UDate(trim($dateFrom)); $to = new UDate(trim($dateFrom->modify($step))); $names[trim($from->format('d/M/y'))] = array('from' => trim($from), 'to' => trim($to)); } while ($dateFrom->before($dateTo)); return $names; }
private function _getXnames() { $names = array(); $_12mthAgo = new UDate(); $_12mthAgo->modify('-12 month'); for ($i = 0; $i < 12; $i++) { $from = new UDate(trim($_12mthAgo->format('Y-m-01 00:00:00'))); $to = new UDate(trim($_12mthAgo->modify('+1 month')->format('Y-m-01 00:00:00'))); $names[trim($from->format('M/Y'))] = array('from' => trim($from), 'to' => trim($to)); } return $names; }
public function getLatestETAs($sender, $param) { $result = $error = array(); try { $pageNo = $this->pageNumber; $pageSize = $this->pageSize; if (isset($param->CallbackParameter->pagination)) { $pageNo = $param->CallbackParameter->pagination->pageNo; $pageSize = $param->CallbackParameter->pagination->pageSize; } $notSearchStatusIds = array(OrderStatus::ID_CANCELLED, OrderStatus::ID_PICKED, OrderStatus::ID_SHIPPED); OrderItem::getQuery()->eagerLoad('OrderItem.order', 'inner join', 'ord', 'ord.id = ord_item.orderId and ord.active = 1'); $stats = array(); $oiArray = OrderItem::getAllByCriteria("(eta != '' and eta IS NOT NULL and eta != ? and ord.statusId not in (" . implode(',', $notSearchStatusIds) . "))", array(trim(UDate::zeroDate())), true, $pageNo, $pageSize, array("ord_item.eta" => "ASC", "ord_item.orderId" => "DESC"), $stats); $result['pagination'] = $stats; $result['items'] = array(); foreach ($oiArray as $oi) { if (!$oi->getProduct() instanceof product) { continue; } $tmp['eta'] = trim($oi->getEta()); $tmp['orderNo'] = $oi->getOrder()->getOrderNo(); $tmp['sku'] = $oi->getProduct() instanceof Product ? $oi->getProduct()->getSku() : ''; $tmp['productName'] = $oi->getProduct()->getName(); $tmp['id'] = $oi->getId(); $tmp['orderId'] = $oi->getOrder()->getId(); $result['items'][] = $tmp; } } catch (Exception $ex) { $error[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($result, $error); }
private static function _findAllZombieAssets() { $start = self::_debug("Start to run " . __FUNCTION__ . ' =================== ', self::NEW_LINE, "\t"); $overDueDate = UDate::now()->format(self::ASSET_OVERDUE_TIME); $sql = "select a.assetId from asset a left join product p on (p.fullDescAssetId = a.assetId) where p.id is null and type in(?, ?) "; $result = Dao::getResultsNative($sql, array(trim(Asset::TYPE_PRODUCT_DEC), trim(Asset::TYPE_PRODUCT_IMG))); $resultCount = count($result); self::_debug("Found " . $resultCount . ': ', " ", "\t\t"); $assetIds = array(); for ($i = 0; $i < $resultCount; $i++) { $assetIds[] = $result[$i]['assetId']; } self::_debug(implode(', ', $assetIds)); return $assetIds; }
private static function _orderItems(Order $order) { $msg = "<div>"; $msg .= "<div>Thank you for your support, we have received your following order, and it is currently in processing.</div>"; $msg .= "<div>Here are the item information/status on your order, our logistics will have them shipped out as soon as possible.</div>"; $msg .= "<div>If you have any item with long ETA waiting time and you want to ship part of your order first, please email <a href='mailto:sales@budgetpc.com.au'>sales@budgetpc.com.au</a> and quote your order number when you call.</div>"; $msg .= "<div style='margin: 10px 0 10px 0'>"; $msg .= '<table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%">'; $msg .= "<thead>"; $msg .= "<tr style='background:#eeeeee; height:23px;'>"; $msg .= "<td width='*'>Item</td>"; $msg .= "<td width='30%'>SKU</td>"; $msg .= "<td width='10%' style='text-align:center;'>Qty</td>"; $msg .= "<td width='20%'>Status</td>"; $msg .= "</tr>"; $msg .= "</thead>"; $msg .= "<tbody>"; foreach ($order->getOrderItems() as $item) { $msg .= "<tr style='height:18px; border-bottom: 1px #cccccc solid;'>"; $msg .= "<td>" . $item->getProduct()->getName() . "</td>"; $msg .= "<td>" . $item->getProduct()->getSku() . "</td>"; $msg .= "<td style='text-align:center;'>" . $item->getQtyOrdered() . "</td>"; $msg .= "<td>" . (trim($item->getEta()) === trim(UDate::zeroDate()) ? 'In Stock' : 'ETA: ' . $item->getEta()->format('d F Y')) . "</td>"; $msg .= "</tr>"; } $msg .= "</tbody>"; $msg .= "</table>"; $msg .= "</div>"; $msg .= "</div>"; return $msg; }
public function getInvDate() { return $this->order->getInvDate() == UDate::zeroDate() ? '' : $this->order->getInvDate()->format('d/M/Y'); }
/** * log all the messages * * @param string $msg * @param string $funcName * @param string $preFix * @param string $postFix * * @return APIService */ public function log($msg, $funcName = '', $preFix = '', $postFix = "\n") { $log = (trim($msg) === '' ? '' : UDate::now() . ': ') . $preFix . $msg . ($funcName === '' ? '' : ' [' . $funcName . '] ') . $postFix; if (is_file($this->_logFile)) { file_put_contents($this->_logFile, $log, FILE_APPEND); } return $this; }
/** * Getting the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function getItems($sender, $param) { $results = $errors = array(); try { $class = trim($this->_focusEntity); $pageNo = 1; $pageSize = DaoQuery::DEFAUTL_PAGE_SIZE; if (isset($param->CallbackParameter->pagination)) { $pageNo = $param->CallbackParameter->pagination->pageNo; $pageSize = $param->CallbackParameter->pagination->pageSize; } $serachCriteria = isset($param->CallbackParameter->searchCriteria) ? json_decode(json_encode($param->CallbackParameter->searchCriteria), true) : array(); $where = array(1); $params = array(); if (isset($serachCriteria['taskId']) && trim($taskId = $serachCriteria['taskId']) !== '') { $where[] = 'id like :taskId'; $params['taskId'] = '%' . $taskId . '%'; } if (isset($serachCriteria['ord.id']) && trim($orderIds = $serachCriteria['ord.id']) !== '' && count($orderIds = explode(',', $orderIds)) > 0) { $params['entityName'] = 'Order'; $keys = array(); foreach ($orderIds as $index => $orderId) { $keys[] = ":" . ($key = "entityId" . $index); $params[$key] = $orderId; } $where[] = 'fromEntityName = :entityName and fromEntityId in (' . implode(', ', $keys) . ')'; } if (isset($serachCriteria['techId']) && trim($techIds = $serachCriteria['techId']) !== '' && count($techIds = explode(',', $techIds)) > 0) { $keys = array(); foreach ($techIds as $index => $techId) { $keys[] = ":" . ($key = "techId" . $index); $params[$key] = $techId; } $where[] = 'technicianId in (' . implode(', ', $keys) . ')'; } if (isset($serachCriteria['customer.id']) && trim($customerIds = $serachCriteria['customer.id']) !== '' && count($customerIds = explode(',', $customerIds)) > 0) { $keys = array(); foreach ($customerIds as $index => $customerId) { $keys[] = ":" . ($key = "customerId" . $index); $params[$key] = $customerId; } $where[] = 'customerId in (' . implode(', ', $keys) . ')'; } if (isset($serachCriteria['statusId']) && count($statusIds = $serachCriteria['statusId']) > 0) { $keys = array(); foreach ($statusIds as $index => $statusId) { $keys[] = ":" . ($key = "statusId" . $index); $params[$key] = $statusId; } $where[] = 'statusId in (' . implode(', ', $keys) . ')'; } if (isset($serachCriteria['dueDate_from']) && ($dueDate_from = new UDate($serachCriteria['dueDate_from'])) !== false) { $where[] = 'dueDate >= :dueDateFrom'; $params['dueDateFrom'] = $dueDate_from->format('Y-m-d') . ' 00:00:00'; } if (isset($serachCriteria['dueDate_to']) && ($dueDate_to = new UDate($serachCriteria['dueDate_to'])) !== false) { $where[] = 'dueDate <= :dueDateTo'; $params['dueDateTo'] = $dueDate_from->format('Y-m-d') . ' 23:59:59'; } $stats = array(); $objects = $class::getAllByCriteria(implode(' AND ', $where), $params, false, $pageNo, $pageSize, array('dueDate' => 'asc'), $stats); $results['pageStats'] = $stats; $results['items'] = array(); foreach ($objects as $obj) { $results['items'][] = $obj->getJson(); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * (non-PHPdoc) * @see BaseEntityAbstract::postSave() */ public function postSave() { if ($this->getOrderItem() instanceof OrderItem) { if (count($serialItems = self::getAllByCriteria('orderItemId = ?', array($this->getOrderItem()->getId()))) > 0) { $totalUnitCostForOrderItem = 0; $totalNoOfKits = 0; foreach ($serialItems as $serialItem) { if (($kit = $serialItem->getKit()) instanceof Kit) { $totalUnitCostForOrderItem = $totalUnitCostForOrderItem + $kit->getCost(); $totalNoOfKits = $totalNoOfKits + 1; if (!$kit->getSoldOnOrder() instanceof Order) { $kit->setSoldOnOrder($this->getOrderItem()->getOrder()); } if (!$kit->getSoldToCustomer() instanceof Customer) { $kit->setSoldToCustomer($this->getOrderItem()->getOrder()->getCustomer()); } if (trim($kit->getSoldDate()) === trim(UDate::zeroDate())) { $kit->setSoldDate(new UDate()); } if (!$kit->getShippment() instanceof Shippment && count($shippments = $this->getOrderItem()->getOrder()->getShippments()) > 0) { $kit->setShippment($shippments[0]); } $kit->save(); } } $this->getOrderItem()->setUnitCost(intval($totalNoOfKits) === 0 ? 0 : $totalUnitCostForOrderItem / $totalNoOfKits)->reCalMargin(); } } }
protected static function _getAttachedFileName() { $now = new UDate(); $now->setTimeZone('Australia/Melbourne'); return 'open_invoice_' . $now->format('Y_m_d_H_i_s') . '.csv'; }
/** * (non-PHPdoc) * @see BaseEntity::__loadDaoMap() */ public function __loadDaoMap() { DaoMap::begin($this, 'pro_price'); DaoMap::setManyToOne('product', 'Product', 'pro_price_pro'); DaoMap::setManyToOne('type', 'ProductPriceType', 'pro_price_type'); DaoMap::setIntType('price', 'double', '10,4'); DaoMap::setDateType('start', 'datetime', false, trim(UDate::zeroDate())); DaoMap::setDateType('end', 'datetime', false, trim(UDate::maxDate())); parent::__loadDaoMap(); DaoMap::createIndex('price'); DaoMap::createIndex('start'); DaoMap::createIndex('end'); DaoMap::commit(); }
/** * @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; }
private function _getNewPrice($updateMagento) { $result = null; $sku = $this->sku; $updateMagento = $updateMagento === true ? true : false; $product = Product::getBySku($sku); if (!$product instanceof Product) { throw new Exception('Invalid sku passed in, "' . $sku . '" given'); } $min = PriceMatchMin::getBySku($sku); $rule = ProductPriceMatchRule::getByProduct($product); $prices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP)); if (count($prices) === 0) { $newPrice = ProductPrice::create($product, ProductPriceType::get(ProductPriceType::ID_RRP), 0); $prices = array($newPrice); } // if(($magePrice = $this->_getMagentoProductPrice($sku)) !== null) // $prices[0]->setPrice($magePrice)->save(); $myPrice = $prices[0]->getPrice(); if (!$min instanceof PriceMatchMin) { $min = PriceMatchMin::create($this->sku); } if ($rule instanceof ProductPriceMatchRule) { $company = $rule->getCompany(); $price_from = $rule->getPrice_from(); $price_to = $rule->getPrice_to(); $offset = $rule->getOffset(); $where = array(1); $params = array(); $where[] = "minId = ? "; $params[] = $min->getId(); $from_date = UDate::now('Australia/Melbourne')->setTime(0, 0, 0)->setTimeZone('UTC'); $to_date = UDate::now('Australia/Melbourne')->setTime(23, 59, 59)->setTimeZone('UTC'); $where[] = "created >= ? "; $params[] = $from_date; $where[] = "created <= ? "; $params[] = $to_date; $companies = $company->getAllAlias(); $companyIds = array_map(create_function('$a', 'return $a->getId();'), $companies); $where[] = 'companyId IN (' . implode(", ", array_fill(0, count($companyIds), "?")) . ')'; $params = array_merge($params, $companyIds); //calculate target compatitor price $records = PriceMatchRecord::getAllByCriteria(implode(' AND ', $where), $params, true, null, DaoQuery::DEFAUTL_PAGE_SIZE, array('price' => 'asc')); $base_price = null; foreach ($records as $record) { if ($base_price === null || doubleval($record->getPrice()) !== doubleval(0) && doubleval($record->getPrice()) < doubleval($base_price)) { $base_price = doubleval($record->getPrice()); } } if ($base_price !== null) { if ($price_from !== null) { if (strpos($price_from, '%') !== false) { $price_from = $base_price - $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_from))); } else { $price_from = $base_price - doubleval($price_from); } if (doubleval($price_from) <= doubleval(0)) { $price_from = doubleval(0); } } if ($price_to !== null) { if (strpos($price_to, '%') !== false) { $price_to = $base_price + $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_to))); } else { $price_to = $base_price + doubleval($price_to); } } // check if in range if (($price_from === null || $myPrice >= $price_from) && ($price_to === null || $myPrice <= $price_to)) { $result = $base_price; // apply offset if ($offset !== null) { if (strpos($offset, '%') !== false) { $result = $result + $result * doubleval(0.01 * doubleval(str_replace('%', '', $offset))); } else { $result = $result + doubleval($offset); } } // set product price if (isset($prices[0]) && $prices[0] instanceof ProductPrice) { $newmatchprice = doubleval($result); if ($newmatchprice > 0) { $oldPrice = $prices[0]->getPrice(); echo 'update price from old price : ' . $oldPrice . ' to new price :' . $newmatchprice . "\n"; $prices[0]->setPrice(doubleval($result))->save()->addLog('PriceMatch change price from $' . $oldPrice . 'to new price $' . $result, Log::TYPE_SYSTEM); // if($updateMagento === true) // $this->updateMagentoPrice(doubleval($result)); } else { echo 'not update price because new match price is 0 ( ' . $newmatchprice . ' )' . "\n"; } } } } else { if ($this->debug === true) { echo "cannot find price for PriceMatchCompany " . $company->getCompanyName() . ', ' . $product->getSku() . '(id=' . $product->getId() . ', min(id=' . $min->getId() . '), records found:' . count($records) . "\n"; } } if ($this->debug === true) { echo 'new price= ' . ($result === null ? 'N/A' : $result) . ', my price= ' . (isset($myPrice) ? $myPrice : 'N/A') . ', ' . $company->getCompanyName() . ' price= ' . $base_price . ', matching range=[' . $price_from . ',' . $price_to . '], offset=' . ($offset === null ? 'null' : $offset) . "\n"; } } elseif ($this->debug === true) { echo ($min instanceof PriceMatchMin ? '' : 'Cannot find result on StaticIce for all known PriceMatchCompanies') . ($rule instanceof ProductPriceMatchRule ? '' : 'cannot find ProductPriceMatchRule for product ' . $product->getSku() . '(id=' . $product->getId() . ')') . "\n"; } return $result; }
/** * create for PriceMatchRecord * * @param PriceMatchCompany $company * @param PriceMatchMin $min * @param string $price * @param string $url * @param string $name * @throws Exception */ public static function create(PriceMatchCompany $company, PriceMatchMin $min, $price, $url = '', $name = '') { if (abs(doubleval($price)) === 0.0 || doubleval($price) < 0.0 || trim($price) === '') { throw new Exception('price must be positive, "' . $price . '" given'); } $price = doubleval($price); $from_date = UDate::now('Australia/Melbourne')->setTime(0, 0, 0)->setTimeZone('UTC'); $to_date = UDate::now('Australia/Melbourne')->setTime(23, 59, 59)->setTimeZone('UTC'); if (count($i = self::getAllByCriteria('companyId = ? and minId = ? and created >= ? and created <= ?', array($company->getId(), $min->getId(), $from_date, $to_date), true, 1, 1, array('id' => 'desc'))) > 0) { $entity = $i[0]; } else { $entity = new self(); } $entity->setCompany($company)->setMin($min)->setPrice($price)->setUrl(trim($url))->setName(trim($name))->save(); return $entity; }
/** * (non-PHPdoc) * @see TreeEntityAbstract::preSave() */ public function preSave() { if (!$this->getProduct() instanceof Product) { throw new EntityException('A product needed to create a kit!'); } if (trim($this->soldDate) === '') { $this->setSoldDate(UDate::zeroDate()); } if ($this->getProduct()->getIsKit() !== true) { throw new EntityException('The product of the kit needs to have the flag IsKit ticked.'); } if (trim($this->getId()) !== '') { if (self::countByCriteria('id = ? and productId != ?', array($this->getId(), $this->getProduct()->getId())) > 0) { throw new EntityException('You can NOT change the product of the KIT[' . $this->getBarcode() . '] once it is created.'); } $origKit = self::get($this->getId()); $this->_changeLog('soldToCustomer', 'getName', $origKit, 'Customer')->_changeLog('soldDate', '__toString', $origKit, '')->_changeLog('soldOnOrder', 'getOrderNo', $origKit, 'Order')->_changeLog('shippment', 'getId', $origKit, 'Shippment'); } }
$rows = count($productIds); echo "--- Got ({$rows}) products having price matching rules !"; foreach ($productIds as $row) { try { $output = ''; $timeout = 60; // in seconds $cmd = 'php ' . dirname(__FILE__) . '/pricematch.php ' . $row['id']; $output = ExecWaitTimeout($cmd, $timeout); // exec($cmd, $output); echo print_r($output, true) . "\n"; } catch (Exception $e) { echo $e->getMessage() . "\n"; } } echo "End at MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; /** * Execute a command and kill it if the timeout limit fired to prevent long php execution * * @see http://stackoverflow.com/questions/2603912/php-set-timeout-for-script-with-system-call-set-time-limit-not-working * * @param string $cmd Command to exec (you should use 2>&1 at the end to pipe all output) * @param integer $timeout * @return string Returns command output */ function ExecWaitTimeout($cmd, $timeout = 5) { echo $cmd . "\n"; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $timeout += time();
/** * output new products list * * @param string $msg * @param string $funcName * @param string $preFix * @param string $postFix * * @return */ private function log_product($type, $msg, $funcName = '', $preFix = '', $postFix = "\n") { $maxsize = 5 * 1024 * 1024; //Max filesize in bytes (e.q. 5MB) $dir = "/tmp/"; if ($type === "NEW") { $filename = "new_productlist.log"; } elseif ($type === "UPDATE") { $filename = "update_productlist.log"; } else { $filename = "skip_productlist.log"; } $productfile = $dir . $filename; $log = (trim($msg) === '' ? '' : UDate::now() . ': ') . $preFix . $msg . ($funcName === '' ? '' : ' [' . $funcName . '] ') . $postFix; if (file_exists($productfile) && filesize($productfile) > $maxsize) { $nb = 1; $logfiles = scandir($dir); foreach ($logfiles as $file) { $tmpnb = substr($file, strlen($filename) - 1); if ($nb < $tmpnb) { $nb = $tmpnb; } } rename($dir . $filename, $dir . $filename . ($nb + 1)); } if (!is_file($productfile)) { file_put_contents($productfile, 'Init log file: ' . $productfile . '>>>>' . "\n"); } file_put_contents($productfile, $log, FILE_APPEND); }
/** * Getting all the entities by criteria * * @param string $where * @param array $params * @param bool $activeOnly * @param int $pageNo * @param int $pageSize * @param array $orderArray * * @throws Exception * @return string * @soapmethod */ public function getAll($where = '', $params = array(), $activeOnly = null, $pageNo = null, $pageSize = null, $orderArray = array()) { $response = $this->_getResponse(UDate::now()); try { $className = trim($this->_entityName); if (!class_exists($className)) { throw new Exception("Entity not exsits: " . $className); } $orderArray = $orderArray === null ? array() : $orderArray; $pageSize = $pageSize === null ? DaoQuery::DEFAUTL_PAGE_SIZE : $pageSize; $activeOnly = $activeOnly === null ? true : $activeOnly; $where = $where === null ? '' : $where; if (trim($where) === '') { $instances = $className::getAll($activeOnly, $pageNo, $pageSize, $orderArray); } else { $instances = $className::getAllByCriteria(trim($where), $params, $activeOnly, $pageNo, $pageSize, $orderArray); } $jsonArray = array(); foreach ($instances as $instance) { $jsonArray[] = $instance->getJson(); } $this->addCData($className . '_array', json_encode($jsonArray), $response); $response['status'] = self::RESULT_CODE_SUCC; } catch (Exception $e) { $response['status'] = self::RESULT_CODE_FAIL; $this->addCData('error', $e->getMessage(), $response); } return trim($response->asXML()); }
<?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";
public function testCheckFormat_notExisting() { $this->assertFalse(\UDate::checkDate('DD/MM/YYYY', '31/02/2013')); }
public function clearETA($sender, $param) { $results = $errors = array(); try { if (!isset($param->CallbackParameter->item_id) || !($item = OrderItem::get($param->CallbackParameter->item_id)) instanceof OrderItem) { throw new Exception('System Error: invalid order item provided!'); } if (!isset($param->CallbackParameter->comments) || ($comments = trim($param->CallbackParameter->comments)) === '') { $comments = ''; } Dao::beginTransaction(); //saving the order item $item->setETA(UDate::zeroDate())->addComment('Clearing the ETA: ' . $comments); $order = $item->getOrder(); $sku = $item->getProduct()->getSku(); $order->addComment('Clearing the ETA for product (' . $sku . '): ' . $comments, Comments::TYPE_PURCHASING); $item->save(); //check to see whether we need to update the order as well $allChecked = true; foreach ($order->getOrderItems() as $orderItems) { if (trim($orderItems->getETA()) !== trim(UDate::zeroDate())) { $allChecked = false; } } if ($allChecked === true) { $order->addComment('Auto Push this order status from [' . $order->getStatus() . '] to [' . OrderStatus::ID_ETA . '], as the last ETA cleared', Comments::TYPE_SYSTEM); $order->setStatus(OrderStatus::get(OrderStatus::ID_STOCK_CHECKED_BY_PURCHASING)); } $order->save(); $results = $item->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Logging * * @param string $msg * @param string $funcName * @param string $preFix * @param UDate $start * @param string $postFix * * @return UDate */ private static function _log($msg, $funcName = '', $preFix = "", UDate $start = null, $postFix = "\r\n") { $now = new UDate(); $timeElapsed = ''; if ($start instanceof UDate) { $timeElapsed = $now->diff($start); $timeElapsed = ' TOOK (' . $timeElapsed->format('%s') . ') seconds '; } $nowString = ''; if (trim($msg) !== '') { $nowString = ' [' . trim($now) . '] '; } $logMsg = $preFix . $msg . $nowString . $timeElapsed . ($funcName !== '' ? ' ' . $funcName . ' ' : '') . $postFix; echo $logMsg; if (is_file(self::$_logFile)) { file_put_contents(self::$_logFile, $logMsg, FILE_APPEND); } return $now; }
<?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";
<?php /** * run this one BEFORE run attribute pull */ require_once dirname(__FILE__) . '/../../bootstrap.php'; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); echo "Begin importProductAttributeSets from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n"; 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))->importProductAttributeSets(); echo "Done importProductAttributeSets from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
/** * Test if the date is not equal to the date passed in * * @param UDate $dateTime The UDate object that we are compare with * * @return bool */ public function notEqual(UDate $dateTime) { return $this->getUnixTimeStamp() !== $dateTime->getUnixTimeStamp(); }
/** * 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')); }
/** * 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; }
/** * (non-PHPdoc) * @see BaseEntityAbstract::postSave() */ public function postSave() { if (trim($this->getReceivedDate()) !== trim(UDate::zeroDate())) { if (self::countByCriteria('RMAId = ? and receivedDate = ?', array($this->getRMA()->getId(), trim(UDate::zeroDate()))) > 0) { $this->getRMA()->setStatus(RMA::STATUS_RECEIVING)->save()->addComment('Setting Status to "' . RMA::STATUS_RECEIVING . '", as received one of items'); } else { $this->getRMA()->setStatus(RMA::STATUS_RECEIVED)->save()->addComment('Setting Status to "' . RMA::STATUS_RECEIVED . '", as no more item to receive'); } } }