/** * Creating a consignment note for the delivery * * @param Shippment $shippment The Shippment * @param string $manifestId The manifest id from the courier * * @throws Exception */ public function createConsignment(Shippment &$shippment, $manifestId = '') { list($apiUrl, $apiKey, $accId) = $this->_getAPIInfos(); $url = str_replace('{method}', 'fastlabel/addconsignment', trim($apiUrl)); $itemsString = array(); foreach ($shippment->getOrder()->getOrderItems() as $index => $item) { $itemString = array(); $itemString[] = "Items[{$index}].Reference=" . $shippment->getOrder()->getOrderNo(); $itemString[] = "Items[{$index}].Quantity=" . 1; $itemString[] = "Items[{$index}].Weight=" . 1; $itemString[] = "Items[{$index}].Packaging=" . 1; $itemString[] = "Items[{$index}].Length=" . ''; $itemString[] = "Items[{$index}].Width=" . ''; $itemString[] = "Items[{$index}].Height=" . ''; $itemsString[] = implode('&', $itemString); } $emails = $shippment->getOrder()->getInfo(OrderInfoType::ID_CUS_EMAIL); $params = array('api_key' => trim($apiKey), 'UserID' => trim($accId), 'ManifestID' => trim($manifestId), 'ContactName' => trim($shippment->getReceiver()), 'Address1' => trim($shippment->getOrder()->getShippingAddr()->getStreet()), 'Suburb' => trim($shippment->getOrder()->getShippingAddr()->getCity()), 'Postcode' => trim($shippment->getOrder()->getShippingAddr()->getPostCode()), 'ContactEmail' => count($emails) > 0 ? $emails[0] : '', 'ContactMobile' => trim($shippment->getContact()), 'SpecialInstruction1' => trim($shippment->getDeliveryInstructions())); $paramString = http_build_query($params) . '&' . implode('&', $itemsString); $result = $this->_getJsonResult(ComScriptCURL::readUrl($url . '?' . $paramString, ComScriptCURL::CURL_TIMEOUT)); return $result; }
/** * 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); }
/** * 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); }