Example #1
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();
            }
        }
Example #2
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();
        }
 /// <summary>
 /// Right now used only from the invoice to the Approval Page
 /// </summary>
 public void ReturnBacktoPicklistConfirmation()
 {
     if (this.OrderStatusID != OrderStatus.Constant.PICK_LIST_CONFIRMED)
         return;//May need to throw an exception here.
     this.ChangeStatus(OrderStatus.Constant.PICK_LIST_GENERATED,CurrentContext.UserId);
     this.Save();
     BLL.PickList picklist = new PickList();
     picklist.LoadByOrderID(this.ID);
     picklist.IsConfirmed = false;
     picklist.Save();
 }
        /// <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();
            }
        }
        /// <summary>
        /// Releases the reservation.
        /// </summary>
        public void ReleaseReservation()
        {
            PickList pickList = new PickList();
            pickList.LoadByOrderID(this.ID);
            if (pickList.RowCount == 0) //If there is no picklist, there is nothing to release.
                return;
            PickListDetail pld = new PickListDetail();
            pld.LoadByPickListID(pickList.ID);
            pld.Rewind();
            while (!pld.EOF)
            {
                ReceivePallet receivePallet = new ReceivePallet();
                receivePallet.LoadByPrimaryKey(pld.ReceivePalletID);
                ReceiveDoc rdoc = new ReceiveDoc();
                rdoc.LoadByPrimaryKey(pld.ReceiveDocID);

                receivePallet.ReservedStock = receivePallet.ReservedStock - Convert.ToInt32(pld.QuantityInBU);
                if (receivePallet.ReservedStock < 0)
                    receivePallet.ReservedStock = 0;
                receivePallet.Save();
                //Delete from picklistDetail and add to pickListDetailDeleted
                PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                pld.MarkAsDeleted();
                pld.MoveNext();

                //Delete issues if the order has any
                    var iss = new Issue();
                    iss.GetIssueByOrderID(this.ID);
                iss.Rewind();
                if (iss.RowCount > 0)
                {
                    while (!iss.EOF)
                    {
                        iss.MarkAsDeleted();
                        iss.MoveNext();
                    }
                    iss.Save();
                }

            }
            pld.Save();
            pickList.MarkAsDeleted();
            pickList.Save();
        }
        /// <summary>
        /// Called when [outstanding picklist selected].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DevExpress.XtraGrid.Views.Grid.RowClickEventArgs" /> instance containing the event data.</param>
        private void OnOutstandingPicklistSelected(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var dr = gridOutstandingPickListView.GetFocusedDataRow();
            _orderID = Convert.ToInt32(dr["ID"]);

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

            // load payment type options
            int? requestedBy = null;

            var usr = new User();

            lblIssueStatus.Text = (string)dr["OrderStatus"];
            lblIssueTypes.Text = (string) dr["Description"];

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                requestedBy = order.RequestedBy;
                lkPaymentType.Properties.DataSource = PaymentType.GetAllowedTypes(order.FromStore, requestedBy);
                ins.LoadByPrimaryKey(order.RequestedBy);

                try
                {
                    lblWoreda.Text = ins.WoredaName ?? "-";
                    lblRegion.Text = ins.RegionName ?? "-";
                    lblZone.Text = ins.ZoneName ?? "-";
                    lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";

                    var ownership = new BLL.OwnershipType();
                    if (!ins.IsColumnNull("Ownership"))
                    {
                        ownership.LoadByPrimaryKey(ins.Ownership);
                        lblOwnership.Text = ownership.Name;
                    }

                }
                catch (NullReferenceException ex)
                {
                    //when transfer, institution has no woreda, zone or region, ignore the error
                }
            }
            else
                lblWoreda.Text = lblRegion.Text = lblZone.Text = lblInstitutionType.Text = lblOwnership.Text = "NA";

            //usr.LoadByPrimaryKey(NewMainWindow.UserId);
            usr = CurrentContext.LoggedInUser;
            txtIssuedBy.Text = usr.FullName ?? "-";

            PickList pl = new PickList();
            _dvOutstandingPickList = pl.GetPickListDetailsForOrder(_orderID, CurrentContext.LoggedInUserName);
            gridOutstandingPicklistDetail.DataSource = _dvOutstandingPickList;

            if (order.FromStore != Mode.Constants.HEALTH_PROGRAM)
            {
                colSKUPicked.Visible = false;
            }
            else
            {
                colSKUPicked.Visible = true;
            }

            txtConfirmFromStore.Text = order.GetFromStore();
            txtConfirmRequestedBy.Text = order.GetRequestedBy();

            int length = order.GetRequestedBy().Length;

            string s = "";

            HeaderSection.Text = order.GetRequestedBy() + s.PadRight(150-length)+"Order Number: " + order.RefNo;

            txtConfirmOrderNumber.Text = order.RefNo;
            //txtConfirmApprovedBy.Text = order.GetApprovedBy() ?? "-";
            lblApprovedBy.Text = order.GetApprovedBy() ?? "-";

            lkPaymentType.EditValue = order.PaymentTypeID;
            // Temporarily copy the STV
            txtIssueRefNo.Text = order.RefNo; //"";
            lblRefNo.Text = order.RefNo ?? "-";

            var paymentType = new BLL.PaymentType();
            paymentType.LoadByPrimaryKey(order.PaymentTypeID);
            lblPaymentType.Text = paymentType.Name ?? "-";

            lblMode.Text = order.GetFromStore() ?? "-";
            lblissuedDate.Text = order.Date.ToShortDateString();
            lblIssuedBy.Text = order.GetFilledBy();
            lblPicklistPrintedDate.Text = pl.PickedDate.ToShortDateString()!="" ? pl.PickedDate.ToShortDateString() : "-";

            var us = new User();
            pl.LoadByOrderID(_orderID);
            if (!pl.IsColumnNull("PickedBy"))
            {
                us.LoadByPrimaryKey(pl.PickedBy);
                lblPicklistConfirmedBy.Text = us.FullName;
            }
            else lblPicklistConfirmedBy.Text = "-";
        }
Example #7
0
        private void OnApprovedOrderRowClicked(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e != null && e.RowHandle < -1)
            {
                return;
            }

            var gv = (GridView)sender;
            var dr = gv.GetFocusedDataRow();

            _orderID = Convert.ToInt32(dr["ID"].ToString());

            order.LoadByPrimaryKey(_orderID);
            // populate the general order variables
            txtPickListFromStore.Text = order.GetFromStore();
            lblMode.Text = order.GetFromStore() ?? "-";

            txtPickListRequestedBy.Text = order.GetRequestedBy();
            labelControl9.Text          = order.GetRequestedBy() ?? "-";

            var us = new BLL.User();

            us.LoadByPrimaryKey(order.FilledBy);
            lblFilledBy.Text = us.FullName ?? "-";
            string s = "";

            lblLetterNum.Text = String.IsNullOrEmpty(order.LetterNo) ? "-" : order.LetterNo;

            var orderDetail = new OrderDetail();

            orderDetail.LoadAllByOrderID(order.ID);

            var paymentType = new BLL.PaymentType();

            paymentType.LoadByPrimaryKey(order.PaymentTypeID);

            if (!orderDetail.IsColumnNull("StoreID"))
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(orderDetail.StoreID);
                lblMode.Text = activity.ModeName ?? "-";
            }

            lblIssueStatus.Text = (string)dr["OrderStatus"] ?? "-";
            lblIssueType.Text   = (string)dr["Description"] ?? "-";

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                ins.LoadByPrimaryKey(order.RequestedBy);

                var ownership = new BLL.OwnershipType();
                ownership.LoadByPrimaryKey(ins.Ownership);

                int length = ins.Name.Length;
                HeaderSection.Text      = ins.Name + s.PadRight(150 - length) + "Order Number: " + order.RefNo;
                lblOwnership.Text       = ownership.Name ?? "-";
                lblZone.Text            = ins.ZoneName ?? "-";
                lblWoreda.Text          = ins.WoredaName ?? "-";
                lblRegion.Text          = ins.RegionName ?? "-";
                lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";
            }
            else
            {
                HeaderSection.Text = lblOwnership.Text = lblZone.Text = lblWoreda.Text = lblRegion.Text = lblInstitutionType.Text = "-";
            }


            lblPaymentType.Text = paymentType.Name;
            lblOrderDate.Text   = order.Date.ToShortDateString();

            txtPickListOrderNumber.Text = order.RefNo;
            labelControl12.Text         = order.RefNo;

            txtPickListApprovedBy.Text = order.GetApprovedBy();
            labelControl13.Text        = order.GetApprovedBy();

            if (order.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
            {
                PickList pl = new PickList();
                gridPickListDetail.DataSource = pl.GetPickListDetailsForOrder(_orderID);

                btnPrintAndSavePickList.Text = @"Confirm";
                colPrice.FieldName           = "Cost";
                colSKU.FieldName             = "Packs";
                btnCancelPickList.Enabled    = (BLL.Settings.UseNewUserManagement)? this.HasPermission("Cancel-Pick-List"):true;

                pl.LoadByOrderID(_orderID);
                if (!pl.IsColumnNull("PickedBy"))
                {
                    us.LoadByPrimaryKey(pl.PickedBy);
                    lblPicklistPrintedBy.Text = us.FullName;
                }
                else
                {
                    lblPicklistPrintedBy.Text = "-";
                }

                lblPicklistPrintedDate.Text = !pl.IsColumnNull("SavedDate") ? pl.SavedDate.ToShortDateString() : "-";
                lblPicklistNo.Text          = !pl.IsColumnNull("PrintedID") ? pl.PrintedID.ToString() : "-";
            }
            //gridPickListView.EndSummaryUpdate();
        }
        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        //public XtraReport RePrintSTV(DataView dv,int orderId, PickList pl,int? stvLogID, bool isConversion, bool generateNewPrintID = true)
        //{
        //     var includeInsurance =XtraMessageBox.Show("Include insurance?", "Insurance",MessageBoxButtons.YesNo,MessageBoxIcon.Question)== DialogResult.Yes;
        //     var ord = new Order();
        //    ord.LoadByPrimaryKey(orderId);
        //    var order = new Order();
        //    order.LoadByPrimaryKey(orderId);
        //    if (!order.IsPaymentTypeValid())
        //    {
        //        //TODO: This needs to be handled well.
        //        throw new Exception(
        //            string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
        //                          ord.PaymentTypeID));
        //    }
        //    var stores = new Activity();
        //    stores.LoadByPrimaryKey(order.FromStore);
        //    var textDeliveryNote = "";
        //    var sendToString = GetReceivingUnitName(order);
        //    if (stvLogID != null)
        //    {
        //        var stvLog = new Issue();
        //        stvLog.LoadByPrimaryKey(stvLogID.Value);
        //        if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
        //        {
        //            textDeliveryNote = stvLog.IDPrinted.ToString("00000");
        //        }
        //    }
        //    if (PaymentType.Constants.CASH == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;
        //        stvReport.TIN.Text = rus.TinNo;
        //        stvReport.VAT.Text = rus.VATNo;
        //        stvReport.Town.Text = rus.Town;
        //        stvReport.Woreda.Text = rus.WoredaText;
        //        stvReport.Zone.Text = rus.ZoneText;
        //        stvReport.Region.Text = rus.Region;
        //        stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;
        //        return stvReport;
        //    }
        //    else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        HCMIS.Desktop.Reports.CreditInvoice stvReport =
        //            new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID,
        //            CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;
        //        //stvReport.Region.Text = rus.Woreda;
        //        stvReport.Zone.Text = rus.Town;
        //        stvReport.Letter.Text = ord.LetterNo;
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;
        //    }
        //}
        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        public XtraReport RePrintSTV(DataView dv, int orderId, PickList pl, int? stvLogID, bool isConversion, bool generateNewPrintID = true)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            includeInsurance = XtraMessageBox.Show("Include insurance?", "Insurance", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
            var ord = new Order();
            ord.LoadByPrimaryKey(orderId);
            //loading two times
            var order = new Order();
            order.LoadByPrimaryKey(orderId);

            if (!order.IsPaymentTypeValid())
            {

                //TODO: This needs to be handled well.
                throw new Exception(
                    string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}", ord.PaymentTypeID));
            }

            var rus = new Institution();
            if (ord.PaymentTypeID == PaymentType.Constants.CASH || ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                rus.LoadByPrimaryKey(order.RequestedBy);
            }

            var stores = new Activity();

            stores.LoadByPrimaryKey(order.FromStore);
            var textDeliveryNote = "";
            var sendToString = GetReceivingUnitName(order);
            if (stvLogID != null)
            {
                var stvLog = new Issue();
                stvLog.LoadByPrimaryKey(stvLogID.Value);
                if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
                {
                    textDeliveryNote = stvLog.IDPrinted.ToString("00000");
                }
            }
            var xtraReport = new XtraReport();
            string stvPrinterName = "";
            if (PaymentType.Constants.CASH == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, dv.Table, rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CASH == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return xtraReport;
            }
            //if (PaymentType.Constants.CASH == ord.PaymentTypeID)
            //{
            //    var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;
            //    stvReport.TIN.Text = rus.TinNo;
            //    stvReport.VAT.Text = rus.VATNo;
            //    stvReport.Town.Text = rus.Town;
            //    stvReport.Woreda.Text = rus.WoredaText;
            //    stvReport.Zone.Text = rus.ZoneText;
            //    stvReport.Region.Text = rus.Region;

            //    stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;

            //    return stvReport;
            //}
            //else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
            //{
            //    HCMIS.Desktop.Reports.CreditInvoice stvReport = new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;

            //    //stvReport.Region.Text = rus.Woreda;
            //    stvReport.Zone.Text = rus.Town;
            //    stvReport.Letter.Text = ord.LetterNo;
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;

            //    return stvReport;
            //}
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);

                // check if this is a delivery note
                Issue sl = new Issue();
                sl.LoadByPrimaryKey(stvLogID.Value);
                if (!sl.IsColumnNull("IsDeliveryNote") && sl.IsDeliveryNote && !isConversion)
                {
                    var stvReport = new HCMIS.Desktop.Reports.DeliveryNoteForIssue(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);

                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return stvReport;
                }
                else
                {
                    var stvReport = new HCMIS.Desktop.Reports.STVonHeadedPaper(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);
                    stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return stvReport;
                }
            }
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && !generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);
                //System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                //MessageBoxButtons.YesNo,
                //MessageBoxIcon.Question);
                Issue log = new Issue();
                log.LoadByPrimaryKey((_reprintId != null) ? _reprintId.Value : stvLogID.Value);

                if (log.IsColumnNull("HasInsurance") || BLL.Settings.IsCenter) //If it is null, we have no idea about what the insurance status was.  So let's ask the user.
                {
                    System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                                                                                   MessageBoxButtons.YesNo,
                                                                                   MessageBoxIcon.Question);
                    includeInsurance = result == DialogResult.Yes ? true : false;
                    log.HasInsurance = includeInsurance;
                    log.Save();
                }
                else
                {
                    includeInsurance = log.HasInsurance;
                }

                //bool includeInsurance = (!log.IsColumnNull("HasInsurance"))? log.HasInsurance : false;
                var stvReport = new HCMIS.Desktop.Reports.STVonA4(ord.ID, includeInsurance,
                                                                  CurrentContext.LoggedInUserName);
                stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                PrepareTheReport(stvReport);
                stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, (_reprintId != null) ? _reprintId : stvLogID, isConversion, generateNewPrintID, includeInsurance);
                stvReport.From.Text = GeneralInfo.Current.HospitalName;
                stvReport.To.Text = sendToString;
                //stvReport.STVNO.Text =  //STVLog.GetLogFor(ord.RefNo);
                //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                DateTimePickerEx dtDate = new DateTimePickerEx();
                dtDate.Value = DateTimeHelper.ServerDateTime;
                stvReport.Date.Text = dtDate.Text;
                return stvReport;
            }
            return null;
        }
        /// <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();
            }
        }
        /// <summary>
        /// Called when [outstanding picklist selected].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DevExpress.XtraGrid.Views.Grid.RowClickEventArgs" /> instance containing the event data.</param>
        private void OnOutstandingPicklistSelected(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var dr = gridOutstandingPickListView.GetFocusedDataRow();

            _orderID = Convert.ToInt32(dr["ID"]);

            var order = new BLL.Order();

            order.LoadByPrimaryKey(_orderID);


            // load payment type options
            int?requestedBy = null;

            var usr = new User();

            lblIssueStatus.Text = (string)dr["OrderStatus"];
            lblIssueTypes.Text  = (string)dr["Description"];

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                requestedBy = order.RequestedBy;
                lkPaymentType.Properties.DataSource = PaymentType.GetAllowedTypes(order.FromStore, requestedBy);
                ins.LoadByPrimaryKey(order.RequestedBy);

                try
                {
                    lblWoreda.Text          = ins.WoredaName ?? "-";
                    lblRegion.Text          = ins.RegionName ?? "-";
                    lblZone.Text            = ins.ZoneName ?? "-";
                    lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";

                    var ownership = new BLL.OwnershipType();
                    if (!ins.IsColumnNull("Ownership"))
                    {
                        ownership.LoadByPrimaryKey(ins.Ownership);
                        lblOwnership.Text = ownership.Name;
                    }
                }
                catch (NullReferenceException ex)
                {
                    //when transfer, institution has no woreda, zone or region, ignore the error
                }
            }
            else
            {
                lblWoreda.Text = lblRegion.Text = lblZone.Text = lblInstitutionType.Text = lblOwnership.Text = "NA";
            }


            //usr.LoadByPrimaryKey(NewMainWindow.UserId);
            usr = CurrentContext.LoggedInUser;
            txtIssuedBy.Text = usr.FullName ?? "-";


            PickList pl = new PickList();

            _dvOutstandingPickList = pl.GetPickListDetailsForOrder(_orderID, CurrentContext.LoggedInUserName);
            gridOutstandingPicklistDetail.DataSource = _dvOutstandingPickList;



            if (order.FromStore != Mode.Constants.HEALTH_PROGRAM)
            {
                colSKUPicked.Visible = false;
            }
            else
            {
                colSKUPicked.Visible = true;
            }


            txtConfirmFromStore.Text   = order.GetFromStore();
            txtConfirmRequestedBy.Text = order.GetRequestedBy();

            int length = order.GetRequestedBy().Length;


            string s = "";

            HeaderSection.Text = order.GetRequestedBy() + s.PadRight(150 - length) + "Order Number: " + order.RefNo;

            txtConfirmOrderNumber.Text = order.RefNo;
            //txtConfirmApprovedBy.Text = order.GetApprovedBy() ?? "-";
            lblApprovedBy.Text = order.GetApprovedBy() ?? "-";

            lkPaymentType.EditValue = order.PaymentTypeID;
            // Temporarily copy the STV
            txtIssueRefNo.Text = order.RefNo; //"";
            lblRefNo.Text      = order.RefNo ?? "-";

            var paymentType = new BLL.PaymentType();

            paymentType.LoadByPrimaryKey(order.PaymentTypeID);
            lblPaymentType.Text = paymentType.Name ?? "-";

            lblMode.Text                = order.GetFromStore() ?? "-";
            lblissuedDate.Text          = order.Date.ToShortDateString();
            lblIssuedBy.Text            = order.GetFilledBy();
            lblPicklistPrintedDate.Text = pl.PickedDate.ToShortDateString() != "" ? pl.PickedDate.ToShortDateString() : "-";

            var us = new User();

            pl.LoadByOrderID(_orderID);
            if (!pl.IsColumnNull("PickedBy"))
            {
                us.LoadByPrimaryKey(pl.PickedBy);
                lblPicklistConfirmedBy.Text = us.FullName;
            }
            else
            {
                lblPicklistConfirmedBy.Text = "-";
            }
        }
        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        //public XtraReport RePrintSTV(DataView dv,int orderId, PickList pl,int? stvLogID, bool isConversion, bool generateNewPrintID = true)
        //{
        //     var includeInsurance =XtraMessageBox.Show("Include insurance?", "Insurance",MessageBoxButtons.YesNo,MessageBoxIcon.Question)== DialogResult.Yes;
        //     var ord = new Order();
        //    ord.LoadByPrimaryKey(orderId);
        //    var order = new Order();
        //    order.LoadByPrimaryKey(orderId);

        //    if (!order.IsPaymentTypeValid())
        //    {

        //        //TODO: This needs to be handled well.
        //        throw new Exception(
        //            string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}",
        //                          ord.PaymentTypeID));

        //    }

        //    var stores = new Activity();

        //    stores.LoadByPrimaryKey(order.FromStore);
        //    var textDeliveryNote = "";
        //    var sendToString = GetReceivingUnitName(order);
        //    if (stvLogID != null)
        //    {
        //        var stvLog = new Issue();
        //        stvLog.LoadByPrimaryKey(stvLogID.Value);
        //        if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
        //        {
        //            textDeliveryNote = stvLog.IDPrinted.ToString("00000");
        //        }
        //    }

        //    if (PaymentType.Constants.CASH == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;
        //        stvReport.TIN.Text = rus.TinNo;
        //        stvReport.VAT.Text = rus.VATNo;
        //        stvReport.Town.Text = rus.Town;
        //        stvReport.Woreda.Text = rus.WoredaText;
        //        stvReport.Zone.Text = rus.ZoneText;
        //        stvReport.Region.Text = rus.Region;
        //        stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;

        //        return stvReport;
        //    }
        //    else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
        //    {
        //        var rus = new Institution();
        //        rus.LoadByPrimaryKey(order.RequestedBy);
        //        HCMIS.Desktop.Reports.CreditInvoice stvReport =
        //            new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
        //        pl.LoadByOrderID(orderId);
        //        PrepareTheReport(stvReport);
        //        stvReport.DeliveryNoteNo.Text = textDeliveryNote;
        //        stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID,
        //            CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
        //        stvReport.From.Text = GeneralInfo.Current.HospitalName;
        //        stvReport.To.Text = sendToString;

        //        //stvReport.Region.Text = rus.Woreda;
        //        stvReport.Zone.Text = rus.Town;
        //        stvReport.Letter.Text = ord.LetterNo;
        //        //stvReport.Program.Text = stores.StoreName;
        //        DateTimePickerEx dtDate = new DateTimePickerEx();
        //        dtDate.Value = DateTimeHelper.ServerDateTime;
        //        stvReport.Date.Text = dtDate.Text;
        //    }
        //}

        /// <summary>
        /// Re print STV.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="isConversion">if set to <c>true</c> [is conversion].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        public XtraReport RePrintSTV(DataView dv, int orderId, PickList pl, int?stvLogID, bool isConversion, bool generateNewPrintID = true)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            includeInsurance = XtraMessageBox.Show("Include insurance?", "Insurance", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
            var ord = new Order();

            ord.LoadByPrimaryKey(orderId);
            //loading two times
            var order = new Order();

            order.LoadByPrimaryKey(orderId);

            if (!order.IsPaymentTypeValid())
            {
                //TODO: This needs to be handled well.
                throw new Exception(
                          string.Format("PaymentTypeID has a problem.  The order has a payment type id of {0}", ord.PaymentTypeID));
            }

            var rus = new Institution();

            if (ord.PaymentTypeID == PaymentType.Constants.CASH || ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                rus.LoadByPrimaryKey(order.RequestedBy);
            }

            var stores = new Activity();

            stores.LoadByPrimaryKey(order.FromStore);
            var textDeliveryNote = "";
            var sendToString     = GetReceivingUnitName(order);

            if (stvLogID != null)
            {
                var stvLog = new Issue();
                stvLog.LoadByPrimaryKey(stvLogID.Value);
                if (!stvLog.IsColumnNull("IsDeliveryNote") && stvLog.IsDeliveryNote && isConversion)
                {
                    textDeliveryNote = stvLog.IDPrinted.ToString("00000");
                }
            }
            var    xtraReport     = new XtraReport();
            string stvPrinterName = "";

            if (PaymentType.Constants.CASH == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, dv.Table, rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return(xtraReport);
            }

            else if (PaymentType.Constants.CASH == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCashRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return(xtraReport);
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && !chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, false, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return(xtraReport);
            }

            else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID && chkDeliveryNotes.Checked)
            {
                xtraReport = FormatCreditRePrintInvoice(ord, pl.DefaultView.ToTable(), rus, pl, true, stvPrinterName, pLogService, _stvLogIdChosen);
                pLogService.CommitPrintLog();
                return(xtraReport);
            }
            //if (PaymentType.Constants.CASH == ord.PaymentTypeID)
            //{
            //    var stvReport = new HCMIS.Desktop.Reports.CashInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;
            //    stvReport.TIN.Text = rus.TinNo;
            //    stvReport.VAT.Text = rus.VATNo;
            //    stvReport.Town.Text = rus.Town;
            //    stvReport.Woreda.Text = rus.WoredaText;
            //    stvReport.Zone.Text = rus.ZoneText;
            //    stvReport.Region.Text = rus.Region;

            //    stvReport.License.Text = (!rus.IsColumnNull("Ownership") && rus.IsPrivatelyOwned) ? rus.LicenseNo : (!ord.IsColumnNull("LetterNo")) ? ord.LetterNo : "";
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;

            //    return stvReport;
            //}
            //else if (PaymentType.Constants.CREDIT == ord.PaymentTypeID)
            //{
            //    HCMIS.Desktop.Reports.CreditInvoice stvReport = new HCMIS.Desktop.Reports.CreditInvoice(CurrentContext.LoggedInUserName);
            //    pl.LoadByOrderID(orderId);
            //    PrepareTheReport(stvReport);
            //    stvReport.DeliveryNoteNo.Text = textDeliveryNote;
            //    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
            //    stvReport.From.Text = GeneralInfo.Current.HospitalName;
            //    stvReport.To.Text = sendToString;

            //    //stvReport.Region.Text = rus.Woreda;
            //    stvReport.Zone.Text = rus.Town;
            //    stvReport.Letter.Text = ord.LetterNo;
            //    //stvReport.Program.Text = stores.StoreName;
            //    DateTimePickerEx dtDate = new DateTimePickerEx();
            //    dtDate.Value = DateTimeHelper.ServerDateTime;
            //    stvReport.Date.Text = dtDate.Text;


            //    return stvReport;
            //}
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);

                // check if this is a delivery note
                Issue sl = new Issue();
                sl.LoadByPrimaryKey(stvLogID.Value);
                if (!sl.IsColumnNull("IsDeliveryNote") && sl.IsDeliveryNote && !isConversion)
                {
                    var stvReport = new HCMIS.Desktop.Reports.DeliveryNoteForIssue(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);


                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text  = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text    = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value        = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return(stvReport);
                }
                else
                {
                    var stvReport = new HCMIS.Desktop.Reports.STVonHeadedPaper(ord.ID, includeInsurance, CurrentContext.LoggedInUserName);
                    stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                    PrepareTheReport(stvReport);
                    stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, stvLogID, isConversion, generateNewPrintID, includeInsurance);
                    stvReport.From.Text  = GeneralInfo.Current.HospitalName;
                    stvReport.To.Text    = sendToString;
                    stvReport.STVNO.Text = Issue.GetLogFor(ord.RefNo);
                    //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                    DateTimePickerEx dtDate = new DateTimePickerEx();
                    dtDate.Value        = DateTimeHelper.ServerDateTime;
                    stvReport.Date.Text = dtDate.Text;
                    //stvReport.ShowPreview();

                    return(stvReport);
                }
            }
            else if (PaymentType.Constants.STV == ord.PaymentTypeID && !generateNewPrintID)
            {
                pl.LoadByOrderID(orderId);
                //System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                //MessageBoxButtons.YesNo,
                //MessageBoxIcon.Question);
                Issue log = new Issue();
                log.LoadByPrimaryKey((_reprintId != null) ? _reprintId.Value : stvLogID.Value);


                if (log.IsColumnNull("HasInsurance") || BLL.Settings.IsCenter) //If it is null, we have no idea about what the insurance status was.  So let's ask the user.
                {
                    System.Windows.Forms.DialogResult result = XtraMessageBox.Show("Include insurance?", "Insurance",
                                                                                   MessageBoxButtons.YesNo,
                                                                                   MessageBoxIcon.Question);
                    includeInsurance = result == DialogResult.Yes ? true : false;
                    log.HasInsurance = includeInsurance;
                    log.Save();
                }
                else
                {
                    includeInsurance = log.HasInsurance;
                }

                //bool includeInsurance = (!log.IsColumnNull("HasInsurance"))? log.HasInsurance : false;
                var stvReport = new HCMIS.Desktop.Reports.STVonA4(ord.ID, includeInsurance,
                                                                  CurrentContext.LoggedInUserName);
                stvReport.DeliveryNoteNo.Text = textDeliveryNote;

                PrepareTheReport(stvReport);
                stvReport.DataSource = Order.ReorganizeDataViewForSTVPrint_Program(dv, ord.ID, pl.ID, CurrentContext.UserId, (_reprintId != null) ? _reprintId : stvLogID, isConversion, generateNewPrintID, includeInsurance);
                stvReport.From.Text  = GeneralInfo.Current.HospitalName;
                stvReport.To.Text    = sendToString;
                //stvReport.STVNO.Text =  //STVLog.GetLogFor(ord.RefNo);
                //stvReport.Date.Text = @"(Reprint) " + Convert.ToDateTime(dv[0]["IssueDate"]).ToString("MM/dd/yyyy");
                DateTimePickerEx dtDate = new DateTimePickerEx();
                dtDate.Value        = DateTimeHelper.ServerDateTime;
                stvReport.Date.Text = dtDate.Text;
                return(stvReport);
            }
            return(null);
        }
        /// <summary>
        /// Saves the and print STV.
        /// </summary>
        /// <param name="pickListDetail">The pick list detail.</param>
        /// <param name="deliveryNotePrinter">The delivery note printer.</param>
        /// <param name="stvPrinterName">Name of the STV printer.</param>
        /// <param name="dtDate">The dt date.</param>
        /// <param name="dtCurrent">The dt current.</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport SaveAndPrintSTV(DataView pickListDetail, bool isDeliveryNote, string printerName, DateTimePickerEx dtDate, DateTime dtCurrent)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            Order ord = IssueDoc.SaveIssueTransaction(_orderID, ref pickListDetail, txtRemarks.Text,
                                                      CurrentContext.LoggedInUserName, dtCurrent);



            if (pickListDetail.Count == 0)
            {
                throw new Exception("An error occurred during saving the issue.  Please contact your administrator.");
            }

            string sendToString = "";

            BLL.Order ordr = new BLL.Order();
            ordr.LoadByPrimaryKey(_orderID);
            BLL.Institution rus = new Institution();
            if (!ordr.IsColumnNull("RequestedBy"))
            {
                rus.LoadByPrimaryKey(ordr.RequestedBy);
                sendToString = rus.Name;
            }

            else if (!ordr.IsColumnNull("OrderTypeID") &&
                     ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                BLL.Transfer transfer = new Transfer();
                transfer.LoadByOrderID(_orderID);
                var activity = new Activity();
                activity.LoadByPrimaryKey(transfer.ToStoreID);
                sendToString = activity.FullActivityName;
            }

            PickList pl = new PickList();

            pl.LoadByOrderID(ord.ID);

            var xtraReport = new XtraReport();

            if (ord.PaymentTypeID == PaymentType.Constants.CASH)
            {
                xtraReport = FormatCashInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                               printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                xtraReport = FormatCreditInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                                 printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.STV)
            {
                xtraReport = FormatSTV(ord, pickListDetail.Table, sendToString, pl, isDeliveryNote,
                                       printerName,
                                       pLogService, _orderID);
            }



            SavePdfReport(pLogService, xtraReport);
            pLogService.CommitPrintLog();
            return(xtraReport);
        }
        /// <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 OnApprovedOrderRowClicked(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e != null && e.RowHandle < -1)
                return;

            var gv = (GridView)sender;
            var dr = gv.GetFocusedDataRow();
            _orderID = Convert.ToInt32(dr["ID"].ToString());

            order.LoadByPrimaryKey(_orderID);
            // populate the general order variables
            txtPickListFromStore.Text = order.GetFromStore();
            lblMode.Text = order.GetFromStore() ?? "-";

            txtPickListRequestedBy.Text = order.GetRequestedBy();
            labelControl9.Text = order.GetRequestedBy() ?? "-";

            var us = new BLL.User();

            us.LoadByPrimaryKey(order.FilledBy);
            lblFilledBy.Text = us.FullName ?? "-";
            string s = "";

            lblLetterNum.Text = String.IsNullOrEmpty(order.LetterNo) ? "-" : order.LetterNo;

            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(order.ID);

            var paymentType = new BLL.PaymentType();
            paymentType.LoadByPrimaryKey(order.PaymentTypeID);

            if (!orderDetail.IsColumnNull("StoreID"))
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(orderDetail.StoreID);
                lblMode.Text = activity.ModeName ?? "-";
            }

            lblIssueStatus.Text = (string)dr["OrderStatus"] ?? "-";
            lblIssueType.Text = (string)dr["Description"] ?? "-";

            if (!order.IsColumnNull("RequestedBy"))
            {
                var ins = new Institution();
                ins.LoadByPrimaryKey(order.RequestedBy);

                var ownership = new BLL.OwnershipType();
                ownership.LoadByPrimaryKey(ins.Ownership);

                int length = ins.Name.Length;
                HeaderSection.Text = ins.Name + s.PadRight(150 - length) + "Order Number: " + order.RefNo;
                lblOwnership.Text = ownership.Name ?? "-";
                lblZone.Text = ins.ZoneName ?? "-";
                lblWoreda.Text = ins.WoredaName ?? "-";
                lblRegion.Text = ins.RegionName ?? "-";
                lblInstitutionType.Text = ins.InstitutionTypeName ?? "-";
            }
            else
            {
                HeaderSection.Text =lblOwnership.Text = lblZone.Text =lblWoreda.Text =lblRegion.Text = lblInstitutionType.Text = "-";
            }

            lblPaymentType.Text = paymentType.Name;
            lblOrderDate.Text = order.Date.ToShortDateString();

            txtPickListOrderNumber.Text = order.RefNo;
            labelControl12.Text = order.RefNo;

            txtPickListApprovedBy.Text = order.GetApprovedBy();
            labelControl13.Text = order.GetApprovedBy();

            if (order.OrderStatusID == OrderStatus.Constant.PICK_LIST_GENERATED)
            {
                PickList pl = new PickList();
                gridPickListDetail.DataSource = pl.GetPickListDetailsForOrder(_orderID);

                btnPrintAndSavePickList.Text = @"Confirm";
                colPrice.FieldName = "Cost";
                colSKU.FieldName = "Packs";
                btnCancelPickList.Enabled = (BLL.Settings.UseNewUserManagement)? this.HasPermission("Cancel-Pick-List"):true;

                pl.LoadByOrderID(_orderID);
                if (!pl.IsColumnNull("PickedBy"))
                {
                    us.LoadByPrimaryKey(pl.PickedBy);
                    lblPicklistPrintedBy.Text = us.FullName;
                }
                else lblPicklistPrintedBy.Text = "-";

                lblPicklistPrintedDate.Text = !pl.IsColumnNull("SavedDate") ? pl.SavedDate.ToShortDateString() : "-";
                lblPicklistNo.Text = !pl.IsColumnNull("PrintedID") ? pl.PrintedID.ToString() : "-";

            }
            //gridPickListView.EndSummaryUpdate();
        }
Example #15
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>
        /// 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();
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList plst = new PickList();
            IssueDoc issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();
            BLL.Order ord = new BLL.Order();
            ord.LoadByPrimaryKey(orderID);
            plst.LoadByOrderID(ord.ID);

            foreach (DataRowView drv in dvOutstandingPickList)
            {
                // Pseudo:
                // for each row in the picklist
                // undate the issue document
                // subtract the issued quantity from the receive doc
                // subtract the issued quantity from recieve pallet
                // subtract the issued the reserved quantity irregardless of the quantity issued.

                //Saving the new Issue issue
                if (Convert.ToDecimal(drv["BUPICKED"]) == 0)
                {
                    continue;

                }

                if (Convert.ToDecimal(drv["SKUPicked"]) != Convert.ToDecimal(drv["SKUTOPICK"]))
                {
                    drv["Cost"] = Convert.ToDecimal(drv["SKUPicked"]) * Convert.ToDecimal(drv["UnitPrice"]);
                }

                // Select the receive doc that is associated with this issue.
                recDoc.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveDocID"]));

                issDoc.AddNew();
                issDoc.StoreId = Convert.ToInt32(drv["StoreID"]);
                issDoc.RefNo = ord.RefNo;
                if (!ord.IsColumnNull("RequestedBy"))
                    issDoc.ReceivingUnitID = ord.RequestedBy;
                // TOFIX:
                // TODO:
                // Lord have mercy kind of hack to avoid the feb date problem
                // this needs to be fixed for pagume also
                issDoc.Date = etCurrentDate;
                issDoc.EurDate = DateTimeHelper.ServerDateTime;
                issDoc.RecievDocID = Convert.ToInt32(drv["ReceiveDocID"]);
                issDoc.IsApproved = true;
                issDoc.IsTransfer = false;
                issDoc.Remark = remark;
                issDoc.ItemID = Convert.ToInt32(drv["ItemID"]);
                issDoc.Quantity = Convert.ToDecimal(drv["BUPICKED"]);
                issDoc.NoOfPack = Convert.ToDecimal(drv["SKUPICKED"]);
                issDoc.QtyPerPack = Convert.ToInt32(drv["SKUBU"]);
                issDoc.BatchNo = drv["BatchNumber"].ToString();
                issDoc.UnitID = recDoc.UnitID;
                issDoc.ManufacturerID = recDoc.ManufacturerId;
                if (drv["Cost"] != DBNull.Value)
                {
                    issDoc.Cost = Convert.ToDouble(drv["Cost"]);

                    issDoc.SellingPrice = Convert.ToDecimal(drv["UnitPrice"]);
                    if (!recDoc.IsColumnNull("Cost"))
                    {
                        issDoc.UnitCost = Convert.ToDecimal(recDoc.Cost);
                    }
                }
                issDoc.OrderID = orderID;
                issDoc.IssuedBy = issuedBy;
                // TODO: is this the right place where we need to pick the physical store ID from?
                // check it against the receipt pallet physical store.
                if (!recDoc.IsColumnNull("PhysicalStoreID"))
                {
                    issDoc.PhysicalStoreID = recDoc.PhysicalStoreID;
                }
                if (!recDoc.IsColumnNull("InventoryPeriodID"))
                {
                    //Todo: Remove for Inventory
                    issDoc.InventoryPeriodID = recDoc.InventoryPeriodID;
                }
                if (!recDoc.IsColumnNull("Margin"))
                {
                    issDoc.Margin = (decimal)recDoc.Margin;
                }
                //Replaced by
                issDoc.PLDetailID = Convert.ToInt32(drv["PLDetailID"]);
                BLL.Balance bal = new Balance();
                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(issDoc.RecievDocID);
                decimal currentBalance = bal.GetSoh(issDoc.ItemID, rd.UnitID, issDoc.StoreId, issDoc.Date.Month, issDoc.Date.Year);
                if (currentBalance < issDoc.NoOfPack)
                {
                    throw new Exception(string.Format("The item {0} is not available in {1} Qty.", drv["FullItemName"].ToString(), issDoc.NoOfPack));
                }

                // This is a field that is not applicable on the hub edition
                // It is about the dispensing unit quantity and there is no such thing as Dispensing unit
                // in the hub edition
                issDoc.DUSOH = 0;
                issDoc.RecomendedQty = 0;// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                // End DU
                issDoc.DispatchConfirmed = false;
                issDoc.Save();
                drv["IssueDocID"] = issDoc.ID;
                // updating the receiving doc

                //long prevQuantityLeft = recDoc.QuantityLeft;

                recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;

                if (recDoc.QuantityLeft < 0)
                {
                    //Possibly the wrong ReceiveDoc Entry chosen
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }
                //long
                recDoc.Out = (recDoc.QuantityLeft == 0) ? true : false;
                recDoc.Save();

                ReceivePallet rp = new ReceivePallet();
                int id = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(id);
                if (rp.IsColumnNull("Balance"))
                {
                    rp.Balance = rp.ReceivedQuantity;
                }
                rp.Balance -= issDoc.Quantity;

                if (rp.Balance < 0)
                {
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }

                decimal totReservedQty = Convert.ToDecimal(drv["QuantityInBU"]);

                if (rp.IsColumnNull("ReservedStock"))
                    rp.ReservedStock = 0;

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                    rp.ReservedStock = 0;
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return ord;
        }
        /// <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>
        /// Saves the and print STV.
        /// </summary>
        /// <param name="pickListDetail">The pick list detail.</param>
        /// <param name="deliveryNotePrinter">The delivery note printer.</param>
        /// <param name="stvPrinterName">Name of the STV printer.</param>
        /// <param name="dtDate">The dt date.</param>
        /// <param name="dtCurrent">The dt current.</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport SaveAndPrintSTV(DataView pickListDetail, bool isDeliveryNote, string printerName, DateTimePickerEx dtDate, DateTime dtCurrent)
        {
            HCMIS.Core.Distribution.Services.PrintLogService pLogService = new HCMIS.Core.Distribution.Services.PrintLogService();

            pLogService.StartPrintingSession();

            Order ord = IssueDoc.SaveIssueTransaction(_orderID, ref pickListDetail, txtRemarks.Text,
                                                      CurrentContext.LoggedInUserName, dtCurrent);

            if (pickListDetail.Count == 0)
                throw new Exception("An error occurred during saving the issue.  Please contact your administrator.");

            string sendToString = "";
            BLL.Order ordr = new BLL.Order();
            ordr.LoadByPrimaryKey(_orderID);
            BLL.Institution rus = new Institution();
            if (!ordr.IsColumnNull("RequestedBy"))
            {
                rus.LoadByPrimaryKey(ordr.RequestedBy);
                sendToString = rus.Name;
            }

            else if (!ordr.IsColumnNull("OrderTypeID") &&
                     ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER)
            {
                BLL.Transfer transfer = new Transfer();
                transfer.LoadByOrderID(_orderID);
                var activity = new Activity();
                activity.LoadByPrimaryKey(transfer.ToStoreID);
                sendToString = activity.FullActivityName;
            }

            PickList pl = new PickList();
            pl.LoadByOrderID(ord.ID);

            var xtraReport = new XtraReport();

            if (ord.PaymentTypeID == PaymentType.Constants.CASH)
            {
                xtraReport = FormatCashInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                  printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.CREDIT)
            {
                xtraReport = FormatCreditInvoice(ord, pickListDetail.Table, rus, pl, isDeliveryNote,
                                    printerName, pLogService);
            }
            else if (ord.PaymentTypeID == PaymentType.Constants.STV)
            {
                xtraReport = FormatSTV(ord, pickListDetail.Table, sendToString, pl, isDeliveryNote,
                          printerName,
                          pLogService, _orderID);
            }

            SavePdfReport(pLogService, xtraReport);
            pLogService.CommitPrintLog();
            return xtraReport;
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

            BLL.Order ord = new BLL.Order();
            ord.LoadByPrimaryKey(orderID);
            plst.LoadByOrderID(ord.ID);

            foreach (DataRowView drv in dvOutstandingPickList)
            {
                // Pseudo:
                // for each row in the picklist
                // undate the issue document
                // subtract the issued quantity from the receive doc
                // subtract the issued quantity from recieve pallet
                // subtract the issued the reserved quantity irregardless of the quantity issued.


                //Saving the new Issue issue
                if (Convert.ToDecimal(drv["BUPICKED"]) == 0)
                {
                    continue;
                }

                if (Convert.ToDecimal(drv["SKUPicked"]) != Convert.ToDecimal(drv["SKUTOPICK"]))
                {
                    drv["Cost"] = Convert.ToDecimal(drv["SKUPicked"]) * Convert.ToDecimal(drv["UnitPrice"]);
                }

                // Select the receive doc that is associated with this issue.
                recDoc.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveDocID"]));


                issDoc.AddNew();
                issDoc.StoreId = Convert.ToInt32(drv["StoreID"]);
                issDoc.RefNo   = ord.RefNo;
                if (!ord.IsColumnNull("RequestedBy"))
                {
                    issDoc.ReceivingUnitID = ord.RequestedBy;
                }
                // TOFIX:
                // TODO:
                // Lord have mercy kind of hack to avoid the feb date problem
                // this needs to be fixed for pagume also
                issDoc.Date           = etCurrentDate;
                issDoc.EurDate        = DateTimeHelper.ServerDateTime;
                issDoc.RecievDocID    = Convert.ToInt32(drv["ReceiveDocID"]);
                issDoc.IsApproved     = true;
                issDoc.IsTransfer     = false;
                issDoc.Remark         = remark;
                issDoc.ItemID         = Convert.ToInt32(drv["ItemID"]);
                issDoc.Quantity       = Convert.ToDecimal(drv["BUPICKED"]);
                issDoc.NoOfPack       = Convert.ToDecimal(drv["SKUPICKED"]);
                issDoc.QtyPerPack     = Convert.ToInt32(drv["SKUBU"]);
                issDoc.BatchNo        = drv["BatchNumber"].ToString();
                issDoc.UnitID         = recDoc.UnitID;
                issDoc.ManufacturerID = recDoc.ManufacturerId;
                if (drv["Cost"] != DBNull.Value)
                {
                    issDoc.Cost = Convert.ToDouble(drv["Cost"]);

                    issDoc.SellingPrice = Convert.ToDecimal(drv["UnitPrice"]);
                    if (!recDoc.IsColumnNull("Cost"))
                    {
                        issDoc.UnitCost = Convert.ToDecimal(recDoc.Cost);
                    }
                }
                issDoc.OrderID  = orderID;
                issDoc.IssuedBy = issuedBy;
                // TODO: is this the right place where we need to pick the physical store ID from?
                // check it against the receipt pallet physical store.
                if (!recDoc.IsColumnNull("PhysicalStoreID"))
                {
                    issDoc.PhysicalStoreID = recDoc.PhysicalStoreID;
                }
                if (!recDoc.IsColumnNull("InventoryPeriodID"))
                {
                    //Todo: Remove for Inventory
                    issDoc.InventoryPeriodID = recDoc.InventoryPeriodID;
                }
                if (!recDoc.IsColumnNull("Margin"))
                {
                    issDoc.Margin = (decimal)recDoc.Margin;
                }
                //Replaced by
                issDoc.PLDetailID = Convert.ToInt32(drv["PLDetailID"]);
                BLL.Balance    bal = new Balance();
                BLL.ReceiveDoc rd  = new ReceiveDoc();
                rd.LoadByPrimaryKey(issDoc.RecievDocID);
                decimal currentBalance = bal.GetSoh(issDoc.ItemID, rd.UnitID, issDoc.StoreId, issDoc.Date.Month, issDoc.Date.Year);
                if (currentBalance < issDoc.NoOfPack)
                {
                    throw new Exception(string.Format("The item {0} is not available in {1} Qty.", drv["FullItemName"].ToString(), issDoc.NoOfPack));
                }

                // This is a field that is not applicable on the hub edition
                // It is about the dispensing unit quantity and there is no such thing as Dispensing unit
                // in the hub edition
                issDoc.DUSOH         = 0;
                issDoc.RecomendedQty = 0;// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                // End DU
                issDoc.DispatchConfirmed = false;
                issDoc.Save();
                drv["IssueDocID"] = issDoc.ID;
                // updating the receiving doc

                //long prevQuantityLeft = recDoc.QuantityLeft;

                recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;

                if (recDoc.QuantityLeft < 0)
                {
                    //Possibly the wrong ReceiveDoc Entry chosen
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }
                //long
                recDoc.Out = (recDoc.QuantityLeft == 0) ? true : false;
                recDoc.Save();

                ReceivePallet rp = new ReceivePallet();
                int           id = Convert.ToInt32(drv["ReceivePalletID"]);
                rp.LoadByPrimaryKey(id);
                if (rp.IsColumnNull("Balance"))
                {
                    rp.Balance = rp.ReceivedQuantity;
                }
                rp.Balance -= issDoc.Quantity;

                if (rp.Balance < 0)
                {
                    BLL.Item itm = new Item();
                    itm.LoadByPrimaryKey(recDoc.ItemID);
                    throw new Exception(string.Format("Quantity problem detected for the item {0}", itm.FullItemName));
                }

                decimal totReservedQty = Convert.ToDecimal(drv["QuantityInBU"]);

                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = 0;
                }

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }