public SelfDeliveriesJournalViewModel(
            OrderJournalFilterViewModel filterViewModel,
            IUnitOfWorkFactory unitOfWorkFactory,
            ICommonServices commonServices,
            CallTaskWorker callTaskWorker,
            OrderPaymentSettings orderPaymentSettings,
            OrderParametersProvider orderParametersProvider,
            IEmployeeService employeeService)
            : base(filterViewModel, unitOfWorkFactory, commonServices)
        {
            _callTaskWorker          = callTaskWorker ?? throw new ArgumentNullException(nameof(callTaskWorker));
            _orderPaymentSettings    = orderPaymentSettings ?? throw new ArgumentNullException(nameof(orderPaymentSettings));
            _orderParametersProvider = orderParametersProvider ?? throw new ArgumentNullException(nameof(orderParametersProvider));
            _currentEmployee         =
                (employeeService ?? throw new ArgumentNullException(nameof(employeeService))).GetEmployeeForUser(
                    UoW,
                    commonServices.UserService.CurrentUserId);

            TabName = "Журнал самовывозов";
            SetOrder(x => x.Date, true);
            UpdateOnChanges(
                typeof(VodovozOrder),
                typeof(OrderItem)
                );
            _userCanChangePayTypeToByCard = commonServices.CurrentPermissionService.ValidatePresetPermission("allow_load_selfdelivery");
        }
Exemplo n.º 2
0
        protected void InitPopupActions()
        {
            var callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                _callTaskRepository,
                new OrderRepository(),
                new EmployeeRepository(),
                _baseParametersProvider,
                commonServices.UserService,
                ErrorReporter.Instance);

            PopupActionsList.Add(new JournalAction(
                                     "Закрытие МЛ",
                                     (selectedItems) => selectedItems.Any(x => _closingDlgStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => _closingDlgStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                if (selectedItems.FirstOrDefault() is RouteListJournalNode selectedNode &&
                    _closingDlgStatuses.Contains(selectedNode.StatusEnum))
                {
                    TabParent.OpenTab(
                        DialogHelper.GenerateDialogHashName <RouteList>(selectedNode.Id),
                        () => new RouteListClosingDlg(selectedNode.Id, true)
                        );
                }
            }
Exemplo n.º 3
0
        public PaymentByCardViewModel(
            IEntityUoWBuilder uowBuilder,
            IUnitOfWorkFactory unitOfWorkFactory,
            ICommonServices commonServices,
            CallTaskWorker callTaskWorker,
            IOrderPaymentSettings orderPaymentSettings,
            IOrderParametersProvider orderParametersProvider,
            Employee currentEmployee) : base(uowBuilder, unitOfWorkFactory, commonServices)
        {
            if (orderPaymentSettings == null)
            {
                throw new ArgumentNullException(nameof(orderPaymentSettings));
            }

            if (orderParametersProvider == null)
            {
                throw new ArgumentNullException(nameof(orderParametersProvider));
            }

            _callTaskWorker  = callTaskWorker ?? throw new ArgumentNullException(nameof(callTaskWorker));
            _currentEmployee = currentEmployee;

            TabName = "Оплата по карте";

            ItemsList = UoW.GetAll <PaymentFrom>().ToList();

            if (PaymentByCardFrom == null)
            {
                PaymentByCardFrom = ItemsList.FirstOrDefault(p => p.Id == orderPaymentSettings.DefaultSelfDeliveryPaymentFromId);
            }

            Entity.PropertyChanged += Entity_PropertyChanged;

            ValidationContext.ServiceContainer.AddService(typeof(IOrderParametersProvider), orderParametersProvider);
        }
Exemplo n.º 4
0
        public override bool Save()
        {
            if (!Entity.CanEdit)
            {
                return(false);
            }

            var valid = new QS.Validation.QSValidator <SelfDeliveryDocument>(UoWGeneric.Root);

            if (valid.RunDlgIfNotValid((Gtk.Window) this.Toplevel))
            {
                return(false);
            }

            Entity.LastEditor     = _employeeRepository.GetEmployeeForCurrentUser(UoW);
            Entity.LastEditedTime = DateTime.Now;
            if (Entity.LastEditor == null)
            {
                MessageDialogHelper.RunErrorDialog("Ваш пользователь не привязан к действующему сотруднику, вы не можете изменять складские документы, так как некого указывать в качестве кладовщика.");
                return(false);
            }

            Entity.UpdateOperations(UoW);
            Entity.UpdateReceptions(UoW, GoodsReceptionList, _nomenclatureRepository, _bottlesRepository);

            IStandartNomenclatures standartNomenclatures = new BaseParametersProvider(new ParametersProvider());
            var callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                new CallTaskRepository(),
                new OrderRepository(),
                _employeeRepository,
                new BaseParametersProvider(new ParametersProvider()),
                ServicesConfig.CommonServices.UserService,
                SingletonErrorReporter.Instance);

            if (Entity.FullyShiped(UoW, standartNomenclatures, new RouteListItemRepository(), new SelfDeliveryRepository(), new CashRepository(), callTaskWorker))
            {
                MessageDialogHelper.RunInfoDialog("Заказ отгружен полностью.");
            }

            logger.Info("Сохраняем документ самовывоза...");
            UoWGeneric.Save();
            //FIXME Необходимо проверить правильность этого кода, так как если заказ именялся то уведомление на его придет и без кода.
            //А если в каком то месте нужно получать уведомления об изменениях текущего объекта, то логично чтобы этот объект на него и подписался.
            //OrmMain.NotifyObjectUpdated(new object[] { Entity.Order });
            logger.Info("Ok.");
            return(true);
        }
Exemplo n.º 5
0
        public void CancelOrder(Order order)
        {
            CallTaskWorker callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                new CallTaskRepository(),
                _orderRepository,
                _employeeRepository,
                new BaseParametersProvider(_parametersProvider),
                ServicesConfig.CommonServices.UserService,
                ErrorReporter.Instance);

            if (order.OrderStatus == OrderStatus.InTravelList)
            {
                ValidationContext validationContext = new ValidationContext(order, null, new Dictionary <object, object> {
                    { "NewStatus", OrderStatus.Canceled },
                });
                validationContext.ServiceContainer.AddService(_orderParametersProvider);
                validationContext.ServiceContainer.AddService(_deliveryRulesParametersProvider);
                if (!ServicesConfig.ValidationService.Validate(order, validationContext))
                {
                    return;
                }

                ITdiPage page = tdiNavigation.OpenTdiTab <UndeliveryOnOrderCloseDlg, Order, IUnitOfWork>(null, order, UoW);
                page.PageClosed += (sender, e) => {
                    order.SetUndeliveredStatus(UoW, new BaseParametersProvider(_parametersProvider), callTaskWorker);

                    var routeListItem = _routeListItemRepository.GetRouteListItemForOrder(UoW, order);
                    if (routeListItem != null && routeListItem.Status != RouteListItemStatus.Canceled)
                    {
                        routeListItem.RouteList.SetAddressStatusWithoutOrderChange(routeListItem.Id, RouteListItemStatus.Canceled);
                        routeListItem.StatusLastUpdate = DateTime.Now;
                        routeListItem.SetOrderActualCountsToZeroOnCanceled();
                        UoW.Save(routeListItem.RouteList);
                        UoW.Save(routeListItem);
                    }

                    UoW.Commit();
                };
            }
            else
            {
                order.ChangeStatusAndCreateTasks(OrderStatus.Canceled, callTaskWorker);
                UoW.Save(order);
                UoW.Commit();
            }
        }
 public SelfDeliveriesJournalViewModel(
     OrderJournalFilterViewModel filterViewModel,
     IUnitOfWorkFactory unitOfWorkFactory,
     ICommonServices commonServices,
     CallTaskWorker callTaskWorker,
     OrderPaymentSettings orderPaymentSettings)
     : base(filterViewModel, unitOfWorkFactory, commonServices)
 {
     this.callTaskWorker       = callTaskWorker ?? throw new ArgumentNullException(nameof(callTaskWorker));
     this.orderPaymentSettings = orderPaymentSettings ?? throw new ArgumentNullException(nameof(orderPaymentSettings));
     TabName = "Журнал самовывозов";
     SetOrder(x => x.Date, true);
     UpdateOnChanges(
         typeof(VodovozOrder),
         typeof(OrderItem)
         );
 }
Exemplo n.º 7
0
        public void CancelOrder(Order order)
        {
            CallTaskWorker callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                new CallTaskRepository(),
                orderRepository,
                employeeRepository,
                new BaseParametersProvider(),
                ServicesConfig.CommonServices.UserService,
                SingletonErrorReporter.Instance);

            if (order.OrderStatus == OrderStatus.InTravelList)
            {
                var valid = new QSValidator <Order>(order,
                                                    new Dictionary <object, object> {
                    { "NewStatus", OrderStatus.Canceled },
                });
                if (valid.RunDlgIfNotValid(null))
                {
                    return;
                }

                ITdiPage page = tdiNavigation.OpenTdiTab <UndeliveryOnOrderCloseDlg, Order, IUnitOfWork>(null, order, UoW);
                page.PageClosed += (sender, e) => {
                    order.SetUndeliveredStatus(UoW, new BaseParametersProvider(), callTaskWorker);

                    var routeListItem = routeListItemRepository.GetRouteListItemForOrder(UoW, order);
                    if (routeListItem != null && routeListItem.Status != RouteListItemStatus.Canceled)
                    {
                        routeListItem.SetStatusWithoutOrderChange(RouteListItemStatus.Canceled);
                        routeListItem.StatusLastUpdate = DateTime.Now;
                        routeListItem.FillCountsOnCanceled();
                        UoW.Save(routeListItem);
                    }

                    UoW.Commit();
                };
            }
            else
            {
                order.ChangeStatusAndCreateTasks(OrderStatus.Canceled, callTaskWorker);
                UoW.Save(order);
                UoW.Commit();
            }
        }
Exemplo n.º 8
0
        public PaymentByCardViewModel(
            IEntityUoWBuilder uowBuilder,
            IUnitOfWorkFactory unitOfWorkFactory,
            ICommonServices commonServices,
            CallTaskWorker callTaskWorker,
            IOrderPaymentSettings orderPaymentSettings
            )
            : base(uowBuilder, unitOfWorkFactory, commonServices)
        {
            this.orderPaymentSettings = orderPaymentSettings ?? throw new ArgumentNullException(nameof(orderPaymentSettings));
            this.callTaskWorker       = callTaskWorker ?? throw new ArgumentNullException(nameof(callTaskWorker));
            TabName = "Оплата по карте";

            ItemsList = UoW.GetAll <PaymentFrom>().ToList();

            if (PaymentByCardFrom == null)
            {
                PaymentByCardFrom = ItemsList.FirstOrDefault(p => p.Id == orderPaymentSettings.DefaultSelfDeliveryPaymentFromId);
            }

            Entity.PropertyChanged += Entity_PropertyChanged;
        }
Exemplo n.º 9
0
        void ConfigureDlg()
        {
            callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                new CallTaskRepository(),
                OrderSingletonRepository.GetInstance(),
                EmployeeSingletonRepository.GetInstance(),
                new BaseParametersProvider(),
                ServicesConfig.CommonServices.UserService,
                SingletonErrorReporter.Instance);

            if (StoreDocumentHelper.CheckAllPermissions(UoW.IsNew, WarehousePermissions.CarUnloadEdit, Entity.Warehouse))
            {
                FailInitialize = true;
                return;
            }

            var currentUserId = QS.Project.Services.ServicesConfig.CommonServices.UserService.CurrentUserId;
            var hasPermitionToEditDocWithClosedRL = QS.Project.Services.ServicesConfig.CommonServices.PermissionService.ValidateUserPresetPermission("can_change_car_load_and_unload_docs", currentUserId);
            var editing = StoreDocumentHelper.CanEditDocument(WarehousePermissions.CarUnloadEdit, Entity.Warehouse);

            editing &= Entity.RouteList?.Status != RouteListStatus.Closed || hasPermitionToEditDocWithClosedRL;
            Entity.InitializeDefaultValues(UoW, new NomenclatureRepository(new NomenclatureParametersProvider()));
            yentryrefRouteList.IsEditable  = ySpecCmbWarehouses.Sensitive = ytextviewCommnet.Editable = editing;
            returnsreceptionview.Sensitive =
                hbxTareToReturn.Sensitive  =
                    nonserialequipmentreceptionview1.Sensitive =
                        defectiveitemsreceptionview1.Sensitive = editing;

            defectiveitemsreceptionview1.UoW =
                returnsreceptionview.UoW     = UoW;

            ylabelDate.Binding.AddFuncBinding(Entity, e => e.TimeStamp.ToString("g"), w => w.LabelProp).InitializeFromSource();
            ySpecCmbWarehouses.ItemsList = StoreDocumentHelper.GetRestrictedWarehousesList(UoW, WarehousePermissions.CarUnloadEdit);
            ySpecCmbWarehouses.Binding.AddBinding(Entity, e => e.Warehouse, w => w.SelectedItem).InitializeFromSource();
            ytextviewCommnet.Binding.AddBinding(Entity, e => e.Comment, w => w.Buffer.Text).InitializeFromSource();
            var filter = new RouteListsFilter(UoW);

            filter.SetAndRefilterAtOnce(x => x.RestrictedStatuses = new[] { RouteListStatus.EnRoute });
            yentryrefRouteList.RepresentationModel = new ViewModel.RouteListsVM(filter);
            yentryrefRouteList.Binding.AddBinding(Entity, e => e.RouteList, w => w.Subject).InitializeFromSource();
            yentryrefRouteList.CanEditReference = ServicesConfig.CommonServices.CurrentPermissionService.ValidatePresetPermission("can_delete");

            Entity.PropertyChanged += (sender, e) => {
                if (e.PropertyName == nameof(Entity.Warehouse))
                {
                    OnWarehouseChanged();
                }
                if (e.PropertyName == nameof(Entity.RouteList))
                {
                    UpdateWidgetsVisible();
                }
            };

            lblTareReturnedBefore.Binding.AddFuncBinding(Entity, e => e.ReturnedTareBeforeText, w => w.Text).InitializeFromSource();
            spnTareToReturn.Binding.AddBinding(Entity, e => e.TareToReturn, w => w.ValueAsInt).InitializeFromSource();

            defectiveitemsreceptionview1.Warehouse = returnsreceptionview.Warehouse = Entity.Warehouse;

            UpdateWidgetsVisible();
            buttonSave.Sensitive = editing;
            if (!editing)
            {
                HasChanges = false;
            }
            if (!UoW.IsNew)
            {
                LoadReception();
            }

            var permmissionValidator = new EntityExtendedPermissionValidator(PermissionExtensionSingletonStore.GetInstance(), EmployeeRepository);

            Entity.CanEdit = permmissionValidator.Validate(typeof(CarUnloadDocument), UserSingletonRepository.GetInstance().GetCurrentUser(UoW).Id, nameof(RetroactivelyClosePermission));
            if (!Entity.CanEdit && Entity.TimeStamp.Date != DateTime.Now.Date)
            {
                ytextviewCommnet.Binding.AddFuncBinding(Entity, e => e.CanEdit, w => w.Sensitive).InitializeFromSource();
                yentryrefRouteList.Binding.AddFuncBinding(Entity, e => e.CanEdit, w => w.Sensitive).InitializeFromSource();
                ySpecCmbWarehouses.Binding.AddFuncBinding(Entity, e => e.CanEdit, w => w.Sensitive).InitializeFromSource();
                ytextviewRouteListInfo.Binding.AddFuncBinding(Entity, e => e.CanEdit, w => w.Sensitive).InitializeFromSource();
                spnTareToReturn.Binding.AddFuncBinding(Entity, e => e.CanEdit, w => w.Sensitive).InitializeFromSource();
                defectiveitemsreceptionview1.Sensitive     = false;
                nonserialequipmentreceptionview1.Sensitive = false;
                returnsreceptionview.Sensitive             = false;

                buttonSave.Sensitive = false;
            }
            else
            {
                Entity.CanEdit = true;
            }
        }
Exemplo n.º 10
0
        protected void InitPopupActions()
        {
            var callTaskWorker = new CallTaskWorker(
                CallTaskSingletonFactory.GetInstance(),
                callTaskRepository,
                new OrderRepository(),
                new EmployeeRepository(),
                baseParametersProvider,
                commonServices.UserService,
                SingletonErrorReporter.Instance);

            PopupActionsList.Add(new JournalAction(
                                     "Закрытие МЛ",
                                     (selectedItems) => selectedItems.Any(x => closingDlgStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => closingDlgStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                var selectedNode = selectedItems.FirstOrDefault() as RouteListJournalNode;
                if (selectedNode != null && closingDlgStatuses.Contains(selectedNode.StatusEnum))
                {
                    TabParent.OpenTab(
                        DialogHelper.GenerateDialogHashName <RouteList>(selectedNode.Id),
                        () => new RouteListClosingDlg(selectedNode.Id)
                        );
                }
            }
                                     ));

            PopupActionsList.Add(new JournalAction(
                                     "Создание талона погрузки",
                                     (selectedItems) => selectedItems.Any(x => createCarLoadDocument.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => createCarLoadDocument.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                var selectedNode = selectedItems.FirstOrDefault() as RouteListJournalNode;
                if (selectedNode != null)
                {
                    TabParent.OpenTab(() => new CarLoadDocumentDlg(selectedNode.Id, null));
                }
            }
                                     ));

            PopupActionsList.Add(new JournalAction(
                                     "Создание талона разгрузки",
                                     (selectedItems) => selectedItems.Any(x => createCarUnloadDocument.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => createCarUnloadDocument.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                var selectedNode = selectedItems.FirstOrDefault() as RouteListJournalNode;
                if (selectedNode != null)
                {
                    TabParent.OpenTab(() => new CarUnloadDocumentDlg(selectedNode.Id, null));
                }
            }
                                     ));

            PopupActionsList.Add(new JournalAction(
                                     "Выдать топливо",
                                     (selectedItems) => selectedItems.Any(x => fuelIssuingStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => fuelIssuingStatuses.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                var selectedNode = selectedItems.FirstOrDefault() as RouteListJournalNode;
                if (selectedNode != null)
                {
                    var RouteList = UoW.GetById <RouteList>(selectedNode.Id);
                    TabParent.OpenTab(
                        DialogHelper.GenerateDialogHashName <RouteList>(selectedNode.Id),
                        () => new FuelDocumentViewModel(
                            RouteList,
                            commonServices,
                            subdivisionRepository,
                            new EmployeeRepository(),
                            fuelRepository,
                            NavigationManagerProvider.NavigationManager,
                            new TrackRepository(),
                            new CategoryRepository(new ParametersProvider())
                            )
                        );
                }
            }
                                     ));

            PopupActionsList.Add(new JournalAction(
                                     "Вернуть в статус Сдается",
                                     (selectedItems) => selectedItems.Any(x => canReturnToOnClosing.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) => selectedItems.Any(x => canReturnToOnClosing.Contains((x as RouteListJournalNode).StatusEnum)),
                                     (selectedItems) =>
            {
                var selectedNode      = selectedItems.FirstOrDefault() as RouteListJournalNode;
                bool isSlaveTabActive = false;
                if (selectedNode != null)
                {
                    using (var uowLocal = UnitOfWorkFactory.CreateWithoutRoot())
                    {
                        var routeList = uowLocal.Session.QueryOver <RouteList>()
                                        .Where(x => x.Id == selectedNode.Id)
                                        .List().FirstOrDefault();

                        if (canReturnToOnClosing.Contains(routeList.Status))
                        {
                            if (TabParent.FindTab(DialogHelper.GenerateDialogHashName <RouteList>(routeList.Id)) != null)
                            {
                                MessageDialogHelper.RunInfoDialog("Требуется закрыть подчиненную вкладку");
                                isSlaveTabActive = true;
                                return;
                            }
                            routeList.ChangeStatusAndCreateTask(RouteListStatus.OnClosing, callTaskWorker);
                            uowLocal.Save(routeList);
                            if (isSlaveTabActive)
                            {
                                return;
                            }
                        }
                        uowLocal.Commit();
                    }
                }
            }
                                     ));
        }
        protected void OnButtonAcceptClicked(object sender, EventArgs e)
        {
            try
            {
                SetSensetivity(false);
                var callTaskWorker = new CallTaskWorker(
                    CallTaskSingletonFactory.GetInstance(),
                    new CallTaskRepository(),
                    new OrderRepository(),
                    _employeeRepository,
                    _baseParametersProvider,
                    ServicesConfig.CommonServices.UserService,
                    ErrorReporter.Instance);

                if (Entity.Car == null)
                {
                    MessageDialogHelper.RunWarningDialog("Не заполнен автомобиль");
                    return;
                }
                StringBuilder warningMsg = new StringBuilder($"Автомобиль '{ Entity.Car.Title }':");
                if (Entity.HasOverweight())
                {
                    warningMsg.Append($"\n\t- перегружен на { Entity.Overweight() } кг");
                }

                if (Entity.HasVolumeExecess())
                {
                    warningMsg.Append($"\n\t- объём груза превышен на { Entity.VolumeExecess() } м<sup>3</sup>");
                }

                if (buttonAccept.Label == "Подтвердить" && (Entity.HasOverweight() || Entity.HasVolumeExecess()))
                {
                    if (ServicesConfig.CommonServices.CurrentPermissionService.ValidatePresetPermission("can_confirm_routelist_with_overweight"))
                    {
                        warningMsg.AppendLine("\nВы уверены что хотите подтвердить маршрутный лист?");
                        if (!MessageDialogHelper.RunQuestionDialog(warningMsg.ToString()))
                        {
                            return;
                        }
                    }
                    else
                    {
                        warningMsg.AppendLine("\nПодтвердить маршрутный лист нельзя.");
                        MessageDialogHelper.RunWarningDialog(warningMsg.ToString());
                        return;
                    }
                }

                if (Entity.Status == RouteListStatus.New)
                {
                    var valid = new QSValidator <RouteList>(Entity,
                                                            new Dictionary <object, object> {
                        { "NewStatus", RouteListStatus.Confirmed },
                        { nameof(IRouteListItemRepository), new RouteListItemRepository() }
                    });
                    if (valid.RunDlgIfNotValid((Window)this.Toplevel))
                    {
                        return;
                    }

                    Entity.ChangeStatusAndCreateTask(RouteListStatus.Confirmed, callTaskWorker);
                    //Строим маршрут для МЛ.
                    if ((!Entity.PrintsHistory?.Any() ?? true) || MessageDialogHelper.RunQuestionWithTitleDialog("Перестроить маршрут?", "Этот маршрутный лист уже был когда-то напечатан. При новом построении маршрута порядок адресов может быть другой. При продолжении обязательно перепечатайте этот МЛ.\nПерестроить маршрут?"))
                    {
                        RouteOptimizer optimizer = new RouteOptimizer(ServicesConfig.InteractiveService);
                        var            newRoute  = optimizer.RebuidOneRoute(Entity);
                        if (newRoute != null)
                        {
                            createroutelistitemsview1.DisableColumnsUpdate = true;
                            newRoute.UpdateAddressOrderInRealRoute(Entity);
                            //Рассчитываем расстояние
                            using (var calc = new RouteGeometryCalculator())
                            {
                                Entity.RecalculatePlanedDistance(calc);
                            }
                            createroutelistitemsview1.DisableColumnsUpdate = false;
                            var noPlan = Entity.Addresses.Count(x => !x.PlanTimeStart.HasValue);
                            if (noPlan > 0)
                            {
                                MessageDialogHelper.RunWarningDialog($"Для маршрута незапланировано { noPlan } адресов.");
                            }
                        }
                        else
                        {
                            MessageDialogHelper.RunWarningDialog($"Маршрут не был перестроен.");
                        }
                    }

                    Save();

                    if (Entity.GetCarVersion.IsCompanyCar && Entity.Car.CarModel.CarTypeOfUse == CarTypeOfUse.Truck && !Entity.NeedToLoad)
                    {
                        if (MessageDialogHelper.RunQuestionDialog(
                                "Маршрутный лист для транспортировки на склад, перевести машрутный лист сразу в статус '{0}'?",
                                RouteListStatus.OnClosing.GetEnumTitle()))
                        {
                            Entity.CompleteRouteAndCreateTask(_wageParameterService, callTaskWorker, _trackRepository);
                        }
                    }
                    else
                    {
                        //Проверяем нужно ли маршрутный лист грузить на складе, если нет переводим в статус в пути.
                        var needTerminal = Entity.Addresses.Any(x => x.Order.PaymentType == PaymentType.Terminal);

                        if (!Entity.NeedToLoad && !needTerminal)
                        {
                            if (MessageDialogHelper.RunQuestionDialog("Для маршрутного листа, нет необходимости грузится на складе. Перевести маршрутный лист сразу в статус '{0}'?", RouteListStatus.EnRoute.GetEnumTitle()))
                            {
                                valid = new QSValidator <RouteList>(
                                    Entity,
                                    new Dictionary <object, object>
                                {
                                    { "NewStatus", RouteListStatus.EnRoute },
                                    { nameof(IRouteListItemRepository), new RouteListItemRepository() }
                                });
                                if (!valid.IsValid)
                                {
                                    return;
                                }

                                Entity.ChangeStatusAndCreateTask(valid.RunDlgIfNotValid((Window)this.Toplevel) ? RouteListStatus.New : RouteListStatus.EnRoute, callTaskWorker);
                            }
                            else
                            {
                                Entity.ChangeStatusAndCreateTask(RouteListStatus.New, callTaskWorker);
                            }
                        }
                    }
                    Save();
                    UpdateButtonStatus();
                    createroutelistitemsview1.SubscribeOnChanges();
                    UpdateAdditionalLoadingWidgets();

                    return;
                }
                if (Entity.Status == RouteListStatus.InLoading || Entity.Status == RouteListStatus.Confirmed)
                {
                    if (_routeListRepository.GetCarLoadDocuments(UoW, Entity.Id).Any())
                    {
                        MessageDialogHelper.RunErrorDialog("Для маршрутного листа были созданы документы погрузки. Сначала необходимо удалить их.");
                    }
                    else
                    {
                        Entity.ChangeStatusAndCreateTask(RouteListStatus.New, callTaskWorker);
                    }
                    UpdateButtonStatus();
                    return;
                }
            }
            finally
            {
                SetSensetivity(true);
            }
            UpdateDlg(_isLogistican);
        }