private void btnDeleteRequisition_Click(object sender, EventArgs e)
        {
            DataRow dr = gridRequisitionListView.GetFocusedDataRow();
            if (dr != null)
            {
                int orderID = Convert.ToInt32(dr["ID"]);
                Order ord = new Order();
                ord.LoadByPrimaryKey(orderID);
                if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
                {
                    if (XtraMessageBox.Show("Are you sure you would like to cancel this requisition?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {

                        if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
                        {
                            ord.ChangeStatus(OrderStatus.Constant.CANCELED,CurrentContext.UserId);
                            LoadRequisitions();
                            XtraMessageBox.Show("Your requisisition has been canceled.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {

                        }
                        LoadRequisitions();
                    }
                }
                else
                {
                    XtraMessageBox.Show("This requisition has already been submitted, you cannot resubmit/cancel it.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var dvPickListMakeup = (DataTable)gridTransactions.DataSource;

            var ord = new BLL.Order();

            ord.LoadByPrimaryKey(OrderID);

            var rus = new Institution();

            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (BLL.Settings.IsCenter)
            {
                dvPickListMakeup.Columns["PhysicalStoreTypeName"].ColumnName = "WarehouseName";
                dvPickListMakeup.Columns["SKUTOPICK"].ColumnName             = "QtyInSKU";
                dvPickListMakeup.Columns["StoreGroupName"].ColumnName        = "AccountName";
                dvPickListMakeup.Columns.Add("ActivityConcat");

                foreach (DataRow r in dvPickListMakeup.Rows)
                {
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(Convert.ToInt32(r["StoreID"]));
                    r["ActivityConcat"] = activity.FullActivityName;
                }
            }
            var pl = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(ord, rus.Name, dvPickListMakeup.DefaultView);


            pl.ShowPreviewDialog();
            // refresh the display
            lstRefNo_FocusedNodeChanged(null, null);
        }
Exemplo n.º 3
0
        private static void ConfirmBranchApprovedOrder(int hcmisOrderID)
        {
            var tsvc       = new ServiceOrderClient();
            var issuedList = new Collection <Issuance>();

            BLL.Order order = new Order();
            order.LoadByPrimaryKey(hcmisOrderID);

            var collOrders = new Collection <int>();

            while (!order.EOF)
            {
                collOrders.Add(order.HCTSReferenceID);
                order.MoveNext();
            }

            try
            {
                tsvc.ConfirmBranchApprovedOrders(collOrders, PlitsUserName, PlitsPassword);
            }
            catch (Exception e)
            {
                throw e.InnerException;
            }
        }
        private void btnDeleteRequisition_Click(object sender, EventArgs e)
        {
            DataRow dr = gridRequisitionListView.GetFocusedDataRow();

            if (dr != null)
            {
                int   orderID = Convert.ToInt32(dr["ID"]);
                Order ord     = new Order();
                ord.LoadByPrimaryKey(orderID);
                if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
                {
                    if (XtraMessageBox.Show("Are you sure you would like to cancel this requisition?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
                        {
                            ord.ChangeStatus(OrderStatus.Constant.CANCELED, CurrentContext.UserId);
                            LoadRequisitions();
                            XtraMessageBox.Show("Your requisisition has been canceled.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                        }
                        LoadRequisitions();
                    }
                }
                else
                {
                    XtraMessageBox.Show("This requisition has already been submitted, you cannot resubmit/cancel it.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// This happes when there is plenty of transaction at the same time
        /// and will result a partial commit.
        /// This fake rows should be deleted from DB.
        /// </summary>
        /// <param name="orderID"></param>
        private void RemoveFakePartialCommitPickListDetails(int orderID)
        {
            var order = new Order();

            order.LoadByPrimaryKey(orderID);
            if (order.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
            {
                var pickList = new PickList();
                pickList.LoadByOrderID(order.ID);
                if (pickList.RowCount == 0) //~ If there is no picklist, there is nothing to delete. ~//
                {
                    return;
                }

                var picklistDetail = new PickListDetail();
                picklistDetail.LoadByPickListID(pickList.ID);
                picklistDetail.Rewind();
                while (!picklistDetail.EOF)
                {
                    PickListDetailDeleted.AddNewLog(picklistDetail, CurrentContext.UserId);
                    picklistDetail.MarkAsDeleted();
                    picklistDetail.MoveNext();
                }

                picklistDetail.Save();
                pickList.MarkAsDeleted();
                pickList.Save();
            }
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var dvPickListMakeup = (DataTable)gridTransactions.DataSource;

            var ord = new BLL.Order();
            ord.LoadByPrimaryKey(OrderID);

            var rus = new Institution();
            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (BLL.Settings.IsCenter)
            {
                dvPickListMakeup.Columns["PhysicalStoreTypeName"].ColumnName = "WarehouseName";
                dvPickListMakeup.Columns["SKUTOPICK"].ColumnName = "QtyInSKU";
                dvPickListMakeup.Columns["StoreGroupName"].ColumnName = "AccountName";
                dvPickListMakeup.Columns.Add("ActivityConcat");

                foreach (DataRow r in dvPickListMakeup.Rows)
                {
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(Convert.ToInt32(r["StoreID"]));
                    r["ActivityConcat"] = activity.FullActivityName;
                }
            }
            var pl = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(ord, rus.Name, dvPickListMakeup.DefaultView);

            pl.ShowPreviewDialog();
            // refresh the display
            lstRefNo_FocusedNodeChanged(null, null);
        }
        public Domain.Request FindSingle(int requestID)
        {
            var request = new Domain.Request();
            var order = new Order();
            order.LoadByPrimaryKey(requestID);

            request.RequestID = order.ID;
            request.OrderNumber = order.RefNo;
            request.LetterNumber = !order.IsColumnNull("LetterNo") ? order.LetterNo : "";
            request.RequestedDate = order.EurDate;

            request.Client = _clientRepository.FindSingle(order.RequestedBy);
            request.Mode = _modeService.GetEnum(order.FromStore);
            request.PaymentTerm = _paymentTermService.FindSingle(order.PaymentTypeID);
            request.OrderStatus = _orderStatusService.GetEnum(order.OrderStatusID);

            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(requestID);
            orderDetail.Rewind();
            request.RequestDetails = new Collection<Domain.RequestDetail>();
            while (!orderDetail.EOF)
            {
                var item = _itemRepository.FindSingle(orderDetail.ItemID);
                var unitOfIssue = _unitOfIssueRepository.FindSingle(orderDetail.UnitID);
                var requestDetail = new Domain.RequestDetail()
                                        {

                                            RequestDetailId = orderDetail.ID,
                                            Item = item,
                                            Unit = unitOfIssue,
                                            RequestedQuantity = orderDetail.Pack,
                                            ApprovedQuantity = !orderDetail.IsColumnNull("ApprovedQuantity") ? orderDetail.ApprovedQuantity : orderDetail.Pack,
                                            IsFirstLoad = orderDetail.IsColumnNull("ApprovedQuantity"),
                                            ActivityGroup = orderDetail.IsColumnNull(OrderDetail.ColumnNames.StoreID)?null:_activityRepository.FindSingle(orderDetail.StoreID,orderDetail.DeliveryNote),
                                            ExpiryDate =
                                                !orderDetail.IsColumnNull("PreferredExpiryDate")
                                                    ? orderDetail.PreferredExpiryDate
                                                    : (DateTime?)null,
                                            Manufacturer =
                                                !orderDetail.IsColumnNull("PreferredManufacturerID")
                                                    ? _manufacturerRepository.FindSingle(
                                                        orderDetail.PreferredManufacturerID)
                                                    : null,
                                            physicalStore =
                                                !orderDetail.IsColumnNull("PreferredPhysicalStoreID")
                                                    ? _physicalStoreRepository.FindSingle(
                                                        orderDetail.PreferredPhysicalStoreID)
                                                    : null

                                        };
                request.RequestDetails.Add(requestDetail);
            orderDetail.MoveNext();
            }

            return request;
        }
Exemplo n.º 8
0
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());

            Order ord = new Order();

            ord.LoadByPrimaryKey(_orderID);
            if (ord.RowCount == 0)
            {
                XtraMessageBox.Show("You have to select an Order to return to approval, ", "Error - Select Order");
                return;
            }
            if (!ord.IsColumnNull("OrderTypeID") && ord.OrderTypeID != OrderType.CONSTANTS.STANDARD_ORDER)
            {
                XtraMessageBox.Show("You cannot return this order to approval, you can either cancel or confirm this order", "Error - You cannot return this order");
                return;
            }

            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();

                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED, CurrentContext.UserId);
                    BindApprovedOrders();
                }
                else if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
                {
                    ord.ReleaseReservation();
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED, CurrentContext.UserId);
                    BindApprovedOrders();
                }
                transaction.CommitTransaction();
            }
            catch (Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;
            //HCMISLoader.MarkAsDirtyUsingOrderID(_orderID, NewMainWindow.UserId, true);
            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 /// <summary>
 /// Handles the Click event of the btnReturnToApprovalStep control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
 private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
 {
     if (XtraMessageBox.Show("Are you sure you would like to return this order to the picklist?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
     {
         BLL.Order order = new Order();
         order.LoadByPrimaryKey(_orderID);
         order.ReturnBacktoPicklistConfirmation();
         BindOutstandingPicklists();
         gridOutstandingPicklistDetail.DataSource = null;
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Undo pick list that has been printed
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        public void CancelOrderWithPickList(int orderID)
        {
            // Create a pick list entry
            Order          ord            = new Order();
            PickList       pl             = new PickList();
            PickListDetail pld            = new PickListDetail();
            ReceivePallet  rp             = new ReceivePallet();
            ReceiveDoc     rd             = new ReceiveDoc();
            PickFace       pf             = new PickFace();
            PalletLocation palletLocation = new PalletLocation();


            ord.LoadByPrimaryKey(orderID);
            pl.LoadByOrderID(orderID);

            pld.LoadByPickListID(pl.ID);

            while (!pld.EOF)
            {
                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                rp.ReservedStock -= Convert.ToInt32(pld.QuantityInBU);
                if (rp.ReservedStock < 0)
                {
                    rp.ReservedStock = 0; //If there has been no reservation, allow to cancel the picklist too.  No need for it to be blocked by the constraint.
                }
                rp.Save();
                palletLocation.LoadByPrimaryKey(pld.PalletLocationID);
                if (palletLocation.StorageTypeID.ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(pld.PalletLocationID);
                    pf.Balance += Convert.ToInt32(pld.QuantityInBU);
                    pf.Save();
                }

                //Delete from picklistDetail and add to pickListDetailDeleted
                PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                pld.MarkAsDeleted();
                pld.MoveNext();
            }
            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.CANCELED, CurrentContext.UserId);

            pl.MarkAsDeleted();
            pl.Save();
        }
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();
                Order ord = new Order();
                ord.LoadByPrimaryKey(_orderID);
                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.OrderStatusID = OrderStatus.Constant.ORDER_FILLED;
                    ord.Save();
                    BindApprovedOrders();
                }
                else if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
                {
                    ord.ReleaseReservation();
                    ord.OrderStatusID = OrderStatus.Constant.ORDER_FILLED;
                    ord.Save();
                    BindApprovedOrders();
                }
                transaction.CommitTransaction();
            }
            catch (Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;
            //HCMISLoader.MarkAsDirtyUsingOrderID(_orderID, NewMainWindow.UserId, true);
            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Marks as dispatched.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <param name="prePrintedSTV">The pre printed STV.</param>
        /// <returns></returns>
        public bool MarkAsDispatched(int userID, int?prePrintedSTV)
        {
            if (!this.IsColumnNull("VoidRequest"))
            {
                if ((this.VoidRequest && this.IsColumnNull("VoidApprovedByUserID"))) //If the approver hasn't acted on the void request.
                {
                    return(false);
                }
            }
            //Mark the NoOfPackIssued equal to the NoOfPack.  Discrepancies are supposed to be saved after this function has finished running.
            var query = HCMIS.Repository.Queries.Issue.UpdateMarkAsDispatched(userID, this.ID);

            var queryConfirmIssue = HCMIS.Repository.Queries.Issue.UpdateMarkAsDispatched(this.ID);

            if (prePrintedSTV.HasValue)
            {
                this.PrePrintedInvoiceNo = prePrintedSTV.Value;
                this.Save();
            }

            BLL.Issue s = new Issue();
            s.LoadFromRawSql(query);
            s.LoadFromRawSql(queryConfirmIssue);

            BLL.IssueDoc isDoc = new IssueDoc();
            isDoc.Where.STVID.Value = this.ID;
            isDoc.Query.Load();
            if (isDoc.RowCount > 0)
            {
                int       orderID = isDoc.OrderID;
                BLL.Order ord     = new Order();
                ord.LoadByPrimaryKey(orderID);
                if (ord.RowCount > 0)
                {
                    ord.ChangeStatus(OrderStatus.Constant.DISPATCH_CONFIRMED, CurrentContext.UserId);
                    ord.Save();
                }
            }

            return(true);
        }
        private void btnSubmitWishlist_Click(object sender, EventArgs e)
        {
            DataRow dr = gridRequisitionListView.GetFocusedDataRow();

            if (dr != null)
            {
                int   orderID = Convert.ToInt32(dr["ID"]);
                Order ord     = new Order();
                ord.LoadByPrimaryKey(orderID);
                if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
                {
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED, CurrentContext.UserId);
                    LoadRequisitions();
                    XtraMessageBox.Show("Your requisisition has been submitted.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    XtraMessageBox.Show("This requisition has already been submitted, you cannot resubmit it.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Exemplo n.º 14
0
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();
                Order ord = new Order();
                ord.LoadByPrimaryKey(_orderID);
                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED, CurrentContext.UserId);;
                    BindApprovedOrders();
                }

                transaction.CommitTransaction();

                this.LogActivity("Return-Pick-List-To-Approval", ord.ID);
            }
            catch (Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;

            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 15
0
        private void SavePickListItems(object sender, EventArgs e)
        {
            var ord = new Order();
            var rus = new Institution();

            ord.LoadByPrimaryKey(_orderID);
            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (_dvPickListMakeup == null || ValidatePickList())
            {
                return;
            }

            // First of all .. print the pick list
            var pls = new PickList();

            PrintPickList(ord, rus);

            MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            try
            {
                mgr.BeginTransaction();
                pls.SavePickList(_orderID, _dvPickListMakeup, CurrentContext.UserId);
                mgr.CommitTransaction();

                BindApprovedOrders();
                this.LogActivity("Print-Pick-List", ord.ID);
                XtraMessageBox.Show("Your pick list has been saved! please continue to the next step or prepare another Picklist here.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exp)
            {
                mgr.RollbackTransaction();
                ViewHelper.ShowErrorMessage("System couldn't save the Pick List, Please contact administrator for additional help", exp);
                ErrorHandler.Handle(exp);
            }
        }
        private Order GenerateOrder()
        {
            var or = new Order();
            if (OrderID == null)
                or.AddNew();
            else
                or.LoadByPrimaryKey(OrderID.Value);

            or.RefNo = Order.GetNextOrderReference();
            txtRefNo.Text = or.RefNo;

            var oldOrderStatus = or.IsColumnNull("OrderStatusID") ? (int?)null : or.OrderStatusID;
            or.OrderStatusID = OrderStatus.Constant.PICK_LIST_GENERATED;
            //or.Remark = txtRemark.Text;

            or.EurDate = or.Date = DateTimeHelper.ServerDateTime; //Both fields are assigned dates.
            if (TransferTypeID == 1)
                or.RequestedBy = Convert.ToInt32(lkForHub.EditValue);

            or.FilledBy = CurrentContext.UserId;

            or.ContactPerson = txtContactPerson.Text;
            var activity = new Activity();
            activity.LoadByPrimaryKey(Convert.ToInt32(lkAccountType.EditValue));

            or.FromStore = activity.ModeID;

            if (BLL.Settings.IsCenter)
            {
                //What the Hell is this?
                or.PaymentTypeID = PaymentType.Constants.STV;
            }
            else
            {
                or.PaymentTypeID = PaymentType.Constants.STV;
            }
            or.FiscalYearID = FiscalYear.Current.ID;
            or.Save();
            or.LogRequisitionStatus(or.ID, oldOrderStatus, OrderStatus.Constant.PICK_LIST_GENERATED,CurrentContext.UserId);
            return or;
        }
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());
            MyGeneration.dOOdads.TransactionMgr transaction =  MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();
                Order ord = new Order();
                ord.LoadByPrimaryKey(_orderID);
                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.OrderStatusID = OrderStatus.Constant.ORDER_FILLED;
                    ord.Save();
                    BindApprovedOrders();
                }
                else if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
                {
                    ord.ReleaseReservation();
                    ord.OrderStatusID = OrderStatus.Constant.ORDER_FILLED;
                    ord.Save();
                    BindApprovedOrders();
                }
                transaction.CommitTransaction();
            }
            catch(Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;
            //HCMISLoader.MarkAsDirtyUsingOrderID(_orderID, NewMainWindow.UserId, true);
            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        public void EditRequisition(int orderID)
        {
            OrderID = orderID;
            Order ord = new Order();
            ord.LoadByPrimaryKey(orderID);
            txtRefNo.Text = ord.RefNo;
            txtLetterNumber.Text = ord.LetterNo;
            labelControl4.Text = ord.RefNo;
            Institution ru = new Institution();
            ru.LoadByPrimaryKey(ord.RequestedBy);

            if (!ru.IsColumnNull("Zone"))
            {
                // Just because the region Property on the Receiving Unit is not working as desired.
                Zone zone = new Zone();
                zone.LoadByPrimaryKey(ru.Zone);

                lkRegion.EditValue = zone.RegionId;
                lkZone.EditValue = ru.Zone;
            }
            lkForFacility.EditValue = ru.ID;

            lkModes.EditValue = ord.FromStore;
            lkModes_EditValueChanged(null, null);

            lkPaymentType.EditValue = ord.PaymentTypeID;
            txtContactPerson.EditValue = ord.ContactPerson;

            BLL.OrderDetail or = new BLL.OrderDetail();
            or.LoadAllByOrderID(orderID);

            DataView selectables = (DataView)gridItemChoiceView.DataSource;

            if (_dtSelectedTable != null)
            {
                _dtSelectedTable.Clear();
            }
            else
            {
                PopulateItemsList();
            }

            while (!or.EOF)
            {
                // select the items and put it in the dtselected table.
                if (selectables != null)
                {
                    DataRow[] dataRows = selectables.Table.Select(String.Format("ID = {0} and UnitID = {1}", or.ItemID, or.UnitID));
                    if (dataRows.Length > 0)
                    {
                        _dtSelectedTable.ImportRow(dataRows[0]);
                        dataRows[0]["IsSelected"] = true;
                    }
                }
                or.MoveNext();
            }

            _dvOrderTable = or.DefaultView;
            orderGrid.DataSource = _dvOrderTable;
            EnableDisableButtons();
        }
        /// <summary>
        /// The code supports manufacturer preference here too but we choose not to prefer manufacturers when looking into the stores.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="orderDetailID"></param>
        /// <param name="pricedUnpricedBoth"></param>
        /// <param name="bal"> </param>
        /// <param name="markStockoutBit"> </param>
        /// <param name="usableStock"> </param>
        /// <param name="approved"> </param>
        public decimal LoadOptionsForOrderDetail(int userID, int orderDetailID, PriceSettings pricedUnpricedBoth, Balance bal, bool markStockoutBit, out decimal usableStock, out decimal approved)
        {
            decimal avQuantity = 0;

            BLL.OrderDetail orderDetail = new OrderDetail();
            orderDetail.LoadByPrimaryKey(orderDetailID);
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderDetail.OrderID);

            Institution ru = new Institution();

            ru.LoadByPrimaryKey(order.RequestedBy);

            int month = EthiopianDate.EthiopianDate.Now.Month;
            int year  = EthiopianDate.EthiopianDate.Now.Year;

            decimal availableQty = 0;

            usableStock = 0;
            approved    = 0;
            int?manufacturerPrefrence = null, unitID = null;

            if (!orderDetail.IsColumnNull("PreferredManufacturerID"))
            {
                manufacturerPrefrence = orderDetail.PreferredManufacturerID;
            }

            DateTime?expPreferrence = null;

            if (!orderDetail.IsColumnNull("PreferredExpiryDate"))
            {
                expPreferrence = orderDetail.PreferredExpiryDate;
            }

            int?preferredPhysicalStoreID = null;

            if (!orderDetail.IsColumnNull("PreferredPhysicalStoreID"))
            {
                preferredPhysicalStoreID = orderDetail.PreferredPhysicalStoreID;
            }

            //--------------------------------------------------------------------------
            //manufacturerPrefrence = null; //We are overriding the manufacturer preference.
            //expPreferrence = null;
            //--------------------------------------------------------------------------
            if (!orderDetail.IsColumnNull("UnitID"))
            {
                unitID = orderDetail.UnitID;
            }

            BLL.UserActivity userStore = new UserActivity();

            // Definitely a danger zone
            userStore.LoadByUserIDAndStoreType(userID, order.FromStore, orderDetail.ItemID, unitID.Value);


            while (!userStore.EOF)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(userStore.ActivityID);

                if (order.FromStore == Mode.Constants.RDF && !BLL.Settings.IsCenter && !BLL.Settings.PrivateCanGetFromMDGAndPBS && ru.Ownership == OwnershipType.Constants.Private && activity.IsSubsidized)
                {
                    userStore.MoveNext();
                    continue;
                }



                // Load the Activity Selection that has PRiced Commodities.
                Balance balance = new Balance();
                if (pricedUnpricedBoth == PriceSettings.PRICED_ONLY || pricedUnpricedBoth == PriceSettings.BOTH)
                {
                    BLL.Order.MakeStockCalculations(userID, month, year, PriceSettings.PRICED_ONLY, orderDetail,
                                                    userStore.ActivityID, orderDetail.ItemID, order, balance, unitID,
                                                    manufacturerPrefrence, expPreferrence, preferredPhysicalStoreID, out usableStock, out approved,
                                                    out availableQty, markStockoutBit);
                    avQuantity += availableQty;

                    if (availableQty > 0)
                    {
                        this.AddNew();
                        this.ID   = userStore.ActivityID;
                        this.Name = string.Format("{0} ({1})", activity.FullActivityName, availableQty.ToString("#,##0"));
                        PrepareColumnsForApproval();
                        this.SetColumn("AvailableSKU", availableQty);
                        this.SetColumn("IsDeliveryNote", false);
                        this.SetColumn("TextID", string.Format("N{0}", this.ID));
                    }
                }



                // Load Activity Selections for Delivery Note Items.
                if (pricedUnpricedBoth == PriceSettings.DELIVERY_NOTE_ONLY || pricedUnpricedBoth == PriceSettings.BOTH)
                {
                    BLL.Order.MakeStockCalculations(userID, month, year, PriceSettings.DELIVERY_NOTE_ONLY, orderDetail,
                                                    userStore.ActivityID, orderDetail.ItemID, order, balance, unitID,
                                                    manufacturerPrefrence, expPreferrence, preferredPhysicalStoreID, out usableStock, out approved,
                                                    out availableQty, markStockoutBit);

                    avQuantity += availableQty;

                    if (availableQty > 0)
                    {
                        this.AddNew();
                        this.ID   = userStore.ActivityID; //Just to give it a different ID so we know there is a change only.
                        this.Name = string.Format("+-- {0} - Delivery Notes - ({1})", userStore.GetColumn("ActivityName"),
                                                  availableQty.ToString("#,##0"));
                        PrepareColumnsForApproval();
                        this.SetColumn("AvailableSKU", availableQty);
                        this.SetColumn("IsDeliveryNote", true);
                        this.SetColumn("TextID", string.Format("D{0}", this.ID));
                    }
                }
                userStore.MoveNext();
            }
            return(avQuantity);
        }
        private static void ConfirmFacilityApprovdOrder(int hcmisOrderID)
        {
            var tsvc = new ServiceOrderClient();
            var issuedList = new Collection<Issuance>();

            BLL.Order order = new Order();
            order.LoadByPrimaryKey(hcmisOrderID);

            var collOrders = new Collection<int>();
            while (!order.EOF)
            {
                collOrders.Add(order.HCTSReferenceID);
                order.MoveNext();
            }
            try
            {
                tsvc.ConfirmFacilityApprovedOrders(GetBranchID(), collOrders, PlitsUserName, PlitsPassword);
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        private void SavePickListItems(object sender, EventArgs e)
        {
            var ord = new Order();
            var rus = new Institution();
            ord.LoadByPrimaryKey(_orderID);
            rus.LoadByPrimaryKey(ord.RequestedBy);

            if (_dvPickListMakeup == null || ValidatePickList())
            {
              return;
            }

            // First of all .. print the pick list
                var pls = new PickList();
                PrintPickList(ord, rus);

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    mgr.BeginTransaction();
                        pls.SavePickList(_orderID, _dvPickListMakeup, CurrentContext.UserId);
                    mgr.CommitTransaction();

                    BindApprovedOrders();
                    this.LogActivity("Print-Pick-List", ord.ID);
                    XtraMessageBox.Show("Your pick list has been saved! please continue to the next step or prepare another Picklist here.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                        ViewHelper.ShowErrorMessage("System couldn't save the Pick List, Please contact administrator for additional help", exp);
                    ErrorHandler.Handle(exp);
                }
        }
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());
            MyGeneration.dOOdads.TransactionMgr transaction =  MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();
                Order ord = new Order();
                ord.LoadByPrimaryKey(_orderID);
                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED,CurrentContext.UserId);;
                    BindApprovedOrders();
                }

                transaction.CommitTransaction();

                this.LogActivity("Return-Pick-List-To-Approval", ord.ID);
            }
            catch(Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;

            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Saves issue order details
        /// </summary>
        /// <param name="orderID"></param>
        /// <param name="dvPickListMakeup"></param>
        public void SavePickList(int orderID, DataView dvPickListMakeup, int userID)
        {
            //~ Check if This Order has a previous Printed Picklist with detail: Note a header only doesnt affect us! //
            var pickList = new PickList();

            pickList.LoadByOrderID(orderID);
            if (pickList.RowCount > 0)
            {
                var pldetail = new PickListDetail();
                pldetail.LoadByPickListID(pickList.ID);
                if (pldetail.RowCount > 0)
                {
                    RemoveFakePartialCommitPickListDetails(orderID);
                    var pickL = new PickList();
                    pickL.LoadByOrderID(orderID);
                    if (pickL.RowCount > 0)
                    {
                        throw new Exception("Picklist has already been printed for this Order ");
                        // This error has been apprearing for the last one year so funny! I hope it won't come again! day: 10/21/2014 @yido  //
                    }
                }
            }
            // Create a pick list entry
            Order ord = new Order();

            ord.LoadByPrimaryKey(orderID);
            PickList       pl        = new PickList();
            PalletLocation plocation = new PalletLocation();

            plocation.LoadByPrimaryKey(Convert.ToInt32(dvPickListMakeup[0]["PalletLocationID"]));
            pl.AddNew();
            pl.OrderID  = orderID;
            pl.PickType = "Pick";
            pl.PickedBy = userID;

            pl.IsConfirmed          = false;
            pl.IssuedDate           = DateTimeHelper.ServerDateTime;
            pl.SavedDate            = DateTimeHelper.ServerDateTime;
            pl.PickedDate           = DateTimeHelper.ServerDateTime;
            pl.IsWarehouseConfirmed = 0;
            pl.WarehouseID          = plocation.WarehouseID;
            pl.Save();
            PickListDetail pld = new PickListDetail();
            ReceivePallet  rp  = new ReceivePallet();
            ReceiveDoc     rd  = new ReceiveDoc();

            PickFace pf = new PickFace();

            foreach (DataRowView drv in dvPickListMakeup)
            {
                pld.AddNew();
                pld.PickListID    = pl.ID;
                pld.OrderDetailID = Convert.ToInt32(drv["OrderDetailID"]);

                pld.ItemID      = Convert.ToInt32(drv["ItemID"]);
                pld.BatchNumber = (drv["BatchNo"].ToString());
                if (drv["ExpDate"] != DBNull.Value)
                {
                    pld.ExpireDate = Convert.ToDateTime(drv["ExpDate"]);
                }
                pld.ManufacturerID   = Convert.ToInt32(drv["ManufacturerID"]);
                pld.BoxLevel         = Convert.ToInt32(drv["BoxLevel"]);
                pld.QtyPerPack       = Convert.ToInt32(drv["QtyPerPack"]);
                pld.Packs            = Convert.ToDecimal(drv["Pack"]);
                pld.PalletLocationID = Convert.ToInt32(drv["PalletLocationID"]);
                pld.QuantityInBU     = Convert.ToDecimal(drv["QtyInBU"]);
                pld.ReceiveDocID     = Convert.ToInt32(drv["ReceiveDocID"]);
                pld.ReceivePalletID  = Convert.ToInt32(drv["ReceivePalletID"]);
                if (drv["CalculatedCost"] != DBNull.Value)
                {
                    pld.Cost = Convert.ToDouble(drv["CalculatedCost"]);
                }
                if (drv["UnitPrice"] != DBNull.Value)
                {
                    pld.UnitPrice = Convert.ToDouble(drv["UnitPrice"]);
                }
                int ReceivePalletID = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(ReceivePalletID);
                pld.StoreID = Convert.ToInt32(drv["StoreID"]);

                if (drv["DeliveryNote"] != null)
                {
                    pld.DeliveryNote = Convert.ToBoolean(drv["DeliveryNote"]);
                }
                else
                {
                    pld.DeliveryNote = false;
                }


                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = Convert.ToDecimal(pld.QuantityInBU);
                }
                else
                {
                    rp.ReservedStock += Convert.ToDecimal(pld.QuantityInBU);
                }
                if (drv["UnitID"] != DBNull.Value)
                {
                    pld.UnitID = Convert.ToInt32(drv["UnitID"]);
                }
                plocation.LoadByPrimaryKey(Convert.ToInt32(drv["PalletLocationID"]));
                pld.PhysicalStoreID = plocation.PhysicalStoreID;

                rp.Save();

                if (drv["StorageTypeID"].ToString() == StorageType.PickFace)
                {
                    pf.LoadByPalletLocation(Convert.ToInt32(drv["PalletLocationID"]));
                    //pf.Balance -= Convert.ToDecimal(pld.QuantityInBU);
                    pf.Save();
                }
            }

            pld.Save();
            ord.ChangeStatus(OrderStatus.Constant.PICK_LIST_GENERATED, CurrentContext.UserId);
            ord.Save();
        }
        /// <summary>
        /// Formats the STV.
        /// </summary>
        /// <param name="ord">The ord.</param>
        /// <param name="dvPriced">The dv priced.</param>
        /// <param name="stvSentTo">The STV sent to.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="deliveryNote">if set to <c>true</c> [delivery note].</param>
        /// <param name="allowCancelByUser">if set to <c>true</c> [allow cancel by user].</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport FormatSTV(Order ord, DataTable dvPriced, string stvSentTo, PickList pl, bool deliveryNote, string printerName, HCMIS.Core.Distribution.Services.PrintLogService pLogService, int orderID)
        {
            bool hasInsurance = chkIncludeInsurance.Checked;
            string accountName = txtConfirmFromStore.Text;
            string transferType = null;

            int? orderTypeID = null;
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);

            if (!order.IsColumnNull("OrderTypeID"))
                orderTypeID = Convert.ToInt32(ord.GetColumn("OrderTypeID"));
            string transferDetail = "";
            if (orderTypeID.HasValue)
            {
                BLL.Transfer transfer = new Transfer();

                if (orderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    PhysicalStore toStore = new PhysicalStore();
                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    BLL.Warehouse toWarehouse = new BLL.Warehouse();
                    toWarehouse.LoadByPrimaryKey(toStore.PhysicalStoreTypeID);
                    transferType = "Store to Store Transfer";
                    stvSentTo = toWarehouse.Name;
                }

                if (orderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    Activity fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    Activity toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);
                    transferType = "Account to Account Transfer";
                    transferDetail = string.Format("From: {0} To: {1}", fromActivity.FullActivityName, toActivity.FullActivityName);
                }
            }

            if (!deliveryNote)
            {
                if(InstitutionIType.IsVaccine(GeneralInfo.Current))
                {
                    return WorkflowReportFactory.CreateModel22(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);
                }
                var stvReport = WorkflowReportFactory.CreateSTVonHeadedPaper(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);
                if (transferDetail != "")
                {
                    stvReport.TransferDetails.Text = transferDetail;
                    stvReport.TransferDetails.Visible = true;
                }
                else
                {
                    stvReport.TransferDetails.Visible = false;
                }

                return stvReport;
            }
            else
            {
                return WorkflowReportFactory.CreateDeliveryNote(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);

            }
        }
        /// <summary>
        /// Handles the Click event of the btnConfirmIssue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <exception cref="System.Exception"></exception>
        private void btnConfirmIssue_Click(object sender, EventArgs e)
        {
            // This is where the Issue is actually recorded and the stv is printed.
            // Do all kinds of validations.
            XtraReport STVReport = null; XtraReport DeliveryNoteReport = null;
            btnConfirmIssue1.Enabled = false;
            if (!IssueValid())
            {
                XtraMessageBox.Show("Please Correct the Items Marked in Red before Proceeding with Issue", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                return;
            }

            if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DateTimePickerEx dtDate = ConvertDate.GetCurrentEthiopianDateText();

                DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
                // The User is now sure that the STV has to be printed and that
                // the order is also good to save.
                // This is the section that does the saving.

                BLL.Order order = new Order();
                order.LoadByPrimaryKey(_orderID);

                // what are the pick lists, do we have devliery notes too?
                DataView dv = _dvOutstandingPickList;
                DataTable dvUnpriced = new DataTable();
                DataTable dvPriced = dv.ToTable();

                if (BLL.Settings.HandleGRV)
                {
                    if (BLL.Settings.IsCenter)
                        dv.RowFilter = "(Cost is null or Cost=0)";
                    else
                        dv.RowFilter = "DeliveryNote = true and (Cost is null or Cost=0)";
                    dvUnpriced = dv.ToTable();

                    dv.RowFilter = "Cost is not null and Cost <> 0";
                    dvPriced = dv.ToTable();
                }
                else
                {
                    dvPriced = dv.ToTable();
                }

                string stvPrinterName = "";
                string deliveryNotePrinter = "";

                if (!ConfirmPrinterSettings(dvPriced, dvUnpriced, out stvPrinterName, out deliveryNotePrinter)) return;
                bool saveSuccessful = false;

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    if (dvPriced.Rows.Count == 0 && dvUnpriced.Rows.Count == 0) throw new Exception("The Items doesn’t meet the requirement: please check the price status for non-delivery notes!");

                    mgr.BeginTransaction();

                    if (dvPriced.Rows.Count > 0)
                    {
                        STVReport = SaveAndPrintSTV(dvPriced.DefaultView, false, stvPrinterName, dtDate, dtCurrent);
                    }

                    if (dvUnpriced.Rows.Count > 0)
                    {
                        DeliveryNoteReport = SaveAndPrintSTV(dvUnpriced.DefaultView, true, deliveryNotePrinter, dtDate,
                                                         dtCurrent);
                    }
                    var ordr = new Order();
                    ordr.LoadByPrimaryKey(_orderID);

                    if (!ordr.IsColumnNull("OrderTypeID") &&

                        (ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER || ordr.OrderTypeID == BLL.OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER))
                    {
                        var transfer = new Transfer();
                        DateTime convertedEthDate = ConvertDate.DateConverter(dtDate.Text);
                        transfer.CommitAccountToAccountTransfer(ordr.ID, CurrentContext.UserId, convertedEthDate);
                    }

                    mgr.CommitTransaction();

                    saveSuccessful = true;

                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                    //Removed the reset logic
                    //MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgrReset();
                    XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ErrorHandler.Handle(exp);
                    saveSuccessful = false;
                }

                if (saveSuccessful)
                {
                    if (STVReport != null)
                    {
                        if (InstitutionIType.IsVaccine(GeneralInfo.Current))
                        {
                            for (int i = 0; i < BLL.Settings.STVCopies; i++)
                            {
                                STVReport.Print(stvPrinterName);
                            }
                        }
                        else
                        {
                            STVReport.Print(stvPrinterName);
                        }
                    }

                    if (DeliveryNoteReport != null)
                    { DeliveryNoteReport.Print(deliveryNotePrinter); }

                    XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK,
                                                            MessageBoxIcon.Information);
                }

                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                BindOutstandingPicklists();
                gridOutstandingPicklistDetail.DataSource = null;
                PalletLocation.GarbageCollection();

                if (BLL.Settings.AllowOnlineOrders)
                {
                    Helpers.RRFServiceIntegration.SubmitOnlineIssue(_orderID);
                }

            }
        }
        /// <summary>
        /// Handles the Click event of the btnConfirmIssue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <exception cref="System.Exception"></exception>
        private void btnConfirmIssue_Click(object sender, EventArgs e)
        {
            // This is where the Issue is actually recorded and the stv is printed.
            // Do all kinds of validations.
            XtraReport STVReport = null; XtraReport DeliveryNoteReport = null;

            btnConfirmIssue1.Enabled = false;
            if (!IssueValid())
            {
                XtraMessageBox.Show("Please Correct the Items Marked in Red before Proceeding with Issue", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                return;
            }

            if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DateTimePickerEx dtDate = ConvertDate.GetCurrentEthiopianDateText();

                DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
                // The User is now sure that the STV has to be printed and that
                // the order is also good to save.
                // This is the section that does the saving.

                BLL.Order order = new Order();
                order.LoadByPrimaryKey(_orderID);

                // what are the pick lists, do we have devliery notes too?
                DataView  dv         = _dvOutstandingPickList;
                DataTable dvUnpriced = new DataTable();
                DataTable dvPriced   = dv.ToTable();

                if (BLL.Settings.HandleGRV)
                {
                    if (BLL.Settings.IsCenter)
                    {
                        dv.RowFilter = "(Cost is null or Cost=0)";
                    }
                    else
                    {
                        dv.RowFilter = "DeliveryNote = true and (Cost is null or Cost=0)";
                    }
                    dvUnpriced = dv.ToTable();

                    dv.RowFilter = "Cost is not null and Cost <> 0";
                    dvPriced     = dv.ToTable();
                }
                else
                {
                    dvPriced = dv.ToTable();
                }

                string stvPrinterName      = "";
                string deliveryNotePrinter = "";

                if (!ConfirmPrinterSettings(dvPriced, dvUnpriced, out stvPrinterName, out deliveryNotePrinter))
                {
                    return;
                }
                bool saveSuccessful = false;

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    if (dvPriced.Rows.Count == 0 && dvUnpriced.Rows.Count == 0)
                    {
                        throw new Exception("The Items doesn’t meet the requirement: please check the price status for non-delivery notes!");
                    }

                    mgr.BeginTransaction();

                    if (dvPriced.Rows.Count > 0)
                    {
                        STVReport = SaveAndPrintSTV(dvPriced.DefaultView, false, stvPrinterName, dtDate, dtCurrent);
                    }


                    if (dvUnpriced.Rows.Count > 0)
                    {
                        DeliveryNoteReport = SaveAndPrintSTV(dvUnpriced.DefaultView, true, deliveryNotePrinter, dtDate,
                                                             dtCurrent);
                    }
                    var ordr = new Order();
                    ordr.LoadByPrimaryKey(_orderID);

                    if (!ordr.IsColumnNull("OrderTypeID") &&

                        (ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER || ordr.OrderTypeID == BLL.OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER))
                    {
                        var      transfer         = new Transfer();
                        DateTime convertedEthDate = ConvertDate.DateConverter(dtDate.Text);
                        transfer.CommitAccountToAccountTransfer(ordr.ID, CurrentContext.UserId, convertedEthDate);
                    }

                    mgr.CommitTransaction();

                    saveSuccessful = true;
                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                    //Removed the reset logic
                    //MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgrReset();
                    XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ErrorHandler.Handle(exp);
                    saveSuccessful = false;
                }

                if (saveSuccessful)
                {
                    if (STVReport != null)
                    {
                        if (InstitutionIType.IsVaccine(GeneralInfo.Current))
                        {
                            for (int i = 0; i < BLL.Settings.STVCopies; i++)
                            {
                                STVReport.Print(stvPrinterName);
                            }
                        }
                        else
                        {
                            STVReport.Print(stvPrinterName);
                        }
                    }

                    if (DeliveryNoteReport != null)
                    {
                        DeliveryNoteReport.Print(deliveryNotePrinter);
                    }

                    XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                }

                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                BindOutstandingPicklists();
                gridOutstandingPicklistDetail.DataSource = null;
                PalletLocation.GarbageCollection();

                if (BLL.Settings.AllowOnlineOrders)
                {
                    Helpers.RRFServiceIntegration.SubmitOnlineIssue(_orderID);
                }
            }
        }
        /// <summary>
        /// Commits the account to account transfer.
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="convertedEthDate">The converted eth date.</param>
        public void CommitAccountToAccountTransfer(int orderID, int userID, DateTime convertedEthDate)
        {
            int?supplierID = null;

            BLL.Transfer transfer = new Transfer();
            transfer.LoadByOrderID(orderID);
            if (transfer.RowCount == 0)
            {
                return;
            }

            int newStoreID, newPhysicalStoreID;

            newStoreID         = transfer.ToStoreID;
            newPhysicalStoreID = transfer.ToPhysicalStoreID;

            PhysicalStore toPhysicalStore = new PhysicalStore();

            toPhysicalStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);

            BLL.PickList picklist = new PickList();
            picklist.LoadByOrderID(orderID);
            BLL.PickListDetail pld = new PickListDetail();
            pld.LoadByPickListIDWithStvlogID(picklist.ID);
            BLL.ReceiveDoc rdOriginal = new ReceiveDoc();
            rdOriginal.LoadByPrimaryKey(pld.ReceiveDocID);


            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);
            if (order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newStoreID);
                supplierID = activity.SupplierID;
            }
            else if (order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(newPhysicalStoreID);
                supplierID = activity.SupplierID;
            }
            PO  po            = PO.CreatePOforStandard((int)order.GetColumn("OrderTypeID"), transfer.ToStoreID, supplierID, "Transfer", CurrentContext.LoggedInUser.ID);
            int IDPrinted     = Convert.ToInt32(pld.GetColumn("IDPrinted"));
            int receiptTypeID = order.OrderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    ? ReceiptType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER
                                    :order.OrderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          ? ReceiptType.CONSTANTS.STORE_TO_STORE_TRANSFER
                                          : order.OrderTypeID == OrderType.CONSTANTS.ERROR_CORRECTION_TRANSFER
                                          ? ReceiptType.CONSTANTS.ERROR_CORRECTION:ReceiptType.CONSTANTS.STANDARD_RECEIPT;



            Receipt receipt = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID, po.ID, toPhysicalStore.PhysicalStoreTypeID, IDPrinted, userID);

            var mergedPickLists = MergePickListsOfSameInfo(pld); // Picklists of the same info means: Based on all constraints we have on receiveDoc(Batch,Exp,ItemID,UnitID...): should be merged with summed quantity.

            pld.Rewind();
            while (!pld.EOF)
            {
                if (IDPrinted != Convert.ToInt32(pld.GetColumn("IDPrinted")))
                {
                    IDPrinted = Convert.ToInt32(pld.GetColumn("IDPrinted"));
                    receipt   = ReceiptInvoice.CreateReceiptInvoiceAndReceiptForTransfer(receiptTypeID, po.ID, toPhysicalStore.PhysicalStoreTypeID, IDPrinted, userID);
                }

                var rDoc = new ReceiveDoc();
                if (!mergedPickLists.ContainsKey(pld.ID))
                {
                    pld.MoveNext();
                    continue;
                }

                rDoc.SaveNewReceiveDocEntryFromPicklistDetail(pld, userID, newStoreID, newPhysicalStoreID,
                                                              convertedEthDate, receipt.ID, supplierID);
                pld.MoveNext();
            }
        }
        private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
        {
            //int ordId = Convert.ToInt32(gridApprovedOrdersView.GetFocusedDataRow()["ID"].ToString());

            Order ord = new Order();
            ord.LoadByPrimaryKey(_orderID);
            if (ord.RowCount == 0)
            {
                XtraMessageBox.Show("You have to select an Order to return to approval, ", "Error - Select Order");
                return;
            }
            if(!ord.IsColumnNull("OrderTypeID") && ord.OrderTypeID != OrderType.CONSTANTS.STANDARD_ORDER)
            {
                XtraMessageBox.Show("You cannot return this order to approval, you can either cancel or confirm this order", "Error - You cannot return this order");
                return;
            }

            MyGeneration.dOOdads.TransactionMgr transaction =  MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                transaction.BeginTransaction();

                if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.ORDER_APPROVED)
                {
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED,CurrentContext.UserId);
                    BindApprovedOrders();
                }
                else if (ord.RowCount > 0 && ord.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
                {
                    ord.ReleaseReservation();
                    ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED,CurrentContext.UserId);
                    BindApprovedOrders();
                }
                transaction.CommitTransaction();
            }
            catch(Exception exp)
            {
                transaction.RollbackTransaction();
                throw exp;
            }
            gridPickListDetail.DataSource = null;
            //HCMISLoader.MarkAsDirtyUsingOrderID(_orderID, NewMainWindow.UserId, true);
            if (BLL.Settings.IsCenter)
            {
                XtraMessageBox.Show("The Issue Order List has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("The Pick list has been returned to approval stage", "Confirmation",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// Formats the STV.
        /// </summary>
        /// <param name="ord">The ord.</param>
        /// <param name="dvPriced">The dv priced.</param>
        /// <param name="stvSentTo">The STV sent to.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="deliveryNote">if set to <c>true</c> [delivery note].</param>
        /// <param name="allowCancelByUser">if set to <c>true</c> [allow cancel by user].</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport FormatSTV(Order ord, DataTable dvPriced, string stvSentTo, PickList pl, bool deliveryNote, string printerName, HCMIS.Core.Distribution.Services.PrintLogService pLogService, int orderID)
        {
            bool   hasInsurance = chkIncludeInsurance.Checked;
            string accountName  = txtConfirmFromStore.Text;
            string transferType = null;

            int?orderTypeID = null;

            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);

            if (!order.IsColumnNull("OrderTypeID"))
            {
                orderTypeID = Convert.ToInt32(ord.GetColumn("OrderTypeID"));
            }
            string transferDetail = "";

            if (orderTypeID.HasValue)
            {
                BLL.Transfer transfer = new Transfer();

                if (orderTypeID == OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    PhysicalStore toStore = new PhysicalStore();
                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    BLL.Warehouse toWarehouse = new BLL.Warehouse();
                    toWarehouse.LoadByPrimaryKey(toStore.PhysicalStoreTypeID);
                    transferType = "Store to Store Transfer";
                    stvSentTo    = toWarehouse.Name;
                }

                if (orderTypeID == OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
                {
                    transfer.LoadByOrderID(orderID);
                    Activity fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    Activity toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);
                    transferType   = "Account to Account Transfer";
                    transferDetail = string.Format("From: {0} To: {1}", fromActivity.FullActivityName, toActivity.FullActivityName);
                }
            }


            if (!deliveryNote)
            {
                if (InstitutionIType.IsVaccine(GeneralInfo.Current))
                {
                    return(WorkflowReportFactory.CreateModel22(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType));
                }
                var stvReport = WorkflowReportFactory.CreateSTVonHeadedPaper(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType);
                if (transferDetail != "")
                {
                    stvReport.TransferDetails.Text    = transferDetail;
                    stvReport.TransferDetails.Visible = true;
                }
                else
                {
                    stvReport.TransferDetails.Visible = false;
                }

                return(stvReport);
            }
            else
            {
                return(WorkflowReportFactory.CreateDeliveryNote(ord, dvPriced, stvSentTo, pl.ID, null, false, true, hasInsurance, transferType));
            }
        }
 private void btnSubmitWishlist_Click(object sender, EventArgs e)
 {
     DataRow dr = gridRequisitionListView.GetFocusedDataRow();
     if (dr != null)
     {
         int orderID = Convert.ToInt32(dr["ID"]);
         Order ord = new Order();
         ord.LoadByPrimaryKey(orderID);
         if (ord.OrderStatusID == OrderStatus.Constant.DRAFT_WISHLIST)
         {
             ord.ChangeStatus(OrderStatus.Constant.ORDER_FILLED,CurrentContext.UserId);
             LoadRequisitions();
             XtraMessageBox.Show("Your requisisition has been submitted.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             XtraMessageBox.Show("This requisition has already been submitted, you cannot resubmit it.", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
 }
 /// <summary>
 /// Handles the Click event of the btnReturnToApprovalStep control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
 private void btnReturnToApprovalStep_Click(object sender, EventArgs e)
 {
     if (XtraMessageBox.Show("Are you sure you would like to return this order to the picklist?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
     {
         BLL.Order order = new Order();
         order.LoadByPrimaryKey(_orderID);
         order.ReturnBacktoPicklistConfirmation();
         BindOutstandingPicklists();
         gridOutstandingPicklistDetail.DataSource = null;
     }
 }
        /// <summary>
        /// Issues the valid.
        /// </summary>
        /// <returns></returns>
        private bool IssueValid()
        {
            //check approved against
            // check if the order has not alrady been printed
            Order Order = new Order();

            Order.LoadByPrimaryKey(_orderID);

            if (Order.OrderStatusID < OrderStatus.Constant.PICK_LIST_CONFIRMED)
            {
                XtraMessageBox.Show("Order is not yet ready for printing Invoice");
                return(false);
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.ISSUED)
            {
                XtraMessageBox.Show("This Order has already been printed. Please select another one.");
                return(false);
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.CANCELED)
            {
                XtraMessageBox.Show("This Order has been canceled. Please select another one.");
                return(false);
            }

            bool     valid = true;
            DataView pl    = gridOutstandingPicklistDetail.DataSource as DataView;

            foreach (DataRowView drv in pl)
            {
                ReceiveDoc rd = new ReceiveDoc();
                drv.Row.ClearErrors();
                if (drv["SKUPICKED"] == null || drv["SKUPICKED"] == DBNull.Value)
                {
                    drv.Row.SetColumnError("SKUPICKED", @"Field cannot be left empty");
                    valid = false;
                }
                else if (Convert.ToInt32(drv["SKUPICKED"]) > Convert.ToInt32(drv["SKUTOPICK"]))
                {
                    drv.Row.SetColumnError("SKUPICKED", @"You cannot issue more amount than the Approved Quantity");
                    valid = false;
                }

                else if (BLL.Settings.BlockWhenExpectingPriceChange && BLL.ReceiveDoc.DoesPriceNeedToBeChanged(int.Parse(drv["StoreID"].ToString()), int.Parse(drv["ItemID"].ToString()), int.Parse(drv["UnitID"].ToString()), int.Parse(drv["ManufacturerID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0) //rd.IsInNonPricedItemsList(int.Parse(drv["ItemID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0)
                {
                    drv.Row.SetColumnError("FullItemName", @"Price Pending!");
                    Item itm = new Item();
                    itm.LoadByPrimaryKey(int.Parse(drv["ItemID"].ToString()));
                    XtraMessageBox.Show(string.Format("The item {0} cannot be issued because it is waiting for price change.", itm.FullItemName), "Price Pending", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    valid = false;
                }
            }

            if (Order.PaymentTypeID != PaymentType.Constants.CASH && Order.PaymentTypeID != PaymentType.Constants.CREDIT && Order.PaymentTypeID != PaymentType.Constants.STV)
            {
                //TODO: This needs to be handled well.
                XtraMessageBox.Show(
                    string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
                                  Order.PaymentTypeID.ToString()), "Payment Type ID Problem");
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                valid = false;
            }

            if (valid)
            {
                valid = dxValidationProvider1.Validate();
            }

            return(valid);
        }
        /// <summary>
        /// Issues the valid.
        /// </summary>
        /// <returns></returns>
        private bool IssueValid()
        {
            //check approved against
            // check if the order has not alrady been printed
            Order Order = new Order();
            Order.LoadByPrimaryKey(_orderID);

            if (Order.OrderStatusID < OrderStatus.Constant.PICK_LIST_CONFIRMED)
            {
                XtraMessageBox.Show("Order is not yet ready for printing Invoice");
                return false;
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.ISSUED)
            {
                XtraMessageBox.Show("This Order has already been printed. Please select another one.");
                return false;
            }
            else if (Order.OrderStatusID == OrderStatus.Constant.CANCELED)
            {
                XtraMessageBox.Show("This Order has been canceled. Please select another one.");
                return false;
            }

            bool valid = true;
            DataView pl = gridOutstandingPicklistDetail.DataSource as DataView;
            foreach (DataRowView drv in pl)
            {
                ReceiveDoc rd = new ReceiveDoc();
                drv.Row.ClearErrors();
                if (drv["SKUPICKED"] == null || drv["SKUPICKED"] == DBNull.Value)
                {
                    drv.Row.SetColumnError("SKUPICKED", @"Field cannot be left empty");
                    valid = false;
                }
                else if (Convert.ToInt32(drv["SKUPICKED"]) > Convert.ToInt32(drv["SKUTOPICK"]))
                {
                    drv.Row.SetColumnError("SKUPICKED", @"You cannot issue more amount than the Approved Quantity");
                    valid = false;
                }

                else if (BLL.Settings.BlockWhenExpectingPriceChange && BLL.ReceiveDoc.DoesPriceNeedToBeChanged(int.Parse(drv["StoreID"].ToString()), int.Parse(drv["ItemID"].ToString()), int.Parse(drv["UnitID"].ToString()), int.Parse(drv["ManufacturerID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0) //rd.IsInNonPricedItemsList(int.Parse(drv["ItemID"].ToString())) && Convert.ToInt32(drv["SKUPICKED"]) > 0)
                {
                    drv.Row.SetColumnError("FullItemName", @"Price Pending!");
                    Item itm = new Item();
                    itm.LoadByPrimaryKey(int.Parse(drv["ItemID"].ToString()));
                    XtraMessageBox.Show(string.Format("The item {0} cannot be issued because it is waiting for price change.", itm.FullItemName), "Price Pending", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    valid = false;
                }
            }

            if (Order.PaymentTypeID != PaymentType.Constants.CASH && Order.PaymentTypeID != PaymentType.Constants.CREDIT && Order.PaymentTypeID != PaymentType.Constants.STV)
            {
                //TODO: This needs to be handled well.
                XtraMessageBox.Show(
                    string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
                                  Order.PaymentTypeID.ToString()), "Payment Type ID Problem");
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                valid = false;
            }

            if (valid)
            {
                valid = dxValidationProvider1.Validate();
            }

            return valid;
        }
        public void Save(Domain.Request _request,int userID, Domain.OrderStatus orderStatus = Domain.OrderStatus.Submitted)
        {
            var order = new Order();
            order.LoadByPrimaryKey(_request.RequestID);

            var dborderStatus = new BLL.OrderStatus();
            dborderStatus.LoadByCode(EnumService<Domain.OrderStatus>.GetCode(orderStatus));

            order.ChangeStatus(dborderStatus.ID,CurrentContext.UserId);
            order.ApprovedBy = userID;
            order.ApprovedDate = DateTimeHelper.ServerDateTime;

            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(_request.RequestID);
            while (!orderDetail.EOF)
            {
                var requestDetail = _request.RequestDetails.SingleOrDefault(r => r.RequestDetailId == orderDetail.ID);
                if(requestDetail== null)
                {
                    orderDetail.MarkAsDeleted();
                }
                else
                {

                    //Set Activity
                    if (requestDetail.ActivityGroup != null)
                    {
                        orderDetail.StoreID = requestDetail.ActivityGroup.Activity.ActivityID;
                        orderDetail.DeliveryNote = requestDetail.ActivityGroup.IsDeliveryNote;
                    }
                    else
                    {
                        orderDetail.SetColumnNull("StoreID");
                    }
                    //Set Manufacturer
                    if (requestDetail.Manufacturer != null)
                    {
                        orderDetail.PreferredManufacturerID = requestDetail.Manufacturer.ManufacturerID;
                    }
                    else
                    {
                        orderDetail.SetColumnNull("PreferredManufacturerID");
                    }

                    //Set PhysicalStore
                    if (requestDetail.physicalStore != null)
                    {
                        orderDetail.PreferredPhysicalStoreID = requestDetail.physicalStore.PhysicalStoreID;
                    }
                    else
                    {
                        orderDetail.SetColumnNull("PreferredPhysicalStoreID");
                    }

                    //Set ExpiryDate
                    if (requestDetail.ExpiryDate.HasValue)
                    {
                        orderDetail.PreferredExpiryDate = requestDetail.ExpiryDate.Value;
                    }
                    else
                    {
                        orderDetail.SetColumnNull("PreferredExpiryDate");
                    }
                        orderDetail.ApprovedQuantity = requestDetail.ApprovedQuantity;
                    orderDetail.StockedOut = requestDetail.StockedOut;
                }

                orderDetail.MoveNext();
            }
            foreach (var requestDetail in _request.RequestDetails.Where(r => r.RequestDetailId == 0).ToList())
            {
                orderDetail.AddNew();
                orderDetail.ItemID = requestDetail.Item.ItemID;
                orderDetail.UnitID = requestDetail.Unit.UnitID;
                orderDetail.Pack = requestDetail.RequestedQuantity;
                orderDetail.OrderID = order.ID;
                orderDetail.QtyPerPack = 1;
                orderDetail.Quantity = requestDetail.RequestedQuantity;
                orderDetail.ApprovedQuantity = requestDetail.ApprovedQuantity;
                orderDetail.StockedOut = requestDetail.StockedOut;
                if (requestDetail.ActivityGroup != null)
                {
                    orderDetail.StoreID = requestDetail.ActivityGroup.Activity.ActivityID;
                    orderDetail.DeliveryNote = requestDetail.ActivityGroup.IsDeliveryNote;
                }
                else
                {
                    orderDetail.SetColumnNull("StoreID");
                }
                //Set Manufacturer
                if (requestDetail.Manufacturer != null)
                {
                    orderDetail.PreferredManufacturerID = requestDetail.Manufacturer.ManufacturerID;
                }
                else
                {
                    orderDetail.SetColumnNull("PreferredManufacturerID");
                }

                //Set PhysicalStore
                if (requestDetail.physicalStore != null)
                {
                    orderDetail.PreferredPhysicalStoreID = requestDetail.physicalStore.PhysicalStoreID;
                }
                else
                {
                    orderDetail.SetColumnNull("PreferredPhysicalStoreID");
                }

                //Set ExpiryDate
                if (requestDetail.ExpiryDate.HasValue)
                {
                    orderDetail.PreferredExpiryDate = requestDetail.ExpiryDate.Value;
                }
                else
                {
                    orderDetail.SetColumnNull("PreferredExpiryDate");
                }

            }

            order.Save();
            orderDetail.Save();
        }