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; }
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; }
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; }
/** * Creating a credit note from an orderitem * * @param CreditNote $creditNote * @param OrderItem $orderItem * @param int $qty * @param double $unitPrice * @param double $itemDescription * @param duble $unitCost * * @return CreditNoteItem */ public static function createFromOrderItem(CreditNote $creditNote, OrderItem $orderItem, $qty, $unitPrice = null, $itemDescription = '', $unitCost = null, $totalPrice = null) { $item = new CreditNoteItem(); $item->setCreditNote($creditNote)->setOrderItem($orderItem)->setProduct($orderItem->getProduct())->setQty($qty)->setUnitPrice($unitPrice === null ? $orderItem->getUnitPrice() : $unitPrice)->setItemDescription(trim($itemDescription))->setUnitCost($unitCost !== null ? $unitCost : $orderItem->getUnitCost())->setTotalPrice($totalPrice !== null ? $totalPrice : $orderItem->getTotalPrice())->save(); $msg = 'A credit item has been created based on OrderItem(ID=' . $orderItem->getId() . ', OrderNo=' . $orderItem->getOrder()->getOrderNo() . ') with ' . $qty . 'Product(s) (SKU=' . $item->getProduct()->getSku() . ', ID=' . $item->getProduct()->getId() . '), unitPrice=' . StringUtilsAbstract::getCurrency($unitPrice) . ', unitCost=' . StringUtilsAbstract::getCurrency($item->getUnitCost()) . ', qty=' . $item->getQty() . ', totalPrice=' . StringUtilsAbstract::getCurrency($item->getTotalPrice()); $creditNote->addComment($msg, Comments::TYPE_SYSTEM)->addLog($msg, Comments::TYPE_SYSTEM); return $item; }
/** * Creating a payment for creditNote * * @param CreditNote $creditNote * @param PaymentMethod $method * @param string $value * @param string $comments * * @return Ambigous <BaseEntityAbstract, GenericDAO> */ public static function createFromCreditNote(CreditNote &$creditNote, PaymentMethod $method, $value, $comments = '', $paymentDate = '') { $payment = new Payment(); $message = 'A ' . StringUtilsAbstract::getCurrency($value) . ' Credit Payment is made via ' . $method->getName() . ' for CreditNote(CreditNoteNo.=' . $creditNote->getCreditNoteNo() . ')' . (trim($comments) !== '' ? ': ' . $comments : '.'); $payment = $payment->setCreditNote($creditNote)->setMethod($method)->setValue($value)->setPaymentDate(new UDate(trim($paymentDate) === '' ? 'now' : trim($paymentDate)))->save()->addComment($message, Comments::TYPE_ACCOUNTING)->addLog($message, Log::TYPE_SYSTEM, get_class($payment) . '_CREATION', __CLASS__ . '::' . __FUNCTION__); $creditNote->addComment($message, Comments::TYPE_ACCOUNTING)->addLog($message, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); return $payment; }
/** * Creating a RMA Item * * @param RMA $rma * @param OrderItem $product * @param int $qty * @param double $itemDescription * @param duble $unitCost * * @return RMAItem */ public static function createFromOrderItem(RMA $rma, OrderItem $orderItem, $qty, $itemDescription = '', $unitCost = null) { $item = new RMAItem(); $item->setRMA($rma)->setOrderItem($orderItem)->setProduct($orderItem->getProduct())->setQty($qty)->setItemDescription(trim($itemDescription))->setUnitCost($unitCost !== null ? $unitCost : $orderItem->getUnitCost())->save(); $msg = 'A RMAItem has been created based on OrderItem(ID=' . $orderItem->getId() . ', OrderNo=' . $orderItem->getOrder()->getOrderNo() . ') with ' . $qty . 'Product(s) (SKU=' . $product->getSku() . ', ID=' . $product->getId() . '), unitCost=' . StringUtilsAbstract::getCurrency($item->getUnitCost()); $rma->addComment($msg, Comments::TYPE_SYSTEM)->addLog($msg, Comments::TYPE_SYSTEM); return $item; }
/** * (non-PHPdoc) * @see BaseEntityAbstract::postSave() */ public function postSave() { if (trim($this->getRaNo()) === '') { $this->setRaNo('BPCR' . str_pad($this->getId(), 8, '0', STR_PAD_LEFT))->save(); if ($this->getOrder() instanceof Order) { $msg = "An RMA(" . $this->getRaNo() . ") has created for this order with a unitPrice: " . StringUtilsAbstract::getCurrency($this->getUnitPrice()) . ', qty: ' . $this->getQty() . ', totalValue: ' . StringUtilsAbstract::getCurrency($this->getTotalValue()); $this->getOrder()->addComment($msg, Comments::TYPE_SYSTEM)->addLog($msg, Log::TYPE_SYSTEM, 'AUTO', __CLASS__ . '::' . __FUNCTION__); } } }
/** * 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); }
/** * (non-PHPdoc) * @see BaseEntityAbstract::preSave() */ public function preSave() { if (!$this->getComponent() instanceof Product) { throw new EntityException('You have to provide a product to install into a kit'); } if (intval($this->getQty()) === 0) { throw new EntityException('You can NOT install a component into a kit with quantity: 0'); } if (intval(ceil($this->getUnitCost())) === 0) { $this->setUnitCost($this->getComponent()->getUnitCost()); } if (trim($this->getUnitPrice()) === '') { $unitPrices = $this->getComponent()->getPrices(); $this->setUnitPrice(count($unitPrices) === 0 ? 0 : $unitPrices[0]->getPrice()); } if (trim($this->getId()) === '') { //when we are creating a new one $this->getComponent()->installedIntoKit($this->getQty(), $this->getUnitCost(), 'KITCOMPONENT CREATED', $this->getKit()); $this->getKit()->addComment('A KitComponent(SKU=' . $this->getComponent()->getSku() . ', UnitPrice=' . StringUtilsAbstract::getCurrency($this->getUnitPrice()) . ', qty=' . $this->getQty() . ', UnitCost=' . StringUtilsAbstract::getCurrency($this->getUnitCost()) . ') has been ADDED INTO this kit (' . $this->getKit()->getBarcode() . ')', Comments::TYPE_WORKSHOP); } else { if (intval($this->getActive()) === 0 && self::countByCriteria('id = ? and active = 1', array($this->getId())) > 0) { //trying to deactivate the kitcomponent $this->getComponent()->installedIntoKit(0 - $this->getQty(), $this->getUnitCost(), 'DEACTIVATED KITCOMPONENT', $this); $this->getKit()->addComment('A KitComponent(SKU=' . $this->getComponent()->getSku() . ', UnitPrice=' . StringUtilsAbstract::getCurrency($this->getUnitPrice()) . ', qty=' . $this->getQty() . ', UnitCost=' . StringUtilsAbstract::getCurrency($this->getUnitCost()) . ') has been REMOVED FROM this kit (' . $this->getKit()->getBarcode() . ')', Comments::TYPE_WORKSHOP); } else { if (intval($this->getActive()) === 1) { $orignal = self::get($this->getId()); if (intval($orignal->getQty()) !== intval($this->getQty())) { $this->getComponent()->installedIntoKit($this->getQty() - $orignal->getQty(), $this->getUnitCost(), 'KITCOMPONENT CHANGED QTY', $this); $this->getKit()->addComment('A KitComponent(SKU=' . $this->getComponent()->getSku() . ', UnitPrice=' . StringUtilsAbstract::getCurrency($this->getUnitPrice()) . ', qty=' . $this->getQty() . ', UnitCost=' . StringUtilsAbstract::getCurrency($this->getUnitCost()) . ') has been QTY CHANGED( ' . $orignal->getQty() . ' => ' . $this->getQty() . ' ) in kit (' . $this->getKit()->getBarcode() . ')', Comments::TYPE_WORKSHOP); } } else { throw new EntityException('CANT update KitComponents once created.'); } } } }
/** * 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; } }
/** * 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; }
/** * deleting a payment * * @param unknown $sender * @param unknown $param * * @throws Exception */ public function delPayment($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($param->CallbackParameter->paymentId) || !($payment = Payment::get($param->CallbackParameter->paymentId)) instanceof Payment) { throw new Exception('System Error: invalid payment provided!'); } if (!isset($param->CallbackParameter->reason) || ($reason = trim($param->CallbackParameter->reason)) === '') { throw new Exception('The reason for the deletion is needed!'); } $comments = 'A payment [Value: ' . StringUtilsAbstract::getCurrency($payment->getValue()) . ', Method: ' . $payment->getMethod()->getName() . '] is DELETED: ' . $reason; $payment->setActive(false)->addComment($comments, Comments::TYPE_ACCOUNTING)->save(); $entityFor = $payment->getOrder() instanceof Order ? $payment->getOrder() : $payment->getCreditNote(); if ($entityFor instanceof Order || $entityFor instanceof CreditNote) { $entityFor->addComment($comments, Comments::TYPE_ACCOUNTING); } $results['item'] = $payment->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * (non-PHPdoc) * @see BaseEntityAbstract::preSave() */ public function preSave() { if (trim($this->getMageOrderId()) === '') { $this->setMageOrderId('0'); } //when brandnew, calculate margin if (trim($this->getUnitCost()) === '') { $this->reCalMarginFromProduct(); } if (trim($this->getId()) === '') { if (trim($this->getItemDescription()) === '') { $this->setItemDescription($this->getProduct()->getName()); } } else { if (intval($this->getActive()) === 1) { //if the isPicked changed $product = $this->getProduct(); $kitCount = 0; //for picked if (self::countByCriteria('id = ? and isPicked != ?', array($this->getId(), $this->getIsPicked())) > 0) { $kitCount = $kitCount === 0 ? SellingItem::countByCriteria('orderItemId = ? and kitId is not null and active = 1 ', array($this->getId())) : $kitCount; if (intval($product->getIsKit()) === 1 && intval($kitCount) !== intval($this->getQtyOrdered())) { throw new EntityException($this->getQtyOrdered() . ' Kit(s) needs to be scanned to this OrderItem(SKU=' . $this->getProduct()->getSku() . ', unitPrice=' . StringUtilsAbstract::getCurrency($this->getUnitPrice()) . ', qty=' . $this->getQtyOrdered() . ') before it can be marked as PICKED, but got:' . $kitCount); } //we are picking this product if (intval($this->getIsPicked()) === 1) { $product->picked($this->getQtyOrdered(), '', $this); $this->addLog('This item is now marked as picked', Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } else { $product->picked(0 - $this->getQtyOrdered(), '', $this); $this->addLog('This item is now Un-marked as picked', Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } } //for shipped if (self::countByCriteria('id = ? and isShipped != ?', array($this->getId(), $this->getIsShipped())) > 0) { $kitCount = $kitCount === 0 ? SellingItem::countByCriteria('orderItemId = ? and kitId is not null and active = 1 ', array($this->getId())) : $kitCount; if (intval($product->getIsKit()) === 1 && intval($kitCount) !== intval($this->getQtyOrdered())) { throw new EntityException($this->getQtyOrdered() . ' Kit(s) needs to be scanned to this OrderItem(ID=' . $this->getId() . ') before it can be marked as SHIPPED, but got:' . $kitCount); } //we are picking this product if (intval($this->getIsShipped()) === 1) { $product->shipped($this->getQtyOrdered(), '', $this); $this->addLog('This item is now marked as SHIPPED', Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } else { $product->shipped(0 - $this->getQtyOrdered(), '', $this); $this->addLog('This item is now Un-marked as SHIPPED', Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } } } else { //if the orderitem is been deactivated if (self::countByCriteria('id = ? and active != ?', array($this->getId(), $this->getActive())) > 0) { if (self::countByCriteria('id = ? and isShipped = 1', array($this->getId())) > 0) { $msg = 'This item is now Un-marked as SHIPPED, as OrderItem(Order: ' . $this->getOrder()->getOrderNo() . ' SKU: ' . $this->getProduct()->getSku() . ', Qty: ' . $this->getQtyOrdered() . ') is now Deactivated'; $product->shipped(0 - $this->getQtyOrdered(), $msg, $this); $this->addLog($msg, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } if (self::countByCriteria('id = ? and isPicked = 1', array($this->getId())) > 0) { $msg = 'This item is now Un-PICKED, as OrderItem(Order: ' . $this->getOrder()->getOrderNo() . ' SKU: ' . $this->getProduct()->getSku() . ', Qty: ' . $this->getQtyOrdered() . ') is now Deactivated'; $product->shipped(0 - $this->getQtyOrdered(), $msg, $this); $this->addLog($msg, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); } foreach (SellingItem::getAllByCriteria('orderItemId = ?', array($this->getId())) as $sellingItem) { $sellingItem->setActive(false)->save(); } } } } }
/** * a product is created as a kit * * @param string $comments * @param BaseEntityAbstract $entity */ public function createAsAKit($comments, Kit $entity) { $task = $entity instanceof Kit ? $entity->getTask() : null; return $this->setStockOnHand(($originalStockOnHand = $this->getStockOnHand()) + 1)->setTotalOnHandValue(($originalTotalOnHandValue = $this->getTotalOnHandValue()) + $entity->getCost())->snapshotQty($entity instanceof BaseEntityAbstract ? $entity : $this, ProductQtyLog::TYPE_WORKSHOP, 'Created a Kit[' . $entity->getBarcode() . '] with value(cost=' . StringUtilsAbstract::getCurrency($entity->getCost()) . ')' . ($task instanceof Task ? ' generated from Task[' . $task->getId() . ']' : '') . (trim($comments) === '' ? '.' : ': ' . $comments))->save()->addLog('StockOnHand(' . $originalStockOnHand . ' => ' . $this->getStockOnHand() . '), StockOnHandValue(' . $originalTotalOnHandValue . ' => ' . $this->getTotalOnHandValue() . ')' . (trim($comments) === '' ? '.' : ': ' . $comments), Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__); }