public static function getMatchPrices($companyAliases, $sku, $myPrice) { $myPrice = StringUtilsAbstract::getValueFromCurrency($myPrice); //initialize values $finalOutputArray = array('sku' => $sku, 'myPrice' => $myPrice, 'minPrice' => 0, 'companyPrices' => array()); foreach ($companyAliases as $key => $value) { $finalOutputArray['companyPrices'][$key] = array('price' => 0, 'priceURL' => '', 'PriceMatchCompanyId' => $value['PriceMatchCompanyId']); } //getting actual values $productPriceArray = PriceMatchConnector::getMatchPrices($sku); foreach ($productPriceArray as $productPriceInfo) { $companyDetails = $productPriceInfo['PriceMatchCompany']; $companyDetails = $companyDetails->getCompanyAlias(); if ($companyDetails === '') { continue; } foreach ($companyAliases as $key => $value) { if (is_array($value) === true && in_array(strtolower($companyDetails), array_map(create_function('$a', 'return strtolower($a);'), $value))) { $price = str_replace(' ', '', str_replace('$', '', str_replace(',', '', $productPriceInfo['price']))); if ($finalOutputArray['minPrice'] == 0 || $finalOutputArray['minPrice'] > $price) { $finalOutputArray['minPrice'] = $price; } $finalOutputArray['companyPrices'][$key] = array('price' => $price, 'priceURL' => $productPriceInfo['url'], 'PriceMatchCompanyId' => $value['PriceMatchCompanyId']); break; } } } $companyAliases = null; $price = null; $productPriceArray = null; //return the result $finalOutputArray['priceDiff'] = $finalOutputArray['myPrice'] - $finalOutputArray['minPrice']; return $finalOutputArray; }
/** * Getting the price match result * * @param array $companyAliases * @param string $sku * @param number $myPrice * * @return multitype:number multitype: unknown Ambigous <number, mixed> */ public static function getPrices($companyAliases, $sku, $myPrice) { $myPrice = StringUtilsAbstract::getValueFromCurrency($myPrice); //initialize values $finalOutputArray = array('sku' => $sku, 'myPrice' => $myPrice, 'minPrice' => 0, 'companyPrices' => array()); foreach ($companyAliases as $key => $value) { $finalOutputArray['companyPrices'][$key] = array('price' => 0, 'priceURL' => '', 'PriceMatchCompanyId' => $value['PriceMatchCompanyId']); } $url = 'http://www.staticice.com.au/cgi-bin/search.cgi'; //getting actual values $productPriceArray = HTMLParser::getPriceListForProduct($url, $sku); foreach ($productPriceArray as $productPriceInfo) { if (($companyDetails = trim($productPriceInfo['companyDetails'])) === '') { continue; } $cdArray = explode('|', $companyDetails); $companyURL = isset($cdArray[count($cdArray) - 2]) ? trim($cdArray[count($cdArray) - 2]) : trim($companyDetails); foreach ($companyAliases as $key => $value) { if (is_array($value) === true && in_array(strtolower($companyURL), array_map(create_function('$a', 'return strtolower($a);'), $value))) { $price = str_replace(' ', '', str_replace('$', '', str_replace(',', '', $productPriceInfo['price']))); if ($finalOutputArray['minPrice'] == 0 || $finalOutputArray['minPrice'] > $price) { $finalOutputArray['minPrice'] = $price; } $finalOutputArray['companyPrices'][$key] = array('price' => $price, 'priceURL' => HTMLParser::getHostUrl($url) . $productPriceInfo['priceLink'], 'PriceMatchCompanyId' => $value['PriceMatchCompanyId']); break; } } } //return the result $finalOutputArray['priceDiff'] = $finalOutputArray['myPrice'] - $finalOutputArray['minPrice']; return $finalOutputArray; }
public function updateSetting($sender, $param) { $result = $errors = array(); try { $result = $products = array(); $systemSetting = SystemSettings::getByType(SystemSettings::TYPE_SYSTEM_BUILD_PRODUCTS_ID); foreach ($param->CallbackParameter as $type => $ids) { $result[$type] = array(); $products[$type] = array(); foreach ($ids as $index => $id) { $id = intval(trim($id)); if (($product = Product::get($id)) instanceof Product) { $result[$type][] = $id; $products[$type][] = $product->getJson(); } } } Dao::beginTransaction(); $systemSetting->setValue(json_encode($result))->save(); Dao::commitTransaction(); } catch (Exception $ex) { // Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($products, $errors); }
protected static function _getData() { if (count(self::$_dateRange) === 0) { $yesterdayLocal = new UDate('now', 'Australia/Melbourne'); $yesterdayLocal->modify('-1 day'); $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne'); $fromDate->setTimeZone('UTC'); $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne'); $toDate->setTimeZone('UTC'); } else { $fromDate = self::$_dateRange['start']; $toDate = self::$_dateRange['end']; } self::$_fromDate = $fromDate; self::$_toDate = $toDate; $orders = Order::getAllByCriteria('invDate >= :fromDate and invDate <= :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate))); $return = array(); foreach ($orders as $order) { //common fields $customer = $order->getCustomer(); $creditNotes = CreditNote::getAllByCriteria('orderId = ?', array($order->getId())); $row = array('Invoice No.' => $order->getInvNo(), 'Invoice Date' => $order->getInvDate()->setTimeZone('Australia/Melbourne')->__toString(), 'Order No.' => $order->getOrderNo(), 'Order Date' => $order->getOrderDate()->setTimeZone('Australia/Melbourne')->__toString(), 'PO No.' => $order->getPONo(), 'Customer Name' => $customer->getName(), 'Customer Ph.' => $customer->getContactNo(), 'Customer Email' => $customer->getEmail(), 'Status' => $order->getStatus()->getName(), 'Total Amt.' => StringUtilsAbstract::getCurrency($order->getTotalAmount()), 'Total Paid' => StringUtilsAbstract::getCurrency($order->getTotalPaid()), 'Total Credited' => StringUtilsAbstract::getCurrency($order->getTotalCreditNoteValue()), 'Total Due' => StringUtilsAbstract::getCurrency($order->getTotalAmount() - $order->getTotalPaid() - $order->getTotalCreditNoteValue()), 'CreditNote Nos.' => implode(', ', array_map(create_function('$a', 'return $a->getCreditNoteNo();'), $creditNotes))); $return[] = $row; } return $return; }
/** * (non-PHPdoc) * @see DetailsPageAbstract::saveItem() */ public function saveItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->id)) { throw new Exception('Invalid supplier ID passed in!'); } $supplier = ($id = trim($param->CallbackParameter->id)) === '' ? new Supplier() : Supplier::get($id); if (!$supplier instanceof Supplier) { throw new Exception('Invalid supplier passed in!'); } $contactName = trim($param->CallbackParameter->address->contactName); $contactNo = trim($param->CallbackParameter->address->contactNo); $street = trim($param->CallbackParameter->address->street); $city = trim($param->CallbackParameter->address->city); $region = trim($param->CallbackParameter->address->region); $postCode = trim($param->CallbackParameter->address->postCode); $country = trim($param->CallbackParameter->address->country); $address = $supplier->getAddress(); $supplier->setName(trim($param->CallbackParameter->name))->setDescription(trim($param->CallbackParameter->description))->setContactNo(trim($param->CallbackParameter->contactNo))->setEmail(trim($param->CallbackParameter->email))->setAddress(Address::create($street, $city, $region, $country, $postCode, $contactName, $contactNo, $address))->save(); $results['url'] = '/supplier/' . $supplier->getId() . '.html' . (isset($_REQUEST['blanklayout']) ? '?blanklayout=' . $_REQUEST['blanklayout'] : ''); $results['item'] = $supplier->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage() . $ex->getTraceAsString(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * * @param unknown $sender * @param unknown $params */ public function addComments($sender, $params) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($params->CallbackParameter->entityName) || ($entityName = trim($params->CallbackParameter->entityName)) === '') { throw new Exception('System Error: EntityName is not provided!'); } if (!isset($params->CallbackParameter->entityId) || ($entityId = trim($params->CallbackParameter->entityId)) === '') { throw new Exception('System Error: entityId is not provided!'); } if (!($entity = $entityName::get($entityId)) instanceof $entityName) { throw new Exception('System Error: no such a entity exisits!'); } if (!isset($params->CallbackParameter->comments) || ($comments = trim($params->CallbackParameter->comments)) === '') { throw new Exception('System Error: invalid comments passed in!'); } $comment = Comments::addComments($entity, $comments, Comments::TYPE_NORMAL); $results['item'] = $comment->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $params->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Getting the transid * * @param string $salt The salt of making the trans id * * @return string */ public static function genGroupId($salt = '') { if (!is_string(self::$_groupId)) { self::$_groupId = StringUtilsAbstract::getRandKey($salt); } return self::$_groupId; }
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); }
/** * Sending the email out * * @param unknown $sender * @param unknown $param * * @throws Exception */ public function sendEmail($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->orderId) || !($order = Order::get($param->CallbackParameter->orderId)) instanceof Order) { throw new Exception('System Error: invalid order provided!'); } if (!isset($param->CallbackParameter->emailAddress) || ($emailAddress = trim($param->CallbackParameter->emailAddress)) === '') { throw new Exception('System Error: invalid emaill address provided!'); } $emailBody = ''; if (isset($param->CallbackParameter->emailBody) && ($emailBody = trim($param->CallbackParameter->emailBody)) !== '') { $emailBody = str_replace("\n", "<br />", $emailBody); } $pdfFile = EntityToPDF::getPDF($order); $asset = Asset::registerAsset($order->getOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP); $type = $order->getType(); EmailSender::addEmail('*****@*****.**', $emailAddress, 'BudgetPC ' . $type . ':' . $order->getOrderNo(), (trim($emailBody) === '' ? '' : $emailBody . "<br /><br />") . 'Please find attached ' . $type . ' (' . $order->getOrderNo() . '.pdf) from Budget PC Pty Ltd.', array($asset)); $order->addComment('An email sent to "' . $emailAddress . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM); $results['item'] = $order->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * (non-PHPdoc) * @see StaticsPageAbstract::getData() */ public function getData($sender, $param) { $results = $errors = array(); try { $dateFrom = trim($param->CallbackParameter->dateRange->from); $dateTo = trim($param->CallbackParameter->dateRange->to); $step = trim($param->CallbackParameter->dateRange->step); $showPrice = $param->CallbackParameter->showPrice; $timeRange = $this->_getXnames($dateFrom, $dateTo, $step); $names = array_keys($timeRange); $productIds = $param->CallbackParameter->productIds; if (count($productIds) === 0) { $productIds = $this->_topProductIds(); } $series = array(); foreach ($productIds as $pid) { $data = array_fill(0, count($names), 0); $name = 'Invalid Pid=' . $pid; if (($product = Product::get($pid)) instanceof Product) { $name = $product->getSku(); $data = $this->_getSeries($timeRange, $dateFrom, $dateTo, array($product->getId()), $showPrice); } $series[] = array('name' => $name, 'data' => $data); } $results = array('chart' => array('type' => 'line'), 'title' => array('text' => 'Product Sales Trend', 'x' => -20), 'subtitle' => array('text' => 'Data is based on date range between "' . $dateFrom . '" to "' . $dateTo . '"', 'x' => -20), 'xAxis' => array('categories' => $names), 'yAxis' => array('title' => array('text' => $showPrice === true ? 'Order Amount ($)' : 'Ordered Qty')), 'series' => $series); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
protected static function _getData() { if (count(self::$_dateRange) === 0) { $yesterdayLocal = new UDate('now', 'Australia/Melbourne'); $yesterdayLocal->modify('-1 day'); $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne'); $fromDate->setTimeZone('UTC'); $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne'); $toDate->setTimeZone('UTC'); } else { $fromDate = self::$_dateRange['start']; $toDate = self::$_dateRange['end']; } $orders = Order::getAllByCriteria('invDate >= :fromDate and invDate < :toDate and statusId != :cancelStatusId', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate), 'cancelStatusId' => trim(OrderStatus::ID_CANCELLED))); $return = array(); foreach ($orders as $order) { //common fields $customer = $order->getCustomer(); $row = array('ContactName' => $customer->getName(), 'EmailAddress' => $customer->getEmail(), 'POAddressLine1' => '', 'POAddressLine2' => '', 'POAddressLine3' => '', 'POAddressLine4' => '', 'POCity' => '', 'PORegion' => '', 'POPostalCode' => '', 'POCountry' => '', 'InvoiceNumber' => $order->getInvNo(), 'Reference' => intval($order->getIsFromB2B()) === 1 ? $order->getOrderNo() : $order->getPONo(), 'InvoiceDate' => $order->getInvDate()->setTimeZone('Australia/Melbourne')->__toString(), 'DueDate' => $order->getInvDate()->modify('+' . self::getTerms($customer) . ' day')->setTimeZone('Australia/Melbourne')->__toString()); foreach ($order->getOrderItems() as $orderItem) { $product = $orderItem->getProduct(); if (!$product instanceof Product) { continue; } $shouldTotal = $orderItem->getUnitPrice() * $orderItem->getQtyOrdered(); $return[] = array_merge($row, array('InventoryItemCode' => $product->getSku(), 'Description' => $product->getShortDescription(), 'Quantity' => $orderItem->getQtyOrdered(), 'UnitAmount' => $orderItem->getUnitPrice(), 'Discount' => (floatval($shouldTotal) === 0.0 ? 0 : round(($shouldTotal - $orderItem->getTotalPrice()) * 100 / $shouldTotal, 2)) . '%', 'AccountCode' => $product->getRevenueAccNo(), 'TaxType' => "GST on Income", 'TrackingName1' => '', 'TrackingOption1' => '', 'TrackingName2' => '', 'TrackingOption2' => '', 'Currency' => '', 'BrandingTheme' => '')); } if (($shippingMethod = trim(implode(',', $order->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD)))) !== '') { $shippingCost = $order->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST); $return[] = array_merge($row, array('InventoryItemCode' => $shippingMethod, 'Description' => $shippingMethod, 'Quantity' => 1, 'UnitAmount' => StringUtilsAbstract::getCurrency(count($shippingCost) > 0 ? StringUtilsAbstract::getValueFromCurrency($shippingCost[0]) : 0), 'Discount' => '', 'AccountCode' => '43300', 'TaxType' => "GST on Income", 'TrackingName1' => '', 'TrackingOption1' => '', 'TrackingName2' => '', 'TrackingOption2' => '', 'Currency' => '', 'BrandingTheme' => '')); } } return $return; }
/** * (non-PHPdoc) * @see StaticsPageAbstract::getData() */ public function getData($sender, $param) { $results = $errors = array(); try { $timeRange = $this->_getXnames(); $names = array_keys($timeRange); $series = array(); $series[] = array('name' => 'All', 'data' => $this->_getSeries($timeRange, $timeRange[$names[0]]['from'], $timeRange[$names[count($names) - 1]]['to'])); foreach (OrderStatus::getAll() as $status) { $series[] = array('name' => $status->getName(), 'data' => $this->_getSeries($timeRange, $timeRange[$names[0]]['from'], $timeRange[$names[count($names) - 1]]['to'], array($status->getId()))); } $results = array('chart' => array('type' => 'line'), 'title' => array('text' => 'BPC: Monthly Order Trend', 'x' => -20), 'subtitle' => array('text' => 'This is just order trend from last 12 month', 'x' => -20), 'xAxis' => array('categories' => $names), 'yAxis' => array('title' => array('text' => 'No of Orders')), 'series' => $series); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function changePersonInfo($sender, $param) { $results = $errors = array(); try { if (!isset($param->CallbackParameter->firstName) || ($firstName = trim($param->CallbackParameter->firstName)) === '') { throw new Exception("Invalid firstName!"); } if (!isset($param->CallbackParameter->lastName) || ($lastName = trim($param->CallbackParameter->lastName)) === '') { throw new Exception("Invalid lastName!"); } Core::getUser()->getPerson()->setFirstName($firstName)->setLastName($lastName)->save(); Core::setUser(UserAccount::get(Core::getUser()->getId()), Core::getRole()); $results['succ'] = true; } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * (non-PHPdoc) * @see StaticsPageAbstract::getData() */ public function getData($sender, $param) { $results = $errors = array(); try { $dateFrom = trim($param->CallbackParameter->dateRange->from); $dateTo = trim($param->CallbackParameter->dateRange->to); if (!($product = Product::get($param->CallbackParameter->productId)) instanceof Product) { throw new Exception('Invalid product id=' . $param->CallbackParameter->productId . ' provided'); } $series = array(); $series[] = array('name' => 'Sales Unit Price (incl. GST)', 'data' => $this->_getSalesSeries($product->getId(), $dateFrom, $dateTo)); $series[] = array('name' => 'Purchase Unit Price (incl. GST)', 'data' => $this->_getPurchaseSeries($product->getId(), $dateFrom, $dateTo)); $results = array('chart' => array('type' => 'spline'), 'title' => array('text' => 'Product Price($) Trend', 'x' => -20), 'subtitle' => array('text' => 'Data is based on date range between "' . $dateFrom . '" to "' . $dateTo . '"', 'x' => -20), 'xAxis' => array('type' => 'datetime', 'dateTimeLabelFormats' => array('month' => '%e. %b', 'year' => '%b'), 'title' => array('text' => 'Date')), 'yAxis' => array('title' => array('text' => 'Price($)'), 'min' => 0), 'tooltip' => array('headerFormat' => '<b>{series.name}</b><br>', 'pointFormat' => '{point.x:%e. %b}: ${point.y:.2f}'), 'series' => $series); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Creating a new Memo * * @param unknown $sender * @param unknown $params * * @throws Exception */ public function addMemo($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->entity) || !isset($param->CallbackParameter->entityId) || ($entityName = trim($param->CallbackParameter->entity)) === '' || !($entity = $entityName::get(trim($param->CallbackParameter->entityId))) instanceof $entityName) { throw new Exception('System Error: no entity provided for the Memo'); } if (!isset($param->CallbackParameter->data) || !isset($param->CallbackParameter->data->comments) || ($comments = trim($param->CallbackParameter->data->comments)) === '') { throw new Exception('You can NOT create a Memo with a blank message.'); } $newComments = null; $entity->addComment($comments, Comments::TYPE_MEMO, '', $newComments); $results['item'] = $newComments->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
protected static function _getData() { if (count(self::$_dateRange) === 0) { $yesterdayLocal = new UDate('now', 'Australia/Melbourne'); $yesterdayLocal->modify('-1 day'); $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne'); $fromDate->setTimeZone('UTC'); $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne'); $toDate->setTimeZone('UTC'); } else { $fromDate = self::$_dateRange['start']; $toDate = self::$_dateRange['end']; } $creditNotes = CreditNote::getAllByCriteria('applyDate >= :fromDate and applyDate < :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate))); $return = array(); foreach ($creditNotes as $creditNote) { $orderStatus = $creditNote->getOrder()->getStatus()->getId(); $orderType = $creditNote->getOrder()->getType(); //file_put_contents('/tmp/datafeed/web.log', __FILE__ .':' . __FUNCTION__ . ':' . __LINE__ . ':' . $orderType . ":" . $orderStatus . PHP_EOL, FILE_APPEND | LOCK_EX); if ($orderType == Order::TYPE_INVOICE && $orderStatus == OrderStatus::ID_CANCELLED) { continue; } //common fields $customer = $creditNote->getCustomer(); $row = array('ContactName' => $customer->getName(), 'EmailAddress' => $customer->getEmail(), 'POAddressLine1' => '', 'POAddressLine2' => '', 'POAddressLine3' => '', 'POAddressLine4' => '', 'POCity' => '', 'PORegion' => '', 'POPostalCode' => '', 'POCountry' => '', 'InvoiceNumber' => $creditNote->getCreditNoteNo(), 'Reference' => $creditNote->getOrder() instanceof Order ? $creditNote->getOrder()->getInvNo() : '', 'InvoiceDate' => $creditNote->getApplyDate()->setTimeZone('Australia/Melbourne')->__toString(), 'DueDate' => ''); foreach ($creditNote->getCreditNoteItems() as $item) { $product = $item->getProduct(); if (!$product instanceof Product) { continue; } $shouldTotal = $item->getUnitPrice() * $item->getQty(); $return[] = array_merge($row, array('InventoryItemCode' => $product->getSku(), 'Description' => $product->getShortDescription(), 'Quantity' => 0 - $item->getQty(), 'UnitAmount' => $item->getUnitPrice(), 'Discount' => (floatval($shouldTotal) === 0.0 ? 0 : round(($shouldTotal - $item->getTotalPrice()) * 100 / $shouldTotal, 2)) . '%', 'AccountCode' => $product->getRevenueAccNo(), 'TaxType' => "GST on Income", 'TrackingName1' => '', 'TrackingOption1' => '', 'TrackingName2' => '', 'TrackingOption2' => '', 'Currency' => '', 'BrandingTheme' => '')); } if (($shippingValue = $creditNote->getShippingValue()) > 0) { $return[] = array_merge($row, array('InventoryItemCode' => 'Credit Note Shipping', 'Description' => 'Credit Note Shipping', 'Quantity' => 0 - 1, 'UnitAmount' => StringUtilsAbstract::getCurrency($shippingValue), 'Discount' => '', 'AccountCode' => '43300', 'TaxType' => "GST on Income", 'TrackingName1' => '', 'TrackingOption1' => '', 'TrackingName2' => '', 'TrackingOption2' => '', 'Currency' => '', 'BrandingTheme' => '')); } } return $return; }
protected static function _getData() { if (count(self::$_dateRange) === 0) { $yesterdayLocal = new UDate('now', 'Australia/Melbourne'); $yesterdayLocal->modify('-1 day'); $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne'); $fromDate->setTimeZone('UTC'); $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne'); $toDate->setTimeZone('UTC'); } else { $fromDate = self::$_dateRange['start']; $toDate = self::$_dateRange['end']; } $dataType = 'created'; $items = Payment::getAllByCriteria($dataType . ' >= :fromDate and ' . $dataType . ' < :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate))); $now = new UDate(); $now->setTimeZone('Australia/Melbourne'); $return = array(); foreach ($items as $item) { $return[] = array('Type' => $item->getOrder() instanceof Order ? 'Payment' : 'Credit', 'InvNo' => $item->getOrder() instanceof Order ? trim($item->getOrder()->getInvNo()) === '' ? '' : $item->getOrder()->getInvNo() : '', 'Payment Date' => $item->getPaymentDate()->setTimeZone('Australia/Melbourne')->format('Y-m-d'), 'Customer Name' => $item->getOrder() instanceof Order ? $item->getOrder()->getCustomer() instanceof Customer ? $item->getOrder()->getCustomer()->getName() : '' : '', 'Order No.' => $item->getOrder() instanceof Order ? $item->getOrder()->getOrderNo() : '', 'CreditNote No' => $item->getCreditNote() instanceof CreditNote ? $item->getCreditNote()->getCreditNoteNo() : '', 'Processed Date' => trim($item->getCreated()->setTimeZone('Australia/Melbourne')), 'Processed By' => $item->getCreatedBy() instanceof UserAccount ? $item->getCreatedBy()->getPerson()->getFullName() : '', 'Method' => $item->getMethod() instanceof PaymentMethod ? trim($item->getMethod()->getName()) : '', 'Amount' => StringUtilsAbstract::getCurrency($item->getCreditNote() instanceof CreditNote ? 0 - $item->getValue() : $item->getValue()), 'Comments' => trim(implode(',', array_map(create_function('$a', 'return $a->getComments();'), Comments::getAllByCriteria('entityName = ? and entityId = ?', array(get_class($item), $item->getId())))))); } return $return; }
public function getAllPricesForProduct($sender, $param) { $result = $errors = $outputArray = $finalOutputArray = array(); try { if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '') { throw new Exception('No SKU to search on!'); } if (!isset($param->CallbackParameter->companyAliases) || count($companyAliases = json_decode(json_encode($param->CallbackParameter->companyAliases), true)) === 0) { throw new Exception('No companyAliases to search on!'); } if (!isset($param->CallbackParameter->price) || ($myPrice = str_replace(' ', '', $param->CallbackParameter->price)) === '') { $myPrice = 0; } else { if (!is_numeric($myPrice = str_replace('$', '', str_replace(',', '', $myPrice)))) { throw new Exception('No provided my price is NOT a number(=' . $myPrice . '!'); } } $result['item'] = PriceMatcher::getPrices($companyAliases, $sku, $myPrice); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($result, $errors); }
/** * Getting the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function getItems($sender, $param) { $results = $errors = array(); try { if (!isset($param->CallbackParameter->searchCriteria->supplierId) || !($supplier = Supplier::get(trim($param->CallbackParameter->searchCriteria->supplierId))) instanceof Supplier) { throw new Exception('Invalid Supplier provided'); } if (!isset($param->CallbackParameter->searchCriteria->invoiceNo) || ($invoiceNo = trim($param->CallbackParameter->searchCriteria->invoiceNo)) === '') { throw new Exception('Invalid Invoice number provided'); } ReceivingItem::getQuery()->eagerLoad('ReceivingItem.purchaseOrder', 'inner join', 'rec_item_po', 'rec_item_po.id = rec_item.purchaseOrderId'); if (ReceivingItem::countByCriteria('rec_item_po.supplierId = ? and rec_item.invoiceNo = ?', array($supplier->getId(), $invoiceNo)) === 0) { throw new Exception('There is no such a invoice(invoice No=' . $invoiceNo . ') for supplier:' . $supplier->getName()); } $sql = 'select ri.productId, ri.unitPrice `unitPrice`, sum(ri.qty) `qty`, group_concat(distinct ri.id) `itemIds`, group_concat(distinct po.id) `poIds` from receivingitem ri inner join purchaseorder po on (po.id = ri.purchaseOrderId) where ri.active = 1 and ri.invoiceNo = ? and po.supplierId = ? group by ri.productId, ri.unitPrice'; $params = array($invoiceNo, $supplier->getId()); $rows = Dao::getResultsNative($sql, $params); $results['supplier'] = $supplier->getJson(); $results['items'] = array(); foreach ($rows as $row) { $items = count($itemIds = explode(',', $row['itemIds'])) === 0 ? array() : ReceivingItem::getAllByCriteria('id in (' . implode(',', array_fill(0, count($itemIds), '?')) . ')', $itemIds); $pos = count($poIds = explode(',', $row['poIds'])) === 0 ? array() : PurchaseOrder::getAllByCriteria('id in (' . implode(',', array_fill(0, count($poIds), '?')) . ')', $poIds); $results['items'][] = array('product' => Product::get($row['productId'])->getJson(), 'totalQty' => $row['qty'], 'totalPrice' => $row['unitPrice'] * $row['qty'], 'items' => array_map(create_function('$a', 'return $a->getJson();'), $items), 'purchaseOrders' => array_map(create_function('$a', 'return $a->getJson();'), $pos)); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * 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; }
/** * deleteItem * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function deleteItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->id) || !($recievingItem = ReceivingItem::get(trim($param->CallbackParameter->id))) instanceof ReceivingItem) { throw new Exception('System Error: invalid item provided'); } $recievingItem->setActive(false)->save(); $results['item'] = $recievingItem->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * save the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function saveItem($sender, $param) { $results = $errors = array(); try { $class = trim($this->_focusEntity); if (!isset($param->CallbackParameter->item)) { throw new Exception("System Error: no item information passed in!"); } $item = isset($param->CallbackParameter->item->id) && ($item = $class::get($param->CallbackParameter->item->id)) instanceof $class ? $item : null; $name = trim($param->CallbackParameter->item->name); $description = trim($param->CallbackParameter->item->description); if ($item instanceof $class) { $item->setName($name)->setDescription($description)->save(); } else { $item = $class::create($name, $description, false); } $results['item'] = $item->getJson(); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * save the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function saveItem($sender, $param) { $results = $errors = array(); try { $class = trim($this->_focusEntity); if (!isset($param->CallbackParameter->item)) { throw new Exception("System Error: no item information passed in!"); } $item = isset($param->CallbackParameter->item->id) && ($item = $class::get($param->CallbackParameter->item->id)) instanceof $class ? $item : null; $value = trim($param->CallbackParameter->item->value); if (!$item instanceof $class) { throw new Exception("System Error: Invalid id passed in"); } $item->setValue($value)->save(); $results['item'] = $item->getJson(); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * delete the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function deleteItems($sender, $param) { $results = $errors = array(); try { $class = trim($this->_focusEntity); $ids = isset($param->CallbackParameter->ids) ? $param->CallbackParameter->ids : array(); if (count($ids) > 0) { $parents = array(); foreach ($ids as $id) { if (!($item = $class::get($id)) instanceof $class) { continue; } $item->setActive(false)->save(); $parents[] = $item->getParent()->getJson(); } $class::deleteByCriteria('id in (' . str_repeat('?', count($ids)) . ')', $ids); $results['parents'] = $parents; } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function getAllCodeForProduct($sender, $param) { $result = $errors = $item = array(); try { if (!isset($param->CallbackParameter->importDataTypes) || ($type = trim($param->CallbackParameter->importDataTypes)) === '' || ($type = trim($param->CallbackParameter->importDataTypes)) === 'Select a Import Type') { throw new Exception('Invalid upload type passed in!'); } switch ($type) { case 'myob_ean': $index = $param->CallbackParameter->index; if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) { throw new Exception('Invalid sku passed in! (line ' . $index . ')'); } if (!isset($param->CallbackParameter->itemNo) || ($itemNo = trim($param->CallbackParameter->itemNo)) === '') { throw new Exception('Invalid itemNo passed in! (line ' . $index . ')'); } $result['path'] = 'product'; $productType = ProductCodeType::get(ProductCodeType::ID_EAN); $item = $this->updateProductCode($product, $itemNo, $productType); $result['item'] = $item->getJson(); break; case 'myob_upc': $index = $param->CallbackParameter->index; if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) { throw new Exception('Invalid sku passed in! (line ' . $index . ')'); } if (!isset($param->CallbackParameter->itemNo) || ($itemNo = trim($param->CallbackParameter->itemNo)) === '') { throw new Exception('Invalid itemNo passed in! (line ' . $index . ')'); } $result['path'] = 'product'; $productType = ProductCodeType::get(ProductCodeType::ID_UPC); $item = $this->updateProductCode($product, $itemNo, $productType); $result['item'] = $item->getJson(); break; case 'stockAdjustment': $index = $param->CallbackParameter->index; if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '' || !($product = Product::getBySku($sku)) instanceof Product) { throw new Exception('Invalid sku passed in! (line ' . $index . ')'); } $result['path'] = 'product'; $item = $this->updateStocktack($product, trim($param->CallbackParameter->stockOnPO), trim($param->CallbackParameter->stockOnHand), trim($param->CallbackParameter->stockInRMA), trim($param->CallbackParameter->stockInParts), trim($param->CallbackParameter->totalInPartsValue), trim($param->CallbackParameter->totalOnHandValue), $param->CallbackParameter->active, trim($param->CallbackParameter->comment)); $result['item'] = $item->getJson(); break; case 'accounting': $index = $param->CallbackParameter->index; if (!isset($param->CallbackParameter->sku) || ($sku = trim($param->CallbackParameter->sku)) === '') { throw new Exception('Invalid sku passed in! (line ' . $index . ')'); } if (!($product = Product::getBySku($sku)) instanceof Product) { $product = Product::create($sku, $sku); } $result['path'] = 'product'; $item = $this->updateAccountingInfo($product, trim($param->CallbackParameter->assetAccNo), trim($param->CallbackParameter->costAccNo), trim($param->CallbackParameter->revenueAccNo)); $result['item'] = $item->getJson(); break; case 'accountingCode': $index = $param->CallbackParameter->index; if (!isset($param->CallbackParameter->description) || ($description = trim($param->CallbackParameter->description)) === '') { throw new Exception('Invalid description passed in! (line ' . $index . ')'); } if (!isset($param->CallbackParameter->code) || ($code = trim($param->CallbackParameter->code)) === '' || !is_numeric($code)) { throw new Exception('Invalid Code passed in! (line ' . $index . ')'); } $result['path'] = ''; $item = $this->updateAccountingCode($description, $code); $result['item'] = $item->getJson(); break; default: throw new Exception('Invalid upload type passed in!'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($result, $errors); }
public function deleteAliasForPriceMatchCompany($sender, $param) { $result = $error = array(); try { if (!isset($param->CallbackParameter->data)) { throw new Exception('System Error: Noting to Delete!!!'); } $data = $param->CallbackParameter->data; if (!isset($data->id) || !isset($data->companyAlias) || ($id = trim($data->id)) == '' || ($alias = trim($data->companyAlias)) == '') { throw new Exception('Data to be deleted is NOT proper format'); } if (!($pmc = PriceMatchCompany::get($id)) instanceof PriceMatchCompany) { throw new Exception('Invalid Id [' . $id . '] provided for PriceMatchCompany!!!'); } $result['items'] = $pmc->setActive(false)->save()->getJson(); } catch (Exception $ex) { $error[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($result, $error); }
private function _getProducts(array $params) { $searchTxt = trim(isset($params['searchTxt']) ? $params['searchTxt'] : ''); if ($searchTxt === '') { throw new Exception('SearchTxt is needed'); } $pageSize = isset($params['pageSize']) && ($pageSize = trim($params['pageSize'])) !== '' ? $pageSize : DaoQuery::DEFAUTL_PAGE_SIZE; $pageNo = isset($params['pageNo']) && ($pageNo = trim($params['pageNo'])) !== '' ? $pageNo : null; $orderBy = isset($params['orderBy']) ? $params['orderBy'] : array(); $isKit = isset($params['isKit']) ? $params['isKit'] === true : null; $sqlParams = array('searchTxtExact' => $searchTxt); $searchTokens = array(); StringUtilsAbstract::permute(preg_split("/[\\s,]+/", trim($searchTxt)), $searchTokens); $nameLikeArray = $skuLikeArray = array(); foreach ($searchTokens as $index => $tokenArray) { $key = 'token' . $index; $sqlParams[$key] = '%' . implode('%', $tokenArray) . '%'; $nameLikeArray[] = 'name like :' . $key; $skuLikeArray[] = 'sku like :' . $key; } $where = array('mageId = :searchTxtExact OR (' . implode(' OR ', $nameLikeArray) . ') OR (' . implode(' OR ', $skuLikeArray) . ')'); $stats = array(); $items = Product::getAllByCriteria(implode(' AND ', $where), $sqlParams, true, $pageNo, $pageSize, $orderBy, $stats); $results = array(); $results['items'] = array_map(create_function('$a', 'return $a->getJson();'), $items); $results['pagination'] = $stats; $results['pageStats'] = $stats; return $results; }
/** * toggleActive * * @param unknown $sender * @param unknown $param */ public function toggleActive($sender, $param) { $results = $errors = array(); try { $id = isset($param->CallbackParameter->productId) ? $param->CallbackParameter->productId : ''; if (!($product = Product::get($id)) instanceof Product) { throw new Exception('Invalid product!'); } $product->setActive(intval($param->CallbackParameter->active))->save(); $results['item'] = $product->getJson(); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Getting the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function genReport($sender, $param) { $results = $errors = array(); try { $searchParams = json_decode(json_encode($param->CallbackParameter), true); $wheres = $joins = $params = array(); if (isset($searchParams['pro.name']) && ($name = trim($searchParams['pro.name'])) !== '') { $wheres[] = 'pro.name like :name'; $params['name'] = '%' . $name . '%'; } if (isset($searchParams['pro.active']) && ($active = trim($searchParams['pro.active'])) !== '') { $wheres[] = 'pro.active = :active'; $params['active'] = $active; } $productIds = $this->_getParams($searchParams, 'pro.id'); if (count($productIds) > 0) { $array = array(); foreach ($productIds as $index => $productId) { $key = 'product_' . $index; $array[] = ':' . $key; $params[$key] = $productId; } $wheres[] = 'pro.id in (' . implode(',', $array) . ')'; } $manufacturerIds = $this->_getParams($searchParams, 'pro.manufacturerIds'); if (count($manufacturerIds) > 0) { $array = array(); foreach ($manufacturerIds as $index => $manufacturerId) { $key = 'brand_' . $index; $array[] = ':' . $key; $params[$key] = $manufacturerId; } $wheres[] = 'pro.manufacturerId in (' . implode(',', $array) . ')'; } $supplierIds = $this->_getParams($searchParams, 'pro.supplierIds'); if (count($supplierIds) > 0) { $array = array(); foreach ($supplierIds as $index => $supplierId) { $key = 'supplier_' . $index; $array[] = ':' . $key; $params[$key] = $supplierId; } $joins[] = 'inner join suppliercode sup_code on (sup_code.productId = pro.id and sup_code.active = 1 and sup_code.supplierId in (' . implode(',', $array) . '))'; } $productCategoryIds = $this->_getParams($searchParams, 'pro.productCategoryIds'); if (count($productCategoryIds) > 0) { $array = array(); foreach ($productCategoryIds as $index => $productCategoryId) { $key = 'productCategory_' . $index; $array[] = ':' . $key; $params[$key] = $productCategoryId; } $joins[] = 'inner join product_category x on (x.productId = pro.id and x.active = 1 and x.categoryId in (' . implode(',', $array) . '))'; } $sql = 'select pro.id `proId`, pro.sku `proSku`, pro.name `proName` from product pro ' . implode(' ', $joins) . (count($wheres) > 0 ? ' where ' . implode(' AND ', $wheres) : ''); $result = Dao::getResultsNative($sql, $params, PDO::FETCH_ASSOC); if (count($result) === 0) { throw new Exception('No result found!'); } $proIdMap = array(); foreach ($result as $row) { $proIdMap[$row['proId']] = $row; } $rates = $this->_getRunRateData(array_keys($proIdMap)); $ratesMap = array(); foreach ($rates as $row) { $ratesMap[$row['proId']] = $row; } $data = array(); foreach ($proIdMap as $productId => $productInfo) { if (!isset($ratesMap[$productId])) { $data[$productId] = array_merge($productInfo, array('7days' => 0, '14days' => 0, '1month' => 0, '3month' => 0, '6month' => 0, '12month' => 0)); } else { $data[$productId] = array_merge($productInfo, $ratesMap[$productId]); } } if (!($asset = $this->_getExcel($data)) instanceof Asset) { throw new Exception('Failed to create a excel file'); } $results['url'] = $asset->getUrl(); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Getting the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function actionTask($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->taskId) || !($task = Task::get(trim($param->CallbackParameter->taskId))) instanceof Task) { throw new Exception('Invalid Task provided!'); } if (!isset($param->CallbackParameter->method) || ($method = trim(trim($param->CallbackParameter->method))) === '' || !method_exists($task, $method)) { throw new Exception('Invalid Action Method!'); } $comments = isset($param->CallbackParameter->comments) ? trim($param->CallbackParameter->comments) : ''; $results['item'] = $task->{$method}(Core::getUser(), $comments)->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }