Пример #1
0
        private void inventorySummaryFormNavAction(object sender, object data)
        {
            NavBox           inventorySummaryNavBox = (NavBox)sender;
            InventorySummary inventorySummaryForm   = (InventorySummary)data;

            NavBox.NavAction action = inventorySummaryNavBox.Action;
            if (action == NavBox.NavAction.BACKANDSUBMIT)
            {
                DesktopSession.HistorySession.Back();
                action = NavBox.NavAction.SUBMIT;
            }
            switch (action)
            {
            case NavBox.NavAction.SUBMIT:
                inventorySummaryForm.Hide();
                this.nextState = InventoryAuditFlowState.InventoryQuestions;
                break;

            case NavBox.NavAction.CANCEL:
                inventorySummaryForm.Hide();
                this.nextState = InventoryAuditFlowState.AuditManager;
                break;

            default:
                throw new ApplicationException("" + action.ToString() + " is not a valid state for InventorySummary");
            }

            this.executeNextState();
        }
Пример #2
0
        async Task <string> GenerateNo(InventorySummary model)
        {
            do
            {
                model.No = CodeGenerator.GenerateCode();
            }while (this.dbSet.Any(d => d.No.Equals(model.No)));

            return(model.No);
            //string Year = DateTimeOffset.Now.ToString("yy");
            //string Month = DateTimeOffset.Now.ToString("MM");


            //string no = $"SUM-{Year}-{Month}-{model.StorageCode}-";
            //int Padding = 7;

            //var lastNo = await this.dbSet.Where(w => w.No.StartsWith(no) && !w._IsDeleted).OrderByDescending(o => o.No).FirstOrDefaultAsync();

            //if (lastNo == null)
            //{
            //    return no + "1".PadLeft(Padding, '0');
            //}
            //else
            //{
            //    int lastNoNumber = Int32.Parse(lastNo.No.Replace(no, "")) + 1;
            //    return no + lastNoNumber.ToString().PadLeft(Padding, '0');
            //}
        }
Пример #3
0
 public DeliveryReceiptPdf(DeliveryDto receipt, InventorySummary inventorySummary, string fileNameDrTemplate)
     : base(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), PageSize.LETTER.Rotate())
 {
     deliveryReceipt       = receipt;
     fileNameTemplate      = fileNameDrTemplate;
     this.inventorySummary = inventorySummary;
 }
Пример #4
0
        public async Task <InventorySummary> GetTestData()
        {
            InventorySummary invSum = GetNewData();

            await _inventorySummaryRepository.Create(invSum);

            return(invSum);
        }
Пример #5
0
        public async Task <InventorySummary> GetTestData()
        {
            InventorySummary invSum = GetNewData();

            await Service.Create(invSum);

            return(invSum);
        }
Пример #6
0
        public async Task <int> Create(InventoryMovement model, string username)
        {
            int Created = 0;

            var internalTransaction = dbContext.Database.CurrentTransaction == null;
            var transaction         = !internalTransaction ? dbContext.Database.CurrentTransaction : dbContext.Database.BeginTransaction();

            try
            {
                model.No = await GenerateNo(model);

                model._CreatedAgent      = "Facade";
                model._CreatedBy         = username;
                model._LastModifiedAgent = "Facade";
                model._LastModifiedBy    = username;
                model._CreatedUtc        = DateTime.UtcNow;
                model._LastModifiedUtc   = DateTime.UtcNow;

                InventorySummaryFacade summary = new InventorySummaryFacade(this.serviceProvider, this.dbContext);

                this.dbSet.Add(model);
                Created = await dbContext.SaveChangesAsync();

                //var SumQty = this.dbSet.Where(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId).Sum(a => a.Quantity);
                var SumQty = this.dbSet.OrderByDescending(a => a._CreatedUtc).FirstOrDefault(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId);

                var SumStock = this.dbSet.Where(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId).Sum(a => a.StockPlanning);
                InventorySummary summaryModel = new InventorySummary
                {
                    ProductId     = model.ProductId,
                    ProductCode   = model.ProductCode,
                    ProductName   = model.ProductName,
                    UomId         = model.UomId,
                    UomUnit       = model.UomUnit,
                    StockPlanning = SumStock,
                    Quantity      = SumQty.After,
                    StorageId     = model.StorageId,
                    StorageCode   = model.StorageCode,
                    StorageName   = model.StorageName
                };
                await summary.Create(summaryModel, username);

                if (internalTransaction)
                {
                    transaction.Commit();
                }

                return(Created);
            }
            catch (Exception e)
            {
                if (internalTransaction)
                {
                    transaction.Rollback();
                }
                throw new Exception(e.Message);
            }
        }
        private string GenerateNo(InventorySummary model)
        {
            do
            {
                model.No = CodeGenerator.GenerateCode();
            }while (this._dbSet.Any(d => d.No.Equals(model.No)));

            return(model.No);
        }
Пример #8
0
        // GET: Inventory
        public ActionResult Index()
        {
            var form = new InventorySummary
            {
                ItemList =
                    _context.Items.ToListItems(t => (t.ItemCode + " - " + t.ItemName),
                                               v => v.ItemId.ToString(CultureInfo.InvariantCulture), "Please Select...")
            };

            return(View(form));
        }
Пример #9
0
        //Create InventoryAreaLogs associated with new Inventory Summary
        private void CreateInventoryAreaLogs(InventorySummary summary)
        {
            var areas = from a in _context.InventoryAreas.Include("ItemSlots.WildeRoverItem")
                        select a;

            foreach (var area in areas.ToList())
            {
                //Create area inventory log
                InventoryAreaInventoryLog log = new InventoryAreaInventoryLog();
                log.InventorySummary   = summary;
                log.InventorySummaryId = summary.InventorySummaryId;
                log.InventoryArea      = area;
                log.InventoryAreaid    = area.InventoryAreaId;
                log.Date = DateTime.Now;

                //Add to context and retrieve Id

                _context.InventoryAreaLogs.Add(log);
                _context.SaveChanges();

                log = _context.InventoryAreaLogs.Last();

                //populate the Inventory
                var items = from i in area.ItemSlots
                            orderby i.Slot ascending
                            select i.WildeRoverItem;

                foreach (var item in items)
                {
                    ItemCount temp = new ItemCount();
                    temp.InventoryAreaInventoryLog   = log;
                    temp.InventoryAreaInventoryLogId = log.InventoryAreaInventoryLogId;
                    temp.Item             = item;
                    temp.WildeRoverItemId = item.WildeRoverItemId;

                    _context.ItemCounts.Add(temp);

                    //Add ItemCount to area log
                    log.Inventory.Add(temp);
                }

                //Update log
                _context.InventoryAreaLogs.Update(log);

                //Add area inventory log to summary
                summary.InventoryAreaLogs.Add(log);
            }

            //Update summary
            _context.InventoryLog.Update(summary);

            //_context.SaveChanges();
        }
        public async Task <int> Create(InventoryMovement model)
        {
            int Created = 0;

            var internalTransaction = DbContext.Database.CurrentTransaction == null;
            var transaction         = !internalTransaction ? DbContext.Database.CurrentTransaction : DbContext.Database.BeginTransaction();

            try
            {
                model.No = GenerateNo(model);
                model.FlagForCreate(IdentityService.Username, UserAgent);
                model.FlagForUpdate(IdentityService.Username, UserAgent);
                IInventorySummaryService summary = ServiceProvider.GetService <IInventorySummaryService>();

                this.DbSet.Add(model);
                Created = await DbContext.SaveChangesAsync();

                //var SumQty = this.dbSet.Where(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId).Sum(a => a.Quantity);
                var SumQty = this.DbSet.OrderByDescending(a => a._CreatedUtc).FirstOrDefault(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId);

                var SumStock = this.DbSet.Where(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId).Sum(a => a.StockPlanning);
                InventorySummary summaryModel = new InventorySummary
                {
                    ProductId     = model.ProductId,
                    ProductCode   = model.ProductCode,
                    ProductName   = model.ProductName,
                    UomId         = model.UomId,
                    UomUnit       = model.UomUnit,
                    StockPlanning = SumStock,
                    Quantity      = SumQty.After,
                    StorageId     = model.StorageId,
                    StorageCode   = model.StorageCode,
                    StorageName   = model.StorageName
                };
                await summary.Create(summaryModel);

                if (internalTransaction)
                {
                    transaction.Commit();
                }

                return(Created);
            }
            catch (Exception e)
            {
                if (internalTransaction)
                {
                    transaction.Rollback();
                }
                throw new Exception(e.Message);
            }
        }
        public ShowForm CreateInventorySummaryShowBlock(
            Form parentForm,
            NavBox.NavBoxActionFired fxn)
        {
            var inventorySummary = new InventorySummary();

            return(this.createShowFormBlock(
                       ValidFormBlockTypes.None,
                       parentForm,
                       inventorySummary,
                       inventorySummary.NavControlBox,
                       fxn));
        }
Пример #12
0
        public async Task <int> Create(InventorySummary model, string username)
        {
            int Created             = 0;
            var internalTransaction = dbContext.Database.CurrentTransaction == null;
            var transaction         = !internalTransaction ? dbContext.Database.CurrentTransaction : dbContext.Database.BeginTransaction();

            try
            {
                var exist = this.dbSet.Where(a => a._IsDeleted == false && a.StorageId == model.StorageId && a.ProductId == model.ProductId && a.UomId == model.UomId).FirstOrDefault();

                if (exist == null)
                {
                    model.No = await GenerateNo(model);

                    model._CreatedAgent      = "Facade";
                    model._CreatedBy         = username;
                    model._LastModifiedAgent = "Facade";
                    model._LastModifiedBy    = username;
                    model._CreatedUtc        = DateTime.UtcNow;
                    model._LastModifiedUtc   = DateTime.UtcNow;

                    this.dbSet.Add(model);
                }
                else
                {
                    model._LastModifiedAgent = "Facade";
                    model._LastModifiedBy    = username;
                    model._LastModifiedUtc   = DateTime.UtcNow;

                    exist.Quantity      = model.Quantity;
                    exist.StockPlanning = model.StockPlanning;
                    this.dbSet.Update(exist);
                }
                Created = await dbContext.SaveChangesAsync();

                if (internalTransaction)
                {
                    transaction.Commit();
                }

                return(Created);
            }
            catch (Exception e)
            {
                if (internalTransaction)
                {
                    transaction.Rollback();
                }
                throw new Exception(e.Message);
            }
        }
        public async Task <int> Create(InventorySummary model)
        {
            int created             = 0;
            var internalTransaction = _inventoryDbContext.Database.CurrentTransaction == null;
            var transaction         = !internalTransaction
                                ? _inventoryDbContext.Database.CurrentTransaction
                                : _inventoryDbContext.Database.BeginTransaction();

            try
            {
                var exist = _dbSet.Where(a => a.IsDeleted == false && a.StorageId == model.StorageId &&
                                         a.ProductId == model.ProductId && a.UomId == model.UomId).FirstOrDefault();

                if (exist == null)
                {
                    model.No = GenerateNo(model);
                    model.FlagForCreate(_identityInterface.Username, UserAgent);
                    model.FlagForUpdate(_identityInterface.Username, UserAgent);

                    _dbSet.Add(model);
                }
                else
                {
                    model.FlagForUpdate(_identityInterface.Username, UserAgent);

                    exist.Quantity      = model.Quantity;
                    exist.StockPlanning = model.StockPlanning;
                    this._dbSet.Update(exist);
                }
                created = await _inventoryDbContext.SaveChangesAsync();

                if (internalTransaction)
                {
                    transaction.Commit();
                }

                return(created);
            }
            catch (Exception e)
            {
                if (internalTransaction)
                {
                    transaction.Rollback();
                }
                throw new Exception(e.Message);
            }
        }
        private void HandleNewSiteItem(SiteItem siteItem, EntityContext entityContext)
        {
            Site             site             = entityContext.Find <Site>(siteItem.NPI);
            InventorySummary inventorySummary = null;

            if (entityContext.InventorySummaries.ContainsKey(site))
            {
                inventorySummary = entityContext.InventorySummaries[site];
            }
            else
            {
                logger.LogInformation("No inventory site found.  Creating a new one.");
                inventorySummary = new InventorySummary();
                entityContext.InventorySummaries.Add(site, inventorySummary);
            }
            inventorySummary.AddSiteItem(siteItem);
        }
Пример #15
0
        private void InventorySummaryButton_Click(object sender, RoutedEventArgs e)
        {
            ICERSSystemServiceManager services = ServiceLocator.GetSystemServiceManager(DataRepository);

            try
            {
                int fsid = 0;
                fsid = Convert.ToInt32(ISFsidTB.Text);

                services.BusinessLogic.SubmittalElements.HazardousMaterialsInventory.InventorySummary.Summary(Convert.ToInt32(fsid));

                // all this was done in Summary but we need the information to get the output
                FacilitySubmittal        fs  = (from fsRec in DataRepository.DataModel.FacilitySubmittals where fsRec.ID == fsid select fsRec).FirstOrDefault();
                FacilitySubmittalElement fse =
                    (from fseRec in DataRepository.DataModel.FacilitySubmittalElements
                     where fseRec.FacilitySubmittal.ID == fs.ID && fseRec.Voided == false &&
                     fseRec.SubmittalElementID == (int)SubmittalElementType.HazardousMaterialsInventory
                     select fseRec).FirstOrDefault();
                FacilitySubmittalElementResource fser =
                    (from fserRec in DataRepository.DataModel.FacilitySubmittalElementResources
                     where fserRec.FacilitySubmittalElementID == fse.ID &&
                     fserRec.Voided == false && fserRec.ResourceTypeID == (int)ResourceType.HazardousMaterialInventory
                     select fserRec).FirstOrDefault();

                InventorySummary inventory = DataRepository.InventorySummaries.GetByFSERID(fser.ID);
                StringBuilder    results   = new StringBuilder();
                results.Append("Inventory Summary  FSE: " + fse.ID + " CERSID: " + fse.CERSID + "\n");

                results.Append("   Solid Material Count: " + inventory.SolidMaterialCount + " EHS Count: " +
                               inventory.SolidEHSCount + " Maximum Daily Value: " + inventory.SolidMaximumDailyValue + " pounds\n");
                results.Append("   Liquid Material Count: " + inventory.LiquidMaterialCount + " EHS Count: " +
                               inventory.LiquidEHSCount + " Maximum Daily Value: " + inventory.LiquidMaximumDailyValue + " gallons\n");
                results.Append("   Gas Material Count: " + inventory.GasMaterialCount + " EHS Count: " +
                               inventory.GasEHSCount + " Maximum Daily Value: " + inventory.GasMaximumDailyValue + " cubic feet\n");
                results.Append("   Unique Location Count: " + inventory.UniqueLocationCount + "\n");

                this.OutputTB.Text = results.ToString();
            }
            catch (Exception ex)
            {
                this.OutputTB.Text = "Error: " + ex.Message;
            }
        }
Пример #16
0
        public ActionResult <InventorySummary> GetInventorySummary(string npi)
        {
            logger.LogDebug("Inventory summary request for {0}", npi);
            logger.LogTrace("Total number of inventory summary details: {0}", entityContext.InventorySummaries.Count);
            Site             site = entityContext.Find <Site>(npi);
            InventorySummary inventorySummaryDetails;

            if (entityContext.InventorySummaries.ContainsKey(site))
            {
                logger.LogDebug("Found Inventory Summary Detail.");
                inventorySummaryDetails = entityContext.InventorySummaries[site];
            }
            else
            {
                logger.LogDebug("No Inventory Summary Detail for site.");
                inventorySummaryDetails = new InventorySummary();
            }
            return(Ok(inventorySummaryDetails));
        }
        async Task <string> GenerateNo(InventorySummary model)
        {
            string Year  = DateTimeOffset.Now.ToString("yy");
            string Month = DateTimeOffset.Now.ToString("MM");


            string no      = $"SUM-{Year}-{Month}-{model.StorageCode}-";
            int    Padding = 7;

            var lastNo = await this.dbSet.Where(w => w.No.StartsWith(no) && !w._IsDeleted).OrderByDescending(o => o.No).FirstOrDefaultAsync();

            if (lastNo == null)
            {
                return(no + "1".PadLeft(Padding, '0'));
            }
            else
            {
                int lastNoNumber = Int32.Parse(lastNo.No.Replace(no, "")) + 1;
                return(no + lastNoNumber.ToString().PadLeft(Padding, '0'));
            }
        }
Пример #18
0
        public InventorySummary MapToModel(InventorySummaryViewModel viewModel)
        {
            var model = new InventorySummary()
            {
                No            = viewModel.code,
                ProductId     = viewModel.productId,
                ProductCode   = viewModel.productCode,
                ProductName   = viewModel.productName,
                UomId         = viewModel.uomId,
                UomUnit       = viewModel.uom,
                StorageId     = viewModel.storageId,
                StorageCode   = viewModel.storageCode,
                StorageName   = viewModel.storageName,
                StockPlanning = double.Parse(viewModel.stockPlanning),
                Quantity      = viewModel.quantity
            };

            PropertyCopier <InventorySummaryViewModel, InventorySummary> .Copy(viewModel, model);

            return(model);
        }
Пример #19
0
        public InventorySummaryViewModel MapToViewModel(InventorySummary model)
        {
            var viewModel = new InventorySummaryViewModel()
            {
                code          = model.No,
                productId     = model.ProductId,
                productCode   = model.ProductCode,
                productName   = model.ProductName,
                uomId         = model.UomId,
                uom           = model.UomUnit,
                storageId     = model.StorageId,
                storageCode   = model.StorageCode,
                storageName   = model.StorageName,
                stockPlanning = model.StockPlanning.ToString(),
                quantity      = model.Quantity
            };

            PropertyCopier <InventorySummary, InventorySummaryViewModel> .Copy(model, viewModel);

            return(viewModel);
        }
Пример #20
0
        public InventoryController(WildeRoverMgmtAppContext context, UserManager <User> userManager)
        {
            _userManager = userManager;
            _context     = context;

            //Get latest inventory summary if it exists
            var current = (from i in _context.InventoryLog.Include("InventoryAreaLogs.Inventory.Item")
                           orderby i.Date descending
                           select i).FirstOrDefault();

            //No inventory log created for the day
            if (current == null || current.Submitted)
            {
                _summary           = new InventorySummary();
                _summary.Date      = DateTime.Now;
                _summary.Submitted = false;

                _context.InventoryLog.Add(_summary);
                _context.SaveChanges();

                _summary = (from i in _context.InventoryLog.Include("InventoryAreaLogs.Inventory.Item")
                            orderby i.Date descending
                            select i).FirstOrDefault();

                _context.InventoryLog.Update(_summary);


                CreateInventoryAreaLogs(_summary);

                _context.SaveChanges();
            }

            else  //Log exists
            {
                _summary = current;
            }
        }
Пример #21
0
        private object executorFxn(object inputData)
        {
            if (inputData == null)
            {
                inputData = suspendedState;
            }
            InventoryAuditFlowState inputState = (InventoryAuditFlowState)inputData;

            Form currForm;

            switch (inputState)
            {
            case InventoryAuditFlowState.SelectAudit:
                SelectAudit selectAudit = new SelectAudit();
                currForm = DesktopSession.HistorySession.Lookup(selectAudit);
                if (currForm.GetType() == typeof(SelectAudit))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm selectAuditBlk = CommonAppBlocks.Instance.CreateSelectAuditShowBlock(this.parentForm, this.selectAuditFormNavAction);
                    if (!selectAuditBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Select Audit block");
                    }
                }

                break;

            case InventoryAuditFlowState.SelectStore:
                SelectStore selectStore = new SelectStore();
                currForm = DesktopSession.HistorySession.Lookup(selectStore);
                if (currForm.GetType() == typeof(SelectStore))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm selectStoreBlk = CommonAppBlocks.Instance.CreateSelectStoreShowBlock(this.parentForm, this.selectStoreFormNavAction);
                    if (!selectStoreBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Select Store block");
                    }
                }

                break;

            case InventoryAuditFlowState.InitiateAudit:
                InitiateAudit initiateAudit = new InitiateAudit();
                currForm = DesktopSession.HistorySession.Lookup(initiateAudit);
                if (currForm.GetType() == typeof(InitiateAudit))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm initiateAuditBlk = CommonAppBlocks.Instance.CreateInitiateAuditShowBlock(this.parentForm, this.initiateAuditFormNavAction);
                    if (!initiateAuditBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Initiate Audit block");
                    }
                }

                break;

            case InventoryAuditFlowState.AuditManager:
                AuditManager auditManager = new AuditManager();
                currForm = DesktopSession.HistorySession.Lookup(auditManager);
                if (currForm.GetType() == typeof(AuditManager))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm auditManagerBlk = CommonAppBlocks.Instance.CreateAuditManagerShowBlock(this.parentForm, this.auditManagerFormNavAction);
                    if (!auditManagerBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Audit Manager block");
                    }
                }

                break;

            case InventoryAuditFlowState.InventorySummary:
                InventorySummary inventorySummary = new InventorySummary();
                currForm = DesktopSession.HistorySession.Lookup(inventorySummary);

                ShowForm inventorySummaryBlk = CommonAppBlocks.Instance.CreateInventorySummaryShowBlock(this.parentForm, this.inventorySummaryFormNavAction);
                if (!inventorySummaryBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Inventory Summary block");
                }


                break;

            case InventoryAuditFlowState.InventoryQuestions:
                InventoryQuestions inventoryQuestions = new InventoryQuestions();
                currForm = DesktopSession.HistorySession.Lookup(inventoryQuestions);
                if (currForm.GetType() == typeof(InventoryQuestions))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm inventoryQuestionsBlk = CommonAppBlocks.Instance.CreateInventoryQuestionsShowBlock(this.parentForm, this.inventoryQuestionsFormNavAction);
                    if (!inventoryQuestionsBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Inventory Questions block");
                    }
                }

                break;

            case InventoryAuditFlowState.DownloadToTrakker:
                //DownloadToTrakker downloadToTrakker = new DownloadToTrakker();
                //currForm = DesktopSession.HistorySession.Lookup(downloadToTrakker);
                //if (currForm.GetType() == typeof(DownloadToTrakker))
                //{
                //    currForm.Show();
                //}
                //else
                //{
                ShowForm downloadToTrakkerBlk = CommonAppBlocks.Instance.CreateDownloadToTrakkerShowBlock(this.parentForm, this.downloadToTrakkerFormNavAction);
                if (!downloadToTrakkerBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Download to Trakker block");
                }
                //}

                break;

            case InventoryAuditFlowState.UploadFromTrakker:
                //UploadFromTrakker uploadFromTrakker = new UploadFromTrakker();
                //currForm = DesktopSession.HistorySession.Lookup(uploadFromTrakker);
                //if (currForm.GetType() == typeof(DownloadToTrakker))
                //{
                //    currForm.Show();
                //}
                //else
                //{
                ShowForm uploadFromTrakkerBlk = CommonAppBlocks.Instance.CreateUploadFromTrakkerShowBlock(this.parentForm, this.uploadFromTrakkerFormNavAction);
                if (!uploadFromTrakkerBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Upload from Trakker block");
                }
                //}

                break;

            case InventoryAuditFlowState.ProcessMissing:
                //ProcessMissingItems processMissingItems = new ProcessMissingItems();
                //currForm = DesktopSession.HistorySession.Lookup(processMissingItems);
                //if (currForm.GetType() == typeof(ProcessMissingItems))
                //{
                //    currForm.Show();
                //}
                //else
                //{
                ShowForm processMissingItemsBlk = CommonAppBlocks.Instance.CreateProcessMissingItemsShowBlock(this.parentForm, this.processMissingItemsFormNavAction);
                if (!processMissingItemsBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Process Missing Items block");
                }
                //}

                break;

            case InventoryAuditFlowState.ProcessUnexpected:
                //ProcessUnexpectedItems processUnexpectedItems = new ProcessUnexpectedItems();
                //currForm = DesktopSession.HistorySession.Lookup(processUnexpectedItems);
                //if (currForm.GetType() == typeof(ProcessUnexpectedItems))
                //{
                //    currForm.Show();
                //}
                //else
                //{
                ShowForm processUnexpectedItemsBlk = CommonAppBlocks.Instance.CreateProcessUnexpectedItemsShowBlock(this.parentForm, this.processUnexpectedItemsFormNavAction);
                if (!processUnexpectedItemsBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Process Unexpected Items block");
                }
                //}

                break;

            case InventoryAuditFlowState.CountCACC:
                EnterCaccItems enterCaccItems = new EnterCaccItems();
                currForm = DesktopSession.HistorySession.Lookup(enterCaccItems);
                if (currForm.GetType() == typeof(EnterCaccItems))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm enterCaccItemsBlk = CommonAppBlocks.Instance.CreateEnterCaccItemsShowBlock(this.parentForm, this.enterCaccItemsFormNavAction);
                    if (!enterCaccItemsBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Enter Cacc Items block");
                    }
                }

                break;

            case InventoryAuditFlowState.AuditResults:
                ClosedAudit closedAudit = new ClosedAudit();
                currForm = DesktopSession.HistorySession.Lookup(closedAudit);
                if (currForm.GetType() == typeof(ClosedAudit))
                {
                    currForm.Show();
                }
                else
                {
                    ShowForm closedAuditBlk = CommonAppBlocks.Instance.CreateClosedAuditShowBlock(this.parentForm, this.closedAuditFormNavAction);
                    if (!closedAuditBlk.execute())
                    {
                        throw new ApplicationException("Cannot execute Closed Audit block");
                    }
                }

                break;

            case InventoryAuditFlowState.ChargeOn:
                ShowForm describeMerchBlk = CommonAppBlocks.Instance.DescribeMerchChargeOnBlock(this.parentForm, this.describeMerchFormAction, DesktopSession);
                if (!describeMerchBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Describe Merchandise Block");
                }
                break;

            case InventoryAuditFlowState.DescribeItem:
                ShowForm describeItemBlk = CommonAppBlocks.Instance.DescribeItemBlock(this.parentForm, this.describeItemFormAction, DesktopSession);
                if (!describeItemBlk.execute())
                {
                    throw new ApplicationException("Cannot execute Describe Item Block");
                }
                break;

            case InventoryAuditFlowState.CancelFlow:
                AuditDesktopSession.Instance.ClearLoggedInUser();
                if (this.endStateNotifier != null)
                {
                    this.endStateNotifier.execute();
                }
                break;

            case InventoryAuditFlowState.ExitFlow:
                AuditDesktopSession.Instance.ClearLoggedInUser();
                break;

            default:
                throw new ApplicationException("Invalid inventory audit flow state");
            }

            return(true);
        }
Пример #22
0
        public void GetInventoryReport(InventoryReportRequest inventoryReportRequest)
        {
            DateTime endDate   = DateTime.UtcNow.Date;
            DateTime beginDate = endDate.AddDays(-inventoryReportRequest.DaysOrderAndInventoryHistoryToUse);

            // Find products that are associated with this manufacturer.
            Task <List <Product> >          productsTask           = Task.Factory.StartNew(() => m_amazonMwSdbService.GetProductsForManufacturer(inventoryReportRequest.ManufacturerId));
            Task <List <OrderSummary> >     ordersTask             = Task.Factory.StartNew(() => m_amazonMwSdbService.GetOrderSummaryForManufacturer(inventoryReportRequest.ManufacturerId, beginDate, endDate));
            Task <List <InventorySummary> > inventoryHistoriesTask = Task.Factory.StartNew(() => m_amazonMwSdbService.GetInventorySummaryForManufacturer(inventoryReportRequest.ManufacturerId, beginDate, endDate));

            Task.WaitAll(new Task[] { productsTask, ordersTask, inventoryHistoriesTask });

            List <Product> products = productsTask.Result
                                      .Where(w => w.ASIN != null)
                                      .ToList();

            Dictionary <string, LookupProductResponse> lookupProductResponses = products
                                                                                .Select(s => new
            {
                s.ASIN,
                LookupProductResponse = m_productAdvertisingApi.LookupProduct(new LookupProductRequest
                {
                    ItemId        = s.ASIN,
                    IdType        = IdType.ASIN,
                    ResponseGroup = ResponseGroup.Medium
                })
            })
                                                                                .ToDictionary(k => k.ASIN, v => v.LookupProductResponse);

            Dictionary <string, OrderSummary> groupedOrders = ordersTask.Result
                                                              .GroupBy(g => g.ASIN)
                                                              .ToDictionary(k => k.Key, v => v.Single());

            Dictionary <string, InventorySummary> inventorySummaries = inventoryHistoriesTask.Result
                                                                       .ToDictionary(k => k.ASIN, v => v);

            List <InventoryReportLine> inventoryReportLines = products.Select(
                s =>
            {
                InventoryReportLine inventoryReportLine = new InventoryReportLine
                {
                    Name           = s.Name,
                    ItemNumber     = s.ItemNumber,
                    ASIN           = s.ASIN,
                    SKU            = s.SKU,
                    Cost           = s.Cost,
                    QuantityInCase = s.QuantityInCase
                };

                if (s.ASIN != null)
                {
                    InventorySummary inventorySummary = null;
                    OrderSummary orderSummary         = null;

                    if (inventorySummaries.ContainsKey(s.ASIN))
                    {
                        inventorySummary = inventorySummaries[s.ASIN];

                        inventoryReportLine.CurrentAfnFulfillableQuantity = inventorySummary.CurrentAfnFulfillableQuantity;
                        inventoryReportLine.DaysInStockDuringTimeframe    = inventorySummary.DaysInStockDuringTimeframe;
                    }

                    if (groupedOrders.ContainsKey(s.ASIN))
                    {
                        orderSummary = groupedOrders[s.ASIN];

                        inventoryReportLine.QuantitySoldTimeframe       = orderSummary.TotalQuantity;
                        inventoryReportLine.TotalExtensionSoldTimeframe = orderSummary.TotalExtension;
                    }

                    if (inventorySummary != null && orderSummary != null)
                    {
                        int currentAfnFulfillableQuantity = inventorySummary.CurrentAfnFulfillableQuantity;

                        decimal quantitySoldPerDayInStock = inventorySummary.DaysInStockDuringTimeframe > 0
                                                                ? orderSummary.TotalQuantity / inventorySummary.DaysInStockDuringTimeframe
                                                                : 0;

                        inventoryReportLine.QuantitySoldPerDayInStock = Math.Round(quantitySoldPerDayInStock, 2);

                        int recommendedReorderQuantity = (int)Math.Round((quantitySoldPerDayInStock * (inventoryReportRequest.DaysToReorder + inventoryReportRequest.DaysLeadTime) - currentAfnFulfillableQuantity), 0);

                        inventoryReportLine.RecommendedReorderQuantity = recommendedReorderQuantity > 0
                                                                ? recommendedReorderQuantity
                                                                : 0;
                    }

                    LookupProductResponse lookupProductResponse = lookupProductResponses[s.ASIN];

                    if (lookupProductResponse != null && lookupProductResponse.ProductMetadata != null)
                    {
                        inventoryReportLine.SellersRank = lookupProductResponse.ProductMetadata.SalesRank;
                    }
                }

                return(inventoryReportLine);
            }).ToList();

            string fileName = string.Format("{0}_InventoryReport_{1}", inventoryReportRequest.ManufacturerName, DateTime.UtcNow.ToShortDateString());

            ExcelUtility.WriteExcelFileToResponse(Response, inventoryReportLines.OrderByDescending(o => o.CurrentAfnFulfillableQuantity), c_worksheet1Name, fileName);
        }