/// <summary>
        /// Calculates the current volume of a pallet, 
        /// this assumes that the box levels have all the dimentions set.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public double CalculateCurrentVolume( int id)
        {
            Pallet p = new Pallet();
            p.GetAllItemsInPallet(id);
            ReceiveDoc rd = new ReceiveDoc();
            ItemManufacturer im = new ItemManufacturer();
            double volume = 0;

            foreach (DataRowView drv in p.DefaultView)
            {
                //Get the recieving box size and manufacturer
                rd.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveID"]));
                //Handle if the box size was not specified for some reason.
                // this shouldn't happen on a non error condition
                if (drv["BoxSize"].ToString() == "")
                {
                    drv["BoxSize"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, Convert.ToInt32(drv["BoxSize"]));
                if (im.RowCount == 0)
                {
                    im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, 0);
                }
                double quantity = Convert.ToInt32(drv["Balance"])/im.QuantityInBasicUnit;
                volume += quantity * im.Volume;
                // find the volume of the items in the current pallet.

            }
            return volume;
        }
        /// <summary>
        /// Deletes the A receive doc entry.
        /// </summary>
        /// <param name="receiveDocID">The receive doc ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <exception cref="System.Exception"></exception>
        public static void DeleteAReceiveDocEntry(int receiveDocID, int userID)
        {
            var rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(receiveDocID);

                if (rd.RowCount > 0)
                {
                    if (rd.HasTransactions())
                    {
                        string printedIDs = "";

                        var issueDoc = new IssueDoc();
                        issueDoc.LoadByReceiveDocID(rd.ID);

                        issueDoc.Rewind();
                        while (!issueDoc.EOF)
                        {
                            var stvs = new BLL.Issue();
                            stvs.LoadByPrimaryKey(issueDoc.STVID);
                            printedIDs += stvs.IDPrinted.ToString(CultureInfo.InvariantCulture) + " ,";
                            issueDoc.MoveNext();
                        }

                        printedIDs = printedIDs.Remove(printedIDs.Length - 1, 1);
                        throw new Exception(
                            string.Format("Please cancel/void the following Stvs: With PrintedIDs : {0}", printedIDs));
                    }

                    HandleReceiveDocDeleting(receiveDocID, userID, rd);
                }
        }
        internal void SetStatusConfirmQuantityAndLocation(int receiveID, int? userID)
        {
            LoadByReceiveDocID(receiveID);
            BLL.ReceiveDoc rcDoc=new ReceiveDoc();
            BLL.Receipt rct = new Receipt();
            rcDoc.LoadByPrimaryKey(receiveID);
            rct.LoadByPrimaryKey(rcDoc.ReceiptID);
            if (RowCount == 0)
            {
                AddNew();
                ReceiveDocID = receiveID;
            }

            if(userID.HasValue)
            {

               ReceiptQuantityConfirmedByUserID = userID.Value;
            }

                ReceiptConfirmationStatusID = rct.ReceiptTypeID == BLL.ReceiptType.CONSTANTS.BEGINNING_BALANCE?
                                                 ReceiptConfirmationStatus.Constants.GRV_PRINTED:
                                                    ReceiptConfirmationStatus.Constants.RECEIVE_QUANTITY_CONFIRMED;

            Save();
        }
        /// <summary>
        /// Calculates the current volume of a pallet,
        /// this assumes that the box levels have all the dimentions set.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public double CalculateCurrentVolume(int id)
        {
            Pallet p = new Pallet();

            p.GetAllItemsInPallet(id);
            ReceiveDoc       rd     = new ReceiveDoc();
            ItemManufacturer im     = new ItemManufacturer();
            double           volume = 0;

            foreach (DataRowView drv in p.DefaultView)
            {
                //Get the recieving box size and manufacturer
                rd.LoadByPrimaryKey(Convert.ToInt32(drv["ReceiveID"]));
                //Handle if the box size was not specified for some reason.
                // this shouldn't happen on a non error condition
                if (drv["BoxSize"].ToString() == "")
                {
                    drv["BoxSize"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, Convert.ToInt32(drv["BoxSize"]));
                if (im.RowCount == 0)
                {
                    im.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, 0);
                }
                double quantity = Convert.ToInt32(drv["Balance"]) / im.QuantityInBasicUnit;
                volume += quantity * im.Volume;
                // find the volume of the items in the current pallet.
            }
            return(volume);
        }
Example #5
0
        internal static PickListDetail GeneratePickListDetail(ReceivePallet receivePallet, int pickListId, decimal qtyInBU)
        {
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadByPrimaryKey(receivePallet.ReceiveID);
            decimal pack = qtyInBU / Convert.ToDecimal(receiveDoc.QtyPerPack);

            PickListDetail pkDetail = new PickListDetail();

            pkDetail.AddNew();
            pkDetail.PickListID = pickListId;
            pkDetail.ItemID     = receiveDoc.ItemID;
            PalletLocation palletLocation = new PalletLocation();

            palletLocation.loadByPalletID(receivePallet.PalletID);
            int palletLocationId;

            try
            {
                palletLocationId = palletLocation.ID;
            }
            catch (Exception exp)
            {
                palletLocationId = receivePallet.PalletLocationID;
                palletLocation.LoadByPrimaryKey(palletLocationId);
            }
            pkDetail.PalletLocationID = palletLocationId;
            if (!receiveDoc.IsColumnNull("BatchNo"))
            {
                pkDetail.BatchNumber = receiveDoc.BatchNo;
            }

            if (!receiveDoc.IsColumnNull("ExpDate"))
            {
                pkDetail.ExpireDate = receiveDoc.ExpDate;
            }

            pkDetail.StoreID      = receiveDoc.StoreID;
            pkDetail.UnitID       = receiveDoc.UnitID;
            pkDetail.ReceiveDocID = receiveDoc.ID;
            if (!receiveDoc.IsColumnNull("Cost"))
            {
                pkDetail.Cost      = Convert.ToDouble(pack) * Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                pkDetail.UnitPrice = Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
            }
            pkDetail.Packs           = pack;
            pkDetail.QtyPerPack      = receiveDoc.QtyPerPack;
            pkDetail.QuantityInBU    = qtyInBU;
            pkDetail.StoreID         = receiveDoc.StoreID;
            pkDetail.ReceivePalletID = receivePallet.ID;
            pkDetail.ManufacturerID  = receiveDoc.ManufacturerId;
            pkDetail.BoxLevel        = 0;
            pkDetail.DeliveryNote    = true;

            pkDetail.PhysicalStoreID = palletLocation.PhysicalStoreID;
            pkDetail.Save();

            return(pkDetail);
        }
 private void RelatedReceipts_Load(object sender, EventArgs e)
 {
     BLL.ReceiveDoc rdoc = new ReceiveDoc();
     rdoc.LoadByPrimaryKey(_reciptID);
     if (mode==RelatedReceiptMode.WAREHOUSE_MODE)
     {
         gridMain.DataSource = BLL.Receipt.GetRawInventoryCountbyAccountandWarehouseItem(_accountID, _warehouseID,
             rdoc.ItemID, rdoc.UnitID);
     }
     else if(mode==RelatedReceiptMode.PHYSICAL_STORE_MODE)
     {
         gridMain.DataSource = BLL.Receipt.GetRawInventoryCountbyAccountandPhysicalStoreItem(_accountID, _warehouseID,
             rdoc.ItemID, rdoc.UnitID);
     }
 }
Example #7
0
 public static bool MarkReceivedBatchAsEmpty(int receiveID)
 {
     try
     {
         BLL.ReceiveDoc rec = new ReceiveDoc();
         rec.LoadByPrimaryKey(receiveID);
         if (rec.RowCount > 0)
         {
             rec.QuantityLeft = 0;
             rec.Out          = true;
             rec.Save();
             return(true);
         }
         return(false);
     }
     catch
     {
         return(false);
     }
 }
Example #8
0
        public void SaveCostCoefficient(int userID)
        {
            ReceiveDoc grvFullDetail = new ReceiveDoc();

            grvFullDetail.FlushData();
            grvFullDetail.LoadAllByReceiptID(GRV.ID);
            CostBuildUp.SaveChange();
            while (!grvFullDetail.EOF)
            {
                //Insurance here is costCoefficient
                ReceiveDoc receivedoc = new ReceiveDoc();
                receivedoc.LoadByPrimaryKey(grvFullDetail.ID);
                //Use Custom StoreProcedure for Costing
                receivedoc.Insurance = CostCoefficient;
                receivedoc.Save();
                ReceiveDoc.SetUnitCostByReceiveDoc(grvFullDetail.ID, Math.Round(receivedoc.PricePerPack * CostCoefficient, 2), userID);
                ReceiveDoc.SetAverageCostByReceiveDoc(grvFullDetail.ID, Math.Round(receivedoc.PricePerPack * CostCoefficient, 2), userID);
                grvFullDetail.MoveNext();
            }
        }
 public static bool MarkReceivedBatchAsEmpty(int receiveID)
 {
     try
     {
         BLL.ReceiveDoc rec = new ReceiveDoc();
         rec.LoadByPrimaryKey(receiveID);
         if (rec.RowCount > 0)
         {
             rec.QuantityLeft = 0;
             rec.Out = true;
             rec.Save();
             return true;
         }
         return false;
     }
     catch
     {
         return false;
     }
 }
        private void btnDispose_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate()) return;

            TransferService transferService = new TransferService();
            IssueService issueService = new IssueService();

            if (XtraMessageBox.Show("Please Confirm that you want to dispose the selected items", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                int activityID = Convert.ToInt32(glkActivity.EditValue);
                var dt = (DataView)grdSelectedExpiredItemsView.DataSource;

                Order order = OrderForDisposal(activityID);
                PickList picklist = PickList.GeneratePickList(order.ID);

                BLL.Issue stvLog = issueService.CreateSTVLog(null, false, picklist, order, null, activityID, false, CurrentContext.UserId);

                foreach (DataRow row in dt.Table.Rows)
                {
                    ReceiveDoc rd = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();

                    rd.LoadByPrimaryKey((int)row["ReceiveDocID"]);
                    rp.LoadByReceiveDocID((int)row["ReceiveDocID"]);

                    var picklistDetail = transferService.GeneratePickListDetail(rd, rp, order, picklist);
                    issueService.CreateIssueFromPicklist(picklistDetail, order, DateTime.Now, stvLog, CurrentContext.LoggedInUser);
                }

                HCMIS.Reports.Workflow.Activities.Disposal disposalPrintout = new HCMIS.Reports.Workflow.Activities.Disposal(glkActivity.Text, txtLicenseNo.Text, DateTime.Now, ((DataView)grdSelectedExpiredItemsView.DataSource).Table);
                disposalPrintout.PrintDialog();

                RefreshSelection();
                txtLicenseNo.ResetText();
            }
        }
        internal void SetStatusConfirmQuantityAndLocation(int receiveID, int?userID)
        {
            LoadByReceiveDocID(receiveID);
            BLL.ReceiveDoc rcDoc = new ReceiveDoc();
            BLL.Receipt    rct   = new Receipt();
            rcDoc.LoadByPrimaryKey(receiveID);
            rct.LoadByPrimaryKey(rcDoc.ReceiptID);
            if (RowCount == 0)
            {
                AddNew();
                ReceiveDocID = receiveID;
            }

            if (userID.HasValue)
            {
                ReceiptQuantityConfirmedByUserID = userID.Value;
            }

            ReceiptConfirmationStatusID = rct.ReceiptTypeID == BLL.ReceiptType.CONSTANTS.BEGINNING_BALANCE?
                                          ReceiptConfirmationStatus.Constants.GRV_PRINTED:
                                          ReceiptConfirmationStatus.Constants.RECEIVE_QUANTITY_CONFIRMED;

            Save();
        }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

            if (backgroundWorker != null)
            {
                backgroundWorker.ReportProgress(0, "Detail");
            }
            //Add the System Damaged quantity, System Sound Quantity and System Expired Quantity to generate this.
            decimal endingSoundBalance, endingDamagedBalance, endExpiredBalance;

            endingSoundBalance   = !IsColumnNull("SystemSoundQuantity") ? SystemSoundQuantity : 0;
            endingDamagedBalance = !IsColumnNull("SystemDamagedQuantity") ? SystemDamagedQuantity : 0;
            endExpiredBalance    = !IsColumnNull("SystemExpiredQuantity") ? SystemExpiredQuantity : 0;

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();

            itemUnit.LoadByPrimaryKey(UnitID);
            if (IsColumnNull("ReceiveDocID") && IsColumnNull("DamagedReceiveDocID")) // This has been recently added to
            {
                if (endingTotalBalance > 0)
                {
                    OrderDetail.GenerateOrderDetail(UnitID, ActivityID, endingTotalBalance,
                                                    InventoryCommitMemberInstance.Order.ID, itemUnit.QtyPerUnit, ItemID);

                    //TODO: Get the receive doc details for this inventory object
                    ReceivePallet receivePallet = new ReceivePallet();
                    receivePallet.LoadForInventory(this);
                    receivePallet.Rewind();

                    while (!receivePallet.EOF)
                    {
                        //Review: New Code
                        PickListDetail pickListDetail = PickListDetail.GeneratePickListDetail(receivePallet,
                                                                                              InventoryCommitMemberInstance
                                                                                              .PickList.ID,
                                                                                              Convert.ToDecimal(
                                                                                                  receivePallet.Balance));

                        //TODO: Create the issueDoc, pass the picklistdetail, orderid and picklist above
                        IssueService issueService = new IssueService();

                        IssueDoc issueDoc = issueService.CreateIssueFromPicklist(pickListDetail,
                                                                                 InventoryCommitMemberInstance.Order,
                                                                                 ethiopianDate,
                                                                                 InventoryCommitMemberInstance.Issue,
                                                                                 InventoryCommitMemberInstance.User);

                        //Link IssueDoc to InventoryTable
                        // Could have put it on the issueService method but it would have decrease the useablity
                        IssueDocInventory issueDocInventory = new IssueDocInventory();
                        issueDocInventory.AddNew();
                        issueDocInventory.InventoryID = ID;
                        issueDocInventory.IssueDocID  = issueDoc.ID;
                        issueDocInventory.Save();

                        receivePallet.MoveNext();
                        count++;
                        if (backgroundWorker != null)
                        {
                            backgroundWorker.ReportProgress(
                                Convert.ToInt32((Convert.ToDecimal(count) / Convert.ToDecimal(receivePallet.RowCount)) * 100),
                                "Detail");
                        }
                    }
                }
                //TODO: Create the receive (use the inventory object itself)
                ReceiveService receiveService = new ReceiveService();
                if (!IsColumnNull("InventorySoundQuantity") && InventorySoundQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Sound,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryExpiredQuantity") && InventoryExpiredQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Expired,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryDamagedQuantity") && InventoryDamagedQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                  ID, QuantityType.Damaged,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    DamagedReceiveDocID = receiveDoc.ID;
                }

                if (backgroundWorker != null)
                {
                    backgroundWorker.ReportProgress(100, "Detail");
                }
            }
            else
            {
                if (!IsColumnNull("ReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(ReceiveDocID);
                    receiveDoc.ChangeQuantity(!IsColumnNull("InventorySoundQuantity") ? InventorySoundQuantity
                                                            : !IsColumnNull("InventoryExpiredQuantity") ? InventoryExpiredQuantity
                                                                                        : 0);
                }

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }
        /// <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();
            }
        }
Example #14
0
        /// <summary>
        /// Gets the pick list details for order.
        /// </summary>
        /// <param name="ordID">The ord ID.</param>
        /// <param name="Preparedby">The preparedby.</param>
        /// <returns></returns>
        public DataView GetPickListDetailsForOrder(int ordID, string Preparedby)
        {
            this.LoadByOrderID(ordID);
            var query = HCMIS.Repository.Queries.PickList.SelectGetPickListDetailsForOrder(this.ID);

            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(decimal));
            this.DataTable.Columns.Add("SKUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(decimal));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));
            this.DataTable.Columns.Add("PreparedBy", typeof(string));
            int i = 1;

            while (!this.EOF)
            {
                decimal packs = Convert.ToDecimal(this.GetColumn("Packs"));


                int          manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m            = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin.Contains("Ethiopia"))
                {
                    this.SetColumn("IsManufacturerLocal", true);
                }
                else
                {
                    this.SetColumn("IsManufacturerLocal", false);
                }

                int           recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp          = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    Receipt    receipt    = new Receipt();
                    receiveDoc.LoadByPrimaryKey(rp.ReceiveID);
                    receipt.LoadByPrimaryKey(receiveDoc.ReceiptID);
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                    if (BLL.Settings.PrintUserNameOnInvoice)
                    {
                        this.SetColumn("PreparedBy", Preparedby);
                    }
                }
                catch
                {
                }

                int     itemId     = Convert.ToInt32(this.GetColumn("ItemID"));
                int     boxLevel   = Convert.ToInt32(this.GetColumn("BoxLevel"));
                decimal qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToDecimal(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                if (this.IsColumnNull("DeliveryNote"))
                {
                    this.SetColumn("DeliveryNote", false);
                }
                this.MoveNext();
            }
            return(this.DefaultView);
        }
        /// <summary>
        /// Releases the reservation.
        /// </summary>
        public void ReleaseReservation()
        {
            PickList pickList = new PickList();
            pickList.LoadByOrderID(this.ID);
            if (pickList.RowCount == 0) //If there is no picklist, there is nothing to release.
                return;
            PickListDetail pld = new PickListDetail();
            pld.LoadByPickListID(pickList.ID);
            pld.Rewind();
            while (!pld.EOF)
            {
                ReceivePallet receivePallet = new ReceivePallet();
                receivePallet.LoadByPrimaryKey(pld.ReceivePalletID);
                ReceiveDoc rdoc = new ReceiveDoc();
                rdoc.LoadByPrimaryKey(pld.ReceiveDocID);

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

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

            }
            pld.Save();
            pickList.MarkAsDeleted();
            pickList.Save();
        }
        /// <summary>
        /// Moves the specified pick list ID.
        /// </summary>
        /// <param name="PickListID">The pick list ID.</param>
        public static void Move(int PickListID)
        {
            DataView dv = GetTransferReportForStore();
            PalletLocation pl = new PalletLocation();
            foreach (DataRowView dr in dv)
            {

                int amount = Convert.ToInt32(dr["packs"]);
                int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                ReceivePallet rp = new ReceivePallet();
                ReceiveDoc rdoc = new ReceiveDoc();

                rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                rdoc.LoadByPrimaryKey(rp.ReceiveID);
                amount *= rdoc.QtyPerPack;

                int qPalletLocationID = PalletLocation.GetTransferPalletLocation(Convert.ToInt32(dr["PhysicalStoreID"]));
                pl.LoadByPrimaryKey(qPalletLocationID);
                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet p = new Pallet();
                    p.AddNew();
                    p.StorageTypeID = Convert.ToInt32(StorageType.Quaranteen);
                    p.Save();
                    pl.PalletID = p.ID;
                    pl.Save();
                }

                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc rd = new ReceiveDoc();

                rd.LoadByPrimaryKey(rp.ReceiveID);
                rp2.AddNew();

                rp2.PalletID = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;

                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                if (dr["BoxLevel"] == DBNull.Value)
                {
                    dr["BoxLevel"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                int packqty = (amount / im.QuantityInBasicUnit);
                rp2.ReservedStock = 0;
                rp.ReservedStock -= amount;
                BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                //rp2.Balance = amount;
                //rp.Balance -= rp2.Balance;

                //rp.Save();
                //rp2.Save();

                pl.Confirmed = false;
                pl.Save();
                if (rp.Balance == 0)
                {
                    PalletLocation.GarbageCollection();
                }

            }
        }
        private bool SaveInventoryWithOutUnit()
        {
            var yEnd = new YearEnd();
            var rec = new ReceiveDoc();

            if (IsValid())
            {
                dtDate.Value = DateTime.Now;
                DateTime dtCurent = new DateTime();
                dtDate.CustomFormat = "MM/dd/yyyy";
                dtCurent = ConvertDate.DateConverter(dtDate.Text);

                int year = dtCurent.Year;
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataTable yearEndTable = (DataTable)grdYearEnd.DataSource;

                    for (int i = 0; i < dtBB.Rows.Count; i++)
                    {
                        int id = 0;
                        int storeID = Convert.ToInt32(cboStores.EditValue);
                        if (dtBB.Rows[i]["ItemID"] != DBNull.Value)
                        {
                            var itemID = Convert.ToInt32(dtBB.Rows[i]["ItemID"]);
                            //var unitID = Convert.ToInt32(dtBB.Rows[i]["UnitID"]);
                            id = yEnd.LoadByItemIDStoreAndYear(itemID, storeID, year, false);
                        }
                        if (id != 0 && !ReferenceEquals(yearEndTable.Rows[i]["Physical Inventory"], string.Empty))//There is already a manual entry in the yearend table.
                        {
                            //yEnd.LoadByPrimaryKey(id);
                            yEnd.BBalance = Convert.ToInt64(FilterNumbers(yearEndTable.Rows[i]["Beginning Balance"].ToString()));
                            yEnd.EBalance = Int64.Parse(FilterNumbers(yearEndTable.Rows[i]["Ending Balance(SOH)"].ToString()), NumberStyles.AllowThousands);
                            yEnd.PhysicalInventory = Convert.ToInt64(FilterNumbers(yearEndTable.Rows[i]["Physical Inventory"].ToString()));
                            //yEnd.BatchNo = yearEndTable.Rows[i]["Batch No."].ToString();
                            yEnd.UnitID = 0;
                            yEnd.Remark = yearEndTable.Rows[i]["Remark"].ToString();
                            yEnd.AutomaticallyEntered = false;
                            yEnd.Save();
                        }
                        else//There is no entry in the yearend table under this item name that has been entered manually.
                        {
                            DataRow cRow = dtBB.Rows[i];
                            if (!ReferenceEquals(cRow["Physical Inventory"], string.Empty) && cRow["ItemID"] != DBNull.Value)
                            {
                                var itemID = Convert.ToInt32(cRow["ItemID"]);
                                var unitID = 0;
                                YearEnd.PurgeAutomaticallyEnteredInventoryForUnit(itemID, storeID, year, unitID);
                                //if (areAllBatchesPhyInventoryNullValue == false) //We want to add an inventory record if at least one of the batches has a non empty value.
                                //{
                                yEnd.AddNew();
                                yEnd.ItemID = itemID;
                                yEnd.StoreID = storeID;
                                yEnd.Year = year;
                                yEnd.BBalance = Convert.ToInt64(cRow["Beginning Balance"]);
                                Int64 endBal = Convert.ToInt64(cRow["Ending Balance(SOH)"]);
                                //yEnd.BatchNo = cRow["Batch No."].ToString();
                                yEnd.EBalance = endBal;// Convert.ToInt64(yearEndTable.Rows[i].Cells[5].Value);

                                if (cRow["Physical Inventory"] != DBNull.Value)
                                    yEnd.PhysicalInventory = Convert.ToInt64(cRow["Physical Inventory"]);

                                //yEnd.PhysicalInventory = physicalInventoryTotal;
                                yEnd.UnitID = 0;
                                 yEnd.Remark = cRow["Remark"].ToString();

                                yEnd.AutomaticallyEntered = cRow["Physical Inventory"] == DBNull.Value;
                                yEnd.Save();
                                //}

                                //long physicalInventoryTotal = 0;
                                //bool areAllBatchesPhyInventoryNullValue = true;
                                //if (endBal != yEnd.PhysicalInventory)
                                if (true)
                                {
                                    int k = i + 1;

                                    if (k < dtBB.Rows.Count)
                                    {
                                        while (Convert.ToInt32(dtBB.Rows[k]["RecID"]) != -1)
                                        {
                                            if (dtBB.Rows[k]["Physical Inventory"] != DBNull.Value)
                                            {
                                                //areAllBatchesPhyInventoryNullValue = false;
                                                long batchPhysicalInventory =
                                                    Convert.ToInt64(dtBB.Rows[k]["Physical Inventory"]);
                                                //physicalInventoryTotal += batchPhysicalInventory;
                                                rec.LoadByPrimaryKey(Convert.ToInt32(dtBB.Rows[k]["RecID"]));
                                                rec.QuantityLeft = Convert.ToInt64(batchPhysicalInventory);
                                                rec.Remark = "Physical Inventory";
                                                rec.UnitID = 0;
                                                rec.Out = rec.QuantityLeft == 0;
                                                rec.Save();
                                            }
                                            k++;
                                            if (k >= yearEndTable.Rows.Count)
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Needs to be the first function to be called when saving a new receive doc entry.
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="receiptID"></param>
        /// <param name="dr"></param>
        private void FillInReceiveDocInformation(ReceiveDoc rec, int receiptID, DataRowView dr)
        {
            try
            {
                rec.GetColumn("GUID");
            }
            catch
            {
                rec.AddColumn("GUID", typeof(string));
                //rec.AddColumn("IsDamaged", typeof(bool));
                //This is only used if the Check box is used to receive damaged receives (For SRM only)
            }

            rec.StoreID = Convert.ToInt32(lkAccounts.EditValue);
            rec.RefNo = txtRefNo.Text;
            rec.Remark = txtRemark.Text;

            rec.ReceivedBy = CurrentContext.LoggedInUserName;

            DateTime xx = dtRecDate.Value;
            dtRecDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtRec = new DateTime();
            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);
            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
            rec.EurDate = BLL.DateTimeHelper.ServerDateTime;
            rec.ItemID = Convert.ToInt32(dr["ID"]);
            rec.NoOfPack = Convert.ToDecimal(dr["Pack Qty"]);
            rec.SetColumn("GUID", dr["GUID"].ToString());
            rec.IsDamaged = Convert.ToBoolean(dr["IsDamaged"]);

            if (standardRecType == StandardReceiptType.iGRVOnline)
            {
                rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                rec.SetColumn("Margin", dr["Margin"]);
                rec.SetColumn("UnitCost", dr["Price/Pack"]);
            }

            //TODO: This if is a garbage. Remove
            if (dr["InvoicedQty"] == DBNull.Value)
            {
                rec.InvoicedNoOfPack = rec.NoOfPack;
            }

            rec.InvoicedNoOfPack = srm ? Convert.ToDecimal(dr["IssuedQty"]) : Convert.ToDecimal(dr["OriginalInvoicedQty"]);

            rec.ManufacturerId = Convert.ToInt32(dr["Manufacturer"]);
            BLL.ItemManufacturer im = new BLL.ItemManufacturer();

            im.LoadIMbyLevel(rec.ItemID, rec.ManufacturerId, 0);
            if (dr["UnitID"] != DBNull.Value)
            {
                // if unit has been set, pick the qty per pack from the unit
                rec.UnitID = Convert.ToInt32(dr["UnitID"]);
                ItemUnit itemUnit = new ItemUnit();
                itemUnit.LoadByPrimaryKey(rec.UnitID);

                rec.QtyPerPack = itemUnit.QtyPerUnit;
            }
            else
            {
                rec.QtyPerPack = im.QuantityInBasicUnit;
            }
            rec.Quantity = rec.QuantityLeft = rec.NoOfPack * rec.QtyPerPack;

            try
            {
                if ((deliveryNoteType == DeliveryNoteType.NotSet))
                {
                    if (!BLL.Settings.HandleGRV && !srm)
                    {
                        rec.PricePerPack = Convert.ToDouble(dr["Price/Pack"]);
                        double pre = (Convert.ToDouble(dr["Price/Pack"]) / 1); //rec.QtyPerPack);
                        rec.Cost = pre;
                    }
                    rec.DeliveryNote = false;
                }
                else
                {
                    rec.DeliveryNote = true;
                    if (deliveryNoteType == DeliveryNoteType.Automatic)
                    {
                        rec.SetColumn("PricePerPack", dr["Price/Pack"]);
                        rec.SetColumn("Margin", dr["Margin"]);
                        rec.SetColumn("UnitCost", dr["Price/Pack"]);
                    }
                }
            }
            catch
            {
                // catch the error if the recieve doesn't have cost information
                // NOTE: this shall never happen.
            }

            if (dr["Batch No"] != DBNull.Value)
            {
                rec.BatchNo = dr["Batch No"].ToString(); // receivingGrid.Rows[i].Cells[8].Value.ToString();
            }

            if (dr["Expiry Date"] != DBNull.Value)
            {
                rec.ExpDate = Convert.ToDateTime(dr["Expiry Date"]); //receivingGrid.Rows[i].Cells[9].Value);
            }

            if (!srm)
            {
                rec.SupplierID = _supplierID;
            }
            else
            {
                rec.SupplierID = BLL.Supplier.CONSTANTS.RETURNED_FROM_FACILITY;
                //TODO: Returned From Supplier: To be removed.  This is an unacceptable hack.
                rec.RefNo = lkSTVInvoiceNo.Text;
                if (string.IsNullOrEmpty(txtRemark.Text))
                {
                    XtraMessageBox.Show(
                        "Please enter the reason for the SRM.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new Exception("Reason not entered for SRM");
                }
                else
                {
                    rec.Remark = txtRemark.Text;
                }
            }

            rec.ReturnedStock = srm;

            if (srm && !chkSRMForOldSystemIssues.Checked)
            {
                rec.ReturnedFromIssueDocID = int.Parse(dr["IssueDocID"].ToString());
                int issueDocID = int.Parse(dr["IssueDocID"].ToString());
                BLL.IssueDoc iss = new IssueDoc();
                iss.LoadByPrimaryKey(issueDocID);
                BLL.ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(iss.RecievDocID);
                //If it was a delivery note, then the return will not have price information associated with it.

                // HW-2189
                decimal? UnitCost, SellingPrice, Margin;
                UnitCost = SellingPrice = Margin = null;

                if (!BLL.Settings.HandleGRV)
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice"))
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost"))
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }
                else
                {
                    if (!iss.IsColumnNull("UnitCost") && iss.IsColumnNull("SellingPrice") && iss.UnitCost != 0 &&
                        iss.SellingPrice != 0)
                    {
                        UnitCost = iss.UnitCost;
                        SellingPrice = iss.SellingPrice;
                        Margin = !iss.IsColumnNull("Margin") ? iss.Margin : 0;
                    }
                    else if (!iss.IsColumnNull("Cost") && iss.Cost != 0)
                    {
                        Margin = !rd.IsColumnNull("Margin") ? Convert.ToDecimal(rd.Margin) : 0;
                        SellingPrice = Convert.ToDecimal(iss.Cost / Convert.ToDouble(iss.NoOfPack));
                        UnitCost = BLL.Settings.IsCenter ? SellingPrice : SellingPrice / Convert.ToDecimal(Margin + 1);
                    }
                }

                if (UnitCost.HasValue)
                {
                    rec.PricePerPack = Convert.ToDouble(UnitCost);
                    rec.Cost = Convert.ToDouble(UnitCost);
                    rec.UnitCost = UnitCost.Value;
                }

                if (SellingPrice.HasValue)
                {
                    rec.SellingPrice = Convert.ToDouble(SellingPrice);
                }

                if (Margin.HasValue)
                {
                    rec.Margin = Convert.ToDouble(Margin);
                }

                if (!rd.IsColumnNull("SupplierID"))
                    rec.SupplierID = rd.SupplierID;
            }

            rec.ReceiptID = receiptID;
            if (BLL.Settings.HandleGRV && !beginningBalance)
            {
                rec.RefNo = receiptID.ToString();
            }
            else if (beginningBalance)
            {
                rec.RefNo = "BeginningBalance";
            }

            //Needs to be fixed! Garbage
            string batch = DateTimeHelper.ServerDateTime.Day.ToString() + DateTimeHelper.ServerDateTime.Hour.ToString() +
                           DateTimeHelper.ServerDateTime.Minute.ToString() + rec.ItemID.ToString();
            rec.LocalBatchNo = batch;
            rec.Out = false;
            rec.IsApproved = false;
            if (dr["ShortageReasonID"] != DBNull.Value)
            {
                rec.ShortageReasonID = Convert.ToInt32(dr["ShortageReasonID"]);
            }
            var item = new Item();
            item.LoadByPrimaryKey(Convert.ToInt32(dr["id"]));

            if (dr["ShortageReasonID"] == DBNull.Value && (item.NeedExpiryBatch || rec.ExpDate <= DateTimeHelper.ServerDateTime))
            {
                rec.ShortageReasonID = ShortageReasons.Constants.DAMAGED;
            }

            dtRecDate.Value = xx;
            _receiptID = receiptID; //Assign it to the global variable so it can be used later on.
        }
        private void btnMoveToQuaranteen_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToQuaranteen())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to move the items to Quarantine", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    InternalItemMovements ims = new InternalItemMovements();
                    PalletLocation pl = new PalletLocation();
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1 ;
                    for (int i = 0; i < gridView3.RowCount; i++)
                    {
                        DataRow dr = gridView3.GetDataRow(i);
                        if (dr["Loss"] != DBNull.Value)
                        {
                            int amount = Convert.ToInt32(dr["Loss"]);
                            int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                            ReceivePallet rp = new ReceivePallet();
                            ReceiveDoc rdoc = new ReceiveDoc();

                            rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                            rdoc.LoadByPrimaryKey(rp.ReceiveID);
                            amount *= rdoc.QtyPerPack;

                            if (rp.Balance - amount < rp.ReservedStock)
                            {
                                //Item has been reserved for a facility.  This needs to be handled.
                                DataTable dtble = rp.GetFacilitiesItemsReservedFor();
                                string facilities = "";
                                foreach(DataRow dRow in dtble.Rows)
                                {
                                    if (dr != null)
                                        facilities += dRow["Name"].ToString() + System.Environment.NewLine;
                                }
                                XtraMessageBox.Show("You cannot fill in a loss because the item in this location has been reserved to the following facilities:" + System.Environment.NewLine + facilities, "Exisiting reservations must be cancelled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return;
                            }

                            var receiveDocID = Convert.ToInt32(dr["ID"]);
                            var rec = new ReceiveDoc();
                            rec.LoadByPrimaryKey(receiveDocID);

                            int qPalletLocationID = PalletLocation.GetQuaranteenPalletLocation(rec.PhysicalStoreID);
                            pl.LoadByPrimaryKey(qPalletLocationID);
                            if (pl.IsColumnNull("PalletID"))
                            {
                                Pallet p = new Pallet();
                                p.AddNew();
                                p.StorageTypeID = Convert.ToInt32( StorageType.Quaranteen);
                                p.Save();
                                pl.PalletID = p.ID;
                                pl.Save();
                            }

                            ReceivePallet rp2 = new ReceivePallet();
                            ReceiveDoc rd = new ReceiveDoc();

                            rd.LoadByPrimaryKey(rp.ReceiveID);
                            rp2.AddNew();

                            rp2.PalletID = pl.PalletID;
                            rp2.ReceiveID = rp.ReceiveID;
                            rp2.PalletLocationID = pl.ID;

                            // calculate the new balance
                            BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                            //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                            if (dr["BoxLevel"] == DBNull.Value)
                            {
                                dr["BoxLevel"] = 0;
                            }
                            im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                            int packqty = (amount / im.QuantityInBasicUnit);
                            rp2.ReservedStock = 0;

                            BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                            //rp2.Balance = amount;
                            //rp.Balance -= rp2.Balance;

                            //rp.Save();
                            //rp2.Save();

                            pl.Confirmed = false;
                            pl.Save();
                            if (rp.Balance == 0 )
                            {
                                PalletLocation.GarbageCollection();
                            }

                            InternalTransfer it = new InternalTransfer();
                            it.AddNew();
                            it.ItemID = rd.ItemID;
                            it.BoxLevel = im.PackageLevel;
                            if (!rd.IsColumnNull("ExpDate"))
                            {
                                it.ExpireDate = rd.ExpDate;
                            }
                            it.BatchNumber = rd.BatchNo;
                            it.ManufacturerID = im.ManufacturerID;
                            it.FromPalletLocationID = palletLocationID;
                            it.ToPalletLocationID = qPalletLocationID;
                            it.QtyPerPack = im.QuantityInBasicUnit;
                            it.Packs = packqty;
                            it.ReceiveDocID = rp.ReceiveID;
                            it.QuantityInBU = rp2.Balance; //it.Packs * it.QtyPerPack;
                            it.Type = "ToQuaranteen";
                            it.IssuedDate = DateTime.Today;
                            it.Status = 0;
                            it.PrintNumber = printNubmer;
                            it.Save();
                        }
                    }

                    gridConfirmationControl.DataSource = InternalTransfer.GetAllTransfers("ToQuaranteen");

                    PopulateItemDetails();
                    XtraMessageBox.Show("Your items are marked for movement to Quarantine, please go to Internal Movements page to confirm!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void btnCommit_Click(object sender, EventArgs e)
        {
            if (ValidateQuarantine())
            {

                MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                transaction.BeginTransaction();
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to commit the Loss and Adjustment on this screen?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    // do the actual commit here.
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1;
                    PalletLocation pl = new PalletLocation();
                    Pallet p = new Pallet();
                    ReceiveDoc rdoc = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        DataRow dr = gridView1.GetDataRow(i);
                        Double writeoff = 0;
                        Double reLocate = 0;
                        try
                        {
                            if (dr["WriteOff"] != DBNull.Value)
                            {
                                writeoff = Double.Parse(dr["WriteOff"].ToString());
                            }
                            if (dr["ReLocate"] != DBNull.Value)
                            {
                                reLocate = Double.Parse(dr["ReLocate"].ToString());
                            }
                        }
                        catch (Exception exc)
                        {
                        }

                        if(dr["WriteOff"] != DBNull.Value & writeoff>0)
                        {
                            if (Double.Parse(dr["WriteOff"].ToString()) > Double.Parse(dr["Balance"].ToString()))
                            {
                                XtraMessageBox.Show("Couldn't commit to the numbers you specified. Please specify number less than the balance.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            int writeoffAmout = Convert.ToInt32(dr["WriteOff"]);
                            int qtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                            writeoffAmout *= qtyPerPack;
                            rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                            rdoc.LoadByPrimaryKey(rp.ReceiveID);
                            string x = dr["NewPalletLocation"].ToString();
                            rp.Balance -= writeoffAmout;
                            try
                            {
                              //  rp.ReceivedQuantity -= writeoffAmout;
                            }
                            catch { }
                            rdoc.QuantityLeft -= writeoffAmout;

                             ReceivePallet nrp =new ReceivePallet();
                             nrp.AddNew();
                             nrp.ReceiveID = rp.ReceiveID;
                             nrp.PalletID = pl.GetpalletidbyPalletLocationOrgetnew(int.Parse(dr["NewPalletLocation"].ToString()));
                            //nrp.ReceivedQuantity = rp.ReceivedQuantity;
                            nrp.Balance = writeoffAmout;
                            nrp.ReservedStock = 0;
                            //nrp.ReserveOrderID = rp.ReserveOrderID;
                            nrp.BoxSize = rp.BoxSize;
                            nrp.PalletLocationID = int.Parse(dr["NewPalletLocation"].ToString());
                            nrp.IsOriginalReceive = rp.IsOriginalReceive;

                            BLL.LossAndAdjustment d = new BLL.LossAndAdjustment();
                            d.AddNew();
                            d.GenerateRefNo();
                            d.ItemID = Convert.ToInt32(dr["ItemID"]);
                            d.ReasonId = Convert.ToInt32(dr["Reason"]);
                            d.RecID = rdoc.ID;
                            d.Quantity = writeoffAmout;
                            d.BatchNo = rdoc.BatchNo;

                            CalendarLib.DateTimePickerEx edate = new CalendarLib.DateTimePickerEx();
                            edate.Value = DateTime.Today;
                            //TODO: fix to an ethiopian date here
                            edate.CustomFormat = "MM/dd/yyyy";

                            d.Date = ConvertDate.DateConverter(edate.Text);

                            d.EurDate = DateTime.Today;
                             d.Cost = rdoc.IsColumnNull("Cost")? 0: Math.Abs(rdoc.Cost * writeoffAmout);
                            d.StoreId = rdoc.StoreID;
                            d.Losses = true;
                            //todo:
                            d.ApprovedBy = CurrentContext.UserId.ToString();
                            //d.Remarks

                             InternalTransfer it =new  InternalTransfer();
                             it.AddNew();
                            it.ItemID = d.ItemID;
                            it.FromPalletLocationID = pl.GetPalletLocationIDByPalletID(int.Parse(dr["PalletID"].ToString()));
                            it.ToPalletLocationID = nrp.PalletLocationID;
                            it.BatchNumber = d.BatchNo;
                            if (!rdoc.IsColumnNull("ExpDate"))
                            {
                                it.ExpireDate = rdoc.ExpDate;
                            }
                            it.ReceiveDocID = rdoc.ID;
                            it.ManufacturerID = rdoc.ManufacturerId;
                            it.QtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                            it.Packs = rdoc.NoOfPack;
                            it.QuantityInBU = nrp.Balance;

                            LossAndAdjustmentReason r = new LossAndAdjustmentReason();
                            it.Type = r.GetReasonByID(d.ReasonId);

                           // d.Save();
                            rdoc.Save();
                            rp.Save();

                            rdoc.QuantityLeft += writeoffAmout;
                             rdoc.Save();
                             nrp.Save();
                             it.Save();
                            int xs = it.ID;
                        }
                        else if (dr["ReLocate"] != DBNull.Value & reLocate > 0)
                         {

                             if (dr["ReLocate"] != DBNull.Value)
                             {
                                 int amount = Convert.ToInt32(dr["ReLocate"]);
                                 int qtyPerPack = Convert.ToInt32(dr["QtyPerPack"]);
                                 amount *= qtyPerPack;
                                 rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                                 rdoc.LoadByPrimaryKey(rp.ReceiveID);
                                 int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                                 int qPalletLocationID =
                                     PalletLocation.GetQuaranteenPalletLocationByPalletLocationID(palletLocationID);//PalletLocation.GetQuaranteenPalletLocation(Convert.ToInt32(dr["ID"]));
                                 pl.LoadByPrimaryKey(qPalletLocationID);

                                 ReceivePallet rp2 = new ReceivePallet();
                                 ReceiveDoc rd = new ReceiveDoc();
                                 Pallet pallet = new Pallet();
                                 rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                                 rd.LoadByPrimaryKey(rp.ReceiveID);
                                 pallet.AddNew();
                                 Item item = new Item();
                                 item.LoadByPrimaryKey(rdoc.ItemID);
                                 if (item.StorageTypeID.ToString() == StorageType.BulkStore)
                                 {
                                     pallet.PalletNo = Pallet.GetLastPanelNumber();

                                 }
                                 pallet.Save();
                                 rp2.AddNew();
                                 rp2.PalletID = pl.GetpalletidbyPalletLocationOrgetnew(int.Parse(dr["NewPalletLocation"].ToString()));//pallet.ID;
                                 rp2.ReceiveID = rp.ReceiveID;
                                 rp2.IsOriginalReceive = rp.IsOriginalReceive;
                                 // calculate the new balance
                                 BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                                 //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                                 //im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                                 //int packqty = (amount / im.QuantityInBasicUnit);
                                 rd.QuantityLeft -= amount;
                                 rp.Balance -= amount;
                                rd.Save();
                                rp.Save();

                                 rd.QuantityLeft += amount;
                                 rp2.Balance = amount;//packqty * im.QuantityInBasicUnit;
                                 rd.Save();

                                 rp2.BoxSize = rp.BoxSize;
                                 rp2.ReservedStock = 0;
                                 rp2.PalletLocationID= int.Parse(dr["NewPalletLocation"].ToString());
                                 rp2.Save();

                                 pl.Confirmed = false;
                                 pl.Save();

                                 // select the new pallet location here.
                              /*   XtraForm xdb = new XtraForm();
                                 xdb.Controls.Add(panelControl2);
                                 Item itms= new Item();
                                 itms.GetItemByPrimaryKey(Convert.ToInt32(dr["ItemID"]));
                                 lblItemName.Text = itms.FullItemName;
                                 panelControl2.Visible = true;
                                 panelControl2.Dock = DockStyle.Fill;
                                 xdb.Text = "Select Location for relocated Item";
                                 lkLocation.Properties.DataSource = PalletLocation.GetAllFreeFor(Convert.ToInt32(dr["ItemID"]));
                                 xdb.ShowDialog();

                                 PalletLocation pl2 = new PalletLocation();
                                 pl2.LoadByPrimaryKey(Convert.ToInt32(lkLocation.EditValue));
                                 pl2.PalletID = pallet.ID;
                                 pl2.Confirmed = false;
                                 pl2.Save();
                                 */
                                 InternalTransfer it = new InternalTransfer();

                                 it.AddNew();
                                 it.ItemID = rd.ItemID;
                                 it.BoxLevel = 0;// im.PackageLevel;
                                 //it.ExpireDate = rd.ExpDate;
                                 if (!rd.IsColumnNull("ExpDate"))
                                 {
                                     it.ExpireDate = rd.ExpDate;
                                 }
                                 it.BatchNumber = rd.BatchNo;
                                 it.ManufacturerID = Convert.ToInt32(dr["ManufacturerID"]);//im.ManufacturerID;
                                 it.FromPalletLocationID = qPalletLocationID;
                                 it.ToPalletLocationID = int.Parse(dr["NewPalletLocation"].ToString()); //pl2.ID;
                                 it.QtyPerPack = 1;
                                //it.Packs = pack qty;
                                 it.ReceiveDocID = rp.ReceiveID;
                                 it.QuantityInBU = amount;// it.QtyPerPack;
                                 it.Type = "ReLocation";
                                 it.IssuedDate = DateTime.Today;
                                 it.Status = 0;
                                 it.PrintNumber = printNubmer;
                                 it.Save();
                             }
                         }
                    }
                    transaction.CommitTransaction();
                    BindQuarantine();
                    XtraMessageBox.Show("Quarantine Write off/Adjustment was commitd.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        internal void Commit(DateTime ethiopianDate, BackgroundWorker backgroundWorker = null)
        {
            InventoryCommitMemberInstance.Transaction.BeginTransaction();
            //TODO: Create the order detail, pass the order id above this inventory object
            int count = 0;

            if (backgroundWorker != null)
            {
                backgroundWorker.ReportProgress(0, "Detail");
            }
            //Add the System Damaged quantity, System Sound Quantity and System Expired Quantity to generate this.
            decimal endingSoundBalance, endingDamagedBalance, endExpiredBalance;
            endingSoundBalance = !IsColumnNull("SystemSoundQuantity") ? SystemSoundQuantity : 0;
            endingDamagedBalance = !IsColumnNull("SystemDamagedQuantity") ? SystemDamagedQuantity : 0;
            endExpiredBalance = !IsColumnNull("SystemExpiredQuantity") ? SystemExpiredQuantity : 0;

            decimal endingTotalBalance = endingSoundBalance + endingDamagedBalance + endExpiredBalance;

            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadByPrimaryKey(UnitID);
            if (IsColumnNull("ReceiveDocID") && IsColumnNull("DamagedReceiveDocID")) // This has been recently added to
            {

                if (endingTotalBalance > 0)
                {

                    OrderDetail.GenerateOrderDetail(UnitID, ActivityID, endingTotalBalance,
                                                    InventoryCommitMemberInstance.Order.ID, itemUnit.QtyPerUnit, ItemID);

                    //TODO: Get the receive doc details for this inventory object
                    ReceivePallet receivePallet = new ReceivePallet();
                    receivePallet.LoadForInventory(this);
                    receivePallet.Rewind();

                    while (!receivePallet.EOF)
                    {

                        //Review: New Code
                        PickListDetail pickListDetail = PickListDetail.GeneratePickListDetail(receivePallet,
                                                                                              InventoryCommitMemberInstance
                                                                                                  .PickList.ID,
                                                                                              Convert.ToDecimal(
                                                                                                  receivePallet.Balance));

                        //TODO: Create the issueDoc, pass the picklistdetail, orderid and picklist above
                        IssueService issueService = new IssueService();

                        IssueDoc issueDoc = issueService.CreateIssueFromPicklist(pickListDetail,
                                                                                 InventoryCommitMemberInstance.Order,
                                                                                 ethiopianDate,
                                                                                 InventoryCommitMemberInstance.Issue,
                                                                                 InventoryCommitMemberInstance.User);

                        //Link IssueDoc to InventoryTable
                        // Could have put it on the issueService method but it would have decrease the useablity
                        IssueDocInventory issueDocInventory = new IssueDocInventory();
                        issueDocInventory.AddNew();
                        issueDocInventory.InventoryID = ID;
                        issueDocInventory.IssueDocID = issueDoc.ID;
                        issueDocInventory.Save();

                        receivePallet.MoveNext();
                        count++;
                        if (backgroundWorker != null)
                        {
                            backgroundWorker.ReportProgress(
                                Convert.ToInt32((Convert.ToDecimal(count) / Convert.ToDecimal(receivePallet.RowCount)) * 100),
                                "Detail");
                        }
                    }

                }
                //TODO: Create the receive (use the inventory object itself)
                ReceiveService receiveService = new ReceiveService();
                if (!IsColumnNull("InventorySoundQuantity") && InventorySoundQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                      ID, QuantityType.Sound,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryExpiredQuantity") && InventoryExpiredQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                      ID, QuantityType.Expired,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    ReceiveDocID = receiveDoc.ID;
                }

                if (!IsColumnNull("InventoryDamagedQuantity") && InventoryDamagedQuantity > 0)
                {
                    ReceiveDoc receiveDoc = receiveService.CreateInventoryReceive(this,
                                                                                  InventoryCommitMemberInstance.Receipt.
                                                                                      ID, QuantityType.Damaged,
                                                                                  ethiopianDate,
                                                                                  InventoryCommitMemberInstance.User);
                    DamagedReceiveDocID = receiveDoc.ID;
                }

                if (backgroundWorker != null)
                {
                    backgroundWorker.ReportProgress(100, "Detail");
                }

            }
            else
            {

                if (!IsColumnNull("ReceiveDocID"))
                {

                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(ReceiveDocID);
                    receiveDoc.ChangeQuantity(!IsColumnNull("InventorySoundQuantity") ? InventorySoundQuantity
                                                            : !IsColumnNull("InventoryExpiredQuantity") ? InventoryExpiredQuantity
                                                                                        : 0);

                }

                if (!IsColumnNull("DamagedReceiveDocID"))
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByPrimaryKey(DamagedReceiveDocID);
                    receiveDoc.ChangeQuantity(InventoryDamagedQuantity);
                }
            }
            IsDraft = false;
            Save();
            InventoryCommitMemberInstance.Transaction.CommitTransaction();
        }
        private void PopulateListToGrid()
        {
            _dtRecGrid = new DataTable();
            var itm = new Items();
            var rec = new ReceiveDoc();
            _tabPage = 1;
            tabControl1.SelectedTabPageIndex = 1;
            if (_dtRecGrid.Columns.Count == 0)
            {
                string[] str = { "ID", "Stock Code", "Item Name", "Batch No", "Unit", "BU Qty", "Price", "Qty To Transfer", "RecID", "UnitID"};
                foreach (string col in str)
                {
                    _dtRecGrid.Columns.Add(col);
                }
            }
            int count = 1;
            foreach (DataRow dr in _dtSelectedTable.Rows)
            {
                rec.LoadByPrimaryKey(Convert.ToInt32(dr["ReceiveID"]));

                int id = Convert.ToInt32(dr["ItemID"]);
                double price = 0;
                if (!rec.IsColumnNull("Cost"))
                {
                    price = (rec.RowCount > 0) ? Convert.ToDouble(rec.Cost) * rec.QuantityLeft : 0;
                }
                DataTable dtItm = itm.GetItemById(id);
                string itemName = dtItm.Rows[0]["FullItemName"].ToString();
                object[] obj;
                switch (VisibilitySetting.HandleUnits)
                {
                    case 1:
                        obj = new object[]
                                 {
                                     id, dtItm.Rows[0]["StockCode"].ToString(),itemName, rec.BatchNo, dtItm.Rows[0]["Unit"].ToString(),rec.QuantityLeft, price, "",Convert.ToInt32(dr["ReceiveID"]),0};
                        break;
                    case 2:
                        obj = new object[]
                                 {
                                     id, dtItm.Rows[0]["StockCode"].ToString(),itemName, rec.BatchNo, dtItm.Rows[0]["Unit"].ToString(),rec.QuantityLeft, price, "",Convert.ToInt32(dr["ReceiveID"]),rec.UnitID
                                 };
                        break;
                    default:
                        obj = new object[]
                                 {
                                     id, dtItm.Rows[0]["StockCode"].ToString(),itemName, rec.BatchNo, dtItm.Rows[0]["Unit"].ToString(),rec.QuantityLeft, price, "",Convert.ToInt32(dr["ReceiveID"]),rec.UnitID
                                 };
                        break;
                }
                _dtRecGrid.Rows.Add(obj);
                count++;
            }
            receivingGrid.DataSource =_dtRecGrid;
            txtTranferFrom.Text = lkFromStore.Text;
        }
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            var confirmedItemsQuantity = new Dictionary<int, long>();
            var confirmedItems = new List<int>();
            var valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You Want To Save This Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    var issDoc = new IssueDoc();
                    var recDoc = new ReceiveDoc();
                    DataTable dtConfirm;
                    long currentSOH = 0;
                    var storeId = 0;
                    var itemId = 0;

                    using (dtConfirm = (DataTable)gridConfirmation.DataSource)
                    {
                        for (int i = 0; i < dtConfirm.Rows.Count; i++)
                        {
                           var receivedocid = Convert.ToInt32(dtConfirm.Rows[i]["RecId"]);
                            issDoc.GetDULastIssue(Convert.ToInt32(dtConfirm.Rows[i]["ItemID"]), Convert.ToInt32(cboReceivingUnits.EditValue));
                            confirmedItems.Add(Convert.ToInt32(dtConfirm.Rows[i]["ItemID"]));
                            if (issDoc.RowCount > 0)
                            {
                                //issDoc.DUSOH = ((dtConfirmation.Rows[i]["DUSOH"] != null) ? Convert.ToInt64(dtConfirmation.Rows[i]["DUSOH"]) : 0);
                                //issDoc.Save();
                            }
                            //Saving the issue
                            issDoc.AddNew();
                            issDoc.StoreId = Convert.ToInt32(cboStores.EditValue);
                            issDoc.RefNo = txtRefNo.Text.Trim();
                            issDoc.ReceivingUnitID = Convert.ToInt32(cboReceivingUnits.EditValue);
                            DateTime xx = dtIssueDate.Value;
                            dtIssueDate.CustomFormat = "MM/dd/yyyy";

                            DateTime dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                            issDoc.Date = dtCurrent;
                            dtIssueDate.IsGregorianCurrentCalendar = true;
                            issDoc.EurDate = dtIssueDate.Value;
                            dtIssueDate.IsGregorianCurrentCalendar = false;
                            issDoc.RecievDocID =Convert.ToInt32(dtConfirm.Rows[i]["RecId"]); // Used to have 8 as an index
                            recDoc.LoadByPrimaryKey(receivedocid);
                            issDoc.IsApproved = true;
                            issDoc.IsTransfer = false;

                            issDoc.Remark = txtRemark.Text;
                            issDoc.RecipientName = txtRecipientName.Text;
                            issDoc.IssuedBy = txtIssuedBy.Text;
                            issDoc.DUSOH = Convert.ToInt32(dtConfirm.Rows[i]["DUSOH"]);
                            issDoc.ItemID = Convert.ToInt32(dtConfirm.Rows[i]["ItemId"]);
                            issDoc.Quantity = Convert.ToInt64(dtConfirm.Rows[i]["Quantity"]);

                            issDoc.NoOfPack = Convert.ToInt32(dtConfirm.Rows[i]["No Of Pack"]);
                            issDoc.QtyPerPack = Convert.ToInt32(dtConfirm.Rows[i]["Qty Per Pack"]);
                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    issDoc.UnitID = 0;
                                    break;
                                case 2:
                                    issDoc.UnitID = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                                    break;
                                default:
                                    issDoc.UnitID = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                                    break;
                            }
                            issDoc.BatchNo = dtConfirm.Rows[i]["BatchNo"].ToString();
                            issDoc.Cost = Convert.ToDouble(dtConfirm.Rows[i]["Unit Price"]);
                            issDoc.RecomendedQty = Convert.ToInt32(dtConfirm.Rows[i]["DURecomended"]);// ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                            //End DU
                            issDoc.Save();
                            //updating the receiving doc
                            recDoc.LoadByPrimaryKey(Convert.ToInt32(dtConfirm.Rows[i]["RecId"]));
                            //this line calculates the current SOH
                            recDoc.QuantityLeft = recDoc.QuantityLeft - issDoc.Quantity;
                            currentSOH = currentSOH + recDoc.QuantityLeft;

                            itemId = Convert.ToInt32(dtConfirm.Rows[i]["ItemId"]);
                            var unitId = Convert.ToInt32(dtConfirm.Rows[i]["UnitID"]);
                            if (recDoc.QuantityLeft != 0)
                                recDoc.Out = false;
                            else
                                recDoc.Out = true;

                            if (confirmedItemsQuantity.ContainsKey(itemId))
                                confirmedItemsQuantity[itemId] += recDoc.QuantityLeft;
                            else
                            {
                                confirmedItemsQuantity.Add(itemId, recDoc.QuantityLeft);
                            }
                            recDoc.Save();

                            storeId = Convert.ToInt32(cboStores.EditValue);

                            //Log Activity
                            dtIssueDate.Value = xx;
                            Builder.RefreshAMCValues(storeId, confirmedItemsQuantity,unitId);
                        }

                        //save stockout information for the current item in current store
                        //if current SOH after this issue is 0
                        if (currentSOH == 0)
                        {
                            StockoutLog stockoutLog = new StockoutLog();
                            stockoutLog.AddNew();
                            stockoutLog.StoreID = storeId;
                            stockoutLog.ItemID = itemId;
                            stockoutLog.StartDate = DateTime.Today;
                            stockoutLog.Save();
                        }
                    }
                    XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            xpButton2_Click(sender, e);
            issueGrid.DataSource = null;
            issueGridView.RefreshData();
            RefreshItems();
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);

            var dr = gridView1.GetFocusedDataRow();

            if (dr == null) return;

            int tranId = Convert.ToInt32(dr["ID"]);
            var rec = new ReceiveDoc();
            rec.LoadByPrimaryKey(tranId);
            var iss = new IssueDoc();
            iss.GetIssueByBatchAndId(rec.ItemID, rec.BatchNo, rec.ID);
            _dtDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtCurrent = ConvertDate.DateConverter(_dtDate.Text);
            if ((rec.Date.Year != dtCurrent.Year && rec.Date.Month < 11) || (iss.RowCount != 0))
            {
                XtraMessageBox.Show("Unable to Delete, This Transaction has been processed. Try Loss and Adjustment.",
                                    "Unable to Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else
            {

                if (
                    XtraMessageBox.Show(
                        "Are You Sure, You want to delete this Transaction? You will not be able to restore this data.",
                        "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //AddDeletedRecieveDoc(rec);
                    rec.MarkAsDeleted();
                    rec.Save();

                    _dtDate.Value = DateTime.Now;
                    _dtDate.CustomFormat = "MM/dd/yyyy";
                    dtCurrent = ConvertDate.DateConverter(_dtDate.Text);
                    int yr = ((dtCurrent.Month > 10) ? dtCurrent.Year : dtCurrent.Year - 1);
                    DateTime dt1 = new DateTime(yr, 11, 1);
                    DateTime dt2 = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day);
                    DataTable dtRec = rec.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), dt1, dt2);
                    gridReceives.DataSource = dtRec;
                }
            }
        }
        private void tpDelete_Click(object sender, EventArgs e)
        {
            DataRow dr = gridViewBinCard.GetFocusedDataRow();
             if (Convert.ToInt32(dr["Precedance"]) != 3)
             {
             XtraMessageBox.Show("You cannot delete this");
             return;
             }
             if (CurrentContext.LoggedInUser.UserType == UserType.Constants.DISTRIBUTION_MANAGER_WITH_DELETE)
             {

             if (
                 XtraMessageBox.Show(
                     "Are you sure you want to delete this transaction? You will not be able to undo this.",
                     "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 MyGeneration.dOOdads.TransactionMgr tranMgr =
                     MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

                 try
                 {
                     tranMgr.BeginTransaction();

                     ReceiveDoc rdoc = new ReceiveDoc();
                     ReceivePallet rp = new ReceivePallet();
                     IssueDoc idoc = new IssueDoc();

                     PickListDetail pld = new PickListDetail();
                     int issueID = Convert.ToInt32(dr["ID"]);
                     //pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]),
                     //                       Convert.ToInt32(dr["Quantity"]));
                     idoc.LoadByPrimaryKey(issueID);
                     pld.LoadByPrimaryKey(idoc.PLDetailID);

                     string RefNo = idoc.RefNo;

                     rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                     //if (pld.RowCount == 0)
                     //{
                     //    pld.LoadByOrderAndItem(Convert.ToInt32(dr["OrderID"]), Convert.ToInt32(dr["ItemID"]));
                     //}

                     rp.LoadByPrimaryKey(pld.ReceivePalletID);
                     PalletLocation pl = new PalletLocation();
                     pl.loadByPalletID(rp.PalletID);

                     if (pl.RowCount == 0)
                     {
                         pl.LoadByPrimaryKey(pld.PalletLocationID);
                         if (pl.IsColumnNull("PalletID"))
                         {
                             pl.PalletID = rp.PalletID;
                             pl.Save();
                         }
                         //rp.LoadNonZeroRPByReceiveID(rdoc.ID);
                     }

                     if (rp.RowCount == 0)
                     {
                         XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                         return;
                     }
                     if (rp.RowCount > 0)
                     {
                         rdoc.QuantityLeft += idoc.Quantity;
                         rp.Balance += idoc.Quantity;
                         pld.QuantityInBU = 0;

                         // are we adding it the pick face?
                         // if so add it to the balance of the pick face also
                         pl.loadByPalletID(rp.PalletID);

                         if (pl.RowCount == 0)
                         {
                             PutawayLocation plocation = new PutawayLocation(rdoc.ItemID);

                             // we don't have a location for this yet,
                             // select a new location
                             //PutawayLocataion pl = new PutawayLocataion();
                             if (plocation.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                             {
                                 pl.LoadByPrimaryKey(plocation.PalletLocationID);
                                 if (pl.RowCount > 0)
                                 {
                                     pl.PalletID = rp.PalletID;
                                     pl.Save();
                                 }
                             }
                         }

                         if (pl.RowCount > 0)
                         {

                             PickFace pf = new PickFace();
                             pf.LoadByPalletLocation(pl.ID);
                             if (pf.RowCount > 0)
                             {
                                 pf.Balance += Convert.ToInt32(idoc.Quantity);
                                 pf.Save();
                             }

                             IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                             idoc.MarkAsDeleted();
                             rdoc.Save();
                             rp.Save();
                             idoc.Save();

                             // now refresh the window
                             XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                                 MessageBoxIcon.Information);
                             tranMgr.CommitTransaction();
                             //TODO: refresh the list
                             // gridViewReferences_FocusedRowChanged(null, null);
                         }

                     }
                     else
                     {
                         XtraMessageBox.Show(
                             "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                             "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         tranMgr.RollbackTransaction();
                     }
                 }
                 catch
                 {
                     XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                         MessageBoxIcon.Warning);
                     tranMgr.RollbackTransaction();
                 }
             }
             }
             else
             {
             XtraMessageBox.Show(
                 "You cannot delete this transaction because you don't have previlage. Please contact the administrator if you thing this is an error.",
                 "Delete is not allowed");
             }
        }
        /// <summary>
        /// This needs to be called after FillInReceiveDocInformation has been called.
        /// </summary>
        /// <param name="rec">ReceiveDoc should be passed to this function having been saved and with the id field different from null</param>
        /// <param name="dr">ReceiveDoc should be passed to this function having been saved and with the id field different from null</param>
        private void HandleReceiveDocShortage(DataRowView dr, ReceiveDoc rec, int receiveDocID = 0)
        {
            var recShortage = new ReceiveDocShortage();
            bool shortagetoBeAdded = false;

            if (receiveDocID == 0)
            {
                receiveDocID = Convert.ToInt32(rec.DefaultView.Table.Select(String.Format("GUID = '{0}'", dr["GUID"]))[0]["ID"]);
                shortagetoBeAdded = true;
            }

            //if (rec.GetColumn("ShortageReasonID") == System.DBNull.Value || Convert.ToInt32(rec.GetColumn("ShortageReasonID")) == 1) return;

            if ((srm && Convert.ToBoolean(dr["IsDamaged"])) || (Convert.ToDecimal(dr["InvoicedQty"]) >= Convert.ToDecimal(dr["Pack Qty"])))
            {
                var item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(dr["id"]));

                if (dr["ShortageReasonID"] == DBNull.Value &&  rec.ExpDate <= DateTimeHelper.ServerDateTime)
                {
                    dr["ShortageReasonID"] = ShortageReasons.Constants.DAMAGED;
                }

                if (dr["ShortageReasonID"] != DBNull.Value && (!(Convert.ToDecimal(dr["Pack Qty"]) == 0 && Convert.ToInt32(dr["ShortageReasonID"]) == ShortageReasons.Constants.NOT_RECEIVED)))
                {
                    int shortageReasonID = Convert.ToInt32(dr["ShortageReasonID"]);

                    recShortage.AddNew();
                    recShortage.ShortageReasonID = shortageReasonID;
                    recShortage.ReceiveDocID = receiveDocID;
                    recShortage.NoOfPacks = Convert.ToDecimal(dr["Pack Qty"]);

                    if (shortagetoBeAdded)
                    {
                        var receiveDoc = new ReceiveDoc();
                        receiveDoc.LoadByPrimaryKey(receiveDocID);
                        if (receiveDoc.InvoicedNoOfPack!=0 && receiveDoc.Quantity >= receiveDoc.InvoicedNoOfPack)
                        {
                            receiveDoc.InvoicedNoOfPack = receiveDoc.Quantity + recShortage.NoOfPacks;
                            receiveDoc.Save();
                        }

                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "Please enter the reason for the discrepancy in invoiced vs. received qty.", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            recShortage.Save();
        }
        public void SaveCostCoefficientAndTotalValue(int userID)
        {
            ReceiveDoc grvFullDetail = new ReceiveDoc();
               grvFullDetail.FlushData();
               grvFullDetail.LoadAllByReceiptID(GRV.ID);

               while (!grvFullDetail.EOF)
               {
                  //Insurance here is costCoefficient
                ReceiveDoc receivedoc = new ReceiveDoc();
                receivedoc.LoadByPrimaryKey(grvFullDetail.ID);
                //Use Custom StoreProcedure for Costing
                receivedoc.Insurance = CostCoefficient;
                receivedoc.Save();
                ReceiveDoc.SetUnitCostByReceiveDoc(grvFullDetail.ID,Math.Round(receivedoc.PricePerPack * CostCoefficient,2),userID);
                ReceiveDoc.SetAverageCostByReceiveDoc(grvFullDetail.ID,Math.Round(receivedoc.PricePerPack * CostCoefficient,2),userID);
                grvFullDetail.MoveNext();
               }
        }
        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            DataRow dr = grdViewYearEnd.GetDataRow(grdViewYearEnd.GetSelectedRows()[0]);
            if (dr != null)
            {
                string batchNo = dr["Batch No."].ToString();
                int recID = int.Parse(dr["RecID"].ToString());
                BLL.ReceiveDoc rec = new ReceiveDoc();

                if (recID == -1)
                {
                    XtraMessageBox.Show("Use this button only on invalid batches", "Nothing to Remove",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                rec.LoadByPrimaryKey(recID);
                int itemID = rec.ItemID;

                //Do another validation here (Make sure that the items that they try to remove have issues like the Total SOH not being equal to the sum of the listed batches and so forth.
                int storeId = (cboStores.EditValue != null) ? Convert.ToInt32(cboStores.EditValue) : 1;
                int month = EthiopianDate.EthiopianDate.Now.Month;
                int year = EthiopianDate.EthiopianDate.Now.Year;

                BLL.Balance bal = new Balance();
                BLL.Items itm = new Items();
                itm.LoadByPrimaryKey(itemID);

                long currentBalance = bal.GetSOH(itemID, storeId, month, year);
                long totalQuantityLeftInBatches = itm.TotalQuantityLeftInAllBatches(storeId);

                if (currentBalance == totalQuantityLeftInBatches)
                {
                    XtraMessageBox.Show(
                        "You do not have to use this button to remove this batch.  Please set the physical inventory 0 instead.  Use this button only for items with discrepancies.",
                        "Unapplicable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (XtraMessageBox.Show("This will make the quantity left for this received batch zero and remove it from this list.  Are you sure you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (BLL.ReceiveDoc.MarkReceivedBatchAsEmpty(recID))
                    {
                        dr.Delete();

                    }
                }
            }
        }
        private void OnReplenishClicked(object sender, EventArgs e)
        {
            PalletLocation pl = new PalletLocation();
            PickFace pf = new PickFace();
            DataRow dr = gridPickFaceStockLevelView.GetFocusedDataRow();
            DataRow dr2 = gridReplenishmentChoiceView.GetFocusedDataRow();
            if (dr2 != null)
            {
                // check if the replenishment is from allowed location.
                //
                if (!Convert.ToBoolean(dr2["CanReplenish"]))
                {
                    XtraMessageBox.Show("Please choose replenishment from the first to expire items", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                pl.LoadByPrimaryKey(_palletLocationID);
                pf.LoadByPrimaryKey(_pickFaceID);
                if (pf.IsColumnNull("Balance"))
                {
                    pf.Balance = 0;
                }

                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet pallet = new Pallet();
                    pallet.AddNew();
                    pallet.StorageTypeID = Convert.ToInt32(StorageType.PickFace);
                    pallet.Save();
                    pl.PalletID = pallet.ID;
                    pl.Save();
                }

                ReceivePallet rp = new ReceivePallet();
                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc rd = new ReceiveDoc();
                rp.LoadByPrimaryKey(Convert.ToInt32(dr2["ReceivePalletID"]));
                rp2.AddNew();
                rp2.IsOriginalReceive = false;
                rp2.PalletID = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;
                rp2.BoxSize = rp.BoxSize;

                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                im.LoadIMbyLevel(_designatedItemID, Convert.ToInt32(dr2["ManufacturerID"]),Convert.ToInt32(dr2["BoxSize"]));
                if (rp.IsColumnNull("ReservedStock"))
                {
                    rp.ReservedStock = 0;
                }
                //if (rp.Balance - rp.ReservedStock < im.QuantityInBasicUnit )
                //{
                //    XtraMessageBox.Show("You cannot replenish the pick face from this location because the items are reserved for Issue. Please replenish from another receive.","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                //    return;
                //}
                BLL.ItemManufacturer imff = new BLL.ItemManufacturer();
                imff.LoadOuterBoxForItemManufacturer(im.ItemID,im.ManufacturerID);
                if (imff.PackageLevel > im.PackageLevel && rp.Balance < imff.QuantityInBasicUnit)
                {
                    rp2.Balance = rp.Balance;
                }
                else if (rp.Balance - rp.ReservedStock > im.QuantityInBasicUnit)
                {
                    rp2.ReceivedQuantity = rp2.Balance = im.QuantityInBasicUnit;
                }
                else
                {
                    rp2.Balance = rp.Balance;
                }
                rp2.ReservedStock = 0;
                rp.Balance -= rp2.Balance;
                if (rp.IsColumnNull("ReceivedQuantity"))
                {
                    rp.ReceivedQuantity = rp.Balance + rp2.Balance;
                }
                rp.ReceivedQuantity -= rp2.Balance;
                rp.Save();
                rp2.Save();
                pl.Confirmed = false;
                pl.Save();
                pf.Balance += Convert.ToInt32(rp2.Balance);
                pf.Save();
                PalletLocation pl2 = new PalletLocation();
                pl2.LoadLocationForPallet(rp.PalletID);
                rd.LoadByPrimaryKey(rp2.ReceiveID);
                // Now update the screen accordingly.
                dr["Balance"] = pf.Balance;// Convert.ToInt32(dr["Balance"]) + rp2.Balance;

                InternalTransfer it = new InternalTransfer();

                it.AddNew();
                it.ItemID = _designatedItemID;
                it.BoxLevel = im.PackageLevel;
                it.ExpireDate = rd.ExpDate;
                it.BatchNumber = rd.BatchNo;
                it.ManufacturerID = im.ManufacturerID;
                it.FromPalletLocationID = pl2.ID;
                it.ToPalletLocationID = _palletLocationID;
                it.IssuedDate = DateTimeHelper.ServerDateTime;
                it.QtyPerPack = im.QuantityInBasicUnit;
                it.Packs = 1;
                it.ReceiveDocID = rp.ReceiveID;
                it.QuantityInBU = it.Packs * it.QtyPerPack;
                it.Type = "PickFace";
                it.Status = 0;
                it.Save();

                BindPickFaceDetailAndReplenismehmnent();
                XtraMessageBox.Show("Your Pick Face is updated, please print the replenishment list and confirm the stock movement", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <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();
            }
        }
Example #31
0
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();

            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();

            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));
            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();

            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost  = Math.Round(receiveDoc.Cost, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost  = Math.Round(receiveDoc.SellingPrice, 2);
                    margin    = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;
                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice    = unitPrice;
                pickList.Cost         = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost         = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost     = Convert.ToDecimal(unitCost);
                issueDoc.Margin       = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return(pickList);
        }
        /// <summary>
        /// Gets the pick list details for order.
        /// </summary>
        /// <param name="ordID">The ord ID.</param>
        /// <param name="Preparedby">The preparedby.</param>
        /// <returns></returns>
        public DataView GetPickListDetailsForOrder(int ordID, string Preparedby)
        {
            this.LoadByOrderID(ordID);
            var query = HCMIS.Repository.Queries.PickList.SelectGetPickListDetailsForOrder(this.ID);
            this.LoadFromRawSql(query);
            // Add important columns
            this.DataTable.Columns.Add("SKUTOPICK", typeof(decimal));
            this.DataTable.Columns.Add("SKUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BUPICKED", typeof(decimal));
            this.DataTable.Columns.Add("BoxSizeDisplay");
            this.DataTable.Columns.Add("SKUBU", typeof(decimal));
            this.DataTable.Columns.Add("IsManufacturerLocal", typeof(bool));
            this.DataTable.Columns.Add("PrintedSTVNumber", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreName", typeof(string));
            this.DataTable.Columns.Add("PhysicalStoreTypeID", typeof(int));
            this.DataTable.Columns.Add("PhysicalStoreTypeName", typeof(string));
            this.DataTable.Columns.Add("PreparedBy", typeof(string));
            int i = 1;
            while (!this.EOF)
            {
                decimal packs = Convert.ToDecimal(this.GetColumn("Packs"));

                int manufacturer = Convert.ToInt32(this.GetColumn("ManufacturerID"));
                Manufacturer m = new Manufacturer();
                m.LoadByPrimaryKey(manufacturer);
                if (!m.IsColumnNull("CountryOfOrigin") && m.CountryOfOrigin.Contains("Ethiopia"))
                    this.SetColumn("IsManufacturerLocal", true);
                else
                    this.SetColumn("IsManufacturerLocal", false);

                int recPalletID = Convert.ToInt32(this.GetColumn("ReceivePalletID"));
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(recPalletID);
                try
                {
                    ReceiveDoc receiveDoc = new ReceiveDoc();
                    Receipt receipt = new Receipt();
                    receiveDoc.LoadByPrimaryKey(rp.ReceiveID);
                    receipt.LoadByPrimaryKey(receiveDoc.ReceiptID);
                    this.SetColumn("PhysicalStoreName", rp.GetPhysicalStoreName());
                    int physicalStoreTypeID = rp.GetPhysicalStoreTypeID();
                    this.SetColumn("PhysicalStoreTypeID", physicalStoreTypeID);
                    Warehouse phyStoreType = new Warehouse();
                    phyStoreType.LoadByPrimaryKey(physicalStoreTypeID);
                    this.SetColumn("PhysicalStoreTypeName", phyStoreType.Name);
                    if (BLL.Settings.PrintUserNameOnInvoice)
                    {
                        this.SetColumn("PreparedBy", Preparedby);
                    }

                }
                catch
                {

                }

                int itemId = Convert.ToInt32(this.GetColumn("ItemID"));
                int boxLevel = Convert.ToInt32(this.GetColumn("BoxLevel"));
                decimal qtyPerPack = this.Getint("QtyPerPack");
                //im.LoadIMbyLevel(itemId, manufacturer, boxLevel);
                this.SetColumn("SKUTOPICK", (packs));
                this.SetColumn("SKUPICKED", this.GetColumn("SKUTOPICK"));
                // TODO:show the box size here for Program store
                this.SetColumn("BoxSizeDisplay", "");
                this.SetColumn("SKUBU", qtyPerPack);
                this.SetColumn("BUPICKED", qtyPerPack * Convert.ToDecimal(this.GetColumn("SKUPICKED")));
                this.SetColumn("LineNum", i++);
                if (this.IsColumnNull("DeliveryNote"))
                {
                    this.SetColumn("DeliveryNote", false);
                }
                this.MoveNext();
            }
            return this.DefaultView;
        }
        /// <summary>
        /// Fix For Delivery Note When Converting Do not use under any other situation
        /// </summary>
        /// <param name="issueDocID"></param>
        /// <param name="picklistID"></param>
        /// <returns></returns>
        public PickListDetail FixDeliveryNoteCostReceiveDoc(int issueDocID, int picklistID)
        {
            IssueDoc issueDoc = new IssueDoc();
            issueDoc.LoadByPrimaryKey(issueDocID);
            PickListDetail pickList = new PickListDetail();
            pickList.LoadByPrimaryKey(picklistID);
            //safety first
            if (issueDoc.RecievDocID != pickList.ReceiveDocID)
            {
                Item item = new Item();
                item.LoadByPrimaryKey(picklistID);
                throw new Exception(String.Format("PicklistDetail vs IssueDoc Inconsistancy for Item {0}", item.FullItemName));

            }
            // now we are sure we have one ReceiveDocID
            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByPrimaryKey(pickList.ReceiveDocID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            receiveDocConfirmation.LoadByReceiveDocID(receiveDoc.ID);
            //Check if it has been Printed and that Selling Price and Cost is set
            if (receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                double unitPrice, unitCost, margin;
                if (Settings.IsCenter == true && !receiveDoc.IsColumnNull("Cost") && receiveDoc.Cost != 0)
                {
                    unitPrice = Math.Round(receiveDoc.Cost, 2);
                    unitCost = Math.Round(receiveDoc.Cost, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else if (!receiveDoc.IsColumnNull("SellingPrice") && receiveDoc.SellingPrice != 0)
                {
                    unitPrice = Math.Round(receiveDoc.SellingPrice, 2);
                    unitCost = Math.Round(receiveDoc.SellingPrice, 2);
                    margin = !receiveDoc.IsColumnNull("Margin") ? receiveDoc.Margin : 0;

                }
                else
                {
                    var item = new Item();
                    item.LoadByPrimaryKey(pickList.ItemID);
                    throw new Exception(String.Format("Price Not set For item: {0}", item.FullItemName));
                }
                pickList.UnitPrice = unitPrice;
                pickList.Cost = Convert.ToDouble(pickList.Packs) * unitPrice;
                issueDoc.SellingPrice = Convert.ToDecimal(unitPrice);
                issueDoc.Cost = Convert.ToDouble(issueDoc.NoOfPack) * unitPrice;
                issueDoc.UnitCost = Convert.ToDecimal(unitCost);
                issueDoc.Margin = Convert.ToDecimal(margin);
                pickList.Save();
                issueDoc.Save();
            }
            else
            {
                var item = new Item();
                item.LoadByPrimaryKey(pickList.ItemID);
                throw new Exception(String.Format("GRV/IGRV Not Printed For Item: {0}", item.FullItemName));
            }
            return pickList;
        }
        /// <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>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

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

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


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

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

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


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

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

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

                //long prevQuantityLeft = recDoc.QuantityLeft;

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

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

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

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

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

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

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }
        private void btnAdjustments_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToAdjustments())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you would like to commit this adjustment?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {

                    PalletLocation pl = new PalletLocation();
                    Pallet p = new Pallet();
                    ReceiveDoc rdoc = new ReceiveDoc();
                    ReceivePallet rp = new ReceivePallet();
                    int printNubmer = InternalTransfer.GetNewPrintNumber() + 1 ;
                    for (int i = 0; i < gridView3.RowCount; i++)
                    {
                         DataRow dr = gridView3.GetDataRow(i);
                         if (dr["Adjust"] != DBNull.Value)
                         {

                             int amount = Convert.ToInt32(dr["Adjust"]);
                             rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                             rdoc.LoadByPrimaryKey(rp.ReceiveID);

                             rdoc.NoOfPack += amount;
                             amount *= rdoc.QtyPerPack;
                             rp.Balance += amount;
                             if (rp.IsColumnNull("ReceivedQuantity"))
                             {
                                 rp.ReceivedQuantity = 0;
                             }
                             rp.ReceivedQuantity += amount;

                             rdoc.QuantityLeft += amount;
                             rdoc.Quantity += amount;

                             BLL.LossAndAdjustment d = new BLL.LossAndAdjustment();
                             d.AddNew();
                             d.GenerateRefNo();
                             d.ItemID = Convert.ToInt32(dr["ItemID"]);
                             d.ReasonId = Convert.ToInt32(dr["Reason"]);
                             d.RecID = rdoc.ID;
                             d.Quantity = amount;
                             d.BatchNo = rdoc.BatchNo;

                             CalendarLib.DateTimePickerEx edate = new CalendarLib.DateTimePickerEx();
                             edate.Value = DateTime.Today;

                             edate.CustomFormat = "MM/dd/yyyy";
                             d.Date = ConvertDate.DateConverter(edate.Text);

                             d.EurDate = DateTime.Today;
                             if (!rdoc.IsColumnNull("Cost"))
                             {
                                 d.Cost = Math.Abs(rdoc.Cost*amount);
                             }
                             d.StoreId = rdoc.StoreID;
                             d.Losses = false;
                             d.ApprovedBy = CurrentContext.UserId.ToString();
                             d.Save();
                             rdoc.Save();
                             rp.Save();

                         }
                    }
                    PopulateItemDetails();
                    XtraMessageBox.Show("Items adjusted successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// Moves the specified pick list ID.
        /// </summary>
        /// <param name="PickListID">The pick list ID.</param>
        public static void Move(int PickListID)
        {
            DataView       dv = GetTransferReportForStore();
            PalletLocation pl = new PalletLocation();

            foreach (DataRowView dr in dv)
            {
                int amount           = Convert.ToInt32(dr["packs"]);
                int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

                ReceivePallet rp   = new ReceivePallet();
                ReceiveDoc    rdoc = new ReceiveDoc();

                rp.LoadByPrimaryKey(Convert.ToInt32(dr["ReceivePalletID"]));
                rdoc.LoadByPrimaryKey(rp.ReceiveID);
                amount *= rdoc.QtyPerPack;

                int qPalletLocationID = PalletLocation.GetTransferPalletLocation(Convert.ToInt32(dr["PhysicalStoreID"]));
                pl.LoadByPrimaryKey(qPalletLocationID);
                if (pl.IsColumnNull("PalletID"))
                {
                    Pallet p = new Pallet();
                    p.AddNew();
                    p.StorageTypeID = Convert.ToInt32(StorageType.Quaranteen);
                    p.Save();
                    pl.PalletID = p.ID;
                    pl.Save();
                }


                ReceivePallet rp2 = new ReceivePallet();
                ReceiveDoc    rd  = new ReceiveDoc();


                rd.LoadByPrimaryKey(rp.ReceiveID);
                rp2.AddNew();

                rp2.PalletID  = pl.PalletID;
                rp2.ReceiveID = rp.ReceiveID;


                // calculate the new balance
                BLL.ItemManufacturer im = new BLL.ItemManufacturer();
                //im.LoadDefaultReceiving(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]));
                if (dr["BoxLevel"] == DBNull.Value)
                {
                    dr["BoxLevel"] = 0;
                }
                im.LoadIMbyLevel(rd.ItemID, Convert.ToInt32(dr["ManufacturerID"]), Convert.ToInt32(dr["BoxLevel"]));
                int packqty = (amount / im.QuantityInBasicUnit);
                rp2.ReservedStock = 0;
                rp.ReservedStock -= amount;
                BLL.ReceivePallet.MoveBalance(rp, rp2, amount);
                //rp2.Balance = amount;
                //rp.Balance -= rp2.Balance;

                //rp.Save();
                //rp2.Save();

                pl.Confirmed = false;
                pl.Save();
                if (rp.Balance == 0)
                {
                    PalletLocation.GarbageCollection();
                }
            }
        }
        private object GetForPrint(DataView dv)
        {
            DataTable dtbl = dv.Table.Clone();
            dtbl.Columns.Add("Supplier");
            dtbl.Clear();
            foreach (DataRowView drv in dv)
            {
                if (dtbl.Rows.Count == 0)
                {
                    dtbl.ImportRow(drv.Row);
                }
                else
                {
                    //check if items with same expiry esists in the table
                    DataRow[] ar = dtbl.Select(string.Format("ItemID={0} and BatchNumber='{1}' and UnitPrice = {2}", drv["ItemID"], drv["BatchNumber"], drv["UnitPrice"]));
                    if (ar.Length > 0)
                    {
                        ar[0]["SKUPICKED"] = Convert.ToInt32(ar[0]["SKUPICKED"]) + Convert.ToInt32(drv["SKUPICKED"]);
                        ar[0]["Cost"] = Convert.ToInt32(ar[0]["Cost"]) + Convert.ToInt32(drv["Cost"]);
                        ar[0].EndEdit();
                    }
                    else
                    {
                        dtbl.ImportRow(drv.Row);
                    }
                }

            }

            Supplier supplier = new Supplier();
            ReceiveDoc rd = new ReceiveDoc();
            foreach (DataRow drw in dtbl.Rows)
            {
                rd.LoadByPrimaryKey(Convert.ToInt32(drw["ReceiveDocID"]));
                if (rd.RowCount > 0)
                {
                    supplier.LoadByPrimaryKey(rd.SupplierID);
                    drw["Supplier"] = supplier.CompanyName;
                    drw.EndEdit();
                }
            }
            return dtbl;
        }
        public static void DeleteIssueDoc(int issueID)
        {
            MyGeneration.dOOdads.TransactionMgr tranMgr =
                MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                tranMgr.BeginTransaction();

                var pld = new PickListDetail();
                var rdoc = new ReceiveDoc();
                var rp = new ReceivePallet();
                var idoc = new IssueDoc();

                idoc.LoadByPrimaryKey(issueID);
                pld.LoadByPrimaryKey(idoc.PLDetailID);
                rdoc.LoadByPrimaryKey(idoc.RecievDocID);

                rp.LoadByPrimaryKey(pld.ReceivePalletID);
                var pl = new PalletLocation();
                pl.loadByPalletID(rp.PalletID);

                if (pl.RowCount == 0)
                {
                    pl.LoadByPrimaryKey(pld.PalletLocationID);
                    if (pl.IsColumnNull("PalletID"))
                    {
                        pl.PalletID = rp.PalletID;
                        pl.Save();
                    }
                }

                if (rp.RowCount == 0)
                {
                    XtraMessageBox.Show("You cannot delete this item, please contact the administrator", "Error");
                    return;
                }
                if (rp.RowCount > 0)
                {
                    // in error cases this could lead to a number greater than the received quantity
                    // instead of being an error, it should just delete the respective issue and
                    // adjust the remaining quantity to the received quantity.
                    if (rdoc.QuantityLeft + idoc.Quantity > rdoc.Quantity)
                    {
                        rdoc.QuantityLeft = rp.Balance = rdoc.Quantity;
                    }
                    else
                    {
                        rdoc.QuantityLeft += idoc.Quantity;
                        rp.Balance += idoc.Quantity;
                    }

                    //Delete from picklistDetail and add to pickListDetailDeleted
                    PickListDetailDeleted.AddNewLog(pld, BLL.CurrentContext.UserId);
                    pld.MarkAsDeleted();

                    // are we adding it the pick face?
                    // if so add it to the balance of the pick face also
                    pl.loadByPalletID(rp.PalletID);

                    if (pl.RowCount == 0)
                    {
                        var plocation = new PutawayLocation(rdoc.ItemID);

                        // we don't have a location for this yet,
                        // select a new location
                        //PutawayLocataion pl = new PutawayLocataion();
                        if (plocation.ShowDialog() == DialogResult.OK)
                        {
                            pl.LoadByPrimaryKey(plocation.PalletLocationID);
                            if (pl.RowCount > 0)
                            {
                                pl.PalletID = rp.PalletID;
                                pl.Save();
                            }
                        }
                    }

                    if (pl.RowCount > 0)
                    {
                        var pf = new PickFace();
                        pf.LoadByPalletLocation(pl.ID);
                        if (pf.RowCount > 0)
                        {
                            pf.Balance += Convert.ToInt32(idoc.Quantity);
                            pf.Save();
                        }

                        IssueDocDeleted.AddNewLog(idoc, CurrentContext.UserId);
                        idoc.MarkAsDeleted();
                        rdoc.Save();
                        rp.Save();
                        idoc.Save();
                        pld.Save();

                        // now refresh the window
                        XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        tranMgr.CommitTransaction();

                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                        "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tranMgr.RollbackTransaction();
                }
            }
            catch
            {
                XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                tranMgr.RollbackTransaction();
            }
        }
        private void returnToBulkStoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataRow dr = gridPickFaceDetailView.GetFocusedDataRow();
            if (dr != null)
            {
                int ReceivePalletID = Convert.ToInt32(dr["ID"]);
                ReceivePallet rp = new ReceivePallet();
                rp.LoadByPrimaryKey(ReceivePalletID);

                ReceiveDoc rd = new ReceiveDoc();
                rd.LoadByPrimaryKey(rp.ReceiveID);

                BLL.ItemManufacturer imf = new BLL.ItemManufacturer();
                imf.LoadIMbyLevel(rd.ItemID, rd.ManufacturerId, rp.BoxSize);

                int QuantityToReturn = Convert.ToInt32(((rp.Balance - rp.ReservedStock) / imf.QuantityInBasicUnit) * imf.QuantityInBasicUnit);
                InternalTransfer itfr = new InternalTransfer();

            }
        }
        internal static PickListDetail GeneratePickListDetail(ReceivePallet receivePallet, int pickListId,decimal qtyInBU)
        {
            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.LoadByPrimaryKey(receivePallet.ReceiveID);
            decimal pack = qtyInBU / Convert.ToDecimal(receiveDoc.QtyPerPack);

            PickListDetail pkDetail = new PickListDetail();

            pkDetail.AddNew();
            pkDetail.PickListID = pickListId;
            pkDetail.ItemID = receiveDoc.ItemID;
            PalletLocation palletLocation = new PalletLocation();
            palletLocation.loadByPalletID(receivePallet.PalletID);
            int palletLocationId;
            try
            {
                palletLocationId = palletLocation.ID;
            }
            catch (Exception exp)
            {

                palletLocationId = receivePallet.PalletLocationID;
                palletLocation.LoadByPrimaryKey(palletLocationId);

            }
            pkDetail.PalletLocationID = palletLocationId;
            if (!receiveDoc.IsColumnNull("BatchNo"))
                pkDetail.BatchNumber = receiveDoc.BatchNo;

            if (!receiveDoc.IsColumnNull("ExpDate"))
                pkDetail.ExpireDate = receiveDoc.ExpDate;

            pkDetail.StoreID = receiveDoc.StoreID;
            pkDetail.UnitID = receiveDoc.UnitID;
            pkDetail.ReceiveDocID = receiveDoc.ID;
            if (!receiveDoc.IsColumnNull("Cost"))
            {
                pkDetail.Cost = Convert.ToDouble(pack) * Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
                pkDetail.UnitPrice = Math.Round(receiveDoc.Cost, BLL.Settings.NoOfDigitsAfterTheDecimalPoint);
            }
            pkDetail.Packs = pack;
            pkDetail.QtyPerPack = receiveDoc.QtyPerPack;
            pkDetail.QuantityInBU = qtyInBU;
            pkDetail.StoreID = receiveDoc.StoreID;
            pkDetail.ReceivePalletID = receivePallet.ID;
            pkDetail.ManufacturerID = receiveDoc.ManufacturerId;
            pkDetail.BoxLevel = 0;
            pkDetail.DeliveryNote = true;

            pkDetail.PhysicalStoreID = palletLocation.PhysicalStoreID;
            pkDetail.Save();

            return pkDetail;
        }