public function testMarshalling() { $expectedXml = <<<XML <?xml version="1.0"?> <purchase-order xmlns="http://openuri.org/easypo"> <customer> <name>Gladys Kravitz</name> <address>Anytown, PA</address> </customer> <date>2003-01-07T14:16:00-05:00</date> <line-item> <description>Burnham's Celestial Handbook, Vol 1</description> <per-unit-ounces>5</per-unit-ounces> <price>21.79</price> <quantity>2</quantity> </line-item> <line-item> <description>Burnham's Celestial Handbook, Vol 2</description> <per-unit-ounces>5</per-unit-ounces> <price>19.89</price> <quantity>2</quantity> </line-item> <shipper> <name>ZipShip</name> <per-ounce-rate>0.74</per-ounce-rate> </shipper> </purchase-order> XML; $filepath = dirname(__FILE__) . '/../../_files/EasyPO/'; $binding = new PiBX_Runtime_Binding($filepath . '/binding.xml'); $marshaller = new PiBX_Runtime_Marshaller($binding); $po = new PurchaseOrder(); $po->setDate('2003-01-07T14:16:00-05:00'); $customer = new Customer(); $customer->setName('Gladys Kravitz'); $customer->setAddress('Anytown, PA'); $lineItem1 = new LineItem(); $lineItem1->setDescription('Burnham\'s Celestial Handbook, Vol 1'); $lineItem1->setPerUnitOunces('5'); $lineItem1->setPrice(21.79); $lineItem1->setQuantity(2); $lineItem2 = new LineItem(); $lineItem2->setDescription('Burnham\'s Celestial Handbook, Vol 2'); $lineItem2->setPerUnitOunces('5'); $lineItem2->setPrice(19.89); $lineItem2->setQuantity(2); $shipper = new Shipper(); $shipper->setName('ZipShip'); $shipper->setPerOunceRate(0.74); $po->setCustomer($customer); $po->setLineItems(array($lineItem1, $lineItem2)); $po->setShipper($shipper); $xml = $marshaller->marshal($po); $this->assertEquals($expectedXml, $xml); $dom = new DOMDocument(); $dom->loadXML($xml); $this->assertTrue($dom->schemaValidate($filepath . '/easypo.xsd')); }
public function index() { App::import('Model', 'QuoteManager.Quote'); $quoteModel = new Quote(); $quoteDataList = $quoteModel->find('all', array('fields' => array('quote_number', 'status'), 'conditions' => array('Quote.vid' => null, 'Quote.created_by' => $this->loginUser['id']))); App::import('Model', 'WorkOrderManager.WorkOrder'); $workOrderModel = new WorkOrder(); $workOrderDataList = $workOrderModel->find('all', array('fields' => array('work_order_number', 'status'), 'conditions' => array('WorkOrder.created_by' => $this->loginUser['id']))); App::import('Model', 'PurchaseOrderManager.PurchaseOrder'); $purchaseOrderModel = new PurchaseOrder(); $purchaseOrderDataList = $purchaseOrderModel->find('all', array('fields' => array('purchase_order_num', 'received'), 'conditions' => array('PurchaseOrder.created_by' => $this->loginUser['id']))); $this->set(compact('quoteDataList', 'workOrderDataList', 'purchaseOrderDataList')); }
function processFile($filename) { //extract the filename to get the exact filename on the folder $newFile = substr($filename, 3); $dirname = substr($filename, 0, 2); $fs = new Filesystem(); if ($fs->exists('../Repo/' . $dirname . '/' . $newFile)) { $xml = simplexml_load_file('../Repo/' . $dirname . '/' . $newFile, null, LIBXML_NOCDATA); $newXML = json_decode(json_encode($xml), true); $data = formulateData($newXML, $dirname); //checks if the record is already processed before $hasRecord = PurchaseOrderQuery::create()->filterByNumber($data['number'])->find(); if ($hasRecord->count() === 0) { logMessage("No duplicate data: processFile " . date('m/d/Y h:i:s') . ".\n"); //log something //insert data to db $po = new PurchaseOrder(); $po->setFilename($newFile); $po->setStore($dirname); $po->setCustomerCode($data['customer_code']); $po->setDeliveryDate($data['delivery_date']); $po->setNumber($data['number']); $po->save(); $po_id = $po->getId(); //insert all items foreach ($data['items'] as $key => $value) { $items = new Item(); $items->setPurchaseOrderId($po_id); $items->setUpc($value['upc']); $items->setQty($value['qty']); $items->setQty($value['discount']); $items->save(); } $formulated_data = formulateData($newXML, $dirname); $formulated_data['id'] = $po_id; //print_r($formulated_data); logMessage("Return data in JSON: processFile " . date('m/d/Y h:i:s') . ".\n"); //log something return $formulated_data; print_r($formulated_data); } else { logMessage("This file(" . $newFile . ") with store(" . $dirname . ") is already processed before: processFile " . date('m/d/Y h:i:s') . ".\n"); //log something } print_r($data); } else { logMessage("Return no such file: processFile " . date('m/d/Y h:i:s') . ".\n"); //log something return "No such file!"; } }
function processFile($filename) { //extract the filename to get the exact filename on the folder $newFile = substr($filename, 3); $dirname = substr($filename, 0, 2); $fs = new Filesystem(); if ($fs->exists('../Repo/' . $dirname . '/' . $newFile)) { $xml = simplexml_load_file('../Repo/' . $dirname . '/' . $newFile, null, LIBXML_NOCDATA); $newXML = json_decode(json_encode($xml), true); $data = formulateData($newXML, $dirname); //insert data to db $po = new PurchaseOrder(); $po->setFilename($newFile); $po->setStore($dirname); $po->setCustomerCode($data['customer_code']); $po->setDeliveryDate($data['delivery_date']); $po->setNumber($data['number']); $po->save(); $po_id = $po->getId(); //insert all items foreach ($data['items'] as $key => $value) { $items = new Item(); $items->setPurchaseOrderId($po_id); $items->setUpc($value['upc']); $items->setQty($value['qty']); $items->setQty($value['discount']); $items->save(); } $formulated_data = formulateData($newXML, $dirname); $formulated_data['id'] = $po_id; //print_r($formulated_data); return $formulated_data; } }
/** * saveOrder * * @param unknown $sender * @param unknown $param * * @throws Exception * */ public function saveOrder($sender, $param) { $results = $errors = array(); $daoStart = false; try { Dao::beginTransaction(); $daoStart = true; $supplier = Supplier::get(trim($param->CallbackParameter->supplier->id)); if (!$supplier instanceof Supplier) { throw new Exception('Invalid Supplier passed in!'); } $supplierContactName = trim($param->CallbackParameter->supplier->contactName); $supplierContactNo = trim($param->CallbackParameter->supplier->contactNo); $supplierEmail = trim($param->CallbackParameter->supplier->email); if (!empty($supplierContactName) && $supplierContactName !== $supplier->getContactName()) { $supplier->setContactName($supplierContactName); } if (!empty($supplierContactNo) && $supplierContactNo !== $supplier->getContactNo()) { $supplier->setContactNo($supplierContactNo); } if (!empty($supplierEmail) && $supplierEmail !== $supplier->getEmail()) { $supplier->setEmail($supplierEmail); } $supplier->save(); $purchaseOrder = PurchaseOrder::create($supplier, trim($param->CallbackParameter->supplierRefNum), $supplierContactName, $supplierContactNo, StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->shippingCost)), StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->handlingCost)))->setTotalAmount(StringUtilsAbstract::getValueFromCurrency(trim($param->CallbackParameter->totalPaymentDue)))->setEta(trim($param->CallbackParameter->eta))->setStatus(PurchaseOrder::STATUS_NEW)->save()->addComment(trim($param->CallbackParameter->comments), Comments::TYPE_PURCHASING); foreach ($param->CallbackParameter->items as $item) { if (!($product = Product::get(trim($item->productId))) instanceof Product) { throw new Exception('Invalid Product passed in!'); } $purchaseOrder->addItem($product, StringUtilsAbstract::getValueFromCurrency(trim($item->unitPrice)), 0 - abs(intval(trim($item->qtyOrdered)))); } if ($param->CallbackParameter->submitToSupplier === true) { $purchaseOrder->setStatus(PurchaseOrder::STATUS_ORDERED); } // For credit PO if (isset($param->CallbackParameter->type) && trim($param->CallbackParameter->type) === 'CREDIT') { $purchaseOrder->setIsCredit(true); if (isset($param->CallbackParameter->po) && ($fromPO = PurchaseOrder::get(trim($param->CallbackParameter->po->id))) instanceof PurchaseOrder) { $purchaseOrder->setFromPO($fromPO); } } $purchaseOrder->save(); $daoStart = false; Dao::commitTransaction(); $results['item'] = $purchaseOrder->getJson(); if (isset($param->CallbackParameter->confirmEmail) && trim($confirmEmail = trim($param->CallbackParameter->confirmEmail)) !== '') { $pdfFile = EntityToPDF::getPDF($purchaseOrder); $asset = Asset::registerAsset($purchaseOrder->getPurchaseOrderNo() . '.pdf', file_get_contents($pdfFile), Asset::TYPE_TMP); EmailSender::addEmail('*****@*****.**', $confirmEmail, 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset)); EmailSender::addEmail('*****@*****.**', '*****@*****.**', 'BudgetPC Purchase Order:' . $purchaseOrder->getPurchaseOrderNo(), 'Please Find the attached PurchaseOrder(' . $purchaseOrder->getPurchaseOrderNo() . ') from BudgetPC.', array($asset)); $purchaseOrder->addComment('An email sent to "' . $confirmEmail . '" with the attachment: ' . $asset->getAssetId(), Comments::TYPE_SYSTEM); } } catch (Exception $ex) { if ($daoStart === true) { Dao::rollbackTransaction(); } $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * add method * * @return void */ public function add($id = null, $type = null) { $data = array(); $itemData = array(); if ($type == 'Purchase Order') { App::import('Model', 'PurchaseOrderManager.PurchaseOrder'); $purchaseOrder = new PurchaseOrder(); $purchaseOrder->recursive = 0; $data = $purchaseOrder->find('first', array('conditions' => array('PurchaseOrder.id' => $id))); $itemData = $this->QuoteItem->listOfPoItem(null, $id); } elseif ($type == 'Quote') { App::import('Model', 'QuoteManager.Quote'); $quote = new Quote(); $quote->recursive = 1; $data = $quote->find('first', array('conditions' => array('Quote.id' => $id))); $itemData = $this->QuoteItem->ListQuoteItems($id); // debug($itemData); $itemData = $this->QuoteItem->AdjustPOItem($itemData); $itemData['main_list'] = $itemData['name_list']; unset($itemData['name_list']); $itemData['qty_list'] = $itemData['quantity_list']; unset($itemData['quantity_list']); // debug($data); // debug($itemData); // // exit; } $invoice_no = $this->QuoteItem->auto_generate_number('Invoice'); $invoiceFormatData = $this->InvoiceItem->formatInvoiceData($invoice_no, $type, $id, $data, $itemData); $invoiceCreate = $this->InvoiceItem->createInvoice($invoiceFormatData); if ($invoiceCreate) { $this->Session->setFlash(__('The invoice has been saved')); $this->redirect(array('action' => 'detail', $invoiceCreate['Invoice']['id'])); } else { $this->Session->setFlash(__('The invoice could not be saved. Please, try again.')); } $this->set(compact('invoiceStatuses', 'type')); }
/** * (non-PHPdoc) * @see BPCPageAbstract::onLoad() */ public function onLoad($param) { parent::onLoad($param); if (!$this->isPostBack) { $this->order = PurchaseOrder::get($this->Request['POId']); if (!$this->order instanceof PurchaseOrder) { die('Invalid Purchase Order!'); } if (isset($_REQUEST['pdf']) && intval($_REQUEST['pdf']) === 1) { $file = EntityToPDF::getPDF($this->order); header('Content-Type: application/pdf'); // The PDF source is in original.pdf readfile($file); die; } } }
/** * 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); }
/** * (non-PHPdoc) * @see CRUDPageAbstract::_getEndJs() */ protected function _getEndJs() { $js = parent::_getEndJs(); $js .= "pageJs.setCallbackId('deleteItem', '" . $this->deleteItemBtn->getUniqueID() . "');"; if (isset($_REQUEST['productid']) || isset($_REQUEST['purchaseorderid'])) { if (isset($_REQUEST['productid'])) { if (!($product = Product::get(trim($_REQUEST['productid']))) instanceof Product) { die('Invalid Product Provided'); } $js .= "\$('searchBtn').up('.panel').down('.panel-body').insert({'bottom': new Element('input', {'type': 'hidden', 'search_field': 'productid', 'value': '" . $product->getId() . "'}) });"; $js .= "\$('searchBtn').up('.panel').hide();"; } if (isset($_REQUEST['purchaseorderid'])) { if (!($purchaseOrder = PurchaseOrder::get(trim($_REQUEST['purchaseorderid']))) instanceof PurchaseOrder) { die('Invalid PurchaseOrder Provided'); } $js .= "\$('searchBtn').up('.panel').down('.panel-body').insert({'bottom': new Element('input', {'type': 'hidden', 'search_field': 'purchaseorderid', 'value': '" . $purchaseOrder->getId() . "'}) });"; $js .= "\$('searchBtn').up('.panel').hide();"; } $js .= "\$('searchBtn').click();"; } $js .= "pageJs._bindSearchKey();"; return $js; }
$form = $this->beginWidget('CActiveForm', array('id' => 'item-on-order-form', 'enableAjaxValidation' => false)); ?> <?php /**COLLECTING THE DATA*/ $purchase_id = $_GET['po_id']; $item_id = $_GET['item_id']; $model->purchase_order_id = $purchase_id; $model->items_id = $item_id; //*SINCE FIRST STATUS OF ITEM IS DRAFT*// $model->item_status = 1; /*THIS IS FOR THE CURRENT ITEMS Which is being added*/ $itemModel = Items::model()->findByPk($item_id); $purchaseModel = PurchaseOrder::model()->findByPk($purchase_id); /*THIS IS To get the items which are already orrderd**/ $items_on_order_model = PurchaseOrder::model()->getItemsOnOrder($purchase_id); $model->suppliers_id = $purchaseModel->suppliers_id; $model->unit_price = $itemModel->sale_price; ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <!-- FIRST PART OF THE FORM WHICH DISPLAYS PURCHASE ORDER DETAILS --> <div class="row"> <table>
protected function afterSave() { $vat_percentage = Yii::app()->params['vat_in_percentage']; $purchaseOrderQueryModel = PurchaseOrder::model()->findByPk($this->purchase_order_id); $total_cost = $purchaseOrderQueryModel->total_cost + $this->total_price; $vat_amount = $total_cost * $vat_percentage / 100; $net_cost = $total_cost + $vat_amount; //echo $total_cost; $purchaseOrderUpdateModel = PurchaseOrder::model()->updateByPk($this->purchase_order_id, array('total_cost' => $total_cost, 'vat' => $vat_amount, 'net_cost' => $net_cost)); }
<td colspan="3"><button id="btnFind" onclick="submit()" >Find</button></td> </tr> </table> <br/> <table border="1" cellspacing="0" width="850" align="center"> <tr class="ui-widget-header"> <th style="width: 5%"> </th> <th style="width: 30%">Item</th> <th>Real purchase qty</th> <th style="width: 20%">Vendor</th> <th>Purchase price</th> <th>Order #</th> </tr> <?php include_once "../model/PurchaseOrder.php"; $porder = new PurchaseOrder(); $items = $porder->getSavedItems($_POST['txtDate1'], $_POST['txtDate2'], $_POST["cmbVendor"]); for ($i = 0; $i < count($items); $i++) { $item = $items[$i]; $_GET["idvendor"] = $item["idvendor"]; $_GET["i"] = $i; ?> <tr id="row<?php echo $i; ?> " class="ui-widget-content"> <td> <img alt="+" id="add<?php echo $i; ?> " src="../images/plus.png" onclick="addItem(<?php
public static function RaiseOrderPurchase($supplierid, $invno, $date, $items) { $ords; foreach ($items as $item) { $ords[$item['order']] = 1; } $orders = []; foreach ($ords as $key => $oid) { $orders[] = $key; $order = PurchaseOrder::GetOrder($key); $order->setPurchased(); } $porders = implode(",", $orders); $descr = "Ordered Purchases. Order No(s): " . $porders; $supplier = Supplier::GetSupplier($supplierid); $pid = 0; $invoice = PurchaseInvoice::CreateInvoice($supplier, $pid, $porders, $invno, $descr, $date); foreach ($items as $item) { $invoice->addToInvoice(PurchaseInvoiceLine::Create($invoice->id, $item['item'], $item['qty'], $item['price'], $item['tax'], $item['disc'], $item['ledger'])); } if ($invoice->generate()) { return new PurchaseTX($invoice, 'Purchase Order Invoice'); } else { Logger::Log('PurchaseTX', 'Failed', 'Ordered purchase invoice transaction with id:' . $invoice->id . ' and tx id:' . $this->transactionId . ' could not be completed'); return false; } }
<?php namespace Afosto\ActiveAnts; require_once dirname(__FILE__) . '/vendor/autoload.php'; //Include our configs require_once dirname(__FILE__) . '/../config.php'; //Make sure this directory is writable $cacheDirectory = dirname(__FILE__) . '/../cache/'; App::start($url, $user, $password, $cacheDirectory); $product = Product::model()->setName('testProduct')->setSku('testSku'); if (!$product->save()) { echo $product->getMessage(); } $item = OrderItem::model()->setSku('testSku', false)->setGrossPrice(1.21)->setName('testProduct')->setTaxRate(21); $address = Address::model()->setName('Afosto SaaS BV')->setAddress('Protonstraat', 9, 'a')->setCity('Groningen')->setCountry('NL')->setPostalcode('9743AL'); $order = Order::model()->setEmail('*****@*****.**')->setOrderId('#' . rand(100, 999))->setPhoneNumber('test')->addOrderItem($item)->setBillingAddress($address)->setShippingAddress(); //$order->setPickupPoint('NL-111101', '1111AA', 'Straatnaam 10a' , 'Groningen'); if (!$order->save()) { echo $order->getMessage(); } $purchase = PurchaseOrder::model()->addItem('testSku', 1)->addReference('testPurchaseOrder'); if (!$purchase->save()) { echo $purchase->getMessage(); } foreach (Stock::model()->findAll() as $stock) { echo $stock->sku . ': ' . $stock->stock . "\n"; }
/** * creating a PO Item * * @param PurchaseOrder $po * @param Product $product * @param double $unitPrice * @param int $qty * @param string $supplierItemCode * @param string $supplierId * @param string $description * @param double $totalPrice * * @return PurchaseOrderItem */ public static function create(PurchaseOrder $po, Product $product, $unitPrice = '0.0000', $qty = 1, $totalPrice = null, $receivedQty = 0) { $entity = new PurchaseOrderItem(); $msg = 'created POI for PO(' . $po->getPurchaseOrderNo() . ') with Product(SKU=' . $product->getSku() . ') unitPrice=' . $unitPrice . ', qty=' . $qty; $entity->setPurchaseOrder($po)->setProduct($product)->setUnitPrice($unitPrice)->setQty($qty)->setReceivedQty($receivedQty)->setTotalPrice(trim($totalPrice) !== '' ? $totalPrice : $unitPrice * $qty)->save()->addLog($msg, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); $po->addLog($msg, Log::TYPE_SYSTEM, 'Auto Log', __CLASS__ . '::' . __FUNCTION__); return $entity; }
/** * Getting the items * * @param unknown $sender * @param unknown $param * @throws Exception * */ public function getItems($sender, $param) { $results = $errors = array(); try { $class = trim($this->_focusEntity); $pageNo = 1; $pageSize = DaoQuery::DEFAUTL_PAGE_SIZE; if (isset($param->CallbackParameter->pagination)) { $pageNo = $param->CallbackParameter->pagination->pageNo; $pageSize = $param->CallbackParameter->pagination->pageSize; } $where = array('ri.active = :active'); $params = array('active' => 1); if (isset($param->CallbackParameter->searchCriteria)) { $criteria = $param->CallbackParameter->searchCriteria; if (isset($criteria->invoiceNo) && ($invNo = trim($criteria->invoiceNo)) !== '') { $where[] = 'ri.invoiceNo like :invNo'; $params['invNo'] = '%' . $invNo . '%'; } if (isset($criteria->purchaseOrderIds) && count($purchaseOrderIds = array_filter(explode(',', trim($criteria->purchaseOrderIds)))) > 0) { $poWhere = array(); foreach ($purchaseOrderIds as $index => $purchaseOrderId) { $key = 'purchaseOrderId' . $index; $poWhere[] = ':' . $key; $params[$key] = $purchaseOrderId; } $where[] = 'ri.purchaseOrderId in(' . implode(', ', $poWhere) . ')'; } if (isset($criteria->supplierIds) && count($supplierIds = array_filter(explode(',', trim($criteria->supplierIds)))) > 0) { $suppWhere = array(); foreach ($supplierIds as $index => $supplierId) { $key = 'supplierId' . $index; $suppWhere[] = ':' . $key; $params[$key] = $supplierId; } $where[] = 'po.supplierId in(' . implode(', ', $suppWhere) . ')'; } } $sql = 'select sql_calc_found_rows ri.invoiceNo, po.supplierId, sum(ri.qty) `qty`, sum(ri.unitPrice * ri.qty) `price`, group_concat(distinct po.id) `poIds`, group_concat(distinct ri.id) `itemIds`, min(ri.created) `created` from receivingitem ri inner join purchaseorder po on (po.id = ri.purchaseOrderId) where ' . implode(' AND ', $where) . ' group by po.supplierId, ri.invoiceNo order by ri.id desc limit ' . ($pageNo - 1) * $pageSize . ', ' . $pageSize; $rows = Dao::getResultsNative($sql, $params); $stats = array(); $statsResult = Dao::getSingleResultNative('select found_rows()', array(), PDO::FETCH_NUM); $stats['totalRows'] = intval($statsResult[0]); $stats['pageSize'] = $pageSize; $stats['pageNumber'] = $pageNo; $stats['totalPages'] = intval(ceil($stats['totalRows'] / $stats['pageSize'])); $results['items'] = array(); foreach ($rows as $row) { $pos = count($poIds = explode(',', $row['poIds'])) === 0 ? array() : PurchaseOrder::getAllByCriteria('id in (' . implode(',', array_fill(0, count($poIds), '?')) . ')', $poIds); $results['items'][] = array('invoiceNo' => $row['invoiceNo'], 'supplier' => Supplier::get($row['supplierId'])->getJson(), 'created' => $row['created'], 'totalQty' => $row['qty'], 'totalPrice' => $row['price'], 'purchaseOrders' => array_map(create_function('$a', 'return $a->getJson();'), $pos), 'poIds' => explode(',', $row['poIds']), 'itemIds' => explode(',', $row['itemIds'])); } $results['pageStats'] = $stats; } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
function auto_generate_number($type) { $value = ""; if ($type == "Quote") { App::uses('Quote', 'QuoteManager.Model'); $quoteModel = new Quote(); $quotes = $quoteModel->find('all', array('fields' => array('Quote.id,Quote.quote_number'))); if ($quotes) { $quote_number = (int) $quotes[count($quotes) - 1]['Quote']['quote_number']; $cnt = count($quotes); $max = 0; for ($i = 1; $i <= $cnt; $i++) { $num = (int) $quotes[$i - 1]['Quote']['quote_number']; if ($max < $num) { $max = $num; } } $quote_number = explode("-", $quote_number); $length = strlen($quote_number[0] + 1) == strlen($quote_number[0]) ? strlen($quote_number[0]) : strlen($quote_number[0] + 1); for ($i = $length; $i < 6; $i++) { $value .= '0'; } //$value.=$quote_number[0] + 1; $value .= $max + 1; } else { $value = "000001"; } } elseif ($type == "Work Order") { App::uses('WorkOrder', 'WorkOrderManager.Model'); $woModel = new WorkOrder(); $wos = $woModel->find('all', array('fields' => array('WorkOrder.id,work_order_number'))); if ($wos) { $wo_number = (int) $wos[count($wos) - 1]['WorkOrder']['work_order_number']; $length = strlen($wo_number + 1) == strlen($wo_number) ? strlen($wo_number) : strlen($wo_number + 1); for ($i = $length; $i < 6; $i++) { $value .= '0'; } $value .= $wo_number + 1; } else { $value = "000001"; } } elseif ($type == "Purchase Order") { App::uses('PurchaseOrder', 'PurchaseOrderManager.Model'); $poModel = new PurchaseOrder(); $pos = $poModel->find('all', array('fields' => array('PurchaseOrder.id,purchase_order_num'))); if ($pos) { $po_number = (int) $pos[count($pos) - 1]['PurchaseOrder']['purchase_order_num']; $length = strlen($po_number + 1) == strlen($po_number) ? strlen($po_number) : strlen($po_number + 1); for ($i = $length; $i < 6; $i++) { $value .= '0'; } $value .= $po_number + 1; } else { $value = "000001"; } } elseif ($type == "Invoice") { App::uses('Invoice', 'Invoice.Model'); $invoiceModel = new Invoice(); $invoice = $invoiceModel->find('all', array('fields' => array('Invoice.id,invoice_no'))); if ($invoice) { $invoice_number = (int) $invoice[count($invoice) - 1]['Invoice']['invoice_no']; $length = strlen($invoice_number + 1) == strlen($invoice_number) ? strlen($invoice_number) : strlen($invoice_number + 1); for ($i = $length; $i < 6; $i++) { $value .= '0'; } $value .= $invoice_number + 1; } else { $value = "000001"; } } return $value; }
<?php if (!isset($system) || $system != 'yes') { die("<H2>You are not allowed to view this resource</H2>"); } //fetch purchase_order_details require_once "./classes/class.purchaseorder.php"; $purchaseorder = new PurchaseOrder(); $purchaseorder->setPurchaseOrderID($a_s_id); $purchase_order_details = $purchaseorder->purchase_order_details(); //$purchase_order_details=$db->get_results("SELECT * FROM purchase_order WHERE po_s_id='$a_s_id' AND po_status='1'");
/** * creating a PO * * @param Supplier $supplier * @param string $supplierRefNo * @param string $supplierContact * @param string $supplierContactNumber * @param string $shippingCost * @param string $handlingCost * @param bool $isCredit * * @return PurchaseOrder */ public static function create(Supplier $supplier, $supplierRefNo = '', $supplierContact = '', $supplierContactNumber = '', $shippingCost = 0, $handlingCost = 0, $isCredit = false, PurchaseOrder $fromPO = null) { $entity = new PurchaseOrder(); return $entity->setSupplier($supplier)->setSupplierRefNo(trim($supplierRefNo))->setSupplierContact($supplierContact)->setSupplierContactNumber($supplierContactNumber)->setshippingCost($shippingCost)->sethandlingCost($handlingCost)->setIsCredit($isCredit)->setFromPO($fromPO)->save(); }
********************************************************************************/ require_once 'Smarty_setup.php'; require_once "data/Tracker.php"; require_once 'modules/PurchaseOrder/PurchaseOrder.php'; require_once 'include/logging.php'; require_once 'include/ListView/ListView.php'; require_once 'include/utils/utils.php'; require_once 'modules/CustomView/CustomView.php'; require_once 'include/database/Postgres8.php'; global $app_strings, $list_max_entries_per_page, $currentModule, $theme; $log = LoggerManager::getLogger('order_list'); if (!isset($where)) { $where = ""; } $url_string = '&smodule=PO'; $focus = new PurchaseOrder(); // Initialize sort by fields $focus->initSortbyField('PurchaseOrder'); // END $smarty = new vtigerCRM_Smarty(); $other_text = array(); if (!$_SESSION['lvs'][$currentModule]) { unset($_SESSION['lvs']); $modObj = new ListViewSession(); $modObj->sorder = $sorder; $modObj->sortby = $order_by; $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); } if ($_REQUEST['errormsg'] != '') { $errormsg = vtlib_purify($_REQUEST['errormsg']); $smarty->assign("ERROR", "The User does not have permission to Change/Delete " . $errormsg . " " . $currentModule);
* * The Initial Developer of the Original Code is C3CRM Team. * Portions created by C3CRM are Copyright (C) 2005 C3CRM * All Rights Reserved. * Contributors: Goodwill Consulting http://www.goodwill.co.id ********************************************************************************/ require_once 'XTemplate/xtpl.php'; require_once 'data/Tracker.php'; require_once 'modules/PurchaseOrders/PurchaseOrder.php'; require_once 'modules/PurchaseOrders/Forms.php'; require_once 'include/JSON.php'; global $app_strings; global $app_list_strings; global $mod_strings; global $current_user; $focus = new PurchaseOrder(); if (isset($_REQUEST['record'])) { $focus->retrieve($_REQUEST['record']); } if (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { $focus->id = ""; } echo "\n<p>\n"; echo get_module_title($mod_strings['LBL_MODULE_NAME'], $mod_strings['LBL_MODULE_NAME'] . ": " . $focus->name, true); echo "\n</p>\n"; global $theme; $theme_path = "themes/" . $theme . "/"; $image_path = $theme_path . "images/"; require_once $theme_path . 'layout_utils.php'; $log->info("PurchaseOrder detail view"); $xtpl = new XTemplate('modules/PurchaseOrders/EditView.html');
function createpdffile($idnumber, $purpose = '', $path = '', $current_id = '') { require_once 'include/tcpdf/tcpdf.php'; require_once 'include/tcpdf/config/tcpdf_config.php'; require_once 'modules/PurchaseOrder/PurchaseOrder.php'; require_once 'include/database/PearDatabase.php'; require_once 'include/utils/InventoryUtils.php'; require_once 'include/utils/PDFutils.php'; require_once 'test/contact/bank.php'; global $FOOTER_PAGE, $default_font, $font_size_footer, $NUM_FACTURE_NAME, $pdf_strings, $PurchaseOrder_no, $footer_margin; global $org_name, $org_address, $org_city, $org_code, $org_country, $org_irs, $org_taxid, $org_phone, $org_fax, $org_website; global $VAR40_NAME, $VAR3_NAME, $VAR4_NAME, $ORG_POSITION, $VAR_PAGE, $VAR_OF; //bank information - content global $bank_name, $bank_street, $bank_city, $bank_zip, $bank_country, $bank_account, $bank_routing, $bank_iban, $bank_swift; //bank information - labels from language files global $ACCOUNT_NUMBER, $ROUTING_NUMBER, $SWIFT_NUMBER, $IBAN_NUMBER; global $columns, $logoradio, $logo_name, $footerradio, $pageradio; global $adb, $app_strings, $focus, $current_user; $module = 'PurchaseOrder'; //get bank information $bank_name = $bank_array['bank_name']; $bank_street = $bank_array['bank_street']; $bank_city = $bank_array['bank_city']; $bank_zip = $bank_array['bank_zip']; $bank_country = $bank_array['bank_country']; $bank_account = $bank_array['bank_account']; $bank_routing = $bank_array['bank_routing']; $bank_iban = $bank_array['bank_iban']; $bank_swift = $bank_array['bank_swift']; //get tax information $org_taxid = $tax_array['org_taxid']; $org_irs = $tax_array['org_irs']; //get the stored configuration values $pdf_config_details = getAllPDFDetails('PurchaseOrder'); //set font $default_font = getTCPDFFontsname($pdf_config_details[fontid]); if ($default_font == '') { $default_font = 'freesans'; } $font_size_header = $pdf_config_details[fontsizeheader]; $font_size_address = $pdf_config_details[fontsizeaddress]; $font_size_body = $pdf_config_details[fontsizebody]; $font_size_footer = $pdf_config_details[fontsizefooter]; //select comma or dot as numberformat //European Format $decimal_precision = 2; $decimals_separator = ','; $thousands_separator = '.'; //US Format //$decimal_precision = 2; //$decimals_separator = '.'; //$thousands_separator = ','; //get users data //select language file if (file_exists("modules/PurchaseOrder/language/" . $pdf_config_details[pdflang] . ".lang.pdf.php")) { include "modules/PurchaseOrder/language/" . $pdf_config_details[pdflang] . ".lang.pdf.php"; $language = strtoupper(substr($pdf_config_details[pdflang], -2, 2)); } else { include "modules/PurchaseOrder/language/en_us.lang.pdf.php"; $language = "EN"; } //internal number $id = $idnumber; //retreiving the PO info $focus = new PurchaseOrder(); $focus->retrieve_entity_info($id, 'PurchaseOrder'); $vendor_name = getVendorName($focus->column_fields['vendor_id']); //get vendors No $sql = "SELECT vendor_no FROM vtiger_vendor where vendorid = '" . $focus->column_fields['vendor_id'] . "'"; $result = $adb->query($sql); $vendor_id = $adb->query_result($result, 0, 'vendor_no'); $carriername = $focus->column_fields['carrier']; $PurchaseOrder_no = $focus->column_fields['purchaseorder_no']; $sql = "select vtiger_currency_info.currency_symbol from vtiger_currency_info where vtiger_currency_info.id= " . $focus->column_fields['currency_id']; $currency_symbol = $adb->query_result($adb->query($sql), 0, 'currency_symbol'); //get the PO date set $date_to_display_array = array(str_replace("-", ".", getDisplayDate(date("Y-m-d")))); $date_created = getDisplayDate($focus->column_fields['createdtime']); $date_array = explode(" ", $date_created); $date_to_display_array[1] = str_replace("-", ".", $date_array[0]); $date_modified = getDisplayDate($focus->column_fields['modifiedtime']); $date_array = explode(" ", $date_modified); $date_to_display_array[2] = str_replace("-", ".", $date_array[0]); $date_to_display = $date_to_display_array[$pdf_config_details['dateused']]; //number of lines after headline $space_headline = $pdf_config_details['space_headline']; //display logo? $logoradio = $pdf_config_details['logoradio']; //display summary? $summaryradio = $pdf_config_details['summaryradio']; //display footer? $footerradio = $pdf_config_details['footerradio']; //display footer page number? $pageradio = $pdf_config_details['pageradio']; //display requisition #? $req = $pdf_config_details['poname']; //display vendor id? $carrier = $pdf_config_details['carrier']; //display vendor id? $vendor = $pdf_config_details['clientid']; // get company information from settings $add_query = "select * from vtiger_organizationdetails"; $result = $adb->query($add_query); $num_rows = $adb->num_rows($result); if ($num_rows > 0) { $org_name = $adb->query_result($result, 0, "organizationname"); $org_address = $adb->query_result($result, 0, "address"); $org_city = $adb->query_result($result, 0, "city"); $org_state = $adb->query_result($result, 0, "state"); $org_country = $adb->query_result($result, 0, "country"); $org_code = $adb->query_result($result, 0, "code"); $org_phone = $adb->query_result($result, 0, "phone"); $org_fax = $adb->query_result($result, 0, "fax"); $org_website = $adb->query_result($result, 0, "website"); $logo_name = $adb->query_result($result, 0, "logoname"); } // get owner information $recordOwnerArr = getRecordOwnerId($_REQUEST['record']); foreach ($recordOwnerArr as $type => $id) { $ownertype = $type; $ownerid = $id; } if ($ownertype == 'Users') { // get owner information for user $sql = "SELECT * FROM vtiger_users,vtiger_crmentity WHERE vtiger_users.id = vtiger_crmentity.smownerid AND vtiger_crmentity.crmid = '" . $_REQUEST['record'] . "'"; $result = $adb->query($sql); $owner_lastname = $adb->query_result($result, 0, 'last_name'); $owner_firstname = $adb->query_result($result, 0, 'first_name'); $owner_id = $adb->query_result($result, 0, 'smownerid'); $owner_phone = $adb->query_result($result, 0, 'phone_work'); $owner_title = decode_html(trim($adb->query_result($result, 0, 'title'))); } else { // get owner information for Groups $sql = "SELECT * FROM vtiger_groups,vtiger_crmentity WHERE vtiger_groups.groupid = vtiger_crmentity.smownerid AND vtiger_crmentity.crmid = '" . $_REQUEST['record'] . "'"; $result = $adb->query($sql); $owner_lastname = ''; $owner_firstname = $adb->query_result($result, 0, 'groupname'); $owner_id = $adb->query_result($result, 0, 'smownerid'); $owner_phone = $org_phone; $owner_title = ''; } //display owner? $owner = $pdf_config_details['owner']; //display owner phone#? $ownerphone = $pdf_config_details['ownerphone']; //to display at product description based on tax type $gproddetailarray = array($pdf_config_details[gprodname], $pdf_config_details[gproddes], $pdf_config_details[gprodcom]); $gproddetails = 0; foreach ($gproddetailarray as $key => $value) { if ($value == 'true') { if ($key == 0) { $gproddetails = $gproddetails + 1; } else { $gproddetails = $gproddetails + $key * 2; } } } $iproddetails = 0; $iproddetailarray = array($pdf_config_details[iprodname], $pdf_config_details[iproddes], $pdf_config_details[iprodcom]); foreach ($iproddetailarray as $key => $value) { if ($value == 'true') { if ($key == 0) { $iproddetails = $iproddetails + 1; } else { $iproddetails = $iproddetails + $key * 2; } } } // PO Requisition Nummer $subject = $focus->column_fields[requisition_no]; if ($focus->column_fields["hdnTaxType"] == "individual") { $product_taxes = 'true'; } else { $product_taxes = 'false'; } // **************** BEGIN POPULATE DATA ******************** $requisition_no = $focus->column_fields["requisition_no"]; $customermark = $focus->column_fields["tracking_no"]; $valid_till = $focus->column_fields["duedate"]; $valid_till = str_replace("-", ".", getDisplayDate($valid_till)); $bill_street = decode_html($focus->column_fields["bill_street"]); $bill_city = decode_html($focus->column_fields["bill_city"]); $bill_state = decode_html($focus->column_fields["bill_state"]); $bill_code = decode_html($focus->column_fields["bill_code"]); $bill_country = decode_html($focus->column_fields["bill_country"]); //format contact name $contact_name = decode_html(getContactforPDF($focus->column_fields["contact_id"])); //get department of contact or account, contact wins $contact_department = ''; //get contact department if (trim($focus->column_fields["contact_id"]) != '') { $sql = "select * from vtiger_contactdetails where contactid=" . $focus->column_fields["contact_id"]; $result = $adb->query($sql); $contact_department = decode_html(trim($adb->query_result($result, 0, "department"))); $contact_firstname = decode_html(trim($adb->query_result($result, 0, "firstname"))); $contact_lastname = decode_html(trim($adb->query_result($result, 0, "lastname"))); $contact_salutation = decode_html(trim($adb->query_result($result, 0, "salutation"))); } $ship_street = $focus->column_fields["ship_street"]; $ship_city = $focus->column_fields["ship_city"]; $ship_state = $focus->column_fields["ship_state"]; $ship_code = $focus->column_fields["ship_code"]; $ship_country = $focus->column_fields["ship_country"]; // condition field for last page $conditions = decode_html($focus->column_fields["terms_conditions"]); // description field for first page $description = decode_html($focus->column_fields["description"]); // ************************ BEGIN POPULATE DATA *************************** //get the Associated Products for this Purchase Order $focus->id = $focus->column_fields["record_id"]; $associated_products = getAssociatedProducts("PurchaseOrder", $focus); $num_products = count($associated_products); //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes and adjustment $final_details = $associated_products[1]['final_details']; //getting the Net Total $price_subtotal = $final_details["hdnSubTotal"]; $price_subtotal_formated = number_format($price_subtotal, $decimal_precision, $decimals_separator, $thousands_separator); //Final discount amount/percentage $discount_amount = $final_details["discount_amount_final"]; $discount_percent = $final_details["discount_percentage_final"]; if ($discount_amount != "") { $price_discount = $discount_amount; $price_discount_formated = number_format($price_discount, $decimal_precision, $decimals_separator, $thousands_separator); } else { if ($discount_percent != "") { //This will be displayed near Discount label $final_price_discount_percent = "(" . number_format($discount_percent, $decimal_precision, $decimals_separator, $thousands_separator) . " %)"; $price_discount = $discount_percent * $final_details["hdnSubTotal"] / 100; $price_discount_formated = number_format($price_discount, $decimal_precision, $decimals_separator, $thousands_separator); } else { $price_discount = "0.00"; } } //Adjustment $price_adjustment = $final_details["adjustment"]; $price_adjustment_formated = number_format($price_adjustment, $decimal_precision, $decimals_separator, $thousands_separator); //Grand Total $price_total = $final_details["grandTotal"]; $price_total_formated = number_format($price_total, $decimal_precision, $decimals_separator, $thousands_separator); //To calculate the group tax amount if ($final_details['taxtype'] == 'group') { $group_tax_total = $final_details['tax_totalamount']; $price_salestax = $group_tax_total; $price_salestax_formated = number_format($price_salestax, $decimal_precision, $decimals_separator, $thousands_separator); $group_total_tax_percent = '0.00'; $group_tax_details = $final_details['taxes']; for ($i = 0; $i < count($group_tax_details); $i++) { $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage']; } } //S&H amount $sh_amount = $final_details['shipping_handling_charge']; $price_shipping_formated = number_format($sh_amount, $decimal_precision, $decimals_separator, $thousands_separator); //S&H taxes $sh_tax_details = $final_details['sh_taxes']; $sh_tax_percent = '0.00'; for ($i = 0; $i < count($sh_tax_details); $i++) { $sh_tax_percent = $sh_tax_percent + $sh_tax_details[$i]['percentage']; } $sh_tax_amount = $final_details['shtax_totalamount']; $price_shipping_tax = number_format($sh_tax_amount, $decimal_precision, $decimals_separator, $thousands_separator); //to calculate the individuel tax amounts included we should get all available taxes and then retrieve the corresponding tax values $tax_details = getAllTaxes('available'); $numer_of_tax_types = count($tax_details); for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) { $taxtype_listings[taxname . $tax_count] = $tax_details[$tax_count]['taxname']; $taxtype_listings[percentage . $tax_count] = $tax_details[$tax_count]['percentage']; $taxtype_listings[value . $tax_count] = '0'; } //This is to get all prodcut details as row basis for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) { $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i]; $product_name[$i] = decode_html($associated_products[$i]['productName' . $i]); $prod_description[$i] = decode_html($associated_products[$i]['productDescription' . $i]); $qty[$i] = $associated_products[$i]['qty' . $i]; $qty_formated[$i] = number_format($associated_products[$i]['qty' . $i], $decimal_precision, $decimals_separator, $thousands_separator); $comment[$i] = decode_html($associated_products[$i]['comment' . $i]); $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], $decimal_precision, $decimals_separator, $thousands_separator); $list_price[$i] = number_format($associated_products[$i]['listPrice' . $i], $decimal_precision, $decimals_separator, $thousands_separator); $list_pricet[$i] = $associated_products[$i]['listPrice' . $i]; $discount_total[$i] = $associated_products[$i]['discountTotal' . $i]; $discount_totalformated[$i] = number_format($associated_products[$i]['discountTotal' . $i], $decimal_precision, $decimals_separator, $thousands_separator); //added by crm-now $usageunit[$i] = $associated_products[$i]['usageunit' . $i]; //look whether the entry already exists, if the translated string is available then the translated string other wise original string will be returned $usageunit[$i] = getTranslatedString($usageunit[$i], 'Products'); $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i]; $producttotal = $taxable_total; $total_taxes = '0.00'; if ($focus->column_fields["hdnTaxType"] == "individual") { $total_tax_percent = '0.00'; //This loop is to get all tax percentage and then calculate the total of all taxes for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) { $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage']; $total_tax_percent = $total_tax_percent + $tax_percent; $tax_amount = $taxable_total * $tax_percent / 100; //calculate the tax amount for any available tax percentage $detected_tax = substr(array_search($total_tax_percent, $taxtype_listings), -1); $taxtype_listings[value . $detected_tax] = $taxtype_listings[value . $detected_tax] + $tax_amount; $total_taxes = $total_taxes + $tax_amount; } $producttotal = $taxable_total + $total_taxes; $product_line[$j][$pdf_strings['Tax']] = " ({$total_tax_percent} %) " . number_format($total_taxes, $decimal_precision, $decimals_separator, $thousands_separator); // combine product name, description and comment to one field based on settings } // combine product name, description and comment to one field based on settings if ($focus->column_fields["hdnTaxType"] == "individual") { $product_selection = $iproddetails; } else { $product_selection = $gproddetails; } switch ($product_selection) { case 1: $product_name_long[$i] = $product_name[$i]; break; case 2: $product_name_long[$i] = $prod_description[$i]; break; case 3: $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i]; break; case 4: $product_name_long[$i] = $comment[$i]; break; case 5: $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i]; break; case 6: if ($prod_description[$i] != '') { $product_name_long[$i] = $prod_description[$i] . "\n" . $comment[$i]; } else { $product_name_long[$i] = $comment[$i]; } break; case 7: if ($prod_description[$i] != '') { $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i] . "\n" . $comment[$i]; } else { $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i]; } break; default: if ($prod_description[$i] != '') { $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i] . "\n" . $comment[$i]; } else { $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i]; } break; } $prod_total[$i] = number_format($producttotal, $decimal_precision, $decimals_separator, $thousands_separator); $product_line[$j][$pdf_strings['Position']] = $j + 1; $product_line[$j][$pdf_strings['OrderCode']] = $product_code[$i]; $product_line[$j][$pdf_strings['Description']] = $product_name_long[$i]; $product_line[$j][$pdf_strings['Qty']] = $qty_formated[$i]; $product_line[$j][$pdf_strings['Unit']] = $usageunit[$i]; $product_line[$j][$pdf_strings['UnitPrice']] = $list_price[$i]; $product_line[$j][$pdf_strings['Discount']] = $discount_totalformated[$i]; $product_line[$j][$pdf_strings['LineTotal']] = $prod_total[$i]; } //Population of current date $addyear = strtotime("+0 year"); $dat_fmt = $current_user->date_format == '' ? 'dd-mm-yyyy' : $current_user->date_format; $date_issued = $dat_fmt == 'dd-mm-yyyy' ? date('d-m-Y', $addyear) : ($dat_fmt == 'mm-dd-yyyy' ? date('m-d-Y', $addyear) : ($dat_fmt == 'yyyy-mm-dd' ? date('Y-m-d', $addyear) : '')); // ************************ END POPULATE DATA *************************** //************************BEGIN PDF FORMATING************************** // Extend the TCPDF class to create custom Header and Footer class MYPDF extends TCPDF { //modifiy tcpdf class footer public function Footer() { //To make the function Footer() work properly $this->AliasNbPages(); if (!isset($this->original_lMargin)) { $this->original_lMargin = $this->lMargin; } if (!isset($this->original_rMargin)) { $this->original_rMargin = $this->rMargin; } include "modules/PurchaseOrder/pdf_templates/footer.php"; } } $page_num = '1'; // create new PDF document //$pdf = new PDF( 'P', 'mm', 'A4' ); $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true); // set font $pdf->SetFont($default_font, " ", $default_font_size); $pdf->setPrintHeader(0); //header switched off permanently // auto break on //$pdf->SetAutoPageBreak(true); // set footer fonts //$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); // set pdf information $pdf->SetTitle($pdf_strings['FACTURE'] . ": " . $account_name); $pdf->SetAuthor($owner_firstname . " " . $owner_lastname . ", " . $org_name); $pdf->SetSubject($account_name); $pdf->SetCreator('CRM PDF Creator from www.crm-now.com'); //list product names as keywords $productlisting = implode(", ", $product_name); $pdf->SetKeywords($productlisting); //Disable automatic page break $pdf->SetAutoPageBreak(true, PDF_MARGIN_FOOTER); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($l); //initialize document $pdf->AliasNbPages(); //in reference to body.php -> if a new page must be added if the space available for summary is too small $new_page_started = false; $pdf->AddPage(); $pdf->setImageScale(1.5); //$pdf->SetY(PDF_MARGIN_HEADER); include "modules/PurchaseOrder/pdf_templates/header.php"; $pdf->SetFont($default_font, " ", $font_size_body); include "modules/PurchaseOrder/pdf_templates/body.php"; // issue pdf if ($purpose == 'print') { $pdf->Output($pdf_strings['FACTURE'] . '_' . $date_issued . '.pdf', 'D'); } elseif ($purpose == 'send') { // send pdf with mail switch ($language) { case "EN": $pdf->Output('storage/PurchaseOrder_' . $_REQUEST['record'] . '.pdf', 'F'); //added file name to make it work in IE, also forces the download giving the user the option to save break; case "DE": $pdf->Output('storage/Einkaufsbestellung_' . $_REQUEST['record'] . '.pdf', 'F'); //added file name to make it work in IE, also forces the download giving the user the option to save break; } return; } exit; }
<?php // Copyright SQCRM. For licensing, reuse, modification and distribution see license.txt /** * PurchaseOrder detail * @author Abhik Chakraborty */ $do_crmfields = new CRMFields(); $do_block = new Block(); $do_block->get_block_by_module($module_id); $module_obj = new PurchaseOrder(); $module_obj->getId($sqcrm_record_id); $do_lineitems = new Lineitems(); $do_lineitems->get_line_items($module_id, $sqcrm_record_id); $lineitems = array(); if ($do_lineitems->getNumRows() > 0) { while ($do_lineitems->next()) { $lineitems[] = array("idlineitems" => $do_lineitems->idlineitems, "item_type" => $do_lineitems->item_type, "item_name" => $do_lineitems->item_name, "item_value" => $do_lineitems->item_value, "item_description" => $do_lineitems->item_description, "item_quantity" => $do_lineitems->item_quantity, "item_price" => $do_lineitems->item_price, "discount_type" => $do_lineitems->discount_type, "discount_value" => $do_lineitems->discount_value, "discounted_amount" => $do_lineitems->discounted_amount, "tax_values" => $do_lineitems->tax_values, "taxed_amount" => $do_lineitems->taxed_amount, "total_after_discount" => $do_lineitems->total_after_discount, "total_after_tax" => $do_lineitems->total_after_tax, "net_total" => $do_lineitems->net_total); } } //updates detail, just add and last updated $do_crmentity = new CRMEntity(); $update_history = $do_crmentity->get_last_updates($sqcrm_record_id, $module_id, $module_obj); if (isset($_GET['ajaxreq']) && $_GET['ajaxreq'] == true) { require_once 'view/detail_view_entry.php'; } else { require_once 'view/detail_view.php'; }
$_REQUEST['shipping_handling_charge'] = $shipping_handling_charge = '50'; $_REQUEST['adjustmenttype'] = '+'; $_REQUEST['adjustment'] = $adjustment = '100'; $_REQUEST['total'] = $subtotal - $discount_amount_final + $shipping_handling_charge + $adjustment; //Upto this added to set the request values which will be used to save the inventory product details //Now call the saveInventoryProductDetails function saveInventoryProductDetails($so, 'SalesOrder'); } //Populate PurchaseOrder Data $psubj_array = array("PO_vtiger", "PO_zoho", "PO_vtiger5usrp", "PO_vt100usrpk", "PO_vendtl"); $pstatus_array = array("Created", "Delivered", "Approved", "Cancelled", "Received Shipment"); $carrier_array = array("FedEx", "UPS", "USPS", "DHL", "BlueDart"); $trkno_array = array("po1425", "po2587", "po7974", "po7979", "po6411"); $duedate_array = array("2007-04-21", "2007-05-29", "2007-07-11", "2007-04-09", "2006-08-18"); for ($i = 0; $i < 5; $i++) { $po = new PurchaseOrder(); $po->column_fields["assigned_user_id"] = $assigned_user_id; $vendor_key = array_rand($vendor_ids); $po->column_fields["vendor_id"] = $vendor_ids[$vendor_key]; $contact_key = array_rand($contact_ids); $po->column_fields["contact_id"] = $contact_ids[$contact_key]; $rand = array_rand($num_array); $po->column_fields["subject"] = $psubj_array[$i]; $po->column_fields["postatus"] = $pstatus_array[$i]; $po->column_fields["carrier"] = $carrier_array[$i]; $po->column_fields["tracking_no"] = $trkno_array[$i]; $po->column_fields["duedate"] = $duedate_array[$i]; $po->column_fields["bill_street"] = $street_address_array[rand(0, $street_address_count - 1)]; $po->column_fields["bill_city"] = $city_array[rand(0, $city_array_count - 1)]; $po->column_fields["bill_state"] = "CA"; $po->column_fields["bill_code"] = rand(10000, 99999);
/** * function to generate inventory (quote,invoice,sales order,purchase order) PDF * @param integer $idquotes * @param boolean $save * @see http://www.mpdf1.com/mpdf/index.php */ public function generate_inventory_pdf($idrecord, $idmodule, $save = false) { include_once BASE_PATH . THIRD_PARTY_LIB_PATH . "/mpdf/mpdf.php"; //echo BASE_PATH.THIRD_PARTY_LIB_PATH ;exit; $pdf = new \mPDF(); $crm_global_settings = new \CRMGlobalSettings(); if ($idmodule == 13) { $obj = new \Quotes(); $obj->getId($idrecord); $prefix = $crm_global_settings->get_setting_data_by_name('quote_num_prefix'); $inventory_type = _('QUOTE'); $inv = 'q'; $inv_number_fld = 'quote_number'; $inv_date_fld = 'valid_till'; $file_name = 'Quote_' . $prefix . $obj->quote_number . '.pdf'; $inventory_number = _('Quote #'); } elseif ($idmodule == 14) { $obj = new \SalesOrder(); $obj->getId($idrecord); $prefix = $crm_global_settings->get_setting_data_by_name('salesorder_num_prefix'); $inventory_type = _('SALES ORDER'); $inv = 'so'; $inv_number_fld = 'sales_order_number'; $inv_date_fld = 'due_date'; $file_name = 'SalesOrder_' . $prefix . $obj->sales_order_number . '.pdf'; $inventory_number = _('Sales Order #'); } elseif ($idmodule == 15) { $obj = new \Invoice(); $obj->getId($idrecord); $prefix = $crm_global_settings->get_setting_data_by_name('invoice_num_prefix'); $inventory_type = _('INVOICE'); $inv = 'inv'; $inv_number_fld = 'invoice_number'; $inv_date_fld = 'due_date'; $file_name = 'Invoice_' . $prefix . $obj->invoice_number . '.pdf'; $inventory_number = _('Invoice #'); } elseif ($idmodule == 16) { $obj = new \PurchaseOrder(); $obj->getId($idrecord); $prefix = $crm_global_settings->get_setting_data_by_name('purchaseorder_num_prefix'); $inventory_type = _('PURCHASE ORDER'); $inv = 'po'; $inv_number_fld = 'po_number'; $inv_date_fld = 'due_date'; $file_name = 'PurchaseOrder_' . $prefix . $obj->po_number . '.pdf'; $inventory_number = _('Purchase Order #'); } $inventory_logo = $crm_global_settings->get_setting_data_by_name('inventory_logo'); $company_address = $crm_global_settings->get_setting_data_by_name('company_address'); $do_lineitems = new \Lineitems(); $do_lineitems->get_line_items($idmodule, $idrecord); $lineitems = array(); if ($do_lineitems->getNumRows() > 0) { while ($do_lineitems->next()) { $lineitems[] = array("idlineitems" => $do_lineitems->idlineitems, "item_type" => $do_lineitems->item_type, "item_name" => $do_lineitems->item_name, "item_value" => $do_lineitems->item_value, "item_description" => $do_lineitems->item_description, "item_quantity" => $do_lineitems->item_quantity, "item_price" => $do_lineitems->item_price, "discount_type" => $do_lineitems->discount_type, "discount_value" => $do_lineitems->discount_value, "discounted_amount" => $do_lineitems->discounted_amount, "tax_values" => $do_lineitems->tax_values, "taxed_amount" => $do_lineitems->taxed_amount, "total_after_discount" => $do_lineitems->total_after_discount, "total_after_tax" => $do_lineitems->total_after_tax, "net_total" => $do_lineitems->net_total); } } $html = ''; if (is_array($lineitems) && count($lineitems) > 0) { //--load the stylesheet $stylesheet = file_get_contents(BASE_PATH . '/themes/custom-css/inventory_export.css'); $pdf->WriteHTML($stylesheet, 1); $html .= ' <div> <div class="inv_wrapper"> <h1 class="inv_heading">' . $inventory_type . '</h1> <div class="inv_address_wrapper"> <p class="inv_address_section"> <span class="inv_address_to_from">FROM:</span><br> ' . nl2br($company_address) . ' </p> </div> <div class="inv_company_address_wrapper"> <img class="inv_company_address_logo" src="' . $GLOBALS['FILE_UPLOAD_DISPLAY_PATH'] . '/' . $inventory_logo . '"> </div> </div> <div style="clear:both;"></div> <div class="inv_wrapper"> <div class="inv_address_wrapper"> <p class="inv_address_section"> <span class="inv_address_to_from">To:</span><br>' . $this->generate_to_address($obj, $inv) . ' </p> </div> <div class="inv_brief_section"> <table class="inv_brief_section_table"> <tr> <th class="inv_brief_section_table_heading"> <span>' . $inventory_number . '</span> </th> <td class="inv_brief_section_table_content"> <span>' . $prefix . $obj->{$inv_number_fld} . '</span> </td> </tr> <tr> <th class="inv_brief_section_table_heading"> <span>Date</span> </th> <td class="inv_brief_section_table_content"> <span>' . \FieldType9::display_value($obj->{$inv_date_fld}) . '</span> </td> </tr> <tr> <th class="inv_brief_section_table_heading"> <span>Amount Due</span> </th> <td class="inv_brief_section_table_content"> <span>' . \FieldType30::display_value($obj->grand_total) . '</span> </td> </tr> </table> </div> </div> <div style="clear:both;"></div> <br> '; $html .= ' <table class="inv_line_table"> <thead> <tr> <th class="inv_line_table_header inv_line_table_header_width_30"> <span>Item Name</span> </th> <th class="inv_line_table_header inv_line_table_header_width_10"> <span>Qty</span> </th> <th class="inv_line_table_header inv_line_table_header_width_30"> <span>Price</span> </th> <th class="inv_line_table_header inv_line_table_header_width_15"> <span>Total</span> </th> <th class="inv_line_table_header inv_line_table_header_width_15"> <span>Net Price</span> </th> </tr> </thead> '; $html .= '<tbody>'; foreach ($lineitems as $key => $items) { $line_discount = ''; if ($items["discount_type"] == 'direct') { $line_discount = _('Discount') . '-' . \FieldType30::display_value($items["discount_value"]); } elseif ($items["discount_type"] == 'percentage') { $line_discount = _('Discount') . '-' . $items["discount_value"] . ' %'; } else { $line_discount = _('Discount') . '-' . _('no discount'); } $line_tax = ''; if ($items["tax_values"] != '') { $line_tax = ' - ' . rtrim($items["tax_values"], ','); } else { $line_tax = ' - no tax'; } $html .= ' <tr> <td class="inv_line_table_content inv_line_table_content_vertical_top"> <div class="inv_line_table_content_block"> ' . $items["item_name"] . ' <br><br> ' . nl2br($items["item_description"]) . ' </div> </td> <td class="inv_line_table_content inv_line_table_content_vertical_top"> <div class="inv_line_table_content_block"> ' . \FieldType16::display_value($items["item_quantity"]) . ' </div> </td> <td class="inv_line_table_content"> <div class="inv_line_table_content_block"> ' . \FieldType30::display_value($items["item_price"]) . ' </div> <div class="inv_line_table_content_block"> ' . $line_discount . ' </div> <div class="inv_line_table_content_block"> <b>Total after discount</b> </div> <div class="inv_line_table_content_block"> <b>Tax </b> ' . $line_tax . ' </div> </td> <td class="inv_line_table_content"> <div class="inv_line_table_content_block"> ' . \FieldType30::display_value($items["item_price"] * $items["item_quantity"]) . ' </div> <div class="inv_line_table_content_block"> ' . \FieldType30::display_value($items["discounted_amount"]) . ' </div> <div class="inv_line_table_content_block"> ' . \FieldType30::display_value($items["total_after_discount"]) . ' </div> <div class="inv_line_table_content_block"> ' . \FieldType30::display_value($items["taxed_amount"]) . ' </div> </td> <td class="inv_line_table_content inv_line_table_content_vertical_top"> ' . \FieldType30::display_value($items["net_total"]) . ' </td> </tr>'; } $html .= ' </tbody></table>'; $net_discount = ''; if ($obj->discount_type == 'percentage') { $net_discount = $obj->discount_value . ' %'; } elseif ($obj->discount_type == 'direct') { $net_discount = FieldType30::display_value($obj->discount_value); } else { $net_discount = _('no discount'); } $net_tax = ''; if ($obj->tax_values != '') { $net_tax = rtrim($obj->tax_values, ','); } $ship_hand_tax = ''; if ($obj->shipping_handling_tax_values != '') { $ship_hand_tax = rtrim($obj->shipping_handling_tax_values, ','); } $final_adj = ''; if ($obj->final_adjustment_type == 'add') { $final_adj = '(+)'; } elseif ($obj->final_adjustment_type == 'deduct') { $final_adj = '(-)'; } $html .= ' <div style="clear:both;"></div> <br> <div class="inv_grand_total_section"> <table class="inv_grand_total_table"> <tr> <td class="inv_grand_total_table_header"> <span><b>Net Total</b></span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->net_total) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Discount -</b> ' . $net_discount . '</span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->discounted_amount) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Tax -</b> ' . $net_tax . ' </span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->taxed_amount) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Shipping/Handling charges</b></span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->shipping_handling_charge) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Shipping/Handling Tax -</b>' . $ship_hand_tax . '</span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->shipping_handling_taxed_amount) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Final Adjustment</b>' . $final_adj . '</span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->final_adjustment_amount) . '</span> </td> </tr> <tr> <td class="inv_grand_total_table_header"> <span><b>Grand Total</span> </td> <td class="inv_grand_total_table_content"> <span>' . \FieldType30::display_value($obj->grand_total) . '</span> </td> </tr> </table> </div> <div style="clear:both;"></div> <br> <h3 class="inv_terms_cond_section"> <span>Terms & Condition</span> </h3> <div style="top:2px;"> <p> ' . nl2br($obj->terms_condition) . ' </p> </div></div>'; } if (true === $save) { $pdf->WriteHTML($html); $pdf->Output(OUTBOUND_PATH . '/' . $file_name, 'F'); return $file_name; } else { $pdf->WriteHTML($html, 2); $pdf->Output($file_name, 'D'); exit; } }
public function quote_approved($id = null) { $this->autoRender = FALSE; App::import('Model', 'QuoteManager.QuoteStatus'); $QuoteStatus = new QuoteStatus(); App::import('Model', 'QuoteManager.Quote'); $Quote = new Quote(); $Q_model = new Quote(); $quote['Quote']['id'] = $id; $quote['Quote']['status'] = 'Approve'; $Q_data = $Q_model->find("first", array("conditions" => array("Quote.id" => $id))); if (empty($Q_data['Quote']['est_shipping'])) { if ($Q_data['Quote']['delivery'] == '4 - 8 Weeks Delivery') { $add_days = 56; $today = $Q_data['Quote']['quote_created_date']; $esd_date = date('d/m/Y', strtotime($today) + 24 * 3600 * $add_days); } if ($Q_data['Quote']['delivery'] == '5 - 10 Weeks Delivery') { $add_days = 70; $today = $Q_data['Quote']['quote_created_date']; $esd_date = date('d/m/Y', strtotime($today) + 24 * 3600 * $add_days); } $quote['Quote']['est_shipping'] = $esd_date; } $Quote->save($quote); $quote_status['QuoteStatus']['status'] = 'Approve'; $quote_status['QuoteStatus']['quote_id'] = $id; $quote_info = $Quote->find("first", array("conditions" => array("Quote.id" => $id))); $workorder['WorkOrder']['quote_id'] = $quote_info['Quote']['id']; $workorder['WorkOrder']['project_id'] = $quote_info['Quote']['project_id']; $workorder['WorkOrder']['customer_id'] = $quote_info['Quote']['customer_id']; $workorder['WorkOrder']['status'] = 'New'; $quote_number_explode = explode("-", $quote_info['Quote']['quote_number']); $workorder['WorkOrder']['work_order_number'] = $quote_number_explode[0]; $workorder['WorkOrder']['skid_number'] = $quote_info['Quote']['skid_number']; $workorder['WorkOrder']['skid_weight'] = $quote_info['Quote']['skid_weight']; App::import("Model", "WorkOrderManager.WorkOrder"); $wo = new WorkOrder(); $wo->save($workorder); App::import("Model", "PurchaseOrderManager.PurchaseOrder"); App::import("Model", "PurchaseOrderManager.PurchaseOrderItem"); App::import("Model", "Inventory.Supplier"); App::import('Model', 'PurchaseOrderManager.GeneralSetting'); $supplier = array(); foreach ($quote_info['CabinetOrderItem'] as $quote_item) { $item_info = $this->findQuoteItem($quote_item['item_id']); $supplier_required = $this->findQuoteItemDept($item_info['Item']['item_department_id']); if ($supplier_required['ItemDepartment']['supplier_required'] == 1) { $supplier[$item_info['Item']['supplier_id']][] = $item_info; } } $total_amount = 0; foreach ($supplier as $key => $value) { if (empty($Q_data['Quote']['est_shipping'])) { $est_date_quote = $quote['Quote']['est_shipping']; } else { $est_date_quote = $quote_info['Quote']['est_shipping']; } $purchaseorder = new PurchaseOrder(); $sp_model = new Supplier(); $sp_data = $sp_model->find("first", array("conditions" => array("Supplier.id" => $id))); $general_model = new GeneralSetting(); $location_data = $general_model->find("first", array("conditions" => array("GeneralSetting.name" => 'Default'))); $po['supplier_id'] = $key; $po['work_order_id'] = $wo->id; $po_number = explode("-", $quote_info['Quote']['quote_number']); $po['purchase_order_num'] = $po_number[0]; $po['quote_id'] = $quote_info['Quote']['id']; $po['shipment_date'] = $est_date_quote; $po['payment_type'] = 'On Account'; $po['issued_on'] = date('d/m/Y'); $po['issued_by'] = $this->loginUser['id']; $po['term'] = $sp_data['Supplier']['terms']; $po['location_name'] = $location_data['GeneralSetting']['name']; $po['name_ship_to'] = $location_data['GeneralSetting']['name_address']; $po['address'] = $location_data['GeneralSetting']['address']; $po['city'] = $location_data['GeneralSetting']['city']; $po['province'] = $location_data['GeneralSetting']['province']; $po['postal_code'] = $location_data['GeneralSetting']['postal_code']; $po['country'] = $location_data['GeneralSetting']['country']; foreach ($value as $v) { foreach ($quote_info['CabinetOrderItem'] as $req_info) { if ($req_info['item_id'] == $v['Item']['id']) { $quantity = $req_info['quantity']; $total_amount = $total_amount + $quantity * $v['Item']['price']; } } } App::import("Model", "PurchaseOrderManager.GeneralSetting"); $g_setting = new GeneralSetting(); $gst_rate = $g_setting->find("first", array("conditions" => array("GeneralSetting.type" => 'gst'))); $pst_rate = $g_setting->find("first", array("conditions" => array("GeneralSetting.type" => 'pst'))); $gst_amount = $gst_rate['GeneralSetting']['value'] / 100 * $total_amount; $pst_amount = $pst_rate['GeneralSetting']['value'] / 100 * $total_amount; $total_amount = $total_amount + $gst_amount + $pst_amount; $po['total_amount'] = $total_amount; $purchaseorder->save($po); $index = 0; $purchaseorderitem = new PurchaseOrderItem(); foreach ($value as $v) { foreach ($quote_info['CabinetOrderItem'] as $req_info) { if ($req_info['item_id'] == $v['Item']['id']) { $po_item[$index]['quantity'] = $req_info['quantity']; $po_item[$index]['code'] = $req_info['code']; $po_item[$index]['cabinet_id'] = $req_info['cabinet_id']; $po_item[$index]['door_id'] = $req_info['door_id']; } } $po_item[$index]['item_id'] = $v['Item']['id']; $po_item[$index]['purchase_order_id'] = $purchaseorder->id; $index++; } $purchaseorderitem->saveAll($po_item); } // foreach($quote_info['CabinetOrderItem'] as $quote_item){ // $purchaseorder = new PurchaseOrder(); // $item_info = $this->findQuoteItem($quote_item['item_id']); // $supplier_required = $this->findQuoteItemDept($item_info['Item']['item_department_id']); // if(!empty($supplier_required['ItemDepartment']['supplier_required'])){ // $supplier[$item_info['Item']['supplier_id']][] = $item_info; // $po['supplier_id'] = $item_info['Item']['supplier_id']; // $po['work_order_id'] = $wo->id; // $po['purchase_order_num'] = $quote_info['Quote']['quote_number']; // $po['quote_id'] = $quote_info['Quote']['id']; // $po['shipment_date'] = date("Y-m-d"); // $po['expiry_date'] = date("Y-m-d"); // $po['cc_num'] = 'Test CC Number'; // $po['name_cc'] = 'Test CC Name'; // $po['payment_type'] = 'On Account'; // //$purchaseorder->save($po); // // $index = 0; // foreach($quote_info['CabinetOrderItem'] as $qitem){ // $purchaseorderitem = new PurchaseOrderItem(); // $item_info = $this->findQuoteItem($qitem['item_id']); // $supplier_required = $this->findQuoteItemDept($item_info['Item']['item_department_id']); // if(!empty($supplier_required['ItemDepartment']['supplier_required'])){ // $po_item[$index]['item_id'] = $item_info['Item']['id']; // $po_item[$index]['code'] = $item_info['Item']['id']."|item"; // $po_item[$index]['purchase_order_id'] = $purchaseorder->id; // $index++; // } // } // //$purchaseorderitem->saveAll($po_item); // } // }exit; //exit; if ($QuoteStatus->save($quote_status)) { $this->redirect("http://{$_SERVER['SERVER_NAME']}{$this->webroot}work_order_manager/work_orders/detail/{$wo->id}"); } }
private function _getPurchaseOrders(array $params) { $searchTxt = trim(isset($params['searchTxt']) ? $params['searchTxt'] : ''); if ($searchTxt === '') { throw new Exception('SearchTxt is needed'); } $pageSize = isset($params['pageSize']) && ($pageSize = trim($params['pageSize'])) !== '' ? $pageSize : DaoQuery::DEFAUTL_PAGE_SIZE; $pageNo = isset($params['pageNo']) && ($pageNo = trim($params['pageNo'])) !== '' ? $pageNo : null; $orderBy = isset($params['orderBy']) ? $params['orderBy'] : array(); $where = array('purchaseOrderNo like :searchTxt'); $sqlParams = array('searchTxt' => '%' . $searchTxt . '%'); $stats = array(); $items = PurchaseOrder::getAllByCriteria(implode(' AND ', $where), $sqlParams, true, $pageNo, $pageSize, $orderBy, $stats); $results = array(); $results['items'] = array_map(create_function('$a', 'return $a->getJson();'), $items); $results['pageStats'] = $stats; return $results; }
function generate_number() { $return_value = ''; $number_filed = array('num_suf'); $rown = ''; $n = $this->db->getRowCount($result); $query = 'SELECT num_suf'; $query .= ' FROM purchaseorders'; $query .= " WHERE deleted=0"; $query .= " AND num_suf IS NOT NULL"; $query .= " ORDER by num_suf ASC"; $result = $this->db->query($query, true, " Error filling in additional detail fields: "); $n = $this->db->getRowCount($result); if ($n > 0) { while ($row = $this->db->fetchByAssoc($result)) { foreach ($number_filed as $num_field) { for ($i = 0; $i < $n; $i++) { $rown[$i] = $row[$num_field]; } } } } if ($rown != null) { $return_value = $rown; $number = PurchaseOrder::pnum_sort($return_value); $numb = $number[0] + 1; } else { $numb = 10000; } return $numb; }
public static function PurchaseOrders() { $collection = PurchaseOrder::GetAllOrders($_GET['period'], $_GET['all']); echo ' <div class="logo"> <h5 style="margin-bottom:-15px;margin-top:0px;font-size:14px;">Date: ' . date('d/m/Y') . '</h5> <h4>ALL PURCHASE ORDERS</h4>'; if ($_GET['period'] != '' && $_GET['period']) { echo '<h5 style="margin-top:-10px">Period: ' . $_GET['period'] . '</h5>'; } echo '</div> <table class="table table-bordered table-striped" style="text-align:center;margin-left:0;margin-right:0;width:760px;font-size:12px;"> <thead class="title"> <tr> <td>DATE</td> <td>ORDER ID</td> <td>COMPANY</td> <td>PURPOSE</td> <td>STATUS</td> <td>TOTAL</td> </tr> </thead> <tbody>'; $total = 0.0; $invoiced = 0.0; $itms = 0; foreach ($collection as $item) { echo '<tr> <td>' . $item->date . '</td> <td>' . $item->id . '</td> <td>' . $item->party->name . '</td>'; $sql = 'SELECT * FROM purchase_orders WHERE id = ' . $item->id; $res = DatabaseHandler::GetRow($sql); $vc = PurchaseOrderVoucher::initialize($res); echo '<td>' . $vc->description . '</td>'; if ($item->status == 1) { echo '<td style="color:#232836">CREATED</td>'; } else { echo '<td style="color:#27c97b">ORDERED</td>'; $invoiced += $item->total; } echo '<td class="text-right" style="padding: 0 5px;"><script>document.writeln((' . $item->total . ').formatMoney(2, \'.\', \',\'));</script></td> </tr>'; $total += $item->total; ++$itms; } echo '</tbody> </table> <div class="logo"> <p style="margin: 5px 0 0 5px">Total Quotes: <b>' . $itms . '</b></p> <p style="margin: 5px 0 0 5px">Total Quoted: <b>Ksh. <script>document.writeln((' . $total . ').formatMoney(2, \'.\', \',\'));</script></b></p> <p style="margin: 5px 0 0 5px">Total Invoiced: <b>Ksh. <script>document.writeln((' . $invoiced . ').formatMoney(2, \'.\', \',\'));</script></b></p> </div>'; }