/** * 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); }
/** * Getting the selling item * * @param OrderItem $orderItem * @param string $serialNo * @param string $description * @param Order $order * @param Product $product * @param string $activeOnly * @param string $pageNo * @param unknown $pageSize * @param unknown $orderBy * @param unknown $stats * @return Ambigous <Ambigous, multitype:, multitype:BaseEntityAbstract > */ public static function getSellingItems(OrderItem $orderItem = null, $serialNo = '', $description = '', Order $order = null, Product $product = null, $activeOnly = true, $pageNo = null, $pageSize = DaoQuery::DEFAUTL_PAGE_SIZE, $orderBy = array(), &$stats = array()) { $where = $params = array(); if (trim($serialNo) !== '') { $where[] = 'serialNo like ?'; $params[] = $serialNo; } if (trim($description) !== '') { $where[] = 'description like ?'; $params[] = '%' . $description . '%'; } if ($orderItem instanceof OrderItem) { $where[] = 'orderItemId = ?'; $params[] = $orderItem->getId(); } if ($order instanceof Order) { $where[] = 'orderId = ?'; $params[] = $order->getId(); } if ($product instanceof Product) { $where[] = 'productId = ?'; $params[] = $product->getId(); } if (count($where) === 0) { return SellingItem::getAll($activeOnly, $pageNo, $pageSize, $orderBy, $stats); } $results = SellingItem::getAllByCriteria(implode(' AND ', $where), $params, $activeOnly, $pageNo, $pageSize, $orderBy, $stats); return $results; }
/** * A product is picked * * @param int $qty * @param string $comments * @param BaseEntityAbstract $entity * * @return Product */ public function picked($qty, $comments = '', BaseEntityAbstract $entity = null) { $order = $entity instanceof Order ? $entity : ($entity instanceof OrderItem ? $entity->getOrder() : null); $unitCost = $this->getUnitCost(); $totalCost = $qty * $unitCost; $action = intval($qty) > 0 ? 'Stock picked' : 'stock UNPICKED'; $newQty = ($originStockOnHand = $this->getStockOnHand()) - $qty; if ($newQty < 0 && intval($qty) > 0 && intval(SystemSettings::getSettings(SystemSettings::TYPE_ALLOW_NEGTIVE_STOCK)) !== 1) { throw new Exception('Product (SKU:' . $this->getSKU() . ') can NOT be ' . $action . ' , as there is not enough stock: stock on hand will fall below zero'); } if ($entity instanceof OrderItem) { $kits = array_map(create_function('$a', 'return $a->getKit();'), SellingItem::getAllByCriteria('orderItemId = ? and kitId is not null', array($entity->getId()))); $kits = array_unique($kits); if (count($kits) > 0) { $totalCost = 0; $barcodes = array(); foreach ($kits as $kit) { $totalCost = $kit->getCost(); $barcodes[] = $kit->getBarcode(); } $comments .= ' ' . $action . ' KITS[' . implode(',', $barcodes) . '] with total cost value:' . StringUtilsAbstract::getCurrency($totalCost); } } $newStockOnOrder = ($originStockOnOrder = $this->getStockOnOrder()) + $qty; if ($newStockOnOrder < 0 && intval(SystemSettings::getSettings(SystemSettings::TYPE_ALLOW_NEGTIVE_STOCK)) !== 1) { throw new Exception('Product (SKU:' . $this->getSKU() . ') can NOT be ' . $action . ' , as there is not enough stock: new stock on order will fall below zero'); } return $this->setStockOnHand($newQty)->setStockOnOrder($newStockOnOrder)->setTotalOnHandValue(($origTotalOnHandValue = $this->getTotalOnHandValue()) - $totalCost)->snapshotQty($entity instanceof BaseEntityAbstract ? $entity : $this, ProductQtyLog::TYPE_SALES_ORDER, $action . ': ' . ($order instanceof Order ? '[' . $order->getOrderNo() . ']' : '') . $comments)->save()->addLog('StockOnHand(' . $originStockOnHand . ' => ' . $this->getStockOnHand() . ')', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__)->addLog('StockOnOrder(' . $originStockOnOrder . ' => ' . $this->getStockOnOrder() . ')', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__)->addLog('TotalOnHandValue(' . $origTotalOnHandValue . ' => ' . $this->getTotalOnHandValue() . ')', Log::TYPE_SYSTEM, 'STOCK_VALUE_CHG', __CLASS__ . '::' . __FUNCTION__); }
/** * (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(); } } } } }
/** * (non-PHPdoc) * @see BaseEntityAbstract::postSave() */ public function postSave() { if (trim($this->getOrderNo()) === '') { $this->setOrderNo('BPCM' . str_pad($this->getId(), 8, '0', STR_PAD_LEFT))->setMargin($this->getCalculatedTotalMargin())->save(); } if (trim($this->getType()) === trim(self::TYPE_INVOICE)) { $this->_changeToInvoice(); } //if the order is now SHIPPED if (trim($this->getStatus()->getId()) === trim(OrderStatus::ID_SHIPPED)) { $items = OrderItem::getAllByCriteria('orderId = ? and isPicked = 1', array($this->getId())); foreach ($items as $item) { $item->setIsShipped(true)->save(); } $this->_changeToInvoice(); } elseif (trim($this->getStatus()->getId()) === trim(OrderStatus::ID_CANCELLED)) { //if the order is now cancelled //we need to unlink all the kits that were provided in this order item for sale. SellingItem::getQuery()->eagerLoad('SellingItem.orderItem', 'inner join', 'rec_item_oi', 'rec_item_oi.id = sell_item.orderItemId and sell_item.active = 1 and sell_item.kitId is not null'); $items = SellingItem::getAllByCriteria('rec_item_oi.orderId = ? and rec_item_oi.isShipped = 0', array($this->getId())); foreach ($items as $item) { $item->setActive(false)->save(); } } }