/** * 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 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; }
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; }
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); $daoStart = false; try { Dao::beginTransaction(); $daoStart = true; $supplier = Supplier::get(trim($param->CallbackParameter->supplier->id)); if (!$supplier instanceof Supplier) { throw new Exception('Invalid Supplier passed in!'); } $supplierContactName = trim($param->CallbackParameter->supplier->contactName); $supplierContactNo = trim($param->CallbackParameter->supplier->contactNo); $supplierEmail = trim($param->CallbackParameter->supplier->email); if (!empty($supplierContactName) && $supplierContactName !== $supplier->getContactName()) { $supplier->setContactName($supplierContactName); } if (!empty($supplierContactNo) && $supplierContactNo !== $supplier->getContactNo()) { $supplier->setContactNo($supplierContactNo); } if (!empty($supplierEmail) && $supplierEmail !== $supplier->getEmail()) { $supplier->setEmail($supplierEmail); } $supplier->save(); $purchaseOrder = PurchaseOrder::create($supplier, trim($param->CallbackParameter->supplierRefNum), $supplierContactName, $supplierContactNo, StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->shippingCost)), StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->handlingCost)))->setTotalAmount(StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->totalPaymentDue)))->setEta(trim($param->CallbackParameter->eta))->setStatus(PurchaseOrder::STATUS_NEW)->save()->addComment(trim($param->CallbackParameter->comments), Comments::TYPE_PURCHASING); foreach ($param->CallbackParameter->items as $item) { if (!($product = Product::get(trim($item->productId))) instanceof Product) { throw new Exception('Invalid Product passed in!'); } $purchaseOrder->addItem($product, StringUtilsAbstract::getValueFromCurrency(trim($item->unitPrice)), 0 - abs(intval(trim($item->qtyOrdered)))); } if ($param->CallbackParameter->submitToSupplier === true) { $purchaseOrder->setStatus(PurchaseOrder::STATUS_ORDERED); } // For credit PO if (isset($param->CallbackParameter->type) && trim($param->CallbackParameter->type) === 'CREDIT') { $purchaseOrder->setIsCredit(true); if (isset($param->CallbackParameter->po) && ($fromPO = PurchaseOrder::get(trim($param->CallbackParameter->po->id))) instanceof PurchaseOrder) { $purchaseOrder->setFromPO($fromPO); } } $purchaseOrder->save(); $daoStart = false; Dao::commitTransaction(); $results['item'] = $purchaseOrder->getJson(); if (isset($param->CallbackParameter->confirmEmail) && trim($confirmEmail = trim($param->CallbackParameter->confirmEmail)) !== '') { $pdfFile = EntityToPDF::getPDF($purchaseOrder); $asset = Asset::registerAsset($purchaseOrder->getPurchaseOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP); EmailSender::addEmail('*****@*****.**', $confirmEmail, 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset)); EmailSender::addEmail('*****@*****.**', '*****@*****.**', 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset)); $purchaseOrder->addComment('An email sent to "' . $confirmEmail . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM); } } catch (Exception $ex) { if ($daoStart === true) { Dao::rollbackTransaction(); } $errors[] = $ex->getMessage(); } $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; }
/** * updating the shipping details * * @param unknown $sender * @param unknown $param */ public function updateShippingDetails($sender, $params) { $result = $error = $shippingInfoArray = array(); try { Dao::beginTransaction(); if (!isset($params->CallbackParameter->order) || !($order = Order::getByOrderNo($params->CallbackParameter->order->orderNo)) instanceof Order) { throw new Exception('System Error: invalid order passed in!'); } if (!$order->getStatus() instanceof OrderStatus || trim($order->getStatus()->getId()) !== trim(OrderStatus::ID_PICKED)) { throw new Exception('System Error: Order [' . $order->getOrderNo() . '] Is Not is PICKED status. Current status is [' . ($order->getStatus() instanceof OrderStatus ? $order->getStatus()->getName() : 'NULL') . ']'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('Error: there is no payment or payments has been cancelled!'); } if (!isset($params->CallbackParameter->shippingInfo)) { throw new Exception('System Error: invalid Shipping Info Details passed in!'); } $shippingInfo = $params->CallbackParameter->shippingInfo; if (!($courier = Courier::get($shippingInfo->courierId)) instanceof Courier) { throw new Exception('Invalid Courier Id [' . $shippingInfo->courierId . '] provided'); } if (intval($order->getPassPaymentCheck()) !== 1) { throw new Exception('This ' . $order->getType() . ' has NOT pass payment check yet, please let the accounting department know before further actions!'); } $notifyCust = isset($shippingInfo->notifyCust) && intval($shippingInfo->notifyCust) === 1 ? true : false; //$companyName = $shippingInfo->companyName; $contactName = $shippingInfo->contactName; $contactNo = $shippingInfo->contactNo; $shippingAddress = Address::create(trim($shippingInfo->street), trim($shippingInfo->city), trim($shippingInfo->region), trim($shippingInfo->country), trim($shippingInfo->postCode), trim($contactName), trim($contactNo)); $shipment = Shippment::create($shippingAddress, $courier, trim($shippingInfo->conNoteNo), new UDate(), $order, $contactName, trim($contactNo), trim($shippingInfo->noOfCartons), '0', StringUtilsAbstract::getValueFromCurrency(trim($shippingInfo->actualShippingCost)), isset($shippingInfo->deliveryInstructions) ? trim($shippingInfo->deliveryInstructions) : ''); $order->setStatus(OrderStatus::get(OrderStatus::ID_SHIPPED))->save(); $result['shipment'] = $shipment->getJson(); //add shipment information if ($notifyCust === true && $order->getIsFromB2B() === true) { $templateName = trim($shipment->getCourier()->getId()) === trim(Courier::ID_LOCAL_PICKUP) ? 'local_pickup' : $order->getStatus()->getName(); $notificationMsg = trim(OrderNotificationTemplateControl::getMessage($templateName, $order)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_SHIP, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->shipOrder($order, $shipment, array(), $notificationMsg, false, false); //push the status of the order to SHIPPed $emailToCustomer = trim($shipment->getCourier()->getId()) !== trim(Courier::ID_LOCAL_PICKUP); B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($order, $order->getStatus()->getMageStatus(), $notificationMsg, $emailToCustomer); if ($emailToCustomer === true) { $order->addComment('An email notification contains shippment information has been sent to customer for: ' . $order->getStatus()->getName(), Comments::TYPE_SYSTEM); } } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $error[] = $ex->getMessage(); } $params->ResponseData = StringUtilsAbstract::getJson($result, $error); }
public function getPaymentSummary() { $total = $this->order->getTotalAmount(); $shippingCostIncGST = StringUtilsAbstract::getValueFromCurrency(implode('', $this->order->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST))); $totalWithOutShipping = $total - $shippingCostIncGST; $totalWithOutShippingNoGST = $totalWithOutShipping / 1.1; $gst = $totalWithOutShipping - $totalWithOutShippingNoGST; $html = $this->_getPaymentSummaryRow('Total Excl. GST:', '$' . number_format($totalWithOutShippingNoGST, 2, '.', ','), 'grandTotalNoGST'); $html .= $this->_getPaymentSummaryRow('Total GST:', '$' . number_format($gst, 2, '.', ','), 'gst'); $html .= $this->_getPaymentSummaryRow('Sub Total Incl. GST:', '$' . number_format($totalWithOutShipping, 2, '.', ','), 'grandTotal'); $html .= $this->_getPaymentSummaryRow('Shipping Incl. GST:', '$' . number_format((double) $shippingCostIncGST, 2, '.', ','), 'grandTotal'); $html .= $this->_getPaymentSummaryRow('<strong>Grand Total Incl. GST:</strong>', '<strong>$' . number_format((double) $total, 2, '.', ',') . '</strong>', 'grandTotal'); $html .= $this->_getPaymentSummaryRow('Paid to Date:', '$' . number_format($this->order->getTotalPaid(), 2, '.', ','), 'paidTotal'); $overDueClass = $this->order->getTotalDue() > 0 ? 'overdue' : ''; $html .= $this->_getPaymentSummaryRow('<strong class="text-danger">Balance Due:</strong>', '<strong class="text-danger">$' . number_format($this->order->getTotalDue(), 2, '.', ',') . '</strong>', 'dueTotal ' . $overDueClass); return $html; }
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $customer = Customer::get(trim($param->CallbackParameter->customer->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } if (!isset($param->CallbackParameter->applyTo) || ($applyTo = trim($param->CallbackParameter->applyTo)) === '' || !in_array($applyTo, CreditNote::getApplyToTypes())) { throw new Exception('Invalid Apply To passed in!'); } if (isset($param->CallbackParameter->creditNoteId) && ($creditNote = CreditNote::get(trim($param->CallbackParameter->creditNoteId))) instanceof CreditNote) { $creditNote = $creditNote; } else { if (isset($param->CallbackParameter->orderId) && ($order = Order::get(trim($param->CallbackParameter->orderId))) instanceof Order) { $creditNote = CreditNote::createFromOrder($order, $customer, trim($param->CallbackParameter->description)); } else { $creditNote = CreditNote::create($customer, trim($param->CallbackParameter->description)); } } $creditNote->setShippingValue(isset($param->CallbackParameter->totalShippingCost) ? StringUtilsAbstract::getValueFromCurrency($param->CallbackParameter->totalShippingCost) : 0); if (isset($param->CallbackParameter->shippingAddr)) { $shippAddress = Address::create($param->CallbackParameter->shippingAddr->street, $param->CallbackParameter->shippingAddr->city, $param->CallbackParameter->shippingAddr->region, $param->CallbackParameter->shippingAddr->country, $param->CallbackParameter->shippingAddr->postCode, $param->CallbackParameter->shippingAddr->contactName, $param->CallbackParameter->shippingAddr->contactNo); $customer->setShippingAddress($shippAddress); } $printItAfterSave = false; if (isset($param->CallbackParameter->printIt)) { $printItAfterSave = intval($param->CallbackParameter->printIt) === 1 ? true : false; } if (isset($param->CallbackParameter->comments)) { $comments = trim($param->CallbackParameter->comments); $creditNote->addComment($comments, Comments::TYPE_SALES); } $totalPaymentDue = $creditNote->getShippingValue(); $hasShipped = $creditNote->getOrder() instanceof Order && Shippment::countByCriteria('orderId = ?', array($creditNote->getOrder()->getId())) > 0; $creditNoteItemsMap = array(); foreach ($param->CallbackParameter->items as $item) { if (!($product = Product::get(trim($item->product->id))) instanceof Product) { throw new Exception('Invalid Product passed in!'); } $unitPrice = StringUtilsAbstract::getValueFromCurrency(trim($item->unitPrice)); $qtyOrdered = trim($item->qtyOrdered); $totalPrice = StringUtilsAbstract::getValueFromCurrency(trim($item->totalPrice)); $itemDescription = trim($item->itemDescription); $active = trim($item->valid); $totalPaymentDue += $totalPrice; if (is_numeric($item->creditNoteItemId) && !CreditNoteItem::get(trim($item->creditNoteItemId)) instanceof CreditNoteItem) { throw new Exception('Invalid Credit Note Item passed in'); } $unitCost = $product->getUnitCost(); $orderItem = null; if (isset($item->orderItemId) && ($orderItem = OrderItem::get(trim($item->orderItemId))) instanceof OrderItem) { $unitCost = $orderItem->getUnitCost(); } $creditNoteItem = is_numeric($item->creditNoteItemId) ? CreditNoteItem::get(trim($item->creditNoteItemId))->setActive($active)->setProduct($product)->setQty($qtyOrdered)->setUnitPrice($unitPrice)->setItemDescription($itemDescription)->setUnitCost($unitCost)->setTotalPrice($totalPrice)->save() : ($orderItem instanceof OrderItem ? CreditNoteItem::createFromOrderItem($creditNote, $orderItem, $qtyOrdered, $unitPrice, $itemDescription, $unitCost, $totalPrice) : CreditNoteItem::create($creditNote, $product, $qtyOrdered, $unitPrice, $itemDescription, $unitCost, $totalPrice)); if (intval($creditNoteItem->getActive()) === 1) { if (!isset($creditNoteItemsMap[$product->getId()])) { $creditNoteItemsMap[$product->getId()] = 0; } $creditNoteItemsMap[$product->getId()] += $qtyOrdered; } //if we are not creating from a order, or there are shippments for this order then if (!$creditNote->getOrder() instanceof Order || $hasShipped === true) { switch (trim($item->stockData)) { case 'StockOnHand': $product->returnedIntoSOH($qtyOrdered, $creditNoteItem->getUnitCost(), '', $creditNoteItem); break; case 'StockOnRMA': $product->returnedIntoRMA($qtyOrdered, $creditNoteItem->getUnitCost(), '', $creditNoteItem); break; default: throw new Exception('System Error: NO where to transfer the stock: ' . trim($item->stockData) . ' for product(SKU=' . $product->getSku() . ').'); } } else { //revert all the shipped stock foreach (OrderItem::getAllByCriteria('ord_item.orderId = ? and ord_item.isShipped = 1', array($creditNote->getOrder()->getId())) as $orderItem) { $orderItem->setIsShipped(false)->save(); } //revert all the picked stock foreach (OrderItem::getAllByCriteria('ord_item.orderId = ? and ord_item.isPicked = 1', array($creditNote->getOrder()->getId())) as $orderItem) { $orderItem->setIsPicked(false)->save(); } } } if (($paymentMethod = PaymentMethod::get(trim($param->CallbackParameter->paymentMethodId))) instanceof PaymentMethod) { $creditNote->setTotalPaid($totalPaidAmount = $param->CallbackParameter->totalPaidAmount)->addPayment($paymentMethod, $totalPaidAmount); } $creditNote->setTotalValue($totalPaymentDue)->setApplyTo($applyTo)->save(); //if need to check half credited orders if ($creditNote->getOrder() instanceof Order && $hasShipped === false) { $orderItemMap = array(); foreach ($order->getOrderItems() as $orderItem) { $productId = $orderItem->getProduct()->getId(); if (!isset($orderItemMap[$productId])) { $orderItemMap[$productId] = 0; } $orderItemMap[$productId] += $orderItem->getQtyOrdered(); } //figure out the difference foreach ($creditNoteItemsMap as $productId => $qty) { if (isset($orderItemMap[$productId])) { if ($orderItemMap[$productId] <= $qty) { //credited more than orderred unset($orderItemMap[$productId]); } else { //credited less then ordered $orderItemMap[$productId] = $orderItemMap[$productId] - $qty; } } } $orderItemMap = array_filter($orderItemMap); if (count($orderItemMap) > 0) { //there are difference $creditNote->creditFullOrder(); $newOrder = Order::create($creditNote->getOrder()->getCustomer(), $creditNote->getOrder()->getType() === 'INVOICE' ? Order::TYPE_ORDER : $creditNote->getOrder()->getType(), null, 'Spliting order because of partial credit note(CreditNoteNo:.' . $creditNote->getCreditNoteNo() . ') created', null, $creditNote->getOrder()->getOrderDate(), false, $creditNote->getOrder()->getShippingAddr(), $creditNote->getOrder()->getBillingAddr(), $creditNote->getOrder()->getPassPaymentCheck(), $creditNote->getOrder()->getPONo(), $creditNote->getOrder())->addComment('Created because of partial credit from '); $totalAmount = 0; foreach ($orderItemMap as $productId => $qty) { $orderItems = OrderItem::getAllByCriteria('productId = ? and orderId = ?', array($productId, $creditNote->getOrder()->getId()), true, 1, 1); if (count($orderItems) > 0) { $totalAmount += $orderItems[0]->getUnitPrice() * $qty; } $newOrder->addItem($orderItems[0]->getProduct(), $orderItems[0]->getUnitPrice(), $qty, $orderItems[0]->getTotalPrice(), $orderItems[0]->getMageOrderId(), $orderItems[0]->getEta(), $orderItems[0]->getItemDescription()); } if (count($shippingMethods = $creditNote->getOrder()->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD)) > 0) { $newOrder->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $shippingMethods[0], true); } if (count($shippingCost = $creditNote->getOrder()->getInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST)) > 0) { $newOrder->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST, $shippingCost[0], true); $totalAmount += StringUtilsAbstract::getValueFromCurrency($shippingCost[0]); } $results['newOrder'] = $newOrder->setTotalAmount($totalAmount)->save()->getJson(); $creditNote->getOrder()->setStatus(OrderStatus::get(OrderStatus::ID_CANCELLED))->save()->addComment('This ' . $creditNote->getOrder()->getType() . ' is CANCELED, because of partial credit (CreditNoteNo:<a href="/creditnote/' . $creditNote->getId() . '.html" target="_BLANK">' . $creditNote->getCreditNoteNo() . '</a>) is created and a new ' . $newOrder->getType() . ' (<a href="/orderdetails/' . $newOrder->getId() . '.html?blanklayout=1">' . $newOrder->getOrderNo() . '</a>) is created for the diference.', Comments::TYPE_MEMO); } else { $creditNote->getOrder()->setStatus(OrderStatus::get(OrderStatus::ID_CANCELLED))->save()->addComment('This ' . $creditNote->getOrder()->getType() . ' is CANCELED, because of full credit (CreditNoteNo:<a href="/creditnote/' . $creditNote->getId() . '.html" target="_BLANK">' . $creditNote->getCreditNoteNo() . '</a>) is created.', Comments::TYPE_MEMO); } } $results['item'] = $creditNote->getJson(); $results['redirectURL'] = '/creditnote/' . $creditNote->getId() . '.html?' . $_SERVER['QUERY_STRING']; if ($printItAfterSave === true) { $results['printURL'] = '/print/creditnote/' . $creditNote->getId() . '.html?pdf=1'; } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage() . '<pre>' . $ex->getTraceAsString() . '</pre>'; } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $customer = Customer::get(trim($param->CallbackParameter->customer->id)); if (!$customer instanceof Customer) { throw new Exception('Invalid Customer passed in!'); } if (!isset($param->CallbackParameter->type) || ($type = trim($param->CallbackParameter->type)) === '' || !in_array($type, Order::getAllTypes())) { throw new Exception('Invalid type passed in!'); } $order = null; if (isset($param->CallbackParameter->orderId) && ($orderId = trim($param->CallbackParameter->orderId)) !== '') { if (!($order = Order::get($orderId)) instanceof Order) { throw new Exception('Invalid Order to edit!'); } } $orderCloneFrom = null; if (isset($param->CallbackParameter->orderCloneFromId) && ($orderCloneFromId = trim($param->CallbackParameter->orderCloneFromId)) !== '') { if (!($orderCloneFrom = Order::get($orderCloneFromId)) instanceof Order) { throw new Exception('Invalid Order to clone from!'); } } $shipped = isset($param->CallbackParameter->shipped) && intval($param->CallbackParameter->shipped) === 1; $poNo = isset($param->CallbackParameter->poNo) && trim($param->CallbackParameter->poNo) !== '' ? trim($param->CallbackParameter->poNo) : ''; if (isset($param->CallbackParameter->shippingAddr)) { $shippAddress = $order instanceof Order ? $order->getShippingAddr() : null; $shippAddress = Address::create($param->CallbackParameter->shippingAddr->street, $param->CallbackParameter->shippingAddr->city, $param->CallbackParameter->shippingAddr->region, $param->CallbackParameter->shippingAddr->country, $param->CallbackParameter->shippingAddr->postCode, $param->CallbackParameter->shippingAddr->contactName, $param->CallbackParameter->shippingAddr->contactNo, $param->CallbackParameter->shippingAddr->companyName, $shippAddress); } else { $shippAddress = $customer->getShippingAddress(); } $printItAfterSave = false; if (isset($param->CallbackParameter->printIt)) { $printItAfterSave = intval($param->CallbackParameter->printIt) === 1 ? true : false; } if (!$order instanceof Order) { $order = Order::create($customer, $type, null, '', OrderStatus::get(OrderStatus::ID_NEW), new UDate(), false, $shippAddress, $customer->getBillingAddress(), false, $poNo, $orderCloneFrom); } else { $order->setType($type)->setPONo($poNo)->save(); } $totalPaymentDue = 0; if (trim($param->CallbackParameter->paymentMethodId)) { $paymentMethod = PaymentMethod::get(trim($param->CallbackParameter->paymentMethodId)); if (!$paymentMethod instanceof PaymentMethod) { throw new Exception('Invalid PaymentMethod passed in!'); } $totalPaidAmount = trim($param->CallbackParameter->totalPaidAmount); $order->addPayment($paymentMethod, $totalPaidAmount); $order = Order::get($order->getId()); $order->addInfo(OrderInfoType::ID_MAGE_ORDER_PAYMENT_METHOD, $paymentMethod->getName(), true); if ($shipped === true) { $order->setType(Order::TYPE_INVOICE); } } else { $paymentMethod = ''; $totalPaidAmount = 0; } foreach ($param->CallbackParameter->items as $item) { $product = Product::get(trim($item->product->id)); if (!$product instanceof Product) { throw new Exception('Invalid Product passed in!'); } if (isset($item->active) && intval($item->active) === 1 && intval($product->getActive()) !== 1 && $type === Order::TYPE_INVOICE) { throw new Exception('Product(SKU:' . $product->getSku() . ') is DEACTIVATED, please change it to be proper product before converting it to a ' . $type . '!'); } $unitPrice = trim($item->unitPrice); $qtyOrdered = trim($item->qtyOrdered); $totalPrice = trim($item->totalPrice); $itemDescription = trim($item->itemDescription); if (intval($item->active) === 1) { $totalPaymentDue += $totalPrice; if ($orderCloneFrom instanceof Order || !($orderItem = OrderItem::get($item->id)) instanceof OrderItem) { $orderItem = OrderItem::create($order, $product, $unitPrice, $qtyOrdered, $totalPrice, 0, null, $itemDescription); } else { $orderItem->setActive(intval($item->active))->setProduct($product)->setUnitPrice($unitPrice)->setQtyOrdered($qtyOrdered)->setTotalPrice($totalPrice)->setItemDescription($itemDescription)->save(); $existingSellingItems = SellingItem::getAllByCriteria('orderItemId = ?', array($orderItem->getId())); foreach ($existingSellingItems as $sellingItem) { //DELETING ALL SERIAL NUMBER BEFORE ADDING $sellingItem->setActive(false)->save(); } } $orderItem = OrderItem::get($orderItem->getId())->reCalMarginFromProduct()->resetCostNMarginFromKits()->save(); } else { if ($orderCloneFrom instanceof Order) { continue; } elseif (($orderItem = OrderItem::get($item->id)) instanceof OrderItem) { $orderItem->setActive(false)->save(); } } if (isset($item->serials) && count($item->serials) > 0) { foreach ($item->serials as $serialNo) { $orderItem->addSellingItem($serialNo)->save(); } } if ($shipped === true) { $orderItem->setIsPicked(true)->save(); } } if (isset($param->CallbackParameter->courierId)) { $totalShippingCost = 0; $courier = null; if (is_numeric($courierId = trim($param->CallbackParameter->courierId))) { $courier = Courier::get($courierId); if (!$courier instanceof Courier) { throw new Exception('Invalid Courier passed in!'); } $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $courier->getName(), true); } else { $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_METHOD, $courierId, true); } if (isset($param->CallbackParameter->totalShippingCost)) { $totalShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->totalShippingCost)); $order->addInfo(OrderInfoType::ID_MAGE_ORDER_SHIPPING_COST, StringUtilsAbstract::getCurrency($totalShippingCost), true); } if ($shipped === true) { if (!$courier instanceof Courier) { $courier = Courier::get(Courier::ID_LOCAL_PICKUP); } Shippment::create($shippAddress, $courier, '', new UDate(), $order, ''); } } else { $courier = ''; $totalShippingCost = 0; } $totalPaymentDue += $totalShippingCost; $comments = isset($param->CallbackParameter->comments) ? trim($param->CallbackParameter->comments) : ''; $order = $order->addComment($comments, Comments::TYPE_SALES)->setTotalPaid($totalPaidAmount); if ($shipped === true) { $order->setStatus(OrderStatus::get(OrderStatus::ID_SHIPPED)); } $order->setTotalAmount($totalPaymentDue)->save(); if (isset($param->CallbackParameter->newMemo) && ($newMemo = trim($param->CallbackParameter->newMemo)) !== '') { $order->addComment($newMemo, Comments::TYPE_MEMO); } $results['item'] = $order->getJson(); if ($printItAfterSave === true) { $results['printURL'] = '/print/order/' . $order->getId() . '.html?pdf=1'; } $results['redirectURL'] = '/order/' . $order->getId() . '.html' . (trim($_SERVER['QUERY_STRING']) === '' ? '' : '?' . $_SERVER['QUERY_STRING']); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * create/update product via datafeed. * * @param array $params * * @return array */ private function _dataFeedImport($params) { try { Dao::beginTransaction(); $this->_runner->log('dataFeedImport: ', __CLASS__ . '::' . __FUNCTION__); $sku = $this->_getPram($params, 'sku', null, true); $name = $this->_getPram($params, 'name', null, true); $shortDesc = $this->_getPram($params, 'short_description', $name); $fullDesc = $this->_getPram($params, 'description', ''); $price = StringUtilsAbstract::getValueFromCurrency($this->_getPram($params, 'price', null, true)); $supplierName = $this->_getPram($params, 'supplier', null, true); $supplierCode = $this->_getPram($params, 'supplier_code', null, true); $supplier = $this->_getEntityByName($supplierName, 'Supplier'); if (!$supplier instanceof Supplier) { throw new Exception("invalid supplier:" . $supplierName); } $manufacturerId = $this->_getPram($params, 'manufacturer_id', null, true); $manufacturer = Manufacturer::get($manufacturerId); if (!$manufacturer instanceof Manufacturer) { throw new Exception("invalid Manufacturer:" . $manufacturerId); } $statusName = $this->_getPram($params, 'availability', null, true); $status = $this->_getEntityByName($statusName, 'ProductStatus'); if (!$status instanceof ProductStatus) { throw new Exception("invalid ProductStatus:" . $statusName); } $assetAccNo = $this->_getPram($params, 'assetAccNo', null); $revenueAccNo = $this->_getPram($params, 'revenueAccNo', null); $costAccNo = $this->_getPram($params, 'costAccNo', null); $categoryIds = $this->_getPram($params, 'category_ids', array()); $canSupplyQty = $this->_getPram($params, 'qty', 0); $weight = $this->_getPram($params, 'weight', 0); $images = $this->_getPram($params, 'images', array()); $showOnWeb = $this->_getPram($params, 'showonweb', true); $attributesetId = $this->_getPram($params, 'attributesetId', null); $canUpdate = false; //if we have this product already, then skip if (!($product = Product::getBySku($sku)) instanceof Product) { $this->_runner->log('new SKU(' . $sku . ') for import, creating ...', '', APIService::TAB); $product = Product::create($sku, $name, '', null, null, false, $shortDesc, $fullDesc, $manufacturer, $assetAccNo, $revenueAccNo, $costAccNo, null, null, true, $weight, $attributesetId); $this->log_product("NEW", "=== new === sku={$sku}, name={$name}, shortDesc={$shortDesc}, fullDesc={$fullDesc}, category=" . implode(', ', $categoryIds), '', APIService::TAB); $canUpdate = true; } else { //$this->log_product("UPDATE", "=== update === sku=$sku, name=$name, shortDesc=$shortDesc, fullDesc=$fullDesc, category=" . implode(', ', $categoryIds), '', APIService::TAB); //if there is no price matching rule for this product if (($rulesCount = intval(ProductPriceMatchRule::countByCriteria('active = 1 and productId = ?', array($product->getId())))) === 0) { $this->_runner->log('Found SKU(' . $sku . '): ', '', APIService::TAB); $fullAsset = Asset::getAsset($product->getFullDescAssetId()); $this->_runner->log('Finding asset for full description, assetId:' . ($fullAsset instanceof Asset ? $fullAsset->getAssetId() : ''), '', APIService::TAB . APIService::TAB); $fullAssetContent = ''; if ($fullAsset instanceof Asset) { $fullAssetContent = file_get_contents($fullAsset->getPath()); $this->_runner->log('Got full asset content before html_decode: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB); $fullAssetContent = trim(str_replace(' ', '', $fullAssetContent)); $this->_runner->log('Got full asset content after html_code: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB); } if ($fullAssetContent === '') { $this->_runner->log('GOT BLANK FULL DESD. Updating full description.', '', APIService::TAB . APIService::TAB . APIService::TAB); if ($fullAsset instanceof Asset) { Asset::removeAssets(array($fullAsset->getAssetId())); $this->_runner->log('REMOVED old empty asset for full description', '', APIService::TAB . APIService::TAB . APIService::TAB); } $fullAsset = Asset::registerAsset('full_description_for_product.txt', $fullDesc, Asset::TYPE_PRODUCT_DEC); $product->setFullDescAssetId($fullAsset->getAssetId())->save(); $this->_runner->log('Added a new full description with assetId: ' . $fullAsset->getAssetId(), '', APIService::TAB . APIService::TAB); $canUpdate = true; $this->log_product("UPDATE", "=== updating === sku={$sku} Found ", '', APIService::TAB); } else { $this->log_product("SKIP", "=== SKIP updating === sku={$sku} for full description not null", '', APIService::TAB); } } else { $this->_runner->log('SKIP updating. Found ProductPriceMatchRule count:' . $rulesCount, '', APIService::TAB); $this->log_product("SKIP", "=== SKIP updating === sku={$sku} Found ProductPriceMatchRule count:{$rulesCount}", '', APIService::TAB); } } $json = $product->getJson(); //only update categories and status when there is no pricematching rule or created new if ($canUpdate === true) { //short description, name, manufacturer $this->_runner->log('Updating the price to: ' . StringUtilsAbstract::getCurrency($price), '', APIService::TAB . APIService::TAB); $product->setShortDescription($shortDesc)->setName($name)->setManufacturer($manufacturer)->setWeight($weight)->setSellOnWeb($showOnWeb)->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price); //show on web if (is_array($categoryIds) && count($categoryIds) > 0) { $this->_runner->log('Updating the categories: ' . implode(', ', $categoryIds), '', APIService::TAB . APIService::TAB); foreach ($categoryIds as $categoryId) { if (!($category = ProductCategory::get($categoryId)) instanceof ProductCategory) { continue; } if (count($ids = explode(ProductCategory::POSITION_SEPARATOR, trim($category->getPosition()))) > 0) { foreach (ProductCategory::getAllByCriteria('id in (' . implode(',', $ids) . ')') as $cate) { $product->addCategory($cate); $this->_runner->log('Updated Category ID: ' . $cate->getId(), '', APIService::TAB . APIService::TAB . APIService::TAB); } } } } //updating the images if (is_array($images) && count($images) > 0) { $this->_runner->log('Processing ' . count($images) . ' image(s) ...', '', APIService::TAB . APIService::TAB); $exisitingImgsKeys = array(); $this->_runner->log('Checking exsiting images...', '', APIService::TAB . APIService::TAB . APIService::TAB); $exisitingImgs = $product->getImages(); $this->_runner->log('Got ' . count($exisitingImgs) . ' exisiting image(s), keys: ', '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB); foreach ($exisitingImgs as $image) { if (($asset = Asset::getAsset($image->getImageAssetId())) instanceof Asset) { $imgKey = md5($asset->read()); $exisitingImgsKeys[] = $imgKey; $this->_runner->log($imgKey, '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB); } } $this->_runner->log('Checking ' . count($images) . ' new image(s) ...', '', APIService::TAB . APIService::TAB); foreach ($images as $image) { //if haven't got any content at all if (!isset($image['content'])) { $this->_runner->log('No Content, SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB); continue; } $newImageContent = base64_decode($image['content']); $newImgKey = md5($newImageContent); //if we've got the image already if (in_array($newImgKey, $exisitingImgsKeys)) { $this->_runner->log('Same Image Exists[' . $newImgKey . '], SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB); continue; } $asset = Asset::registerAsset($image['name'], $newImageContent, Asset::TYPE_PRODUCT_IMG); $this->_runner->log('Registered a new Asset [AssetID=' . $asset->getAssetId() . '].', '', APIService::TAB . APIService::TAB . APIService::TAB); $product->addImage($asset); $this->_runner->log('Added to product(SKU=' . $product->getSku() . ')', '', APIService::TAB . APIService::TAB . APIService::TAB); } } $product->setStatus($status); $this->_runner->log('Updated Status to: ' . $status->getName(), '', APIService::TAB . APIService::TAB); $product->addSupplier($supplier, $supplierCode, $canSupplyQty); $this->_runner->log('Updated Supplier(ID' . $supplier->getId() . ', name=' . $supplier->getName() . ') with code: ' . $supplierCode . 'canSupplyQty=' . $canSupplyQty, '', APIService::TAB . APIService::TAB); $json = $product->save()->getJson(); $this->_runner->log('Saved Product ID: ' . $product->getId(), '', APIService::TAB . APIService::TAB); } Dao::commitTransaction(); return $json; } catch (Exception $e) { Dao::rollbackTransaction(); throw $e; } }
/** * The row with default value * * @param UDate $lastUpdatedInDB * @param Product $product * @param string $preFix * @param bool $debug * * @return multitype:string number */ private static function _getRowWithDefaultValues(UDate $lastUpdatedInDB, Product $product = null, $preFix = '', $debug = false) { $attributeSetDefault = 'Default'; $attributeSetName = $attributeSetDefault; $enabled = true; $sku = $statusId = $productName = $rrpPrice = $weight = $shortDescription = $fullDecription = $supplierName = $supplierCode = $manufacturerName = $asNewFrom = $asNewTo = $specialPrice = $specialPriceFromDate = $specialPriceToDate = ''; $categoryIds = array(2); //default category if ($product instanceof Product) { $sku = trim($product->getSku()); $productName = trim($product->getName()); $shortDescription = trim($product->getShortDescription()); $asNewFrom = $product->getAsNewFromDate() instanceof UDate ? $product->getAsNewFromDate()->format('Y-m-d H:i:sP') : ''; $asNewTo = $product->getAsNewToDate() instanceof UDate ? $product->getAsNewToDate()->format('Y-m-d H:i:sP') : ''; $weight = trim($product->getWeight()); if ($product->getAttributeSet() instanceof ProductAttributeSet) { $attributeSetName = $product->getAttributeSet()->getName(); self::_log('-- attributeSetName ', __CLASS__ . '::' . __FUNCTION__ . " attributeSetName={$attributeSetName}", $preFix); } //RRP if (($rrp = $product->getRRP()) instanceof ProductPrice) { $rrpPrice = StringUtilsAbstract::getValueFromCurrency($rrp->getPrice()); } //special price if (($specialPriceObj = $product->getNearestSpecialPrice()) instanceof ProductPrice) { $specialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); if ($specialPrice == 0) { $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } } else { // delete the special price //$specialPrice = StringUtilsAbstract::getValueFromCurrency('99999999'); //$specialPrice = '9999999'; $specialPrice = ''; $specialPriceFromDate = '1990-10-10'; $specialPriceToDate = '2009-10-10'; } // if it is the daily promotion time then overwrite the special price with the daily special price $isDailyPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISDAILYPROMOTIONTIME)); if ($isDailyPromotionTime === 1) { // get daily promotion price if (($specialPriceObj = $product->getDailySpecialPrice()) instanceof ProductPrice) { $dailySpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($dailySpecialPrice != 0) { $specialPrice = $dailySpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } // if it is the daily promotion time then overwrite the special price with the daily special price $isWeekendPromotionTime = intval(SystemSettings::getSettings(SystemSettings::TYP_ISWEEKENDPROMOTIONTIME)); if ($isWeekendPromotionTime === 1) { // get weekend promotion price if (($specialPriceObj = $product->getWeekendSpecialPrice()) instanceof ProductPrice) { $weekendSpecialPrice = StringUtilsAbstract::getValueFromCurrency($specialPriceObj->getPrice()); if ($weekendSpecialPrice != 0) { $specialPrice = $weekendSpecialPrice; $specialPriceFromDate = $specialPriceObj->getStart()->format('Y-m-d H:i:sP'); $specialPriceToDate = $specialPriceObj->getEnd()->format('Y-m-d H:i:sP'); } } } //full description if (($asset = Asset::getAsset($product->getFullDescAssetId())) instanceof Asset) { //$fullDecription = '"' . $asset->read() . '"'; $fullDecription = $asset->read(); } //supplier if (count($supplierCodes = SupplierCode::getAllByCriteria('productId = ?', array($product->getId()), true, 1, 1)) > 0) { $supplierName = ($supplier = $supplierCodes[0]->getSupplier()) instanceof Supplier ? $supplier->getName() : ''; $supplierCode = trim($supplierCodes[0]->getCode()); } //Manufacturer if ($product->getManufacturer() instanceof Manufacturer) { $manufacturerName = trim($product->getManufacturer()->getName()); } //disable or enabled if (intval($product->getActive()) === 0 || intval($product->getSellOnWeb()) === 0) { $enabled = false; } else { if ($product->getStatus() instanceof ProductStatus && intval($product->getStatus()->getId()) === ProductStatus::ID_DISABLED) { $enabled = false; } } //categories if (count($categories = Product_Category::getAllByCriteria('productId = ?', array($product->getId()))) > 0) { foreach ($categories as $category) { if (!$category->getCategory() instanceof ProductCategory || ($mageCateId = trim($category->getCategory()->getMageId())) === '') { continue; } if (trim($attributeSetName) === $attributeSetDefault && ($productAttributeSet = $category->getCategory()->getProductAttributeSet()) instanceof ProductAttributeSet) { $attributeSetName = trim($productAttributeSet->getName()); } $categoryIds[] = $mageCateId; } } //ProductStatus if ($product->getStatus() instanceof ProductStatus) { $statusId = $product->getStatus()->getName(); } } $categoryIds = array_unique($categoryIds); return array("store" => 'default', "websites" => 'base', "attribute_set" => $attributeSetName, "type" => 'simple', "category_ids" => implode(',', $categoryIds), "sku" => $sku, "name" => $productName, "price" => $rrpPrice, "special_from_date" => $specialPriceFromDate, "special_to_date" => $specialPriceToDate, "special_price" => $specialPrice, "news_from_date" => $asNewFrom, "news_to_date" => $asNewTo, "status" => intval($enabled) === 1 ? 1 : 2, "visibility" => 4, "tax_class_id" => 2, "description" => $fullDecription, "short_description" => $shortDescription, "supplier" => $supplierName, "man_code" => '', "sup_code" => $supplierCode, "meta_title" => '', "meta_description" => '', "manufacturer" => $manufacturerName, "url_key" => '', "url_path" => '', "custom_design" => '', "page_layout" => '', "country_of_manufacture" => '', "msrp_enabled" => '', "msrp_display_actual_price_type" => '', "meta_keyword" => '', "custom_layout_update" => '', "custom_design_from" => '', "custom_design_to" => '', "weight" => $weight, "msrp" => 'Use config', "gift_wrapping_price" => '', "qty" => 99, "min_qty" => 99, "use_config_min_qty" => 99, "is_qty_decimal" => '', "backorders" => '', "use_config_backorders" => '', "min_sale_qty" => '', "use_config_min_sale_qty" => '', "max_sale_qty" => '', "use_config_max_sale_qty" => '', "all_ln_stock" => $statusId, "is_in_stock" => 1, "low_stock_date" => '', "notify_stock_qty" => '', "use_config_notify_stock_qty" => '', "manage_stock" => '', "use_config_manage_stock" => '', "stock_status_changed_auto" => '', "use_config_qty_increments" => '', "qty_increments" => '', "use_config_enable_qty_inc" => '', "enable_qty_increments" => '', "is_decimal_divided" => '', "stock_status_changed_automatically" => '', "use_config_enable_qty_increments" => '', "image" => '', "small_image" => '', "thumbnail" => '', "media_gallery" => '', "is_recurring" => '', "media_gallery_reset" => 0); }
/** * updateproduct price * * @param unknown $sender * @param unknown $param */ public function updatePrice($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $id = isset($param->CallbackParameter->productId) ? $param->CallbackParameter->productId : ''; if (!($product = Product::get($id)) instanceof Product) { throw new Exception('Invalid product!'); } if (!isset($param->CallbackParameter->newPrice)) { throw new Exception('No New Price Provided!'); } $isSpecial = 0; if (isset($param->CallbackParameter->isSpecial)) { $isSpecial = intval($param->CallbackParameter->isSpecial); } $newPrice = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->newPrice)); if ($isSpecial === 0) { $priceType = ProductPriceType::ID_RRP; } else { $priceType = ProductPriceType::ID_CASUAL_SPECIAL; } $prices = ProductPrice::getAllByCriteria('productId = ? and typeId = ?', array($product->getId(), $priceType), true, 1, 1); if (count($prices) > 0) { $msg = 'Update price for product(SKU=' . $product->getSku() . ') to ' . StringUtilsAbstract::getCurrency($newPrice); $price = $prices[0]; } else { $msg = 'New Price Created for product(SKU=' . $product->getSku() . '): ' . StringUtilsAbstract::getCurrency($newPrice); $price = new ProductPrice(); $price->setProduct($product)->setType(ProductPriceType::get($priceType)); } $price->setPrice($newPrice)->save()->addComment($msg, Comments::TYPE_NORMAL)->addLog($msg, Log::TYPE_SYSTEM); $product->addComment($msg, Log::TYPE_SYSTEM)->addLog($msg, Log::TYPE_SYSTEM); $results['item'] = $product->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage() . $ex->getTraceAsString(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * Creating a new shippment * * @param Address $address * @param Courier $courier * @param string $consignmentNo * @param string $shippingDate * @param Order $order * @param string $contactName * @param string $contactNo * @param number $noOfCartons * @param string $estShippingCost The est shipping cost * @param string $actualShippingCost The actual shipping cost * @param string $deliveryInstructions The delivery instructions * @param string $mageShipmentId The magento shippment id * * @return Shippment */ public static function create(Address $address, Courier $courier, $consignmentNo, $shippingDate, Order $order, $contactName, $contactNo = '', $noOfCartons = 0, $estShippingCost = '0.00', $actualShippingCost = '0.00', $deliveryInstructions = '', $mageShipmentId = '') { $shippment = new Shippment(); if (($shippingDate = trim($shippingDate)) === '') { $shippingDate = new UDate(); } $estShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($estShippingCost)); $actualShippingCost = StringUtilsAbstract::getValueFromCurrency(trim($actualShippingCost)); $msg = 'Shipment create for Order(' . $order->getOrderNo() . ') to address(' . trim($address) . ') via Courier(' . $courier->getName() . ') with ConNote(=' . $consignmentNo . ') on ' . $shippingDate . '(UTC) with actualCost = ' . StringUtilsAbstract::getCurrency($actualShippingCost); $shippment = $shippment->setAddress($address)->setCourier($courier)->setConNoteNo(trim($consignmentNo))->setOrder($order)->setReceiver(trim($contactName))->setContact(trim($contactNo))->setShippingDate(trim($shippingDate))->setNoOfCartons(trim($noOfCartons))->setEstShippingCost($estShippingCost)->setActualShippingCost($actualShippingCost)->setDeliveryInstructions(trim($deliveryInstructions))->setMageShipmentId(trim($mageShipmentId))->setActive(true)->save()->addLog($msg, Log::TYPE_SYSTEM, get_class($shippment) . '_CREATION', __CLASS__ . '::' . __FUNCTION__); $order->addComment($msg, Comments::TYPE_SYSTEM)->addLog($msg, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); return $shippment; }
private function _setPrices(Product &$product, $param) { if (isset($param->CallbackParameter->prices) && count($prices = $param->CallbackParameter->prices) > 0) { //delete all price first $deleteIds = array(); foreach ($prices as $price) { if (trim($price->active) === '0' && isset($price->id)) { $deleteIds[] = trim($price->id); } } if (count($deleteIds) > 0) { ProductPrice::updateByCriteria('active = 0', 'id in (' . str_repeat('?', count($deleteIds)) . ')', $deleteIds); } //update or create new foreach ($prices as $price) { if (isset($price->id) && in_array(trim($price->id), $deleteIds)) { continue; } if (!($type = ProductPriceType::get(trim($price->typeId))) instanceof ProductPriceType) { continue; } $priceValue = trim($price->value); $start = trim($price->start); $end = trim($price->end); if (!is_numeric(StringUtilsAbstract::getValueFromCurrency($priceValue))) { throw new Exception('Invalid price: ' . $priceValue); } if (!isset($price->id) || ($id = trim($price->id)) === '') { if (trim($price->active) === '1') { ProductPrice::create($product, $type, $priceValue, $start, $end); } //if it's deactivated one, ignore } else { if (($productPrice = ProductPrice::get($id)) instanceof ProductPrice) { $productPrice->setPrice($priceValue)->setType($type)->setProduct($product)->setStart($start)->setEnd($end)->save(); } } } } return $this; }
/** * * @param unknown $sender * @param unknown $params * @throws Exception */ public function addPayment($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->againstEntity) || !isset($param->CallbackParameter->againstEntity->entity) || !isset($param->CallbackParameter->againstEntity->entityId) || ($entityName = trim($param->CallbackParameter->againstEntity->entity)) === '' || !($entity = $entityName::get(trim($param->CallbackParameter->againstEntity->entityId))) instanceof $entityName) { throw new Exception('System Error: invalid Order or CreditNote provided. Can NOT get any payments at all.'); } if (!$entity instanceof Order && !$entity instanceof CreditNote) { throw new Exception('System Error: you can ONLY add payments for a Order or a CreditNote'); } if (!isset($param->CallbackParameter->payment) || !isset($param->CallbackParameter->payment->paidAmount) || ($paidAmount = StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->payment->paidAmount))) === '' || !is_numeric($paidAmount)) { throw new Exception('System Error: invalid Paid Amount passed in!'); } if (!isset($param->CallbackParameter->payment->payment_method_id) || ($paymentMethodId = trim($param->CallbackParameter->payment->payment_method_id)) === '' || !($paymentMethod = PaymentMethod::get($paymentMethodId)) instanceof PaymentMethod) { throw new Exception('System Error: invalid Payment Method passed in!'); } $notifyCust = isset($param->CallbackParameter->payment->notifyCust) && intval($param->CallbackParameter->payment->notifyCust) === 1 ? true : false; $extraComment = ''; if (!isset($param->CallbackParameter->payment->extraComments) || ($extraComment = trim($param->CallbackParameter->payment->extraComments)) === '') { throw new Exception('Some comments for this payment is required.'); } //save the payment $newPayment = null; $entity = $entity->addPayment($paymentMethod, $paidAmount, $extraComment, new UDate(), $newPayment); $results['item'] = $newPayment->getJson(); //notify the customer if ($entity instanceof Order && $notifyCust === true && $entity->getIsFromB2B() === true) { $notificationMsg = trim(OrderNotificationTemplateControl::getMessage('paid', $entity)); if ($notificationMsg !== '') { B2BConnector::getConnector(B2BConnector::CONNECTOR_TYPE_ORDER, SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_WSDL), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_USER), SystemSettings::getSettings(SystemSettings::TYPE_B2B_SOAP_KEY))->changeOrderStatus($entity, OrderStatus::get(OrderStatus::ID_PICKED)->getMageStatus(), $notificationMsg, true); $comments = 'An email notification contains payment checked info has been sent to customer for: ' . $entity->getStatus()->getName(); Comments::addComments($entity, $comments, Comments::TYPE_SYSTEM); } } Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * ReCalMargin * * @return OrderItem */ public function reCalMargin() { $this->setMargin(StringUtilsAbstract::getValueFromCurrency($this->getTotalPrice()) - StringUtilsAbstract::getValueFromCurrency($this->getUnitCost()) * 1.1 * intval($this->getQtyOrdered())); return $this; }