private void btnSave_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you would like to change the status of this store/warehouse?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            DataTable table = gridManageInvetoryView.GetFocusedDataRow().Table;
            foreach(DataRow dr in table.Rows)
            {
                if (dr != null && dr.RowState == DataRowState.Modified)
                {
                    var freezChoice = Convert.ToString(ComboBoxFreezChoice.Text);

                    if (freezChoice == "Cluster")
                    {
                        int selected = Convert.ToInt32(dr["LocationID"]);
                        Cluster cluster = new Cluster();
                        cluster.LoadByPrimaryKey(selected);
                        cluster.IsActive = Convert.ToBoolean(dr["Status"]);
                        cluster.Save();
                        this.LogActivity("Changed Status of Cluster");
                        BLL.Warehouse warehouse = new BLL.Warehouse();
                        warehouse.UpdateWarehouseStatusbyCluster(selected, Convert.ToBoolean(dr["Status"]));

                        BLL.PhysicalStore physicalStore = new PhysicalStore();
                        physicalStore.UpdatePhysicalStoreStatusbyCluster(selected, Convert.ToBoolean(dr["Status"]));
                    }

                    else if (freezChoice == "Warehouse")
                    {
                        int selected = Convert.ToInt32(dr["LocationID"]);
                        BLL.Warehouse warehouse = new BLL.Warehouse();
                        warehouse.LoadByPrimaryKey(selected);
                        warehouse.IsActive = Convert.ToBoolean(dr["Status"]);
                        warehouse.Save();
                        this.LogActivity("Changed Status of Warehouse");
                        BLL.PhysicalStore physicalStore = new PhysicalStore();
                        physicalStore.UpdatePhysicalStoreStatusbyWarehouse(selected, Convert.ToBoolean(dr["Status"]));
                    }
                    else if (freezChoice == "Physical Store")
                    {
                        int selected = Convert.ToInt32(dr["LocationID"]);
                        PhysicalStore physicalStore = new PhysicalStore();
                        physicalStore.LoadByPrimaryKey(selected);
                        physicalStore.IsActive = Convert.ToBoolean(dr["Status"]);
                        physicalStore.Save();
                        this.LogActivity("Changed Status of Store");
                    }

                }
            }

            XtraMessageBox.Show("The freezing and unfreezing you have made have been saved.", "Successfully Saved",
                                MessageBoxButtons.OK);
        }
 public static bool CanInventoryBeStarted(int physicalStoreID)
 {
     BLL.PhysicalStore ps = new PhysicalStore();
     ps.LoadByPrimaryKey(physicalStoreID);
     int warehouseID = ps.PhysicalStoreTypeID;
     if (!ReceiveDoc.checkOutstandingReceives(warehouseID))
     {
         return false;
     }
     if (!IssueDoc.CheckOutStandingIssues(warehouseID))
     {
         return false;
     }
     return true;
 }
 private void btnRefresh_Click(object sender, EventArgs e)
 {
     if (dxRequiredValidation.Validate())
     {
         storeReport            = new StockStatusByPhysicalStore(CurrentContext.LoggedInUserName);
         storeReport.DataSource = BLL.Balance.GetStockStatusByPhysicalStore(Convert.ToInt32(lkPhysicalStore.EditValue), Convert.ToInt32(lkAccountType.EditValue), chkIncludeStockedOut.Checked);
         var activity = new Activity();
         activity.LoadByPrimaryKey(Convert.ToInt32(lkAccountType.EditValue));
         storeReport.AccountName.Text = activity.FullActivityName;
         BLL.PhysicalStore pstore = new BLL.PhysicalStore();
         pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
         storeReport.WarehouseName.Text = pstore.Name;
         pcPrintout.PrintingSystem      = storeReport.PrintingSystem;
         storeReport.CreateDocument();
     }
 }
        public static bool CanInventoryBeStarted(int physicalStoreID)
        {
            BLL.PhysicalStore ps = new PhysicalStore();
            ps.LoadByPrimaryKey(physicalStoreID);
            int warehouseID = ps.PhysicalStoreTypeID;

            if (!ReceiveDoc.checkOutstandingReceives(warehouseID))
            {
                return(false);
            }
            if (!IssueDoc.CheckOutStandingIssues(warehouseID))
            {
                return(false);
            }
            return(true);
        }
        public static void CommitInventory(int periodId, int activityId, int physicalStoreId, DateTime ethiopianDate, int userId, BackgroundWorker backgroundWorker)
        {
            Inventory inventory = new Inventory();

            if (!InventoryPeriod.HasUnCommited(periodId, activityId))
            {
                throw new Exception("This inventory has been commited already,you are not allow to commit again.");
            }
            if (InventoryPeriod.HasInCompleteReceives(activityId, physicalStoreId))
            {
                throw new Exception("There are incompleted receives,you can only processed after canceling the receives.");
            }
            inventory.LoadByStoreAndActivity(activityId, physicalStoreId, periodId);

            try
            {
                var physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(physicalStoreId);
                inventory.InitializeCommit(userId, physicalStore.PhysicalStoreTypeID);

                inventory.Rewind();
                int count = 0;
                while (!inventory.EOF)
                {
                    string itemDetail = inventory.GetColumn("FullItemName") + " - " + inventory.GetColumn("ManufacturerName")
                                        + " - " + inventory.GetColumn("Unit") + " - " + inventory.GetColumn("ExpiryDate")
                                        + " - " + inventory.GetColumn("BatchNo");



                    if (inventory.IsColumnNull("IsDraft") || inventory.IsDraft)
                    {
                        inventory.Commit(ethiopianDate, backgroundWorker);
                    }

                    inventory.MoveNext();
                    count++;
                    backgroundWorker.ReportProgress(count, itemDetail);
                }

                inventory.FinishCommit();
            }
            catch (Exception exception)
            {
                inventory.CancelCommit(exception);
            }
        }
        public static void CommitInventory(int periodId, int activityId, int physicalStoreId,DateTime ethiopianDate, int userId,BackgroundWorker backgroundWorker)
        {
            Inventory inventory = new Inventory();

            if (!InventoryPeriod.HasUnCommited(periodId, activityId))
            {
                throw new Exception("This inventory has been commited already,you are not allow to commit again.");
            }
            if(InventoryPeriod.HasInCompleteReceives(activityId,physicalStoreId))
            {
                throw new Exception("There are incompleted receives,you can only processed after canceling the receives.");
            }
            inventory.LoadByStoreAndActivity(activityId, physicalStoreId, periodId);

            try
            {
                var physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(physicalStoreId);
                inventory.InitializeCommit(userId, physicalStore.PhysicalStoreTypeID);

                inventory.Rewind();
                int count = 0;
                while (!inventory.EOF)
                {

                    string itemDetail = inventory.GetColumn("FullItemName")+" - " +inventory.GetColumn("ManufacturerName")
                        + " - " + inventory.GetColumn("Unit") + " - " + inventory.GetColumn("ExpiryDate")
                        + " - " + inventory.GetColumn("BatchNo");

                    if (inventory.IsColumnNull("IsDraft") || inventory.IsDraft)
                    {
                        inventory.Commit(ethiopianDate,backgroundWorker);
                    }

                    inventory.MoveNext();
                    count++;
                    backgroundWorker.ReportProgress(count,itemDetail);
                }

                inventory.FinishCommit();
            }
            catch (Exception exception)
            {
                inventory.CancelCommit(exception);
            }
        }
        private void btnPrintCountSheet_Click(object sender, EventArgs e)
        {
            if (dxRequiredValidation.Validate())
            {
                DataTable tbl;
                var       activity = new Activity();
                activity.LoadByPrimaryKey(Convert.ToInt32(lkAccountType.EditValue));

                if (chkIncludeBatchExpiry.Checked)
                {
                    tbl =
                        BLL.Balance.GetCountSheetByPhysicalStoreWithBatchExpiry(
                            Convert.ToInt32(lkPhysicalStore.EditValue), Convert.ToInt32(lkAccountType.EditValue),
                            chkIncludeStockedOut.Checked, chkShowLocations.Checked);
                }
                else
                {
                    tbl = BLL.Balance.GetCountSheetByPhysicalStore(Convert.ToInt32(lkPhysicalStore.EditValue),
                                                                   Convert.ToInt32(lkAccountType.EditValue),
                                                                   chkIncludeStockedOut.Checked);
                }

                if (chkShowLocations.Checked)
                {
                    storeReportWithLocation.DataSource       = tbl;
                    storeReportWithLocation.AccountName.Text = activity.FullActivityName;
                    BLL.PhysicalStore pstore = new BLL.PhysicalStore();
                    pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
                    storeReport.WarehouseName.Text = pstore.Name;
                    pcPrintout.PrintingSystem      = storeReportWithLocation.PrintingSystem;
                    storeReportWithLocation.CreateDocument();
                }
                else
                {
                    storeReport.DataSource       = tbl;
                    storeReport.AccountName.Text = activity.FullActivityName;
                    BLL.PhysicalStore pstore = new BLL.PhysicalStore();
                    pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
                    storeReport.WarehouseName.Text = pstore.Name;
                    pcPrintout.PrintingSystem      = storeReport.PrintingSystem;
                    storeReport.CreateDocument();
                }
            }
        }
        public static void CommitSingle(int inventoryId, DateTime ethiopianDate, int userId)
        {
            Inventory inventory = new Inventory();

            inventory.LoadByPrimaryKey(inventoryId);
            if (!inventory.IsColumnNull("isDraft") && !inventory.IsDraft)
            {
                throw new Exception("This inventory has been commited already,you are not allow to commit again.");
            }

            try
            {
                var physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(inventory.PhysicalStoreID);
                inventory.InitializeCommit(userId, physicalStore.PhysicalStoreTypeID);
                inventory.Commit(ethiopianDate);
                inventory.FinishCommit();
            }
            catch (Exception exp)
            {
                inventory.CancelCommit(exp);
            }
        }
        public static void CommitSingle(int inventoryId,DateTime ethiopianDate,int userId)
        {
            Inventory inventory = new Inventory();
            inventory.LoadByPrimaryKey(inventoryId);
            if(!inventory.IsColumnNull("isDraft") && !inventory.IsDraft)
            {
                  throw new Exception("This inventory has been commited already,you are not allow to commit again.");

            }

            try
            {
                var physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(inventory.PhysicalStoreID);
                inventory.InitializeCommit(userId,physicalStore.PhysicalStoreTypeID);
                inventory.Commit(ethiopianDate);
                inventory.FinishCommit();
            }
            catch (Exception exp)
            {
                inventory.CancelCommit(exp);
            }
        }
        /// <summary>
        /// Saves the new receive doc entry from picklist detail.
        /// </summary>
        /// <param name="pld">The PLD.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="activityID">The new store ID.</param>
        /// <param name="newPhysicalStoreID">The new physical store ID.</param>
        /// <param name="convertedEthDate">The converted eth date.</param>
        /// <param name="supplierID">Activity or Store where it has Transfered from </param>
        /// <exception cref="System.Exception"></exception>
        internal void SaveNewReceiveDocEntryFromPicklistDetail(PickListDetail pld, int userID, int activityID, int newPhysicalStoreID, DateTime convertedEthDate,int receiptID,int? supplierID)
        {
            BLL.User user = new User();
            user.LoadByPrimaryKey(userID);

            BLL.ReceiveDoc rdOriginal = new ReceiveDoc();
            rdOriginal.LoadByPrimaryKey(pld.ReceiveDocID);

            //Now Save the receive doc entry
            this.AddNew();
            this.SetColumn("BatchNo", pld.GetColumn("BatchNumber"));
            this.ItemID = pld.ItemID;
            if (supplierID != null) this.SupplierID = supplierID.Value;
            this.Quantity = pld.QuantityInBU;
            //this.Date=
            this.Date = convertedEthDate;
            this.SetColumn("ExpDate", rdOriginal.GetColumn("ExpDate"));
            this.Out = false;
            this.ReceivedBy = user.UserName;
            this.StoreID = activityID;
            SetColumn("LocalBatchNo", rdOriginal.GetColumn("LocalBatchNo"));
            this.RefNo = receiptID.ToString();
            this.SetColumn("Cost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("IsApproved", rdOriginal.GetColumn("IsApproved"));
            this.ManufacturerId = rdOriginal.ManufacturerId;
            this.QuantityLeft = this.Quantity;
            this.NoOfPack = pld.Packs;
            this.QtyPerPack = rdOriginal.QtyPerPack;
            this.EurDate = DateTimeHelper.ServerDateTime;
            this.SetColumn("SellingPrice", rdOriginal.GetColumn("SellingPrice"));
            this.SetColumn("UnitCost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("Cost", rdOriginal.GetColumn("Cost"));
            this.SetColumn("PricePerPack", rdOriginal.GetColumn("Cost"));
            this.SetColumn("UnitID", rdOriginal.GetColumn("UnitID"));
            this.SetColumn("DeliveryNote", rdOriginal.GetColumn("DeliveryNote"));
            this.Confirmed = false;
            this.ConfirmedDateTime = DateTimeHelper.ServerDateTime;
            this.ReturnedStock = false;
            this.ReceiptID = receiptID;
            this.PhysicalStoreID = newPhysicalStoreID;
            PhysicalStore physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(newPhysicalStoreID);
            this.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;
            this.SetColumn("Margin", rdOriginal.GetColumn("Margin"));
            this.InvoicedNoOfPack = pld.Packs;
            this.IsDamaged = (bool) rdOriginal.GetColumn("IsDamaged");
            this.Save();

            //Now Save the ReceiveDocConfirmation

            ReceiveDocConfirmation rdConf = new ReceiveDocConfirmation();
            rdConf.AddNew();
            rdConf.ReceiveDocID = this.ID;
            rdConf.ReceivedByUserID = userID;
            rdConf.ReceiptConfirmationStatusID = BLL.ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED;
            rdConf.Save();

            //Now Save the palletization.

            ReceivePallet rp = new ReceivePallet();
            rp.AddNew();

            rp.ReceivedQuantity = this.Quantity;
            rp.Balance = this.Quantity;
            rp.ReservedStock = 0;
            rp.ReceiveID = this.ID;

            PalletLocation pLocation = new PalletLocation();
            pLocation.LoadFirstOrDefault(newPhysicalStoreID, int.Parse(BLL.StorageType.BulkStore));

            if (pLocation.RowCount == 0)
            {
                throw new Exception("No locations created in the destination store. Please check if there are Bulk store pallet locations in the physical store.");
            }
            else
            {
                if (pLocation.IsColumnNull("PalletID"))
                {
                    Pallet pallet = new Pallet();
                    pallet.AddNew();
                    pallet.PalletNo = BLL.Pallet.GetLastPanelNumber() + 1;
                    pallet.StorageTypeID = int.Parse(BLL.StorageType.Free);
                    pallet.Save();
                    pLocation.PalletID = pallet.ID;
                }

                rp.PalletID = pLocation.PalletID;
                rp.PalletLocationID = pLocation.ID;
                rp.BoxSize = 0;
                rp.IsOriginalReceive = true;
                rp.Save();
            }
        }
        private void gridReceiveView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            // Bind the detail grid
            PalletLocation pl = new PalletLocation();
            try
            {
                ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);
                BLL.Receipt receiptDoc = new BLL.Receipt();
                var rd = new ReceiveDoc();
                rd.LoadByReceiptID(ReceiptID);

                var ps = new PhysicalStore();
                ps.LoadByPrimaryKey(rd.PhysicalStoreID);

                var w = new BLL.Warehouse();
                w.LoadByPrimaryKey(ps.PhysicalStoreTypeID);
                lblWarehouse.Text = w.Name ?? "-";

                var c = new Cluster();
                c.LoadByPrimaryKey(w.ClusterID);
                lblCluster.Text = c.Name ?? "-";

                receiptDoc.LoadByPrimaryKey(ReceiptID);
                DataTable GRNFDetail =  receiptDoc.GetDetailsForGRNF();
                gridDetails.DataSource = GRNFDetail;
                gridShortage.DataSource = receiptDoc.GetDiscrepancyForGRNF();
                int status = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["Status"]);

                var SelectGRV = gridReceiveView.GetFocusedDataRow();

                lblMode.Text = (string)SelectGRV["ModeName"];
                lblAccount.Text = (string)SelectGRV["AccountName"];
                lblSubAccount.Text = (string)SelectGRV["SubAccountName"];
                lblActivity.Text = (string)SelectGRV["ActivityName"];
                lblSupplier.Text = (string)SelectGRV["SupplierName"];
                lblPONumber.Text = (string)SelectGRV["PONo"];

                lblType.Text = (string)SelectGRV["ReceiptType"];
                lblStatus.Text = (string)SelectGRV["CurrentStatus"];

                var lgs = new LogReceiptStatus();
                lgs.LoadByReceiptID(ReceiptID);

                lblCalculatedDate.Text = lgs.StatusChangedDate.ToShortDateString();

                var user = new User();
                if (SelectGRV["calculatedBy"] != DBNull.Value)
                {
                    user.LoadByPrimaryKey(Convert.ToInt32(SelectGRV["calculatedBy"]));
                    lblCalculatedBy.Text = user.FullName;
                }

                else
                {
                    lblCalculatedBy.Text = "-";
                }

                lblCostConfirmedBy.Text = SelectGRV["confirmedBy"] != DBNull.Value ? SelectGRV["confirmedBy"].ToString() : "-";

                //lblGRVNumber.Text = reference;
                //lblRecivedDate.Text = ((DateTime)SelectGRV["Date"]).ToShortDateString();
                lblCostConfirmedDate.Text = SelectGRV["confirmedDate"] != DBNull.Value ? Convert.ToDateTime(SelectGRV["confirmedDate"]).ToShortDateString() : "-";

                string s = "";

                int length = ((string)SelectGRV["STVOrInvoiceNo"]).Length;
                string grv = (Convert.ToInt32(SelectGRV["IDPrinted"])).ToString();
                HeaderGroup.Text = "Invoice No: " + (string)SelectGRV["STVOrInvoiceNo"] + s.PadRight(240 - length) + "GRV No: " + grv ;

                //ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);
                //ds = new DataSet();
                //DataTable dvMaster = pl.GetDetailsOfByReceiptID(ReceiptID);
                //dvMaster.TableName = "Master";
                //ds.Tables.Add(dvMaster);
                //gridDetails.DataSource = ds.Tables[dvMaster.TableName];

                //var receipt = new BLL.Receipt();
                //receipt.LoadByPrimaryKey(ReceiptID);
                //int receiptTypeID = receipt.ReceiptTypeID;

                if (currentMode == Modes.GRVPrinting)
                {
                    if (status != ReceiptConfirmationStatus.Constants.PRICE_CONFIRMED)
                    {
                        gridDetails.Enabled = false;

                        btnConfirm.Enabled = false;
                        btnPrint.Enabled = false;
                        btnReturn.Enabled = false;
                    }
                    else
                    {
                        gridDetails.Enabled = true;
                        btnConfirm.Enabled = true;
                        btnPrint.Enabled = true;
                        btnReturn.Enabled = true;
                    }
                }
            }

            catch
            {
                gridDetails.DataSource = null;
                gridShortage.DataSource = null;
            }
        }
        private void startbgWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            MyGeneration.dOOdads.TransactionMgr transactionMgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                // Add the inventory details.
                // For each Activity, populate the inventory.
                //ToDO: this grid reading in a non ui thread is dangerous
                //please don't do it this way.
                transactionMgr.BeginTransaction();
                int physicalStoreID = Convert.ToInt32(gridManageInvetoryView.GetFocusedDataRow()["ID"]);
                PhysicalStore physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(physicalStoreID);

                DateTime startDate = dtStartInventory.Value;
                if (!physicalStore.IsColumnNull("CurrentInventoryPeriodID"))
                {
                // create the inventory period
                InventoryPeriod oldPeriod = new InventoryPeriod();
                oldPeriod.LoadByPrimaryKey(physicalStore.CurrentInventoryPeriodID);
                oldPeriod.EndDate = dtStartInventory.Value;
                oldPeriod.Save();
                }
                InventoryPeriod period = new InventoryPeriod();
                period.AddNew();
                period.InventoryStatusID = InventoryPeriod.Constants.BEGIN_INVENTORY;
                period.PhysicalStoreID = physicalStoreID;
                period.StartDate = dtStartInventory.Value;
                period.EndDate = FiscalYear.Current.EndDate;
                period.StartedBy = CurrentContext.UserId;
                period.FiscalYearID = FiscalYear.Current.ID;
                if (memoEdit1.EditValue != null)
                {
                    period.Remark = memoEdit1.EditValue.ToString();
                }

                period.Save();
                //ChangePhysicalStoreToCurrentPeriod

                physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(physicalStoreID);
                physicalStore.CurrentInventoryPeriodID = period.ID;
                physicalStore.CurrentPeriodStartDate = period.StartDate;
                physicalStore.Save();

                Activity activity = new Activity();
                activity.LoadAll();
                int activityIndex = 1;
                while (!activity.EOF)
                {
                    // report that this activity is being processed.
                    startbgWorker.ReportProgress(activityIndex++, "Activity: " + activity.FullActivityName);

                    DataTable dtbl = Balance.GetBalanceByPhysicalStore(physicalStoreID, activity.ID, false);
                    decimal total = dtbl.Rows.Count;
                    decimal i = 0;
                    foreach (DataRow dr in dtbl.Rows)
                    {

                        Inventory inv = new Inventory();
                        inv.AddNew();

                        inv.IsDraft = true;
                        inv.PhysicalStoreID = physicalStoreID;
                        inv.RecordedBy = CurrentContext.UserId;
                        inv.RecordedDate = BLL.DateTimeHelper.ServerDateTime;

                        inv.InventoryPeriodID = period.ID;
                        inv.ItemID = Convert.ToInt32(dr["ID"]);
                        inv.UnitID = Convert.ToInt32(dr["UnitID"]);
                        inv.ActivityID = activity.ID;
                        inv.ManufacturerID = Convert.ToInt32(dr["ManufacturerID"]);
                        inv.SetColumn("BatchNo", dr["BatchNo"]);
                        inv.SetColumn("ExpiryDate", dr["ExpDate"]);
                        if (!inv.IsColumnNull("ExpiryDate") && inv.ExpiryDate < BLL.DateTimeHelper.ServerDateTime)
                        {
                            inv.SystemExpiredQuantity = Convert.ToDecimal(dr["SoundSOH"]);
                        }
                        else
                        {
                            inv.SystemSoundQuantity = Convert.ToDecimal(dr["SoundSOH"]);
                        }

                        inv.SystemDamagedQuantity = Convert.ToDecimal(dr["DamagedSOH"]);
                        inv.SetColumn("Cost", dr["Cost"]);
                        inv.Margin = dr["Margin"] == DBNull.Value ? 0 : Convert.ToDecimal(dr["Margin"]);
                        inv.SetColumn("PalletLocationID", dr["PalletLocationID"]);
                        inv.Save();

                        startbgWorker.ReportProgress(Convert.ToInt32((i / total) * 100), "Detail");
                        //inventory
                        i++;
                    }

                    activity.MoveNext();
                }
                transactionMgr.CommitTransaction();
                XtraMessageBox.Show("The new Inventory Period has been defined.");
            }
            catch (Exception exception)
            {
                transactionMgr.RollbackTransaction();
                XtraMessageBox.Show(exception.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnStartInventory_Click(object sender, EventArgs e)
        {
            //Show a dialog box to confirm if they are sure to do this.

            if (XtraMessageBox.Show("Are you sure you would like to start inventory on this physical store?", "Confrim",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int physicalStoreID = Convert.ToInt32(gridManageInvetoryView.GetFocusedDataRow()["ID"]);

                if (!BLL.Inventory.CanInventoryBeStarted(physicalStoreID))
                {
                    XtraMessageBox.Show(
                        "Inventory cannot be started in the chosen warehouse because there are outstanding transactions.",
                        "Inventory Cannot Be Started");
                    return;
                }

                //Set The PhsyicalStore to The CurrentInventoryPeriod
                PhysicalStore physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(physicalStoreID);
                if (physicalStore.IsActive)
                {
                    XtraMessageBox.Show(
                       "Transaction on this warehouse should be blocked before starting inventory.The selected warehouse is still Active",
                       "Inventory Cannot Be Started");
                    return;
                }
                InitializeProgressBar();

                lblDescription.Text =
                    string.Format(
                        "HCMIS is starting inventory on <b>{1} - {0}</b>. Please do not close this window until this operation is complete.",
                        physicalStore.Name, physicalStore.WarehouseName);

                //TODO: this needs to be optimized.
                // there is no need that this has to be loaded here.
                // or if it is loaded, dont load it in the background thread.
                Activity activity = new Activity();
                activity.LoadAll();

                labelTotalActivity.Text =
                    string.Format("HCMIS is searching this physical store for stock under all <b>{0}</b> activities.",
                                  activity.RowCount);
                progressBarActivities.Properties.Maximum = activity.RowCount;

                startbgWorker.RunWorkerAsync();

                // post start inventory transaction
                // todo:
                // lock all items from issue from this phsical store.
            }
        }
        private void NewInventoryEntry_Load(object sender, EventArgs e)
        {
            lkCategory.Properties.DataSource = CommodityType.GetAllTypes();

            // load the activity and the physical store names ... so the dialog box shows some context
            Activity activity = new Activity();
            activity.LoadByPrimaryKey(_activityID);
            textActivity.Text = activity.FullActivityName;

            PhysicalStore physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(_physicalStoreID);
            textStore.Text = string.Format("{0} - {1}", physicalStore.WarehouseName, physicalStore.Name);
        }
        private void btnPrintCountSheet_Click(object sender, EventArgs e)
        {
            if (dxRequiredValidation.Validate())
            {
                DataTable tbl;
                var activity = new Activity();
                activity.LoadByPrimaryKey(Convert.ToInt32(lkAccountType.EditValue));

                if (chkIncludeBatchExpiry.Checked)
                {
                    tbl =
                        BLL.Balance.GetCountSheetByPhysicalStoreWithBatchExpiry(
                            Convert.ToInt32(lkPhysicalStore.EditValue), Convert.ToInt32(lkAccountType.EditValue),
                            chkIncludeStockedOut.Checked, chkShowLocations.Checked);

                }
                else
                {
                    tbl = BLL.Balance.GetCountSheetByPhysicalStore(Convert.ToInt32(lkPhysicalStore.EditValue),
                                                                   Convert.ToInt32(lkAccountType.EditValue),
                                                                   chkIncludeStockedOut.Checked);
                }

                if (chkShowLocations.Checked)
                {
                    storeReportWithLocation.DataSource = tbl;
                    storeReportWithLocation.AccountName.Text = activity.FullActivityName;
                    BLL.PhysicalStore pstore = new BLL.PhysicalStore();
                    pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
                    storeReport.WarehouseName.Text = pstore.Name;
                    pcPrintout.PrintingSystem = storeReportWithLocation.PrintingSystem;
                    storeReportWithLocation.CreateDocument();
                }
                else
                {
                    storeReport.DataSource = tbl;
                    storeReport.AccountName.Text = activity.FullActivityName;
                    BLL.PhysicalStore pstore = new BLL.PhysicalStore();
                    pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
                    storeReport.WarehouseName.Text = pstore.Name;
                    pcPrintout.PrintingSystem = storeReport.PrintingSystem;
                    storeReport.CreateDocument();
                }

            }
        }
        /// <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>
        /// 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 int SaveOrder()
        {
            int warehouseID;
            var order = GenerateOrder();
            PickList pickList = PickList.GeneratePickList(order.ID);
            int picklistId = pickList.ID;
            if (TransferTypeID != Transfer.Constants.HUB_TO_HUB)
            {
                warehouseID = GenerateTransfer(order.ID);
            }

            // Log
            this.LogActivity("Transfer", order.ID);

            int LineNo = 0;

            // This is a kind of initializing the data table.

            DataView dv = orderGrid.DataSource as DataView;

            foreach (DataRowView r in dv)
            {
                if (r["ApprovedPacks"] != null && r["ApprovedPacks"] != DBNull.Value && r["ApprovedPacks"].ToString()!= "")
                    if (Convert.ToDecimal(r["ApprovedPacks"]) != 0)
                    {
                        LineNo = LineNo + 1;
                        int itemId = Convert.ToInt32(r["ItemID"]);
                        int unitId = Convert.ToInt32(r["UnitID"]);
                        decimal pack = Convert.ToDecimal(r["ApprovedPacks"]);
                        int qtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        int activityId = Convert.ToInt32(lkFromActivity.EditValue);
                        int manufacturerId = Convert.ToInt32(Convert.ToInt32(r["ManufacturerID"]));
                        int receivePalletId = Convert.ToInt32(r["ReceivingLocationID"]);
                        int palletLocationId = Convert.ToInt32(r["LocationID"]);
                        double? unitPrice;
                        string batchNumber = r["BatchNo"].ToString();
                        string expireDate ="" ;
                        int receiveDocId = Convert.ToInt32(r["ReceiveDocID"]);
                        if((r["UnitPrice"] != DBNull.Value))
                        {
                            unitPrice = Convert.ToDouble(r["UnitPrice"]);
                        }
                        else
                        {
                            unitPrice = null;
                        }

                        if (r["ExpDate"] != DBNull.Value)
                             expireDate= r["ExpDate"].ToString();

                        OrderDetail ord = OrderDetail.GenerateOrderDetail(unitId, activityId, pack, order.ID, qtyPerPack, itemId);
                        PalletLocation palletLocation = new PalletLocation();
                        palletLocation.LoadByPrimaryKey(palletLocationId);
                        int palletID = palletLocation.PalletID;
                        PickListDetail pkDetail = PickListDetail.GeneratePickListDetail(pack, unitPrice, receiveDocId, manufacturerId, receivePalletId, qtyPerPack, activityId, unitId, itemId, picklistId, palletID, expireDate, batchNumber);
                        ReceivePallet.ReserveQty(pack, receivePalletId);
                        //To Print The Picklist
                        //Then reserve Items

                       Item item = new Item();
                        item.LoadByPrimaryKey(itemId);
                        DataRow drvpl = dvPickList.NewRow();
                        drvpl["FullItemName"] = item.FullItemName;
                        drvpl["StockCode"] = item.StockCode;
                        drvpl["BatchNo"] = batchNumber;
                        if (expireDate != "" )
                            drvpl["ExpDate"] = Convert.ToDateTime(expireDate).ToString("MMM/yyyy");
                        else
                            drvpl["ExpDate"] = DBNull.Value;
                        drvpl["LineNum"] = LineNo + 1;
                        var manufacturer = new Manufacturer();
                        manufacturer.LoadByPrimaryKey(manufacturerId);
                        drvpl["ManufacturerName"] = manufacturer.Name;

                        drvpl["Pack"] = pack;
                        drvpl["UnitPrice"] = unitPrice;
                        var unit = new ItemUnit();
                        unit.LoadByPrimaryKey(unitId);

                        drvpl["Unit"] = unit.Text;

                        drvpl["QtyInSKU"] = pack;
                        if (unitPrice != null)
                             drvpl["CalculatedCost"] = pack *Convert.ToDecimal(unitPrice);

                         palletLocation.LoadByPrimaryKey(pkDetail.PalletLocationID);
                         drvpl["PalletLocation"] = palletLocation.Label;
                         drvpl["WarehouseName"] = palletLocation.WarehouseName;
                        drvpl["PhysicalStoreName"] = palletLocation.PhysicalStoreName;
                        var activity = new Activity();
                        activity.LoadByPrimaryKey(pkDetail.StoreID);
                        drvpl["ActivityConcat"] = activity.FullActivityName;
                        drvpl["AccountName"] = activity.AccountName;
                        dvPickList.Rows.Add(drvpl);
                    }

            }
            if (LineNo == 0)
                throw new System.ArgumentException("Please review your list,you haven't approved any Quantity");
            string receivingUnit;
                Transfer transfer = new Transfer();
                transfer.LoadByOrderID(order.ID);
                if (TransferTypeID == Transfer.Constants.ACCOUNT_TO_ACCOUNT)
                {
                    var fromActivity = new Activity();
                    fromActivity.LoadByPrimaryKey(transfer.FromStoreID);
                    var toActivity = new Activity();
                    toActivity.LoadByPrimaryKey(transfer.ToStoreID);

                    receivingUnit = String.Format("Account to Account from {0} to {1}", fromActivity.FullActivityName,
                                                toActivity.FullActivityName);
                }
                else if (TransferTypeID == Transfer.Constants.STORE_TO_STORE)
                {

                    var toStore = new PhysicalStore();

                    toStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
                    receivingUnit = string.Format("Store to Store transfer to: {0}", toStore.WarehouseName);
                }
                else
                {
                    receivingUnit = lkForHub.Text;
                }
            var plr = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(order, receivingUnit,
                                                                                       dvPickList.DefaultView);
            plr.PrintDialog();

                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return order.ID;
        }
        private int GenerateTransfer(int OrderID)
        {
            Transfer transfer = new Transfer();
            transfer.AddNew();
            transfer.OrderID = OrderID;
            transfer.FromStoreID = Convert.ToInt32(lkFromActivity.EditValue);
            transfer.SetColumn("TransferTypeID",TransferTypeID);
            transfer.FromPhysicalStoreID = Convert.ToInt32(lkFromStore.EditValue);

            if (TransferTypeID != 1)
            {
                transfer.ToPhysicalStoreID = Convert.ToInt32(lkToStore.EditValue);
                transfer.ToStoreID = Convert.ToInt32(lkToActivity.EditValue);
            }

            transfer.Save();
            var physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(transfer.ToPhysicalStoreID);
            return physicalStore.PhysicalStoreTypeID;
        }
        private Order GenerateOrder()
        {
            int transerTypeID = (TransferTypeID == 1) ? OrderType.CONSTANTS.HUB_TO_HUB_TRANSFER : (TransferTypeID == 2) ? OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER : OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER;

            int? requestedBy= null;
            if (TransferTypeID == 1)
                requestedBy = Convert.ToInt32(lkForHub.EditValue);
            else if(TransferTypeID == 2)
            {
                var activity = new Activity();
                activity.LoadByPrimaryKey(Convert.ToInt32(lkToActivity.EditValue));
                requestedBy = activity.InstitutionID;

            }
            else
            {
                var ps = new PhysicalStore();
                ps.LoadByPrimaryKey(Convert.ToInt32(lkToStore.EditValue));
                requestedBy = ps.InstitutionID;

            }
            Order order = Order.GenerateOrder(OrderID, transerTypeID ,BLL.OrderStatus.Constant.PICK_LIST_CONFIRMED,
                      Convert.ToInt32(lkFromActivity.EditValue), PaymentType.Constants.STV,txtContactPerson.Text, requestedBy, CurrentContext.UserId);
            return order;
        }
 private void btnRefresh_Click(object sender, EventArgs e)
 {
     if (dxRequiredValidation.Validate())
     {
         storeReport = new StockStatusByPhysicalStore(CurrentContext.LoggedInUserName);
         storeReport.DataSource = BLL.Balance.GetStockStatusByPhysicalStore(Convert.ToInt32(lkPhysicalStore.EditValue), Convert.ToInt32(lkAccountType.EditValue), chkIncludeStockedOut.Checked);
         var activity = new Activity();
         activity.LoadByPrimaryKey(Convert.ToInt32(lkAccountType.EditValue));
         storeReport.AccountName.Text = activity.FullActivityName;
         BLL.PhysicalStore pstore = new BLL.PhysicalStore();
         pstore.LoadByPrimaryKey(Convert.ToInt32(lkPhysicalStore.EditValue));
         storeReport.WarehouseName.Text = pstore.Name;
         pcPrintout.PrintingSystem = storeReport.PrintingSystem;
         storeReport.CreateDocument();
     }
 }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

            BLL.ReceivePallet rp = new ReceivePallet();
            Pallet pallet = new Pallet();
            PalletLocation pl = new PalletLocation();
            ItemUnit itemUnit = new ItemUnit();

            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            guid = rec.GetColumn("GUID").ToString();
            var isDamaged = Convert.ToBoolean(rec.GetColumn("IsDamaged"));
            //DataRow[] r = _dtPalletizedItemList.Select(string.Format("Index = '{0}'", i));
            DataRow[] r =
                _dtPalletizedItemList.Select(string.Format("GUID = '{0}' AND IsDamaged = {1}", guid, isDamaged));
            if (r.Length > 0)
            {
                foreach (DataRow rw in r)
                {
                    rp.AddNew();
                    rp.IsOriginalReceive = true;
                    if (Convert.ToBoolean(rw["Consolidate"]))
                    {
                        try
                        {
                            DataRow dr =
                                _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}",
                                    Convert.ToInt32(rw["PalletNumber"])))[0]; //Assuming we only need one.
                            if (rw["IsStoredInFreeStorageType"] != null)
                            {
                                if (Convert.ToBoolean(rw["IsStoredInFreeStorageType"]) == true)
                                {
                                    pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                                }
                            }
                        }
                        catch
                        {
                            pl.LoadByPalletNumber(Convert.ToInt32(rw["PalletNumber"]));
                        }
                        try
                        {
                            rp.PalletID = pl.PalletID;
                            rp.PalletLocationID = pl.ID;
                        }
                        catch
                        {
                            rp.PalletID = GetPalletID(rw["PalletNumber"].ToString());
                            try
                            {
                                rp.PalletLocationID = PalletLocation.GetPalletLocationID(rp.PalletID);
                            }
                            catch
                            {
                                DataRow dr =
                                    _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}",
                                        Convert.ToInt32(rw["PalletNumber"])))[0];
                                pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                                pl.PalletID = rp.PalletID;
                                pl.Save();
                                rp.PalletLocationID = pl.ID;
                            }
                        }

                        //// if the putaway is on a pick face, increase the amount stored on the pick face
                        //if (pl.StorageTypeID.ToString() == StorageType.PickFace)
                        //{
                        //    PickFace pf = new PickFace();

                        //    pf.LoadPickFaceFor(rec.ItemID, Convert.ToInt32(cboStores.EditValue));
                        //    if (pf.RowCount > 0)
                        //    {
                        //        if (pf.IsColumnNull("Balance"))
                        //        {
                        //            pf.Balance = 0;
                        //        }

                        //        pf.Balance += Convert.ToInt32(rp.Balance);
                        //        pf.Save();
                        //    }
                        //}
                    }
                    else
                    {
                        var palletNumber = Convert.ToInt32(rw["PalletNumber"]);
                        DataRow dr = _dtPutAwayPalletized.Select(string.Format("PalletNumber={0}", palletNumber))[0];
                        //Assuming we only need one.
                        pl.LoadByPrimaryKey(Convert.ToInt32(dr["PutAwayLocation"]));
                        rp.PalletID = GetPalletID(rw["PalletNumber"].ToString());
                        pl.PalletID = rp.PalletID;
                        rp.PalletLocationID = pl.ID; //PalletLocation.GetPalletLocationID(rp.PalletID);
                        pl.Save();
                    }

                    rp.ReservedStock = 0;
                    im.LoadIMbyLevel(Convert.ToInt32(rw["ID"]), Convert.ToInt32(rw["Manufacturer"]),
                        Convert.ToInt32(rw["BoxLevel"]));

                    int qtyPerPack = im.QuantityInBasicUnit;

                    if (rw["UnitID"] != DBNull.Value)
                    {
                        itemUnit.LoadByPrimaryKey(Convert.ToInt32(rw["UnitID"]));
                        qtyPerPack = itemUnit.QtyPerUnit;
                    }

                    rp.ReceivedQuantity = rp.Balance = (Convert.ToDecimal(rw["Pack Qty"]) * Convert.ToDecimal(qtyPerPack));
                    rp.BoxSize = Convert.ToInt32(rw["BoxLevel"]);
                    if (rec.IsColumnNull("PhysicalStoreID") && !rp.IsColumnNull("PalletLocationID"))
                    {
                        PalletLocation l = new PalletLocation();
                        l.LoadByPrimaryKey(rp.PalletLocationID);
                        rec.PhysicalStoreID = (l.PhysicalStoreID);

                        PhysicalStore physicalStore = new PhysicalStore();
                        physicalStore.LoadByPrimaryKey(l.PhysicalStoreID);
                        rec.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;
                    }

                    if (Convert.ToBoolean(rw["Consolidate"]))
                    {
                        try
                        {
                            // if the putaway is on a pick face, increase the amount stored on the pick face
                            if (pl.StorageTypeID.ToString() == StorageType.PickFace)
                            {
                                PickFace pf = new PickFace();

                                pf.LoadPickFaceFor(rec.ItemID, Convert.ToInt32(lkAccounts.EditValue));
                                if (pf.RowCount > 0)
                                {
                                    if (pf.IsColumnNull("Balance"))
                                    {
                                        pf.Balance = 0;
                                    }

                                    pf.Balance += Convert.ToInt32(rp.Balance);
                                    pf.Save();
                                }
                            }
                        }
                        catch
                        {

                        }
                    }

                }
            }

            //r = _dtPutAwayNonPalletized.Select(string.Format("Index = '{0}'", i));
            string filterQuery = _revDocRelatePalletGuid.ContainsKey(guid)
                ? string.Format("{0} AND IsDamaged = {1}", GetFilterByGuid(_revDocRelatePalletGuid[guid]), isDamaged)
                : string.Format("GUID = '{0}' AND IsDamaged = {1} ", guid, isDamaged);
            r = _dtPutAwayNonPalletized.Select(filterQuery);
            if (r.Length > 0)
            {
                // Save the palletization and the putaway here,// this was supposed to be out of here but it is easlier to implement here.
                foreach (DataRow rw in r)
                {
                    pl.LoadByPrimaryKey(Convert.ToInt32(rw["PutAwayLocation"]));
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pallet.AddNew();
                        pallet.Save();
                    }
                    else
                    {
                        pallet.LoadByPrimaryKey(pl.PalletID);
                    }
                    rp.AddNew();
                    rp.IsOriginalReceive = true;
                    rp.PalletID = pallet.ID;
                    rp.PalletLocationID = pl.ID;
                    // rp.ReceiveID = rec.ID;
                    rp.ReservedStock = 0;
                    im.LoadIMbyLevel(Convert.ToInt32(rw["ID"]), Convert.ToInt32(rw["Manufacturer"]),
                        Convert.ToInt32(rw["BoxLevel"]));

                    int qtyPerPack = im.QuantityInBasicUnit;

                    if (rw["UnitID"] != DBNull.Value)
                    {
                        itemUnit.LoadByPrimaryKey(Convert.ToInt32(rw["UnitID"]));
                        qtyPerPack = itemUnit.QtyPerUnit;
                    }

                    rp.ReceivedQuantity =
                        rp.Balance = (Convert.ToDecimal(rw["Palletized Quantity"]) * Convert.ToDecimal(qtyPerPack));
                    rp.BoxSize = Convert.ToInt32(rw["BoxLevel"]);
                    //Get the putaway location

                    pl.Save();
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pl.PalletID = pallet.ID;
                        pl.Confirmed = false;
                        pl.Save();
                    }
                }
            }
            if (rec.IsColumnNull("PhysicalStoreID") && !rp.IsColumnNull("PalletLocationID"))
            {
                PalletLocation l = new PalletLocation();
                l.LoadByPrimaryKey(rp.PalletLocationID);
                PhysicalStore physicalStore = new PhysicalStore();
                physicalStore.LoadByPrimaryKey(l.PhysicalStoreID);
                rec.PhysicalStoreID = (l.PhysicalStoreID);
                // we can take any of the pallet location physical store. as we have one entry on receiveDoc per Store.
                if (physicalStore.IsColumnNull("CurrentInventoryPeriodID"))
                {
                    XtraMessageBox.Show(string.Format("Please Set InventoryPeriod for '{0}' PhysicalStore!",
                        physicalStore.Name), "Empty InventoryPeriod", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception(string.Format("Please Set InventoryPeriod for '{0}' PhysicalStore!",
                        physicalStore.Name));
                }
                rec.InventoryPeriodID = physicalStore.CurrentInventoryPeriodID;

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        private void LoadUpdateForm(DataRow dr)
        {
            btnSave.Text = "Update";
            lkCategory.Enabled = false;
            lkItem.Enabled = false;
            Duplicate.Enabled = false;

            Activity activity = new Activity();
            activity.LoadByPrimaryKey(Convert.ToInt32(_dr["ActivityID"]));
            textActivity.Text = activity.FullActivityName;

            PhysicalStore physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(Convert.ToInt32(_dr["PhysicalStoreID"]));
            textStore.Text = string.Format("{0} - {1}", physicalStore.WarehouseName, physicalStore.Name);

            lkCategory.EditValue = Convert.ToInt32(dr["TypeID"]);
            lkItem.Properties.DataSource = Item.GetActiveItemsByCommodityTypeForReceiveScreen(Convert.ToInt32(dr["TypeID"]) ,Convert.ToInt32(dr["ActivityID"]));
            lkItem.EditValue = Convert.ToInt32(dr["ItemID"]);
            lkUnit.EditValue = Convert.ToInt32(dr["UnitID"]);

            lkManufacturer.EditValue = Convert.ToInt32(dr["ManufacturerID"]);
            dtExpiryDate.EditValue = Convert.ToDateTime(dr["ExpiryDate"]);
            txtBatchNo.Text = Convert.ToString(dr["BatchNo"]);

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

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

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

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

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

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

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

            }
        }
        private void btnFinalPrintout_Click(object sender, EventArgs e)
        {
            int periodId = Convert.ToInt32(lkPeriod.EditValue);
            int activityID = Convert.ToInt32(lkInventoryAccount.EditValue);
            int physicalStoreID = Convert.ToInt32(lkInventoryStore.EditValue);
            PhysicalStore physicalStore = new PhysicalStore();
            physicalStore.LoadByPrimaryKey(physicalStoreID);
            try
            {
                if (InventoryPeriod.HasUnCommited(periodId, activityID))
                {
                    throw new Exception("This inventory has not been commited yet,you are not allow to print before");
                }

                DevExpress.XtraReports.UI.XtraReport xreport;
                DateTimePickerEx dtDate = new DateTimePickerEx();
                dtDate.Value = DateTimeHelper.ServerDateTime;
                if (Settings.LocalvsTender)
                {
                    xreport = new HCMIS.Desktop.Reports.InventoryCountSheetLocalTender(CurrentContext.LoggedInUserName);
                    (xreport as HCMIS.Desktop.Reports.InventoryCountSheetLocalTender).Date.Text = dtDate.Text;
                }
                else
                {
                    xreport = new HCMIS.Desktop.Reports.InventoryCountSheet(CurrentContext.LoggedInUserName);
                    (xreport as HCMIS.Desktop.Reports.InventoryCountSheet).Date.Text = dtDate.Text;
                }
                xreport.DataSource = BLL.Receipt.GetInventoryCountbyInventoryPeriodID(periodId, physicalStoreID, activityID);
                xreport.ShowPreview();
            }
            catch (Exception exp)
            {
                XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }