/**
  *
  * @return array
  */
 public function editAction()
 {
     try {
         $this->view->contentTitle = $this->i18n->_("Purchase Order Edit");
         $idPurchaseOrder = $this->getRequest()->getParam('id');
         $this->view->purchaseOrder = $purchaseOrder = PurchaseOrderQuery::create()->findByPKOrThrow($idPurchaseOrder, $this->i18n->_("The Purchase Order width id {$idPurchaseOrder} does not exist"));
         $accessRole = $this->getUser()->getAccessRole();
         $accessRoleManager = new AccessRoleManager();
         $availableSuppliers = $accessRoleManager->getAssociateSuppliers($accessRole);
         if (!$availableSuppliers->containsIndex($purchaseOrder->getIdSupplier())) {
             throw new PurchaseOrderException($this->i18n->_("You don't have permission to edit this Purchase Order."));
         }
         $this->view->supplier = $supplier = $availableSuppliers->getByPK($purchaseOrder->getIdSupplier());
         // Search Purchase Order Entries by id purchase order
         $purchaseOrderEntryManager = new PurchaseOrderEntryManager();
         $purchaseOrderEntries = $purchaseOrderEntryManager->getPurchaseOrderEntries($purchaseOrder);
         $this->view->entries = Zend_Json::encode($purchaseOrderEntryManager->getEntriesToCompleteInfoArray($purchaseOrderEntries));
         // Search the courtyards by id
         if ($purchaseOrder->getIdCourtyard()) {
             $courtyard = CourtyardQuery::create()->findByPKOrElse($purchaseOrder->getIdCourtyard(), new Courtyard());
             if ($courtyard->getIdForwarder()) {
                 $ports = PortCustomQuery::create()->innerJoinForwarder()->whereAdd("Forwarder." . Forwarder::ID_FORWARDER, $courtyard->getIdForwarder())->find()->toCombo();
                 $portCombo = array("" => "Select a Port") + $ports;
                 $courtyards = CourtyardQuery::create()->whereAdd(Courtyard::ID_PORT_CUSTOM, $courtyard->getIdPortCustom())->whereAdd(Courtyard::ID_FORWARDER, $courtyard->getIdForwarder())->find()->toCombo();
                 $courtyardCombo = array("" => "Select Courtyard") + $courtyards;
             } else {
                 $portCombo = array("" => "Select a Port");
                 $courtyardCombo = array("" => "Select Courtyard");
             }
         } else {
             $courtyard = new Courtyard();
             $portCombo = array("" => "Select a Port");
             $courtyardCombo = array("" => "Select a Courtyard");
         }
         $this->view->forwarders = array("" => "Select Forwarder") + ForwarderQuery::create()->find()->toCombo();
         $this->view->portsCustom = $portCombo;
         $this->view->courtyards = $courtyardCombo;
         $this->view->courtyard = $courtyard;
         $this->view->currencies = CurrencyQuery::create()->find();
         $this->view->warehouses = WarehouseQuery::create()->find()->toCombo($this->i18n->_("Select a Warehouse"));
         $this->view->warehouseStore = $warehouseStore = WarehouseStoreQuery::create()->findByPKOrThrow($purchaseOrderEntries->getOne()->getIdWarehouseStore(), $this->i18n->_("The Warehouse Store with Code {$purchaseOrderEntries->current()->getIdWarehouseStore()} does not exist."));
         $this->view->warehouseStores = WarehouseStoreQuery::create()->whereAdd(WarehouseStore::LOCATION, $warehouseStore->getLocation())->whereAdd(WarehouseStore::TYPE, WarehouseStore::$Type["ppv"])->find()->toCombo($this->i18n->_("Select a Warehouse Store"));
         $this->view->status = array("" => $this->i18n->_("Select a Status"), PurchaseOrder::$Status["New"] => PurchaseOrder::$StatusNames[PurchaseOrder::$Status["New"]], PurchaseOrder::$Status["Ready"] => PurchaseOrder::$StatusNames[PurchaseOrder::$Status["Ready"]]);
         $this->view->uploadBLHouseStatus = PurchaseOrder::$Status["Ready"];
         $this->view->purchaseOrderCommercialInvoice = PurchaseOrderCommercialInvoiceQuery::create()->whereAdd(PurchaseOrderCommercialInvoice::ID_PURCHASE_ORDER, $purchaseOrder->getIdPurchaseOrder())->findOneOrElse(new PurchaseOrderCommercialInvoice());
         $purchaseOrderPaymentsManager = new PurchaseOrderPaymentsManager();
         $this->view->payments = Zend_Json::encode($purchaseOrderPaymentsManager->getCondensedPayments($purchaseOrder));
     } catch (Exception $e) {
         $this->setFlash('error', $e->getMessage());
         $this->_redirect('purchase-order/list');
     }
 }
 /**
  *
  * @return array
  */
 public function editAction()
 {
     try {
         $id = $this->getRequest()->getParam('id');
         $this->view->proformaInvoice = $proformaInvoice = ProformaInvoiceQuery::create()->findByPKOrThrow($id, $this->i18n->_("ProformaInvoice with id {$id} not found"));
         $accessRole = $this->getUser()->getAccessRole();
         $accessRoleManager = new AccessRoleManager();
         $suppliers = $accessRoleManager->getAssociateSuppliers($accessRole);
         if (!$suppliers->containsIndex($proformaInvoice->getIdSupplier())) {
             throw new ProformaInvoiceException($this->i18n->_("You don't have permission to edit this Proforma Invoice."));
         }
         $this->view->proformaInvoiceEntries = $proformaInvoiceEntries = ProformaInvoiceEntryQuery::create()->whereAdd(ProformaInvoiceEntry::ID_PROFORMA_INVOICE, $proformaInvoice->getIdProformaInvoice())->find();
         $this->view->locations = WarehouseQuery::create()->find()->toCombo($this->i18n->_("Select Warehouse Location"));
         if (!$proformaInvoiceEntries->isEmpty()) {
             $this->view->warehouseStore = $warehouseStore = WarehouseStoreQuery::create()->findByPKOrThrow($proformaInvoiceEntries->current()->getIdWarehouseStore(), $this->i18n->_("WarehouseStore with id {$proformaInvoiceEntries->current()->getIdWarehouseStore()} not found"));
             $this->view->warehouseStores = WarehouseStoreQuery::create()->whereAdd(WarehouseStore::LOCATION, $warehouseStore->getLocation())->find()->toCombo($this->i18n->_("Select Warehouse Store"));
             $this->view->products = ProductQuery::create()->whereAdd(Product::ITEM_CODE, $proformaInvoiceEntries->getIdProducts(), ProductQuery::IN)->find();
         } else {
             $this->view->warehouseStore = new Warehouse();
             $this->view->warehouseStores = array("" => $this->i18n->_("Select Warehouse Store"));
         }
         $this->view->forwarders = array("" => $this->i18n->_("Select Forwarder")) + ForwarderQuery::create()->find()->toCombo();
         if ($proformaInvoice->getIdCourtyard() > 0) {
             $this->view->courtyard = $courtyard = CourtyardQuery::create()->findByPKOrThrow($proformaInvoice->getIdCourtyard(), $this->i18n->_("Courtyard with id {$proformaInvoice->getIdCourtyard()} not found"));
             $this->view->portsCustom = array("" => $this->i18n->_("Select Port Custom")) + PortCustomQuery::create()->innerJoinForwarder()->whereAdd("Forwarder." . Forwarder::ID_FORWARDER, $courtyard->getIdForwarder())->find()->toCombo();
             $this->view->courtyards = array("" => $this->i18n->_("Select Courtyard")) + CourtyardQuery::create()->whereAdd(Courtyard::ID_PORT_CUSTOM, $courtyard->getIdPortCustom())->whereAdd(Courtyard::ID_FORWARDER, $courtyard->getIdForwarder())->find()->toCombo();
         } else {
             $this->view->courtyard = new Courtyard();
             $this->view->portCustoms = array("" => $this->i18n->_("Select Port Custom"));
             $this->view->courtyards = array("" => $this->i18n->_("Select Courtyard"));
         }
         $this->view->currencies = CurrencyQuery::create()->find();
         $this->view->events = EventQuery::create()->find();
         $paymentTerms = ProformaInvoicePaymentTermQuery::create()->whereAdd(ProformaInvoicePaymentTerm::ID_PROFORMA_INVOICE, $proformaInvoice->getIdProformaInvoice())->find();
         $proformaInvoiceProgrammedPayment = ProformaInvoiceProgrammedPaymentQuery::create()->whereAdd(ProformaInvoiceProgrammedPayment::ID_PROFORMA_INVOICE, $proformaInvoice->getIdProformaInvoice())->find();
         $purchaseOrderProgrammedPayment = PurchaseOrderProgrammedPaymentQuery::create()->whereAdd(PurchaseOrderProgrammedPayment::ID_PROFORMA_INVOICE_PAYMENT_TERM, $paymentTerms->getPrimaryKeys());
         $this->view->proformaInvoiceProgrammedPayment = $proformaInvoiceProgrammedPayment;
         $this->view->purchaseOrderProgrammedPayment = $purchaseOrderProgrammedPayment;
         $this->view->paymentTerms = $paymentTerms;
         $this->view->contentTitle = $this->i18n->_("Edit Proforma Invoice DocNum ") . $proformaInvoice->getSapDocumentNumber();
         $this->view->setTpl("Edit");
     } catch (Exception $e) {
         $this->setFlash('error', $this->i18n->_($e->getMessage()));
         $this->_redirect('proforma-invoice/list');
     }
 }
 /**
  * This action display the view to china agents
  *
  * @author Erick Guevara Martínez
  */
 public function entriesAction()
 {
     // Get criteria to filter requisition entries
     if ($this->getRequest()->isPost()) {
         $post[RequisitionEntry::ID_REQUISITION] = $this->getRequest()->getParam(RequisitionEntry::ID_REQUISITION);
         $post[RequisitionEntry::STATUS] = $this->getRequest()->getParam(RequisitionEntry::STATUS);
         $post["id_supplier"] = $this->getRequest()->getParam("id_supplier", "");
         $post["id_destination_country"] = $this->getRequest()->getParam("id_destination_country", "");
         $post["startDate"] = $this->getRequest()->getParam("startDate", "");
         $post["endDate"] = $this->getRequest()->getParam("endDate", "");
         $post["key_mother"] = $this->getRequest()->getParam("key_mother", "");
         $post["order"] = $this->getRequest()->getParam("order", "");
     }
     $accessRole = $this->getUser()->getAccessRole();
     $accessRoleManager = new AccessRoleManager();
     $suppliers = $accessRoleManager->getAssociateSuppliers($accessRole);
     $products = ProductQuery::create()->whereAdd(Product::ID_SUPPLIER, $suppliers->getPrimaryKeys())->find();
     // Creates an array with the status can be displayed in this view
     $allowedStatus = array("Pending Price" => RequisitionEntry::$Status["Pending Price"], "Pending Price Auth" => RequisitionEntry::$Status["Pending Price Auth"], "PI Requested" => RequisitionEntry::$Status["PI Requested"]);
     // If don't have a status filter then search by allowed status
     $requisitionEntriesQuery = RequisitionEntryQuery::create()->filter($post)->whereAdd(RequisitionEntry::ID_PRODUCT, $products->getPrimaryKeys());
     if ($post[RequisitionEntry::STATUS] == "") {
         $requisitionEntriesQuery->whereAdd("RequisitionEntry." . RequisitionEntry::STATUS, $allowedStatus, BaseQuery::IN);
     }
     // Filter all requisition entries belonging to a requisition with the same
     if ($post["id_destination_country"] != "") {
         $requisitionEntriesQuery->innerJoinRequisition()->whereAdd("Requisition." . Requisition::ID_DESTINATION_COUNTRY, $post["id_destination_country"]);
     }
     // Filter all requisition entries with a supplier default or a bentchmarcking that equal to id_supplier filter param
     if ($post["id_supplier"] != "") {
         $requisitionEntriesQuery->innerJoinKeyMotherSupplierBudget()->whereAdd("KeyMotherSupplierBudget." . KeyMotherSupplierBudget::ID_SUPPLIER, $post["id_supplier"]);
     }
     // Filter all requisition entries with a supplier default or a bentchmarcking that equal to id_supplier filter param
     if ($post["key_mother"] != "") {
         $requisitionEntriesQuery->whereAdd("RequisitionEntry." . RequisitionEntry::ID_PRODUCT, $post["key_mother"], RequisitionEntryQuery::LIKE);
     }
     if ($post["order"] == "date_asc" || $post["order"] == "date_desc") {
         $requisitionEntriesQuery->addAscendingOrderBy("RequisitionEntry." . RequisitionEntry::CREATION_DATE);
     } else {
         $requisitionEntriesQuery->addAscendingOrderBy("RequisitionEntry." . RequisitionEntry::ID_PRODUCT);
     }
     $requisitionEntries = $requisitionEntriesQuery->find();
     // If have more than 1 requisition entry then get extra info to requisition
     $parentKeys = array();
     $requisitions = new RequisitionCollection();
     $budgets = new KeyMotherSupplierBudgetCollection();
     if ($requisitionEntries->count() > 0) {
         $products = $products->filterByPks($requisitionEntries->getDistinctProducts())->orderByArrayPks($requisitionEntries->getDistinctProducts());
         $parentKeys = $products->getKeyMother();
         $requisitions = RequisitionQuery::create()->whereAdd(Requisition::ID_REQUISITION, $requisitionEntries->getDistinctRequisitions(), RequisitionQuery::IN)->find();
         if (count($parentKeys) > 0) {
             $budgets = KeyMotherSupplierBudgetQuery::create()->whereAdd(KeyMotherSupplierBudget::KEY_MOTHER, $parentKeys, KeyMotherSupplierBudgetQuery::IN)->actives()->find();
         }
     }
     // Proccess and group all requisition entries by parent key
     $requisitionEntriesGroupByParentKey = array();
     foreach ($parentKeys as $parentKey) {
         // Get all products belonging to current parent key
         $parentKeyProducts = $products->filterByKeyMother($parentKey);
         // Get all requisition entries belonging to products of a current parent key
         $parentKeyRequisitionEntries = $requisitionEntries->filterByIdProduct($parentKeyProducts->getPrimaryKeys());
         // Set Headers to group
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["parentKey"] = $parentKey;
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["description"] = $parentKeyProducts->current()->getItemName();
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["idDefaultProduct"] = $parentKeyProducts->current()->getItemCode();
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["firstRequisitionDate"] = $parentKeyRequisitionEntries->getFirstCreationDate();
         // Set a current supplier default name, in case of this don't have suppliers then set "-"
         if ($parentKeyRequisitionEntries->getRecurrentSupplierDefault() == null) {
             $requisitionEntriesGroupByParentKey[$parentKey]["header"]["supplierSapBussinessCode"] = "-";
         } else {
             $supplier = $suppliers->getByPK($parentKeyRequisitionEntries->getRecurrentSupplierDefault());
             if (!$supplier) {
                 $supplier = new SapSupplier();
             }
             $requisitionEntriesGroupByParentKey[$parentKey]["header"]["supplierSapBussinessCode"] = $supplier ? $supplier->getCardCode() : 'Error';
             $requisitionEntriesGroupByParentKey[$parentKey]["header"]["supplierName"] = $supplier->getName();
         }
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["totalQuantity"] = $parentKeyRequisitionEntries->getTotalQuantity();
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["targetPrice"] = $parentKeyProducts->current()->getCost();
         // Check if the min open price is less than target price, then set the lower of two
         if ($parentKeyProducts->current()->getCost() > 0) {
             $minPrice = $parentKeyProducts->current()->getCost() < $parentKeyRequisitionEntries->getMinOpenPrice() ? $parentKeyProducts->current()->getCost() : $parentKeyRequisitionEntries->getMinOpenPrice();
         } else {
             $minPrice = $parentKeyRequisitionEntries->getMinOpenPrice();
         }
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["minOpenPrice"] = $minPrice;
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["MOPTotalImport"] = $parentKeyRequisitionEntries->getTotalQuantity() * $minPrice;
         // Check if the parent key have budgets then set true or if it don't have budgets then set false
         $parentKeyBudgets = $budgets->filterByKeyMother($parentKey);
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["hasBudgets"] = $parentKeyBudgets->count() > 0 ? true : false;
         // Check if a key mother budget is autorized (prevent to no save more budgets when one key mother budget is autoprized)
         $requisitionEntriesGroupByParentKey[$parentKey]["header"]["hasAutorizedBudget"] = $parentKeyBudgets->checkAutorized();
         // Set all requisition entries of the parent key
         $requisitionEntriesGroupByParentKey[$parentKey]["requisitionEntries"] = $parentKeyRequisitionEntries;
         $requisitionEntriesGroupByParentKey[$parentKey]["autorizedBudget"] = $parentKeyBudgets->getAutorizedOrElse(new KeyMotherSupplierBudget());
     }
     if ($post["order"] == "date_desc") {
         $requisitionEntriesGroupByParentKey = array_reverse($requisitionEntriesGroupByParentKey);
     }
     // Assign all information to view
     $this->view->requisitions = $requisitions;
     $this->view->contentTitle = $this->i18n->_("Open Requisition by Item");
     $this->view->emptySupplier = new SapSupplier();
     $this->view->requisitionEntriesGroupByParentKey = $requisitionEntriesGroupByParentKey;
     $this->view->products = $products;
     $this->view->suppliers = $suppliers;
     $this->view->incoterms = array("" => $this->i18n->_("Select a Incoterm")) + IncotermQuery::create()->find()->toCombo();
     $this->view->currencies = $currencies = CurrencyQuery::create()->find();
     $this->view->currenciesToCombo = array("" => $this->i18n->_("Select a Currency")) + $currencies->toCombo();
     $this->view->status = array("" => $this->i18n->_("All")) + array_flip($allowedStatus);
     $this->view->allowedStatus = $allowedStatus;
     $this->view->countries = array("" => $this->i18n->_("All")) + CountryQuery::create()->find()->toCombo();
     $this->view->forwarders = array("" => $this->i18n->_("Select a Forwarder")) + ForwarderQuery::create()->actives()->find()->toCombo();
     $this->view->special = Requisition::$Type['Quick'];
     $this->view->portsCustom = array("" => $this->i18n->_("Select a Port Custom"));
     $this->view->courtyards = array("" => $this->i18n->_("Select a Courtyard"));
     $this->view->order = array("" => $this->i18n->_("Select a Order"), "date_asc" => $this->i18n->_("By First Date"), "date_desc" => $this->i18n->_("By Last Date"), "product" => $this->i18n->_("By Product"));
     $this->view->setTpl("Entries");
 }