private void btnFixLocationStuff_Click(object sender, EventArgs e)
        {
            int storeID = Convert.ToInt32(lkStoreLocation.EditValue);

            BLL.ReceiveDoc rd = new BLL.ReceiveDoc();
            rd.LoadReceivesForStores(storeID);
            while (!rd.EOF)
            {
                BLL.ReceivePallet rp = new BLL.ReceivePallet();
                rp.LoadByReceiveDocID(rd.ID);
                decimal receivedQuantity = 0, balance = 0;
                if (rp.RowCount == 1)// rp.RowCount > 0)
                {
                    while (!rp.EOF)
                    {
                        receivedQuantity += rp.IsColumnNull("ReceivedQuantity") ? 0 : rp.ReceivedQuantity;
                        balance          += rp.IsColumnNull("Balance") ? 0 : rp.Balance;
                        rp.MoveNext();
                    }
                    rp.Rewind();

                    while (!rp.EOF && rp.IsColumnNull("ReceivedQuantity"))
                    {
                        rp.MoveNext();
                    }

                    if (rd.Quantity != receivedQuantity && rd.Quantity > receivedQuantity)
                    {
                        rp.ReceivedQuantity += (rd.Quantity - receivedQuantity);
                    }
                    if (rd.QuantityLeft != balance && rd.QuantityLeft > 0)//rd.QuantityLeft > balance)
                    {
                        rp.Balance += (rd.QuantityLeft - balance);
                    }
                    rp.Save();
                }
                rd.MoveNext();
            }
            XtraMessageBox.Show("Completed!");
        }
        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();
            }
        }
        private void btnFixLocationStuff_Click(object sender, EventArgs e)
        {
            int storeID = Convert.ToInt32(lkStoreLocation.EditValue);
            BLL.ReceiveDoc rd = new BLL.ReceiveDoc();
            rd.LoadReceivesForStores(storeID);
            while(!rd.EOF)
            {
                BLL.ReceivePallet rp = new BLL.ReceivePallet();
                rp.LoadByReceiveDocID(rd.ID);
                decimal receivedQuantity = 0, balance = 0;
                if (rp.RowCount==1)// rp.RowCount > 0)
                {
                    while (!rp.EOF)
                    {
                        receivedQuantity += rp.IsColumnNull("ReceivedQuantity") ? 0 : rp.ReceivedQuantity;
                        balance += rp.IsColumnNull("Balance") ? 0 : rp.Balance;
                        rp.MoveNext();
                    }
                    rp.Rewind();

                    while (!rp.EOF && rp.IsColumnNull("ReceivedQuantity"))
                    {
                        rp.MoveNext();
                    }

                    if (rd.Quantity != receivedQuantity && rd.Quantity > receivedQuantity)
                    {
                        rp.ReceivedQuantity += (rd.Quantity - receivedQuantity);
                    }
                    if (rd.QuantityLeft != balance && rd.QuantityLeft > 0)//rd.QuantityLeft > balance)
                    {
                        rp.Balance += (rd.QuantityLeft - balance);
                    }
                    rp.Save();
                }
                rd.MoveNext();
            }
            XtraMessageBox.Show("Completed!");
        }
        /// <summary>
        /// This method handles Receive of an Item with full NotReceived Reason
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="dr"></param>
        private void HandleFullNotReceivedAndMultipleBatchPalletlization(ReceiveDoc rec,DataRowView dr)
        {
            DataRow firstEntry = null;
            bool noSoundItems = false;
            // Here: We Can Use One of the Items on a receipt //
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") &&
                 rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED))
            {
                firstEntry =
                    rec.DefaultView.Table.Select(String.Format("[ID] > 0 AND [IsDamaged] = 0")).FirstOrDefault();
            }

            //~ This is a multiple batch case ~//
            if ((rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                  var oneAmongMultipleBatchsAndDbSavedGuid =
                        _dtRecGrid.Select(string.Format("CopyGUID = '{0}' And IsCopied = 1 ", dr["CopyGUID"]));

                DataRow[] dbSavedcounts = oneAmongMultipleBatchsAndDbSavedGuid.Any()
                    ? rec.DefaultView.Table.Select(String.Format("GUID = '{0}'",
                        oneAmongMultipleBatchsAndDbSavedGuid[0]["GUID"]))
                    : oneAmongMultipleBatchsAndDbSavedGuid;

                firstEntry = dbSavedcounts.Any()
                    ? dbSavedcounts.FirstOrDefault()
                    : rec.DefaultView.Table.Select(String.Format("[ID] > 0 AND [IsDamaged] = 0")).FirstOrDefault();
            }
            // If we cant find any normal receive in this receipt let's just use one of receiveDocID's randomly: This is just to save a not received Entry with zero quantity! (an awful recent request!)~//
            if (firstEntry == null && ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") &&
                rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED)))
            {
                firstEntry =
                    rec.DefaultView.Table.Select(String.Format("[ID] > 0")).FirstOrDefault();
                if (firstEntry != null)
                {
                    noSoundItems = true;

                }
            }
            // This is  a Zero Quantity ReceiveDoc //
            if (firstEntry != null)
            {
                rec.PhysicalStoreID = Convert.ToInt16(firstEntry["PhysicalStoreID"]);
                rec.InventoryPeriodID = Convert.ToInt16(firstEntry["InventoryPeriodID"]);
                rec.Save();

                // Lets Create a Zero ReceivePallet in the same palletlocation as one of the Items in the receipt //
                var oneOfrecievePallet = new BLL.ReceivePallet();
                oneOfrecievePallet.LoadByReceiveDocID(Convert.ToInt16(firstEntry["ID"]));

                var newReceivePallet = new BLL.ReceivePallet();
                newReceivePallet.AddNew();
                newReceivePallet.IsOriginalReceive = true;
                newReceivePallet.ReceiveID = rec.ID;
                newReceivePallet.Balance = newReceivePallet.ReceivedQuantity = newReceivePallet.ReservedStock = 0;
                newReceivePallet.PalletID = oneOfrecievePallet.PalletID;
                newReceivePallet.PalletLocationID = oneOfrecievePallet.PalletLocationID;
                newReceivePallet.BoxSize = oneOfrecievePallet.BoxSize;
                newReceivePallet.Save();
            }

            if (!rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == BLL.ShortageReasons.Constants.NOT_RECEIVED)
            {
                var recShortage = new ReceiveDocShortage();
                recShortage.AddNew();
                recShortage.ShortageReasonID = rec.ShortageReasonID;
                recShortage.ReceiveDocID = rec.ID;
                recShortage.NoOfPacks = Convert.ToDecimal(dr["InvoicedQty"]);
                recShortage.Save();
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            LogReceiptChange change = new LogReceiptChange(rDoc);

            if (txtBatchNo.EditValue != null)
            {
                rDoc.BatchNo = txtBatchNo.Text;
            }
            if (dtExpiry.EditValue != null)
            {
                rDoc.ExpDate = dtExpiry.DateTime;
            }
            else
            {
                rDoc.SetColumnNull("ExpDate");
            }
            if (txtPrice.EditValue != null)
            {
                rDoc.Cost = Convert.ToDouble(txtPrice.EditValue);
            }

            if(lkAccount.EditValue!=null)
            {
                rDoc.StoreID = Convert.ToInt32(lkAccount.EditValue);
                //TODO:Edit other tables as well.
            }

            if(lkUnit.EditValue!=null)
            {
                int unitID = Convert.ToInt32(lkUnit.EditValue);
                if (rDoc.UnitID != unitID)
                {

                    rDoc.UnitID = Convert.ToInt32(lkUnit.EditValue);
                    BLL.ItemUnit itemUnit = new ItemUnit();
                    itemUnit.LoadByPrimaryKey(rDoc.UnitID);
                    rDoc.QtyPerPack = itemUnit.QtyPerUnit;
                    rDoc.Quantity = rDoc.NoOfPack * rDoc.QtyPerPack;
                    rDoc.QuantityLeft = rDoc.Quantity;

                    BLL.ReceivePallet rp = new ReceivePallet();
                    rp.LoadByReceiveDocID(rDoc.ID);
                    rp.Balance = rDoc.QuantityLeft;
                    rp.ReceivedQuantity = rDoc.Quantity;

                    rDoc.Save();
                    rp.Save();
                }
            }

            // decide to save the quantity or not
            //Lord have mercy, this is not a proper way to do it,
            decimal quantity = Convert.ToDecimal(txtQuanitity.EditValue.ToString().Replace(",", ""));

            if (txtQuanitity.Enabled && !rDoc.HasTransactions() && rDoc.Quantity != rDoc.QtyPerPack * quantity)
            {
                // now find the receive pallets
                ReceivePallet receivePallet = new ReceivePallet();
                receivePallet.LoadNonZeroRPByReceiveID(rDoc.ID);
                if (receivePallet.RowCount > 1)
                {
                    //
                    XtraMessageBox.Show(
                        "This Item is stored in more than one location and chaning the quanitity is not implemented. try to consolidate it and try again");
                }
                else
                {

                    rDoc.NoOfPack = quantity;
                    receivePallet.Balance = receivePallet.ReceivedQuantity = rDoc.QuantityLeft = rDoc.Quantity = quantity * rDoc.QtyPerPack;
                    rDoc.Save();
                    receivePallet.Save();
                }
            }
            else if (rDoc.Quantity != quantity * rDoc.QtyPerPack)
            {
                XtraMessageBox.Show("The Quantity was not edited because there was an issue transaction on it.");
            }

            rDoc.RefNo = txtGrvNo.EditValue.ToString();
            //rDoc.SupplierID = Convert.ToInt32(lkSupplier.EditValue);
            if (lkManufacturer.EditValue != null)
                rDoc.ManufacturerId = Convert.ToInt32(lkManufacturer.EditValue);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            rDoc.Save();
            change.SaveChangeLog(rDoc, CurrentContext.UserId);
            this.LogActivity("Save-Receipt-Change", rDoc.ID);
            this.Close();
        }
        public void DeleteAnIssue(int issueDociD)
        {
            ReceiveDoc rdoc = new ReceiveDoc();
            ReceivePallet rp = new ReceivePallet();
            IssueDoc idoc = new IssueDoc();
            idoc.LoadByPrimaryKey(issueDociD);

            if (idoc.IsThereSRM)
            {
                throw new Exception("There is an SRM for this issue.  You can't void it.");
            }

            PickListDetail pld = new PickListDetail();
            //pld.LoadByOrderAndItem(idoc.OrderID, idoc.ItemID, idoc.NoOfPack);
            pld.LoadByPrimaryKey(idoc.PLDetailID);

            string RefNo = idoc.RefNo;

            rdoc.LoadByPrimaryKey(idoc.RecievDocID);

            //if (pld.RowCount == 0)
            //{
            //    pld.LoadByOrderAndItem(idoc.OrderID, idoc.ItemID);
            //}

            rp.LoadByReceiveDocID(idoc.RecievDocID);
            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();
                }

            }

            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;

                //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)
                {
                    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();
                    pld.Save();
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successful 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);

                }
            }
        }
        /// <summary>
        /// Changes the unit ID.
        /// </summary>
        /// <param name="destinationUnitID">The destination unit ID.</param>
        internal void ChangeUnitID(int destinationUnitID)
        {
            BLL.ItemUnit iuTo = new ItemUnit();
            BLL.ItemUnit iuFrom = new ItemUnit();

            iuTo.LoadByPrimaryKey(destinationUnitID);
            iuFrom.LoadByPrimaryKey(this.UnitID);
            decimal multiplier = iuTo.QtyPerUnit / iuFrom.QtyPerUnit;

            while (!this.EOF)
            {

                this.QtyPerPack = iuTo.QtyPerUnit;
                this.Quantity =Convert.ToDecimal(this.Quantity * multiplier);
                this.QuantityLeft = Convert.ToDecimal(multiplier * this.QuantityLeft);
                this.UnitID = iuTo.ID;
                this.Save();

                BLL.ReceivePallet rp = new ReceivePallet();
                rp.LoadByReceiveDocID(this.ID);
                rp.ReceivedQuantity = Convert.ToDecimal(rp.ReceivedQuantity * multiplier);
                rp.Balance = Convert.ToDecimal(rp.Balance * multiplier);
                rp.ReservedStock = Convert.ToInt32(rp.ReservedStock * multiplier);
                rp.Save();

                this.MoveNext();
            }
        }
        internal void ChangeQuantity(decimal quantity)
        {
            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadByPrimaryKey(UnitID);
            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            receiveDocConfirmation.LoadByReceiveDocID(ID);

            if(receiveDocConfirmation.ReceiptConfirmationStatusID == ReceiptConfirmationStatus.Constants.GRV_PRINTED)
            {
                throw new Exception("Price has already been set for this Item, You cannot commit the Change you have Made");
            }

            if(QuantityLeft != Quantity)
            {
                 throw new Exception("Some Quantity has already been issued, You cannot commit the Change you have Made");
            }

            QuantityLeft= Quantity = quantity * itemUnit.QtyPerUnit;
            InvoicedNoOfPack = NoOfPack = quantity;
            Save();
            ReceivePallet receivePallet = new ReceivePallet();
            receivePallet.LoadByReceiveDocID(ID);

            receivePallet.ReceivedQuantity = receivePallet.Balance = Quantity;
            receivePallet.Save();
        }