public PatientVisitsDbAdapter(
IRepository<PatientVisit, long> repository,
IEntityPropsCache entityPropsCache,
ITelemetry telemetry,
IRepository<Guardian, Guid> guardianRepository,
IRepository<PublicUserChild, Guid> publicUserChildRepository,
ITimeProvider timeProvider) : base(repository, entityPropsCache, telemetry)
{
_guardianRepository = guardianRepository;
_publicUserChildRepository = publicUserChildRepository;
_timeProvider = timeProvider;
}
private static IQueryable<PatientVisit> AddSearchIncludes(IQueryable<PatientVisit> baseQuery)
{
return baseQuery
.AsSplitQuery()
.Include(v => v.OrganizationUnit)
.Include(v => v.Patient)
.Include(v => v.MedicalService)
.Include(v => v.User).ThenInclude(v => v!.MedicalStaffData)
.Include(v => v.ConfirmationRequests)
.Include(v => v.Institution).ThenInclude(v => v!.SpecializationOrgUnits).ThenInclude(v => v.Specialization);
}
private static IQueryable<PatientVisit> AddPublicSearchIncludes(IQueryable<PatientVisit> baseQuery)
{
return baseQuery
.AsSplitQuery()
.Include(v => v.Patient)
.Include(v => v.DependentVisits!.Where(d => d.Entity!.Status != PatientVisitStatus.Cancelled))
.Include(v => v.MasterVisit);
}
protected override IQueryable<PatientVisit> AddIncludes(IQueryable<PatientVisit> baseQuery)
{
return AddSearchIncludes(baseQuery);
}
private static IEnumerable<Expression<Func<PatientVisit, bool>>> GetTimeRangeExpressions(IDateTimeVisitQuery query)
{
if (query.TimeRange.FromTime is { } fromTime)
{
var fromHours = fromTime.Hours;
var fromMinutes = fromTime.Minutes;
yield return v =>
v.From.Hour > fromHours || (v.From.Hour == fromHours && v.From.Minute >= fromMinutes) ||
(query.IncludeOffSchedule && v.SlotReferenceDate != null && v.SlotReferenceDate != v.From &&
v.SlotReferenceDate.Value.Date == v.From.Date && // avoid false positives if visit is moved outside portal
(v.SlotReferenceDate.Value.Hour > fromHours || (v.SlotReferenceDate.Value.Hour == fromHours && v.SlotReferenceDate.Value.Minute >= fromMinutes)));
}
if (query.TimeRange.ToTime is { } toTime)
{
var toHours = toTime.Hours;
var toMinutes = toTime.Minutes;
yield return v =>
(!query.FullFit && (v.From.Hour < toHours || (v.From.Hour == toHours && v.From.Minute <= toMinutes))) ||
(v.To.Hour < toHours || (v.To.Hour == toHours && v.To.Minute <= toMinutes)) ||
(query.IncludeOffSchedule && v.SlotReferenceDate != null && v.SlotReferenceDate != v.From && v.SlotReferenceDate.Value.Date == v.From.Date &&
(v.SlotReferenceDate.Value.Hour < toHours || (v.SlotReferenceDate.Value.Hour == toHours && v.SlotReferenceDate.Value.Minute <= toMinutes)));
}
}
private async Task<ISet<long>?> ResolvePatientId(SinglePatientVisitQuery query)
{
if (query.PatientId is not { } patientId) return null;
if (query.PublicUserChildId != null) return patientId.AsSet();
var idsByCareTakerDirectory = query.IncludeChildrenMode.HasFlag(PatientVisitIncludeChildrenMode.DirectoryCareTakers)
? await _guardianRepository.GetAll().AsNoTracking()
.Where(v => v.AccountId == patientId)
.Select(v => v.CareTakerId)
.ToListAsync()
: new List<long>();
var idsByPublicUserChild = query.PublicUserAccountId is { } publicUserAccountId &&
query.IncludeChildrenMode.HasFlag(PatientVisitIncludeChildrenMode.PublicUserChildren)
? await _publicUserChildRepository.GetAll().AsNoTracking()
.Where(v => v.PublicUserId == publicUserAccountId)
.Where(v => v.PatientId.HasValue)
.Select(v => v.PatientId!.Value)
.ToListAsync()
: new List<long>();
return idsByCareTakerDirectory.Concat(idsByPublicUserChild).ConcatSingle(patientId).ToHashSet();
}
private async Task<Expression<Func<PatientVisit, bool>>> GetUserVisitsIdentityExpression(SinglePatientVisitQuery query)
{
var patientIds = await ResolvePatientId(query);
if (patientIds != null && query.PublicUserAccountId != null)
{
if (query.IncludeChildrenMode.HasFlag(PatientVisitIncludeChildrenMode.PublicUserChildren) && query.PublicUserChildId == null)
{
return v => (v.PatientId != null && patientIds.Contains(v.PatientId.Value)) ||
(v.PatientId == null && v.PublicUserAccountId == query.PublicUserAccountId);
}
return v => (v.PatientId != null && patientIds.Contains(v.PatientId.Value)) ||
(v.PatientId == null && v.PublicUserAccountId == query.PublicUserAccountId && v.PublicUserChildId == query.PublicUserChildId);
}
if (patientIds != null)
{
return v => v.PatientId != null && patientIds.Contains(v.PatientId.Value);
}
if (query.PatientWithoutId != null)
{
if (string.IsNullOrWhiteSpace(query.PatientWithoutId.Name))
throw new ArgumentException(nameof(query.PatientWithoutId.Name));
if (string.IsNullOrWhiteSpace(query.PatientWithoutId.PhoneNumber))
throw new ArgumentException(nameof(query.PatientWithoutId.PhoneNumber));
var parsedPatientName = query.PatientWithoutId.Name.ParsePatientName();
var patientName = string.Join(' ', new[] { parsedPatientName.Name, parsedPatientName.Surname }.Where(v => !string.IsNullOrEmpty(v)));
var reversedPatientName = string.Join(' ', new[] { parsedPatientName.Surname, parsedPatientName.Name }.Where(v => !string.IsNullOrEmpty(v)));
return v => v.PatientId == null
&& v.PatientName != null && (EF.Functions.ILike(v.PatientName, patientName) || EF.Functions.ILike(v.PatientName, reversedPatientName))
&& v.PhoneNumber != null && v.PhoneNumber == query.PatientWithoutId.PhoneNumber;
}
if (query.PublicUserAccountId != null)
{
if (query.IncludeChildrenMode.HasFlag(PatientVisitIncludeChildrenMode.PublicUserChildren) && query.PublicUserChildId == null)
{
return v => v.PatientId == null && v.PublicUserAccountId == query.PublicUserAccountId;
}
return v => v.PatientId == null && v.PublicUserAccountId == query.PublicUserAccountId && v.PublicUserChildId == query.PublicUserChildId;
}
return v => false;
}
public async Task<Either<int>> GetSinglePatientVisitsCountAsync(SinglePatientVisitQuery query)
{
var queryMode = await BaseSinglePatientVisitsQuery(query);
return await CountAsync(dbQuery => queryMode(dbQuery).Where(v => v.Status == PatientVisitStatus.Upcoming));
}
private async Task<Func<IQueryable<PatientVisit>, IQueryable<PatientVisit>>> BaseSinglePatientVisitsQuery(SinglePatientVisitQuery query)
{
var patientIdEx = await GetUserVisitsIdentityExpression(query);
return dbQuery =>
{
var baseQuery = dbQuery
.WithNonEmptyGenericAppointmentTypeId(skipFilter: query.IncludeExternal)
.Where(patientIdEx)
.Where(v => v.Status != PatientVisitStatus.Cancelled)
.WhereIf(query.VisitStatus != null, v => query.VisitStatus!.Contains(v.Status))
.WhereIf(query.OnlyBeforeCancellationThreshold != null, v => v.CancellationThresholdDate == null || v.CancellationThresholdDate > query.OnlyBeforeCancellationThreshold)
.WhereIf(query.FromDate != null, v => v.From >= query.FromDate)
.WhereIf(query.ExcludeId != null, v => v.Id != query.ExcludeId)
.WhereIf(query.ToDate != null, v => v.From <= query.ToDate)
.WhereIf(query.NoWardVisits, v => v.HospitalWardId == null)
.WhereIf(query.SpecializationType != null, v => v.Specialization!.Type == query.SpecializationType)
.WhereIf(query.SpecializationId != null, v => v.SpecializationId == query.SpecializationId);
return baseQuery;
};
}
public Task<Either<PatientVisit>> GetForNotificationAsync(long id)
{
return GetSingleAsync(id, baseQuery => baseQuery
.AsSplitQuery()
.Include(v => v.AppointmentType).ThenInclude(v => v!.MedicalServices)!.ThenInclude(v => v.MedicalService!.FileBucket!.Files)
.Include(v => v.Specialization)
.Include(v => v.MedicalService).ThenInclude(v => v!.FileBucket!.Files)
.Include(v => v.Patient)
.Include(v => v.OrganizationUnit)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.Entity!.Specialization)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.Entity!.AppointmentType)
);
}
public Task<Either<IList<PatientVisit>>> GetForPaymentResolution(ISet<long> ids)
{
return GetListAsync(baseQuery => WithIdFilter(ids.ToList(), baseQuery)
.AsSplitQuery()
.Include(v => v.PatientCare!.PrinterJobSet!.Jobs)
.Include(v => v.Patient)
.Include(v => v.NoShowDebt!.PrinterJobSet!.Jobs)
.Include(v => v.OrganizationUnit)
.Include(v => v.Specialization)
);
}
public Task<Either<PatientVisit>> GetForConfirmation(long id) => GetSingleAsync(id, dbQuery => dbQuery.Include(v => v.ConfirmationRequests), true);
public Task<Either<PatientVisit>> GetForMove(long id) => GetSingleAsync(id, dbQuery => dbQuery
.Include(v => v.ConfirmationRequests)
.Include(v => v.VisitPrenatalProgram)
.Include(v => v.DependentVisits!.Where(dv => dv.Entity!.Status == PatientVisitStatus.Upcoming))
);
public Task<Either<PatientVisit>> GetForPaymentModesAllowed(long id, long specializationId) => GetSingleAsync(id, dbQuery => dbQuery
.Include(v => v.Specialization)
.Include(v => v.AppointmentType)
.Include(v => v.Staff!.Specializations!.Where(ss => ss.SpecializationId == specializationId))
.Include(v => v.OrganizationUnit!.SpecializationOrgUnits!.Where(sou => sou.SpecializationId == specializationId))
);
public Task<Either<PatientVisit>> GetForZlaAssembly(long id, bool includeCare) => GetSingleAsync(id, q => q
.Include(v => v.OrganizationUnit)
.Include(v => v.Staff)
.Include(v => v.Patient)
.Include(v => v.Specialization)
.IncludeIf(includeCare, v => v.PatientCare!.Diagnoses)
);
public Task<Either<PatientVisit>> GetForCancellation(long id) => GetSingleAsync(id, dbQuery => dbQuery.Include(v => v.DependentVisits));
public Task<Either<PatientVisit>> GetForCardView(long id, bool includeReferrals)
{
return GetSingleAsync(id, baseQuery => baseQuery
.AsSplitQuery()
.Include(v => v.Patient).ThenInclude(v => v!.PatientDeclarations)
.IncludeIf(includeReferrals, v => v.Referrals)
.IncludeIf(includeReferrals, v => v.ReferralRequests)
.Include(v => v.ConfirmationRequests)
.Include(v => v.VisitPrenatalProgram)
.IncludeCheckIns()
.Include(v => v.Survey)
.Include(v => v.HospitalWardVisit!.HospitalWardStay)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.DependentMedicalService)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.DependentService!.OccupationalMedicineInfo)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.Entity)
.Include(v => v.MasterVisit).ThenInclude(v => v!.DependentMedicalService)
.Include(v => v.MasterVisit).ThenInclude(v => v!.DependentService!.OccupationalMedicineInfo)
.Include(v => v.MasterVisit).ThenInclude(v => v!.MasterVisit)
);
}
public Task<Either<PatientVisit>> GetForCardViewSummary(long id)
{
return GetSingleAsync(id, baseQuery => baseQuery
.Include(v => v.Patient)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.Entity)
.Include(v => v.DependentVisits)!.ThenInclude(v => v.DependentService!.OccupationalMedicineInfo)
);
}
public Task<Either<PatientVisit>> GetWithCareData(long id)
{
return GetSingleAsync(id, baseQuery => baseQuery
.AsSplitQuery()
.Include(v => v.Institution)
.IncludeCheckIns()
.Include(v => v.Patient!.Guardians)!.ThenInclude(v => v.Account)
.Include(v => v.Specialization!.HostCompany)
.Include(v => v.Staff!.Accounting)
.Include(v => v.MasterVisit)
.Include(v => v.MedicalService!.OccupationalMedicineInfo)
.Include(v => v.PatientCare!.PatientCarePriceListItems)!.ThenInclude(v => v.PriceListItem!.HostPriceListItemEntries)!.ThenInclude(v => v.PriceListVersion)
.Include(v => v.PatientCare!.PatientCarePriceListItems)!.ThenInclude(v => v.PriceListItem!.ForeignPriceListItem)
.Include(v => v.PatientCare!.Procedures)
.Include(v => v.PatientCare!.Diagnoses)
.Include(v => v.PatientCare!.PrinterJobSet!.Jobs)
.Include(v => v.PatientCare!.NfzCare!.Items)
.Include(v => v.PatientCare!.NfzCare!.Staff)
.Include(v => v.PatientCare!.DentalCare).ThenInclude(v => v!.DentalDiagram)
);
}
public async Task<Either<IList<PatientVisit>>> RescheduleVisitsSearchAsync(VisitRescheduleQuery query, bool returnTracking = true)
{
try
{
var baseQuery = returnTracking ? _repository.GetAll() : _repository.GetAll().AsNoTracking();
baseQuery = baseQuery
.AsSplitQuery()
.Include(v => v.Patient);
var dbResult = await GetTimeRangeExpressions(query)
.Concat(query.GetDateRangeExpressions())
.Aggregate(baseQuery, (current, filter) => current.Where(filter))
.Where(v => v.StaffId == query.UserId)
.Where(v => v.Status != PatientVisitStatus.Closed && v.Status != PatientVisitStatus.Cancelled)
.WhereIf(query.ExcludedIds != null, v => !query.ExcludedIds!.Contains(v.Id))
.OrderBy(v => v.From)
.ToListAsync();
return Either.Success(dbResult);
}
catch (Exception e)
{
return Either<IList<PatientVisit>>.InternalError(e);
}
}
public Task<Either<PagedResultDto<PatientVisit>>> SearchAsync(PatientVisitsQuery query) => SearchInternalAsync(query, v => v);
public Task<Either<PagedResultDto<PatientVisit>>> SearchAsync(PatientAccountingQuery query)
{
return PagedNotFilteredSearchAsync(query, baseQuery =>
{
var removedPaymentStatusSet = PatientCarePriceListItem.RemovedPaymentStatusSet.ToHashSet();
var visitStatus = new HashSet<PatientVisitStatus> { PatientVisitStatus.Closed, PatientVisitStatus.Pending, PatientVisitStatus.CheckedIn };
var filteredQuery = query.GetDateRangeExpressions().Aggregate(baseQuery, (current, filter) => current.Where(filter))
.AsSplitQuery()
.Include(v => v.PatientCare).ThenInclude(v => v!.PatientCarePriceListItems!).ThenInclude(v => v.PriceListItem!).ThenInclude(v => v.ForeignPriceListItem)
.Include(v => v.PatientCare).ThenInclude(v => v!.PrinterJobSet!).ThenInclude(v => v.Jobs)
.Include(v => v.AppointmentType)
.Include(v => v.Patient)
.Where(v => visitStatus.Contains(v.Status))
.WithNonEmptyGenericAppointmentTypeId()
.WhereIf(query.OrganizationUnitId != null, v => v.OrganizationUnitId == query.OrganizationUnitId)
.WhereIf(query.PatientIds != null, v => v.PatientId != null && query.PatientIds!.Contains(v.PatientId.Value))
.WhereIf(query.Status != null, v => query.Status!.Contains(v.Status))
.WhereIf(!string.IsNullOrWhiteSpace(query.ReceiptId), v => v.PatientCare!.PrinterJobSet!.Jobs!.Any(j => j.ReceiptGlobalId == query.ReceiptId))
.WhereIf(query.StaffId != null, v => v.StaffId == query.StaffId)
.WhereIf(query.SpecializationId != null, v => v.SpecializationId == query.SpecializationId)
.WhereIf(!query.IncludeProcessed,
v => v.PatientCare!.PatientCarePriceListItems!.Any(i => i.PaymentStatus == PriceItemPaymentStatus.NeedsPayment || i.PaymentStatus == PriceItemPaymentStatus.NeedsVerification))
.WhereIf(!query.KioskCheckoutDestination, v => v.PatientCare!.PatientCarePriceListItems!.Any(i => !removedPaymentStatusSet.Contains(i.PaymentStatus)))
.WhereIf(query.KioskCheckoutDestination,
v => v.From.Date == _timeProvider.Now().Date || v.PatientCare!.PatientCarePriceListItems!.Any(i => i.PaymentStatus == PriceItemPaymentStatus.NeedsPayment));
if (query.SearchPhrase is { } searchPhrase && !string.IsNullOrWhiteSpace(searchPhrase))
{
var chunks = searchPhrase.Split(" ").Select(v => v.Trim()).ToList();
var priceItemStringExp = new QueryableSearchExtensions.ColumnSearch<PatientVisit>(v => v.PatientCare!.PatientCarePriceListItems!.Select(i => i.PriceListItem!.Name),
QueryableSearchExtensions.WildcardType.Contains);
filteredQuery = filteredQuery.ToSearchQueryable(chunks, VisitStringSearchExpressions().Concat(priceItemStringExp.AsList()).ToArray());
}
return filteredQuery.OrderByDescending(v => v.From);
});
}
private static IEnumerable<QueryableSearchExtensions.ColumnSearch<PatientVisit>> VisitStringSearchExpressions()
{
return new QueryableSearchExtensions.ColumnSearch<PatientVisit>[]
{
new(v => v.User!.Name, QueryableSearchExtensions.WildcardType.StartsWith),
new(v => v.User!.Surname, QueryableSearchExtensions.WildcardType.StartsWith),
new(v => v.Patient!.Name, QueryableSearchExtensions.WildcardType.StartsWith),
new(v => v.Patient!.Surname, QueryableSearchExtensions.WildcardType.StartsWith),
new(v => v.Patient!.Pesel, QueryableSearchExtensions.WildcardType.Contains)
};
}
public Task<Either<PagedResultDto<PatientVisit>>> SearchAsync(VisitsToConfirmQuery query)
{
return PagedSearchAsync(query, baseQuery =>
{
var filteredQuery = query.GetDateRangeExpressions().Aggregate(baseQuery, (current, filter) => current.Where(filter))
.AsSplitQuery()
.Include(v => v.Patient)
.Include(v => v.ConfirmationRequests!.Where(cr => cr.Type == PatientVisitConfirmationType.ConfirmVisit))
.WhereIf(query.VisitId.HasValue, v => v.Id == query.VisitId!.Value)
.Where(v => v.Status == PatientVisitStatus.Upcoming)
.Where(v => v.ConfirmationRequests!.Any(cr => cr.Type == PatientVisitConfirmationType.ConfirmVisit && cr.Result == null))
.Where(v => v.PatientName != SchedulesLockService._lockPatientName)
.WithNonEmptyGenericAppointmentTypeId();
if (query.SearchPhrase is { } searchPhrase && !string.IsNullOrWhiteSpace(searchPhrase))
{
var chunks = searchPhrase.Split(" ").Select(v => v.Trim()).ToList();
filteredQuery = filteredQuery.ToSearchQueryable(chunks, VisitStringSearchExpressions().ToArray());
}
return filteredQuery.OrderByDescending(v => v.From);
});
}
public Task<Either<IList<PatientVisit>>> SearchAsync(SimpleStaffVisitsQuery query)
{
return GetListAsync(dbQuery =>
{
var filteredQuery = query.GetDateRangeExpressions().Aggregate(dbQuery, (current, filter) => current.Where(filter))
.AsSplitQuery()
.Include(v => v.Patient)
.Where(v => v.StaffId == query.StaffId)
.WhereIf(query.VisitStatus != null, v => query.VisitStatus!.Contains(v.Status))
.Where(v => v.PatientName != SchedulesLockService._lockPatientName);
return filteredQuery.OrderByDescending(v => v.From);
});
}
public Task<Either<IList<PatientVisit>>> ListGroupAsync(Guid groupId)
{
return GetListAsync(dbQuery =>
{
var filteredQuery = dbQuery
.AsSplitQuery()
.Include(v => v.Patient)
.Where(v => v.Status != PatientVisitStatus.Cancelled)
.Where(v => v.GroupId == groupId);
return filteredQuery.OrderByDescending(v => v.From);
});
}
private Task<Either<PagedResultDto<PatientVisit>>> SearchInternalAsync(PatientVisitsQuery query, Func<IQueryable<PatientVisit>, IQueryable<PatientVisit>> extraFilter)
{
return PagedSearchAsync(query, baseQuery =>
{
var queryWithIncludes = baseQuery
.AsSplitQuery()
.IncludeIf(query.IncludePatient, v => v.Patient)
.IncludeIf(query.IncludeConfirmations, v => v.ConfirmationRequests!.Where(cr => cr.Type == PatientVisitConfirmationType.ConfirmVisit));
var filteredQuery = query.ApplyFilter(queryWithIncludes);
return query.GetPatientExpressions().Concat(query.GetDateRangeExpressions())
.Aggregate(extraFilter(filteredQuery), (current, filter) => current.Where(filter))
.Where(v => v.PatientName != SchedulesLockService._lockPatientName)
.Where(v => v.OrganizationUnitId != null)
.OrderByWithParam(v => v.From, query.NewestFirst);
});
}
public Task<Either<PagedResultDto<PatientVisit>>> SearchVisitsToRescheduleAsync(PatientVisitsQuery query)
{
return SearchInternalAsync(query, dbQuery => dbQuery
.Where(v => v.Status != PatientVisitStatus.Cancelled)
.WithNonEmptyGenericAppointmentTypeId()
.Where(v => v.RescheduleReason != null));
}
public Task<Either<PagedResultDto<PatientVisit>>> SearchAsync(StaffVisitsQuery query)
{
return PagedNotFilteredSearchAsync(query, baseQuery =>
{
var withIncludes = baseQuery
.Include(v => v.Patient)
.Include(v => v.Survey)
.Include(v => v.MasterVisit)
.IncludeCheckIns()
.AsQueryable();
return query.GetDateRangeExpressions()
.Aggregate(withIncludes, (current, filter) => current.Where(filter))
.AsSplitQuery()
.Where(v => v.Status != PatientVisitStatus.Cancelled)
.WhereIf(!query.ShowClosed, v => v.Status != PatientVisitStatus.Closed)
.WhereIf(query.PaymentMode != null, v => query.PaymentMode!.Contains(v.PaymentMode))
.Where(v => v.StaffId == query.StaffId)
.Where(v => v.OrganizationUnitId != null)
.OrderBy(v => v.From);
});
}
public Task<Either<IList<PatientVisit>>> SearchForAccountingAsync(StaffAccountingVisitsQuery query)
{
return GetListAsync(baseQuery => baseQuery
.Include(v => v.Patient)
.Include(v => v.PatientCare!.PatientCarePriceListItems)!.ThenInclude(v => v.PriceListItem!.HostPriceListItemEntries)!.ThenInclude(v => v.PriceListVersion)
.Include(v => v.PatientCare!.PatientCarePriceListItems)!.ThenInclude(v => v.WithdrawCashEntry)
.Where(v => (v.From < query.DateRange.EndTime && v.From >= query.DateRange.StartTime) ||
v.PatientCare!.PatientCarePriceListItems!.Any(i =>
i.WithdrawCashEntry!.CreationTime >= query.DateRange.StartTime && i.WithdrawCashEntry.CreationTime < query.DateRange.EndTime) ||
v.PatientCare!.PatientCarePriceListItems!.Any(i =>
i.StatusModificationTime < query.DateRange.EndTime && i.StatusModificationTime >= query.DateRange.StartTime && PatientCarePriceListItem.RemovedPaidPaymentStatusSet.Contains(i.PaymentStatus))
)
.Where(v => v.Status != PatientVisitStatus.Cancelled)
.Where(v => v.StaffId == query.StaffId)
.Where(v => v.PatientCareId != null)
.Where(v => v.OrganizationUnitId == query.OrgUnitId)
.OrderBy(v => v.From));
}
public async Task<Either<PagedResultDto<PatientVisit>>> SinglePatientVisitsSearchAsync(PagedSinglePatientVisitQuery query, bool resolveCare = false, bool resolveConfirmations = false)
{
var queryMode = await BaseSinglePatientVisitsQuery(query);
return await PagedNotFilteredSearchAsync(query, baseQuery =>
{
var queryWithIncludes = AddPublicSearchIncludes(baseQuery)
.IncludeIf(resolveCare, v => v.PatientCare);
if (resolveConfirmations)
{
queryWithIncludes = queryWithIncludes
.Include(v => v.ConfirmationRequests);
}
return queryMode(queryWithIncludes)
.WhereIf(query.VisitId != null, v => v.Id == query.VisitId)
.OrderByWithParam(v => v.From, query.NewestFirst);
});
}
public async Task<Either<IList<PatientVisit>>> SinglePatientVisitsSearchAsync(SinglePatientVisitQuery query)
{
var queryMod = await BaseSinglePatientVisitsQuery(query);
return await GetListAsync(baseQuery => queryMod(baseQuery).OrderBy(v => v.From));
}
public Task<Either<IList<long>>> TechnicalVisitsSearchAsync(IHavePublicPatientId publicPatientId, DateTime threshold, int limit)
{
return GetListAsync(baseQuery => baseQuery
.Where(v => v.PublicUserAccountId == publicPatientId.PublicUserAccountId)
.WhereIf(publicPatientId.IsChild(), v => v.PublicUserChildId == publicPatientId.PatientPublicId)
.WhereIf(!publicPatientId.IsChild(), v => v.PublicUserChildId == null)
.Where(v => v.PatientId == null)
.Where(v => v.Status == PatientVisitStatus.Upcoming)
.Where(v => v.From > threshold)
.OrderBy(v => v.From)
.Take(limit)
.Select(v => v.Id)
);
}
public Task<Either<IList<long>>> FilterByWardMode(ISet<long> ids, HospitalWardVisitMode mode) =>
GetIdsAsync(dbQuery => WithIdFilter(ids.ToList(), dbQuery)
.WhereIf(mode == HospitalWardVisitMode.None, v => v.HospitalWardVisit == null || v.HospitalWardVisit.Mode == mode)
.WhereIf(mode != HospitalWardVisitMode.None, v => v.HospitalWardVisit != null && v.HospitalWardVisit.Mode == mode)
);
Aby zapobiec wywoływaniu metody NotifyVisitMovedAsync w metodzie MoveValidatedAsync, gdy dane wizyty (oldVisitData i visitMoveData) mają te same daty, godziny oraz miejsce, należy dodać warunek sprawdzający te właściwości przed wywołaniem metody powiadamiającej. Poniżej znajduje się zmodyfikowany kod metody MoveValidatedAsync, który uwzględnia ten warunek:
private Task<Either<VisitOperationSet<PatientVisitResponseData>>> MoveValidatedAsync(
ResolvedPatientVisit resolvedVisit,
OldVisitData oldVisitData,
VisitMoveData visitMoveData,
Guid? visitLockId)
{
var createInput = new CreateValidatedVisitInput(resolvedVisit)
{
LockId = visitLockId,
WithDependencies = !oldVisitData.MimicUpdate,
SkipAutoConfirm = oldVisitData.MimicUpdate,
OldVisitId = oldVisitData.Id
};
return CancelVisitWithDependencies(oldVisitData.Id, visitMoveData.Source, oldVisitData.Reason)
.FlatMapAsync(cancelOps => CreateValidatedAsync(createInput)
.TransparentExecuteAsync(visit => SwitchConfirmationsIfNeeded(
oldVisitData.Id,
visit.Value.MasterVisit.Entity,
oldVisitData.MimicUpdate))
.TransparentExecuteAsync(visit => SwitchDependentEntities(oldVisitData, visit.Value))
.TransparentExecuteAsync(visit => SwitchDependentVisitsIfNeeded(
oldVisitData.Id,
visit.Value.MasterVisit.Entity,
cancelOps.VisitIds))
.TransparentExecuteAsync(async visit =>
{
var newVisit = visit.Value.MasterVisit.Entity;
// Sprawdzenie, czy data, godzina i miejsce są takie same
bool isSameDateTimeAndPlace = oldVisitData.Entity.From == newVisit.From &&
oldVisitData.Entity.To == newVisit.To &&
oldVisitData.Entity.OrganizationUnitId == newVisit.OrganizationUnitId;
if (!isSameDateTimeAndPlace)
{
await _patientVisitNotificationService.NotifyVisitMovedAsync(
newVisit,
visitMoveData.Source,
oldVisitData.Id);
}
})
.TransparentExecuteAsync(newVisit => LogMoveVisitEvent(
oldVisitData.Entity,
newVisit.Value.MasterVisit,
oldVisitData.MimicUpdate,
resolvedVisit.Force))
.MapAsync(createOperationSet => createOperationSet.Merge(cancelOps).Map(v => v.MasterVisit))
);
}
Wyjaśnienie Zmian
-
Dodanie Warunku Sprawdzającego:
- W ramach kroku
.TransparentExecuteAsync, przed wywołaniem NotifyVisitMovedAsync, dodaliśmy warunek, który sprawdza, czy data (From i To) oraz identyfikator jednostki organizacyjnej (OrganizationUnitId) nowej wizyty są różne od tych w oldVisitData.
- Jeśli którakolwiek z tych wartości się różni, metoda
NotifyVisitMovedAsync zostanie wywołana. W przeciwnym razie, wywołanie tej metody zostanie pominięte.
-
Porównanie Właściwości:
oldVisitData.Entity.From i newVisit.From: Porównuje datę rozpoczęcia wizyty.
oldVisitData.Entity.To i newVisit.To: Porównuje datę zakończenia wizyty.
oldVisitData.Entity.OrganizationUnitId i newVisit.OrganizationUnitId: Porównuje identyfikator jednostki organizacyjnej, czyli miejsce wizyty.
-
Uwaga na Inne Właściwości:
- Upewnij się, że pola
From, To oraz OrganizationUnitId są właściwie zmapowane i dostępne w obu obiektach (oldVisitData.Entity i newVisit).
Dodatkowe Rozważania
-
Null Safety: Jeśli istnieje możliwość, że którykolwiek z porównywanych pól może być null, warto dodać dodatkowe sprawdzenia lub użyć operatora ?. oraz porównywać za pomocą metod, które obsługują wartości null bez podnoszenia wyjątków.
bool isSameDateTimeAndPlace = oldVisitData.Entity?.From == newVisit.From &&
oldVisitData.Entity?.To == newVisit.To &&
oldVisitData.Entity?.OrganizationUnitId == newVisit.OrganizationUnitId;
-
Optymalizacja Porównań: Jeśli porównania są kosztowne lub obiekty są duże, można rozważyć inne metody optymalizacji, takie jak przechowywanie skrótów (hash) lub innych wskaźników zmian.
-
Testowanie: Po wprowadzeniu zmian, należy przeprowadzić odpowiednie testy jednostkowe i integracyjne, aby upewnić się, że warunek działa zgodnie z oczekiwaniami i nie wpływa negatywnie na inne części systemu.
Przykładowy Test Jednostkowy
Aby upewnić się, że zmiana działa poprawnie, poniżej znajduje się przykładowy test jednostkowy:
[TestMethod]
public async Task MoveValidatedAsync_ShouldNotNotify_WhenDateTimeAndPlaceAreSame()
{
// Arrange
var oldVisitData = new OldVisitData(/* inicjalizacja z datą, czasem i miejscem */);
var visitMoveData = new VisitMoveData(/* inicjalizacja z tymi samymi datą, czasem i miejscem */);
var resolvedVisit = new ResolvedPatientVisit(/* inicjalizacja */);
var visitLockId = Guid.NewGuid();
var notificationServiceMock = new Mock<IPatientVisitNotificationService>();
// Inicjalizacja innych zależności...
var dbAdapter = new PatientVisitsDbAdapter(/* przekazanie zależności */)
{
_patientVisitNotificationService = notificationServiceMock.Object
};
// Act
await dbAdapter.MoveValidatedAsync(resolvedVisit, oldVisitData, visitMoveData, visitLockId);
// Assert
notificationServiceMock.Verify(
svc => svc.NotifyVisitMovedAsync(It.IsAny<IShallowPatientVisit>(), It.IsAny<PatientVisitRegistrationSource>(), It.IsAny<long>()),
Times.Never);
}
Taki test upewnia się, że metoda NotifyVisitMovedAsync nie jest wywoływana, gdy data, godzina oraz miejsce wizyty nie uległy zmianie.
Dzięki tym zmianom metoda MoveValidatedAsync będzie działać zgodnie z oczekiwaniami, wywołując NotifyVisitMovedAsync tylko wtedy, gdy nastąpiły zmiany w dacie, godzinie lub miejscu wizyty.