Esempio n. 1
0
 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';
     $receivingItems = ReceivingItem::getAllByCriteria($dataType . ' >= :fromDate and ' . $dataType . ' < :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate)));
     $now = new UDate();
     $now->setTimeZone('Australia/Melbourne');
     $formatArray = array();
     foreach ($receivingItems as $receivingItem) {
         $product = $receivingItem->getProduct();
         if (!$product instanceof Product) {
             continue;
         }
         if (!array_key_exists($key = trim($receivingItem->getPurchaseOrder()->getId() . '|' . $product->getId() . '|' . $receivingItem->getInvoiceNo()), $formatArray)) {
             $formatArray[$key] = $receivingItem;
         }
         if ($formatArray[$key]->getId() !== $receivingItem->getId()) {
             $formatArray[$key]->setQty($formatArray[$key]->getQty() + $receivingItem->getQty());
         }
     }
     $return = array();
     foreach ($formatArray as $key => $receivingItem) {
         $product = $receivingItem->getProduct();
         $purchaseOrder = $receivingItem->getPurchaseOrder();
         $supplier = $purchaseOrder->getSupplier();
         $return[] = array('ContactName' => $supplier->getName(), 'EmailAddress' => $supplier->getEmail(), 'POAddressLine1' => '', 'POAddressLine2' => '', 'POAddressLine3' => '', 'POAddressLine4' => '', 'POCity' => '', 'PORegion' => '', 'POPostalCode' => '', 'POCountry' => '', 'InvoiceNumber' => $receivingItem->getInvoiceNo(), 'InvoiceDate' => '', 'DueDate' => trim($now->modify(self::DEFAULT_DUE_DELAY)), 'InventoryItemCode' => $product->getSku(), 'Description' => ($description = trim($product->getShortDescription())) === '' ? $product->getName() : $description, 'Quantity' => $receivingItem->getQty(), 'UnitAmount' => $receivingItem->getUnitPrice(), 'AccountCode' => $product->getAssetAccNo(), 'TaxType' => "GST on Expenses", 'TrackingName1' => '', 'TrackingOption1' => '', 'TrackingName2' => '', 'TrackingOption2' => '', 'Currency' => '');
     }
     return $return;
 }
Esempio n. 2
0
    /**
     * Getting the items
     *
     * @param unknown $sender
     * @param unknown $param
     * @throws Exception
     *
     */
    public function getItems($sender, $param)
    {
        $results = $errors = array();
        try {
            if (!isset($param->CallbackParameter->searchCriteria->supplierId) || !($supplier = Supplier::get(trim($param->CallbackParameter->searchCriteria->supplierId))) instanceof Supplier) {
                throw new Exception('Invalid Supplier provided');
            }
            if (!isset($param->CallbackParameter->searchCriteria->invoiceNo) || ($invoiceNo = trim($param->CallbackParameter->searchCriteria->invoiceNo)) === '') {
                throw new Exception('Invalid Invoice number provided');
            }
            ReceivingItem::getQuery()->eagerLoad('ReceivingItem.purchaseOrder', 'inner join', 'rec_item_po', 'rec_item_po.id = rec_item.purchaseOrderId');
            if (ReceivingItem::countByCriteria('rec_item_po.supplierId = ? and rec_item.invoiceNo = ?', array($supplier->getId(), $invoiceNo)) === 0) {
                throw new Exception('There is no such a invoice(invoice No=' . $invoiceNo . ') for supplier:' . $supplier->getName());
            }
            $sql = 'select ri.productId,
						ri.unitPrice `unitPrice`,
						sum(ri.qty) `qty`,
						group_concat(distinct ri.id) `itemIds`,
						group_concat(distinct po.id) `poIds`
					from receivingitem ri
					inner join purchaseorder po on (po.id = ri.purchaseOrderId)
					where ri.active = 1 and ri.invoiceNo = ? and po.supplierId = ?
					group by ri.productId,  ri.unitPrice';
            $params = array($invoiceNo, $supplier->getId());
            $rows = Dao::getResultsNative($sql, $params);
            $results['supplier'] = $supplier->getJson();
            $results['items'] = array();
            foreach ($rows as $row) {
                $items = count($itemIds = explode(',', $row['itemIds'])) === 0 ? array() : ReceivingItem::getAllByCriteria('id in (' . implode(',', array_fill(0, count($itemIds), '?')) . ')', $itemIds);
                $pos = count($poIds = explode(',', $row['poIds'])) === 0 ? array() : PurchaseOrder::getAllByCriteria('id in (' . implode(',', array_fill(0, count($poIds), '?')) . ')', $poIds);
                $results['items'][] = array('product' => Product::get($row['productId'])->getJson(), 'totalQty' => $row['qty'], 'totalPrice' => $row['unitPrice'] * $row['qty'], 'items' => array_map(create_function('$a', 'return $a->getJson();'), $items), 'purchaseOrders' => array_map(create_function('$a', 'return $a->getJson();'), $pos));
            }
        } catch (Exception $ex) {
            $errors[] = $ex->getMessage();
        }
        $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
    }
Esempio n. 3
0
 /**
  * deleteItem
  *
  * @param unknown $sender
  * @param unknown $param
  * @throws Exception
  *
  */
 public function deleteItem($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         if (!isset($param->CallbackParameter->id) || !($recievingItem = ReceivingItem::get(trim($param->CallbackParameter->id))) instanceof ReceivingItem) {
             throw new Exception('System Error: invalid item provided');
         }
         $recievingItem->setActive(false)->save();
         $results['item'] = $recievingItem->getJson();
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 4
0
 public function getReceivingItem($receiving_id)
 {
     $model = ReceivingItem::model()->findAll('receive_id=:receivingId', array(':receivingId' => $receiving_id));
     return $model;
 }
Esempio n. 5
0
 public function copyEntireReceiving($receiving_id)
 {
     $this->clearAll();
     $receiving = Receiving::model()->findbyPk($receiving_id);
     $receiving_item = ReceivingItem::model()->getReceivingItem($receiving_id);
     //$payments= ReceivSalePayment::model()->getPayment($sale_id);
     foreach ($receiving_item as $row) {
         $item_expire = ItemExpire::model()->findByAttributes(array('item_id' => $row->item_id, 'receiving_id' => $receiving_id));
         $expire_date = null;
         if ($item_expire) {
             $expire_date = $item_expire->expire_date;
         }
         if ($row->discount_type == '$') {
             $discount_amount = $row->discount_type . $row->discount_amount;
         } else {
             $discount_amount = $row->discount_amount;
         }
         $this->addItem($row->item_id, $row->quantity, $discount_amount, $row->price, $row->description, $expire_date);
     }
     /*
      foreach($payments as $row)
      {
      $this->addPayment($row->payment_type,$row->payment_amount);
      }
     * 
     */
     $this->setSupplier($receiving->supplier_id);
     $this->setComment($receiving->remark);
 }
 public function actionEditItem($item_id)
 {
     if (Yii::app()->request->isPostRequest && Yii::app()->request->isAjaxRequest) {
         $data = array();
         $model = new ReceivingItem();
         $quantity = isset($_POST['ReceivingItem']['quantity']) ? $_POST['ReceivingItem']['quantity'] : null;
         $unit_price = isset($_POST['ReceivingItem']['unit_price']) ? $_POST['ReceivingItem']['unit_price'] : null;
         $cost_price = isset($_POST['ReceivingItem']['cost_price']) ? $_POST['ReceivingItem']['cost_price'] : null;
         $discount = isset($_POST['ReceivingItem']['discount']) ? $_POST['ReceivingItem']['discount'] : null;
         $expire_date = isset($_POST['ReceivingItem']['expire_date']) ? $_POST['ReceivingItem']['expire_date'] : null;
         $description = 'test';
         $model->quantity = $quantity;
         $model->unit_price = $unit_price;
         $model->cost_price = $cost_price;
         $model->discount = $discount;
         $model->expire_date = $expire_date;
         if ($model->validate()) {
             Yii::app()->receivingCart->editItem($item_id, $quantity, $discount, $cost_price, $unit_price, $description, $expire_date);
         } else {
             $error = CActiveForm::validate($model);
             $errors = explode(":", $error);
             $data['warning'] = str_replace("}", "", $errors[1]);
             $data['warning'] = Yii::t('app', 'Input data type is invalid');
         }
         $this->reload($data);
     } else {
         throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
     }
 }
 public function actionSetTotalDiscount()
 {
     if (Yii::app()->request->isPostRequest) {
         $data = array();
         $model = new ReceivingItem();
         $total_discount = $_POST['ReceivingItem']['total_discount'];
         $model->total_discount = $total_discount;
         if ($model->validate()) {
             Yii::app()->receivingCart->setTotalDiscount($total_discount);
         } else {
             $error = CActiveForm::validate($model);
             $errors = explode(":", $error);
             $data['warning'] = str_replace("}", "", $errors[1]);
         }
         $this->reload($data);
     }
 }
Esempio n. 8
0
 /**
  * updateInvoiceNo
  *
  * @param unknown $sender
  * @param unknown $param
  * @throws Exception
  *
  */
 public function updateInvoiceNo($sender, $param)
 {
     $results = $errors = array();
     try {
         if (!isset($param->CallbackParameter->supplierId) || !($supplier = Supplier::get(trim($param->CallbackParameter->supplierId))) instanceof Supplier) {
             throw new Exception('Invalid Supplier provided.');
         }
         if (!isset($param->CallbackParameter->newInoviceNo) || ($newInoviceNo = trim($param->CallbackParameter->newInoviceNo)) === '') {
             throw new Exception('Invalid newInoviceNo.');
         }
         if (!isset($param->CallbackParameter->oldInvoiceNo)) {
             throw new Exception('Invalid oldInvoiceNo.');
         }
         $oldInvoiceNo = trim($param->CallbackParameter->oldInvoiceNo);
         ReceivingItem::updateByCriteria('invoiceNo = :newInvoiceNo', 'invoiceNo = :oldInvoiceNo and purchaseOrderId in (select po.id from purchaseorder po where po.active = 1 and po.supplierId = :supplierId)', array('newInvoiceNo' => $newInoviceNo, 'oldInvoiceNo' => $oldInvoiceNo, 'supplierId' => $supplier->getId()));
     } catch (Exception $ex) {
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 9
0
 /**
  * (non-PHPdoc)
  * @see BaseEntityAbstract::postSave()
  */
 public function postSave()
 {
     if (trim($this->getPurchaseOrderNo()) === '') {
         $this->setPurchaseOrderNo(self::PO_NO_PRE . str_pad($this->getId(), 6, '0', STR_PAD_LEFT))->save();
     }
     //if the order status is ordered, then calculated the
     if (intval($this->getActive()) === 0 || trim($this->getStatus()) === PurchaseOrder::STATUS_CANCELED) {
         $items = PurchaseOrderItem::getAllByCriteria('purchaseOrderId = ? and stockCalculated = 1', array($this->getId()));
         foreach ($items as $item) {
             $item->getProduct()->ordered(0 - $item->getQty(), 'PO(' . $this->getPurchaseOrderNo() . ') is CANCELLED or Deactivated', $item);
             $item->setStockCalculated(false)->save()->addLog('UNMarked this item for StockOnPO and stockCalculated', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__);
         }
         $this->addComment(count($items) . ' POItem(s) are reverted, as this PO is now deactivated or CANCELLED');
         $receivedItems = ReceivingItem::getAllByCriteria('purchaseOrderId = ?', array($this->getId()));
         foreach ($receivedItems as $item) {
             $item->setActive(false)->save();
         }
     } else {
         if (trim($this->getStatus()) === PurchaseOrder::STATUS_ORDERED) {
             $items = PurchaseOrderItem::getAllByCriteria('purchaseOrderId = ? and stockCalculated = 0', array($this->getId()));
             foreach ($items as $item) {
                 $item->getProduct()->ordered($item->getQty(), 'PO(' . $this->getPurchaseOrderNo() . ') is ordered now.', $item);
                 $item->setStockCalculated(true)->save()->addLog('Marked this item for StockOnPO and stockCalculated', Log::TYPE_SYSTEM, 'STOCK_QTY_CHG', __CLASS__ . '::' . __FUNCTION__);
             }
         }
     }
 }
Esempio n. 10
0
 /**
  * creating a receiving Item
  *
  * @param PurchaseOrder $po
  * @param Product       $product
  * @param double        $unitPrice
  * @param string        $serialNo
  * @param string        $invoiceNo
  *
  * @return PurchaseOrderItem
  */
 public static function create(PurchaseOrder $po, Product $product, $unitPrice = '0.0000', $qty = 1, $serialNo = '', $invoiceNo = '', $comments = "")
 {
     $entity = new ReceivingItem();
     $msg = 'Received a Product(SKU=' . $product . ') with unitPrice=' . $unitPrice . ', serialNo=' . $serialNo . ', invoiceNo=' . $invoiceNo;
     $entity->setPurchaseOrder($po)->setProduct($product)->setQty($qty)->setUnitPrice($unitPrice)->setInvoiceNo($invoiceNo)->setSerialNo($serialNo)->save()->addComment($comments, Comments::TYPE_WAREHOUSE)->addLog($msg, Log::TYPE_SYSTEM, Log::TYPE_SYSTEM, get_class($entity) . '_CREATE', __CLASS__ . '::' . __FUNCTION__);
     return $entity;
 }
Esempio n. 11
0
 protected function saveReceiveItem($items, $receiving_id, $employee_id, $trans_date)
 {
     foreach ($items as $line => $item) {
         $item_id = $item['item_id'];
         $cost_price = $item['cost_price'];
         $unit_price = $item['unit_price'];
         $quantity = $item['quantity'];
         $remarks = $this->transactionHeader() . ' ' . $receiving_id;
         $cur_item_info = Item::model()->findbyPk($item_id);
         $qty_in_stock = $cur_item_info->quantity;
         $cur_unit_price = $cur_item_info->unit_price;
         $stock_quantity = $this->stockQuantiy($qty_in_stock, $quantity);
         $discount_arr = Common::Discount($item['discount']);
         $discount_amount = $discount_arr[0];
         $discount_type = $discount_arr[1];
         $receiving_item = new ReceivingItem();
         $receiving_item->receive_id = $receiving_id;
         $receiving_item->item_id = $item_id;
         $receiving_item->line = $line;
         $receiving_item->quantity = $quantity;
         $receiving_item->cost_price = $cost_price;
         $receiving_item->unit_price = $cur_item_info->unit_price;
         $receiving_item->price = $unit_price;
         // Not used for Receiving Module
         $receiving_item->discount_amount = $discount_amount == null ? 0 : $discount_amount;
         $receiving_item->discount_type = $discount_type;
         $receiving_item->save();
         // Updating Price (Cost & Resell) to item table requested by owner
         $this->updateItem($cur_item_info, $cost_price, $unit_price, $stock_quantity[0]);
         // Product Price (retail price) history
         $this->updateItemPrice($item_id, $cur_unit_price, $unit_price, $employee_id, $trans_date);
         //Ramel Inventory Tracking
         $this->saveInventory($item_id, $employee_id, $stock_quantity[1], $trans_date, $remarks, $quantity, $qty_in_stock, $stock_quantity[0]);
         // Save Item Expire for tracking
         if (!empty($item['expire_date'])) {
             $this->saveItemExpire($item['expire_date'], $receiving_id, $item_id, $employee_id, $quantity, $trans_date, $remarks);
         }
     }
 }
 public function actionTransactionItem($receive_id, $employee_id, $remark)
 {
     $model = new ReceivingItem('search');
     $model->unsetAttributes();
     // clear any default values
     //$employee=Employee::model()->findByPk((int)$employee_id);
     //$cashier=$employee->first_name . ' ' . $employee->last_name;
     if (isset($_GET['SaleItem'])) {
         $model->attributes = $_GET['SaleItem'];
     }
     if (Yii::app()->request->isAjaxRequest) {
         Yii::app()->clientScript->scriptMap['*.js'] = false;
         //Yii::app()->clientScript->scriptMap['*.css'] = false;
         if (isset($_GET['ajax']) && $_GET['ajax'] == 'receive-item-grid') {
             $this->render('receive_item', array('model' => $model, 'receive_id' => $receive_id, 'employee_id' => $employee_id, 'remark' => $remark));
         } else {
             echo CJSON::encode(array('status' => 'render', 'div' => $this->renderPartial('receive_item', array('model' => $model, 'receive_id' => $receive_id, 'employee_id' => $employee_id, 'remark' => $remark), true, true)));
             Yii::app()->end();
         }
     } else {
         $this->render('receive_item', array('model' => $model, 'receive_id' => $receive_id, 'employee_id' => $employee_id, 'remark' => $remark));
     }
 }
Esempio n. 13
0
 /**
  * saveOrder
  *
  * @param unknown $sender
  * @param unknown $param
  *
  * @throws Exception
  *
  */
 public function saveOrder($sender, $param)
 {
     $results = $errors = array();
     try {
         Dao::beginTransaction();
         $items = array();
         $purchaseOrder = PurchaseOrder::get(trim($param->CallbackParameter->purchaseOrder->id));
         if (!$purchaseOrder instanceof PurchaseOrder) {
             throw new Exception('Invalid PurchaseOrder passed in!');
         }
         $comment = trim($param->CallbackParameter->comments);
         $purchaseOrder->addComment(Comments::TYPE_WAREHOUSE, $comment);
         $products = $param->CallbackParameter->products;
         $outStandingOrders = array();
         $invoiceNos = array();
         foreach ($products->matched as $item) {
             $product = Product::get(trim($item->product->id));
             if (!$product instanceof Product) {
                 throw new Exception('Invalid Product passed in!');
             }
             if (isset($item->product->EANcode)) {
                 $EANcode = trim($item->product->EANcode);
                 $productcodes = ProductCode::getAllByCriteria('pro_code.productId = :productId and pro_code.typeId = :typeId', array('productId' => $product->getId(), 'typeId' => ProductCodeType::ID_EAN), true, 1, 1);
                 if (count($productcodes) > 0) {
                     $productcodes[0]->setCode($EANcode)->save();
                 } else {
                     ProductCode::create($product, ProductCodeType::get(ProductCodeType::ID_EAN), $EANcode);
                 }
             }
             if (isset($item->product->UPCcode)) {
                 $UPCcode = trim($item->product->UPCcode);
                 $productcodes = ProductCode::getAllByCriteria('pro_code.productId = :productId and pro_code.typeId = :typeId', array('productId' => $product->getId(), 'typeId' => ProductCodeType::ID_UPC), true, 1, 1);
                 if (sizeof($productcodes)) {
                     $productcodes[0]->setCode($UPCcode)->save();
                 } else {
                     ProductCode::create($product, ProductCodeType::get(ProductCodeType::ID_UPC), $UPCcode);
                 }
             }
             if (isset($item->product->warehouseLocation) && ($locationName = trim($item->product->warehouseLocation)) !== '') {
                 $locs = Location::getAllByCriteria('name = ?', array($locationName), true, 1, 1);
                 $loc = count($locs) > 0 ? $locs[0] : Location::create($locationName, $locationName);
                 $product->addLocation(PreferredLocationType::get(PreferredLocationType::ID_WAREHOUSE), $loc);
             }
             $serials = $item->serial;
             $totalQty = 0;
             foreach ($serials as $serial) {
                 $qty = trim($serial->qty);
                 $totalQty += intval($qty);
                 $serialNo = trim($serial->serialNo);
                 $unitPrice = trim($serial->unitPrice);
                 $invoiceNo = trim($serial->invoiceNo);
                 $invoiceNos[] = $invoiceNo;
                 $comments = trim($serial->comments);
                 ReceivingItem::create($purchaseOrder, $product, $unitPrice, $qty, $serialNo, $invoiceNo, $comments);
             }
             OrderItem::getQuery()->eagerLoad('OrderItem.order', 'inner join', 'ord', 'ord.id = ord_item.orderId and ord.active = 1 and ord.type = :ordType and ord_item.productId = :productId and ord.statusId in ( :statusId1, :statusId2, :statusId3)');
             $orderItems = OrderItem::getAllByCriteria('ord_item.active = 1', array('ordType' => Order::TYPE_INVOICE, 'productId' => $product->getId(), 'statusId1' => OrderStatus::ID_INSUFFICIENT_STOCK, 'statusId2' => OrderStatus::ID_ETA, 'statusId3' => OrderStatus::ID_STOCK_CHECKED_BY_PURCHASING));
             if (count($orderItems) > 0) {
                 $orders = array();
                 foreach ($orderItems as $orderItem) {
                     if (!array_key_exists($orderItem->getOrder()->getId(), $orders)) {
                         $orders[$orderItem->getOrder()->getId()] = $orderItem->getOrder()->getJson();
                     }
                 }
                 $outStandingOrders[$product->getId()] = array('product' => $product->getJson(), 'recievedQty' => $totalQty, 'outStandingOrders' => array_values($orders));
             }
         }
         $results['outStandingOrders'] = count($outStandingOrders) > 0 ? array_values($outStandingOrders) : array();
         $results['item'] = PurchaseOrder::get($purchaseOrder->getId())->getJson();
         $invoiceNos = array_unique($invoiceNos);
         $results['invoiceNos'] = $invoiceNos;
         Dao::commitTransaction();
     } catch (Exception $ex) {
         Dao::rollbackTransaction();
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Esempio n. 14
0
 public function preSave()
 {
     $this->setProduct($this->getProductQtyLog()->getproduct())->setLastPurchaseTime($this->getProductQtyLog()->getCreated());
     switch ($this->getProductQtyLog()->getEntityName()) {
         case 'ReceivingItem':
             if (($receivingItem = ReceivingItem::get($this->getProductQtyLog()->getEntityId())) instanceof ReceivingItem) {
                 $this->setReceivingItem($receivingItem);
             }
             break;
         case 'PurchaseOrderItem':
             if (($purchaseOrderItem = PurchaseOrderItem::get($this->getProductQtyLog()->getEntityId())) instanceof PurchaseOrderItem) {
                 $this->setPurchaseOrderItem($purchaseOrderItem);
             }
             break;
         case 'OrderItem':
             if (($orderItem = OrderItem::get($this->getProductQtyLog()->getEntityId())) instanceof OrderItem) {
                 $this->setOrderItem($orderItem);
             }
             break;
         case 'CreditNoteItem':
             if (($creditNoteItem = CreditNoteItem::get($this->getProductQtyLog()->getEntityId())) instanceof CreditNoteItem) {
                 $this->setCreditNoteItem($creditNoteItem);
             }
             break;
     }
 }