private void btnSave_Click(object sender, EventArgs e)
        {
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    IssueDoc iss = new IssueDoc();
                    ReceiveDoc rec = new ReceiveDoc();

                    iss.LoadByPrimaryKey(_tranId);

                    string batchNo = iss.BatchNo;
                    Int64 qty = iss.Quantity;
                    rec.GetTransactionByBatch(iss.ItemID, iss.BatchNo, iss.StoreId);

                    iss.RefNo = txtRefNo.Text;
                    iss.BatchNo = txtBatchNo.Text;
                    iss.NoOfPack = Convert.ToInt32(txtPack.Text);
                    iss.QtyPerPack = Convert.ToInt32(txtQtyPack.Text);
                    iss.Quantity = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                    iss.StoreId = Convert.ToInt32(cboStores.SelectedValue);
                    iss.ReceivingUnitID = Convert.ToInt32(cboReceivingUnit.SelectedValue);
                    iss.Remark = txtRemark.Text;
                    iss.IssuedBy = txtReceivedBy.Text;
                    iss.Save();

                    Int64 newQty = 0;
                    if(qty > iss.Quantity)
                        newQty = rec.QuantityLeft + (qty - iss.Quantity);
                    else
                        newQty = rec.QuantityLeft - (iss.Quantity - qty);

                    rec.QuantityLeft = newQty;
                    if(rec.QuantityLeft >0)
                        rec.Out = false;
                    rec.Save();

                    XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
 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;
     }
 }
示例#3
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);
     }
 }
示例#4
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();
            }
        }
示例#5
0
        public void SetPriceForReceiveDocs()
        {
            ReceiveDoc receiveDoc = new ReceiveDoc();

            receiveDoc.LoadbyItemUnitManufacturerMovingAverageID(ReceiptID.Value, ItemID, ItemUnitID, ManufacturerID, MovingAverageID);
            receiveDoc.Rewind();
            while (!receiveDoc.EOF)
            {
                if (receiveDoc.IsColumnNull("PricePerPack") || !(receiveDoc.PricePerPack > 0))
                {
                    receiveDoc.PricePerPack = AverageCost;
                }
                if (receiveDoc.IsColumnNull("UnitCost") || !(receiveDoc.PricePerPack > 0))
                {
                    receiveDoc.UnitCost = Convert.ToDecimal(AverageCost);
                }
                receiveDoc.Cost         = AverageCost;
                receiveDoc.Margin       = Margin;
                receiveDoc.SellingPrice = SellingPrice;
                receiveDoc.MoveNext();
            }
            receiveDoc.Save();
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            var rec = new ReceiveDoc();
            DataTable dtbl = rec.GetTransactionByRefNo(_refno);
            if (rec.RowCount > 0)
            {
                foreach (DataRow datarow in dtbl.Rows)
                {
                    datarow["RefNo"] = refnotextEdit.Text;
                    datarow["Date"] = txtDate.Text;
                }
                rec.Save();
                Close();
                XtraMessageBox.Show("Refrence No and Date is successfully updated", "Success");
            }

            else
            {
                XtraMessageBox.Show("There is no refrence to edit");
                return;
            }
            this.Close();
        }
        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();
            }
        }
        /// <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();
            }
        }
        //, string guid)
        private void SavePalletization(ReceiveDoc rec, DataRowView drow)
        {
            if ((rec.Quantity == 0 && !rec.IsColumnNull("ShortageReasonID") && rec.ShortageReasonID == ShortageReasons.Constants.NOT_RECEIVED) || (rec.Quantity == 0 && rec.IsColumnNull("ShortageReasonID")))
            {
                HandleFullNotReceivedAndMultipleBatchPalletlization(rec,drow);
                return;
            }
            string guid;

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

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

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

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

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

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

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

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

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

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

                        }
                    }

                }
            }

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

                    int qtyPerPack = im.QuantityInBasicUnit;

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

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

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

            }

            rec.Save();
            rp.Rewind();
            while (!rp.EOF)
            {
                rp.ReceiveID = rec.ID;
                rp.MoveNext();
            }
            rp.Save();
            SavePutAwayItems();
        }
        /// <summary>
        /// After doing validation, the receive information is saved to the database.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            string valid = ValidateFields();
            if ( valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ReceiveDoc rec = new ReceiveDoc();
                    IssueDoc iss =new IssueDoc();
                    ProgramProduct pp = new ProgramProduct();
                    rec.LoadByPrimaryKey(_tranId);
                    iss.GetIssueByBatchAndId(rec.ItemID, rec.BatchNo, rec.ID);
                    rec.RefNo = txtRefNo.Text;
                    int previousprogid = rec.SubProgramID;
                    dtRecDate.CustomFormat = "MM/dd/yyyy";
                     string dtValid  = "";
                    try
                     {
                         rec.Date = Convert.ToDateTime(txtDate.Text);
                     }
                     catch
                     {
                         string year = "";
                         if (Convert.ToInt32(txtDate.Text.Substring(0, 2)) == 13)
                         {
                             dtValid = txtDate.Text;
                             year = dtValid.Substring(dtValid.Length - 4, 4);
                             rec.Date = Convert.ToDateTime("12/30/" + year);
                         }
                         else if (Convert.ToInt32(txtDate.Text.Substring(0, 2)) == 2)
                         {
                             dtValid = txtDate.Text;
                             year = dtValid.Substring(dtValid.Length - 4, 4);
                             rec.Date = Convert.ToDateTime("2/28/" + year);
                         }
                     }
                    if ((iss.RowCount != 0) && (iss.RecievDocID != null && iss.RecievDocID == rec.ID))
                        {
                            rec.BatchNo = txtBatchNo.Text;
                            rec.ExpDate = dtExpiryDate.Value;
                            rec.Remark = txtRemark.Text;
                            rec.ReceivedBy = txtReceivedBy.Text;
                            rec.SupplierID = Convert.ToInt32(cboSupplier.SelectedValue);
                            rec.UnitID = VisibilitySetting.HandleUnits==1 ? 0 : Convert.ToInt32(lkItemUnit.EditValue);
                            rec.StoreID = Convert.ToInt32(cboStores.SelectedValue);
                            pp.LoadByNewProgramIdAndItemId(Convert.ToInt32(rec.ItemID), Convert.ToInt32(lkPrograms.EditValue));
                            if (pp.RowCount == 1)
                            {
                                rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.ProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.ItemID = Convert.ToInt32(rec.ItemID);
                                pp.Save();

                            }
                            else if (pp.RowCount == 0)
                            {
                                rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.AddNew();
                                pp.ProgramID = rec.SubProgramID;
                                pp.ItemID = Convert.ToInt32(rec.ItemID);
                                pp.Save();
                            }
                            rec.Out = false;
                            rec.Save();
                            XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.Close();
                        }
                    else if (iss.RowCount == 0)
                    {
                        rec.BatchNo = txtBatchNo.Text;
                        rec.ExpDate = dtExpiryDate.Value;
                        rec.Remark = txtRemark.Text;
                        rec.ReceivedBy = txtReceivedBy.Text;
                        rec.NoOfPack = Convert.ToInt32(txtPack.Text);
                        rec.QtyPerPack = Convert.ToInt32(txtQtyPack.Text);
                        rec.Quantity = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                        rec.QuantityLeft = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                        rec.Out = false;
                        rec.StoreID = Convert.ToInt32(cboStores.SelectedValue);
                        rec.SupplierID = Convert.ToInt32(cboSupplier.SelectedValue);
                        rec.UnitID = VisibilitySetting.HandleUnits == 1 ? 0 : Convert.ToInt32(lkItemUnit.EditValue);
                        pp.LoadByNewProgramIdAndItemId(Convert.ToInt32(rec.ItemID), previousprogid);
                        if (pp.RowCount == 1)
                        {
                            rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.ProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.ItemID = Convert.ToInt32(rec.ItemID);
                            pp.Save();

                        }
                        else if(pp.RowCount ==0)
                        {
                            rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.AddNew();
                            pp.ProgramID = rec.SubProgramID;
                            pp.ItemID = Convert.ToInt32(rec.ItemID);
                            pp.Save();
                        }
                        rec.Cost = Convert.ToDouble(txtPrice.Text) / Convert.ToDouble(txtQtyPack.Text);
                        rec.Save();
                        XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }

                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        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>
        /// Delete a row of adjustmen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);

            var dataRow = gridView1.GetFocusedDataRow();
            if (dataRow == null) return;

            if (us.UserName != "admin")
            {
                XtraMessageBox.Show("You don't have the privilege to update reference number!", "Caution");
                return;
            }
            //get the primary key of the row
            var ID = Convert.ToInt32(dataRow["ID"]);

            var disposal = new Disposal();
            var receiveDoc = new ReceiveDoc();

            //Retrieve the adjustment with the value of the primary key(id)
            disposal.LoadByPrimaryKey(ID);

             int recieveID = disposal.RecID;

            receiveDoc.LoadByPrimaryKey(recieveID);
            if (XtraMessageBox.Show("Are You Sure, You want to delete this?", "Confirmation", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //check for losss

                if (disposal.Losses) //it was loss
                {
                    receiveDoc.LoadByPrimaryKey(recieveID);
                    var s = receiveDoc.Quantity;
                    receiveDoc.Quantity = receiveDoc.Quantity + disposal.Quantity;
                    receiveDoc.QuantityLeft = receiveDoc.QuantityLeft + disposal.Quantity;
                    if (receiveDoc.Out)
                        receiveDoc.Out = false;
                    disposal.Quantity = 0;
                }
                else // it was adjustment
                {
                    receiveDoc.LoadByPrimaryKey(recieveID);
                    var s = receiveDoc.Quantity;
                    receiveDoc.Quantity = receiveDoc.Quantity - disposal.Quantity;
                    receiveDoc.QuantityLeft = receiveDoc.QuantityLeft - disposal.Quantity;
                    if (receiveDoc.Quantity == 0)
                        receiveDoc.Out = true;
                    disposal.Quantity = 0;
                }

                // proceed deletion and make the necessary changes on the database tables.
                DisposalDelete ddel;
                AddDeletedDisposal(disposal, out ddel);

                receiveDoc.Save();
                disposal.MarkAsDeleted();
                disposal.Save();

                //Repopulate the grid
                DataTable dtRec;
                dtFrom.CustomFormat = "MM/dd/yyyy";
                dtTo.CustomFormat = "MM/dd/yyyy";
                DateTime from = ConvertDate.DateConverter(dtFrom.Text);
                DateTime to = ConvertDate.DateConverter(dtTo.Text);
                dtRec = disposal.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), from, to);
                gridAdjustments.DataSource = dtRec;
            }
        }
        /// <summary>
        /// Saves the whole transaction for
        /// </summary>
        /// <param name="orderID">The order ID.</param>
        /// <param name="dvOutstandingPickList">The dv outstanding pick list.</param>
        /// <param name="remark">The remark.</param>
        /// <param name="issuedBy">The issued by.</param>
        /// <param name="etCurrentDate">The et current date.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static Order SaveIssueTransaction(int orderID, ref DataView dvOutstandingPickList, string remark, string issuedBy, DateTime etCurrentDate)
        {
            // Add the IssueDocID field
            dvOutstandingPickList.Table.Columns.Add("IssueDocID");
            PickList   plst   = new PickList();
            IssueDoc   issDoc = new IssueDoc();
            ReceiveDoc recDoc = new ReceiveDoc();

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

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


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

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

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


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

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

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

                //long prevQuantityLeft = recDoc.QuantityLeft;

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

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

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

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

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

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

                rp.ReservedStock -= totReservedQty;
                if (rp.ReservedStock < 0) //If there has been a quantity problem somewhere
                {
                    rp.ReservedStock = 0;
                }
                rp.Save();
            }
            plst.IsConfirmed = true;
            ord.ChangeStatus(OrderStatus.Constant.ISSUED, CurrentContext.UserId);
            plst.Save();
            ord.Save();
            return(ord);
        }
 /// <summary>
 /// Receives from account transfer.
 /// </summary>
 /// <param name="PicklistID">The picklist ID.</param>
 /// <param name="StoreID">The store ID.</param>
 /// <param name="User">The user.</param>
 /// <param name="UserID">The user ID.</param>
 /// <returns></returns>
 public static String ReceiveFromAccountTransfer(int PicklistID, int StoreID, string User, int UserID)
 {
     PickListDetail pickListDetail = new PickListDetail();
     pickListDetail.LoadByPickListID(PicklistID);
     DataView dv = pickListDetail.DefaultView;
     ReceiveDoc NewReceiveDoc = new ReceiveDoc();
     String ReferenceID = ReceiveDoc.GetNextRefForTransfer();
     foreach (DataRowView dvr in dv)
     {
         //Get ReceiveDoc information.
         int receiveDocID = Convert.ToInt32(dvr["ReceiveDocID"]);
         ReceiveDoc receiveDocFromPicklist = new ReceiveDoc();
         receiveDocFromPicklist.LoadByPrimaryKey(receiveDocID);
         //We have all the Receivedoc information that we want
         NewReceiveDoc.AddNew();
         if (receiveDocFromPicklist.s_BatchNo == null)
             NewReceiveDoc.BatchNo = receiveDocFromPicklist.BatchNo;
         NewReceiveDoc.ItemID = receiveDocFromPicklist.ItemID;
         NewReceiveDoc.SupplierID = receiveDocFromPicklist.SupplierID;
         if (receiveDocFromPicklist.s_ExpDate == null)
             NewReceiveDoc.ExpDate = receiveDocFromPicklist.ExpDate;
         NewReceiveDoc.StoreID = StoreID;
         NewReceiveDoc.ReceivedBy = User;
         NewReceiveDoc.Remark = receiveDocFromPicklist.Remark;
         NewReceiveDoc.RefNo = "TA" + receiveDocFromPicklist.RefNo;
         if (!receiveDocFromPicklist.IsColumnNull("Cost"))
             NewReceiveDoc.Cost = receiveDocFromPicklist.Cost;
         NewReceiveDoc.ManufacturerId = receiveDocFromPicklist.ManufacturerId;
         NewReceiveDoc.Quantity = Convert.ToInt32(dvr["Packs"]) * Convert.ToInt32(dvr["QtyPerPack"]);
         NewReceiveDoc.NoOfPack = Convert.ToInt32(dvr["Packs"]);
         NewReceiveDoc.QtyPerPack = Convert.ToInt32(dvr["QtyPerPack"]);
         if (!receiveDocFromPicklist.IsColumnNull("PricePerPack"))
             NewReceiveDoc.PricePerPack = receiveDocFromPicklist.PricePerPack;
         if (!receiveDocFromPicklist.IsColumnNull("SellingPrice"))
             NewReceiveDoc.SellingPrice = receiveDocFromPicklist.SellingPrice;
         NewReceiveDoc.UnitID = receiveDocFromPicklist.UnitID;
         NewReceiveDoc.DeliveryNote = receiveDocFromPicklist.DeliveryNote;
         //NewReceiveDoc.PricePerPack = receiveDocFromPicklist.PricePerPack;
         NewReceiveDoc.QuantityLeft = Convert.ToInt32(dvr["Packs"]) * Convert.ToInt32(dvr["QtyPerPack"]);
         NewReceiveDoc.EurDate = DateTimeHelper.ServerDateTime;
         NewReceiveDoc.Date = EthiopianDate.EthiopianDate.Now.ToGregorianDate();
         NewReceiveDoc.IsDamaged = receiveDocFromPicklist.IsDamaged;
         NewReceiveDoc.Save();
         NewReceiveDoc.SetStatusAsReceived(UserID);
         PalletizeTransfer(NewReceiveDoc);
     }
     return ReferenceID;
 }
        private static void HandleReceiveDocDeleting(int receiveDocID, int userID, ReceiveDoc rd)
        {
            //Check if there is a Related Picklists
            var pld = new PickListDetail();
            pld.LoadByReceiveDocID(receiveDocID);
            pld.Rewind();
            if(pld.RowCount > 0)
            {
                var pl = new PickList();
                pl.LoadByPrimaryKey(pld.PickListID);

                var order = new Order();
                order.LoadByPrimaryKey(pl.OrderID);

                string printedIDs = "";
                var stvs = new BLL.Issue();
                stvs.Where.PickListID.Value = pl.ID;
                stvs.Query.Load();
                stvs.Rewind();
                while (!stvs.EOF)
                {
                    printedIDs += stvs.IDPrinted.ToString(CultureInfo.InvariantCulture) + " ,";
                    stvs.MoveNext();
                }
                printedIDs = printedIDs.Remove(printedIDs.Length - 1, 1);
                throw new Exception(
                    string.Format("Please cancel/void the following Stvs: Ref No = {0} With PrintedIDs : {1}",
                                  order.RefNo,printedIDs));
            }

            // Add new record on ReceiveDocDeleted
            var recDel = ReceiveDocDeleted.AddNewLog(rd, userID);

            // Delete related ReceivePallet
            var receivePallet = new BLL.ReceivePallet();
            receivePallet.LoadByReceiveDocID(receiveDocID);
            receivePallet.Rewind();
            while(!receivePallet.EOF)
            {
                receivePallet.MarkAsDeleted();
                receivePallet.MoveNext();
            }

            // Delete related ReceivePriceConfirmation
            var receivePriceConfirmation = new ReceivePriceConfirmation();
            receivePriceConfirmation.LoadByReceiveDocID(rd.ID);
            receivePriceConfirmation.MarkAsDeleted();

            // Delete related ReceiveDocShortage
            var rdShr = new ReceiveDocShortage();
            rdShr.Where.ReceiveDocID.Value = rd.ID;
            rdShr.Query.Load();
            rdShr.Rewind();
            while(!rdShr.EOF)
            {
                rdShr.MarkAsDeleted();
                rdShr.MoveNext();
            }

            // Delete related ReceiveDocConfirmation
            var rdConf = new ReceiveDocConfirmation();
            rdConf.Where.ReceiveDocID.Value = rd.ID;
            rdConf.Query.Load();
            rdConf.Rewind();
            while(!rdConf.EOF)
            {
                rdConf.MarkAsDeleted();
                rdConf.MoveNext();
            }

            rd.MarkAsDeleted();

            var transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            transaction.BeginTransaction();
            try
            {
                receivePallet.Save();
                receivePriceConfirmation.Save();
                rdShr.Save();
                rdConf.Save();
                recDel.Save();
                rd.Save();
                transaction.CommitTransaction();
            }
            catch (Exception exception)
            {
                transaction.RollbackTransaction();
                throw;
            }
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);

            DataRow dr = gridView1.GetFocusedDataRow();

            if (dr == null) return;

             int tranId = Convert.ToInt32(dr["ID"]);
            var rec = new ReceiveDoc();
            var iss = new IssueDoc();
            iss.LoadByPrimaryKey(tranId);

            string batchNo = iss.BatchNo;
            try
            {
                if (iss.RecievDocID.ToString() != "")
                    rec.LoadByPrimaryKey(iss.RecievDocID);
                else
                    rec.GetTransactionByBatch(iss.ItemID, iss.BatchNo, iss.StoreId);
            }
            catch
            {
                rec.GetTransactionByBatch(iss.ItemID, iss.BatchNo, iss.StoreId);
            }

            if ( batchNo != rec.BatchNo && batchNo !=string.Empty)
            {
                XtraMessageBox.Show("Unable to Delete, This Transaction has been processed. Try Loss and Adjustment.", "Unable to Delete", MessageBoxButtons.OK, MessageBoxIcon.Stop);

            }
            else if (batchNo == string.Empty || batchNo ==rec.BatchNo)
            {
                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)
                {
                    rec.QuantityLeft = rec.QuantityLeft + iss.Quantity;
                    if (rec.QuantityLeft > 0)
                        rec.Out = false;
                    rec.Save();
                    AddIssueLodDelete(iss);
                    iss.MarkAsDeleted();
                    iss.Save();

                    DataTable dtRec = iss.GetAllTransaction(Convert.ToInt32(cboStores.EditValue));
                    gridIssues.DataSource = dtRec;
                }
            }
        }
 public void SetPriceForReceiveDocs()
 {
     ReceiveDoc receiveDoc = new ReceiveDoc();
     receiveDoc.LoadbyItemUnitManufacturerMovingAverageID(ReceiptID.Value,ItemID,ItemUnitID,ManufacturerID,MovingAverageID);
     receiveDoc.Rewind();
     while (!receiveDoc.EOF)
     {
         if(receiveDoc.IsColumnNull("PricePerPack") || !(receiveDoc.PricePerPack > 0))
             receiveDoc.PricePerPack = AverageCost;
         if(receiveDoc.IsColumnNull("UnitCost") || !(receiveDoc.PricePerPack > 0))
             receiveDoc.UnitCost = Convert.ToDecimal(AverageCost);
         receiveDoc.Cost = AverageCost;
         receiveDoc.Margin = Margin;
         receiveDoc.SellingPrice = SellingPrice;
         receiveDoc.MoveNext();
     }
     receiveDoc.Save();
 }
        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");
             }
        }
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var us = new User();
            var userID = MainWindow.LoggedinId;
            us.LoadByPrimaryKey(userID);
            var dr = (DataRowView) lstTree.GetDataRecordByNode(lstTree.FocusedNode);
            if (dr == null) return;

            if (us.UserName != "admin")
            {
                XtraMessageBox.Show("You don't have the privilege to update reference number!", "Caution");
                return;
            }
            var rec = new ReceiveDoc();
            if (XtraMessageBox.Show("Are You Sure, You want to delete this?", "Confirmation", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DataTable dtbl = rec.GetTransactionByRefNo((string) dr["RefNo"]);
                foreach (DataRow dataRow in dtbl.Rows)
                {
                   // AddReceiveDocDeleted(dataRow);
                    dataRow.Delete();
                }
                rec.MarkAsDeleted();
                rec.Save();

                XtraMessageBox.Show("Item successfully deleted.", "Success");
            }
            else
            {
                return;
            }
        }
        private void BtnAddBatchClick(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate()) return;
            var rec = new ReceiveDoc();
            var yEnd = new YearEnd();

            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    {
                        rec.AddNew();
                        rec.ItemID = _itemid;
                        rec.BatchNo = txtBatchNo.Text;
                        rec.StoreID = _storeid;
                        rec.ExpDate = (DateTime) dateEditExpiryDate.EditValue;
                        rec.Date = _date;
                        rec.UnitID = 0;
                        rec.RefNo = txtRefNo.Text;
                        rec.Out = false;
                        rec.EurDate = DateTime.Now.Subtract(TimeSpan.FromDays(35));
                        rec.NoOfPack = Convert.ToInt32(txtPackQty.Text);
                        rec.QtyPerPack = Convert.ToInt32(txtQtyPerPack.Text);
                        rec.Quantity = (Convert.ToInt32(txtPackQty.Text))*(Convert.ToInt32(txtQtyPerPack.Text));
                        rec.QuantityLeft = (Convert.ToInt32(txtPackQty.Text))*(Convert.ToInt32(txtQtyPerPack.Text));
                        rec.Cost = Convert.ToDouble(txtPrice.Text);
                        rec.Save();

                        yEnd.AddNew();
                        yEnd.ItemID = _itemid;
                        yEnd.StoreID = _storeid;
                        yEnd.Year = _date.Year;
                        yEnd.AutomaticallyEntered = true;
                        yEnd.BBalance = 0;
                        yEnd.EBalance = 0;
                        yEnd.Save();

                    }
                    break;
                default:
                    {
                        rec.AddNew();
                        rec.ItemID = _itemid;
                        rec.BatchNo = txtBatchNo.Text;
                        rec.StoreID = _storeid;
                        rec.UnitID = _unitid;
                        rec.ExpDate = (DateTime) dateEditExpiryDate.EditValue;
                        rec.NoOfPack = Convert.ToInt32(txtPackQty.Text);
                        rec.Quantity = Convert.ToInt32(txtPackQty.Text);
                        rec.QuantityLeft = Convert.ToInt32(txtPackQty.Text);
                        rec.QtyPerPack = Convert.ToInt32(txtQtyPerPack.Text);
                        rec.Date = _date;
                        rec.RefNo = txtRefNo.Text;
                        rec.Out = false;
                        rec.EurDate = DateTime.Now.Subtract(TimeSpan.FromDays(35));
                        rec.Cost = Convert.ToDouble(txtPrice.Text);
                        rec.Save();

                        yEnd.AddNew();
                        yEnd.ItemID = _itemid;
                        yEnd.StoreID = _storeid;
                        yEnd.UnitID = _unitid;
                        yEnd.AutomaticallyEntered = true;
                        yEnd.BBalance = 0;
                        yEnd.EBalance = 0;
                        yEnd.Save();
                    }
                    break;
            }
            XtraMessageBox.Show("New Batch successfully added.", "Success");
            Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var rec = new ReceiveDoc();

            var itm = new Items();
            var itemprogram = new ProgramProduct();
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (
                    XtraMessageBox.Show("Are you sure you want to save this transaction?", "Confirmation",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        for (int i = 0; i < dtRecGrid.Rows.Count; i++)
                        {
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                if (Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]) <= DateTime.Now)
                                {
                                    var dialog =
                                        XtraMessageBox.Show(
                                            "The item " + dtRecGrid.Rows[i]["Item Name"].ToString() +
                                            " has already expired.  Are you sure you want to receive it?", "Warning",
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                                    if (dialog == DialogResult.No)
                                    {
                                        return;
                                    }

                                }
                            }
                            rec.AddNew();
                            rec.StoreID = Convert.ToInt32(cboStores.EditValue);
                            rec.RefNo = txtRefNo.Text.Trim();
                            rec.Remark = txtRemark.Text;
                            rec.ReceivedBy = txtReceivedBy.Text;

                            DateTime xx = dtRecDate.Value;
                            dtRecDate.CustomFormat = "MM/dd/yyyy";
                            DateTime dtRec = new DateTime();
                            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);

                            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
                            dtRecDate.IsGregorianCurrentCalendar = true;

                            rec.EurDate = dtRecDate.Value;

                            dtRecDate.IsGregorianCurrentCalendar = false;

                            rec.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);

                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    rec.UnitID = 0;
                                    rec.QtyPerPack = Convert.ToInt32(dtRecGrid.Rows[i]["Qty/Pack"]);
                                    break;
                                case 2:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                                case 3:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                            }
                            rec.NoOfPack = Convert.ToInt32(dtRecGrid.Rows[i]["Pack Qty"]);

                            rec.Quantity = rec.NoOfPack * rec.QtyPerPack;
                            rec.QuantityLeft = rec.Quantity;
                            if (dtRecGrid.Rows[i]["Price/Pack"] != null &&
                                dtRecGrid.Rows[i]["Price/Pack"].ToString() != "")
                            {
                                double pre = Convert.ToDouble(dtRecGrid.Rows[i]["Price/Pack"]) / rec.QtyPerPack;
                                rec.Cost = Convert.ToDouble(pre);
                            }
                            else
                            {
                                rec.Cost = 0;
                            }
                            itm.LoadByPrimaryKey(Convert.ToInt32(dtRecGrid.Rows[i]["ID"]));
                            rec.BatchNo = dtRecGrid.Rows[i][8].ToString();
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                rec.ExpDate = Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]);
                            }

                            rec.SupplierID = Convert.ToInt32(cboSupplier.EditValue);
                            rec.SubProgramID = Convert.ToInt32(cboProgram.EditValue);
                            string batch = DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() +
                                           DateTime.Now.Minute.ToString() + rec.ItemID.ToString();
                            rec.LocalBatchNo = batch;

                            rec.Out = false;
                            rec.IsApproved = false;
                            dtRecDate.Value = xx;
                            rec.Save();

                            //check if there is any data on stockoutLog about this item on this store
                            //and update its enddate to today
                            StockoutLog stockoutLog = new StockoutLog();
                            DataTable tblStockoutLog = stockoutLog.LoadByStoreAndItemId(rec.ItemID, rec.StoreID, true);
                            if (tblStockoutLog != null)
                            {
                                if (tblStockoutLog.Rows.Count > 0)
                                {
                                    stockoutLog.LoadByPrimaryKey(int.Parse(tblStockoutLog.Rows[0]["ID"].ToString()));
                                    stockoutLog.EndDate = DateTime.Today;
                                    stockoutLog.Save();
                                }
                            }

                            itemprogram.LoadByOldProgramIdAndItemId(Convert.ToInt32(dtRecGrid.Rows[i][0]),
                                                                 Convert.ToInt32(cboProgram.EditValue));
                            if (itemprogram.RowCount != 0)
                            {
                                continue;
                            }
                            else
                            {
                                itemprogram.AddNew();
                                itemprogram.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);
                                itemprogram.ProgramID = Convert.ToInt32(cboProgram.EditValue);
                                itemprogram.Save();
                            }
                        }
                        XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        ResetFields();
                        //  mgr.CommitTransaction();

                    }
                    catch (Exception exp)
                    {
                        //mgr.RollbackTransaction();
                        BLL.User user = new User();
                        user.LoadByPrimaryKey(MainWindow.LoggedinId);
                        if (user.UserType == UserType.Constants.SYSTEM_ADMIN)
                            XtraMessageBox.Show(exp.Message);
                        else
                            XtraMessageBox.Show("Saving Error!", "Error", MessageBoxButtons.OK);
                    }
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        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;
                }
            }
        }
        /// <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();
        }
示例#24
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            int warehouseID = Convert.ToInt32(lkWarehouse.EditValue);

            receiveDoc.Rewind();
            var po             = new BLL.PO();
            var receiptInvoice = new BLL.ReceiptInvoice();

            while (!receiveDoc.EOF)
            {
                //Handle the PO.
                //int receiptID;
                if (po.RowCount == 0 || po.StoreID != receiveDoc.StoreID)
                {
                    Supplier supplier = new Supplier();
                    po = BLL.PO.CreatePOforStandard(OrderType.CONSTANTS.STANDARD_ORDER, receiveDoc.StoreID,
                                                    supplier.GetHubHomeOfficeSupplierID(), "", CurrentContext.LoggedInUser.ID);
                    //Should we receive it as hub to hub transfer? We're now using Standard order.
                    receipt = BLL.ReceiptInvoice.CreateAutomaticReceiptInvoiceForSTVTransfer(po.ID, warehouseID, STVNo,
                                                                                             CurrentContext.UserId);
                }

                receiveDoc.Quantity  = receiveDoc.QtyPerPack * receiveDoc.NoOfPack;
                receiveDoc.ReceiptID = receipt.ID;
                receiveDoc.MoveNext();
            }
            receiveDoc.Save();

            //Save the location
            receiveDoc.Rewind();

            BLL.ReceivePallet receivePallet = new ReceivePallet();
            while (!receiveDoc.EOF)
            {
                //Save Location Information
                BLL.PalletLocation palletLocation = new PalletLocation();

                receivePallet.AddNew();

                int palletLocationID = Convert.ToInt32(receiveDoc.GetColumn("PalletLocationID"));
                receivePallet.PalletLocationID = palletLocationID;

                palletLocation.LoadByPrimaryKey(palletLocationID);

                receivePallet.PalletID         = palletLocation.PalletID;
                receivePallet.ReceivedQuantity = receiveDoc.Quantity;
                receivePallet.Balance          = receiveDoc.Quantity;
                receivePallet.ReceiveID        = receiveDoc.ID;
                receivePallet.ReservedStock    = 0;


                //Save Discrepancy information if there is any
                receiveDocShortage.Rewind();
                while (receiveDocShortage.FindNextByGUID(receiveDoc.GetColumn("GUID").ToString()))
                {
                    receiveDocShortage.ReceiveDocID = receiveDoc.ID;

                    if (receiveDocShortage.ShortageReasonID == ShortageReasons.Constants.DAMAGED)
                    {
                        receiveDoc.NoOfPack += receiveDocShortage.NoOfPacks;
                        receiveDoc.Quantity += receiveDocShortage.NoOfPacks * receiveDoc.QtyPerPack;

                        palletLocationID = Convert.ToInt32(receiveDocShortage.GetColumn("PalletLocationID"));
                        receivePallet.AddNew();
                        receivePallet.PalletLocationID = palletLocationID;
                        palletLocation.LoadByPrimaryKey(palletLocationID);

                        receivePallet.PalletID         = palletLocation.PalletID;
                        receivePallet.ReceivedQuantity = receiveDocShortage.NoOfPacks * receiveDoc.QtyPerPack;
                        receivePallet.Balance          = receiveDocShortage.NoOfPacks * receiveDoc.QtyPerPack;
                        receivePallet.ReceiveID        = receiveDoc.ID;
                        receivePallet.ReservedStock    = 0;
                    }
                }

                receiveDoc.MoveNext();
            }
            receivePallet.IsOriginalReceive = true;
            receivePallet.Save();
        }
        private void SaveReceive()
        {
            // Merge all Receives with Same Item information and Assigned to Same PhysicalStore as One Item , Quantity Sumed UP!
            MergeReceiveDocLines();

            BLL.ReceiveDoc rec = new ReceiveDoc();

            ////int receiptTypeID = srm
            ////    ? ReceiptType.CONSTANTS.STOCK_RETURN
            ////    : (deliveryNoteType != DeliveryNoteType.NotSet)
            ////        ? ReceiptType.CONSTANTS.DELIVERY_NOTE
            ////        : beginningBalance
            ////            ? ReceiptType.CONSTANTS.BEGINNING_BALANCE
            ////            : ReceiptType.CONSTANTS.STANDARD_RECEIPT;
            int receiptID;
            int warehouseID = Convert.ToInt32(lkWarehouse.EditValue);

            receiptID = SaveRelevantReceiptHeaders(_receiptTypeID, warehouseID);

            DataTable zeroQuantitiesDueToMultipleBatch = null;
            DataRow [] zeroQuantityRows =
                _dtRecGrid.Select(string.Format("[Pack Qty] = 0"),"[Ordering] ASC ");

            if (zeroQuantityRows.Any() && zeroQuantityRows.Any(r => r["ShortageReasonID"] == DBNull.Value))
            {
                zeroQuantityRows = CheckAndRemoveIfFullNotReceiveEntry(zeroQuantityRows);
                if (zeroQuantityRows.Any())
                    zeroQuantitiesDueToMultipleBatch =
                        zeroQuantityRows.Where(r => r["ShortageReasonID"] == DBNull.Value).CopyToDataTable();
            }

            var mergeableTables = _dtRecGrid.Select(string.Format("[Pack Qty] > 0 "), "[Ordering] ASC ");
            DataTable mergedDataTable = null;
            if (mergeableTables.Any())
            {
                mergedDataTable =
                    _dtRecGrid.Select(string.Format("[Pack Qty] > 0 "), "[Ordering] ASC ").CopyToDataTable();

                if (zeroQuantitiesDueToMultipleBatch != null)
                    mergedDataTable.Merge(zeroQuantitiesDueToMultipleBatch);

                if (grdShortageOrDamaged.DataSource != null)
                {
                    var shortageOrDamage = (DataTable) grdShortageOrDamaged.DataSource;
                    mergedDataTable.Merge(shortageOrDamage);
                }
            }
            else
            {
                if (grdShortageOrDamaged.DataSource != null)
                {
                    var shortageOrDamage = (DataTable)grdShortageOrDamaged.DataSource;
                    if (zeroQuantitiesDueToMultipleBatch != null)
                        shortageOrDamage.Merge(zeroQuantitiesDueToMultipleBatch);
                    //~ {"[ShortageReasonID] ASC} --> Just to give priority among shortages to Damaged reasons as we will create a receiveDoc entry for this ~//
                    mergedDataTable = mergedDataTable == null ? shortageOrDamage.Select(string.Format("[Pack Qty] >= 0 "), "[ShortageReasonID] ASC ").CopyToDataTable() : shortageOrDamage;

                }
            }

            foreach (DataRowView dr in mergedDataTable.DefaultView)
            {
                var shortageReasonID = dr["ShortageReasonID"];

                var onlyOneEntryFound = _dtRecGrid.Select(String.Format("GUID = '{0}'", dr["GUID"]));

                bool zeroQtyDueTomultipleBatchFound = (Convert.ToDecimal(dr["Pack Qty"]) == 0) && (shortageReasonID == DBNull.Value) && (onlyOneEntryFound.Count() == 1);
                bool fullNotReceivedEntry = (Convert.ToDecimal(dr["BU Qty"]) == 0) && (shortageReasonID != DBNull.Value) && (Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.NOT_RECEIVED) && (onlyOneEntryFound.Count() == 1);
                if (fullNotReceivedEntry)
                {
                    dr["Pack Qty"] = 0;
                }

                var item = new Item();
                item.LoadByPrimaryKey(Convert.ToInt32(dr["ID"]));

                if (item.NeedExpiryBatch || (shortageReasonID == DBNull.Value && ((dr["Expiry Date"] != DBNull.Value) && (Convert.ToDateTime(dr["Expiry Date"]) <= DateTimeHelper.ServerDateTime))))
                {

                    var expDate = Convert.ToDateTime(dr["Expiry Date"]);

                    if ((shortageReasonID == DBNull.Value && expDate > DateTimeHelper.ServerDateTime) || zeroQtyDueTomultipleBatchFound)
                    {
                        AddNewReceiveDoc(rec, receiptID, dr);
                    }
                    else
                    {
                        //for physically Damaged receives and expired receives
                        if ((shortageReasonID != DBNull.Value && Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.DAMAGED) || (shortageReasonID == DBNull.Value && expDate <= DateTimeHelper.ServerDateTime) || fullNotReceivedEntry)
                        {
                            AddNewReceiveDoc(rec, receiptID, dr, true);
                            if (shortageReasonID == DBNull.Value)
                            {
                                dr["ShortageReasonID"] = ShortageReasons.Constants.DAMAGED;
                            }
                        }
                        else
                        {

                            HandleReceiveDocShortage(dr, rec);
                        }
                    }
                }
                else
                {

                    if ((shortageReasonID == DBNull.Value) || zeroQtyDueTomultipleBatchFound)
                    {
                        AddNewReceiveDoc(rec, receiptID, dr);
                    }
                    else
                    {
                        //for physically Damaged receives
                        if (shortageReasonID != DBNull.Value && Convert.ToInt32(shortageReasonID) == ShortageReasons.Constants.DAMAGED || fullNotReceivedEntry)
                        {
                            AddNewReceiveDoc(rec, receiptID, dr, true);
                        }
                        else
                        {
                            HandleReceiveDocShortage(dr, rec);
                        }

                    }
                }

            }

            rec.SetStatusAsReceived(CurrentContext.UserId);

            BLL.Receipt receiptStatus = new BLL.Receipt();
            receiptStatus.LoadByPrimaryKey(receiptID);
            receiptStatus.ChangeStatus(ReceiptConfirmationStatus.Constants.RECEIVE_ENTERED, null,
                this.GetFormIdentifier(), CurrentContext.UserId, "Received");
            if (!BLL.Settings.HandleGRV) //If HandleGRV is true, the price isn't entered in the receive stage meaning
            {
                rec.Rewind();
                while (!rec.EOF)
                {
                    if (!ReceiveDoc.DoesPriceNeedToBeChanged(rec.StoreID, rec.ItemID, rec.UnitID, rec.ManufacturerId) &&
                        (deliveryNoteType == DeliveryNoteType.NotSet))
                    {
                        rec.SellingPrice = rec.Cost;
                        rec.UnitCost = Convert.ToDecimal(rec.Cost);
                        // Added by Heny In order to display Unit Cost on Vaccine
                        rec.Margin = 0;
                    }
                    rec.MoveNext();
                }
            }

            rec.Save(); //TODO: To be removed after the ShortageReasonID in receviedoc is discontinued.

            //SavePalletization(rdDamaged);
            _revDocRelatePalletGuid.Clear();
        }
        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 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;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            var transfer = new Transfer();
            var newreceiveDoc = new ReceiveDoc();
            var receiveDoc = new ReceiveDoc();
            var issuedoc = new IssueDoc();
            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)
                {
                try{
                      var dtRecGrid = (DataTable)receivingGrid.DataSource;
                        for (int i = 0; i < dtRecGrid.Rows.Count; i++)
                        {
                            transfer.AddNew();
                            var receiveid = Convert.ToInt32(dtRecGrid.Rows[i]["RecID"]);
                            transfer.ItemID = _itemID = Convert.ToInt32(dtRecGrid.Rows[i]["ID"]);
                            transfer.RecID = receiveid;
                            transfer.BatchNo = dtRecGrid.Rows[i]["Batch No"].ToString();
                            transfer.FromStoreID = Convert.ToInt32(lkFromStore.EditValue);
                            transfer.ToStoreID = Convert.ToInt32(lkToStore.EditValue);
                            transfer.Quantity = Convert.ToInt64(dtRecGrid.Rows[i]["Qty To Transfer"]);
                            transfer.RefNo = txtRefNo.Text;
                            transfer.UnitID = VisibilitySetting.HandleUnits == 1 ? 0 : Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);

                            DateTime xx = dtRecDate.Value;
                            dtRecDate.CustomFormat = "MM/dd/yyyy";
                            new DateTime();
                            transfer.Date = ConvertDate.DateConverter(dtRecDate.Text);
                            ConvertDate.DateConverter(dtRecDate.Text);
                            dtRecDate.IsGregorianCurrentCalendar = true;

                            transfer.EurDate = dtRecDate.Value;
                            dtRecDate.IsGregorianCurrentCalendar = false;

                            transfer.TransferReason = txtTransferReason.Text;
                            transfer.ApprovedBy = txtApprovedBy.Text;
                            transfer.TransferRequestedBy = txtRequestedBy.Text;
                            transfer.Save();

                           transfer.GetTransfered(receiveid, _itemID, Convert.ToInt32(lkFromStore.EditValue));
                           issuedoc.AddNew();
                           issuedoc.StoreId = transfer.FromStoreID;
                           issuedoc.ItemID = transfer.ItemID;
                           issuedoc.Quantity = transfer.Quantity;
                           issuedoc.Date = transfer.Date;
                           issuedoc.BatchNo = transfer.BatchNo;
                           issuedoc.UnitID = transfer.UnitID;
                           issuedoc.RecievDocID = transfer.RecID;
                           issuedoc.IsTransfer = true;
                           issuedoc.RefNo = transfer.RefNo;
                           var allstores = new Stores();
                           allstores.LoadByPrimaryKey(transfer.ToStoreID);
                           issuedoc.ReceivingUnitID = (int) allstores.GetColumn("ReceivingUnitID");
                           issuedoc.Save();

                            receiveDoc.GetReceivedItems(receiveid,_itemID, Convert.ToInt32(lkFromStore.EditValue));
                            receiveDoc.QuantityLeft = receiveDoc.QuantityLeft - transfer.Quantity;

                            newreceiveDoc.AddNew();

                            newreceiveDoc.StoreID = transfer.ToStoreID;
                            newreceiveDoc.RefNo = transfer.RefNo;
                            newreceiveDoc.BatchNo = transfer.BatchNo;
                            newreceiveDoc.ItemID = transfer.ItemID;
                            newreceiveDoc.Quantity = transfer.Quantity;
                            newreceiveDoc.QuantityLeft = transfer.Quantity;
                            newreceiveDoc.NoOfPack =  Convert.ToInt32(transfer.Quantity) / receiveDoc.QtyPerPack;
                            newreceiveDoc.QtyPerPack = receiveDoc.QtyPerPack;
                            newreceiveDoc.Cost = receiveDoc.Cost;

                            newreceiveDoc.Date = transfer.Date;
                            newreceiveDoc.UnitID = transfer.UnitID;
                            newreceiveDoc.Out = false;
                            newreceiveDoc.ReceivedBy = transfer.ApprovedBy;
                            newreceiveDoc.ExpDate = receiveDoc.ExpDate;

                            allstores.LoadByPrimaryKey(transfer.FromStoreID);
                            newreceiveDoc.SupplierID = (int) allstores.GetColumn("SupplierID");
                            newreceiveDoc.BoxLevel = 1;
                            newreceiveDoc.Save();
                            receiveDoc.Save();
                        }

                        XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ResetFields();

                    }
                    catch (Exception exp)
                    {
                       XtraMessageBox.Show(exp.InnerException.Message ,"Error");
                    }
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        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);
                }
            }
        }
        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);
                }
            }
        }
        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 btnSave_Click(object sender, EventArgs e)
        {
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Disposal dis = new Disposal();
                    Balance bal = new Balance();
                    ReceiveDoc rec = new ReceiveDoc();
                    DataTable dtAdjVal = (DataTable)AdjustmentGrid.DataSource;
                    for (int i = 0; i < dtAdjVal.Rows.Count; i++)
                    {

                        dis.AddNew();
                        dis.StoreId = Convert.ToInt32(cboStores.EditValue);
                        dis.ItemID = Convert.ToInt32(dtAdjVal.Rows[i]["ID"]);
                        dis.ApprovedBy = txtApprovedBy.Text;
                        DateTime xx = dtAdjustDate.Value;
                        dtAdjustDate.CustomFormat = "MM/dd/yyyy";
                        DateTime dtRec = new DateTime();

                        dis.Date = ConvertDate.DateConverter(dtAdjustDate.Text);
                        dtRec = ConvertDate.DateConverter(dtAdjustDate.Text);

                        dis.RefNo = txtRefNo.Text;
                        dis.BatchNo = dtAdjVal.Rows[i]["Batch No"].ToString();
                        double price = ((Convert.ToDouble(dtAdjVal.Rows[i]["BU Qty"]) != 0) ? (Convert.ToDouble(dtAdjVal.Rows[i]["Price"]) / Convert.ToDouble(dtAdjVal.Rows[i]["BU Qty"])) : 0);
                        dis.Cost = price;
                        dis.Remark = txtRemark.Text;
                        if (dtAdjVal.Rows[i]["Losses"].ToString() != "")
                        {
                            if (Convert.ToInt64(dtAdjVal.Rows[i]["Losses"]) <= Convert.ToInt64(dtAdjVal.Rows[i]["BU Qty"]))
                            {
                                dis.Losses = true;
                                dis.Quantity = Convert.ToInt64(dtAdjVal.Rows[i]["Losses"]);
                            }
                            else
                            {
                                XtraMessageBox.Show("You can't loss more quantity than what you have in the store!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                ResetFields();
                                return;
                            }
                        }
                        else
                        {
                            dis.Losses = false;
                            dis.Quantity = Convert.ToInt64(dtAdjVal.Rows[i]["Adjustment"]);
                        }
                        dis.ReasonId = Convert.ToInt32(dtAdjVal.Rows[i]["Reason"]);
                        if (VisibilitySetting.HandleUnits == 1)
                        {
                            dis.UnitID = 0;
                        }
                        else if (VisibilitySetting.HandleUnits == 2)
                        {
                            dis.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                        }
                        else if (VisibilitySetting.HandleUnits == 3)
                        {
                            dis.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                        }
                        dis.RecID = Convert.ToInt32(dtAdjVal.Rows[i]["RecID"]);
                        dis.EurDate = dtAdjustDate.Value;
                        dis.Save();

                        rec.LoadByPrimaryKey(Convert.ToInt32(dtAdjVal.Rows[i]["RecID"]));

                        if (rec.RowCount > 0)
                        {
                            if (dis.Losses)
                            {
                                rec.QuantityLeft = rec.QuantityLeft - dis.Quantity;
                                if (rec.QuantityLeft == 0)
                                    rec.Out = true;
                                else
                                    rec.Out = false;
                                //  rec.UnitID = Convert.ToInt32(dtAdjVal.Rows[i]["UnitID"]);
                                rec.Save();
                                //Log Activity, ActivityID for save is 1
                                // logger.SaveAction(1, 1, "Transaction\\LossesAdjustment.cs", "Loss/Adjustmet of " + dis.Quantity +" LOSS has been made.");
                            }
                            else
                            {
                                rec.QuantityLeft = rec.QuantityLeft + dis.Quantity;
                                if (rec.QuantityLeft != 0)
                                    rec.Out = false;
                                else
                                    rec.Out = true;
                                rec.Save();
                                //Log Activity, ActivityID for save is 1
                                //logger.SaveAction(1, 1, "Transaction\\LossesAdjustment.cs", "Loss/Adjustmet of " + dis.Quantity + " ADJUSTMENT has been made.");
                            }
                        }

                        dtAdjustDate.Value = xx;
                    }
                    XtraMessageBox.Show("Transaction successfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ResetFields();
                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }