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); }
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 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 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(); }
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(); }
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(); }
public int ReplaceEverywhere <TEntity>(IUnitOfWork uow, TEntity fromE, TEntity toE) where TEntity : IDomainObject { int replacedLinks = 0; if (fromE == null) { throw new ArgumentNullException(nameof(fromE)); } if (toE == null) { throw new ArgumentNullException(nameof(toE)); } if (fromE.Id == 0) { throw new ArgumentException("Сущность должна уже иметь ID", nameof(fromE)); } if (toE.Id == 0) { throw new ArgumentException("Сущность должна уже иметь ID", nameof(toE)); } var delConfig = configuration.GetDeleteInfo <TEntity>(); if (delConfig == null) { throw new InvalidOperationException($"Конфигурация удаления для типа {typeof(TEntity)} не найдена."); } if (!(delConfig is IDeleteInfoHibernate)) { throw new NotSupportedException($"Поддерживаются только конфигурации удаления Hibernate."); } Progress?.Start(delConfig.DeleteItems.Count + delConfig.ClearItems.Count + delConfig.RemoveFromItems.Count); foreach (var depend in delConfig.DeleteItems) { Progress?.Add(); if (String.IsNullOrEmpty(depend.PropertyName)) { continue; } var propInfo = depend.ObjectClass.GetProperty(depend.PropertyName); foreach (var item in GetLinkedEntities(uow, depend, fromE)) { propInfo.SetValue(item, toE, null); uow.TrySave(item); replacedLinks++; } } foreach (var depend in delConfig.ClearItems) { Progress?.Add(); var propInfo = depend.ObjectClass.GetProperty(depend.PropertyName); foreach (var item in GetLinkedEntities(uow, depend, fromE)) { propInfo.SetValue(item, toE, null); uow.TrySave(item); replacedLinks++; } } foreach (var depend in delConfig.RemoveFromItems) { Progress?.Add(); var collPropInfo = depend.ObjectClass.GetProperty(depend.CollectionName); foreach (var item in GetLinkedEntities(uow, depend, fromE)) { var coll = (collPropInfo.GetValue(item) as IList); var replaced = coll.Cast <IDomainObject>().First(x => x.Id == fromE.Id); var exist = coll.Cast <IDomainObject>().FirstOrDefault(x => x.Id == toE.Id); //Это правило используется для коллекций со связью многие к многим. Объект на который заменяем уже может быть добавлен в коллекцию, добавлять его повторно не имеет смысла. coll.Remove(replaced); if (exist == null) { coll.Add(toE); } uow.TrySave(item); replacedLinks++; } } Progress?.Close(); return(replacedLinks); }