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);
                }
            }
        }
        public static void DeleteIssueDoc(int issueID)
        {
            MyGeneration.dOOdads.TransactionMgr tranMgr =
                MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();

            try
            {
                tranMgr.BeginTransaction();


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

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

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

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


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

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

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

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

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

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


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


                        // now refresh the window
                        XtraMessageBox.Show("Issue Deleted!", "Confirmation", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        tranMgr.CommitTransaction();
                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "This delete is not successfull because a free pick face location was not selected. please select a free location and try again.",
                        "Error Deleteing issue transaction", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tranMgr.RollbackTransaction();
                }
            }
            catch
            {
                XtraMessageBox.Show("This delete is not successfull", "Warning ...", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                tranMgr.RollbackTransaction();
            }
        }
        private void btnMoveToQuaranteen_Click(object sender, EventArgs e)
        {
            if (ValidateMoveToQuaranteen())
            {
                if (DialogResult.Yes == XtraMessageBox.Show("Are you sure you want to move the items to Quarantine", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    InternalItemMovements ims = new InternalItemMovements();
                    PalletLocation        pl  = new PalletLocation();
                    int printNubmer           = InternalTransfer.GetNewPrintNumber() + 1;
                    for (int i = 0; i < gridView3.RowCount; i++)
                    {
                        DataRow dr = gridView3.GetDataRow(i);
                        if (dr["Loss"] != DBNull.Value)
                        {
                            int amount           = Convert.ToInt32(dr["Loss"]);
                            int palletLocationID = Convert.ToInt32(dr["PalletLocationID"]);

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

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

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

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

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


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


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

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


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

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

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

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

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


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

                    PopulateItemDetails();
                    XtraMessageBox.Show("Your items are marked for movement to Quarantine, please go to Internal Movements page to confirm!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void 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);
                }
            }
        }
Esempio n. 5
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 SaveOrder()
        {
            var order    = GenerateOrder();
            var picklist = PickList.GeneratePickList(order.ID);

            int lineNo = 0;

            // This is a kind of initializing the data table.
            OrderDetail    ord      = new OrderDetail();
            PickListDetail pkDetail = new PickListDetail();
            DataView       dv       = orderGrid.DataSource as DataView;

            foreach (DataRowView r in dv)
            {
                if (r["ApprovedPacks"] != null && r["ApprovedPacks"] != DBNull.Value && r["ApprovedPacks"].ToString() != "")
                {
                    if (Convert.ToInt32(r["ApprovedPacks"]) != 0)
                    {
                        lineNo = lineNo + 1;
                        int itemID = Convert.ToInt32(r["ItemID"]);
                        int unitID = Convert.ToInt32(r["UnitID"]);
                        ord.AddNew();
                        ord.OrderID = order.ID;
                        ord.ItemID  = itemID;
                        if (r["ApprovedPacks"] != DBNull.Value)
                        {
                            ord.Pack = Convert.ToInt32(r["ApprovedPacks"]);
                        }
                        if (r["QtyPerPack"] != DBNull.Value)
                        {
                            ord.QtyPerPack = Convert.ToInt32(r["QtyPerPack"]);
                        }
                        ord.Quantity         = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        ord.ApprovedQuantity = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        ord.UnitID           = unitID;
                        ord.StoreID          = Convert.ToInt32(lkAccountType.EditValue);


                        ord.Save();
                        pkDetail.AddNew();
                        pkDetail.PickListID       = picklist.ID;
                        pkDetail.ItemID           = itemID;
                        pkDetail.PalletLocationID = Convert.ToInt32(r["LocationID"]);
                        pkDetail.BatchNumber      = r["BatchNo"].ToString();
                        if (r["ExpDate"] != DBNull.Value)
                        {
                            pkDetail.ExpireDate = DateTime.Parse(r["ExpDate"].ToString());
                        }

                        pkDetail.StoreID      = Convert.ToInt32(r["StoreID"]);
                        pkDetail.UnitID       = unitID;
                        pkDetail.ReceiveDocID = Convert.ToInt32(r["ReceiveDocID"]);
                        if (r["UnitPrice"] != DBNull.Value)
                        {
                            pkDetail.Cost      = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToDouble(r["UnitPrice"]);
                            pkDetail.UnitPrice = Convert.ToDouble(r["UnitPrice"]);
                        }
                        pkDetail.Packs           = Convert.ToInt32(r["ApprovedPacks"]);
                        pkDetail.QtyPerPack      = Convert.ToInt32(r["QtyPerPack"]);
                        pkDetail.QuantityInBU    = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToInt32(r["QtyPerPack"]);
                        pkDetail.StoreID         = Convert.ToInt32(r["StoreID"]);
                        pkDetail.ReceivePalletID = Convert.ToInt32(r["ReceivingLocationID"]);
                        pkDetail.ManufacturerID  = Convert.ToInt32(r["ManufacturerID"]);
                        pkDetail.BoxLevel        = 0;
                        pkDetail.DeliveryNote    = true;
                        pkDetail.Save();
                        //To Print The Picklist
                        //Then reserve Items
                        ReceivePallet receivepallet = new ReceivePallet();
                        receivepallet.LoadByPrimaryKey(Convert.ToInt32(r["ReceivingLocationID"]));
                        receivepallet.ReservedStock = receivepallet.ReservedStock + Convert.ToInt32(r["ApprovedPacks"]);
                        receivepallet.Save();


                        DataRow drvpl = dvPickList.NewRow();
                        drvpl["FullItemName"] = r["FullItemName"];
                        drvpl["StockCode"]    = r["StockCode"];
                        drvpl["BatchNo"]      = r["BatchNo"];
                        if (r["ExpDate"] != DBNull.Value)
                        {
                            drvpl["ExpDate"] = Convert.ToDateTime(r["ExpDate"]).ToString("MMM/yyyy");
                        }
                        else
                        {
                            drvpl["ExpDate"] = DBNull.Value;
                        }
                        drvpl["LineNum"]          = lineNo + 1;
                        drvpl["ManufacturerName"] = r["Manufacturer"];
                        drvpl["Pack"]             = r["ApprovedPacks"];
                        drvpl["UnitPrice"]        = r["UnitPrice"];

                        drvpl["Unit"]           = r["Unit"];
                        drvpl["PalletLocation"] = r["Location"];
                        drvpl["QtyInSKU"]       = Convert.ToInt32(r["ApprovedPacks"]);
                        if (r["UnitPrice"] != DBNull.Value)
                        {
                            drvpl["CalculatedCost"] = Convert.ToInt32(r["ApprovedPacks"]) * Convert.ToDouble(r["UnitPrice"]);
                        }

                        PalletLocation palletLocation = new PalletLocation();
                        palletLocation.LoadByPrimaryKey(pkDetail.PalletLocationID);
                        drvpl["WarehouseName"]     = palletLocation.WarehouseName;
                        drvpl["PhysicalStoreName"] = palletLocation.PhysicalStoreName;
                        var activity = new Activity();
                        activity.LoadByPrimaryKey(pkDetail.StoreID);
                        drvpl["ActivityConcat"] = activity.FullActivityName;
                        drvpl["AccountName"]    = activity.AccountName;
                        dvPickList.Rows.Add(drvpl);
                    }
                }
            }
            if (lineNo == 0)
            {
                throw new System.ArgumentException("Please review your list,you haven't approved any Quantity");
            }

            var plr = HCMIS.Desktop.Reports.WorkflowReportFactory.CreatePicklistReport(order, lkForHub.Text,
                                                                                       dvPickList.DefaultView);


            plr.PrintDialog();

            if (!BLL.Settings.IsCenter)
            {
                if (TransferTypeID == 3)
                {
                    XtraMessageBox.Show("Your Store To Store Transfer will be Printed now", "Store To Store Transfer");
                    Transfer.Move(picklist.ID);
                    HCMIS.Desktop.Reports.StoreTransferPrintOut STM =
                        new HCMIS.Desktop.Reports.StoreTransferPrintOut();
                    STM.LoadByPickListID(picklist.ID);
                    STM.PrintDialog();
                }
                else if (TransferTypeID == 2)
                {
                    XtraMessageBox.Show(ReceiveDoc.ReceiveFromAccountTransfer(picklist.ID,
                                                                              Convert.ToInt32(lkForHub.EditValue),
                                                                              CurrentContext.LoggedInUserName,
                                                                              CurrentContext.UserId));
                }
            }
            else
            {
                XtraMessageBox.Show("Picklist Prepared!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Esempio n. 7
0
        private static void AddLoads(JobLogDB log, IEnumerable <LoadAction> currentLoads, string pallet, PalletLocation palLoc, CurrentStatus curStatus)
        {
            var queuedMats = new Dictionary <string, List <BlackMaple.MachineFramework.JobLogDB.QueuedMaterial> >();

            //process remaining loads/unloads (already processed ones have been removed from currentLoads)
            foreach (var operation in currentLoads)
            {
                if (!operation.LoadEvent || operation.LoadStation != palLoc.Num)
                {
                    continue;
                }
                for (int i = 0; i < operation.Qty; i++)
                {
                    List <BlackMaple.MachineFramework.JobLogDB.QueuedMaterial> queuedMat = null;
                    if (curStatus.Jobs.ContainsKey(operation.Unique))
                    {
                        var queue = curStatus.Jobs[operation.Unique].GetInputQueue(process: operation.Process, path: operation.Path);
                        if (!string.IsNullOrEmpty(queue))
                        {
                            //only lookup each queue once
                            if (queuedMats.ContainsKey(queue))
                            {
                                queuedMat = queuedMats[queue];
                            }
                            else
                            {
                                queuedMat = log.GetMaterialInQueue(queue).ToList();
                                queuedMats.Add(queue, queuedMat);
                            }
                        }
                    }
                    long   matId  = -1;
                    string serial = null;
                    string workId = null;
                    var    loc    = new InProcessMaterialLocation()
                    {
                        Type = InProcessMaterialLocation.LocType.Free
                    };
                    if (queuedMat != null)
                    {
                        var mat = queuedMat
                                  .Where(m => m.Unique == operation.Unique)
                                  .Select(m => (JobLogDB.QueuedMaterial?)m)
                                  .DefaultIfEmpty(null)
                                  .First();
                        if (mat.HasValue)
                        {
                            matId = mat.Value.MaterialID;
                            loc   = new InProcessMaterialLocation()
                            {
                                Type          = InProcessMaterialLocation.LocType.InQueue,
                                CurrentQueue  = mat.Value.Queue,
                                QueuePosition = mat.Value.Position,
                            };
                            queuedMat.RemoveAll(m => m.MaterialID == mat.Value.MaterialID);
                            var matDetails = log.GetMaterialDetails(matId);
                            serial = matDetails?.Serial;
                            workId = matDetails?.Workorder;
                        }
                    }
                    var inProcMat = new InProcessMaterial()
                    {
                        MaterialID  = matId,
                        JobUnique   = operation.Unique,
                        PartName    = operation.Part,
                        Process     = operation.Process,
                        Path        = operation.Path,
                        Serial      = serial,
                        WorkorderId = workId,
                        Location    = loc,
                        Action      = new InProcessMaterialAction()
                        {
                            Type             = InProcessMaterialAction.ActionType.Loading,
                            LoadOntoPallet   = pallet,
                            LoadOntoFace     = operation.Process,
                            ProcessAfterLoad = operation.Process,
                            PathAfterLoad    = operation.Path
                        }
                    };
                    curStatus.Material.Add(inProcMat);
                }
            }
        }
Esempio n. 8
0
        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);
                }
            }
        }
        private void ConfirmQuantityAndLocation()
        {
            //TODO: finish updating the changed locations
            MyGeneration.dOOdads.TransactionMgr transaction = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
            transaction.BeginTransaction();
            try
            {
                PalletLocation pl        = new PalletLocation();
                String         reference = gridReceiveView.GetFocusedDataRow()["RefNo"].ToString();
                //           pl.ConfirmAllReceived(reference);
                if (gridDetailView.DataSource == null)
                {
                    return;
                }

                foreach (DataRowView drv in gridDetailView.DataSource as DataView)
                {
                    int PalletLocationID         = Convert.ToInt32(drv["PalletLocationID"]);
                    int ProposedPalletLocationID = Convert.ToInt32(drv["ProposedPalletLocationID"]);
                    int PalletID  = Convert.ToInt32(drv["PalletID"]);
                    int receiveID = Convert.ToInt32(drv["ReceiveID"]);

                    if (PalletLocationID != ProposedPalletLocationID)
                    {
                        pl.LoadByPrimaryKey(PalletLocationID);
                        if (pl.IsColumnNull("PalletID"))
                        {
                            pl.PalletID  = PalletID;
                            pl.Confirmed = true;
                            pl.Save();

                            pl.LoadByPrimaryKey(ProposedPalletLocationID);
                            pl.SetColumnNull("PalletID");
                            pl.Save();
                        }
                        else
                        {
                            XtraMessageBox.Show("Some Items/Pallets were not confirmed correctly because the newly selected pallet location was already occupied.", "Some Items were not confirmed.");
                        }
                    }
                    else
                    {
                        pl.LoadByPrimaryKey(PalletLocationID);
                        pl.PalletID  = PalletID;
                        pl.Confirmed = true;
                        pl.Save();
                    }
                }

                BLL.ReceiveDoc recDoc = new ReceiveDoc();
                recDoc.LoadByReferenceNo(reference);
                recDoc.ConfirmQuantityAndLocation(null);

                transaction.CommitTransaction();
                XtraMessageBox.Show("Receipt Confirmed!", "Success", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                BindFormContents();
            }
            catch (Exception exp)
            {
                transaction.RollbackTransaction();
                XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 10
0
 private static LoadAction CheckUnload(List <LoadAction> currentLoads, string unique, int process, PalletLocation loc)
 {
     if (loc.Location != PalletLocationEnum.LoadUnload)
     {
         return(null);
     }
     foreach (var act in currentLoads)
     {
         if (act.LoadEvent == false &&
             loc.Num == act.LoadStation &&
             unique == act.Unique &&
             process == act.Process &&
             act.Qty >= 1)
         {
             if (act.Qty == 1)
             {
                 currentLoads.Remove(act);
             }
             else
             {
                 act.Qty -= 1;
             }
             return(act);
         }
     }
     return(null);
 }
Esempio n. 11
0
        private void gridReceiveView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            // Bind the detail grid
            PalletLocation pl = new PalletLocation();

            if (e != null && e.PrevFocusedRowHandle < -1)
            {
                return;
            }
            string warehouseName = string.Empty;

            try
            {
                var dr = gridReceiveView.GetFocusedDataRow();
                if (dr == null)
                {
                    return;
                }
                ReceiptID = Convert.ToInt32(dr["ReceiptID"]);
                var receiptDoc = new BLL.Receipt();

                var receipt = new BLL.Receipt();
                receipt.LoadByPrimaryKey(ReceiptID);

                receiptDoc.LoadByPrimaryKey(ReceiptID);
                var GRNFDetail = receiptDoc.GetDetailsForGRNF();
                if (GRNFDetail.Rows.Count > 0)
                {
                    txtOrderNo.EditValue = dr["PONumber"] == DBNull.Value ? "-" : dr["PONumber"];
                    lblPONo.Text         = (dr["PONumber"] == DBNull.Value ? "-" : dr["PONumber"].ToString());

                    lblCluster.Text        = dr["ClusterName"] == DBNull.Value ? "-" : dr["ClusterName"].ToString();
                    txtWarehouse.EditValue = lblWarehouse.Text = warehouseName = dr["WarehouseName"] == DBNull.Value ? "-" : dr["WarehouseName"].ToString();

                    var receiptInvoice = new ReceiptInvoice(receiptDoc.ReceiptInvoiceID);
                    txtInvoiceNo.EditValue = lblInvoiceNo.Text = String.IsNullOrEmpty(receiptInvoice.STVOrInvoiceNo) ? "-" : receiptInvoice.STVOrInvoiceNo;
                    txtInsurance.EditValue = lblInsurancePolicy.Text = String.IsNullOrEmpty(receiptInvoice.InsurancePolicyNo) ? "-" : receiptInvoice.InsurancePolicyNo;
                    txtTransfer.EditValue  = lblTransferVoucherNo.Text = String.IsNullOrEmpty(receipt.TransitTransferNo) ? "-" : receipt.TransitTransferNo;
                    txtWayBill.EditValue   = lblWayBill.Text = String.IsNullOrEmpty(receiptInvoice.WayBillNo) ? "-" : receiptInvoice.WayBillNo;

                    var activity = new Activity();
                    activity.LoadByPrimaryKey(Convert.ToInt32(dr["StoreID"]));
                    txtActivity.EditValue = activity.FullActivityName;

                    lblActivity.Text   = String.IsNullOrEmpty(activity.Name) ? "-" : activity.Name;
                    lblSubAccount.Text = String.IsNullOrEmpty(activity.SubAccountName) ? "-" : activity.SubAccountName;
                    lblAccount.Text    = String.IsNullOrEmpty(activity.AccountName) ? "-" : activity.AccountName;
                    lblMode.Text       = String.IsNullOrEmpty(activity.ModeName) ? "-" : activity.ModeName;

                    lblReceiveType.Text   = dr["ReceiptType"] == DBNull.Value ? "-" : dr["ReceiptType"].ToString();
                    lblReceiveStatus.Text = dr["Status"] == DBNull.Value ? "-" : dr["Status"].ToString();
                    lblDocumentType.Text  = dr["DocumentType"] == DBNull.Value ? "-" : dr["DocumentType"].ToString();
                    lblPOType.Text        = dr["POType"] == DBNull.Value ? "-" : dr["POType"].ToString();
                    lblPaymentType.Text   = dr["PaymentType"] == DBNull.Value ? "-" : dr["PaymentType"].ToString();
                    lblReceiptNo.Text     = dr["ReceiptNo"] == DBNull.Value ? "-" : dr["ReceiptNo"].ToString();

                    lblSupplier.Text = dr["Supplier"] == DBNull.Value ? "-" : dr["Supplier"].ToString();

                    var user = new User();
                    user.LoadByPrimaryKey(receiptDoc.SavedByUserID);
                    lblReceivedBy.Text = String.IsNullOrEmpty(user.FullName) ? "-" : user.FullName;

                    var receiveDoc = new ReceiveDoc();
                    receiveDoc.LoadByReceiptID(ReceiptID);
                    lblReceivedDate.Text  = receiptDoc.IsColumnNull("DateOfEntry") ? "-" :receiveDoc.EurDate.ToShortDateString();
                    lblConfirmedDate.Text = receiveDoc.IsColumnNull("ConfirmedDateTime") ? "-" : receiveDoc.ConfirmedDateTime.ToShortDateString();

                    if (!receiveDoc.IsColumnNull("ConfirmedByUserID"))
                    {
                        user.LoadByPrimaryKey(receiveDoc.ConfirmedByUserID);
                        lblConfirmedBy.Text = String.IsNullOrEmpty(user.FullName) ? "-" : user.FullName;
                    }
                    else
                    {
                        lblConfirmedBy.Text = "-";
                    }
                    var space  = string.Empty;
                    var length = warehouseName.Length;

                    HeaderGroup.Text = warehouseName + space.PadRight(180 - length) + "Invoice No: " + receiptInvoice.STVOrInvoiceNo;
                }

                gridDetails.DataSource  = GRNFDetail;
                gridShortage.DataSource = receiptDoc.GetDiscrepancyForGRNF();
            }

            catch
            {
                gridDetails.DataSource = null;
            }
        }
Esempio n. 12
0
        private void gridReceiveView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            // Bind the detail grid
            PalletLocation pl = new PalletLocation();

            try
            {
                ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);
                BLL.Receipt receiptDoc = new BLL.Receipt();
                var         rd         = new ReceiveDoc();
                rd.LoadByReceiptID(ReceiptID);

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

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

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



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

                var SelectGRV = gridReceiveView.GetFocusedDataRow();

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

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

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

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



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

                else
                {
                    lblCalculatedBy.Text = "-";
                }

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

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


                string s = "";

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



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



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



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

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

            catch
            {
                gridDetails.DataSource  = null;
                gridShortage.DataSource = null;
            }
        }
Esempio n. 13
0
        private void gridReceiveView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            // Bind the detail grid
            var pl = new PalletLocation();

            ReceiptID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["ReceiptID"]);

            try
            {
                //B1A data
                var    SelectGRV = gridReceiveView.GetFocusedDataRow();
                String reference = gridReceiveView.GetFocusedDataRow()["RefNo"].ToString();
                lblGRVNo.Text      = reference;
                lblMode.Text       = (string)SelectGRV["ModeName"];
                lblAccount.Text    = (string)SelectGRV["AccountName"];
                lblSubAccount.Text = (string)SelectGRV["SubAccountName"];
                lblActivity.Text   = (string)SelectGRV["ActivityName"];
                lblSupplier.Text   = (string)SelectGRV["SupplierName"];
                lblPoNumber.Text   = (string)SelectGRV["PONo"];
                lblCluster.Text    = (string)SelectGRV["ClusterName"];
                lblWarehouse.Text  = (string)SelectGRV["WarehouseName"];
                lblStore.Text      = (string)SelectGRV["PhysicalStoreName"];
                lblType.Text       = (string)SelectGRV["ReceiptType"];
                lblStatus.Text     = (string)SelectGRV["ReceiptStatus"];

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

                if (dtHistory != null && dtHistory.Count > 0)
                {
                    lblCalculatedBy.Text   = (string)dtHistory[0]["FullName"];
                    lblCalculatedDate.Text = ((DateTime)dtHistory[0]["Date"]).ToShortDateString();
                }
                else
                {
                    lblCalculatedDate.Text = lblCalculatedBy.Text = "-";
                }

                var receiveDoc = new ReceiveDoc();
                receiveDoc.LoadByReceiptID(Convert.ToInt32(SelectGRV["ReceiptID"]));
                lblConfirmedDate.Text = receiveDoc.ConfirmedDateTime.ToString() != "" ? receiveDoc.ConfirmedDateTime.ToShortDateString() : "-";


                lblConfirmedBy.Text = SelectGRV["confirmedBy"] != DBNull.Value ? SelectGRV["confirmedBy"].ToString() : "-";
                lblGRVNumber.Text   = reference;
                lblRecivedDate.Text = ((DateTime)SelectGRV["Date"]).ToShortDateString();


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

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


                int status = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["Status"]);
                try
                {
                    StoreID = Convert.ToInt32(gridReceiveView.GetFocusedDataRow()["StoreID"]);
                }
                catch
                {
                }

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

            catch
            {
                gridDetails.DataSource = null;
            }

            //reset
            btnCancelVoidRequest.Enabled = true;
            btnVoidRequest.Enabled       = true;
            btnVoid.Enabled       = true;
            btnReprintGRV.Enabled = true;

            if (Convert.ToBoolean(gridReceiveView.GetFocusedDataRow()["isreprint"].ToString()))
            {
                btnReprintGRV.Enabled = false;
            }

            if (Convert.ToBoolean(gridReceiveView.GetFocusedDataRow()["hasreprint"].ToString()))
            {
                btnCancelVoidRequest.Enabled = false;
                btnVoidRequest.Enabled       = false;
                btnVoid.Enabled = false;
            }
        }
        public ReceiveDoc CreateInventoryReceive(Inventory inventory,int receiptID,Inventory.QuantityType quantityType,DateTime ethiopianDate,User user)
        {
            ItemUnit itemUnit = new ItemUnit();
            itemUnit.LoadByPrimaryKey(inventory.UnitID);

            ReceiveDoc receiveDoc = new ReceiveDoc();
            receiveDoc.AddNew();
            receiveDoc.ItemID = inventory.ItemID;
            receiveDoc.UnitID = inventory.UnitID;
            receiveDoc.ManufacturerId = inventory.ManufacturerID;

            receiveDoc.StoreID = inventory.ActivityID;
            receiveDoc.Date = ethiopianDate;
            receiveDoc.EurDate = DateTimeHelper.ServerDateTime;
            receiveDoc.PhysicalStoreID = inventory.PhysicalStoreID;
            receiveDoc.SetColumn("BatchNo", inventory.GetColumn("BatchNo"));
            decimal quantity = quantityType == Inventory.QuantityType.Sound
                                   ? inventory.InventorySoundQuantity
                                   : quantityType == Inventory.QuantityType.Damaged
                                    ? inventory.InventoryDamagedQuantity :inventory.InventoryExpiredQuantity;

            if(quantityType == Inventory.QuantityType.Damaged) receiveDoc.ShortageReasonID = ShortageReasons.Constants.DAMAGED;
            receiveDoc.Quantity = receiveDoc.QuantityLeft = quantity * itemUnit.QtyPerUnit;
            receiveDoc.NoOfPack = receiveDoc.InvoicedNoOfPack = quantity;
            receiveDoc.QtyPerPack = itemUnit.QtyPerUnit;
            receiveDoc.SetColumn("ExpDate", inventory.GetColumn("ExpiryDate"));

            receiveDoc.Out = false;

            receiveDoc.ReceivedBy = user.UserName;

            receiveDoc.StoreID = inventory.ActivityID;
            receiveDoc.RefNo = "BeginningBalance";
            decimal cost = 0;
            decimal margin = 0;

            if (!inventory.IsColumnNull("Cost"))
            {
                cost = inventory.Cost;
            }

            if(!inventory.IsColumnNull("Margin"))
            {
                margin = inventory.Margin;
            }

            receiveDoc.Cost = Convert.ToDouble(cost);
            receiveDoc.PricePerPack = Convert.ToDouble(cost);
            receiveDoc.UnitCost = cost;
            receiveDoc.Margin = Convert.ToDouble(margin);
            receiveDoc.SellingPrice = Convert.ToDouble(BLL.Settings.IsCenter ? cost : cost * (1 + margin));
            receiveDoc.SupplierID = 2; //TODO: HARDCODE WARNING WARNING WARNING
            receiveDoc.DeliveryNote = false;
            receiveDoc.Confirmed = true;
            receiveDoc.ConfirmedDateTime = DateTimeHelper.ServerDateTime;
            receiveDoc.ReturnedStock = false;
            receiveDoc.ReceiptID = receiptID;
            receiveDoc.RefNo = "BeginningBalance";
            receiveDoc.InventoryPeriodID = inventory.InventoryPeriodID;
            receiveDoc.IsDamaged = (quantityType == Inventory.QuantityType.Damaged ||
                                   quantityType == Inventory.QuantityType.Expired);
            receiveDoc.Save();

            //Now Save the ReceiveDocConfirmation

            ReceiveDocConfirmation rdConf = new ReceiveDocConfirmation();
            rdConf.AddNew();
            rdConf.ReceiveDocID = receiveDoc.ID;
            rdConf.ReceivedByUserID = user.ID;
            rdConf.ReceiptConfirmationStatusID = ReceiptConfirmationStatus.Constants.RECEIVE_QUANTITY_CONFIRMED;
            rdConf.Save();

            //TODO: Create Receive Pallet Here
            PalletLocation palletLocation = new PalletLocation();

            palletLocation.LoadByPrimaryKey(quantityType != Inventory.QuantityType.Damaged
                                                ? inventory.PalletLocationID
                                                : inventory.DamagedPalletLocationID);

            ReceivePallet receivePallet = new ReceivePallet();
            receivePallet.AddNew();
            receivePallet.Balance = quantity * itemUnit.QtyPerUnit;
            receivePallet.ReceivedQuantity = quantity * itemUnit.QtyPerUnit;
            receivePallet.ReservedStock = 0;
            receivePallet.ReceiveID = receiveDoc.ID;

            if(palletLocation.IsColumnNull("PalletID"))
            {
                Pallet pallet = new Pallet();
                pallet.AddNew();
                pallet.Save();
                palletLocation.PalletID = pallet.ID;
                palletLocation.Save();
            }

            receivePallet.PalletID = palletLocation.PalletID;
            receivePallet.PalletLocationID =palletLocation.ID;
            receivePallet.BoxSize = 0;
            receivePallet.IsOriginalReceive = true;
            receivePallet.Save();

            return receiveDoc;
        }
        /// <summary>
        /// Handles the Click event of the btnConfirmIssue control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <exception cref="System.Exception"></exception>
        private void btnConfirmIssue_Click(object sender, EventArgs e)
        {
            // This is where the Issue is actually recorded and the stv is printed.
            // Do all kinds of validations.
            XtraReport STVReport = null; XtraReport DeliveryNoteReport = null;

            btnConfirmIssue1.Enabled = false;
            if (!IssueValid())
            {
                XtraMessageBox.Show("Please Correct the Items Marked in Red before Proceeding with Issue", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                return;
            }

            if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DateTimePickerEx dtDate = ConvertDate.GetCurrentEthiopianDateText();

                DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
                // The User is now sure that the STV has to be printed and that
                // the order is also good to save.
                // This is the section that does the saving.

                BLL.Order order = new Order();
                order.LoadByPrimaryKey(_orderID);

                // what are the pick lists, do we have devliery notes too?
                DataView  dv         = _dvOutstandingPickList;
                DataTable dvUnpriced = new DataTable();
                DataTable dvPriced   = dv.ToTable();

                if (BLL.Settings.HandleGRV)
                {
                    if (BLL.Settings.IsCenter)
                    {
                        dv.RowFilter = "(Cost is null or Cost=0)";
                    }
                    else
                    {
                        dv.RowFilter = "DeliveryNote = true and (Cost is null or Cost=0)";
                    }
                    dvUnpriced = dv.ToTable();

                    dv.RowFilter = "Cost is not null and Cost <> 0";
                    dvPriced     = dv.ToTable();
                }
                else
                {
                    dvPriced = dv.ToTable();
                }

                string stvPrinterName      = "";
                string deliveryNotePrinter = "";

                if (!ConfirmPrinterSettings(dvPriced, dvUnpriced, out stvPrinterName, out deliveryNotePrinter))
                {
                    return;
                }
                bool saveSuccessful = false;

                MyGeneration.dOOdads.TransactionMgr mgr = MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgr();
                try
                {
                    if (dvPriced.Rows.Count == 0 && dvUnpriced.Rows.Count == 0)
                    {
                        throw new Exception("The Items doesn’t meet the requirement: please check the price status for non-delivery notes!");
                    }

                    mgr.BeginTransaction();

                    if (dvPriced.Rows.Count > 0)
                    {
                        STVReport = SaveAndPrintSTV(dvPriced.DefaultView, false, stvPrinterName, dtDate, dtCurrent);
                    }


                    if (dvUnpriced.Rows.Count > 0)
                    {
                        DeliveryNoteReport = SaveAndPrintSTV(dvUnpriced.DefaultView, true, deliveryNotePrinter, dtDate,
                                                             dtCurrent);
                    }
                    var ordr = new Order();
                    ordr.LoadByPrimaryKey(_orderID);

                    if (!ordr.IsColumnNull("OrderTypeID") &&

                        (ordr.OrderTypeID == BLL.OrderType.CONSTANTS.ACCOUNT_TO_ACCOUNT_TRANSFER || ordr.OrderTypeID == BLL.OrderType.CONSTANTS.STORE_TO_STORE_TRANSFER))
                    {
                        var      transfer         = new Transfer();
                        DateTime convertedEthDate = ConvertDate.DateConverter(dtDate.Text);
                        transfer.CommitAccountToAccountTransfer(ordr.ID, CurrentContext.UserId, convertedEthDate);
                    }

                    mgr.CommitTransaction();

                    saveSuccessful = true;
                }
                catch (Exception exp)
                {
                    mgr.RollbackTransaction();
                    //Removed the reset logic
                    //MyGeneration.dOOdads.TransactionMgr.ThreadTransactionMgrReset();
                    XtraMessageBox.Show(exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ErrorHandler.Handle(exp);
                    saveSuccessful = false;
                }

                if (saveSuccessful)
                {
                    if (STVReport != null)
                    {
                        if (InstitutionIType.IsVaccine(GeneralInfo.Current))
                        {
                            for (int i = 0; i < BLL.Settings.STVCopies; i++)
                            {
                                STVReport.Print(stvPrinterName);
                            }
                        }
                        else
                        {
                            STVReport.Print(stvPrinterName);
                        }
                    }

                    if (DeliveryNoteReport != null)
                    {
                        DeliveryNoteReport.Print(deliveryNotePrinter);
                    }

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

                btnConfirmIssue1.Enabled = (BLL.Settings.UseNewUserManagement && this.HasPermission("Print-Invoice")) ? true : (!BLL.Settings.UseNewUserManagement);
                BindOutstandingPicklists();
                gridOutstandingPicklistDetail.DataSource = null;
                PalletLocation.GarbageCollection();

                if (BLL.Settings.AllowOnlineOrders)
                {
                    Helpers.RRFServiceIntegration.SubmitOnlineIssue(_orderID);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inventory"></param>
        /// <param name="palletLocation">Please note that the pallet location passed here is going to be used for the sound qty.  A quarantine location in the physical store that the pallet location exists is chosen for the damaged location.  For now, we're using the same pallet location for the expired quantity as well. (Only if the location type is free)</param>
        /// <param name="confirmationStatusID"></param>
        /// <param name="receipt"></param>
        /// <param name="user"></param>
        /// <param name="convertedEthDate"></param>
        /// <param name="remark"></param>
        internal void CreateReceiveEntriesForInventory(Inventory inventory, PalletLocation palletLocation, int confirmationStatusID, Receipt receipt, User user, DateTime convertedEthDate, string remark)
        {
            //Now Save the receive doc entry
            decimal soundQty = inventory.IsColumnNull("InventorySoundQuantity") ? 0 : inventory.InventorySoundQuantity;
            decimal damagedQty = inventory.IsColumnNull("InventoryDamagedQuantity") ? 0 : inventory.InventoryDamagedQuantity;
            decimal expQty = inventory.IsColumnNull("InventoryExpiredQuantity") ? 0 : inventory.InventoryExpiredQuantity;

            //As per the design of the Inventory object, expired and sound cannot be passed using a single object: Why? There's a data memeber for Expiry Date which can only hold one value.
            decimal soundOrExpiredQty = soundQty + expQty;
            decimal totalFoundQty = soundOrExpiredQty + damagedQty;

            ReceiveDoc newReceiveDoc = CreateReceiveDocForInventory(inventory, confirmationStatusID, totalFoundQty,
                                                                    receipt.ID, convertedEthDate, user, remark);

            ReceivePallet newReceivePallet = new ReceivePallet();
            BLL.ItemUnit iu = new ItemUnit();
            iu.LoadByPrimaryKey(inventory.UnitID);

            if (soundOrExpiredQty > 0)
            {
                newReceivePallet.AddNew();
                newReceivePallet.ReceiveID = newReceiveDoc.ID;
                newReceivePallet.ReceivedQuantity = newReceivePallet.Balance = soundOrExpiredQty*iu.QtyPerUnit;
                newReceivePallet.ReservedStock = 0;
                newReceivePallet.PalletID = palletLocation.PalletID;
                newReceivePallet.PalletLocationID = palletLocation.ID;
            }

            if(damagedQty>0)
            {
                newReceivePallet.AddNew();
                newReceivePallet.ReceiveID = newReceiveDoc.ID;
                newReceivePallet.ReceivedQuantity = newReceivePallet.Balance = damagedQty*iu.QtyPerUnit;
                newReceivePallet.ReservedStock = 0;

                if(palletLocation.StorageTypeID==Convert.ToInt32(BLL.StorageType.Quaranteen)) //Was the original pallet stored in a quarantine location?
                {
                    newReceivePallet.PalletID = palletLocation.PalletID;
                    newReceivePallet.PalletLocationID = palletLocation.ID;
                }
                else //The original pallet was not marked as a quarantine or suspension location.  Meaning we need to choose a quarantine location in the same physical store as the original pallet location.
                {
                    BLL.PalletLocation plQuarantine = new PalletLocation();
                    plQuarantine.LoadFirstOrDefault(palletLocation.PhysicalStoreID,
                                                    Convert.ToInt32((StorageType.Quaranteen)));
                    if(plQuarantine.RowCount>0) //There is already quarantine location.
                    {
                        //Pick the first quarantine location.
                        if(plQuarantine.IsColumnNull("PalletID"))
                        {
                            //TODO: Create a Pallet.
                        }

                        newReceivePallet.PalletID = plQuarantine.PalletID;
                        newReceivePallet.PalletLocationID = plQuarantine.ID;
                    }
                    else
                    {
                        //There is no quarantine locaiton in the physical store: This is basically bad news.  We let them know that this is unacceptable.
                        throw new Exception("Please create a quarantine storage location for this store");
                    }
                }
            }
            newReceivePallet.IsOriginalReceive = true;
            newReceivePallet.Save();
        }
Esempio n. 17
0
        public CurrentStatus LoadCurrentInfo()
        {
            using (var cmd = _db.CreateCommand()) {
                var map    = new MakinoToJobMap(_logDb);
                var palMap = new MakinoToPalletMap();

                Load("SELECT PartID, ProcessNumber, ProcessID FROM " + dbo + "Processes", reader => {
                    map.AddProcess(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2));
                });

                //Makino: Parts   MachineWatch: Jobs
                Load("SELECT PartID, PartName, Revision, Comment, Priority FROM " + dbo + "Parts", reader => {
                    var partID = reader.GetInt32(0);

                    var partName = reader.GetString(1);
                    if (!reader.IsDBNull(2))
                    {
                        partName += reader.GetString(2);
                    }

                    var job = map.CreateJob(partName, partID);

                    job.JobCopiedToSystem = true;
                    job.PartName          = reader.GetString(1);
                    if (!reader.IsDBNull(3))
                    {
                        job.Comment = reader.GetString(3);
                    }
                    if (!reader.IsDBNull(4))
                    {
                        job.Priority = reader.GetInt16(4);
                    }
                    job.ManuallyCreatedJob = false;
                    job.CreateMarkerData   = false;
                });


                var devices = Devices();

                Load("SELECT ProcessID, JobNumber, JobID FROM " + dbo + "Jobs", reader => {
                    map.AddJobToProcess(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2));
                });

                Load("SELECT a.JobID, b.Name FROM " + dbo + "MachineJobs a " +
                     "INNER JOIN " + dbo + "NCProgramFiles b " +
                     "ON a.NCProgramFileID = b.NCProgramFileID", reader => {
                    map.AddProgramToJob(reader.GetInt32(0), reader.GetString(1));
                });

                Load("SELECT JobID, FeasibleDeviceID FROM " + dbo + "JobFeasibleDevices", reader => {
                    map.AddAllowedStationToJob(reader.GetInt32(0), devices[reader.GetInt32(1)]);
                });

                map.CompleteStations();

                Load("SELECT a.PalletFixtureID, a.FixtureNumber, a.FixtureID, b.PalletNumber, c.CurDeviceType, c.CurDeviceNumber " +
                     "FROM " + dbo + "PalletFixtures a, " + dbo + "Pallets b, " + dbo + "PalletLocation c " +
                     "WHERE a.PalletID = b.PalletID AND a.PalletID = c.PalletID " +
                     " AND a.FixtureID IS NOT NULL", reader => {
                    var loc = new PalletLocation(PalletLocationEnum.Buffer, "Unknown", 0);
                    if (!reader.IsDBNull(4) && !reader.IsDBNull(5))
                    {
                        loc = ParseDevice(reader.GetInt16(4), reader.GetInt16(5));
                    }

                    palMap.AddPalletInfo(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2),
                                         reader.GetInt32(3), loc);
                });

                Load("SELECT ProcessID, FixtureID FROM " + dbo + "FixtureProcesses", reader => {
                    map.AddFixtureToProcess(reader.GetInt32(0), reader.GetInt32(1),
                                            palMap.PalletsForFixture(reader.GetInt32(1)));
                });

                Load("SELECT OrderID, OrderName, PartID, Comment, Quantity, Priority, StartDate " +
                     "FROM " + dbo + "Orders", reader => {
                    var newJob = map.DuplicateForOrder(reader.GetInt32(0), reader.GetString(1), reader.GetInt32(2));

                    if (!reader.IsDBNull(3))
                    {
                        newJob.Comment = reader.GetString(3);
                    }

                    newJob.SetPlannedCyclesOnFirstProcess(1, reader.GetInt32(4));

                    if (!reader.IsDBNull(5))
                    {
                        newJob.Priority = reader.GetInt16(5);
                    }

                    DateTime start = DateTime.SpecifyKind(reader.GetDateTime(6), DateTimeKind.Local);
                    start          = start.ToUniversalTime();

                    for (int i = 1; i <= newJob.NumProcesses; i++)
                    {
                        newJob.SetSimulatedStartingTimeUTC(i, 1, start);
                    }
                });

                Load("SELECT OrderID, ProcessID, RemainingQuantity, NormalQuantity, ScrapQuantity " +
                     "FROM " + dbo + "Quantities", reader => {
                    map.AddQuantityToProcess(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(3));
                });

                Load("SELECT PalletFixtureID, CurProcessID, CurOrderID, CurJobID, WorkStatus " +
                     "FROM " + dbo + "FixtureRun WHERE CurProcessID IS NOT NULL", reader => {
                    int palfixID = reader.GetInt32(0);
                    int orderID  = reader.GetInt32(2);
                    var job      = map.JobForOrder(orderID);

                    string orderName = "";
                    if (job != null)
                    {
                        orderName = job.UniqueStr;
                    }

                    // Lookup (pallet,location) for this palfixID
                    int palletNum;
                    int fixtureNum;
                    palMap.PalletLocInfo(palfixID, out palletNum, out fixtureNum);

                    //look for material id
                    IList <StatusDB.MatIDRow> matIDs;
                    if (_status == null)
                    {
                        matIDs = new List <StatusDB.MatIDRow>();
                    }
                    else
                    {
                        matIDs = _status.FindMaterialIDs(palletNum, fixtureNum, DateTime.UtcNow.AddSeconds(10));
                    }

                    //check material ids share the same order
                    if (orderName != "")
                    {
                        foreach (var m in matIDs)
                        {
                            if (m.Order != orderName)
                            {
                                Log.Debug("Current material on pallet " + palletNum.ToString() +
                                          " loc " + fixtureNum.ToString() + " was expecting orderID " +
                                          orderID.ToString() + " for order " + orderName.ToString() +
                                          ", but found order " + m.Order + " for part loaded at " + m.LoadedUTC.ToString());
                                matIDs.Clear();
                                break;
                            }
                        }
                    }

                    if (matIDs.Count == 0)
                    {
                        var m   = default(StatusDB.MatIDRow);
                        m.MatID = -1;
                        matIDs.Add(m);
                    }

                    foreach (var m in matIDs)
                    {
                        var inProcMat =
                            map.CreateMaterial(
                                orderID, reader.GetInt32(1), reader.GetInt32(3), palletNum,
                                fixtureNum, m.MatID);

                        palMap.AddMaterial(palfixID, inProcMat);
                    }
                });

                //There is a MovePalletFixtureID column which presumebly means rotate through process?
                //Other columns include remachining, cancel, recleaning, offdutyprocess, operation status
                Load("SELECT PalletFixtureID, UnclampJobID, UnclampOrderID, ClampJobID, ClampOrderID, ClampQuantity " +
                     "FROM " + dbo + "WorkSetCommand WHERE PalletFixtureID IS NOT NULL", reader => {
                    var palfixID = reader.GetInt32(0);

                    if (!reader.IsDBNull(1) && !reader.IsDBNull(2))
                    {
                        var unclampJobID = reader.GetInt32(1);
                        var unclampOrder = reader.GetInt32(2);

                        var procNum = map.ProcessForJobID(unclampJobID);
                        var job     = map.JobForOrder(unclampOrder);
                        if (job != null)
                        {
                            palMap.SetMaterialAsUnload(palfixID, job.NumProcesses == procNum);
                        }
                    }

                    if (!reader.IsDBNull(3) && !reader.IsDBNull(4))
                    {
                        var clampJobID = reader.GetInt32(3);
                        var clampOrder = reader.GetInt32(4);

                        var procNum = map.ProcessForJobID(clampJobID);
                        var job     = map.JobForOrder(clampOrder);
                        int qty     = 1;
                        if (!reader.IsDBNull(5))
                        {
                            qty = reader.GetInt32(5);
                        }

                        if (job != null)
                        {
                            palMap.AddMaterialToLoad(palfixID, job.UniqueStr, job.PartName, procNum, qty);
                        }
                    }
                });

                //TODO: inspections (from jobdb), holds

                var st = new CurrentStatus();
                foreach (var j in map.Jobs)
                {
                    st.Jobs.Add(j.UniqueStr, j);
                }
                foreach (var p in palMap.Pallets)
                {
                    st.Pallets.Add(p);
                }
                foreach (var m in palMap.Material)
                {
                    st.Material.Add(m);
                }
                return(st);
            }
        }