/// <summary> /// The get pfr statistic. /// </summary> /// <param name="batches"> /// The batches. /// </param> /// <returns> /// The <see cref="PfrStatisticInfo"/> . /// </returns> private PfrStatisticInfo GetPfrStatistic(IEnumerable <Batch> batches) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var result = new PfrStatisticInfo(); foreach (var batch in batches) { var message = batch.Messages.FirstOrDefault(); if (message != null) { var countQr = session.QueryOver <QueryResponse>().Where(x => x.Message.Id == message.Id).RowCount(); result.TotalRecordCount += countQr; EmploymentHistory employmentHistory = null; InsuredPerson person = null; var foundRecordCount = session.QueryOver <QueryResponse>() .JoinAlias(x => x.EmploymentHistories, () => employmentHistory) .Where(x => x.Message.Id == message.Id) .RowCount(); var insuredRecordCount = session.QueryOver <QueryResponse>() .JoinAlias(x => x.EmploymentHistories, () => employmentHistory) .JoinAlias(x => employmentHistory.InsuredPerson, () => person) .Where(x => x.Message.Id == message.Id) .And(x => person.Status.Id == StatusPerson.Active) .RowCount(); var employedRecordCount = session.QueryOver <QueryResponse>() .JoinAlias(x => x.EmploymentHistories, () => employmentHistory) .JoinAlias(x => employmentHistory.InsuredPerson, () => person) .Where(x => x.Message.Id == message.Id) .And(x => person.Status.Id == StatusPerson.Active) .And(x => employmentHistory.Employment) .RowCount(); result.NotFoundRecordCount += countQr - foundRecordCount; result.InsuredRecordCount += insuredRecordCount; result.EmployedRecordCount += employedRecordCount; switch (batch.Type.Id) { case ExchangeFileType.PfrData: result.FoundByDataRecordCount += foundRecordCount; break; case ExchangeFileType.PfrSnils: result.FoundBySnilsRecordCount += foundRecordCount; break; } } } return(result); }
/// <summary> /// The get insured person by statement. /// </summary> /// <param name="statement"> /// The statement. /// </param> /// <param name="keys"> /// The keys. /// </param> /// <returns> /// The <see cref="InsuredPerson"/>. /// </returns> public InsuredPerson GetInsuredPersonByStatement(Statement statement, IEnumerable <SearchKey> keys) { var numberPolicyCounterManager = ObjectFactory.GetInstance <INumberPolicyCounterManager>(); var insuredPersons = GetInsuredPersonsByKeys(keys); if (insuredPersons.Count > 0) { if (insuredPersons.Count > 1) { //// Заносим двойников в твинсы ObjectFactory.GetInstance <IInsuredPersonManager>().AddTwinsFirstAndOther(insuredPersons); } return(insuredPersons.First()); } // Новое застрахованное лицо var insuredPersonByStatement = new InsuredPerson { Status = ObjectFactory.GetInstance <IConceptCacheManager>() .GetById(StatusPerson.Active), }; if (!string.IsNullOrEmpty(statement.NumberPolicy)) { insuredPersonByStatement.MainPolisNumber = statement.NumberPolicy; } else { var insuredPersonDatum = statement.InsuredPersonData; if (insuredPersonDatum.Birthday != null) { insuredPersonByStatement.MainPolisNumber = numberPolicyCounterManager.GetNextEnpNumber( statement.PointDistributionPolicy.Parent.Parent.Id, insuredPersonDatum.Gender.Id, insuredPersonDatum.Birthday.Value); } } var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); session.Save(insuredPersonByStatement); return(insuredPersonByStatement); }
/// <summary> /// The response maping. /// </summary> /// <param name="statement"> /// The statement. /// </param> /// <returns> /// The <see cref="UIRResponseUIRQueryResponse[]"/>. /// </returns> private UIRResponseUIRQueryResponse[] ResponseMaping(Statement statement) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var conceptManager = ObjectFactory.GetInstance <IConceptCacheManager>(); var organisationManager = ObjectFactory.GetInstance <IOrganisationCacheManager>(); // поднимаем все страховки по InsurepPerson.PeriodInsurance.MedicalInsured // и мапим это все в ответ InsuredPerson person = null; return (session.QueryOver <MedicalInsurance>() .JoinAlias(x => x.InsuredPerson, () => person) .WhereRestrictionOn(x => person.Id) .IsIn(InsuredPersonsByKeis(statement).Select(m => m.Id).ToArray()) .List() .Select( ins => new UIRResponseUIRQueryResponse { Insurance = new Insurance { InsType = conceptManager.GetById(ins.PolisType.Id) .Code, InsRegion = organisationManager.GetById(ins.Smo.Id) .Parent.Code, MedInsCompanyId = organisationManager.GetById(ins.Smo.Id) .Code, StartDate = ins.DateFrom, EndDate = ins.DateTo, InsId = DocumentNumSeparator.SpecFormat(ins.PolisSeria, ins.PolisNumber) }, Person = new Person { MainENP = ins.InsuredPerson.MainPolisNumber, RegionalENP = ins.Statement.NumberPolicy } }) .ToArray()); }
private List <Rizik_za_osigurani_entitet> handleAppliedRisksForIP(Data data, InsuredPerson ip) { List <Rizik_za_osigurani_entitet> retList = new List <Rizik_za_osigurani_entitet>(); Rizik_za_osigurani_entitet rzoeAG = null; if (ip.ageGroup == -1) { return(retList); } else { rzoeAG = new Rizik_za_osigurani_entitet(); rzoeAG.Id_Rizik = ip.ageGroup; retList.Add(rzoeAG); } Rizik_za_osigurani_entitet rzoeLoc = null; if (data.selectedLocation != -1) { rzoeLoc = new Rizik_za_osigurani_entitet(); rzoeLoc.Id_Rizik = data.selectedLocation; retList.Add(rzoeLoc); } Rizik_za_osigurani_entitet rzoeSport = null; if (data.sport) { rzoeSport = new Rizik_za_osigurani_entitet(); rzoeSport.Id_Rizik = data.selectedSport; retList.Add(rzoeSport); } Rizik_za_osigurani_entitet rzoeAmount = null; if (data.selectedInsuranceAmount != -1) { rzoeAmount = new Rizik_za_osigurani_entitet(); rzoeAmount.Id_Rizik = data.selectedInsuranceAmount; retList.Add(rzoeAmount); } return(retList); }
/// <summary> /// The on canceled or remove statement. /// </summary> /// <param name="insuredPerson"> /// The insured person. /// </param> public void OnCanceledOrRemoveStatement(InsuredPerson insuredPerson) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var conceptManager = ObjectFactory.GetInstance <IConceptCacheManager>(); if (insuredPerson.Statements != null && (!insuredPerson.Statements.Any() || insuredPerson.Statements.All(x => StatusStatement.IsAnnuled(x.Status.Id)))) { insuredPerson.Status = conceptManager.GetById(StatusPerson.Annuled); session.Update(insuredPerson); foreach (var period in insuredPerson.MedicalInsurances) { period.IsActive = false; session.Update(period); } } }
/// <summary> /// The apply active. /// </summary> /// <param name="person"> /// The person. /// </param> public void ApplyActive(InsuredPerson person) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); // Выбираем все не отмененные заявления var history = session.QueryOver <Statement>() .Where(x => x.InsuredPerson.Id == person.Id) .And(x => x.Status.Id != StatusStatement.Cancelled) .And(x => x.Status.Id != StatusStatement.Declined) .OrderBy(x => x.DateFiling) .Asc.ThenBy(x => x.Id) .Desc.List(); // Получаем самое старое заявление var last = history.FirstOrDefault(); if (last != null) { // У самого старого нет предыдущего заявления last.IsActive = false; last.PreviousStatement = null; // Пропускам самое старое и строим хронологическую цепочку foreach (var x in history.Skip(1)) { x.IsActive = false; x.PreviousStatement = last; last = x; } last.IsActive = true; } ObjectFactory.GetInstance <IInsuredPersonManager>().OnCanceledOrRemoveStatement(person); }
/// <summary> /// The change insured person. /// </summary> /// <param name="currentPerson"> /// The current person. /// </param> /// <param name="person"> /// The person. /// </param> private void ChangeInsuredPerson(InsuredPerson currentPerson, InsuredPerson person) { ApplyActive(person); }
/// <summary> /// Добавление заявления /// </summary> /// <param name="sstatement"> /// The sstatement. /// </param> /// <returns> /// The <see cref="Statement"/> . /// </returns> public Statement SaveStatement(Statement sstatement) { var statement = sstatement; var statementSearchManager = ObjectFactory.GetInstance <IStatementSearchManager>(); // Текущая сессия var sessionFactory = ObjectFactory.GetInstance <ISessionFactory>(); var session = sessionFactory.GetCurrentSession(); try { using (var transaction = session.BeginTransaction(IsolationLevel.ReadUncommitted)) { // Первый этап простые проверки // Внимание!!! Сохраненного заявления еще нет в базе данных и в сессию ничего не сброшено // Внимание!!! Если хоть одна ПРОСТАЯ проверка полезит в базу данных или изменит сессию, что // кстати одинаково, уши оторву ObjectFactory.GetInstance <ICheckManager>().CheckStatement(statement, CheckLevelEnum.Simple); // Присваиваем автозаполняемые поля SetAutoProperty(statement, null); // Начинаем сохранять данные в БД, с этого момента и до Flush(), лучше не делать запросы в БД // Сохранение истории изменения ObjectFactory.GetInstance <IStatementChangeDateManager>().SaveStatementChangeHistory(statement); // Если пустой ID, то вставляем, если нет, то реплицируем if (statement.Id == Guid.Empty) { session.SaveOrUpdate(statement); } else { session.Replicate(statement, ReplicationMode.Overwrite); } // Сохранение зависимых данных SaveRelationData(statement); // Далее потребуются запросы в БД, поэтому сбрасываем все изменения из сессии session.Flush(); // Расчет ключей var allKeys = CalculateSearchKeys(statement).ToList(); // Поиск Insured Person var currentPerson = statement.InsuredPerson; // Продление истории при переоформлении, когда предыдущий пипл известен var peopleKeys = statementSearchManager.GetInsuredPersonByStatement(statement, allKeys); InsuredPerson peoplePrevios = null; if (statement.PreviousStatement != null && statement.PreviousStatement.InsuredPerson != null && statement.PreviousStatement.InsuredPerson.Id != Guid.Empty) { peoplePrevios = statement.PreviousStatement.InsuredPerson; } statement.InsuredPerson = peoplePrevios ?? peopleKeys; // появились двойники if (peoplePrevios != null && peopleKeys.Id != Guid.Empty && peoplePrevios.Id != peopleKeys.Id) { ObjectFactory.GetInstance <IInsuredPersonManager>() .AddTwinsFirstAndOther(new List <InsuredPerson> { peoplePrevios, peopleKeys }); } // Если пипл изменился, то надо корректно перенаправить данные if (currentPerson != null && currentPerson.Id != statement.InsuredPerson.Id) { foreach (var medIns in statement.MedicalInsurances) { medIns.InsuredPerson = statement.InsuredPerson; } session.Flush(); ChangeInsuredPerson(statement.InsuredPerson, currentPerson); } foreach (var ins in statement.MedicalInsurances) { ins.InsuredPerson = statement.InsuredPerson; } // В сессии накопились данные, а перед запросами в БД их надо сбрситьо session.SaveOrUpdate(statement); session.Flush(); // Сложные проверки, сессия сброшена, поэтому можно делать запросы в БД ObjectFactory.GetInstance <ICheckManager>().CheckStatement(statement, CheckLevelEnum.Complex); // Сохранение ключей ObjectFactory.GetInstance <ISearchKeyManager>().SaveSearchKeys(statement, allKeys); session.Flush(); // Сохране информации о работающий, неработающий SaveEmloymentHistry(statement); // Определяем активность ApplyActive(statement.InsuredPerson); session.Flush(); // пересчет ЕНП ObjectFactory.GetInstance <INumberPolicyCounterManager>() .RecalculateNumberPolicyCounter(statement.NumberPolicy); session.Flush(); // Обрабатываем испорченные документы ProcesingBadData(statement); // Обрабатываем испорченные документы ProcesingBadData(statement); // Создаем батч ////var a01manager = ObjectFactory.GetInstance<IStatementADT_A01Manager>(); ////var batch = a01manager.CreateBatchForExportAdtA01(statement); //// Выгружаем ADT_A01 для выполнения ФЛК с помощью шлюза РС ////a01manager.ExportAdtA01ForFLK(batch, statement); ////session.Flush(); // Коммитим изменения в базу transaction.Commit(); ////// Сохраняем информацию о внесении изменений ////var uam = new UserActionManager(); ////uam.LogAccessToPersonalData(statement, "Изменение записи"); } } catch (LogicalControlException) { session.Clear(); throw; } catch (Exception ex) { // Закрываем и удаляем старую сессию CurrentSessionContext.Unbind(sessionFactory); session.Dispose(); // Открываем новую сессию session = sessionFactory.OpenSession(); CurrentSessionContext.Bind(session); throw; } return(statement); }
/// <summary> /// The search. /// </summary> /// <param name="criteria"> /// The criteria. /// </param> /// <param name="addCriteriaDelegate"> /// The add criteria delegate. /// </param> /// <returns> /// The /// <see> /// <cref>SearchResult</cref> /// </see> /// . /// </returns> private SearchResult <SearchStatementResult> Search( SearchStatementCriteria criteria, Action <SearchStatementCriteria, QueryOver <Statement, Statement>, InsuredPersonDatum, Document, MedicalInsurance, bool> addCriteriaDelegate) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var currentUser = ObjectFactory.GetInstance <ISecurityProvider>().GetCurrentUser(); var currentSmo = currentUser.GetSmo(); InsuredPersonDatum dpersonDatum = null; InsuredPerson dperson = null; Document ddocument = null; MedicalInsurance dmedicalInsurance = null; var deatachQuery = QueryOver.Of <Statement>() .JoinAlias(x => x.InsuredPersonData, () => dpersonDatum) .JoinAlias(x => x.InsuredPerson, () => dperson) .JoinAlias(x => x.DocumentUdl, () => ddocument) .JoinAlias(x => x.MedicalInsurances, () => dmedicalInsurance, JoinType.LeftOuterJoin) .Select(x => dperson.Id); Statement statement = null; InsuredPersonDatum personDatum = null; InsuredPerson person = null; CauseReinsurance cause = null; Organisation tfom = null; Organisation smo = null; Organisation point = null; Concept gender = null; Concept citizenship = null; Document document = null; Concept documentType = null; Concept status = null; var query = session.QueryOver(() => statement) .Left.JoinAlias(x => x.Status, () => status) .Left.JoinAlias(x => x.InsuredPersonData, () => personDatum) .Left.JoinAlias(x => x.InsuredPerson, () => person) .Left.JoinAlias(x => x.CauseFiling, () => cause) .Left.JoinAlias(x => x.PointDistributionPolicy, () => point) .Left.JoinAlias(() => point.Parent, () => smo) .Left.JoinAlias(() => smo.Parent, () => tfom) .Left.JoinAlias(() => personDatum.Gender, () => gender) .Left.JoinAlias(() => personDatum.Citizenship, () => citizenship) .Left.JoinAlias(x => x.DocumentUdl, () => document) .Left.JoinAlias(() => document.DocumentType, () => documentType) .WithSubquery.WhereProperty(x => x.InsuredPerson.Id) .In(deatachQuery); var emptyCriteria = true; // Статус заявления if (criteria.StatementStatus > 0) { switch (criteria.StatementStatus) { case 9000: query.Where(x => document.IsBad); query.Where(x => point.Parent.Id == currentSmo.Id); break; case 9001: query.Where(x => personDatum.IsBadSnils); query.Where(x => point.Parent.Id == currentSmo.Id); break; default: query.Where(x => x.Status.Id == criteria.StatementStatus); break; } emptyCriteria = false; } // Тип заявления if (criteria.StatementType > 0) { emptyCriteria = false; query.WhereRestrictionOn(x => x.CauseFiling.Id).IsInG(Statement.GetCauseFillingByType(criteria.StatementType)); } // Поиск по дате подачи заявления if (criteria.UseDateFiling && criteria.DateFilingFrom != null && criteria.DateFilingTo != null) { if (criteria.DateFilingFrom > criteria.DateFilingTo) { throw new SearchException("Дата начала периода больше, чем дата его окончания."); } criteria.DateFilingTo = criteria.DateFilingTo.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59); emptyCriteria = false; query.WhereRestrictionOn(x => x.DateFiling).IsBetween(criteria.DateFilingFrom).And(criteria.DateFilingTo); } // Выводить только последние значения if (criteria.ReturnLastStatement) { query.Where(x => x.IsActive); } addCriteriaDelegate(criteria, deatachQuery, dpersonDatum, ddocument, dmedicalInsurance, emptyCriteria); var count = query.RowCount(); var searchResult = new SearchResult <SearchStatementResult> { Skip = criteria.Skip, Total = count }; query = AddOrder(criteria, statement, cause, smo, personDatum, gender, citizenship, documentType, document, query); query.Skip(criteria.Skip).Take(criteria.Take); SearchStatementResult result = null; var res = query.SelectList( y => y.Select(x => x.Id) .WithAlias(() => result.Id) .Select(x => x.DateFiling) .WithAlias(() => result.DateFiling) .Select(x => x.IsActive) .WithAlias(() => result.IsActive) .Select(x => cause.Name) .WithAlias(() => result.CauseFiling) .Select(x => x.CauseFiling.Id) .WithAlias(() => result.CauseFilingId) .Select(x => smo.Id) .WithAlias(() => result.SmoId) .Select(x => smo.ShortName) .WithAlias(() => result.Smo) .Select(x => smo.Ogrn) .WithAlias(() => result.SmoOGRN) .Select(x => tfom.Okato) .WithAlias(() => result.TfomOKATO) .Select(x => personDatum.FirstName) .WithAlias(() => result.FirstName) .Select(x => personDatum.LastName) .WithAlias(() => result.LastName) .Select(x => personDatum.MiddleName) .WithAlias(() => result.MiddleName) .Select(x => gender.Name) .WithAlias(() => result.Gender) .Select(x => personDatum.Birthday) .WithAlias(() => result.Birthday) .Select(x => personDatum.Birthplace) .WithAlias(() => result.Birthplace) .Select(x => x.Address2) .WithAlias(() => result.AddressLive) .Select(x => x.Address) .WithAlias(() => result.AddressRegistration) .Select(x => x.NumberPolicy) .WithAlias(() => result.PolicyNumber) .Select(x => citizenship.Name) .WithAlias(() => result.Citizenship) .Select(x => documentType.Name) .WithAlias(() => result.DocumentType) .Select(x => document.Series) .WithAlias(() => result.DocumentSeria) .Select(x => document.Number) .WithAlias(() => result.DocumentNumber) .Select(x => personDatum.Snils) .WithAlias(() => result.Snils) .Select(x => status.Name) .WithAlias(() => result.StatusStatement) .Select(x => status.Id) .WithAlias(() => result.Status) .Select(x => person.Status.Id) .WithAlias(() => result.PersonStatus) .Select(x => x.IsExportPolis) .WithAlias(() => result.IsSinhronized)) .TransformUsing(Transformers.AliasToBean <SearchStatementResult>()) .List <SearchStatementResult>(); var errorManager = ObjectFactory.GetInstance <IErrorManager>(); var conceptCacheManager = ObjectFactory.GetInstance <IConceptCacheManager>(); // получение текущего пользователя и текущей страховой foreach (var statementResult in res) { if (statementResult.IsActive) { statementResult.StatusStatement += " (Активное"; if (statementResult.PersonStatus == StatusPerson.Dead) { statementResult.StatusStatement += " , Умерший"; } statementResult.StatusStatement += ")"; } statementResult.Errors = errorManager.GetBy(x => x.Statement.Id == statementResult.Id) .Select( x => string.IsNullOrEmpty(x.Repl) ? x.Message1 : string.Format("{0} ({1})", x.Message1, x.Repl)) .ToList(); statementResult.TypeStatement = conceptCacheManager.GetById(Statement.GetTypeStatementId(statementResult.CauseFilingId)).Name; statementResult.FromCurrentSmo = currentSmo.Id == statementResult.SmoId; statementResult.DateInsuranceEnd = new DateTime(2030, 1, 1); // TODO: логика для даты окончания var temp = ObjectFactory.GetInstance <IMedicalInsuranceManager>() .GetBy(x => x.Statement.Id == statementResult.Id && x.IsActive && x.PolisType.Id == PolisType.В) .FirstOrDefault(); if (temp != null) { statementResult.NumberTemporaryCertificate = temp.PolisNumber; } var polis = ObjectFactory.GetInstance <IMedicalInsuranceManager>() .GetBy(x => x.Statement.Id == statementResult.Id && x.IsActive && x.PolisType.Id != PolisType.В) .FirstOrDefault(); if (polis != null) { statementResult.PolicyNumber = polis.Enp; } } searchResult.Rows = res; return(searchResult); }
private List <Stavka_u_realizaciji> handleItems(Realizacija_osiguranja ro, ProcessData processData, Data data) { List <Stavka_u_realizaciji> retList = new List <Stavka_u_realizaciji>(); //Handling Items - customers for (int i = 0; i < processData.customers.Count; i++) { Stavka_u_realizaciji sur = new Stavka_u_realizaciji(); //Handle Osoba entity var customer = processData.customers.ElementAt(i); Osoba existing = db.Osoba.Where(o => o.JMBG_Osoba == customer.osoba.JMBG_Osoba).FirstOrDefault(); if (existing != null) { checkCustomersData(existing, customer.osoba); sur.Id_Osigurana_osoba = existing.Id_Osigurani_entitet; } else { sur.Osoba = customer.osoba; } sur.Nosilac_Stavka_u_realiziciji = customer.carrier; if (customer.insured) { InsuredPerson personWithRisks = data.insuredPeople.Where(ip => ip.id == i).FirstOrDefault(); sur.Vrednost_Stavka_u_realizaciji = (decimal)personWithRisks.price; //Rizik_za_osigurani_entitet //Ako bude vremena, resite da se neki rizici vezuju direkt za Realizaciju, a ne za stavke. sur.Rizik_za_osigurani_entitet = handleAppliedRisksForIP(data, personWithRisks); } retList.Add(sur); } //Handle items - vehicle if (data.carInsured) { Stavka_u_realizaciji sur = new Stavka_u_realizaciji(); sur.Vozilo = processData.vehicleData.vehicle; sur.Rizik_za_osigurani_entitet = handleAppliedRisksForIV(data.insuredCar); sur.Vrednost_Stavka_u_realizaciji = (decimal)data.insuredCar.price; retList.Add(sur); } if (data.realEstateInsured) { Stavka_u_realizaciji sur = new Stavka_u_realizaciji(); sur.Nekretnina = processData.objectData.obj; sur.Rizik_za_osigurani_entitet = handleAppliedRisksForIRE(data.insuredRealEstate); sur.Vrednost_Stavka_u_realizaciji = (decimal)data.insuredRealEstate.price; retList.Add(sur); } return(retList); }
/// <summary> /// Разделение /// </summary> /// <param name="personId"> /// The person Id. /// </param> /// <param name="statementsToSeparate"> /// The statements To Separate. /// </param> /// <param name="copyDeadInfo"> /// The copy Dead Info. /// </param> /// <param name="status"> /// The status. /// </param> public void Separate(Guid personId, IList <Statement> statementsToSeparate, bool copyDeadInfo, int status) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var conceptManager = ObjectFactory.GetInstance <IConceptCacheManager>(); var currentUser = ObjectFactory.GetInstance <ISecurityProvider>().GetCurrentUser(); var personManager = ObjectFactory.GetInstance <IInsuredPersonManager>(); var statementManager = ObjectFactory.GetInstance <IStatementManager>(); var twinManager = ObjectFactory.GetInstance <ITwinManager>(); var numberPolicyCounterManager = ObjectFactory.GetInstance <INumberPolicyCounterManager>(); var transaction = session.BeginTransaction(); try { var person = personManager.GetById(personId); var statementToSeparateIdList = statementsToSeparate.Select(x => x.Id).ToList(); var searchKeys = session.QueryOver <SearchKey>().WhereRestrictionOn(x => x.Statement.Id).IsIn(statementToSeparateIdList).List(); // Создаем пипла var personNew = new InsuredPerson { Status = conceptManager.GetById(status) }; // Определяем ЕНП, последний, заполненный var enp = statementsToSeparate.Where(x => !string.IsNullOrEmpty(x.NumberPolicy)) .OrderByDescending(x => x.DateFiling) .Select(x => x.NumberPolicy) .FirstOrDefault(); if (enp == null) { var statement = statementsToSeparate.OrderByDescending(x => x.DateFiling).FirstOrDefault(); if (statement != null) { var personData = statement.InsuredPersonData; if (personData.Birthday != null) { enp = numberPolicyCounterManager.GetNextEnpNumber( currentUser.GetTf().Id, personData.Gender.Id, personData.Birthday.Value); } } } personNew.MainPolisNumber = enp; // создаём новую персону и делаем копию инфы о смерти if (copyDeadInfo && person.DeadInfo != null) { var resultDeadInfo = new DeadInfo { ActRecordDate = person.DeadInfo.ActRecordDate, ActRecordNumber = person.DeadInfo.ActRecordNumber, DateDead = person.DeadInfo.DateDead }; session.Save(resultDeadInfo); personNew.DeadInfo = resultDeadInfo; } session.Save(personNew); // создаём копию истории и назначаем новой персоне var historyManager = ObjectFactory.GetInstance <IEmploymentHistoryManager>(); var histories = historyManager.GetByInsuredPersonId(person.Id); foreach (var history in histories) { session.Evict(history); history.Id = Guid.Empty; history.InsuredPerson = personNew; session.Save(history); } // переставляем ссылки в периодах страхования MedicalInsurance medicalInsurance = null; var periodInsurances = session.QueryOver <MedicalInsurance>() .WhereRestrictionOn(x => medicalInsurance.Statement.Id) .IsIn(statementToSeparateIdList) .List(); foreach (var periodInsurance in periodInsurances) { periodInsurance.InsuredPerson = personNew; session.Update(periodInsurance); } // переставляем ссылки в ключах поиска foreach (var key in searchKeys) { key.InsuredPerson = personNew; session.SaveOrUpdate(key); } // В заявлениях на разделение переставляем ссылки на новую персону foreach (var statement in statementsToSeparate) { statement.InsuredPerson = personNew; session.SaveOrUpdate(statement); } // Перестраиваем заявления statementManager.ApplyActive(person); statementManager.ApplyActive(personNew); // Отменять обработку дубликата не нужно!!! // Ищем все дуликаты с исходным пиплом и пораждаем новые дубликаты этих же дубликатов, но уже с новым пиплом var twins = twinManager.GetBy(x => x.FirstInsuredPerson.Id == personId); foreach (var twin in twins) { session.Evict(twin); twin.Id = Guid.Empty; twin.FirstInsuredPerson = personNew; session.Save(twin); } twins = twinManager.GetBy(x => x.SecondInsuredPerson.Id == personId); foreach (var twin in twins) { session.Evict(twin); twin.Id = Guid.Empty; twin.SecondInsuredPerson = personNew; session.Save(twin); } // А теперь помечаем пару как обработанный дубликат var twin1 = new Twin { FirstInsuredPerson = person, SecondInsuredPerson = personNew, TwinType = conceptManager.GetById(TypeTwin.TypeTwin3) }; session.Save(twin1); session.Flush(); transaction.Commit(); } catch { transaction.Dispose(); throw; } }
/// <summary> /// Дубликаты по критерию для разбивки постранично /// </summary> /// <param name="criteria"> /// The criteria. /// </param> /// <returns> /// The /// <see> /// <cref>SearchResult</cref> /// </see> /// . /// </returns> public SearchResult <Twin> GetTwins(SearchTwinCriteria criteria) { var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); var currentUser = ObjectFactory.GetInstance <ISecurityProvider>().GetCurrentUser(); Concept twinType = null; InsuredPerson insuredPerson1 = null; MedicalInsurance medicalInsurance1 = null; Organisation smo1 = null; InsuredPerson insuredPerson2 = null; MedicalInsurance medicalInsurance2 = null; Organisation smo2 = null; var query = session.QueryOver <Twin>() .JoinAlias(x => x.TwinType, () => twinType) .Where(x => twinType.Id == TypeTwin.TypeTwin2); if (currentUser.HasTf()) { var tf = currentUser.GetTf(); query.JoinAlias(x => x.FirstInsuredPerson, () => insuredPerson1) .JoinAlias(() => insuredPerson1.MedicalInsurances, () => medicalInsurance1) .JoinAlias(() => medicalInsurance1.Smo, () => smo1) .And(() => medicalInsurance1.IsActive) .And(() => smo1.Parent.Id == tf.Id) .JoinAlias(x => x.SecondInsuredPerson, () => insuredPerson2) .JoinAlias(() => insuredPerson2.MedicalInsurances, () => medicalInsurance2) .JoinAlias(() => medicalInsurance2.Smo, () => smo2) .And(() => medicalInsurance2.IsActive) .And(() => smo2.Parent.Id == tf.Id); } TwinsKey twinKeys = null; SearchKeyType skt = null; switch (criteria.KeyType) { case TwinKeyType.All: break; case TwinKeyType.Standard: query.JoinAlias(t => t.TwinsKeys, () => twinKeys) .JoinAlias(t => twinKeys.KeyType, () => skt) .WhereRestrictionOn(t => skt.Tfoms) .IsNull(); break; case TwinKeyType.NonStandard: query.JoinAlias(t => t.TwinsKeys, () => twinKeys).Where(t => twinKeys.KeyType.Id == criteria.KeyId); break; } var count = query.RowCount(); var searchResult = new SearchResult <Twin> { Skip = criteria.Skip, Total = count }; query.Skip(criteria.Skip).Take(criteria.Take); searchResult.Rows = query.List(); return(searchResult); }