/**
  * Getting The end javascript
  *
  * @return string
  */
 protected function _getEndJs()
 {
     $js = parent::_getEndJs();
     $searchCriteria = array();
     $searchCriteria['productId'] = isset($_REQUEST['productid']) ? trim($_REQUEST['productid']) : '';
     $dateFrom = isset($_REQUEST['from']) ? trim($_REQUEST['from']) : trim(UDate::now()->modify('-11 month'));
     $dateTo = isset($_REQUEST['to']) ? trim($_REQUEST['to']) : trim(UDate::now());
     $searchCriteria['dateRange'] = array('from' => $dateFrom, 'to' => $dateTo);
     $js .= 'pageJs';
     $js .= '.load(' . json_encode($searchCriteria) . ');';
     return $js;
 }
 /**
  * Getting The end javascript
  *
  * @return string
  */
 protected function _getEndJs()
 {
     $js = parent::_getEndJs();
     $searchCriteria = array();
     $searchCriteria['productIds'] = isset($_REQUEST['productids']) ? explode(',', str_replace(' ', '', $_REQUEST['productids'])) : array();
     $dateStepBy = isset($_REQUEST['step']) ? trim($_REQUEST['step']) : '+1 week';
     $dateFrom = isset($_REQUEST['from']) ? trim($_REQUEST['from']) : trim(UDate::now()->modify('-10 week'));
     $dateTo = isset($_REQUEST['to']) ? trim($_REQUEST['to']) : trim(UDate::now());
     $searchCriteria['dateRange'] = array('from' => $dateFrom, 'to' => $dateTo, 'step' => $dateStepBy);
     $searchCriteria['showPrice'] = isset($_REQUEST['showprice']) && trim($_REQUEST['showprice']) === '1';
     $js .= 'pageJs';
     $js .= '.load(' . json_encode($searchCriteria) . ');';
     return $js;
 }
Exemple #3
0
 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;
 }
 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();
 }
 /**
  * Archiving the file
  *
  * @param unknown $filePath
  * @param string $preFix
  * @param string $debug
  * @throws Exception
  */
 private static function _zipFile($files, $preFix = '', $debug = false)
 {
     $tarFilePath = self::$_outputFileDir . '/' . self::FILE_NAME . '.tar';
     $start = self::_log('== Archiving the file: ' . $tarFilePath, __CLASS__ . '::' . __FUNCTION__, $preFix);
     $csvFilePath = '/tmp/' . md5('ProductToMagento_CSV_' . trim(UDate::now())) . '.csv';
     $tarFile = new PharData($tarFilePath);
     //add csv file
     self::_log('Generating the CSV file: ' . $csvFilePath, '', $preFix . self::TAB);
     $objWriter = PHPExcel_IOFactory::createWriter($files['phpExcel'], 'CSV');
     $objWriter->save($csvFilePath);
     self::_log('Adding the CSV file to: ' . $tarFilePath, '', $preFix . self::TAB);
     $tarFile->addFile($csvFilePath, self::FILE_NAME . '.csv');
     //add image files
     if (isset($files['imageFiles']) && count($files['imageFiles']) > 0) {
         $imageDir = self::$_imageDirName;
         $tarFile->addEmptyDir($imageDir);
         foreach ($files['imageFiles'] as $index => $imageFile) {
             self::_log('Processing file: ' . $index, '', $preFix . self::TAB . self::TAB);
             if (!isset($imageFile['filePath'])) {
                 self::_log('No File Path SET. SKIP ', '', $preFix . self::TAB . self::TAB . self::TAB);
                 continue;
             }
             if (!is_file($imageFile['filePath'])) {
                 self::_log('File NOT FOUND: ' . $imageFile['filePath'], '', $preFix . self::TAB . self::TAB . self::TAB);
                 continue;
             }
             $tarFile->addFile($imageFile['filePath'], $imageDir . '/' . $imageFile['fileName']);
             self::_log('Added File:' . $imageFile['fileName'] . ', from path: ' . $imageFile['filePath'], '', $preFix . self::TAB . self::TAB . self::TAB);
         }
     } else {
         self::_log('No image files to add.', '', $preFix . self::TAB);
     }
     // COMPRESS archive.tar FILE. COMPRESSED FILE WILL BE archive.tar.gz
     self::_log('Compressing file: ' . $tarFilePath, '', $preFix . self::TAB . self::TAB . self::TAB);
     $tarFile->compress(Phar::GZ);
     // NOTE THAT BOTH FILES WILL EXISTS. SO IF YOU WANT YOU CAN UNLINK archive.tar
     self::_log('REMOVING the orginal file: ' . $tarFilePath, '', $preFix . self::TAB);
     unlink($tarFilePath);
     self::_log('REMOVED', '', $preFix . self::TAB . self::TAB);
     //remving temp csv file
     self::_log('REMOVING the tmp csv file: ' . $csvFilePath, '', $preFix . self::TAB);
     unlink($csvFilePath);
     self::_log('REMOVED', '', $preFix . self::TAB . self::TAB);
     self::_log('== Archived', __CLASS__ . '::' . __FUNCTION__, $preFix, $start);
 }
<?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";
 /**
  * Archiving the file
  *
  * @param unknown $filePath
  * @param string $preFix
  * @param string $debug
  * @throws Exception
  */
 private static function _zipFile($filePath, $preFix = '', $debug = false)
 {
     $start = self::_log('== Archiving the file: ' . $filePath, __CLASS__ . '::' . __FUNCTION__, $preFix);
     if (!is_file($filePath)) {
         throw new Exception("Invalid file: " . $filePath);
     }
     $zip = new ZipArchive();
     $zipFilePath = self::$_outputFileDir . '/' . UDate::now()->format('Y_m_d') . '.zip';
     if ($zip->open($zipFilePath, ZipArchive::CREATE) !== TRUE) {
         throw new Exception("cannot open file<" . $zipFilePath . ">");
     }
     if ($zip->addFile($filePath, '/' . basename($filePath) . '.' . UDate::now()->format('Y_m_d_H_i_s')) !== true) {
         throw new Exception('Failed add file(' . $filePath . ') to zip file:' . $zipFilePath);
     }
     self::_log('Add file: ' . $filePath, '', $preFix . self::TAB);
     self::_log('Zip file (' . $zipFilePath . ') are now:', '', $preFix . self::TAB);
     self::_log('- Contains: ' . $zip->numFiles . ' file(s)', '', $preFix . self::TAB . self::TAB);
     self::_log('- Status: ' . $zip->getStatusString(), '', $preFix . self::TAB . self::TAB);
     if ($zip->close() !== true) {
         throw new Exception('Failed to save the zip file:' . $zipFilePath);
     }
     self::_log('REMOVING the orginal file: ' . $filePath, '', $preFix . self::TAB);
     unlink($filePath);
     self::_log('REMOVED', '', $preFix . self::TAB . self::TAB);
     self::_log('== Archived', __CLASS__ . '::' . __FUNCTION__, $preFix, $start);
 }
$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);
 }
<?php

ini_set('memory_limit', '1024M');
require_once dirname(__FILE__) . '/../../bootstrap.php';
Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
echo "Begin updateProductByDatafeed from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
$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->updateProductByDatafeed(true);
echo "Done updateProductByDatafeed from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
 /**
  * @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;
 }
<?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";
Exemple #13
0
 /**
  * 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;
 }
<?php

require_once dirname(__FILE__) . '/../main/bootstrap.php';
try {
    $soapClient = null;
    echo "Begin" . __CLASS__ . " Melb Time: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n <pre>";
    Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
    Dao::beginTransaction();
    SystemSettings::addSettings('system_build_product_ids', json_encode(array()), 'the product id json for system builds');
    Dao::commitTransaction();
} catch (Exception $e) {
    echo "Error:";
    if ($soapClient instanceof SoapClient) {
        echo "Response:<textarea>" . $soapClient->__getLastResponse() . "</textarea>";
    }
    echo $e->getMessage() . "\n" . $e->getTraceAsString() . "\n";
    Dao::rollbackTransaction();
    throw $e;
}
Exemple #15
0
 /**
  * Getting the RRP for this product
  * @return ProductPrice|NULL
  */
 public function getNearestSpecialPrice()
 {
     $now = UDate::now();
     if (count($prices = ProductPrice::getPrices($this, ProductPriceType::get(ProductPriceType::ID_CASUAL_SPECIAL), '', trim($now), trim($now), '', 1, 1, array('created' => 'asc'))) > 0) {
         return $prices[0];
     }
     return null;
 }
foreach ($categoryIds as $id) {
    if (($i = ProductCategory::get($id)) instanceof ProductCategory) {
        $categories[] = $i;
        echo 'try to disable all product with category "' . $i->getName() . '"(' . $i->getId() . ')' . "\n";
    } else {
        throw new Exception('Invalid category id "' . $id . '" passed in');
    }
}
$categoryIds = array_map(create_function('$a', 'return $a->getId();'), $categories);
// run
$products = Product::getProducts('', '', array(), $manufacturerIds, $categoryIds);
$count = 0;
echo 'found total ' . count($products) . ' products' . "\n";
foreach ($products as $product) {
    if ($product->getStockOnHand() == 0 && $product->getStockOnOrder() == 0 && $product->getStockOnPO() == 0 && $product->getStockInParts() == 0) {
        $sku = $product->getSku();
        disableProduct($sku);
        $count++;
    }
}
echo 'total ' . $count . ' products changed' . "\n";
echo "Done disableProducts from magento MELB TIME: " . UDate::now(UDate::TIME_ZONE_MELB) . "\n";
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";
}
Exemple #17
0
 /**
  * get category info by magento-b2b productCategory id
  *
  * @param string $systemid
  *
  * @return string
  * @soapmethod
  */
 public function getCategory($systemid)
 {
     $response = $this->_getResponse(UDate::now());
     try {
         $systemid = intval(trim($systemid));
         Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT));
         //TODO
         $obj = ProductCategory::get($systemid);
         if (!$obj instanceof ProductCategory) {
             throw new Exception('category with system id "' . $systemid . '" does not exist.');
         }
         $response['status'] = self::RESULT_CODE_SUCC;
         $this->addCData('category', json_encode($obj->getJson()), $response);
     } catch (Exception $e) {
         $response['status'] = self::RESULT_CODE_FAIL;
         $this->addCData('error', $e->getMessage(), $response);
     }
     return trim($response->asXML());
 }
 /**
  * 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;
 }
Exemple #19
0
 /**
  * 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();
         foreach ($serachCriteria as $field => $value) {
             if (is_array($value) && count($value) === 0 || is_string($value) && ($value = trim($value)) === '') {
                 continue;
             }
             $query = $class::getQuery();
             switch ($field) {
                 case 'pro.ids':
                     $value = explode(',', $value);
                     $where[] = 'pal.productId in (' . implode(", ", array_fill(0, count($value), "?")) . ')';
                     $params = array_merge($params, $value);
                     break;
                 case 'pro.categories':
                     $value = array_map(create_function('$a', 'return trim($a);'), explode(',', $value));
                     $query->eagerLoad("ProductAgeingLog.product", 'inner join', 'pro', 'pro.id = pal.productId and pro.active = 1')->eagerLoad('Product.categories', 'inner join', 'pro_cate', 'pro_cate.active = 1 and pro.id = pro_cate.productId and pro_cate.categoryId in (' . implode(", ", array_fill(0, count($value), "?")) . ')');
                     $params = array_merge($value, $params);
                     break;
                 case 'po.id':
                     ProductAgeingLog::getQuery()->eagerLoad('ProductAgeingLog.purchaseOrderItem', 'inner join', 'pal_po');
                     $where[] = '(pal_po.id = ? )';
                     $params[] = $value;
                     break;
                 case 'aged-days':
                     $where[] = 'date_add(pal.lastPurchaseTime, INTERVAL ' . intval($value) . ' DAY) < NOW()';
                     break;
             }
         }
         $stats = array();
         $objects = $class::getAllByCriteria(implode(' AND ', $where), $params, false, $pageNo, $pageSize, array('pal.lastPurchaseTime' => 'asc'), $stats);
         $results['pageStats'] = $stats;
         $results['items'] = array();
         foreach ($objects as $obj) {
             $results['items'][] = $obj->getJson(array('NOW' => UDate::now()->__toString()));
         }
     } catch (Exception $ex) {
         $errors[] = $ex->getMessage() . $ex->getTraceAsString();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
 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;
 }
 /**
  * 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

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";
Exemple #23
0
 /**
  * (non-PHPdoc)
  * @see BaseEntityAbstract::preSave()
  */
 public function preSave()
 {
     if (trim($this->getId()) === '') {
         if (!$this->status instanceof TaskStatus) {
             $this->setStatus(TaskStatus::get(TaskStatus::ID_NEW));
         }
         if (trim($this->getDueDate()) === trim(UDate::zeroDate())) {
             $this->setDueDate(UDate::now()->modify(self::DUE_DATE_PERIOD));
         }
     } else {
         $changed = array();
         $origTech = $origCustomer = $origOrder = $origStatus = null;
         $origTask = Task::get($this->getId());
         if (($customer = $this->getCustomer()) instanceof Customer && !($origCustomer = $origTask->getCustomer()) instanceof Customer || !$customer instanceof Customer && $origCustomer instanceof Customer || $customer instanceof Customer && $origCustomer instanceof Customer && $customer->getId() !== $origCustomer->getId()) {
             $changed[] = 'Customer Changed["' . ($origCustomer instanceof Customer ? $origCustomer->getName() : '') . '" => "' . ($customer instanceof Customer ? $customer->getName() : '') . '"]';
         }
         if (($tech = $this->getTechnician()) instanceof UserAccount && !($origTech = $origTask->getTechnician()) instanceof UserAccount || !$tech instanceof UserAccount && $origTech instanceof UserAccount || $tech instanceof UserAccount && $origTech instanceof UserAccount && $tech->getId() !== $origTech->getId()) {
             $changed[] = 'Technician Changed["' . ($origTech instanceof UserAccount ? $origTech->getPerson()->getFullName() : '') . '" => "' . ($tech instanceof UserAccount ? $tech->getPerson()->getFullName() : '') . '"]';
         }
         if (($order = $this->getFromEntity()) instanceof Order && !($origOrder = $origTask->getFromEntity()) instanceof Order || !$order instanceof Order && $origOrder instanceof Order || $order instanceof Order && $origOrder instanceof Order && $order->getId() !== $origOrder->getId()) {
             $changed[] = 'Order Changed["' . ($origOrder instanceof Order ? $origOrder->getOrderNo() : '') . '" => "' . ($order instanceof Order ? $order->getOrderNo() : '') . '"]';
         }
         if (($status = $this->getStatus()) instanceof TaskStatus && !($origStatus = $origTask->getStatus()) instanceof TaskStatus || !$status instanceof TaskStatus && $origStatus instanceof TaskStatus || $status instanceof TaskStatus && $origStatus instanceof TaskStatus && $status->getId() !== $origStatus->getId()) {
             $changed[] = 'Status Changed["' . ($origStatus instanceof TaskStatus ? $origStatus->getName() : '') . '" => "' . ($status instanceof TaskStatus ? $status->getName() : '') . '"]';
         }
         if (count($changed) > 0) {
             $this->addComment(implode(', ', $changed), Comments::TYPE_SYSTEM);
         }
     }
 }