Esempio n. 1
0
        public IList <GoodsInRouteListResultToDivide> AllGoodsLoadedDivided(IUnitOfWork uow, RouteList routeList, CarLoadDocument excludeDoc = null)
        {
            CarLoadDocument                docAlias      = null;
            CarLoadDocumentItem            docItemsAlias = null;
            GoodsInRouteListResultToDivide inCarLoads    = null;

            var loadedQuery = uow.Session.QueryOver <CarLoadDocument>(() => docAlias)
                              .Where(d => d.RouteList.Id == routeList.Id);

            if (excludeDoc != null)
            {
                loadedQuery.Where(d => d.Id != excludeDoc.Id);
            }

            var loadedlist = loadedQuery
                             .JoinAlias(d => d.Items, () => docItemsAlias)
                             .SelectList(list => list
                                         .SelectGroup(() => docItemsAlias.Nomenclature.Id).WithAlias(() => inCarLoads.NomenclatureId)
                                         .SelectSum(() => docItemsAlias.Amount).WithAlias(() => inCarLoads.Amount)
                                         .SelectGroup(() => docItemsAlias.ExpireDatePercent).WithAlias(() => inCarLoads.ExpireDatePercent)
                                         .SelectGroup(() => docItemsAlias.OwnType).WithAlias(() => inCarLoads.OwnType)
                                         ).TransformUsing(Transformers.AliasToBean <GoodsInRouteListResultToDivide>())
                             .List <GoodsInRouteListResultToDivide>();

            return(loadedlist);
        }
Esempio n. 2
0
        public decimal LoadedTerminalAmount(IUnitOfWork uow, int routelistId, int terminalId)
        {
            CarLoadDocument     carLoadDocumentAlias     = null;
            CarLoadDocumentItem carLoadDocumentItemAlias = null;

            var query = uow.Session.QueryOver(() => carLoadDocumentAlias)
                        .JoinAlias(c => c.Items, () => carLoadDocumentItemAlias)
                        .Where(() => carLoadDocumentAlias.RouteList.Id == routelistId)
                        .And(() => carLoadDocumentItemAlias.Nomenclature.Id == terminalId)
                        .Select(Projections.Sum(() => carLoadDocumentItemAlias.Amount))
                        .SingleOrDefault <decimal>();

            return(query);
        }
        private void FillCarLoadDocument(CarLoadDocument document, IUnitOfWork uow, int routeListId, int warehouseId)
        {
            var currentEmployee = _employeeRepository.GetEmployeeForCurrentUser(uow);

            document.RouteList      = uow.GetById <RouteList>(routeListId);
            document.Author         = currentEmployee;
            document.LastEditor     = currentEmployee;
            document.LastEditedTime = DateTime.Now;
            document.Warehouse      = uow.GetById <Warehouse>(warehouseId);

            document.FillFromRouteList(uow, _routeListRepository, _subdivisionRepository, true);
            document.UpdateAlreadyLoaded(uow, _routeListRepository);
            document.UpdateStockAmount(uow, _stockRepository);
            document.UpdateAmounts();
        }
        private void SendToLoadingAndPrint(RouteListJournalNode selectedNode, Warehouse warehouse)
        {
            using (var localUow = UnitOfWorkFactory.CreateWithoutRoot())
            {
                var routeList = localUow.GetById <RouteList>(selectedNode.Id);
                routeList.ChangeStatusAndCreateTask(RouteListStatus.InLoading, _callTaskWorker);

                var carLoadDocument = new CarLoadDocument();
                FillCarLoadDocument(carLoadDocument, localUow, routeList.Id, warehouse.Id);

                var routeListFullyShipped = routeList.ShipIfCan(localUow, _callTaskWorker, out var notLoadedGoods, carLoadDocument);
                localUow.Save(routeList);

                //Не погружен остался только терминал
                var routeListShippedWithoutTerminal = notLoadedGoods.Count == 1 &&
                                                      notLoadedGoods.All(x => x.NomenclatureId == _terminalNomenclatureProvider.GetNomenclatureIdForTerminal);

                var valid = commonServices.ValidationService.Validate(carLoadDocument, showValidationResults: false);

                if ((routeListFullyShipped || routeListShippedWithoutTerminal) && valid)
                {
                    carLoadDocument.ClearItemsFromZero();
                    carLoadDocument.UpdateOperations(localUow);

                    if (!carLoadDocument.Items.Any())
                    {
                        localUow.Commit();
                        return;
                    }

                    localUow.Save(carLoadDocument);
                    localUow.Commit();

                    if (routeListShippedWithoutTerminal)
                    {
                        commonServices.InteractiveService.ShowMessage(ImportanceLevel.Info,
                                                                      "Водителю необходимо получить терминал на кассе");
                    }

                    var reportInfo = new ReportInfo
                    {
                        Title      = carLoadDocument.Title,
                        Identifier = "Store.CarLoadDocument",
                        Parameters = new Dictionary <string, object> {
                            { "id", carLoadDocument.Id }
                        },
                        PrintType = ReportInfo.PrintingType.MultiplePrinters
                    };

                    _reportPrinter.Print(reportInfo);
                }
                else
                {
                    localUow.Commit();
                    commonServices.InteractiveService.ShowMessage(ImportanceLevel.Warning,
                                                                  "Не удалось автоматически отгрузить Маршрутный лист");

                    var dlg = new CarLoadDocumentDlg();
                    FillCarLoadDocument(dlg.Entity, dlg.UoW, routeList.Id, warehouse.Id);
                    TabParent.OpenTab(() => dlg);
                }
            }
        }
Esempio n. 5
0
        public override void UpdateNodes()
        {
            IncomingInvoice              invoiceAlias          = null;
            IncomingWater                waterAlias            = null;
            MovementDocument             movementAlias         = null;
            WriteoffDocument             writeoffAlias         = null;
            InventoryDocument            inventoryAlias        = null;
            ShiftChangeWarehouseDocument shiftchangeAlias      = null;
            SelfDeliveryDocument         selfDeliveryAlias     = null;
            RegradingOfGoodsDocument     regradingOfGoodsAlias = null;
            DocumentVMNode               resultAlias           = null;
            Counterparty  counterpartyAlias       = null;
            Counterparty  secondCounterpartyAlias = null;
            Warehouse     warehouseAlias          = null;
            Warehouse     secondWarehouseAlias    = null;
            MovementWagon wagonAlias = null;

            Nomenclature productAlias = null;

            CarLoadDocument   loadCarAlias   = null;
            CarUnloadDocument unloadCarAlias = null;
            RouteList         routeListAlias = null;
            Car      carAlias        = null;
            Employee driverAlias     = null;
            Employee authorAlias     = null;
            Employee lastEditorAlias = null;

            Domain.Orders.Order orderAlias = null;

            List <DocumentVMNode> result = new List <DocumentVMNode> ();

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.IncomingInvoice) && Filter.RestrictDriver == null)
            {
                var invoiceQuery = UoW.Session.QueryOver <IncomingInvoice>(() => invoiceAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    invoiceQuery.Where(x => x.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    invoiceQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    invoiceQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var invoiceList = invoiceQuery.JoinQueryOver(() => invoiceAlias.Contractor, () => counterpartyAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .JoinQueryOver(() => invoiceAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .JoinAlias(() => invoiceAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .JoinAlias(() => invoiceAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .SelectList(list => list
                                              .Select(() => invoiceAlias.Id).WithAlias(() => resultAlias.Id)
                                              .Select(() => invoiceAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                              .Select(() => invoiceAlias.Comment).WithAlias(() => resultAlias.Comment)
                                              .Select(() => DocumentType.IncomingInvoice).WithAlias(() => resultAlias.DocTypeEnum)
                                              .Select(Projections.Conditional(
                                                          Restrictions.Where(() => counterpartyAlias.Name == null),
                                                          Projections.Constant("Не указан", NHibernateUtil.String),
                                                          Projections.Property(() => counterpartyAlias.Name)))
                                              .WithAlias(() => resultAlias.Counterparty)
                                              .Select(Projections.Conditional(
                                                          Restrictions.Where(() => warehouseAlias.Name == null),
                                                          Projections.Constant("Не указан", NHibernateUtil.String),
                                                          Projections.Property(() => warehouseAlias.Name)))
                                              .WithAlias(() => resultAlias.Warehouse)
                                              .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                              .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                              .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                              .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                              .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                              .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                              .Select(() => invoiceAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime)
                                              )
                                  .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                  .List <DocumentVMNode> ();

                result.AddRange(invoiceList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.IncomingWater) && Filter.RestrictDriver == null)
            {
                var waterQuery = UoW.Session.QueryOver <IncomingWater>(() => waterAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    waterQuery.Where(x => x.IncomingWarehouse.Id == Filter.RestrictWarehouse.Id || x.WriteOffWarehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    waterQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    waterQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var waterList = waterQuery
                                .JoinQueryOver(() => waterAlias.IncomingWarehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                .JoinAlias(() => waterAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                .JoinAlias(() => waterAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                .Left.JoinAlias(() => waterAlias.Product, () => productAlias)
                                .SelectList(list => list
                                            .Select(() => waterAlias.Id).WithAlias(() => resultAlias.Id)
                                            .Select(() => waterAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                            .Select(() => DocumentType.IncomingWater).WithAlias(() => resultAlias.DocTypeEnum)
                                            .Select(Projections.Conditional(
                                                        Restrictions.Where(() => warehouseAlias.Name == null),
                                                        Projections.Constant("Не указан", NHibernateUtil.String),
                                                        Projections.Property(() => warehouseAlias.Name)))
                                            .WithAlias(() => resultAlias.Warehouse)
                                            .Select(() => productAlias.Name).WithAlias(() => resultAlias.ProductName)
                                            .Select(() => waterAlias.Amount).WithAlias(() => resultAlias.Amount)
                                            .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                            .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                            .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                            .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                            .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                            .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                            .Select(() => waterAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                .List <DocumentVMNode> ();

                result.AddRange(waterList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.MovementDocument) && Filter.RestrictDriver == null)
            {
                var movementQuery = UoW.Session.QueryOver <MovementDocument>(() => movementAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    movementQuery.Where(x => x.FromWarehouse.Id == Filter.RestrictWarehouse.Id || x.ToWarehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    movementQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    movementQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }
                if (Filter.RestrictMovementStatus.HasValue && Filter.RestrictDocumentType == DocumentType.MovementDocument)
                {
                    movementQuery.Where(o => o.Status == Filter.RestrictMovementStatus.Value);
                }

                var movementList = movementQuery
                                   .JoinQueryOver(() => movementAlias.FromWarehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinQueryOver(() => movementAlias.ToWarehouse, () => secondWarehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinAlias(() => movementAlias.MovementWagon, () => wagonAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinAlias(() => movementAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinAlias(() => movementAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .SelectList(list => list
                                               .Select(() => movementAlias.Id).WithAlias(() => resultAlias.Id)
                                               .Select(() => movementAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                               .Select(() => DocumentType.MovementDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                               .Select(() => movementAlias.Status).WithAlias(() => resultAlias.MovementDocumentStatus)
                                               .Select(() => movementAlias.HasDiscrepancy).WithAlias(() => resultAlias.MovementDocumentDiscrepancy)
                                               .Select(() => wagonAlias.Name).WithAlias(() => resultAlias.CarNumber)
                                               .Select(Projections.Conditional(
                                                           Restrictions.Where(() => warehouseAlias.Name == null),
                                                           Projections.Constant("Не указан", NHibernateUtil.String),
                                                           Projections.Property(() => warehouseAlias.Name)))
                                               .WithAlias(() => resultAlias.Warehouse)
                                               .Select(Projections.Conditional(
                                                           Restrictions.Where(() => secondWarehouseAlias.Name == null),
                                                           Projections.Constant("Не указан", NHibernateUtil.String),
                                                           Projections.Property(() => secondWarehouseAlias.Name)))
                                               .WithAlias(() => resultAlias.SecondWarehouse)
                                               .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                               .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                               .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                               .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                               .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                               .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                               .Select(() => movementAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                   .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                   .List <DocumentVMNode> ();

                result.AddRange(movementList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.WriteoffDocument) && Filter.RestrictDriver == null)
            {
                var writeoffQuery = UoW.Session.QueryOver <WriteoffDocument>(() => writeoffAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    writeoffQuery.Where(x => x.WriteoffWarehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    writeoffQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    writeoffQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var writeoffList = writeoffQuery
                                   .JoinQueryOver(() => writeoffAlias.Client, () => counterpartyAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinQueryOver(() => writeoffAlias.WriteoffWarehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinAlias(() => writeoffAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinAlias(() => writeoffAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .SelectList(list => list
                                               .Select(() => writeoffAlias.Id).WithAlias(() => resultAlias.Id)
                                               .Select(() => writeoffAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                               .Select(() => DocumentType.WriteoffDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                               .Select(Projections.Conditional(
                                                           Restrictions.Where(() => counterpartyAlias.Name == null),
                                                           Projections.Constant(string.Empty, NHibernateUtil.String),
                                                           Projections.Property(() => counterpartyAlias.Name)))
                                               .WithAlias(() => resultAlias.Counterparty)
                                               .Select(Projections.Conditional(
                                                           Restrictions.Where(() => warehouseAlias.Name == null),
                                                           Projections.Constant(string.Empty, NHibernateUtil.String),
                                                           Projections.Property(() => warehouseAlias.Name)))
                                               .WithAlias(() => resultAlias.Warehouse)
                                               .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                               .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                               .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                               .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                               .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                               .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                               .Select(() => writeoffAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                   .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                   .List <DocumentVMNode> ();

                result.AddRange(writeoffList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.InventoryDocument) && Filter.RestrictDriver == null)
            {
                var inventoryQuery = UoW.Session.QueryOver <InventoryDocument>(() => inventoryAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    inventoryQuery.Where(x => x.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    inventoryQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    inventoryQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var inventoryList = inventoryQuery
                                    .JoinQueryOver(() => inventoryAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                    .JoinAlias(() => inventoryAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                    .JoinAlias(() => inventoryAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                    .SelectList(list => list
                                                .Select(() => inventoryAlias.Id).WithAlias(() => resultAlias.Id)
                                                .Select(() => inventoryAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                                .Select(() => DocumentType.InventoryDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                                .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                                .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                                .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                                .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                                .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                                .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                                .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                                .Select(() => inventoryAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                    .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                    .List <DocumentVMNode> ();

                result.AddRange(inventoryList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.ShiftChangeDocument) && Filter.RestrictDriver == null)
            {
                var shiftchangeQuery = UoW.Session.QueryOver <ShiftChangeWarehouseDocument>(() => shiftchangeAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    shiftchangeQuery.Where(x => x.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    shiftchangeQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    shiftchangeQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var shiftchangeList = shiftchangeQuery
                                      .JoinQueryOver(() => shiftchangeAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                      .JoinAlias(() => shiftchangeAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                      .JoinAlias(() => shiftchangeAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                      .SelectList(list => list
                                                  .Select(() => shiftchangeAlias.Id).WithAlias(() => resultAlias.Id)
                                                  .Select(() => shiftchangeAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                                  .Select(() => DocumentType.ShiftChangeDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                                  .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                                  .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                                  .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                                  .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                                  .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                                  .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                                  .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                                  .Select(() => shiftchangeAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                      .TransformUsing(Transformers.AliasToBean <DocumentVMNode>())
                                      .List <DocumentVMNode>();

                result.AddRange(shiftchangeList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.RegradingOfGoodsDocument) && Filter.RestrictDriver == null)
            {
                var regrandingQuery = UoW.Session.QueryOver <RegradingOfGoodsDocument>(() => regradingOfGoodsAlias);
                if (Filter.RestrictWarehouse != null)
                {
                    regrandingQuery.Where(x => x.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    regrandingQuery.Where(o => o.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    regrandingQuery.Where(o => o.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var regrandingList = regrandingQuery
                                     .JoinQueryOver(() => regradingOfGoodsAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .JoinAlias(() => regradingOfGoodsAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .JoinAlias(() => regradingOfGoodsAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .SelectList(list => list
                                                 .Select(() => regradingOfGoodsAlias.Id).WithAlias(() => resultAlias.Id)
                                                 .Select(() => regradingOfGoodsAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                                 .Select(() => DocumentType.RegradingOfGoodsDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                                 .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                                 .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                                 .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                                 .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                                 .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                                 .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                                 .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                                 .Select(() => regradingOfGoodsAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                     .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                     .List <DocumentVMNode> ();

                result.AddRange(regrandingList);
            }

            if ((Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.SelfDeliveryDocument) && Filter.RestrictDriver == null)
            {
                var selfDeliveryQuery = UoW.Session.QueryOver <SelfDeliveryDocument>(() => selfDeliveryAlias)
                                        .JoinQueryOver(() => selfDeliveryAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                        .JoinQueryOver(() => selfDeliveryAlias.Order, () => orderAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                        .JoinQueryOver(() => orderAlias.Client, () => counterpartyAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin);

                if (Filter.RestrictWarehouse != null)
                {
                    selfDeliveryQuery.Where(() => selfDeliveryAlias.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    selfDeliveryQuery.Where(() => selfDeliveryAlias.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    selfDeliveryQuery.Where(() => selfDeliveryAlias.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }

                var selfDeliveryList = selfDeliveryQuery
                                       .JoinAlias(() => selfDeliveryAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                       .JoinAlias(() => selfDeliveryAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                       .SelectList(list => list
                                                   .Select(() => selfDeliveryAlias.Id).WithAlias(() => resultAlias.Id)
                                                   .Select(() => orderAlias.Id).WithAlias(() => resultAlias.OrderId)
                                                   .Select(() => selfDeliveryAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                                   .Select(() => DocumentType.SelfDeliveryDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                                   .Select(() => counterpartyAlias.Name).WithAlias(() => resultAlias.Counterparty)
                                                   .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                                   .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                                   .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                                   .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                                   .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                                   .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                                   .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                                   .Select(() => selfDeliveryAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                       .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                       .List <DocumentVMNode> ();

                result.AddRange(selfDeliveryList);
            }

            if (Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.CarLoadDocument)
            {
                var carLoadQuery = UoW.Session.QueryOver <CarLoadDocument>(() => loadCarAlias)
                                   .JoinQueryOver(() => loadCarAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinQueryOver(() => loadCarAlias.RouteList, () => routeListAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinQueryOver(() => routeListAlias.Car, () => carAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                   .JoinQueryOver(() => routeListAlias.Driver, () => driverAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin);

                if (Filter.RestrictWarehouse != null)
                {
                    carLoadQuery.Where(() => loadCarAlias.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    carLoadQuery.Where(() => loadCarAlias.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    carLoadQuery.Where(() => loadCarAlias.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }
                if (Filter.RestrictDriver != null)
                {
                    carLoadQuery.Where(() => routeListAlias.Driver.Id == Filter.RestrictDriver.Id);
                }

                var carLoadList = carLoadQuery
                                  .JoinAlias(() => loadCarAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .JoinAlias(() => loadCarAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                  .SelectList(list => list
                                              .Select(() => loadCarAlias.Id).WithAlias(() => resultAlias.Id)
                                              .Select(() => loadCarAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                              .Select(() => DocumentType.CarLoadDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                              .Select(() => carAlias.Model).WithAlias(() => resultAlias.CarModel)
                                              .Select(() => carAlias.RegistrationNumber).WithAlias(() => resultAlias.CarNumber)
                                              .Select(() => driverAlias.LastName).WithAlias(() => resultAlias.DirverSurname)
                                              .Select(() => driverAlias.Name).WithAlias(() => resultAlias.DirverName)
                                              .Select(() => driverAlias.Patronymic).WithAlias(() => resultAlias.DirverPatronymic)
                                              .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                              .Select(() => routeListAlias.Id).WithAlias(() => resultAlias.RouteListId)
                                              .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                              .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                              .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                              .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                              .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                              .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                              .Select(() => loadCarAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                  .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                  .List <DocumentVMNode> ();

                result.AddRange(carLoadList);
            }

            if (Filter.RestrictDocumentType == null || Filter.RestrictDocumentType == DocumentType.CarUnloadDocument)
            {
                var carUnloadQuery = UoW.Session.QueryOver <CarUnloadDocument>(() => unloadCarAlias)
                                     .JoinQueryOver(() => unloadCarAlias.Warehouse, () => warehouseAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .JoinQueryOver(() => unloadCarAlias.RouteList, () => routeListAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .JoinQueryOver(() => routeListAlias.Car, () => carAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                     .JoinQueryOver(() => routeListAlias.Driver, () => driverAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin);

                if (Filter.RestrictWarehouse != null)
                {
                    carUnloadQuery.Where(() => unloadCarAlias.Warehouse.Id == Filter.RestrictWarehouse.Id);
                }
                if (Filter.RestrictStartDate.HasValue)
                {
                    carUnloadQuery.Where(() => unloadCarAlias.TimeStamp >= Filter.RestrictStartDate.Value);
                }
                if (Filter.RestrictEndDate.HasValue)
                {
                    carUnloadQuery.Where(() => unloadCarAlias.TimeStamp < Filter.RestrictEndDate.Value.AddDays(1));
                }
                if (Filter.RestrictDriver != null)
                {
                    carUnloadQuery.Where(() => routeListAlias.Driver.Id == Filter.RestrictDriver.Id);
                }

                var carUnloadList = carUnloadQuery
                                    .JoinAlias(() => unloadCarAlias.Author, () => authorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                    .JoinAlias(() => unloadCarAlias.LastEditor, () => lastEditorAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                    .SelectList(list => list
                                                .Select(() => unloadCarAlias.Id).WithAlias(() => resultAlias.Id)
                                                .Select(() => unloadCarAlias.TimeStamp).WithAlias(() => resultAlias.Date)
                                                .Select(() => DocumentType.CarUnloadDocument).WithAlias(() => resultAlias.DocTypeEnum)
                                                .Select(() => carAlias.Model).WithAlias(() => resultAlias.CarModel)
                                                .Select(() => carAlias.RegistrationNumber).WithAlias(() => resultAlias.CarNumber)
                                                .Select(() => driverAlias.LastName).WithAlias(() => resultAlias.DirverSurname)
                                                .Select(() => driverAlias.Name).WithAlias(() => resultAlias.DirverName)
                                                .Select(() => driverAlias.Patronymic).WithAlias(() => resultAlias.DirverPatronymic)
                                                .Select(() => warehouseAlias.Name).WithAlias(() => resultAlias.Warehouse)
                                                .Select(() => routeListAlias.Id).WithAlias(() => resultAlias.RouteListId)
                                                .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorSurname)
                                                .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                                .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                                .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorSurname)
                                                .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                                .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                                .Select(() => unloadCarAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime))
                                    .TransformUsing(Transformers.AliasToBean <DocumentVMNode> ())
                                    .List <DocumentVMNode> ();

                result.AddRange(carUnloadList);
            }

            result.Sort((x, y) => {
                if (x.Date < y.Date)
                {
                    return(1);
                }
                if (x.Date == y.Date)
                {
                    return(0);
                }
                return(-1);
            });

            SetItemsSource(result);
        }
Esempio n. 6
0
        public void UpdateInRouteListAmount_WhenCall_UpdatesQuantityCorrectly()
        {
            // arrange
            Vodovoz.Domain.Logistic.RouteList routeListMock01 = Substitute.For <Vodovoz.Domain.Logistic.RouteList>();

            Nomenclature nomenclatureMock01 = Substitute.For <Nomenclature>();

            nomenclatureMock01.Id.Returns(101);
            Nomenclature nomenclatureMock02 = Substitute.For <Nomenclature>();

            nomenclatureMock02.Id.Returns(102);
            Nomenclature nomenclatureMock03 = Substitute.For <Nomenclature>();

            nomenclatureMock03.Id.Returns(103);

            List <GoodsInRouteListResult> listOfGoods = new List <GoodsInRouteListResult> {
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock01.Id,
                    Amount         = 1
                },
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock02.Id,
                    Amount         = 2
                },
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock03.Id,
                    Amount         = 3
                }
            };

            IUnitOfWork uowMock = Substitute.For <IUnitOfWork>();

            IRouteListRepository routeListRepositoryMock = Substitute.For <IRouteListRepository>();

            routeListRepositoryMock.GetGoodsAndEquipsInRL(uowMock, routeListMock01, null).Returns(listOfGoods);

            CarLoadDocument loadDocumentUnderTest = new CarLoadDocument {
                RouteList = routeListMock01,
                Items     = new List <CarLoadDocumentItem> {
                    new CarLoadDocumentItem {
                        Nomenclature      = nomenclatureMock01,
                        AmountInRouteList = 11
                    },
                    new CarLoadDocumentItem {
                        Nomenclature      = nomenclatureMock02,
                        AmountInRouteList = 12
                    },
                    new CarLoadDocumentItem {
                        Nomenclature      = nomenclatureMock03,
                        AmountInRouteList = 13
                    }
                }
            };

            // act
            loadDocumentUnderTest.UpdateInRouteListAmount(uowMock, routeListRepositoryMock);

            // assert
            Assert.That(loadDocumentUnderTest.Items.Count, Is.EqualTo(3));
            Assert.That(loadDocumentUnderTest.Items[0].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock01.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[1].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock02.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[2].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock03.Id).Amount));
        }
Esempio n. 7
0
        public void FillFromRouteList_WhenPassARouteList_CarLoadItemsCreatingCorrectly()
        {
            // arrange
            Vodovoz.Domain.Logistic.RouteList routeListMock01 = Substitute.For <Vodovoz.Domain.Logistic.RouteList>();
            Warehouse warehouseMock01 = Substitute.For <Warehouse>();
            ISubdivisionRepository subdivisionRepositoryMock01 = Substitute.For <ISubdivisionRepository>();
            Nomenclature           nomenclatureMock01          = Substitute.For <Nomenclature>();

            nomenclatureMock01.Id.Returns(101);
            Nomenclature nomenclatureMock02 = Substitute.For <Nomenclature>();

            nomenclatureMock02.Id.Returns(102);
            Nomenclature nomenclatureMock03 = Substitute.For <Nomenclature>();

            nomenclatureMock03.Id.Returns(103);

            List <GoodsInRouteListResult> listOfGoods = new List <GoodsInRouteListResult> {
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock01.Id,
                    Amount         = 10
                },
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock02.Id,
                    Amount         = 20
                },
                new GoodsInRouteListResult {
                    NomenclatureId = nomenclatureMock03.Id,
                    Amount         = 30
                }
            };

            IUnitOfWork uowMock = Substitute.For <IUnitOfWork>();

            uowMock.GetById <Nomenclature>(Arg.Any <int[]>()).Returns(
                new List <Nomenclature> {
                nomenclatureMock01,
                nomenclatureMock02,
                nomenclatureMock03
            }
                );

            IRouteListRepository routeListRepositoryMock = Substitute.For <IRouteListRepository>();

            routeListRepositoryMock.GetGoodsAndEquipsInRL(uowMock, routeListMock01, subdivisionRepositoryMock01, warehouseMock01).Returns(listOfGoods);

            CarLoadDocument loadDocumentUnderTest = new CarLoadDocument {
                Warehouse = warehouseMock01,
                RouteList = routeListMock01
            };

            // act
            loadDocumentUnderTest.FillFromRouteList(uowMock, routeListRepositoryMock, subdivisionRepositoryMock01, true);

            // assert
            Assert.That(loadDocumentUnderTest.Items.Count, Is.EqualTo(3));
            Assert.That(loadDocumentUnderTest.Items[0].Document, Is.EqualTo(loadDocumentUnderTest));
            Assert.That(loadDocumentUnderTest.Items[0].Nomenclature, Is.EqualTo(nomenclatureMock01));
            Assert.That(loadDocumentUnderTest.Items[0].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock01.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[0].Amount, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock01.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[1].Document, Is.EqualTo(loadDocumentUnderTest));
            Assert.That(loadDocumentUnderTest.Items[1].Nomenclature, Is.EqualTo(nomenclatureMock02));
            Assert.That(loadDocumentUnderTest.Items[1].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock02.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[1].Amount, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock02.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[2].Document, Is.EqualTo(loadDocumentUnderTest));
            Assert.That(loadDocumentUnderTest.Items[2].Nomenclature, Is.EqualTo(nomenclatureMock03));
            Assert.That(loadDocumentUnderTest.Items[2].AmountInRouteList, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock03.Id).Amount));
            Assert.That(loadDocumentUnderTest.Items[2].Amount, Is.EqualTo(listOfGoods.FirstOrDefault(x => x.NomenclatureId == nomenclatureMock03.Id).Amount));
        }
Esempio n. 8
0
        public bool HasEnoughQuantityForFastDelivery(IUnitOfWork uow, RouteListItem routeListItemFrom, RouteList routeListTo)
        {
            RouteListItem          routeListItemAlias           = null;
            RouteListItem          routeListItemTransferedAlias = null;
            OrderItem              orderItemAlias          = null;
            NomenclatureAmountNode nomenclatureAmountAlias = null;
            Order               orderAlias               = null;
            OrderEquipment      orderEquipmentAlias      = null;
            CarLoadDocument     carLoadDocumentAlias     = null;
            CarLoadDocumentItem carLoadDocumentItemAlias = null;

            var nomenclaturesToDeliver = routeListItemFrom.Order.GetAllGoodsToDeliver();

            var neededIds = nomenclaturesToDeliver.Select(x => x.NomenclatureId).ToArray();

            var orderItemsToDeliver = uow.Session.QueryOver <RouteListItem>(() => routeListItemAlias)
                                      .Inner.JoinAlias(() => routeListItemAlias.Order, () => orderAlias)
                                      .Inner.JoinAlias(() => orderAlias.OrderItems, () => orderItemAlias)
                                      .Left.JoinAlias(() => routeListItemAlias.TransferedTo, () => routeListItemTransferedAlias)
                                      .Where(() => routeListItemAlias.RouteList.Id == routeListTo.Id)
                                      .WhereRestrictionOn(() => orderItemAlias.Nomenclature.Id).IsIn(neededIds)
                                      .Where(() =>
                                             //не отменённые и не недовозы
                                             routeListItemAlias.Status != RouteListItemStatus.Canceled && routeListItemAlias.Status != RouteListItemStatus.Overdue
                                             // и не перенесённые к водителю; либо перенесённые с погрузкой; либо перенесённые и это экспресс-доставка (всегда без погрузки)
                                             && (!routeListItemAlias.WasTransfered || routeListItemAlias.NeedToReload || orderAlias.IsFastDelivery)
                                             // и не перенесённые от водителя; либо перенесённые и не нужна погрузка и не экспресс-доставка (остатки по экспресс-доставке не переносятся)
                                             && (routeListItemAlias.Status != RouteListItemStatus.Transfered || (!routeListItemTransferedAlias.NeedToReload && !orderAlias.IsFastDelivery)))
                                      .SelectList(list => list
                                                  .SelectGroup(() => orderItemAlias.Nomenclature.Id).WithAlias(() => nomenclatureAmountAlias.NomenclatureId)
                                                  .SelectSum(() => orderItemAlias.Count).WithAlias(() => nomenclatureAmountAlias.Amount)
                                                  ).TransformUsing(Transformers.AliasToBean <NomenclatureAmountNode>())
                                      .Future <NomenclatureAmountNode>();

            var orderEquipmentsToDeliver = uow.Session.QueryOver <RouteListItem>(() => routeListItemAlias)
                                           .Inner.JoinAlias(() => routeListItemAlias.Order, () => orderAlias)
                                           .Inner.JoinAlias(() => orderAlias.OrderEquipments, () => orderEquipmentAlias)
                                           .Left.JoinAlias(() => routeListItemAlias.TransferedTo, () => routeListItemTransferedAlias)
                                           .Where(() => routeListItemAlias.RouteList.Id == routeListTo.Id)
                                           .WhereRestrictionOn(() => orderEquipmentAlias.Nomenclature.Id).IsIn(neededIds)
                                           .Where(() =>
                                                  //не отменённые и не недовозы
                                                  routeListItemAlias.Status != RouteListItemStatus.Canceled && routeListItemAlias.Status != RouteListItemStatus.Overdue
                                                  // и не перенесённые к водителю; либо перенесённые с погрузкой; либо перенесённые и это экспресс-доставка (всегда без погрузки)
                                                  && (!routeListItemAlias.WasTransfered || routeListItemAlias.NeedToReload || orderAlias.IsFastDelivery)
                                                  // и не перенесённые от водителя; либо перенесённые и не нужна погрузка и не экспресс-доставка (остатки по экспресс-доставке не переносятся)
                                                  && (routeListItemAlias.Status != RouteListItemStatus.Transfered || (!routeListItemTransferedAlias.NeedToReload && !orderAlias.IsFastDelivery)))
                                           .And(() => orderEquipmentAlias.Direction == Domain.Orders.Direction.Deliver)
                                           .SelectList(list => list
                                                       .SelectGroup(() => orderEquipmentAlias.Nomenclature.Id).WithAlias(() => nomenclatureAmountAlias.NomenclatureId)
                                                       .Select(Projections.Cast(NHibernateUtil.Decimal, Projections.Sum(Projections.Property(() => orderEquipmentAlias.Count)))).WithAlias(() => nomenclatureAmountAlias.Amount)
                                                       ).TransformUsing(Transformers.AliasToBean <NomenclatureAmountNode>())
                                           .Future <NomenclatureAmountNode>();

            var allToDeliver = orderItemsToDeliver
                               .Union(orderEquipmentsToDeliver)
                               .GroupBy(x => new { x.NomenclatureId })
                               .Select(group => new NomenclatureAmountNode()
            {
                NomenclatureId = group.Key.NomenclatureId,
                Amount         = group.Sum(x => x.Amount)
            })
                               .ToList();

            var allLoaded = uow.Session.QueryOver <CarLoadDocument>(() => carLoadDocumentAlias)
                            .Inner.JoinAlias(() => carLoadDocumentAlias.Items, () => carLoadDocumentItemAlias)
                            .Where(() => carLoadDocumentAlias.RouteList.Id == routeListTo.Id)
                            .WhereRestrictionOn(() => carLoadDocumentItemAlias.Nomenclature.Id).IsIn(neededIds)
                            .SelectList(list => list
                                        .SelectGroup(() => carLoadDocumentItemAlias.Nomenclature.Id).WithAlias(() => nomenclatureAmountAlias.NomenclatureId)
                                        .SelectSum(() => carLoadDocumentItemAlias.Amount).WithAlias(() => nomenclatureAmountAlias.Amount)
                                        ).TransformUsing(Transformers.AliasToBean <NomenclatureAmountNode>())
                            .List <NomenclatureAmountNode>();

            foreach (var need in nomenclaturesToDeliver)
            {
                var toDeliver = allToDeliver.FirstOrDefault(x => x.NomenclatureId == need.NomenclatureId)?.Amount ?? 0;
                var loaded    = allLoaded.FirstOrDefault(x => x.NomenclatureId == need.NomenclatureId)?.Amount ?? 0;

                if (loaded - toDeliver < need.Amount)
                {
                    return(false);
                }
            }

            return(true);
        }
        public FastDeliveryAvailabilityHistory GetRouteListsForFastDelivery(
            IUnitOfWork uow,
            double latitude,
            double longitude,
            bool isGetClosestByRoute,
            IDeliveryRulesParametersProvider deliveryRulesParametersProvider,
            IEnumerable <NomenclatureAmountNode> nomenclatureNodes,
            Order fastDeliveryOrder = null)
        {
            var maxDistanceToTrackPoint      = deliveryRulesParametersProvider.MaxDistanceToLatestTrackPointKm;
            var driverGoodWeightLiftPerHand  = deliveryRulesParametersProvider.DriverGoodWeightLiftPerHandInKg;
            var maxFastOrdersPerSpecificTime = deliveryRulesParametersProvider.MaxFastOrdersPerSpecificTime;

            var maxTimeForFastDeliveryTimespan = deliveryRulesParametersProvider.MaxTimeForFastDelivery;

            //Переводим всё в минуты
            var trackPointTimeOffset           = (int)deliveryRulesParametersProvider.MaxTimeOffsetForLatestTrackPoint.TotalMinutes;
            var maxTimeForFastDelivery         = (int)maxTimeForFastDeliveryTimespan.TotalMinutes;
            var minTimeForNewOrder             = (int)deliveryRulesParametersProvider.MinTimeForNewFastDeliveryOrder.TotalMinutes;
            var driverUnloadTime               = (int)deliveryRulesParametersProvider.DriverUnloadTime.TotalMinutes;
            var specificTimeForFastOrdersCount = (int)deliveryRulesParametersProvider.SpecificTimeForMaxFastOrdersCount.TotalMinutes;

            var fastDeliveryAvailabilityHistory = new FastDeliveryAvailabilityHistory
            {
                IsGetClosestByRoute = isGetClosestByRoute,
                Order = fastDeliveryOrder,
                MaxDistanceToLatestTrackPointKm = maxDistanceToTrackPoint,
                DriverGoodWeightLiftPerHandInKg = driverGoodWeightLiftPerHand,
                MaxFastOrdersPerSpecificTime    = maxFastOrdersPerSpecificTime,
                MaxTimeForFastDelivery          = maxTimeForFastDeliveryTimespan,
                MinTimeForNewFastDeliveryOrder  = deliveryRulesParametersProvider.MinTimeForNewFastDeliveryOrder,
                DriverUnloadTime = deliveryRulesParametersProvider.DriverUnloadTime,
                SpecificTimeForMaxFastOrdersCount = deliveryRulesParametersProvider.SpecificTimeForMaxFastOrdersCount,
            };

            var order = fastDeliveryAvailabilityHistory.Order;

            if (order != null)
            {
                fastDeliveryAvailabilityHistory.Order         = order.Id == 0 ? null : order;
                fastDeliveryAvailabilityHistory.Author        = order.Author;
                fastDeliveryAvailabilityHistory.DeliveryPoint = order.DeliveryPoint;
                fastDeliveryAvailabilityHistory.District      = order.DeliveryPoint.District;
                fastDeliveryAvailabilityHistory.Counterparty  = order.Client;
            }

            var fastDeliveryHistoryConverter = new FastDeliveryHistoryConverter();

            if (nomenclatureNodes != null)
            {
                fastDeliveryAvailabilityHistory.OrderItemsHistory =
                    fastDeliveryHistoryConverter.ConvertNomenclatureAmountNodesToOrderItemsHistory(nomenclatureNodes, fastDeliveryAvailabilityHistory);
            }

            var distributions = uow.GetAll <AdditionalLoadingNomenclatureDistribution>();

            fastDeliveryAvailabilityHistory.NomenclatureDistributionHistoryItems =
                fastDeliveryHistoryConverter.ConvertNomenclatureDistributionToDistributionHistory(distributions, fastDeliveryAvailabilityHistory);

            var district = GetDistrict(uow, (decimal)latitude, (decimal)longitude);

            if (district?.TariffZone == null || !district.TariffZone.IsFastDeliveryAvailableAtCurrentTime)
            {
                fastDeliveryAvailabilityHistory.AdditionalInformation =
                    new List <string> {
                    "Не найден район, у района отсутствует тарифная зона, либо недоступна экспресс-доставка в текущее время."
                };

                return(fastDeliveryAvailabilityHistory);
            }

            var neededNomenclatures = nomenclatureNodes.ToDictionary(x => x.NomenclatureId, x => x.Amount);

            Track      t       = null;
            TrackPoint tp      = null;
            RouteList  rl      = null;
            TrackPoint tpInner = null;
            FastDeliveryVerificationDetailsNode result = null;
            Employee e = null;

            RouteListItem       rla           = null;
            RouteListItem       rlaTransfered = null;
            Order               o             = null;
            OrderItem           oi            = null;
            OrderEquipment      oe            = null;
            CarLoadDocument     scld          = null;
            CarLoadDocumentItem scldi         = null;
            CountUnclosedFastDeliveryAddressesNode countUnclosedFastDeliveryAddressesAlias = null;

            RouteListNomenclatureAmount ordersAmountAlias        = null;
            RouteListNomenclatureAmount loadDocumentsAmountAlias = null;

            var lastTimeTrackQuery = QueryOver.Of(() => tpInner)
                                     .Where(() => tpInner.Track.Id == t.Id)
                                     .Select(Projections.Max(() => tpInner.TimeStamp));

            //МЛ только в пути и с погруженным запасом
            var routeListNodes = uow.Session.QueryOver(() => rl)
                                 .JoinEntityAlias(() => t, () => t.RouteList.Id == rl.Id)
                                 .Inner.JoinAlias(() => t.TrackPoints, () => tp)
                                 .Inner.JoinAlias(() => rl.Driver, () => e)
                                 .WithSubquery.WhereProperty(() => tp.TimeStamp).Eq(lastTimeTrackQuery)
                                 .And(() => rl.Status == RouteListStatus.EnRoute)
                                 .And(() => rl.AdditionalLoadingDocument.Id != null) // только с погруженным запасом
                                 .SelectList(list => list
                                             .Select(() => tp.TimeStamp).WithAlias(() => result.TimeStamp)
                                             .Select(() => tp.Latitude).WithAlias(() => result.Latitude)
                                             .Select(() => tp.Longitude).WithAlias(() => result.Longitude)
                                             .Select(Projections.Entity(() => rl)).WithAlias(() => result.RouteList))
                                 .TransformUsing(Transformers.AliasToBean <FastDeliveryVerificationDetailsNode>())
                                 .List <FastDeliveryVerificationDetailsNode>();

            //Последняя координата в указанном радиусе
            foreach (var node in routeListNodes)
            {
                var distance      = DistanceHelper.GetDistanceKm(node.Latitude, node.Longitude, latitude, longitude);
                var deliveryPoint = new PointOnEarth(latitude, longitude);
                var proposedRoute = OsrmClientFactory.Instance
                                    .GetRoute(new List <PointOnEarth> {
                    new PointOnEarth(node.Latitude, node.Longitude), deliveryPoint
                }, false, GeometryOverview.False, _globalSettings.ExcludeToll)?.Routes?
                                    .FirstOrDefault();

                node.DistanceByLineToClient.ParameterValue = (decimal)distance;
                node.DistanceByRoadToClient.ParameterValue = decimal.Round((decimal)(proposedRoute?.TotalDistance ?? int.MaxValue) / 1000, 2);
                if (distance < maxDistanceToTrackPoint)
                {
                    node.DistanceByLineToClient.IsValidParameter = node.DistanceByRoadToClient.IsValidParameter = true;
                }
                else
                {
                    node.DistanceByLineToClient.IsValidParameter = node.DistanceByRoadToClient.IsValidParameter = false;
                    node.IsValidRLToFastDelivery = false;
                }

                //Выставляем время последней координаты

                var timeSpan = DateTime.Now - node.TimeStamp;
                node.LastCoordinateTime.ParameterValue = timeSpan.TotalHours > 838 ? new TimeSpan(838, 0, 0) : timeSpan;

                if (node.LastCoordinateTime.ParameterValue.TotalMinutes <= trackPointTimeOffset)
                {
                    node.LastCoordinateTime.IsValidParameter = true;
                }
                else
                {
                    node.LastCoordinateTime.IsValidParameter = false;
                    node.IsValidRLToFastDelivery             = false;
                }
            }

            routeListNodes = routeListNodes
                             .OrderBy(x => isGetClosestByRoute ? x.DistanceByRoadToClient.ParameterValue : x.DistanceByLineToClient.ParameterValue)
                             .ToList();

            //Не более определённого кол-ва заказов с быстрой доставкой в определённый промежуток времени
            var addressCountSubquery = QueryOver.Of(() => rla)
                                       .Inner.JoinAlias(() => rla.Order, () => o)
                                       .Where(() => rla.RouteList.Id == rl.Id)
                                       .And(() => rla.Status == RouteListItemStatus.EnRoute)
                                       .And(() => o.IsFastDelivery)
                                       .And(Restrictions.GtProperty(
                                                Projections.Property(() => rla.CreationDate),
                                                Projections.SqlFunction(
                                                    new SQLFunctionTemplate(NHibernateUtil.DateTime,
                                                                            $"TIMESTAMPADD(MINUTE, -{specificTimeForFastOrdersCount}, CURRENT_TIMESTAMP)"),
                                                    NHibernateUtil.DateTime)))
                                       .Select(Projections.Count(() => rla.Id));

            var routeListsWithCountUnclosedFastDeliveries = uow.Session.QueryOver(() => rl)
                                                            .WhereRestrictionOn(() => rl.Id).IsInG(routeListNodes.Select(x => x.RouteList.Id))
                                                            .SelectList(list => list
                                                                        .Select(() => rl.Id).WithAlias(() => countUnclosedFastDeliveryAddressesAlias.RouteListId)
                                                                        .SelectSubQuery(addressCountSubquery).WithAlias(() => countUnclosedFastDeliveryAddressesAlias.UnclosedFastDeliveryAddresses))
                                                            .TransformUsing(Transformers.AliasToBean <CountUnclosedFastDeliveryAddressesNode>())
                                                            .List <CountUnclosedFastDeliveryAddressesNode>();

            var rlsWithCountUnclosedFastDeliveries =
                routeListsWithCountUnclosedFastDeliveries.ToDictionary(x => x.RouteListId, x => x.UnclosedFastDeliveryAddresses);

            foreach (var node in routeListNodes)
            {
                var countUnclosedFastDeliveryAddresses = rlsWithCountUnclosedFastDeliveries[node.RouteList.Id];
                node.UnClosedFastDeliveries.ParameterValue = countUnclosedFastDeliveryAddresses;
                if (countUnclosedFastDeliveryAddresses < maxFastOrdersPerSpecificTime)
                {
                    node.UnClosedFastDeliveries.IsValidParameter = true;
                }
                else
                {
                    node.UnClosedFastDeliveries.IsValidParameter = false;
                    node.IsValidRLToFastDelivery = false;
                }
            }

            //Время доставки следующего (текущего) заказа позволяет взять быструю доставку
            foreach (var routeListNode in routeListNodes)
            {
                RouteListItem latestAddress = null;

                var orderedEnRouteAddresses = routeListNode.RouteList.Addresses
                                              .Where(x => x.Status == RouteListItemStatus.EnRoute).OrderBy(x => x.IndexInRoute).ToList();

                var orderedCompletedAddresses = routeListNode.RouteList.Addresses
                                                .Where(x => x.Status == RouteListItemStatus.Completed).OrderBy(x => x.IndexInRoute).ToList();

                var latestCompletedAddress = orderedCompletedAddresses.OrderByDescending(x => x.StatusLastUpdate).FirstOrDefault();

                if (latestCompletedAddress != null)
                {
                    latestAddress = orderedEnRouteAddresses.FirstOrDefault(x => x.IndexInRoute > latestCompletedAddress.IndexInRoute);
                }
                if (latestAddress == null)
                {
                    latestAddress = orderedEnRouteAddresses.FirstOrDefault();
                }

                if (latestAddress != null)
                {
                    var neededTime1 = maxTimeForFastDelivery - latestAddress.Order.DeliveryPoint.MinutesToUnload;
                    if (neededTime1 < minTimeForNewOrder)
                    {
                        routeListNode.RemainingTimeForShipmentNewOrder.ParameterValue   = new TimeSpan(0, neededTime1, 0);
                        routeListNode.RemainingTimeForShipmentNewOrder.IsValidParameter = false;
                        routeListNode.IsValidRLToFastDelivery = false;
                        continue;
                    }

                    var water19Count = latestAddress.Order.OrderItems
                                       .Where(x => x.Nomenclature.TareVolume == TareVolume.Vol19L && x.Nomenclature.Category == NomenclatureCategory.water)
                                       .Sum(x => x.Count);

                    var orderItemsSummaryWeight = latestAddress.Order.OrderItems
                                                  .Where(x => x.Nomenclature.TareVolume != TareVolume.Vol19L || x.Nomenclature.Category != NomenclatureCategory.water)
                                                  .Sum(x => x.Nomenclature.Weight * x.Count);

                    var orderEquipmentsSummaryWeight = latestAddress.Order.OrderEquipments
                                                       .Where(x => x.Direction == Direction.Deliver)
                                                       .Sum(x => x.Nomenclature.Weight * x.Count);

                    var goodsSummaryWeight = orderItemsSummaryWeight + orderEquipmentsSummaryWeight;

                    //Время выгрузки след. заказа:
                    //(Суммарный вес прочих товаров / кол-во кг, которое водитель может унести в одной руке + кол-во 19л) / 2 руки * время выгрузки в 2 руках 2 бутылей или товара
                    var unloadTime  = (goodsSummaryWeight / driverGoodWeightLiftPerHand + water19Count) / 2 * driverUnloadTime;
                    var neededTime2 = maxTimeForFastDelivery - (int)unloadTime;

                    if (neededTime2 < minTimeForNewOrder)
                    {
                        routeListNode.RemainingTimeForShipmentNewOrder.ParameterValue   = new TimeSpan(0, neededTime2, 0);
                        routeListNode.RemainingTimeForShipmentNewOrder.IsValidParameter = false;
                        routeListNode.IsValidRLToFastDelivery = false;
                    }
                    else
                    {
                        routeListNode.RemainingTimeForShipmentNewOrder.ParameterValue   = new TimeSpan(0, neededTime2, 0);
                        routeListNode.RemainingTimeForShipmentNewOrder.IsValidParameter = true;
                    }
                }
                else
                {
                    routeListNode.RemainingTimeForShipmentNewOrder.ParameterValue   = maxTimeForFastDeliveryTimespan;
                    routeListNode.RemainingTimeForShipmentNewOrder.IsValidParameter = true;
                }
            }

            var rlIds = routeListNodes.Select(x => x.RouteList.Id).ToArray();

            //OrderItems
            var orderItemsToDeliver = uow.Session.QueryOver <RouteListItem>(() => rla)
                                      .Inner.JoinAlias(() => rla.Order, () => o)
                                      .Inner.JoinAlias(() => o.OrderItems, () => oi)
                                      .Left.JoinAlias(() => rla.TransferedTo, () => rlaTransfered)
                                      .WhereRestrictionOn(() => rla.RouteList.Id).IsIn(rlIds)
                                      .WhereRestrictionOn(() => oi.Nomenclature.Id).IsIn(neededNomenclatures.Keys)
                                      .Where(() =>
                                             //не отменённые и не недовозы
                                             rla.Status != RouteListItemStatus.Canceled && rla.Status != RouteListItemStatus.Overdue
                                             // и не перенесённые к водителю; либо перенесённые с погрузкой; либо перенесённые и это экспресс-доставка (всегда без погрузки)
                                             && (!rla.WasTransfered || rla.NeedToReload || o.IsFastDelivery)
                                             // и не перенесённые от водителя; либо перенесённые и не нужна погрузка и не экспресс-доставка (остатки по экспресс-доставке не переносятся)
                                             && (rla.Status != RouteListItemStatus.Transfered || (!rlaTransfered.NeedToReload && !o.IsFastDelivery)))
                                      .SelectList(list => list
                                                  .SelectGroup(() => rla.RouteList.Id).WithAlias(() => ordersAmountAlias.RouteListId)
                                                  .SelectGroup(() => oi.Nomenclature.Id).WithAlias(() => ordersAmountAlias.NomenclatureId)
                                                  .SelectSum(() => oi.Count).WithAlias(() => ordersAmountAlias.Amount))
                                      .TransformUsing(Transformers.AliasToBean <RouteListNomenclatureAmount>())
                                      .Future <RouteListNomenclatureAmount>();

            //OrderEquipments
            var orderEquipmentsToDeliver = uow.Session.QueryOver <RouteListItem>(() => rla)
                                           .Inner.JoinAlias(() => rla.Order, () => o)
                                           .Inner.JoinAlias(() => o.OrderEquipments, () => oe)
                                           .Left.JoinAlias(() => rla.TransferedTo, () => rlaTransfered)
                                           .WhereRestrictionOn(() => rla.RouteList.Id).IsIn(rlIds)
                                           .WhereRestrictionOn(() => oe.Nomenclature.Id).IsIn(neededNomenclatures.Keys)
                                           .Where(() =>
                                                  //не отменённые и не недовозы
                                                  rla.Status != RouteListItemStatus.Canceled && rla.Status != RouteListItemStatus.Overdue
                                                  // и не перенесённые к водителю; либо перенесённые с погрузкой; либо перенесённые и это экспресс-доставка (всегда без погрузки)
                                                  && (!rla.WasTransfered || rla.NeedToReload || o.IsFastDelivery)
                                                  // и не перенесённые от водителя; либо перенесённые и не нужна погрузка и не экспресс-доставка (остатки по экспресс-доставке не переносятся)
                                                  && (rla.Status != RouteListItemStatus.Transfered || (!rlaTransfered.NeedToReload && !o.IsFastDelivery)))
                                           .And(() => oe.Direction == Direction.Deliver)
                                           .SelectList(list => list
                                                       .SelectGroup(() => rla.RouteList.Id).WithAlias(() => ordersAmountAlias.RouteListId)
                                                       .SelectGroup(() => oe.Nomenclature.Id).WithAlias(() => ordersAmountAlias.NomenclatureId)
                                                       .Select(Projections.Sum(Projections.Cast(NHibernateUtil.Decimal, Projections.Property(() => oe.Count)))
                                                               ).WithAlias(() => ordersAmountAlias.Amount))
                                           .TransformUsing(Transformers.AliasToBean <RouteListNomenclatureAmount>())
                                           .Future <RouteListNomenclatureAmount>();

            //CarLoadDocuments
            var allLoaded = uow.Session.QueryOver <CarLoadDocument>(() => scld)
                            .Inner.JoinAlias(() => scld.Items, () => scldi)
                            .WhereRestrictionOn(() => scld.RouteList.Id).IsIn(rlIds)
                            .WhereRestrictionOn(() => scldi.Nomenclature.Id).IsIn(neededNomenclatures.Keys)
                            .SelectList(list => list
                                        .SelectGroup(() => scld.RouteList.Id).WithAlias(() => loadDocumentsAmountAlias.RouteListId)
                                        .SelectGroup(() => scldi.Nomenclature.Id).WithAlias(() => loadDocumentsAmountAlias.NomenclatureId)
                                        .SelectSum(() => scldi.Amount).WithAlias(() => loadDocumentsAmountAlias.Amount))
                            .TransformUsing(Transformers.AliasToBean <RouteListNomenclatureAmount>())
                            .Future <RouteListNomenclatureAmount>();

            var allToDeliver = orderItemsToDeliver
                               .Union(orderEquipmentsToDeliver)
                               .GroupBy(x => new { x.RouteListId, x.NomenclatureId })
                               .Select(group => new RouteListNomenclatureAmount
            {
                RouteListId    = group.Key.RouteListId,
                NomenclatureId = group.Key.NomenclatureId,
                Amount         = group.Sum(x => x.Amount)
            })
                               .ToList();

            //Выбираем МЛ, в котором хватает запаса номенклатур на поступивший быстрый заказ
            foreach (var routeListNode in routeListNodes)
            {
                var toDeliverForRL = allToDeliver.Where(x => x.RouteListId == routeListNode.RouteList.Id).ToList();
                var loadedForRL    = allLoaded.Where(x => x.RouteListId == routeListNode.RouteList.Id).ToList();

                foreach (var need in neededNomenclatures)
                {
                    var toDeliver = toDeliverForRL.FirstOrDefault(x => x.NomenclatureId == need.Key)?.Amount ?? 0;
                    var loaded    = loadedForRL.FirstOrDefault(x => x.NomenclatureId == need.Key)?.Amount ?? 0;

                    var onBoard = loaded - toDeliver;
                    if (onBoard < need.Value)
                    {
                        routeListNode.IsGoodsEnough.ParameterValue   = false;
                        routeListNode.IsGoodsEnough.IsValidParameter = false;
                        routeListNode.IsValidRLToFastDelivery        = false;
                        break;
                    }
                }
            }

            if (routeListNodes != null)
            {
                fastDeliveryAvailabilityHistory.Items = fastDeliveryHistoryConverter
                                                        .ConvertVerificationDetailsNodesToAvailabilityHistoryItems(routeListNodes, fastDeliveryAvailabilityHistory);
            }

            return(fastDeliveryAvailabilityHistory);
        }