/// <summary>
        /// Gets all SOH for print out.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="year">The year.</param>
        /// <param name="month">The month.</param>
        /// <returns></returns>
        public static DataTable GetAllSOHForPrintOut(int userId, int year, int month)
        {
            DataTable datatable = null;

            Activity stores = new Activity();
            stores.LoadByUserID(userId);
            Balance balance = new Balance();
            while(!stores.EOF){
                string account = stores.FullActivityName;
                if(datatable == null){
                    var query = HCMIS.Repository.Queries.Balance.SelectGetAllSOHForPrintOutInitial(stores.ID);
                    balance.LoadFromRawSql( query );
                    datatable = balance.DataTable;
                    datatable.Columns.Add("Account");
                    foreach (DataRow dr in datatable.Rows)
                    {
                        dr["Account"] = account;
                    }
                }else{
                    var query = HCMIS.Repository.Queries.Balance.SelectGetAllSOHForPrintOut(stores.ID);
                    balance.LoadFromRawSql(query);
                    DataTable dtbl = balance.DataTable;
                    dtbl.Columns.Add("Account");
                    foreach(DataRow dr in dtbl.Rows){
                        dr["Account"] = account;
                        datatable.ImportRow(dr);
                    }
                }
                stores.MoveNext();
            }
            return datatable;
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var dvPickListMakeup = (DataTable)gridTransactions.DataSource;

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

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

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

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

            pl.ShowPreviewDialog();
            // refresh the display
            lstRefNo_FocusedNodeChanged(null, null);
        }
 private void BindFormElements()
 {
     Activity stores = new Activity();
     stores.LoadAll();
     cmbLogicalStore.Properties.DataSource = stores.DefaultView;
     stores.Rewind();
     cmbLogicalStore.EditValue = stores.ID;
     radioLogicalStore_SelectedIndexChanged(new object(), new EventArgs());
 }
 /// <summary>
 /// Loads the by user ID.
 /// </summary>
 /// <param name="userID">The user ID.</param>
 public void LoadByUserID(int userID)
 {
     string query = HCMIS.Repository.Queries.UserActivity.SelectLoadByUserID(userID);
     this.LoadFromRawSql(query);
     // TO Clean: This
     while (!EOF)
     {
         Activity activity = new Activity();
         activity.LoadByPrimaryKey(Getint("StoreID"));
         SetColumn("StoreName", activity.FullActivityName);
         MoveNext();
     }
     this.Rewind();
 }
 /// <summary>
 /// Generates the matrix for A new user.
 /// </summary>
 /// <param name="userID">The user ID.</param>
 public void GenerateMatrixForANewUser(int userID)
 {
     BLL.Activity store = new Activity();
     store.LoadAll();
     while (!store.EOF)
     {
         BLL.UserActivity usrStore = new UserActivity();
         usrStore.AddNew();
         usrStore.UserID = userID;
         usrStore.ActivityID = store.ID;
         usrStore.CanAccess = false;
         usrStore.IsDefault = false;
         usrStore.Save();
         store.MoveNext();
     }
 }
        private void OrderDetailForm_Load(object sender, EventArgs e)
        {
            Item item = new Item();
            item.LoadByPrimaryKey(_itemID);

            txtItemName.Text = item.FullItemName;

            ItemUnit iu = new ItemUnit();
            iu.LoadByPrimaryKey(_unitID);
            txtUnit.Text = iu.Text;

            BLL.Balance balance = new Balance();
            gridApprovedPrinted.DataSource = balance.GetApprovedValueForFacility(CurrentContext.UserId, item.ID, iu.ID);

            gridPicklistPrinted.DataSource = balance.GetPicklistedValueForFacility(CurrentContext.UserId, item.ID, iu.ID);

            var activities = new Activity();
            activities.LoadByUserID(CurrentContext.UserId);

            DataTable dtbl = null;
            while (!activities.EOF)
            {
                DataTable dt = balance.GetSOHForAnItem(activities.ID, item.ID, iu.ID);
                if (dt != null && dt.Rows.Count > 0)
                {
                    dt.Columns.Add("Account");
                    dt.Rows[0]["Account"] = activities.FullActivityName;
                    if (dtbl == null && Convert.ToInt32(dt.Rows[0]["SOH"]) > 0)
                    {
                        dtbl = dt;
                    }
                    else if (Convert.ToInt32(dt.Rows[0]["SOH"]) > 0)
                    {
                        dtbl.ImportRow(dt.Rows[0]);
                    }
                }
                activities.MoveNext();
            }

            gridItemStockStatus.DataSource = dtbl;
            this.Text = string.Format("({0} - {1}) Details of : {2}", _itemID, _unitID, item.FullItemName);
        }
        public DataTable GetSavedRRFForDisplay()
        {
            this.FlushData();
            string query = HCMIS.Repository.Queries.RRF.SelectGetSavedRRFForDisplay();
            this.LoadFromRawSql(query);
            this.AddColumn("DateOfSubmissionEth", typeof(string));
            this.AddColumn("RRFTypeText", typeof(string));

            while (!this.EOF)
            {
                string ethDate = this.IsColumnNull("DateOfSubmission")
                                     ? ""
                                     : EthiopianDate.EthiopianDate.GregorianToEthiopian(this.DateOfSubmission);
                this.SetColumn("DateOfSubmissionEth", ethDate);

                Activity str = new Activity();
                str.LoadByPrimaryKey(this.RRFType);
                this.SetColumn("RRFTypeText", str.FullActivityName);
                this.MoveNext();
            }
            return this.DataTable;
        }
        public static Order GenerateOrder(int? orderID, int orderTypeID, int orderStatusID, int activityID, int paymentTypeID, string contactPerson, int? requestedBy, int userID, int? refNo = null)
        {
            var requisitionType = new RequisitionType();
            int requisitionTypeID = Convert.ToInt32(requisitionType.LoadIDByCode("DMN")["RequisitionTypeID"]);
            Order or = new Order();
            if (orderID == null)
            {
                or.AddNew();
            }
            else
            {
                or.LoadByPrimaryKey(orderID.Value);
            }

            or.RefNo = refNo == null ? GetNextOrderReference() : refNo.ToString();
            var oldOrderStatus = or.IsColumnNull("OrderStatusID") ? (int?)null : or.OrderStatusID;
            or.OrderStatusID = orderStatusID;
               // or.RequisitionTypeID = RequisitionType.CONSTANTS.DEMAND;
            or.RequisitionTypeID = requisitionTypeID;

            or.EurDate = or.Date = DateTimeHelper.ServerDateTime;

            if (requestedBy != null)
            {
                or.RequestedBy = requestedBy.Value;
            }

            or.FilledBy = userID;
            or.ContactPerson = contactPerson;
            var activity = new Activity();
            activity.LoadByPrimaryKey(activityID);
            or.FromStore = activity.ModeID;
            or.PaymentTypeID = paymentTypeID;
            or.FiscalYearID = FiscalYear.Current.ID;
            or.OrderTypeID = orderTypeID;
            or.Save();
            or.LogRequisitionStatus(or.ID, oldOrderStatus, orderStatusID, CurrentContext.UserId);
            return or;
        }
        public static Reports.BinCardReport CreateBinCard(int activityID, int itemID, int unitID, int warehouse,DateTime? startDate=null,DateTime? endDate =null)
        {
            BLL.Balance balance = new Balance();

            BLL.Item item = new Item();
            item.LoadByPrimaryKey(itemID);

            ItemUnit iunit = new ItemUnit();
            iunit.LoadByPrimaryKey(unitID);

            Activity activity = new Activity();
            activity.LoadByPrimaryKey(activityID);
            var dataView = new DataView();
            if (startDate == null || endDate == null)
            {
                dataView = Balance.GetBinCardByWarehouse(activityID, itemID, unitID, EthiopianDate.EthiopianDate.Now.FiscalYear,
                                          warehouse);
            }
            else
            {
                dataView = Balance.GetBinCardByDate(activityID, itemID, unitID, warehouse,startDate.Value,endDate.Value);
            }
            BinCardReport report = new BinCardReport();
            report.DataSource = dataView;

            report.StockCode.Text = item.StockCode;
            report.Description.Text = item.FullItemName;
            report.Unit.Text = iunit.Text;

            report.ItemSource.Text = activity.FullActivityName;

            // TODO: add the Item Source Here (the suggested interpretation is that item source is supplier)
            report.PrintedBy.Text = string.Format("Generated By: {0} On {1}", CurrentContext.LoggedInUserName,
                                                  BLL.DateTimeHelper.ServerDateTime.ToString("dd-MM-yyyy hh:mm tt"));
            report.AppVersion.Text = "HCMIS";
            return report;
        }
        private void gridGRVs_MouseClick(object sender, MouseEventArgs e)
        {
            DataRow SelectGRV = gridGRVsView.GetFocusedDataRow();
            if (SelectGRV != null)
            {
                ReceiptID = Convert.ToInt32(SelectGRV["ReceiptID"]);
                PONumber = Convert.ToString(SelectGRV["PONumber"]);
                LoadSelectedGRVDetailForInvoiceEntry(ReceiptID);

                txtOrderNo.EditValue = SelectGRV["PONumber"];

                txtInvoiceNo.EditValue = SelectGRV["InvoiceNumber"];
                string space = "";
                 int length = ((string) SelectGRV["InvoiceNumber"]).Length;
                 lcgInvoiceNo.Text = "Invoice No: " + (string)SelectGRV["InvoiceNumber"] + space.PadRight(180 - length) + "GRNF No: " + (string)SelectGRV["RefNo"].ToString();

                 lblMode.Text = (string)SelectGRV["Mode"] ?? "-";
                 lblAccount.Text = (string)SelectGRV["AccountName"] ?? "-";
                 lblSubAccount.Text = (string)SelectGRV["SubAccountName"] ?? "-";
                 lblActivity.Text = (string)SelectGRV["ActivityName"] ?? "-";
                 lblWarehouse.Text = (string)SelectGRV["WarehouseName"] ?? "-";

                 lblCluster.Text = (string)SelectGRV["ClusterName"] ?? "-";
                 lblReceiptType.Text = (string)SelectGRV["ReceiveType"] ?? "-";
                 lblReceiptStatus.Text = (string)SelectGRV["ReceiveStatus"] ?? "-";
                 lblSupplier.Text = (string)SelectGRV["SupplierName"] ?? "-";
                 lblOrderNo.Text = (string)SelectGRV["PONumber"] ?? "-";

                lblConfirmedBy.Text = SelectGRV["ConfirmedBy"] == DBNull.Value ? "-" : (string)SelectGRV["ConfirmedBy"];

                lblConfirmedDate.Text = SelectGRV["ConfirmedTime"] != DBNull.Value
                    ? Convert.ToDateTime(SelectGRV["ConfirmedTime"]).ToShortDateString()
                    : "-";

                lblReceivedBy.Text = (string)SelectGRV["ReceivedBy"] ?? "-";
                lblReceiptDate.Text = ((DateTime)SelectGRV["ReceivedTime"]).ToShortDateString() ?? "-";
                lblInsurance.Text = SelectGRV["InsuranceNumber"] == DBNull.Value ? "" : (string)SelectGRV["InsuranceNumber"] ?? "-";

                txtInsuranceNo.EditValue = SelectGRV["InsuranceNumber"];
                lblInsurancePolicyNo.Text = SelectGRV["InsuranceNumber"].ToString() ?? "-";
                txtTransfer.EditValue = SelectGRV["TransitNumber"];
                lblTransferNo.Text = SelectGRV["TransitNumber"].ToString() ?? "-";
                txtWayBill.EditValue = SelectGRV["WayBillNumber"];
                lblWayBillNo.Text = SelectGRV["WayBillNumber"].ToString() ?? "-";
                Activity Activity = new Activity();
                Activity.LoadByPrimaryKey(Convert.ToInt32(SelectGRV["StoreID"]));
                txtActivity.EditValue = Activity.FullActivityName;
                lblActivity.Text = Activity.FullActivityName ?? "-";

                var logReceiptStatus = new LogReceiptStatus();
                var dtHistory = logReceiptStatus.GetLogHistory(ReceiptID, "PRC");

                if (dtHistory != null && dtHistory.Count > 0)
                {
                    lblCalcuatedBy.Text =(string)dtHistory[0]["FullName"];
                    lblCalculatedDate.Text = ((DateTime)dtHistory[0]["Date"]).ToShortDateString();
                }
                else
                {
                    lblCalculatedDate.Text = lblCalcuatedBy.Text = "-";
                }
            }
            else
            {
                ResetForm();
            }
        }
        /// <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>
 /// Renews the matrix for A user.
 /// </summary>
 /// <param name="userID">The user ID.</param>
 public void RenewMatrixForAUser(int userID)
 {
     BLL.Activity store = new Activity();
     store.LoadAll();
     while (!store.EOF)
     {
         BLL.UserActivity usrStore = new UserActivity();
         this.LoadByUserAndStoreID(userID,store.ID);
         if (this.RowCount == 0)
         {
             usrStore.AddNew();
             usrStore.UserID = userID;
             usrStore.ActivityID = store.ID;
             usrStore.CanAccess = false;
             usrStore.IsDefault = false;
             usrStore.Save();
         }
         store.MoveNext();
     }
 }
        private int SaveRelevantReceiptHeaders(int receiptTypeID, int warehouseID)
        {
            int receiptID;
            var receipt = new BLL.Receipt();
            var sup = new BLL.Supplier();

            if (lkReceiptInvoice.EditValue != null && Convert.ToInt32(lkReceiptInvoice.EditValue) != -1)
            {
                receiptID = receipt.AddNewReceipt(receiptTypeID, warehouseID, CurrentContext.UserId,
                    Convert.ToInt32(lkReceiptInvoice.EditValue), txtEditTransferNo.Text,
                    ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED);
                // , txtTransitNo.Text, txtInsuranceNo.Text, txtWayBillNo.Text);
            }
            else
            {
                //PO and ReceiptInvoice created automatically.
                //Needs to be fixed.
                BLL.PO po = new PO();
                BLL.ReceiptInvoice rctInvoice = new ReceiptInvoice();

                po.AddNew();
                var serverDateTime = DateTimeHelper.ServerDateTime;
                po.PODate = serverDateTime;
                po.DateOfEntry = serverDateTime;
                po.PurchaseType = POType.INVENTORY;
                po.IsElectronic = false;
                po.POFinalized = false;
                po.Rowguid = Guid.NewGuid();
                po.Identifier = "00000";

                po.PaymentTypeID = BLL.PaymentType.Constants.STV;
                po.TermOfPayement = BLL.PaymentTerm.Internal;
                po.PurchaseOrderStatusID = PurchaseOrderStatus.Processed;

                rctInvoice.AddNew();

                po.StoreID = Convert.ToInt32(lkAccounts.EditValue);
                Activity acc = new Activity();
                acc.LoadByPrimaryKey(po.StoreID);
                po.ModeID = acc.ModeID;

                //po.PONumber = srm ? lkSTVInvoiceNo.EditValue.ToString() : (deliveryNote ? txtRefNo.Text : (beginningBalance ? "BeginningBalance" : String.Empty));

                if (lcSTVNo.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                {
                    po.PONumber = srm && !chkSRMForOldSystemIssues.Checked
                        ? txtSTVNo.Text
                        : ((deliveryNoteType != DeliveryNoteType.NotSet)
                            ? txtSTVNo.Text
                            : (beginningBalance
                                ? "BeginningBalance"
                                : (srm && chkSRMForOldSystemIssues.Checked
                                    ? txtSTVInvoiceNoOldSystem.Text
                                    : txtRefNo.Text)));
                }
                else
                {
                    po.PONumber = srm && !chkSRMForOldSystemIssues.Checked
                        ? lkSTVInvoiceNo.Text
                        : ((deliveryNoteType != DeliveryNoteType.NotSet)
                            ? txtRefNo.Text
                            : (beginningBalance
                                ? "BeginningBalance"
                                : (srm && chkSRMForOldSystemIssues.Checked
                                    ? txtSTVInvoiceNoOldSystem.Text
                                    : txtRefNo.Text)));
                }

                   //TODO: Ugly hack, supplier. To be fixed.
                    if (srm)
                    {
                        po.SupplierID = BLL.Supplier.CONSTANTS.RETURNED_FROM_FACILITY;

                        //Let's put Finance Required stuff here.
                        po.Insurance = 0;
                        po.ExhangeRate = 1;
                        rctInvoice.ExchangeRate = 1;
                        rctInvoice.Insurance = 0;

                        rctInvoice.InvoiceTypeID = ReceiptInvoiceType.InvoiceType.LOCAL_PURCHASE;

                        if (chkSRMForOldSystemIssues.Checked)
                        {
                            if (lkForFacility.EditValue == null)
                                throw new Exception("Facility not chosen!");
                            po.RefNo = lkForFacility.EditValue.ToString();
                        }
                    }

                po.SavedbyUserID = CurrentContext.LoggedInUser.ID;
                po.Save();

                rctInvoice.POID = po.ID;
                if (lcSTVNo.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                {
                    rctInvoice.STVOrInvoiceNo = srm && !chkSRMForOldSystemIssues.Checked
                        ? txtSTVNo.Text
                        : ((deliveryNoteType != DeliveryNoteType.NotSet)
                            ? txtSTVNo.Text
                            : (beginningBalance
                                ? "BeginningBalance"
                                : (srm && chkSRMForOldSystemIssues.Checked
                                    ? txtSTVInvoiceNoOldSystem.Text
                                    : txtSTVNo.Text)));
                }
                else
                {
                    rctInvoice.STVOrInvoiceNo = srm && !chkSRMForOldSystemIssues.Checked
                        ? lkSTVInvoiceNo.Text
                        : ((deliveryNoteType != DeliveryNoteType.NotSet)
                            ? txtRefNo.Text
                            : (beginningBalance
                                ? "BeginningBalance"
                                : (srm && chkSRMForOldSystemIssues.Checked
                                    ? txtSTVInvoiceNoOldSystem.Text
                                    : txtRefNo.Text)));
                }
                rctInvoice.DateOfEntry = DateTimeHelper.ServerDateTime;
                rctInvoice.ActivityID = po.StoreID;
                rctInvoice.SavedByUserID = CurrentContext.LoggedInUser.ID;
                rctInvoice.IsDeliveryNote = false;

                rctInvoice.Rowguid = Guid.NewGuid();
                rctInvoice.PrintedDate = po.DateOfEntry;
                rctInvoice.IsVoided = false;
                rctInvoice.ShippingSite = " ";
                rctInvoice.IsConvertedFromDeliveryNote = false;
                rctInvoice.IsDeliveryNote = false;
                rctInvoice.DocumentTypeID = DocumentType.CONSTANTS.SRM;

                rctInvoice.Save();

                receiptID = receipt.AddNewReceipt(receiptTypeID, warehouseID, CurrentContext.UserId, rctInvoice.ID,
                    txtTransitTransferVoucherNo.Text, ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED);

                //receiptID = receipt.AddNewReceipt(receiptTypeID, NewMainWindow.UserId);
            }
            return receiptID;
        }
        public static LookUpEditBase SetDefaultMode(this LookUpEditBase editor)
        {
            if (_activity == null)
            {
                _activity = new Activity();
                _activity.LoadDefaultByUser(CurrentContext.UserId);
            }

            if (_activity.RowCount > 0)
            {
                editor.EditValue = _activity.ModeID;
            }
            return editor;
        }
 private static void BindAllowedActivities(this LookUpEditBase editor)
 {
     if (_activities == null)
     {
         _activities = new Activity();
         _activities.LoadByUserID(CurrentContext.UserId);
     }
     editor.Properties.DataSource = _activities.DefaultView;
 }
        private void PrintReceiptConfirmation(string referenceNumber, int? reprintOfReceiptConfirmationPrintoutID)
        {
            ReceiptConfirmationPrintout rc = new ReceiptConfirmationPrintout();
            HCMIS.Desktop.Reports.ReceiptConfirmationPrintout printout = new HCMIS.Desktop.Reports.ReceiptConfirmationPrintout(CurrentContext.LoggedInUserName);

            HCMIS.Desktop.Reports.SRMPrintout srmPrintout = new HCMIS.Desktop.Reports.SRMPrintout(CurrentContext.LoggedInUserName);

            int ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);
            BLL.ReceiveDoc receiveDoc = new ReceiveDoc();
            //  receiveDoc.LoadByReferenceNo(reference);
            receiveDoc.LoadByReceiptID(ReceiptID);
            BLL.Supplier supplier = new Supplier();
            supplier.LoadByPrimaryKey(receiveDoc.SupplierID);

            int printedID = 0;
            int GRNFNo = BLL.ReceiptConfirmationPrintout.GetGRNFNo(ReceiptID);
            if (currentMode == Modes.DeliveryNotePrinting)
            {

                printout.BranchName.Text = GeneralInfo.Current.HospitalName;

                printout.xrGRVLabel.Text = "Delivery Note.";
                printout.xrAir.Visible = false;
                printout.xrAirValue.Visible = false;
                printout.xrTransit.Visible = false;
                printout.xrTransitValue.Visible = false;
                printout.xrInsurance.Visible = false;
                printout.xrInsuranceValue.Visible = false;
                printout.xrNumberOfCases.Visible = false;
                printout.xrNumberOfCasesValue.Visible = false;
                printout.xrInvoiceNo.Visible = false;

                printout.xrInvoiceNoValue.Visible = false;
                printout.xrPurchaseOrderNo.Visible = false;
                printout.xrPurchaseOrderNoValue.Visible = false;

                printout.xrSTV.Visible = false;
                printout.xrSTVNoValue.Visible = false;

                printout.DataSource = rc.PrepareDataForPrintout(ReceiptID, CurrentContext.UserId, false, 5, null, reprintOfReceiptConfirmationPrintoutID,FiscalYear.Current);

                CalendarLib.DateTimePickerEx dtDate = new CalendarLib.DateTimePickerEx();
                //dtDate.CustomFormat = "dd/MM/yyyy";
                dtDate.Value = receiveDoc.EurDate;

                printout.Date.Text = dtDate.Text;
            }

            var activity = new Activity();
            activity.LoadByPrimaryKey(receiveDoc.StoreID);
            printout.xrLabelStoreName.Text = activity.FullActivityName;

            if (ReceiveDoc.IsThereShortageOrDamage(ReceiptID))
            {
                HCMIS.Desktop.Reports.ReceiptConfirmationShortagePrintout printoutShortage =
                    PrintReceiptConfirmationForShortage(referenceNumber, printedID);

                printout.xrShortageReport.ReportSource = printoutShortage;

                printout.PrintingSystem.ContinuousPageNumbering = true;
            }
            else
            {
               printout.ReportFooter.Visible = false;
            }

            //Successfully printed

            //Release Product
            CostCalculator GRV = new CostCalculator();
            GRV.LoadGRV(ReceiptID);
            GRV.ReleaseForIssue();

            String reference = gridReceiveView.GetFocusedDataRow()["RefNo"].ToString();
            BLL.ReceiveDoc recDoc = new ReceiveDoc();
            recDoc.LoadByReferenceNo(reference);
            recDoc.ConfirmGRVPrinted(CurrentContext.UserId);
            BindFormContents();
        }
        public static BaseEdit SetDefaultActivity(this BaseEdit editor)
        {
            if (_activity == null)
            {
                _activity = new Activity();
                _activity.LoadDefaultByUser(CurrentContext.UserId);
            }

            if (_activity.RowCount > 0)
            {
                editor.EditValue = _activity.ID;
            }
            return editor;
        }
        /// <summary>
        /// Gets the next GRV number.
        /// </summary>
        /// <param name="storeID">The store ID.</param>
        /// <param name="receiptTypeID">The receipt type ID.</param>
        /// <param name="preGRVorGRVOrSRM">The pre GR vor GRV or SRM.</param>
        /// <returns></returns>
        /// <summary>
        /// Adds the new.
        /// </summary>
        /// <param name="printedConfirmationNumber">The printed confirmation number.</param>
        /// <param name="storeID">The store ID.</param>
        /// <param name="supplierID">The supplier ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="receiptID">The receipt ID.</param>
        /// <param name="grvOrPreGRVorSRM">The GRV or pre GR vor SRM.</param>
        /// <param name="isReprintOfRCNo">The is reprint of RC no.</param>
        private int AddNew(int storeID, int? supplierID, int? userID, int receiptID, int grvOrPreGRVorSRM, int? isReprintOfRCNo)
        {
            //1-PreGRV,2-GRV,3-SRM,4-iGRV,5-DeliveryNote

            AddNew();
            PrintedDate = DateTimeHelper.ServerDateTime;
            StoreID = storeID;

            if (supplierID.HasValue)
                SupplierID = supplierID.Value;
            if (userID.HasValue)
                UserID = userID.Value;
            ReceiptID = receiptID;
            FiscalYearID = FiscalYear.Current.ID;

            Activity activity = new Activity();
            activity.LoadByPrimaryKey(storeID);
            AccountID = activity.AccountID;

            //This has been Added to maintain the grvOrPreGRVorSRM(the variable with a funny name)
            //Which should be removed soon
            if (grvOrPreGRVorSRM == 1)
            {
                Reason = "PGRV";
                DocumentTypeID = DocumentType.documentTypes.GRNF.DocumentTypeID;
            }
            else if (grvOrPreGRVorSRM == 2)
            {
                Reason = "GRV";
                DocumentTypeID = DocumentType.documentTypes.GRV.DocumentTypeID;

            }
            else if (grvOrPreGRVorSRM == 3)
            {
                Reason = "SRM";
                DocumentTypeID = DocumentType.documentTypes.SRM.DocumentTypeID;

            }
            else
            {
                Reason = "iGRV";
                DocumentTypeID = DocumentType.documentTypes.IGRV.DocumentTypeID;

            }

            if (isReprintOfRCNo.HasValue)
            {
                IsReprintOf = isReprintOfRCNo.Value;
            }
            IDPrinted = DocumentType.GetNextSequenceNo(DocumentTypeID, AccountID, FiscalYearID);
            Save();
            return IDPrinted;
        }
        private void DatabaseInteractivityUtility_Load(object sender, EventArgs e)
        {
            SetPermission();
            PreparePrintLog();
            var activity = new Activity();
            activity.LoadAll();
            lkStoreLocation.Properties.DataSource = activity.DefaultView;

            txtEditVersion.Text = Program.HCMISVersionStringShort;

            try
            {
                txtItemID.Text = _itemID == 0 ? "" : _itemID.ToString();
                if (txtItemID.Text != "")
                    btnGo_Click(null, null);
            }
            catch
            {
            }
        }
        /// <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;
        }
        private void RrfFormLoad(object sender, EventArgs e)
        {
            PopulateTheMonthCombos(cboFromMonth);
            PopulateTheMonthCombos(cboToMonth);
            PopulateTheYearCombo(cboFromYear);
            PopulateTheYearCombo(cboToYear);
            var stor = new Activity();
            stor.LoadAll();
            cboStores.Properties.DataSource = stor.DefaultView;
            PopulateRrFs();
            WindowVisibility(false);
            EnableDisableStatusCheck();

            btnAutoPushToPFSA.Enabled = BLL.Settings.AllowOnlineOrders;
        }
        /// <summary>
        /// Reorganizes the data view for STV print_ program.
        /// </summary>
        /// <param name="dv">The dv.</param>
        /// <param name="refNo">The ref no.</param>
        /// <param name="pickListId">The pick list id.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="stvLogID">The STV log ID.</param>
        /// <param name="convertDNtoSTV">if set to <c>true</c> [convert D nto STV].</param>
        /// <param name="generateNewPrintID">if set to <c>true</c> [generate new print ID].</param>
        /// <param name="hasInsurance">if set to <c>true</c> [has insurance].</param>
        /// <returns></returns>
        public static DataTable ReorganizeDataViewForSTVPrint_Program(DataView dv, int orderID, int pickListId, int userID, int? stvLogID, bool convertDNtoSTV, bool generateNewPrintID, bool hasInsurance)
        {
            BLL.Order order = new Order();
            order.LoadByPrimaryKey(orderID);
            int? paymentTypeID = null;

            if (order.PaymentTypeID == PaymentType.Constants.CASH || order.PaymentTypeID == PaymentType.Constants.CREDIT || order.PaymentTypeID == PaymentType.Constants.STV)
            {
                paymentTypeID = order.PaymentTypeID;
            }

            // This is just to make the delivery notes print a separate series of numbers.
            // This section completely asks for a re-write.
            if (dv.Count > 0 && (dv[0]["Cost"] == DBNull.Value || Convert.ToDecimal(dv[0]["Cost"]) == 0M))
            {
                paymentTypeID = PaymentType.Constants.DELIVERY_NOTE;
            }
            else if (stvLogID != null)
            {
                Issue issue = new Issue();
                issue.LoadByPrimaryKey(stvLogID.Value);

                if (!issue.IsColumnNull("IsDeliveryNote") && issue.IsDeliveryNote && !convertDNtoSTV)
                {
                    paymentTypeID = PaymentType.Constants.DELIVERY_NOTE;
                }
            }

            // prepare the pick list for printing.
            // this method only merges the items that come in different rows but ...
            // that have same price same item.
            DataTable dtbl = dv.Table.Clone();

            if (!dtbl.Columns.Contains("Supplier"))
            {
                dtbl.Columns.Add("Supplier");
            }
            if (!dtbl.Columns.Contains("SupplierID"))
            {
                dtbl.Columns.Add("SupplierID");
            }
            dtbl.Columns.Add("STVNumber");
            dtbl.Columns.Add("StoreName");
            dtbl.Columns.Add("ContactPerson");
            dtbl.Columns.Add("PhysicalStoreType"); //The virtual store (The grouping for the stores) for the display on the stv

            dtbl.Clear();
            foreach (DataRowView drv in dv)
            {
                if (dtbl.Rows.Count == 0)
                {
                    dtbl.ImportRow(drv.Row);
                }

                else
                {

                    //check if items with same expiry exists in the table
                    //TOFIX: Add the supplier in this mix

                    string qItemID = "", qbatchNumberID = "", qUnitPriceID = "", qPhysicalStoreName = "", qStoreID = "";

                    qItemID = string.Format("ItemID={0} and UnitID={1}", drv["ItemID"].ToString(), drv["UnitID"]);

                    if (drv["BatchNumber"] != DBNull.Value)
                        qbatchNumberID = string.Format(" and BatchNumber='{0}'", drv["BatchNumber"].ToString());
                    if (drv["UnitPrice"] != DBNull.Value)
                        qUnitPriceID = string.Format(" and UnitPrice = {0} ", drv["UnitPrice"].ToString());
                    if (drv["PhysicalStoreName"] != DBNull.Value)
                        qPhysicalStoreName = string.Format(" and PhysicalStoreName= '{0}'",
                                                           drv["PhysicalStoreName"].ToString());
                    if (drv["StoreID"] != DBNull.Value)
                        qStoreID = string.Format(" and StoreID= '{0}'", drv["StoreID"].ToString());

                    string query = string.Format("{0}{1}{2}{3}{4}", qItemID, qbatchNumberID, qUnitPriceID,
                                                 qPhysicalStoreName, qStoreID);
                    DataRow[] ar = dtbl.Select(query);
                    if (ar.Length > 0)
                    {
                        //
                        foreach (var dataRow in ar)
                        {
                            dataRow["SKUPICKED"] = Convert.ToInt32(dataRow["SKUPICKED"]) +
                                                   Convert.ToInt32(drv["SKUPICKED"]);
                            dataRow["Cost"] = (dataRow["Cost"] != DBNull.Value ? Convert.ToDouble(dataRow["Cost"]) : 0) +
                                              (drv["Cost"] != DBNull.Value ? Convert.ToDouble(drv["Cost"]) : 0);
                            dataRow["IssueDocID"] = dataRow["IssueDocID"].ToString() + ',' +
                                                    drv["IssueDocID"].ToString();
                            dataRow.EndEdit();
                            // If we have been here before, no need to do it again.
                            // this means the same amount is printed duplicated.
                            break;
                        }
                    }
                    else
                    {
                        dtbl.ImportRow(drv.Row);
                    }
                }

            }

            Supplier supplier = new Supplier();
            ReceiveDoc rd = new ReceiveDoc();

            // First sort the Data Table by Supplier
            // then create STV Number for each supplier

            foreach (DataRowView drw in dtbl.DefaultView)
            {
                rd.LoadByPrimaryKey(Convert.ToInt32(drw["ReceiveDocID"]));
                if (rd.RowCount > 0)
                {
                    supplier.LoadByPrimaryKey(rd.SupplierID);
                    // Add the supplier to the table
                    drw["SupplierID"] = supplier.ID;
                    drw["Supplier"] = supplier.CompanyName;
                    drw.EndEdit();
                }
            }

            int supplierId = 0;
            int storeID = 0;
            int phyStoreTypeID = 0;
            bool isManufacturerLocal = false;
            int storeGroupID = 0;
            string storeName = "";

            int lineNumber = 1;
            int rowsOnPaper = 1;
            int maxLinesOnPage = 15;

            string stvNo = "";
            string stvNoForPrint = "";
            int stvID = -1;

            dtbl.DefaultView.Sort = "PhysicalStoreTypeName, StoreGroupID,StoreID,IsManufacturerLocal, CommodityType, FullItemName";

            string commodityType = "";
            foreach (DataRowView drw in dtbl.DefaultView)
            {
                //if ((BLL.Settings.IsRdfMode && (palletLocationID != Convert.ToInt32(drw["PalletLocationID"]) || storeID != Convert.ToInt32(drw["StoreID"]))) || (Convert.ToInt32(drw["SupplierID"]) != supplierId) || lineNumber > 13)

                if (commodityType == "")
                    commodityType = drw["CommodityType"].ToString();

                if ((drw["PhysicalStoreTypeID"] != DBNull.Value) && phyStoreTypeID != Convert.ToInt32(drw["PhysicalStoreTypeID"]) || (commodityType != drw["CommodityType"].ToString() && !BLL.Settings.PrintMultipleCommodityTypesPerPage) || (isManufacturerLocal != bool.Parse(drw["IsManufacturerLocal"].ToString()) || storeGroupID != Convert.ToInt32(drw["StoreGroupID"]) || storeID != Convert.ToInt32(drw["StoreID"]) || (rowsOnPaper + (Convert.ToInt32(drw["FullItemName"].ToString().Length / 32))) > maxLinesOnPage))// lineNumber > 10)
                {

                    lineNumber = 1;
                    rowsOnPaper = 1;

                    supplierId = Convert.ToInt32(drw["SupplierID"]);
                    storeGroupID = Convert.ToInt32(drw["StoreGroupID"]);
                    storeID = Convert.ToInt32(drw["StoreID"]);
                    var activity = new Activity();
                    activity.LoadByPrimaryKey(storeID);
                    storeName = activity.FullActivityName;

                    isManufacturerLocal = Convert.ToBoolean(drw["IsManufacturerLocal"]);

                    if (drw["PhysicalStoreTypeID"] != DBNull.Value)
                    {
                        phyStoreTypeID = Convert.ToInt32(drw["PhysicalStoreTypeID"]);
                    }

                    // Pseudo:
                    // Get hub details from the general info table
                    // prepare the printable data
                    // bind the printable data and GO

                    Issue stvLog = new Issue();
                    if (BLL.Settings.UseHeadedSTV && generateNewPrintID)
                    {
                        stvLog.AddNew();
                        stvLog.PrintedDate = DateTimeHelper.ServerDateTime;
                        stvLog.RefNo = order.RefNo;
                        stvLog.PickListID = pickListId;
                        stvLog.SupplierID = supplierId;
                        stvLog.UserID = userID;
                        stvLog.StoreID = storeID;
                         stvLog.IsDeliveryNote = (paymentTypeID == PaymentType.Constants.DELIVERY_NOTE);
                        stvLog.HasInsurance = hasInsurance;
                        stvLog.FiscalYearID = FiscalYear.Current.ID;
                        stvLog.AccountID = activity.AccountID;
                        if (paymentTypeID == PaymentType.Constants.DELIVERY_NOTE)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.DeliveryNote.DocumentTypeID;
                        }
                        else if (paymentTypeID == PaymentType.Constants.CASH)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.Cash.DocumentTypeID;
                        }
                        else if (paymentTypeID == PaymentType.Constants.CREDIT)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.Credit.DocumentTypeID;
                        }
                        else if(paymentTypeID == PaymentType.Constants.STV)
                        {
                            stvLog.DocumentTypeID = DocumentType.documentTypes.STV.DocumentTypeID;
                        }
                        stvLog.IDPrinted = DocumentType.GetNextSequenceNo(stvLog.DocumentTypeID,stvLog.AccountID,stvLog.FiscalYearID);
                        stvLog.PaymentTypeID = order.PaymentTypeID;

                        if (!order.IsColumnNull("RequestedBy"))
                            stvLog.ReceivingUnitID = order.RequestedBy;
                        if (stvLogID.HasValue)
                        {
                            stvLog.IsReprintOf = stvLogID.Value;
                            //this means the STV is from replaced
                            Issue s = new Issue();
                            s.LoadByPrimaryKey(stvLogID.Value);
                            stvLog.IsDeliveryNote=(!s.IsColumnNull("IsDeliveryNote") && s.IsDeliveryNote && !convertDNtoSTV);
                        }

                        stvLog.Save();

                        stvNo = stvLog.ID.ToString("00000"); //If we wanted  to show just the ID of the sql table on the printout. We Use this
                        stvNoForPrint = FiscalYear.Current.GetCode(stvLog.IDPrinted);
                        stvID = stvLog.ID;
                    }
                    else if (!generateNewPrintID && stvLogID.HasValue)
                    {
                        // this assumes that we don't have to export
                        stvLog.LoadByPrimaryKey(stvLogID.Value);

                        stvNo = stvLog.ID.ToString("00000");//If we wanted  to show just the ID of the sql table on the printout. Use this
                       FiscalYear fiscalYear = new FiscalYear();
                        fiscalYear.LoadByPrimaryKey(stvLog.FiscalYearID);
                        stvNoForPrint = fiscalYear.GetCode(stvLog.IDPrinted);
                    }
                }

                if (commodityType != drw["CommodityType"].ToString()) //Check if the commodity type has changed.  Meaning that there will be a new group on the same paper (Pharmaceuticals, Chemicals, etc.) therefore we have to make the number of items that come to that page lower (Because we have headings for each group)
                {
                    commodityType = drw["CommodityType"].ToString();
                    rowsOnPaper = rowsOnPaper + 5;
                }
                else
                {
                    if (drw["FullItemName"].ToString().Length > 30) //The reason behind this code.  If the item name is a long one, it wraps and goes into the next line, making the number of row numbers more than just 1, so we don't just add one
                        rowsOnPaper += Convert.ToInt32(drw["FullItemName"].ToString().Length / 30) + 1;
                    else
                        rowsOnPaper++;
                }

                drw["STVNumber"] = stvNo;
                drw["LineNum"] = lineNumber++;
                drw["StoreName"] = storeName;
                drw["PrintedSTVNumber"] = stvNoForPrint;

                //Save the STVID into the IssueDoc Table.

                BLL.IssueDoc issDoc = new IssueDoc();

                int itemID = Convert.ToInt32(drw["ItemID"]);
                int receiveDocID = Convert.ToInt32(drw["ReceiveDocID"]);
                int picklistID = Convert.ToInt32(drw["PicklistID"]);
                drw["ContactPerson"] = BLL.Order.GetContactPerson(picklistID);
                BLL.Order orderInfo = new Order();

                // the only time the STVLog ID should be an entry in the Issue Doc should be when this is a fresh printout.
                if (stvID != -1 && stvLogID == null)
                {
                    SaveSTVIDbyPickListDetails(drw["IssueDocID"].ToString(), stvID);
                    //SaveSTVIDIntoIssueData(supplierId, itemID, stvID, issDoc, orderInfo.LoadByPickListID(picklistID), receiveDocID, storeID);
                }

                if (stvID == -1 && stvLogID == null)
                {
                    throw new Exception("An error occurred during save.  Please contact your administrator if this happens again.");
                }
                //SaveSTVIDIntoIssueData(supplierId, itemID, stvID, issDoc, order.LoadByPickListID(picklistID), receiveDocID);
            }
            return dtbl;
        }
        /// <summary>
        /// Generate the pick list
        /// </summary>
        /// <param name="orderId">The order id.</param>
        /// <param name="bgWorker">The bg worker.</param>
        /// <returns></returns>
        public DataView GetPalletLocationChoice(int userID, int orderId, BackgroundWorker bgWorker)
        {
            var order = new Order();
            // Load the order

            order.LoadByPrimaryKey(orderId);
            //TODO: check if the order is already approved or not.
            // if not please return from here
            // Load the order details
            var orderDetail = new OrderDetail();
            orderDetail.LoadAllByOrderID(orderId);
            orderDetail.AddColumn("ActivityConcat", typeof(string));
            // prepare the pick list data table with the proper fields
            _pickList = GetPickListTable();
            _replenishmentList = new DataTable();
            _replenishmentList.Columns.Add("ItemID", typeof(int));
            _replenishmentList.Columns.Add("StoreID", typeof(int));

            int count = 0;

            // iterate through the order detail and make the pick list
            while (!orderDetail.EOF)
            {
                DateTime startTime = DateTime.Now;
                System.Console.WriteLine("Processing - " + orderDetail.ItemID);
                // check if there are enough priced items of the same or more quantity in the store
                int? unitID = null;
                if (!orderDetail.IsColumnNull("UnitID"))
                {
                    unitID = orderDetail.UnitID;
                }

                if (!orderDetail.IsColumnNull("StockedOut") && (!orderDetail.StockedOut ||(orderDetail.ApprovedQuantity > 0 && orderDetail.Quantity > orderDetail.ApprovedQuantity)))
                {
                    DateTime? preferredExpiry = new DateTime();

                    if (orderDetail.IsColumnNull("PreferredManufacturerID"))
                        orderDetail.PreferredManufacturerID = -1;

                    if (orderDetail.IsColumnNull("PreferredPhysicalStoreID"))
                        orderDetail.PreferredPhysicalStoreID = -1;

                    if (orderDetail.IsColumnNull("PreferredExpiryDate"))
                        preferredExpiry = null;
                    else
                    {
                        preferredExpiry = orderDetail.PreferredExpiryDate;
                    }
                    if (!orderDetail.IsColumnNull("ApprovedQuantity") && (orderDetail.ApprovedQuantity > 0 && !orderDetail.IsColumnNull("StoreID")))
                    {
                        AddToPickListFor(userID, orderDetail.ID, orderDetail.ItemID, unitID, orderDetail.ApprovedQuantity, orderDetail.StoreID,
                                         orderDetail.PreferredManufacturerID, orderDetail.PreferredPhysicalStoreID,
                                         !orderDetail.IsColumnNull("DeliveryNote") && orderDetail.DeliveryNote,
                                         preferredExpiry);
                    }

                }
                System.Console.WriteLine(string.Format("Took - {0}:{1} for Item ID = {2}", DateTime.Now.Subtract(startTime).Minutes, DateTime.Now.Subtract(startTime).Seconds, orderDetail.ItemID));
                orderDetail.MoveNext();
                count++;
                bgWorker.ReportProgress(count, null);
            }

            // A quick hack just to show the pallet location on the order form

            var pl = new PalletLocation();
            var im = new ItemManufacturer();
            foreach (DataRowView drv in _pickList.DefaultView)
            {
                int plid = Convert.ToInt32(drv["PalletLocationID"]);
                pl.LoadByPrimaryKey(plid);
                drv["PalletLocation"] = pl.FullName;
                im.LoadIMbyLevel(Convert.ToInt32(drv["ItemID"]), Convert.ToInt32(drv["ManufacturerID"]),
                                 Convert.ToInt32(drv["BoxLevel"]));
                drv["QtyInSKU"] = im.RowCount > 0
                                     ? Convert.ToDecimal(drv["Pack"]) * im.QuantityInSku
                                     : Convert.ToDecimal(drv["Pack"]);
                drv["BoxSizeDisplay"] = im.RowCount > 0 ? im.LevelView2 : ""; //im.RightName;
                drv["WarehouseName"] = pl.WarehouseName;
                drv["PhysicalStoreName"] = pl.PhysicalStoreName;
                var activity = new Activity();
                activity.LoadByPrimaryKey(Convert.ToInt32(drv["StoreID"]));
                drv["ActivityConcat"] = activity.FullActivityName;
                drv["AccountName"] = activity.AccountName;
            }

            //foreach (DataRowView v in _pickList.DefaultView)
            //{

            //}

            return _pickList.DefaultView;
        }
 /// <summary>
 /// Gets the name of the StoreType
 /// </summary>
 /// <returns></returns>
 public string GetFromStore()
 {
     var stores = new Mode();
     stores.LoadByPrimaryKey(FromStore);
     // Old data has it in the form of StoreID,
     // What we expect are StoreTypeIDs,
     // HACK: until the old data entered using the old system are cleared, show the store ID
     // TODO: After the data has cleared, delete this condition
     // TODO: Clean the data by converting the RDF Types to ... the appropriate StoreTypeID
     if (stores.RowCount == 0)
     {
         Activity store = new Activity();
         store.LoadByPrimaryKey(FromStore);
         return store.Name;
     }
     return stores.TypeName;
 }
        /// <summary>
        /// Formats the STV.
        /// </summary>
        /// <param name="ord">The ord.</param>
        /// <param name="dvPriced">The dv priced.</param>
        /// <param name="stvSentTo">The STV sent to.</param>
        /// <param name="pl">The pl.</param>
        /// <param name="deliveryNote">if set to <c>true</c> [delivery note].</param>
        /// <param name="allowCancelByUser">if set to <c>true</c> [allow cancel by user].</param>
        /// <exception cref="System.Exception"></exception>
        private XtraReport FormatSTV(Order ord, DataTable dvPriced, string stvSentTo, PickList pl, bool deliveryNote, string printerName, HCMIS.Core.Distribution.Services.PrintLogService pLogService, int orderID)
        {
            bool hasInsurance = chkIncludeInsurance.Checked;
            string accountName = txtConfirmFromStore.Text;
            string transferType = null;

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

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

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

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

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

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

            }
        }
        /// <summary>
        /// Computes the stock calculations for an order detail.
        /// </summary>
        /// <param name="currentMonth">The current month.</param>
        /// <param name="currentYear">The current year.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="orderDetail">The order detail.</param>
        /// <returns></returns>
        public DataRow ComputeStockCalculationsForAnOrderDetail(int currentMonth, int currentYear, int userID, OrderDetail orderDetail)
        {
            if (!IsOrderDetailTableReady(orderDetail))
            {
                PrepareOrderDetailTable(orderDetail);
            }

            int? preferredManufacturer;
            int? preferredPhysicalStoreID;
            decimal usableStock;
            decimal approved;
            decimal availableQuantity;

            Balance bal = new Balance();
            ItemManufacturer imf = new ItemManufacturer();
            int? unitid = null;

            PriceSettings priceSettings = BLL.Settings.HandleDeliveryNotes ? PriceSettings.BOTH : PriceSettings.PRICED_ONLY;

            BLL.Order parentOrder = new Order();
            parentOrder.LoadByPrimaryKey(orderDetail.OrderID);

            unitid = orderDetail.UnitID;
            preferredManufacturer = orderDetail.IsColumnNull("PreferredManufacturerID") ? null : new int?(orderDetail.PreferredManufacturerID);
            preferredPhysicalStoreID = orderDetail.IsColumnNull("PreferredPhysicalStoreID") ? null : new int?(orderDetail.PreferredPhysicalStoreID);

            if (orderDetail.IsColumnNull("StoreID"))
            {
                orderDetail.StoreID = BLL.Activity.GetActivityUsingFEFO(this.FromStore, orderDetail.ItemID, orderDetail.UnitID);
                orderDetail.Save();
            }

            Activity storeObject = new Activity();
            availableQuantity = storeObject.LoadOptionsForOrderDetail(userID, orderDetail.ID, priceSettings, bal, false, out usableStock, out approved);
            orderDetail.SetColumn("AvailableStores", storeObject.DefaultView);
            if (storeObject.RowCount == 1)
            {

                orderDetail.StoreID = storeObject.ID;
                // Avoid error if the column IsDeliveryNote doesn't exsit at all.
                orderDetail.DeliveryNote = storeObject.DefaultView.Table.Columns.IndexOf("IsDeliveryNote") >= 0 &&
                                       !storeObject.IsColumnNull("IsDeliveryNote") &&
                                       Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote"));
                availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
            }
            else if (storeObject.RowCount > 1)
            {
                //TOCLEAN: Lord have mercy.
                //
                // check if the default activity is selected
                // if it has been selected, then do a good job and select it.
                storeObject.Rewind();

                while (
                            !storeObject.EOF
                            &&
                           (
                               (
                                    storeObject.ID == orderDetail.StoreID
                                        && !orderDetail.IsColumnNull("DeliveryNote")
                                        && orderDetail.DeliveryNote
                                        && !Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote"))
                               )
                               ||
                               storeObject.ID != orderDetail.StoreID
                          )
                   )
                {
                    storeObject.MoveNext();
                }

                // the selected store is found, don't worry.
                if (!storeObject.EOF)
                {
                    availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
                }
                else
                {
                    // the selected store is not found, please do select the first store.
                    storeObject.Rewind();
                    orderDetail.StoreID = storeObject.ID;
                    orderDetail.DeliveryNote = (storeObject.DefaultView.Table.Columns.IndexOf("IsDeliveryNote") >= 0 &&
                                                !storeObject.IsColumnNull("IsDeliveryNote") &&
                                                Convert.ToBoolean(storeObject.GetColumn("IsDeliveryNote")));
                    availableQuantity = Convert.ToDecimal(storeObject.GetColumn("AvailableSKU"));
                }
            }
            orderDetail.SetColumn("HasStores", (storeObject.RowCount > 1) ? "*" : "");
            // Precaution ... to hide -ve available quantity.
            if (availableQuantity < 0)
            {
                availableQuantity = 0;
            }

            orderDetail.StockedOut = availableQuantity <= 0;
            orderDetail.Save();

            int qinBu = 1;
            if (unitid.HasValue)
            {
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadByPrimaryKey(unitid.Value);
                qinBu = itemUnit.QtyPerUnit;

                //Checking if the columns from the vwGetAllItems have been filled in.
                var fullItemName = orderDetail.GetColumn("FullItemName").ToString();
                if (string.IsNullOrEmpty(fullItemName))
                {
                    BLL.Order temp = new Order();
                    temp.LoadFromRawSql(HCMIS.Repository.Queries.Order.SelectItemDetail(orderDetail.ItemID));
                    orderDetail.SetColumn("Unit", itemUnit.Text);
                    orderDetail.SetColumn("FullItemName", temp.GetColumn("FullItemName"));
                    orderDetail.SetColumn("StockCode", temp.GetColumn("StockCode"));
                    orderDetail.SetColumn("CategoryType", temp.GetColumn("CategoryType"));
                }
            }

            orderDetail.SetColumn("AvailableQuantity", availableQuantity);
            orderDetail.SetColumn("PricedQuantity", usableStock);

            if (orderDetail.IsColumnNull("ApprovedQuantity"))
            {
                if ((orderDetail.Quantity / ((long)qinBu)) < availableQuantity)
                {
                    orderDetail.ApprovedQuantity = orderDetail.Quantity;
                }
                else
                {
                    orderDetail.ApprovedQuantity = availableQuantity * qinBu;
                }
            }

            if (BLL.Settings.AllowPreferredManufacturers)
            {
                Manufacturer manuf = new Manufacturer();
                manuf.LoadForItem(orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID, true);
                manuf.AddNew();
                manuf.ID = -1;
                manuf.Name = "Remove Preference";
                orderDetail.SetColumn("AvailableManufacturer", manuf.DefaultView);
                orderDetail.SetColumn("HasManufacturers", (manuf.RowCount > 2) ? "*" : "");

                if (manuf.RowCount == 2)
                {
                    manuf.Rewind();
                    orderDetail.PreferredManufacturerID = manuf.ID;
                }
            }

            if (BLL.Settings.AllowPreferredPhysicalStore)
            {
                PhysicalStore phyStore = new PhysicalStore();
                phyStore.LoadForItem(userID, orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID);
                phyStore.AddNew();
                phyStore.Name = "Remove Preference";
                phyStore.ID = -1;
                orderDetail.SetColumn("AvailablePhysicalStore", phyStore.DefaultView);
                orderDetail.SetColumn("HasPhysicalStoreChoice", (phyStore.RowCount > 2) ? "*" : "");

                if (phyStore.RowCount == 2)
                {
                    phyStore.Rewind();
                    orderDetail.PreferredPhysicalStoreID = phyStore.ID;
                }
            }

            if (BLL.Settings.AllowPreferredExpiry)
            {
                ReceiveDoc rd = new ReceiveDoc();
                rd.LoadExpiryDatesForItem(orderDetail.ItemID, orderDetail.StoreID, orderDetail.UnitID, true, preferredManufacturer, preferredPhysicalStoreID);
                rd.AddNew();
                rd.SetColumn("ExpiryDateString", "Remove Preference");
                orderDetail.SetColumn("AvailableExpiry", rd.DefaultView);
                orderDetail.SetColumn("HasExpiryChoice", (rd.RowCount > 2) ? "*" : "");
                if (!orderDetail.IsColumnNull("PreferredExpiryDate"))
                {
                    DateTime expDate = orderDetail.PreferredExpiryDate;
                    string expDateStr = string.Format("{0}-{1:00}-{2:00}", expDate.Year, expDate.Month, expDate.Day, "");
                    orderDetail.SetColumn("ExpiryDateString", expDateStr);
                }
            }
            // do some reseting if the approved quanitty is greater than
            if (orderDetail.ApprovedQuantity / qinBu > availableQuantity)
            {
                orderDetail.ApprovedQuantity = availableQuantity * qinBu;
            }
            orderDetail.SetColumn("UsableStock", usableStock);
            orderDetail.SetColumn("PApprovedStock", approved);
            orderDetail.SetColumn("SKUBU", qinBu);
            orderDetail.SetColumn("AvailableSKU", availableQuantity);
            string TextID = ((orderDetail.IsColumnNull("DeliveryNote") || !orderDetail.DeliveryNote)
                                ? "N"
                                : "D") + orderDetail.StoreID.ToString();
            orderDetail.SetColumn("TextID", TextID);
            orderDetail.SetColumn("ApprovedSKU", orderDetail.ApprovedQuantity / Convert.ToDecimal(qinBu));
            orderDetail.SetColumn("RequestedSKU", orderDetail.Quantity / Convert.ToDecimal(qinBu));
            if (availableQuantity == 0)
            {
                orderDetail.SetColumnNull("TextID");
                orderDetail.SetColumnNull("StoreID");

            }
            Item itm = new Item();
            string warning = (itm.GetItemAllowStatus(orderDetail.ItemID, this.RequestedBy) == 0) ? "Warning" : "";
            orderDetail.SetColumn("Warning", warning);
            //if (!orderDetail.IsColumnNull("StoreID"))
            //{
                // var balance = new Balance();
                //balance.LoadQuantityNotReceive(orderDetail.ItemID, orderDetail.UnitID, parentOrder.FromStore);
                //var totalrequested =balance.GetTotalApprovedQuantityByItem(parentOrder.ID, orderDetail.ItemID, orderDetail.UnitID,parentOrder.FromStore);
                orderDetail.SetColumn("GIT", 0);
                orderDetail.SetColumn("CRequested",0);
                orderDetail.SetColumn("CApproved",0);
                //orderDetail.SetColumn("DOS", balance.DOS);
                //orderDetail.SetColumn("TotalIssued", balance.TotalIssued);
                //orderDetail.SetColumn("FiscalYearDays", balance.FiscalYearDays);

                //decimal amc = 0;
                //decimal mos = 0;

                //var totalissued = balance.TotalIssued;
                //var totaldatediff = balance.FiscalYearDays - balance.DOS;

                //if (totalissued != 0)
                //{
                //    amc = Convert.ToDecimal(totalissued / totaldatediff) * 30;
                //}

                //else if (amc == 0)
                //{
                //    mos = Convert.ToDecimal(balance.FiscalYearDays / 30.0);
                //}

                //else if (amc != 0 && availableQuantity != 0)
                //{
                //    mos = Convert.ToDecimal(availableQuantity / amc);
                //}

                //else if (availableQuantity == 0 && amc != 0)
                //{
                //    mos = 0;
                //}
                //else
                //{
                //    amc = 0;
                //    mos = 0;
                //}
                orderDetail.SetColumn("TotalRequested", 0);
                orderDetail.SetColumn("AMC", 0);
                orderDetail.SetColumn("MOS", 0);

            //}
            return orderDetail.DefaultView.ToTable().Rows[0];
        }
        private void GeneralReport_Load(object sender, EventArgs e)
        {
            Activity stor = new Activity();
            stor.LoadAll();
            DataTable dtStor = stor.DefaultView.ToTable();
            object[] obj = {0,1,"All"};
            //if(stor.RowCount > 1)
                //dtStor.Rows.Add(obj);
            cboStores.DataSource = dtStor;
            //if (stor.RowCount > 1)
            //    cboStores.SelectedValue = 0;

            dtDate.Value = DateTimeHelper.ServerDateTime;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            curMont = dtCurrent.Month;
            curYear = dtCurrent.Year;

            Item itm = new Item();
            DataTable dtyears = itm.AllYears();

            foreach (DataRow drYears in dtyears.Rows)
            {
                int yr = Convert.ToInt32(drYears["year"]);
                cboYear.Items.Add(yr);
            }
            cboYear.SelectedItem = dtCurrent.Year;
        }
        public DataView CostAnalysis(string pGRVNo)
        {
            Receipt receipt = new Receipt(ReceiptID);
               PO PO = receipt.ReceiptInvoice.PO;
               ReceiptInvoice receiptInvoice = receipt.ReceiptInvoice;
               ReceiveDoc receiveDoc = new ReceiveDoc();
               receiveDoc.LoadByReceiptID(ReceiptID);

               Activity activity = new Activity();
               activity.LoadByPrimaryKey(receiveDoc.StoreID);
               JournalEntry UnitCostJournal = new JournalEntry(activity.AccountName, activity.SubAccountName, activity.Name, PO.Supplier.CompanyName, "", PO.PONumber, pGRVNo, receiptInvoice.STVOrInvoiceNo, receiptInvoice.TransitTransferNo, receiptInvoice.WayBillNo, receiptInvoice.InsurancePolicyNo);

            double SupplierClaim = Convert.ToDouble(GetSupplierClaim());
            double InsuranceClaim = Convert.ToDouble(GetInsuranceClaim());
            double Provision = Convert.ToDouble(Math.Round(CostBuildUp.Provision, 2));
            double GrandTotal = Math.Round(GetGrandTotal(), 2);
            double PriceDifference = Math.Round(_PriceDifference, 2);
            double Bonus = Convert.ToDouble(Math.Round(_Bonus,2));
            //Request from Mery Formula Provide by Phone
            //Wednesday October 10
            double GIT = Math.Round(GrandTotal + SupplierClaim + InsuranceClaim + _PriceDifference - Provision - Convert.ToDouble(Bonus), 2);

            // trying out Sprout Method to Handle
            if(receiveDoc.ReturnedStock)
            {
                double stock = Math.Round(GetGrandTotalForSRM(),2);
                return SRMCostAnalysis(UnitCostJournal,_CommodityType, stock, stock,ReceiptID);
            }

                if(POType.GetModes(PO.PurchaseType) == POType.STANDARD && CostBuildUp.Invoice.InvoiceTypeID != ReceiptInvoiceType.InvoiceType.LOCAL_PURCHASE && CostBuildUp.Invoice.InvoiceTypeID  != ReceiptInvoiceType.InvoiceType.CIP)
                {
                    UnitCostJournal.AddNewEntry(String.Format("Stock ({0})", _CommodityType), GrandTotal, null);
                    UnitCostJournal.AddNewEntry("ClaimFromSupplier", SupplierClaim, null);
                    UnitCostJournal.AddNewEntry("ClaimFromInsurance", InsuranceClaim, null);

                    if (PriceDifference < 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", null, Math.Abs(PriceDifference));
                    }
                    else if (PriceDifference > 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", Math.Abs(PriceDifference), null);
                    }

                    UnitCostJournal.AddNewEntry("GIT", null, GIT);
                    UnitCostJournal.AddNewEntry("Provision", null, Provision);
                    if (Bonus > 0)
                    {
                        UnitCostJournal.AddNewEntry("Other Income", null, Math.Abs(Bonus));
                    }
                }
                else if (activity.IsHealthProgram())
                {
                    UnitCostJournal.AddNewEntry(String.Format("Stock ({0})", _CommodityType), Math.Round(GrandTotal, Settings.NoOfDigitsAfterTheDecimalPoint), null);
                    if (PriceDifference < 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", null, Math.Abs(PriceDifference));
                    }
                    else if (PriceDifference > 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", Math.Abs(PriceDifference), null);
                    }
                    UnitCostJournal.AddNewEntry(String.Format("Net Asset ({0})", _Supplier), null, Math.Round(GrandTotal - PriceDifference - Bonus, Settings.NoOfDigitsAfterTheDecimalPoint));
                    if (Bonus > 0)
                    {
                        UnitCostJournal.AddNewEntry("Other Income", null, Math.Abs(Bonus));
                    }
                }
                else
                {
                    UnitCostJournal.AddNewEntry(String.Format("Stock ({0})", _CommodityType), Math.Round(GrandTotal, Settings.NoOfDigitsAfterTheDecimalPoint), null);
                    if (PriceDifference > 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", null, Math.Abs(PriceDifference));
                    }
                    else if (PriceDifference < 0)
                    {
                        UnitCostJournal.AddNewEntry("Price Difference", Math.Abs(PriceDifference), null);
                    }
                    UnitCostJournal.AddNewEntry(String.Format("Account Payable ({0})", _Supplier), null, Math.Round(GIT - Convert.ToDouble(GetTotalDamagedAndShortlanded())-Bonus, Settings.NoOfDigitsAfterTheDecimalPoint));
                    if (Bonus > 0)
                    {
                        UnitCostJournal.AddNewEntry("Other Income", null, Math.Abs(Bonus));
                    }
                }

            return UnitCostJournal.DefaultView();
        }
        private void LoadSTVDetails()
        {
            int documentID = Convert.ToInt32(grdViewReceivedSTVs.GetFocusedDataRow()["DocumentID"]);
            BLL.Document document = new Document();
            document.LoadByPrimaryKey(documentID);
            DocumentExchange.Documents.XmlMappings.STV stv =
                DocumentExchange.Documents.XmlMappings.STV.Load(document.DocumentContent);

            //Clean up the receivedoc entry
            receiveDoc.FlushData();
            STVNo = Convert.ToInt32(stv.DocumentNumber);

            lblDaysAgo.Text = string.Format("Printed: {0}", Helpers.DateTimeFunctions.GetDateSpan(stv.PrintedDate));
            for (int i = 0; i < stv.DocumentDetails.Count; i++)
            {
                STVDetail detail = stv.DocumentDetails[i];
                receiveDoc.AddNew();

                //Add columns for display purposes and for storing temporary information
                if (!receiveDoc.DefaultView.ToTable().Columns.Contains("FullItemName"))
                {
                    receiveDoc.AddColumn("FullItemName", typeof(string));
                    receiveDoc.AddColumn("UnitName", typeof(string));
                    receiveDoc.AddColumn("ManufacturerName", typeof(string));
                    receiveDoc.AddColumn("ActivityName", typeof(string));
                    receiveDoc.AddColumn("StockCode", typeof(string));
                    receiveDoc.AddColumn("PalletLocationID", typeof(int));
                    receiveDoc.AddColumn("GUID", typeof(string));
                }

                //Fill in the data
                receiveDoc.ItemID = detail.ItemID;
                receiveDoc.UnitID = detail.UnitID;
                receiveDoc.StoreID = detail.ActivityID;
                receiveDoc.ManufacturerId = detail.ManufacturerID;
                receiveDoc.SetColumn("BatchNo", detail.BatchNumber);
                receiveDoc.SetColumn("ExpDate", detail.ExpiryDate);
                receiveDoc.SetColumn("GUID", Guid.NewGuid());

                BLL.Item item = new Item();
                item.LoadByPrimaryKey(detail.ItemID);
                receiveDoc.SetColumn("FullItemName", item.FullItemName);

                BLL.ItemUnit unit = new ItemUnit();
                unit.LoadByPrimaryKey(detail.UnitID);
                receiveDoc.SetColumn("UnitName", unit.Text);
                receiveDoc.QtyPerPack = unit.QtyPerUnit;

                BLL.Manufacturer manufacturer = new Manufacturer();
                manufacturer.LoadByPrimaryKey(detail.ManufacturerID);
                receiveDoc.SetColumn("ManufacturerName", manufacturer.Name);
                var activity = new Activity();
                activity.LoadByPrimaryKey(detail.ActivityID);
                receiveDoc.SetColumn("ActivityName", activity.FullActivityName);

                receiveDoc.SetColumn("StockCode", item.StockCode);

                //Financial Info
                receiveDoc.InvoicedNoOfPack = detail.Quantity;
                receiveDoc.Margin = detail.Margin;
                receiveDoc.PricePerPack = detail.UnitPrice;
            }

            grdSTVDetails.DataSource = receiveDoc.DefaultView;
        }
        public DataView CostAnalysis(string pGRVNo)
        {
            Receipt receipt = new Receipt(ReceiptID);
               PO PO = receipt.ReceiptInvoice.PO;
               ReceiptInvoice receiptInvoice = receipt.ReceiptInvoice;
               ReceiveDoc receiveDoc = new ReceiveDoc();
               receiveDoc.LoadByReceiptID(ReceiptID);

               Activity activity = new Activity();
               activity.LoadByPrimaryKey(receiveDoc.StoreID);
               JournalEntry UnitCostJournal = new JournalEntry(activity.AccountName, activity.SubAccountName, activity.Name, PO.Supplier.CompanyName, "", PO.PONumber, pGRVNo, receiptInvoice.STVOrInvoiceNo, receiptInvoice.TransitTransferNo, receiptInvoice.WayBillNo, receiptInvoice.InsurancePolicyNo);
            double GIT = _GrandTotalCost;
               //When insurance is included (_TotalLandedCost-_GrandTotal) is the price effect cauzed by rounding

            double PriceDifference = Math.Round(_PriceDifference - _PriceDifferenceIns,Settings.NoOfDigitsAfterTheDecimalPoint);

            if (receiveDoc.ReturnedStock)
            {
                double stock = Math.Round(GetGrandTotalForSRM(), 2);
                return SRMCostAnalysis(UnitCostJournal, _CommodityType, stock, stock,ReceiptID);
            }
                UnitCostJournal.AddNewEntry("Stock (" + _CommodityType + ")",
                                            Math.Round(_GrandTotalCost + PriceDifference,
                                                       Settings.NoOfDigitsAfterTheDecimalPoint), null);
                if (PriceDifference > 0)
                {
                    UnitCostJournal.AddNewEntry("Price Difference", null, Math.Abs(PriceDifference));
                }
                else if (PriceDifference < 0)
                {
                    UnitCostJournal.AddNewEntry("Price Difference", Math.Abs(PriceDifference), null);
                }
                UnitCostJournal.AddNewEntry(
                    "Account Payable (" + GetAccountPayableCorrectNameByAccount(_Supplier) + ")", null,
                    Math.Round(_GrandTotalCost, Settings.NoOfDigitsAfterTheDecimalPoint));

               return UnitCostJournal.DefaultView();
        }