Ejemplo n.º 1
0
        public RouteListWorkingJournalViewModel(
            RouteListJournalFilterViewModel filterViewModel,
            IUnitOfWorkFactory unitOfWorkFactory,
            ICommonServices commonServices,
            IRouteListRepository routeListRepository,
            IFuelRepository fuelRepository,
            ICallTaskRepository callTaskRepository,
            BaseParametersProvider baseParametersProvider,
            IExpenseParametersProvider expenseParametersProvider,
            ISubdivisionRepository subdivisionRepository,
            IAccountableDebtsRepository accountableDebtsRepository,
            IGtkTabsOpener gtkTabsOpener)
            : base(filterViewModel, unitOfWorkFactory, commonServices)
        {
            TabName = "Работа кассы с МЛ";

            _routeListRepository        = routeListRepository ?? throw new ArgumentNullException(nameof(routeListRepository));
            _fuelRepository             = fuelRepository ?? throw new ArgumentNullException(nameof(fuelRepository));
            _callTaskRepository         = callTaskRepository ?? throw new ArgumentNullException(nameof(callTaskRepository));
            _baseParametersProvider     = baseParametersProvider ?? throw new ArgumentNullException(nameof(baseParametersProvider));
            _expenseParametersProvider  = expenseParametersProvider ?? throw new ArgumentNullException(nameof(expenseParametersProvider));
            _subdivisionRepository      = subdivisionRepository ?? throw new ArgumentNullException(nameof(subdivisionRepository));
            _accountableDebtsRepository = accountableDebtsRepository ?? throw new ArgumentNullException(nameof(accountableDebtsRepository));
            _gtkTabsOpener = gtkTabsOpener ?? throw new ArgumentNullException(nameof(gtkTabsOpener));

            UseSlider = false;

            NotifyConfiguration.Enable();
            NotifyConfiguration.Instance.BatchSubscribeOnEntity <RouteList>(OnRouteListChanged);

            InitPopupActions();
        }
Ejemplo n.º 2
0
        public ReturnsReceptionView()
        {
            var baseParameters = new BaseParametersProvider(new ParametersProvider());

            _terminalNomenclatureProvider = baseParameters;
            var routeListRepository = new RouteListRepository(new StockRepository(), baseParameters);

            _carLoadDocumentRepository = new CarLoadDocumentRepository(routeListRepository);
            _carUnloadRepository       = new CarUnloadRepository();
            _subdivisionRepository     = new SubdivisionRepository(new ParametersProvider());

            Build();

            ytreeReturns.ColumnsConfig = Gamma.GtkWidgets.ColumnsConfigFactory.Create <ReceptionItemNode>()
                                         .AddColumn("Номенклатура").AddTextRenderer(node => node.Name)
                                         .AddColumn("№ Кулера").AddTextRenderer(node => node.Redhead)
                                         .AddSetter((cell, node) => cell.Editable = node.NomenclatureCategory == NomenclatureCategory.additional)
                                         .AddColumn("Кол-во")
                                         .AddNumericRenderer(node => node.Amount, false)
                                         .Adjustment(new Gtk.Adjustment(0, 0, 9999, 1, 100, 0))
                                         .AddSetter((cell, node) => cell.Editable = node.EquipmentId == 0)
                                         .AddSetter((cell, node) => CalculateAmount(node))
                                         .AddColumn("Ожидаемое кол-во")
                                         .AddNumericRenderer(node => node.ExpectedAmount, false)
                                         .AddColumn("")
                                         .Finish();

            ytreeReturns.ItemsDataSource = ReceptionReturnsList;
        }
Ejemplo n.º 3
0
        public RouteListWorkingJournalViewModel(
            RouteListJournalFilterViewModel filterViewModel,
            IUnitOfWorkFactory unitOfWorkFactory,
            ICommonServices commonServices,
            IRouteListRepository routeListRepository,
            FuelRepository fuelRepository,
            CallTaskRepository callTaskRepository,
            BaseParametersProvider baseParametersProvider,
            SubdivisionRepository subdivisionRepository) :
            base(filterViewModel, unitOfWorkFactory, commonServices)
        {
            TabName = "Работа кассы с МЛ";

            this.routeListRepository    = routeListRepository;
            this.fuelRepository         = fuelRepository;
            this.callTaskRepository     = callTaskRepository;
            this.baseParametersProvider = baseParametersProvider;
            this.subdivisionRepository  = subdivisionRepository;

            UseSlider = false;

            NotifyConfiguration.Enable();
            NotifyConfiguration.Instance.BatchSubscribeOnEntity <RouteList>(OnRouteListChanged);

            InitPopupActions();
        }
Ejemplo n.º 4
0
        protected void OnButtonCreateBottleOperationsClicked(object sender, EventArgs e)
        {
            IStandartNomenclatures standartNomenclatures = new BaseParametersProvider(new ParametersProvider());

            orders.ForEach(x => x.UpdateBottlesMovementOperationWithoutDelivery(uow, standartNomenclatures, new RouteListItemRepository(), new CashRepository()));
            if (uow.HasChanges && MessageDialogHelper.RunQuestionDialog(
                    "Создано \"{0}\" недостающих операций передвижения бутылей, сохранить изменения?",
                    orders.Count(x => x.BottlesMovementOperation != null)))
            {
                uow.Commit();
            }
            OnCloseTab(false);
        }
Ejemplo n.º 5
0
    void ActionRouteListAddressesTransferring_Activated(object sender, System.EventArgs e)
    {
        var employeeNomenclatureMovementRepository = new EmployeeNomenclatureMovementRepository();
        var terminalNomenclatureProvider           = new BaseParametersProvider();

        tdiMain.OpenTab(
            TdiTabBase.GenerateHashName <RouteListAddressesTransferringDlg>(),
            () => new RouteListAddressesTransferringDlg(
                employeeNomenclatureMovementRepository,
                terminalNomenclatureProvider
                )
            );
    }
Ejemplo n.º 6
0
        public static void Init()
        {
            if (IsInitialized)
            {
                return;
            }

            IMailjetParametersProvider parametersProvider = new BaseParametersProvider(new ParametersProvider());

            try {
                SetLoginSetting(parametersProvider.MailjetUserId, parametersProvider.MailjetSecretKey);
            } catch (Exception ex) {
                logger.Error(ex);
            }
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public bool IsTerminalRequired(IUnitOfWork uow, int routeListId)
        {
            CarLoadDocumentItem carLoadDocumentItemAlias = null;

            var terminalId = new BaseParametersProvider().GetNomenclatureIdForTerminal;
            var routeList  = uow.Query <RouteList>().Where(x => x.Id == routeListId).SingleOrDefault();
            var anyAddressesRequireTermanal = routeList.Addresses.Any(x => x.Order.PaymentType == PaymentType.Terminal);

            var loadedTerminal = uow.Session.QueryOver <CarLoadDocument>()
                                 .JoinAlias(x => x.Items, () => carLoadDocumentItemAlias)
                                 .Where(() => carLoadDocumentItemAlias.Nomenclature.Id == terminalId)
                                 .And(() => carLoadDocumentItemAlias.Amount > 0)
                                 .And(x => x.RouteList.Id == routeList.Id)
                                 .List();

            return(anyAddressesRequireTermanal && !loadedTerminal.Any());
        }
Ejemplo n.º 9
0
        public GoodsInRouteListResultWithSpecialRequirements GetTerminalInRLWithSpecialRequirements(IUnitOfWork uow, RouteList routeList, Warehouse warehouse = null)
        {
            CarLoadDocumentItem carLoadDocumentItemAlias = null;

            var terminalId   = new BaseParametersProvider().GetNomenclatureIdForTerminal;
            var needTerminal = routeList.Addresses.Any(x => x.Order.PaymentType == PaymentType.Terminal);

            var loadedTerminal = uow.Session.QueryOver <CarLoadDocument>()
                                 .JoinAlias(x => x.Items, () => carLoadDocumentItemAlias)
                                 .Where(() => carLoadDocumentItemAlias.Nomenclature.Id == terminalId)
                                 .And(x => x.RouteList.Id == routeList.Id)
                                 .List();

            if (needTerminal || loadedTerminal.Any())
            {
                var terminal = uow.GetById <Nomenclature>(terminalId);
                int amount   = 1;

                if (warehouse == null)
                {
                    return(new GoodsInRouteListResultWithSpecialRequirements
                    {
                        NomenclatureName = terminal.Name,
                        NomenclatureId = terminalId,
                        Amount = amount
                    });
                }


                if (StockRepository.NomenclatureInStock(uow, warehouse.Id, new int[] { terminal.Id }).Any())
                {
                    return(new GoodsInRouteListResultWithSpecialRequirements
                    {
                        NomenclatureName = terminal.Name,
                        NomenclatureId = terminalId,
                        Amount = amount
                    });
                }
            }

            return(null);
        }
Ejemplo n.º 10
0
        public MangoManager(Gtk.Action toolbarIcon,
                            IUnitOfWorkFactory unitOfWorkFactory,
                            IEmployeeService employeeService,
                            IUserService userService,
                            INavigationManager navigation,
                            BaseParametersProvider parameters)
        {
            this.toolbarIcon       = toolbarIcon;
            this.unitOfWorkFactory = unitOfWorkFactory ?? throw new ArgumentNullException(nameof(unitOfWorkFactory));
            this.employeeService   = employeeService ?? throw new ArgumentNullException(nameof(employeeService));
            this.userService       = userService ?? throw new ArgumentNullException(nameof(userService));
            this.navigation        = navigation ?? throw new ArgumentNullException(nameof(navigation));
            _mangoController       = new MangoController(parameters.VpbxApiKey, parameters.VpbxApiSalt);

            timer = GLib.Timeout.Add(1000, new GLib.TimeoutHandler(HandleTimeoutHandler));
            toolbarIcon.Activated += ToolbarIcon_Activated;
            var userId = this.userService.CurrentUserId;

            NotifyConfiguration.Instance.BatchSubscribe(OnUserChanged).IfEntity <Employee>()
            .AndWhere(x => x.User != null && x.User.Id == userId);
        }
Ejemplo n.º 11
0
        public PotentialFreePromosetsReport()
        {
            this.Build();
            UoW = UnitOfWorkFactory.CreateWithoutRoot();

            buttonCreateReport.Clicked += (sender, e) => OnUpdate(false);
            IPotentialFreePromosetsReportDefaultsProvider defaultsValuesProvider = new BaseParametersProvider();

            ytreeview1.ColumnsConfig = FluentColumnsConfig <PromosetReportNode> .Create()
                                       .AddColumn("Выбрать").AddToggleRenderer(x => x.Active)
                                       .AddColumn("Промонабор").AddTextRenderer(x => x.Name)
                                       .Finish();

            PromosetReportNode resultAlias = null;

            promotionalSets = UoW.Session.QueryOver <PromotionalSet>()
                              .SelectList(list => list
                                          .Select(x => x.Id).WithAlias(() => resultAlias.Id)
                                          .Select(x => x.Name).WithAlias(() => resultAlias.Name)
                                          )
                              .TransformUsing(Transformers.AliasToBean <PromosetReportNode>())
                              .List <PromosetReportNode>();

            var defaultValues = defaultsValuesProvider.GetDefaultActivePromosets();

            if (defaultValues.Any())
            {
                foreach (var ps in promotionalSets)
                {
                    if (defaultValues.Contains(ps.Id))
                    {
                        ps.Active = true;
                    }
                }
            }

            ytreeview1.ItemsDataSource = promotionalSets;
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            SmsRuConfiguration smsRuConfig;

            try {
                var builder = new ConfigurationBuilder()
                              .AddIniFile(configFile, optional: false);

                var configuration = builder.Build();

                var serviceSection = configuration.GetSection("Service");
                serviceHostName = serviceSection["service_host_name"];
                servicePort     = serviceSection["service_port"];

                var mysqlSection = configuration.GetSection("Mysql");
                mysqlServerHostName = mysqlSection["mysql_server_host_name"];
                mysqlServerPort     = mysqlSection["mysql_server_port"];
                mysqlUser           = mysqlSection["mysql_user"];
                mysqlPassword       = mysqlSection["mysql_password"];
                mysqlDatabase       = mysqlSection["mysql_database"];

                var smsRuSection = configuration.GetSection("SmsRu");

                smsRuConfig =
                    new SmsRuConfiguration(
                        smsRuSection["login"],
                        smsRuSection["password"],
                        smsRuSection["appId"],
                        smsRuSection["partnerId"],
                        smsRuSection["email"],
                        smsRuSection["smsNumberFrom"],
                        smsRuSection["smtpLogin"],
                        smsRuSection["smtpPassword"],
                        smsRuSection["smtpServer"],
                        int.Parse(smsRuSection["smtpPort"]),
                        bool.Parse(smsRuSection["smtpUseSSL"]),
                        bool.Parse(smsRuSection["translit"]),
                        bool.Parse(smsRuSection["test"])
                        );
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            try {
                var conStrBuilder = new MySqlConnectionStringBuilder();
                conStrBuilder.Server   = mysqlServerHostName;
                conStrBuilder.Port     = uint.Parse(mysqlServerPort);
                conStrBuilder.Database = mysqlDatabase;
                conStrBuilder.UserID   = mysqlUser;
                conStrBuilder.Password = mysqlPassword;
                conStrBuilder.SslMode  = MySqlSslMode.None;

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                                .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(db_config,
                                       new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();

                ISmsNotificationRepository smsNotificationRepository = new SmsNotificationRepository();

                SmsRuSendController smsSender = new SmsRuSendController(smsRuConfig);

                newClientInformer = new NewClientSmsInformer(smsSender, smsNotificationRepository);
                newClientInformer.Start();

                BaseParametersProvider parametersProvider = new BaseParametersProvider();
                LowBalanceNotifier     lowBalanceNotifier = new LowBalanceNotifier(smsSender, smsSender, parametersProvider);
                lowBalanceNotifier.Start();

                SmsInformerInstanceProvider serviceStatusInstanceProvider = new SmsInformerInstanceProvider(
                    smsNotificationRepository,
                    new BaseParametersProvider()
                    );
                WebServiceHost smsInformerStatus = new SmsInformerServiceHost(serviceStatusInstanceProvider);
                smsInformerStatus.AddServiceEndpoint(
                    typeof(ISmsInformerService),
                    new WebHttpBinding(),
                    String.Format("http://{0}:{1}/SmsInformer", serviceHostName, servicePort)
                    );
                smsInformerStatus.Open();
                logger.Info("Запущена служба мониторинга отправки смс уведомлений");

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception ex) {
                logger.Fatal(ex);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
Ejemplo n.º 13
0
        public static void Main(string[] args)
        {
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("ru-RU");
            Application.Init();
            QSMain.GuiThread = System.Threading.Thread.CurrentThread;
            applicationInfo  = new ApplicationVersionInfo();

            #region Первоначальная настройка обработки ошибок
            SingletonErrorReporter.Initialize(ReportWorker.GetReportService(), applicationInfo, new LogService(), null, false, null);
            var errorMessageModelFactoryWithoutUserService = new DefaultErrorMessageModelFactory(SingletonErrorReporter.Instance, null, null);
            var exceptionHandler = new DefaultUnhandledExceptionHandler(errorMessageModelFactoryWithoutUserService, applicationInfo);

            exceptionHandler.SubscribeToUnhandledExceptions();
            exceptionHandler.GuiThread = System.Threading.Thread.CurrentThread;
            #endregion

            //FIXME Удалить после того как будет удалена зависимость от библиотеки QSProjectLib
            QSMain.ProjectPermission = new System.Collections.Generic.Dictionary <string, UserPermission>();

            CreateProjectParam();
            ConfigureViewModelWidgetResolver();
            ConfigureJournalColumnsConfigs();

            QSMain.SetupFromArgs(args);
            QS.Project.Search.GtkUI.SearchView.QueryDelay = 1500;

            Gtk.Settings.Default.SetLongProperty("gtk-button-images", 1, "");
            // Создаем окно входа
            Login LoginDialog = new Login();
            LoginDialog.Logo = Gdk.Pixbuf.LoadFromResource("Vodovoz.icons.logo.png");
            LoginDialog.SetDefaultNames("Vodovoz");
            LoginDialog.DefaultLogin  = "******";
            LoginDialog.DefaultServer = "sql.vod.qsolution.ru";
            LoginDialog.UpdateFromGConf();

            ResponseType LoginResult;
            LoginResult = (ResponseType)LoginDialog.Run();
            if (LoginResult == ResponseType.DeleteEvent || LoginResult == ResponseType.Cancel)
            {
                return;
            }

            LoginDialog.Destroy();

            PerformanceHelper.StartMeasurement("Замер запуска приложения");
            GetPermissionsSettings();
            //Настройка базы
            CreateBaseConfig();
            PerformanceHelper.AddTimePoint(logger, "Закончена настройка базы");
            VodovozGtkServicesConfig.CreateVodovozDefaultServices();
            ParametersProvider.Instance.RefreshParameters();

            #region Настройка обработки ошибок c параметрами из базы и сервисами
            var baseParameters = new BaseParametersProvider();
            SingletonErrorReporter.Initialize(
                ReportWorker.GetReportService(),
                applicationInfo,
                new LogService(),
                LoginDialog.BaseName,
                LoginDialog.BaseName == baseParameters.GetDefaultBaseForErrorSend(),
                baseParameters.GetRowCountForErrorLog()
                );

            var errorMessageModelFactoryWithUserService = new DefaultErrorMessageModelFactory(SingletonErrorReporter.Instance, ServicesConfig.UserService, UnitOfWorkFactory.GetDefaultFactory);
            exceptionHandler.InteractiveService       = ServicesConfig.InteractiveService;
            exceptionHandler.ErrorMessageModelFactory = errorMessageModelFactoryWithUserService;
            //Настройка обычных обработчиков ошибок.
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.MySqlException1055OnlyFullGroupBy);
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.MySqlException1366IncorrectStringValue);
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.NHibernateFlushAfterException);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.NHibernateStaleObjectStateExceptionHandler);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.MySqlExceptionConnectionTimeoutHandler);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.MySqlExceptionAuthHandler);

            #endregion

            //Настройка карты
            GMapProvider.UserAgent = String.Format("{0}/{1} used GMap.Net/{2} ({3})",
                                                   applicationInfo.ProductName,
                                                   applicationInfo.Version.VersionToShortString(),
                                                   Assembly.GetAssembly(typeof(GMapProvider)).GetName().Version.VersionToShortString(),
                                                   Environment.OSVersion.VersionString
                                                   );
            GMapProvider.Language = GMap.NET.LanguageType.Russian;
            PerformanceHelper.AddTimePoint(logger, "Закончена настройка карты.");

            DatePicker.CalendarFontSize      = 16;
            DateRangePicker.CalendarFontSize = 16;

            OsmWorker.ServiceHost = "osm.vod.qsolution.ru";
            OsmWorker.ServicePort = 7073;

            QS.Osm.Osrm.OsrmMain.ServerUrl = "http://osrm.vod.qsolution.ru:5000";

            PerformanceHelper.StartPointsGroup("Главное окно");

            var baseVersionChecker = new CheckBaseVersion(applicationInfo, new ParametersService(QS.Project.DB.Connection.ConnectionDB));
            if (baseVersionChecker.Check())
            {
                ServicesConfig.CommonServices.InteractiveService.ShowMessage(ImportanceLevel.Warning, baseVersionChecker.TextMessage, "Несовпадение версии");
                return;
            }
            QSMain.CheckServer(null);             // Проверяем настройки сервера

            PerformanceHelper.AddTimePoint("Закончена загрузка параметров базы и проверка версии.");

            AutofacClassConfig();
            PerformanceHelper.AddTimePoint("Закончена настройка AutoFac.");
            if (QSMain.User.Login == "root")
            {
                string        Message = "Вы зашли в программу под администратором базы данных. У вас есть только возможность создавать других пользователей.";
                MessageDialog md      = new MessageDialog(null, DialogFlags.Modal,
                                                          MessageType.Info,
                                                          ButtonsType.Ok,
                                                          Message);
                md.Run();
                md.Destroy();
                UsersDialog usersDlg = new UsersDialog(ServicesConfig.InteractiveService);
                usersDlg.Show();
                usersDlg.Run();
                usersDlg.Destroy();
                return;
            }
            else
            {
                if (ChangePassword(LoginDialog.BaseName) && CanLogin())
                {
                    StartMainWindow(LoginDialog.BaseName);
                }
                else
                {
                    return;
                }
            }

            PerformanceHelper.EndPointsGroup();

            PerformanceHelper.AddTimePoint(logger, "Закончен старт SAAS. Конец загрузки.");

            QSSaaS.Session.StartSessionRefresh();

            PerformanceHelper.AddTimePoint(logger, "Закончен старт SAAS. Конец загрузки.");
            PerformanceHelper.Main.PrintAllPoints(logger);

            Application.Run();
            QSSaaS.Session.StopSessionRefresh();
            ClearTempDir();
        }
Ejemplo n.º 14
0
        public EmployeeViewModel(
            IAuthorizationService authorizationService,
            IEmployeeWageParametersFactory employeeWageParametersFactory,
            IEmployeeJournalFactory employeeJournalFactory,
            ISubdivisionJournalFactory subdivisionJournalFactory,
            IEmployeePostsJournalFactory employeePostsJournalFactory,
            ICashDistributionCommonOrganisationProvider commonOrganisationProvider,
            ISubdivisionService subdivisionService,
            IEmailServiceSettingAdapter emailServiceSettingAdapter,
            IWageCalculationRepository wageCalculationRepository,
            IEmployeeRepository employeeRepository,
            IUnitOfWorkGeneric <Employee> uowGeneric,
            ICommonServices commonServices,
            IValidationContextFactory validationContextFactory,
            IPhonesViewModelFactory phonesViewModelFactory,
            IWarehouseRepository warehouseRepository,
            IRouteListRepository routeListRepository,
            DriverApiUserRegisterEndpoint driverApiUserRegisterEndpoint,
            UserSettings userSettings,
            IUserRepository userRepository,
            BaseParametersProvider baseParametersProvider,
            bool traineeToEmployee = false,
            INavigationManager navigationManager = null
            ) : base(commonServices?.InteractiveService, navigationManager)
        {
            _authorizationService         = authorizationService ?? throw new ArgumentNullException(nameof(authorizationService));
            EmployeeWageParametersFactory =
                employeeWageParametersFactory ?? throw new ArgumentNullException(nameof(employeeWageParametersFactory));
            EmployeeJournalFactory      = employeeJournalFactory ?? throw new ArgumentNullException(nameof(employeeJournalFactory));
            EmployeePostsJournalFactory = employeePostsJournalFactory ?? throw new ArgumentNullException(nameof(employeePostsJournalFactory));
            SubdivisionJournalFactory   = subdivisionJournalFactory ?? throw new ArgumentNullException(nameof(subdivisionJournalFactory));

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

            _subdivisionService            = subdivisionService ?? throw new ArgumentNullException(nameof(subdivisionService));
            _emailServiceSettingAdapter    = emailServiceSettingAdapter ?? throw new ArgumentNullException(nameof(emailServiceSettingAdapter));
            _wageCalculationRepository     = wageCalculationRepository ?? throw new ArgumentNullException(nameof(wageCalculationRepository));
            _employeeRepository            = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository));
            _warehouseRepository           = warehouseRepository ?? throw new ArgumentNullException(nameof(warehouseRepository));
            _routeListRepository           = routeListRepository ?? throw new ArgumentNullException(nameof(routeListRepository));
            _driverApiUserRegisterEndpoint = driverApiUserRegisterEndpoint ?? throw new ArgumentNullException(nameof(driverApiUserRegisterEndpoint));
            _userSettings           = userSettings ?? throw new ArgumentNullException(nameof(userSettings));
            UoWGeneric              = uowGeneric ?? throw new ArgumentNullException(nameof(uowGeneric));
            _commonServices         = commonServices ?? throw new ArgumentNullException(nameof(commonServices));
            _userRepository         = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
            _baseParametersProvider = baseParametersProvider ?? throw new ArgumentNullException(nameof(baseParametersProvider));

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

            ConfigureValidationContext(validationContextFactory);

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

            PhonesViewModel = phonesViewModelFactory.CreateNewPhonesViewModel(UoW);

            if (Entity.Id == 0)
            {
                Entity.OrganisationForSalary = commonOrganisationProvider.GetCommonOrganisation(UoW);
                TabName = "Новый сотрудник";
            }
            else
            {
                TabName = Entity.GetPersonNameWithInitials();
            }

            if (Entity.Phones == null)
            {
                Entity.Phones = new List <Phone>();
            }

            SetPermissions();

            Entity.PropertyChanged += OnEntityPropertyChanged;

            organizations = UoW.GetAll <Organization>().ToList();
            FillHiddenCategories(traineeToEmployee);

            CanRegisterMobileUser = string.IsNullOrWhiteSpace(Entity.AndroidLogin) && string.IsNullOrWhiteSpace(Entity.AndroidPassword);

            var permissionResult =
                _commonServices.PermissionService.ValidateUserPermission(typeof(Employee), _commonServices.UserService.CurrentUserId);

            if (!permissionResult.CanRead)
            {
                AbortOpening(PermissionsSettings.GetEntityReadValidateResult(typeof(Employee)));
            }
        }
        public override bool IsValidForOrder(Order order)
        {
            if (!IsForZeroDebt)
            {
                return(true);
            }

            var forfeitId = new BaseParametersProvider().GetForfeitId();

            BottlesRepository bottlesRepository = new BottlesRepository();

            BottlesMovementOperation bottlesMovementAlias = null;
            Order orderAlias = null;

            //Долг клиента
            var counterpartyDebtQuery = order.UoW.Session.QueryOver <BottlesMovementOperation>(() => bottlesMovementAlias)
                                        .Where(() => bottlesMovementAlias.DeliveryPoint == null)
                                        .Where(() => bottlesMovementAlias.Counterparty.Id == order.Client.Id)
                                        .Select(
                Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int32, "( ?2 - ?1 )"),
                                        NHibernateUtil.Int32, new IProjection[] {
                Projections.Sum(() => bottlesMovementAlias.Returned),
                Projections.Sum(() => bottlesMovementAlias.Delivered)
            }
                                        )).SingleOrDefault <int>();

            if (counterpartyDebtQuery != 0)
            {
                return(false);
            }

            //Долг по точкам доставки
            foreach (var deliveryPoint in order.Client.DeliveryPoints)
            {
                if (bottlesRepository.GetBottlesAtDeliveryPoint(order.UoW, deliveryPoint) != 0)
                {
                    return(false);
                }
            }

            //Возврат бутылей и(ничего или возврат залога или неустойка)
            var orders1 = order.UoW.Session.QueryOver(() => orderAlias)
                          .Where(() => orderAlias.Client.Id == order.Client.Id)
                          .Where(() => orderAlias.OrderStatus == OrderStatus.Closed)
                          .Where(() => orderAlias.BottlesReturn != 0)
                          .List <Order>();

            if (orders1.Count == 0)
            {
                return(false);
            }

            var orders2 = new List <Order>();

            foreach (var o in orders1)
            {
                if (o.OrderDepositItems != null && o.OrderItems == null)
                {
                    orders2.Add(o);
                }
                if (o.OrderItems.All(i => i.Nomenclature.Id == forfeitId))
                {
                    orders2.Add(o);
                }
                if (o.OrderItems == null)
                {
                    orders2.Add(o);
                }
            }

            if (orders2.Count == 0)
            {
                return(false);
            }

            //Ввод остатков
            foreach (var o in orders2)
            {
                if (o.DeliveryPoint == null)
                {
                    continue;
                }
                if (o.DeliveryPoint.HaveResidue.HasValue)
                {
                    if (!o.DeliveryPoint.HaveResidue.Value)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }