public void MatchAndChanged(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            if (Columns.Any(x => x.DataType == DataTypeEmployee.PersonnelNumber))
            {
                dataParser.MatchByNumber(uow, UsedRows, Columns, matchSettingsViewModel, progress);
            }
            else
            {
                dataParser.MatchByName(uow, UsedRows, Columns, progress);
            }

            dataParser.FillExistEntities(uow, UsedRows, Columns, progress);
            dataParser.FindChanges(
                uow,
                UsedRows,
                Columns
                .Where(x => x.DataType != DataTypeEmployee.Unknown)
                .OrderBy(x => x.DataType)
                .ToArray(),
                progress,
                matchSettingsViewModel);
            OnPropertyChanged(nameof(DisplayRows));

            RecalculateCounters();
            CanSave = CountersViewModel.GetCount(CountersEmployee.ChangedEmployee) > 0 ||
                      CountersViewModel.GetCount(CountersEmployee.NewEmployee) > 0 ||
                      CountersViewModel.GetCount(CountersEmployee.NewPosts) > 0 ||
                      CountersViewModel.GetCount(CountersEmployee.NewDepartments) > 0 ||
                      CountersViewModel.GetCount(CountersEmployee.NewSubdivisions) > 0;
        }
示例#2
0
        public List <object> MakeToSave(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            var countColumn = Columns.First(x => x.DataType == DataTypeWorkwearItems.Count);
            var rows        = UsedRows.Where(x => !x.Skipped && x.ChangedColumns.Any()).ToList();
            var grouped     = UsedRows.Where(x => x.Operation != null)
                              .GroupBy(x => x.Employee);

            logger.Debug($"В обработке {grouped.Count()} сотрудников.");
            progress.Start(maxValue: grouped.Count(), text: "Подготовка");
            foreach (var employeeGroup in grouped)
            {
                progress.Add(text: $"Подготовка {employeeGroup.Key.ShortName}");
                var rowByItem = employeeGroup.GroupBy(x => x.WorkwearItem);
                foreach (var itemGroup in rowByItem)
                {
                    var last = itemGroup.OrderByDescending(x => x.Date).First();
                    if (itemGroup.Key.LastIssue == null || itemGroup.Key.LastIssue < last.Date)
                    {
                        itemGroup.Key.LastIssue = last.Date;
                        itemGroup.Key.Amount    = last.CellIntValue(countColumn.Index).Value;
                        itemGroup.Key.NextIssue = itemGroup.Key.ActiveNormItem.CalculateExpireDate(last.Date.Value, itemGroup.Key.Amount);
                        dataParser.ChangedEmployees.Add(employeeGroup.Key);
                    }
                }
            }

            List <object> toSave = new List <object>();

            toSave.AddRange(dataParser.UsedNomeclature.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.ChangedEmployees);
            toSave.AddRange(UsedRows.Where(x => x.Operation != null).Select(x => x.Operation));
            return(toSave);
        }
示例#3
0
        public void MatchAndChanged(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            dataParser.MatchChanges(progress, settingsWorkwearItemsViewModel, CountersViewModel, uow, UsedRows, Columns);
            OnPropertyChanged(nameof(DisplayRows));

            RecalculateCounters();
            CanSave = CountersViewModel.GetCount(CountersWorkwearItems.NewOperations) > 0;
        }
        public void MatchAndChanged(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            dataParser.MatchWithExist(uow, UsedRows, Columns, progress);
            dataParser.FindChanges(UsedRows, Columns.Where(x => x.DataType != DataTypeNorm.Unknown).ToArray());
            OnPropertyChanged(nameof(DisplayRows));

            RecalculateCounters();
            CanSave = CountersViewModel.GetCount(CountersNorm.ChangedNormItems) > 0 ||
                      CountersViewModel.GetCount(CountersNorm.NewNormItems) > 0 ||
                      CountersViewModel.GetCount(CountersNorm.NewNorms) > 0 ||
                      CountersViewModel.GetCount(CountersNorm.NewPosts) > 0 ||
                      CountersViewModel.GetCount(CountersNorm.NewSubdivisions) > 0 ||
                      CountersViewModel.GetCount(CountersNorm.NewProtectionTools) > 0;
        }
        public List <object> MakeToSave(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            var rows = UsedRows.Where(x => x.ChangedColumns.Any()).ToList();

            progress.Start(maxValue: rows.Count, text: "Подготовка");

            List <object> toSave = new List <object>();

            toSave.AddRange(dataParser.UsedSubdivisions.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedDepartment.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedPosts.Where(x => x.Id == 0));
            foreach (var row in rows)
            {
                toSave.AddRange(dataParser.PrepareToSave(uow, matchSettingsViewModel, row));
            }
            return(toSave);
        }
        public void MatchByNumber(
            IUnitOfWork uow,
            IEnumerable <SheetRowEmployee> list,
            List <ImportedColumn <DataTypeEmployee> > columns,
            SettingsMatchEmployeesViewModel settings,
            IProgressBarDisplayable progress)
        {
            progress.Start(2, text: "Сопоставление с существующими сотрудниками");
            var numberColumn =
                columns.FirstOrDefault(x => x.DataType == DataTypeEmployee.PersonnelNumber);
            var numbers = list.Select(x => GetPersonalNumber(settings, x, numberColumn.Index))
                          .Where(x => !String.IsNullOrWhiteSpace(x))
                          .Distinct().ToArray();
            var exists = uow.Session.QueryOver <EmployeeCard>()
                         .Where(x => x.PersonnelNumber.IsIn(numbers))
                         .List();

            progress.Add();
            foreach (var employee in exists)
            {
                var found = list.Where(x =>
                                       GetPersonalNumber(settings, x, numberColumn.Index) == employee.PersonnelNumber).ToArray();
                found.First().Employees.Add(employee);
            }

            //Пропускаем дубликаты Табельных номеров в файле
            progress.Add();
            var groups = list.GroupBy(x => GetPersonalNumber(settings, x, numberColumn.Index));

            foreach (var group in groups)
            {
                if (String.IsNullOrWhiteSpace(group.Key))
                {
                    //Если табельного номера нет проверяем по FIO
                    MatchByName(uow, group, columns, progress);
                }

                foreach (var item in group.Skip(1))
                {
                    item.ProgramSkipped = true;
                }
            }
            progress.Close();
        }
        public List <object> MakeToSave(IProgressBarDisplayable progress, IUnitOfWork uow)
        {
            var rows = UsedRows.Where(x => !x.Skipped && x.ChangedColumns.Any()).ToList();

            progress.Start(maxValue: rows.Count, text: "Подготовка");

            List <object> toSave = new List <object>();

            toSave.AddRange(dataParser.UsedSubdivisions.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedPosts.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedItemTypes.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedProtectionTools.Where(x => x.Id == 0));
            toSave.AddRange(dataParser.UsedNorms.Where(x => x.Id == 0));
            foreach (var row in rows)
            {
                toSave.AddRange(dataParser.PrepareToSave(uow, row));
            }
            return(toSave);
        }
        public void FillExistEntities(
            IUnitOfWork uow,
            IEnumerable <SheetRowEmployee> list,
            List <ImportedColumn <DataTypeEmployee> > columns,
            IProgressBarDisplayable progress)
        {
            progress.Start(3, text: "Загружаем подразделения");
            var subdivisionColumn = columns.FirstOrDefault(x => x.DataType == DataTypeEmployee.Subdivision);

            if (subdivisionColumn != null)
            {
                var subdivisionNames = list.Select(x => x.CellStringValue(subdivisionColumn.Index)).Distinct().ToArray();
                UsedSubdivisions.AddRange(uow.Session.QueryOver <Subdivision>()
                                          .Where(x => x.Name.IsIn(subdivisionNames))
                                          .List());
            }
            progress.Add(text: "Загружаем отделы");
            var departmentColumn = columns.FirstOrDefault(x => x.DataType == DataTypeEmployee.Department);

            if (departmentColumn != null)
            {
                var departmentNames = list.Select(x => x.CellStringValue(departmentColumn.Index)).Distinct().ToArray();
                UsedDepartment.AddRange(uow.Session.QueryOver <Department>()
                                        .Where(x => x.Name.IsIn(departmentNames))
                                        .List());
            }
            progress.Add(text: "Загружаем должности");
            var postColumn = columns.FirstOrDefault(x => x.DataType == DataTypeEmployee.Post);

            if (postColumn != null)
            {
                var postNames = list.Select(x => x.CellStringValue(postColumn.Index)).Distinct().ToArray();
                UsedPosts.AddRange(uow.Session.QueryOver <Post>()
                                   .Where(x => x.Name.IsIn(postNames))
                                   .List());
            }
            progress.Close();
        }
        public void FindChanges(
            IUnitOfWork uow,
            IEnumerable <SheetRowEmployee> list,
            ImportedColumn <DataTypeEmployee>[] meaningfulColumns,
            IProgressBarDisplayable progress,
            SettingsMatchEmployeesViewModel settings)
        {
            progress.Start(list.Count(), text: "Поиск изменений");
            foreach (var row in list)
            {
                progress.Add();
                if (row.Skipped)
                {
                    continue;
                }

                var employee  = row.Employees.FirstOrDefault();
                var rowChange = ChangeType.ChangeValue;

                if (employee == null)
                {
                    employee = new EmployeeCard {
                        Comment       = "Импортирован из Excel",
                        CreatedbyUser = userService?.GetCurrentUser(uow)
                    };
                    row.Employees.Add(employee);
                    rowChange = ChangeType.NewEntity;
                }

                foreach (var column in meaningfulColumns)
                {
                    MakeChange(settings, employee, row, column, rowChange, uow);
                }
            }
            progress.Close();
        }
示例#10
0
        public CollectiveExpenseItemsViewModel(CollectiveExpenseViewModel сollectiveExpenseViewModel, FeaturesService featuresService, INavigationManager navigation, SizeService sizeService, IDeleteEntityService deleteService, BaseParameters baseParameters, IProgressBarDisplayable globalProgress)
        {
            this.сollectiveExpenseViewModel = сollectiveExpenseViewModel ?? throw new ArgumentNullException(nameof(сollectiveExpenseViewModel));
            this.featuresService            = featuresService ?? throw new ArgumentNullException(nameof(featuresService));
            this.navigation    = navigation ?? throw new ArgumentNullException(nameof(navigation));
            SizeService        = sizeService ?? throw new ArgumentNullException(nameof(sizeService));
            this.deleteService = deleteService ?? throw new ArgumentNullException(nameof(deleteService));
            BaseParameters     = baseParameters ?? throw new ArgumentNullException(nameof(baseParameters));

            //Предварительная загрузка элементов для более быстрого открытия документа
            globalProgress.Start(2);
            var query = UoW.Session.QueryOver <CollectiveExpenseItem>()
                        .Where(x => x.Document.Id == Entity.Id)
                        .Fetch(SelectMode.ChildFetch, x => x)
                        .Fetch(SelectMode.Skip, x => x.IssuanceSheetItem)
                        .Fetch(SelectMode.Fetch, x => x.WarehouseOperation)
                        .Future();

            UoW.Session.QueryOver <CollectiveExpenseItem>()
            .Where(x => x.Document.Id == Entity.Id)
            .Fetch(SelectMode.ChildFetch, x => x)
            .Fetch(SelectMode.Skip, x => x.IssuanceSheetItem)
            .Fetch(SelectMode.Fetch, x => x.Employee)
            .Fetch(SelectMode.Fetch, x => x.Employee.WorkwearItems)
            .Future();

            query.ToList();
            globalProgress.Add();

            Entity.PrepareItems(UoW, baseParameters);
            globalProgress.Add();

            Entity.PropertyChanged += Entity_PropertyChanged;
            Entity.ObservableItems.ListContentChanged += ExpenceDoc_ObservableItems_ListContentChanged;
            OnPropertyChanged(nameof(Sum));
            globalProgress.Close();
        }
        public void MatchByName(
            IUnitOfWork uow,
            IEnumerable <SheetRowEmployee> list,
            List <ImportedColumn <DataTypeEmployee> > columns,
            IProgressBarDisplayable progress)
        {
            progress.Start(2, text: "Сопоставление с существующими сотрудниками");
            var searchValues = list.Select(x => GetFIO(x, columns))
                               .Where(fio => !String.IsNullOrEmpty(fio.LastName) && !String.IsNullOrEmpty(fio.FirstName))
                               .Select(fio => (fio.LastName + "|" + fio.FirstName).ToUpper())
                               .Distinct().ToArray();

            Console.WriteLine(((ISessionFactoryImplementor)uow.Session.SessionFactory).Dialect);
            var exists = uow.Session.QueryOver <EmployeeCard>()
                         .Where(Restrictions.In(
                                    Projections.SqlFunction(
                                        "upper", NHibernateUtil.String,
                                        ((ISessionFactoryImplementor)uow.Session.SessionFactory).Dialect is SQLiteDialect                    //Данный диалект используется в тестах.
                                                                  ?
                                        Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.String, "( ?1 || '|' || ?2)"),
                                                                NHibernateUtil.String,
                                                                Projections.Property <EmployeeCard>(x => x.LastName),
                                                                Projections.Property <EmployeeCard>(x => x.FirstName)
                                                                )
                                                        : Projections.SqlFunction(new StandardSQLFunction("CONCAT_WS"),
                                                                                  NHibernateUtil.String,
                                                                                  Projections.Constant(""),
                                                                                  Projections.Property <EmployeeCard>(x => x.LastName),
                                                                                  Projections.Constant("|"),
                                                                                  Projections.Property <EmployeeCard>(x => x.FirstName)
                                                                                  )),
                                    searchValues)).List();

            progress.Add();
            foreach (var employee in exists)
            {
                var found = list.Where(x => СompareFio(x, employee, columns)).ToArray();
                if (!found.Any())
                {
                    continue;                     //Так как в базе ищем без отчества, могут быть лишние.
                }
                found.First().Employees.Add(employee);
            }

            progress.Add();
            //Пропускаем дубликаты имен в файле
            var groups = list.GroupBy(x => GetFIO(x, columns).GetHash());

            foreach (var group in groups)
            {
                if (String.IsNullOrWhiteSpace(group.Key))
                {
                    group.First().ProgramSkipped = true;
                }

                foreach (var item in group.Skip(1))
                {
                    item.ProgramSkipped = true;
                }
            }
            progress.Close();
        }
示例#12
0
        public void MatchChanges(
            IProgressBarDisplayable progress,
            SettingsWorkwearItemsViewModel settings,
            CountersViewModel counters,
            IUnitOfWork uow,
            IEnumerable <SheetRowWorkwearItems> list,
            List <ImportedColumn <DataTypeWorkwearItems> > columns)
        {
            var personnelNumberColumn = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.PersonnelNumber);
            var protectionToolsColumn = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.ProtectionTools);
            var nomenclatureColumn    = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Nomenclature);
            var issueDateColumn       = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.IssueDate);
            var countColumn           = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Count);
            var postColumn            = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Post);
            var subdivisionColumn     = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Subdivision);
            var sizeAndGrowthColumn   = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.SizeAndGrowth);
            var sizeColumn            = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Size);
            var growthColumn          = columns.FirstOrDefault(x => x.DataType == DataTypeWorkwearItems.Growth);

            progress.Start(list.Count() * 2 + 3, text: "Загрузка сотрудников");
            var personnelNumbers = list.Select(x => GetPersonalNumber(settings, x, personnelNumberColumn.Index))
                                   .Where(x => !String.IsNullOrWhiteSpace(x)).Distinct().ToArray();

            var employees = uow.Session.QueryOver <EmployeeCard>()
                            .Where(x => x.PersonnelNumber.IsIn(personnelNumbers))
                            .Fetch(SelectMode.Fetch, x => x.WorkwearItems)
                            .List();

            foreach (var row in list)
            {
                progress.Add(text: "Сопоставление");
                row.Date = ParseDateOrNull(row.CellStringValue(issueDateColumn.Index));
                if (row.Date == null)
                {
                    row.ProgramSkipped = true;
                    row.AddColumnChange(issueDateColumn, ChangeType.ParseError);
                    continue;
                }

                if (row.CellIntValue(countColumn.Index) == null)
                {
                    row.ProgramSkipped = true;
                    row.AddColumnChange(countColumn, ChangeType.ParseError);
                    continue;
                }

                row.Employee = employees.FirstOrDefault(x => x.PersonnelNumber == GetPersonalNumber(settings, row, personnelNumberColumn.Index));
                if (row.Employee == null)
                {
                    logger.Warn(
                        $"Не найден сотрудник в табельным номером [{GetPersonalNumber(settings, row, personnelNumberColumn.Index)}]. Пропускаем.");
                    row.ProgramSkipped = true;
                    row.AddColumnChange(personnelNumberColumn, ChangeType.NotFound);
                    counters.AddCount(CountersWorkwearItems.EmployeeNotFound);
                    continue;
                }

                var protectionToolName = row.CellStringValue(protectionToolsColumn.Index);
                row.WorkwearItem = row.Employee.WorkwearItems.FirstOrDefault(x => x.ProtectionTools.Name == protectionToolName);
                if (row.WorkwearItem == null && postColumn != null && subdivisionColumn != null)
                {
                    if (!TryAddNorm(uow, row.CellStringValue(postColumn.Index),
                                    row.CellStringValue(subdivisionColumn.Index), row.Employee))
                    {
                        row.AddColumnChange(postColumn, ChangeType.NotFound);
                        row.AddColumnChange(subdivisionColumn, ChangeType.NotFound);
                    }
                    else
                    {
                        counters.AddCount(CountersWorkwearItems.EmployeesAddNorm);
                    }
                }

                if (row.WorkwearItem != null)
                {
                    continue;
                }
                row.ProgramSkipped = true;
                row.AddColumnChange(protectionToolsColumn, ChangeType.NotFound);
            }

            progress.Add(text: "Загрузка номенклатуры");
            var nomenclatureTypes = new NomenclatureTypes(uow, sizeService, true);
            var nomenclatureNames =
                list.Select(x => x.CellStringValue(nomenclatureColumn.Index)).Where(x => x != null).Distinct().ToArray();
            var nomenclatures = nomenclatureRepository.GetNomenclatureByName(uow, nomenclatureNames);

            progress.Add(text: "Загрузка операций выдачи");
            var dates = list
                        .Select(x => x.Date)
                        .Where(x => x != null)
                        .Select(x => x.Value);
            var startDate   = dates.Min();
            var endDate     = dates.Max();
            var employeeIds = list.Where(x => x.Employee != null)
                              .Select(x => x.Employee.Id).Distinct().ToArray();
            var operations = uow.Session.QueryOver <EmployeeIssueOperation>()
                             .Where(x => x.Employee.Id.IsIn(employeeIds))
                             .Where(x => x.OperationTime >= startDate)
                             .Where(x => x.OperationTime < endDate.AddDays(1))
                             .List()
                             .GroupBy(x => x.Employee);

            foreach (var row in list)
            {
                progress.Add(text: "Обработка операций выдачи");
                if (row.Skipped)
                {
                    continue;
                }
                var nomenclatureName = row.CellStringValue(nomenclatureColumn.Index);
                if (String.IsNullOrWhiteSpace(nomenclatureName))
                {
                    row.AddColumnChange(nomenclatureColumn, ChangeType.NotFound);
                    continue;
                }

                var nomenclature =
                    UsedNomeclature.FirstOrDefault(x => String.Equals(x.Name, nomenclatureName, StringComparison.CurrentCultureIgnoreCase));
                if (nomenclature == null)
                {
                    nomenclature =
                        nomenclatures.FirstOrDefault(x => String.Equals(x.Name, nomenclatureName, StringComparison.CurrentCultureIgnoreCase));
                    if (nomenclature == null)
                    {
                        nomenclature = new Nomenclature {
                            Name    = nomenclatureName,
                            Type    = row.WorkwearItem.ProtectionTools.Type,
                            Comment = "Создана при импорте выдачи из Excel",
                        };
                        nomenclature.Sex = nomenclatureTypes.ParseSex(nomenclature.Name) ?? ClothesSex.Universal;
                        row.WorkwearItem.ProtectionTools.AddNomeclature(nomenclature);
                    }
                    UsedNomeclature.Add(nomenclature);
                }

                row.Operation = operations.FirstOrDefault(group => group.Key == row.Employee)
                                ?.FirstOrDefault(x => x.OperationTime.Date == row.Date && x.Nomenclature == nomenclature);

                if (row.Operation != null)
                {
                    //TODO Обновление операций не реализовано
                    continue;
                }

                if (row.Operation != null)
                {
                    continue;
                }
                {
                    var count       = row.CellIntValue(countColumn.Index).Value;
                    var expenseDate = row.WorkwearItem.ActiveNormItem.CalculateExpireDate(row.Date.Value, count);
                    row.Operation = new EmployeeIssueOperation {
                        OperationTime    = row.Date.Value,
                        Employee         = row.Employee,
                        Issued           = count,
                        Nomenclature     = nomenclature,
                        AutoWriteoffDate = expenseDate,
                        ExpiryByNorm     = expenseDate,
                        NormItem         = row.WorkwearItem.ActiveNormItem,
                        ProtectionTools  = row.WorkwearItem.ProtectionTools,
                        Returned         = 0,
                        StartOfUse       = row.Date,
                        UseAutoWriteoff  = expenseDate != null,
                    };
                    //Обрабатываем размер.
                    if (TryParseSizeAndGrowth(uow, row, columns, out var sizeAndGrowth))
                    {
                        row.Operation.WearSize = sizeAndGrowth.Size;
                        row.Operation.Height   = sizeAndGrowth.Growth;
                        var sizeOk   = nomenclature.Type.SizeType == sizeAndGrowth.Size.SizeType;
                        var growthOk = nomenclature.Type.HeightType == sizeAndGrowth.Growth.SizeType;
                        if (sizeAndGrowthColumn != null)
                        {
                            row.ChangedColumns.Add(sizeAndGrowthColumn, new ChangeState(sizeOk && growthOk ? ChangeType.NewEntity : ChangeType.ParseError));
                        }
                        if (sizeColumn != null)
                        {
                            row.ChangedColumns.Add(sizeColumn, new ChangeState(sizeOk ? ChangeType.NewEntity : ChangeType.ParseError));
                        }
                        if (growthColumn != null)
                        {
                            row.ChangedColumns.Add(growthColumn, new ChangeState(growthOk ? ChangeType.NewEntity : ChangeType.ParseError));
                        }
                    }
                    //Проставляем размер в сотрудника.
                    if (row.Operation.Height != null)
                    {
                        var employeeSize = row.Employee.Sizes.FirstOrDefault(x => x.SizeType == row.Operation.Height.SizeType);
                        if (employeeSize is null)
                        {
                            employeeSize = new EmployeeSize
                            {
                                Size = row.Operation.Height, SizeType = row.Operation.Height.SizeType, Employee = row.Employee
                            };
                            row.Employee.Sizes.Add(employeeSize);
                        }
                        else
                        {
                            employeeSize.Size = row.Operation.Height;
                        }
                        ChangedEmployees.Add(row.Employee);
                        counters.AddCount(CountersWorkwearItems.EmployeesSetSize);
                    }
                    if (row.Operation.WearSize != null)
                    {
                        var employeeSize = row.Employee.Sizes.FirstOrDefault(x => x.SizeType == row.Operation.WearSize.SizeType);
                        if (employeeSize is null)
                        {
                            employeeSize = new EmployeeSize
                            {
                                Size = row.Operation.WearSize, SizeType = row.Operation.WearSize.SizeType, Employee = row.Employee
                            };
                            row.Employee.Sizes.Add(employeeSize);
                        }
                        else
                        {
                            employeeSize.Size = row.Operation.WearSize;
                        }
                        ChangedEmployees.Add(row.Employee);
                        counters.AddCount(CountersWorkwearItems.EmployeesSetSize);
                    }
                    var toSetChangeColumns = columns.Where(
                        x => x.DataType != DataTypeWorkwearItems.Unknown &&
                        x.DataType != DataTypeWorkwearItems.SizeAndGrowth &&
                        x.DataType != DataTypeWorkwearItems.Size &&
                        x.DataType != DataTypeWorkwearItems.Growth
                        );
                    foreach (var column in toSetChangeColumns)
                    {
                        if (!row.ChangedColumns.ContainsKey(column))
                        {
                            row.ChangedColumns.Add(column, new ChangeState(ChangeType.NewEntity));
                        }
                    }
                }
            }
            progress.Close();
        }
示例#13
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
        //Передаем лебл
        QSMain.StatusBarLabel = labelStatus;
        ProgressBar           = progresswidget1;
        this.Title            = AutofacScope.Resolve <IApplicationInfo>().ProductTitle;
        QSMain.MakeNewStatusTargetForNlog();

        QSMain.CheckServer(this);         // Проверяем настройки сервера

        NavigationManager      = AutofacScope.Resolve <TdiNavigationManager>(new TypedParameter(typeof(TdiNotebook), tdiMain));
        tdiMain.WidgetResolver = AutofacScope.Resolve <ITDIWidgetResolver>(new TypedParameter(typeof(Assembly[]), new[] { Assembly.GetAssembly(typeof(OrganizationViewModel)) }));

        var checker = new VersionCheckerService(MainClass.AppDIContainer);

        checker.RunUpdate();

        var userService  = AutofacScope.Resolve <IUserService>();
        var user         = userService.GetCurrentUser(UoW);
        var databaseInfo = AutofacScope.Resolve <IDataBaseInfo>();

        //Пока такая реализация чтобы не плодить сущностей.
        var connectionBuilder = AutofacScope.Resolve <MySqlConnectionStringBuilder>();

        if (connectionBuilder.UserID == "root")
        {
            string        Message = "Вы зашли в программу под администратором базы данных. У вас есть только возможность создавать других пользователей.";
            MessageDialog md      = new MessageDialog(this, DialogFlags.DestroyWithParent,
                                                      MessageType.Info,
                                                      ButtonsType.Ok,
                                                      Message);
            md.Run();
            md.Destroy();
            Users WinUser = new Users();
            WinUser.Show();
            WinUser.Run();
            WinUser.Destroy();
            return;
        }

        if (databaseInfo.IsDemo)
        {
            string Message = "Вы подключились к демонстрационному серверу. НЕ используете его для работы! " +
                             "Введенные данные будут доступны другим пользователям.\n\nДля работы вам необходимо " +
                             "установить собственный сервер или купить подписку на QS:Облако.";
            MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent,
                                                 MessageType.Info,
                                                 ButtonsType.Ok,
                                                 Message);
            md.Run();
            md.Destroy();
            dialogAuthenticationAction.Sensitive = false;
            ActionSN.Sensitive = false;
        }

        bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

        if (isWindows)
        {
            this.KeyReleaseEvent += ClipboardWorkaround.HandleKeyReleaseEvent;
        }
        TDIMain.MainNotebook  = tdiMain;
        this.KeyReleaseEvent += TDIMain.TDIHandleKeyReleaseEvent;

        UsersAction.Sensitive = user.IsAdmin;
        labelUser.LabelProp   = user.Name;

        //Настраиваем новости
        var feeds = new List <NewsFeed>()
        {
            new NewsFeed("workwearsite", "Новости программы", "http://workwear.qsolution.ru/?feed=atom")
        };
        var reader = AutofacScope.Resolve <FeedReader>(new TypedParameter(typeof(List <NewsFeed>), feeds));

        reader.LoadReadFeed();
        var newsmenuModel = new QS.NewsFeed.ViewModels.NewsMenuViewModel(reader);
        var newsmenu      = new NewsMenuView(newsmenuModel);

        menubar1.Add(newsmenu);
        newsmenuModel.LoadFeed();

        ReadUserSettings();

        var EntityAutocompleteSelector = new JournalViewModelAutocompleteSelector <EmployeeCard, EmployeeJournalViewModel>(UoW, AutofacScope);

        entitySearchEmployee.ViewModel = new EntitySearchViewModel <EmployeeCard>(EntityAutocompleteSelector);
        entitySearchEmployee.ViewModel.EntitySelected += SearchEmployee_EntitySelected;

        NavigationManager                  = AutofacScope.Resolve <TdiNavigationManager>(new TypedParameter(typeof(TdiNotebook), tdiMain));
        tdiMain.WidgetResolver             = AutofacScope.Resolve <ITDIWidgetResolver>(new TypedParameter(typeof(Assembly[]), new[] { Assembly.GetAssembly(typeof(OrganizationViewModel)) }));
        NavigationManager.ViewModelOpened += NavigationManager_ViewModelOpened;

        #region Проверки и исправления базы
        //Если склады отсутствуют создаём новый, так как для версий ниже предприятия пользователь его создать не сможет.
        if (UoW.GetAll <Warehouse>().Count() == 0)
        {
            CreateDefaultWarehouse();
        }
        //Если у базы еще нет Guid создаем его.
        using (var localScope = MainClass.AppDIContainer.BeginLifetimeScope()) {
            var baseParam = localScope.Resolve <BaseParameters>();
            if (baseParam.Dynamic.BaseGuid == null)
            {
                baseParam.Dynamic.BaseGuid = Guid.NewGuid();
            }
        }
        #endregion

        FeaturesService = AutofacScope.Resolve <FeaturesService>();
        DisableFeatures();

        HistoryMain.Enable();
    }