feat: 应用内通知系统 + 结构化手术史/用药等相关改动

- 新增用户通知 outbox 流水线(EfUserNotificationPipeline)与后台投递 worker
- 通知中心页面及前端通知服务接入
- 健康指标异常、用药/运动提醒等事件统一产出站内通知
- 健康档案结构化手术史、用药提醒扫描、医生/用户端点等配套调整
- AppDbContext 注册通知相关实体
This commit is contained in:
MingNian
2026-06-21 21:06:29 +08:00
parent b57d0d16f4
commit 13714d9ed8
34 changed files with 1541 additions and 200 deletions

View File

@@ -24,7 +24,10 @@ public sealed class PatientContextService(
if (archive != null)
{
if (!string.IsNullOrEmpty(archive.Diagnosis)) sb.AppendLine($"诊断: {archive.Diagnosis}");
if (!string.IsNullOrEmpty(archive.SurgeryType)) sb.AppendLine($"手术: {archive.SurgeryType} ({archive.SurgeryDate})");
if (archive.Surgeries.Count > 0)
sb.AppendLine($"手术: {string.Join("", archive.Surgeries.Select(s => $"{s.Type} ({s.Date})"))}");
else if (!string.IsNullOrEmpty(archive.SurgeryType))
sb.AppendLine($"手术: {archive.SurgeryType} ({archive.SurgeryDate})");
if (archive.ChronicDiseases.Count > 0) sb.AppendLine($"慢病史: {string.Join(", ", archive.ChronicDiseases)}");
if (!string.IsNullOrEmpty(archive.FamilyHistory)) sb.AppendLine($"家族病史: {archive.FamilyHistory}");
if (archive.Allergies.Count > 0) sb.AppendLine($"过敏: {string.Join(", ", archive.Allergies)}");

View File

@@ -2,12 +2,22 @@ using Health.Domain.Entities;
namespace Health.Application.HealthArchives;
public sealed record HealthArchiveSurgeryDto(
Guid Id,
string Type,
DateOnly? Date);
public sealed record HealthArchiveSurgeryInput(
string Type,
DateOnly? Date);
public sealed record HealthArchiveDto(
Guid Id,
Guid UserId,
string? Diagnosis,
string? SurgeryType,
DateOnly? SurgeryDate,
IReadOnlyList<HealthArchiveSurgeryDto> Surgeries,
IReadOnlyList<string> Allergies,
IReadOnlyList<string> DietRestrictions,
IReadOnlyList<string> ChronicDiseases,
@@ -21,7 +31,8 @@ public sealed record HealthArchiveUpdateRequest(
IReadOnlyList<string>? Allergies,
IReadOnlyList<string>? DietRestrictions,
IReadOnlyList<string>? ChronicDiseases,
string? FamilyHistory);
string? FamilyHistory,
IReadOnlyList<HealthArchiveSurgeryInput>? Surgeries = null);
public interface IHealthArchiveService
{

View File

@@ -42,7 +42,8 @@ public sealed class HealthArchiveService(IHealthArchiveRepository archives) : IH
"update_diagnosis" => request with
{
SurgeryType = null, SurgeryDate = null, Allergies = null,
DietRestrictions = null, ChronicDiseases = null, FamilyHistory = null
DietRestrictions = null, ChronicDiseases = null, FamilyHistory = null,
Surgeries = null
},
"update_surgery" => request with
{
@@ -77,8 +78,41 @@ public sealed class HealthArchiveService(IHealthArchiveRepository archives) : IH
private static void Apply(HealthArchive archive, HealthArchiveUpdateRequest request)
{
if (request.Diagnosis != null) archive.Diagnosis = request.Diagnosis;
if (request.SurgeryType != null) archive.SurgeryType = request.SurgeryType;
if (request.SurgeryDate.HasValue) archive.SurgeryDate = request.SurgeryDate.Value;
if (request.Surgeries != null)
{
archive.Surgeries.Clear();
var items = request.Surgeries
.Where(s => !string.IsNullOrWhiteSpace(s.Type))
.Select((s, index) => new HealthArchiveSurgery
{
Id = Guid.NewGuid(),
HealthArchiveId = archive.Id,
Type = s.Type.Trim(),
Date = s.Date,
SortOrder = index,
})
.ToList();
foreach (var item in items) archive.Surgeries.Add(item);
SyncLegacySurgeryFields(archive);
}
else if (request.SurgeryType != null)
{
SeedLegacySurgeryIfNeeded(archive);
var type = request.SurgeryType.Trim();
if (type.Length > 0 && !archive.Surgeries.Any(s =>
s.Type == type && s.Date == request.SurgeryDate))
{
archive.Surgeries.Add(new HealthArchiveSurgery
{
Id = Guid.NewGuid(),
HealthArchiveId = archive.Id,
Type = type,
Date = request.SurgeryDate,
SortOrder = archive.Surgeries.Count,
});
}
SyncLegacySurgeryFields(archive);
}
if (request.Allergies != null) archive.Allergies = request.Allergies.ToList();
if (request.DietRestrictions != null) archive.DietRestrictions = request.DietRestrictions.ToList();
if (request.ChronicDiseases != null) archive.ChronicDiseases = request.ChronicDiseases.ToList();
@@ -91,6 +125,7 @@ public sealed class HealthArchiveService(IHealthArchiveRepository archives) : IH
archive.Diagnosis,
archive.SurgeryType,
SurgeryDate = archive.SurgeryDate?.ToString("yyyy-MM-dd"),
surgeries = archive.Surgeries.Select(s => new { s.Type, date = s.Date?.ToString("yyyy-MM-dd") }),
archive.Allergies,
archive.DietRestrictions,
archive.ChronicDiseases,
@@ -103,9 +138,41 @@ public sealed class HealthArchiveService(IHealthArchiveRepository archives) : IH
archive.Diagnosis,
archive.SurgeryType,
archive.SurgeryDate,
GetSurgeries(archive),
archive.Allergies,
archive.DietRestrictions,
archive.ChronicDiseases,
archive.FamilyHistory,
archive.UpdatedAt);
private static IReadOnlyList<HealthArchiveSurgeryDto> GetSurgeries(HealthArchive archive)
{
var surgeries = archive.Surgeries
.OrderBy(s => s.SortOrder)
.Select(s => new HealthArchiveSurgeryDto(s.Id, s.Type, s.Date))
.ToList();
if (surgeries.Count == 0 && !string.IsNullOrWhiteSpace(archive.SurgeryType))
surgeries.Add(new HealthArchiveSurgeryDto(Guid.Empty, archive.SurgeryType, archive.SurgeryDate));
return surgeries;
}
private static void SyncLegacySurgeryFields(HealthArchive archive)
{
var first = archive.Surgeries.OrderBy(s => s.SortOrder).FirstOrDefault();
archive.SurgeryType = first?.Type;
archive.SurgeryDate = first?.Date;
}
private static void SeedLegacySurgeryIfNeeded(HealthArchive archive)
{
if (archive.Surgeries.Count > 0 || string.IsNullOrWhiteSpace(archive.SurgeryType)) return;
archive.Surgeries.Add(new HealthArchiveSurgery
{
Id = Guid.NewGuid(),
HealthArchiveId = archive.Id,
Type = archive.SurgeryType,
Date = archive.SurgeryDate,
SortOrder = 0,
});
}
}

View File

@@ -78,7 +78,6 @@ public interface IMedicationRepository
Task<bool> DoseLogExistsAsync(Guid userId, Guid medicationId, TimeOnly scheduledTime, DateTime startUtc, DateTime endUtc, CancellationToken ct);
Task<MedicationLog?> GetDoseLogAsync(Guid userId, Guid medicationId, TimeOnly scheduledTime, DateTime startUtc, DateTime endUtc, CancellationToken ct);
Task<IReadOnlyList<Medication>> ListActiveForReminderScanAsync(CancellationToken ct);
Task<bool> HasTakenInWindowAsync(Guid userId, Guid medicationId, DateTime startUtc, DateTime endUtc, CancellationToken ct);
Task AddMedicationAsync(Medication medication, CancellationToken ct);
Task AddLogAsync(MedicationLog log, CancellationToken ct);
void DeleteMedication(Medication medication);

View File

@@ -21,10 +21,18 @@ public sealed class MedicationReminderScanner(IMedicationRepository medications)
foreach (var medication in active)
{
if (!IsActiveOn(medication, date) || !GetDosesForToday(medication, date)) continue;
if (await _medications.HasTakenInWindowAsync(medication.UserId, medication.Id, todayStartUtc, todayEndUtc, ct)) continue;
foreach (var scheduledTime in medication.TimeOfDay.Where(t => IsInWindow(t, windowStart, time)))
{
if (await _medications.DoseLogExistsAsync(
medication.UserId,
medication.Id,
scheduledTime,
todayStartUtc,
todayEndUtc,
ct))
continue;
tasks.Add(new MedicationReminderTask(
Guid.NewGuid(),
medication.UserId,

View File

@@ -5,22 +5,56 @@ public sealed record InAppNotificationDto(
string Type,
string Title,
string Message,
string Severity,
string? ActionType,
string? ActionTargetId,
bool IsRead,
DateTime CreatedAt);
public sealed record NotificationMessage(
string Type,
string Title,
string Message,
string Severity,
string? ActionType,
string? ActionTargetId);
public interface IInAppNotificationService
{
Task<IReadOnlyList<InAppNotificationDto>> GetPendingAsync(Guid userId, CancellationToken ct);
Task<IReadOnlyList<InAppNotificationDto>> GetHistoryAsync(Guid userId, CancellationToken ct);
Task<bool> AcknowledgeAsync(Guid userId, Guid notificationId, CancellationToken ct);
Task<int> MarkAllReadAsync(Guid userId, CancellationToken ct);
Task<bool> DeleteAsync(Guid userId, Guid notificationId, CancellationToken ct);
}
public interface IInAppNotificationRepository
{
Task<IReadOnlyList<InAppNotificationRecord>> GetPendingAsync(Guid userId, CancellationToken ct);
Task<IReadOnlyList<InAppNotificationRecord>> GetHistoryAsync(Guid userId, CancellationToken ct);
Task<bool> AcknowledgeAsync(Guid userId, Guid notificationId, CancellationToken ct);
Task<int> MarkAllReadAsync(Guid userId, CancellationToken ct);
Task<bool> DeleteAsync(Guid userId, Guid notificationId, CancellationToken ct);
}
public sealed record InAppNotificationRecord(
Guid Id,
string Type,
string Payload,
string Title,
string Message,
string Severity,
string? ActionType,
string? ActionTargetId,
bool IsRead,
DateTime CreatedAt);
public interface IUserNotificationProducer
{
Task<bool> EnqueueAsync(Guid userId, Guid sourceId, NotificationMessage message, CancellationToken ct);
}
public interface INotificationOutboxProcessor
{
Task RecoverStaleAsync(CancellationToken ct);
Task<bool> ProcessNextAsync(CancellationToken ct);
}

View File

@@ -1,5 +1,3 @@
using System.Text.Json;
namespace Health.Application.Notifications;
public sealed class InAppNotificationService(IInAppNotificationRepository notifications) : IInAppNotificationService
@@ -12,36 +10,22 @@ public sealed class InAppNotificationService(IInAppNotificationRepository notifi
return records.Select(ToDto).ToList();
}
public async Task<IReadOnlyList<InAppNotificationDto>> GetHistoryAsync(Guid userId, CancellationToken ct)
{
var records = await _notifications.GetHistoryAsync(userId, ct);
return records.Select(ToDto).ToList();
}
public Task<bool> AcknowledgeAsync(Guid userId, Guid notificationId, CancellationToken ct) =>
_notifications.AcknowledgeAsync(userId, notificationId, ct);
private static InAppNotificationDto ToDto(InAppNotificationRecord record)
{
if (record.Type == "MedicationReminder")
{
using var json = JsonDocument.Parse(record.Payload);
var root = json.RootElement;
var name = root.TryGetProperty("Name", out var nameValue) ? nameValue.GetString() : null;
var dosage = root.TryGetProperty("Dosage", out var dosageValue) ? dosageValue.GetString() : null;
var time = root.TryGetProperty("ScheduledTime", out var timeValue) ? timeValue.GetString() : null;
var details = string.Join(" · ", new[] { dosage, time }.Where(x => !string.IsNullOrWhiteSpace(x)));
return new InAppNotificationDto(
record.Id,
record.Type,
"用药提醒",
$"该服用{name ?? ""}{(details.Length > 0 ? $"{details}" : "")}了",
record.CreatedAt);
}
public Task<int> MarkAllReadAsync(Guid userId, CancellationToken ct) =>
_notifications.MarkAllReadAsync(userId, ct);
if (record.Type == "ExerciseReminder")
{
using var json = JsonDocument.Parse(record.Payload);
var root = json.RootElement;
var type = root.TryGetProperty("ExerciseType", out var typeValue) ? typeValue.GetString() : "运动";
var minutes = root.TryGetProperty("DurationMinutes", out var minutesValue) ? minutesValue.GetInt32() : 30;
return new InAppNotificationDto(record.Id, record.Type, "运动提醒", $"今天的{type}计划还未完成,目标 {minutes} 分钟", record.CreatedAt);
}
public Task<bool> DeleteAsync(Guid userId, Guid notificationId, CancellationToken ct) =>
_notifications.DeleteAsync(userId, notificationId, ct);
return new InAppNotificationDto(record.Id, record.Type, "健康提醒", "您有一条新的健康提醒", record.CreatedAt);
}
private static InAppNotificationDto ToDto(InAppNotificationRecord record) => new(
record.Id, record.Type, record.Title, record.Message, record.Severity,
record.ActionType, record.ActionTargetId, record.IsRead, record.CreatedAt);
}

View File

@@ -38,6 +38,18 @@ public sealed class HealthArchive
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
public User User { get; set; } = null!;
public ICollection<HealthArchiveSurgery> Surgeries { get; set; } = [];
}
public sealed class HealthArchiveSurgery
{
public Guid Id { get; set; }
public Guid HealthArchiveId { get; set; }
public string Type { get; set; } = string.Empty;
public DateOnly? Date { get; set; }
public int SortOrder { get; set; }
public HealthArchive HealthArchive { get; set; } = null!;
}
/// <summary>
@@ -97,3 +109,20 @@ public sealed class DeviceToken
public User User { get; set; } = null!;
}
public sealed class UserNotification
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Guid SourceId { get; set; }
public string Type { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public string Severity { get; set; } = "info";
public string? ActionType { get; set; }
public string? ActionTargetId { get; set; }
public bool IsRead { get; set; }
public DateTime? ReadAt { get; set; }
public bool IsDeleted { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

View File

@@ -55,7 +55,7 @@ public static class CommonAgentHandler
return new
{
found = true, archive.Diagnosis, archive.SurgeryType,
SurgeryDate = archive.SurgeryDate?.ToString("yyyy-MM-dd"),
SurgeryDate = archive.SurgeryDate?.ToString("yyyy-MM-dd"), archive.Surgeries,
archive.Allergies, archive.DietRestrictions, archive.ChronicDiseases, archive.FamilyHistory,
};
}

View File

@@ -28,11 +28,13 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbCon
public DbSet<DoctorProfile> DoctorProfiles => Set<DoctorProfile>();
public DbSet<FollowUp> FollowUps => Set<FollowUp>();
public DbSet<HealthArchive> HealthArchives => Set<HealthArchive>();
public DbSet<HealthArchiveSurgery> HealthArchiveSurgeries => Set<HealthArchiveSurgery>();
// 支撑表
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<VerificationCode> VerificationCodes => Set<VerificationCode>();
public DbSet<NotificationPreference> NotificationPreferences => Set<NotificationPreference>();
public DbSet<UserNotification> UserNotifications => Set<UserNotification>();
public DbSet<DeviceToken> DeviceTokens => Set<DeviceToken>();
public DbSet<AiWriteCommandRecord> AiWriteCommands => Set<AiWriteCommandRecord>();
public DbSet<ReportAnalysisTaskRecord> ReportAnalysisTasks => Set<ReportAnalysisTaskRecord>();
@@ -154,12 +156,33 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbCon
e.HasIndex(n => n.UserId).IsUnique();
});
builder.Entity<UserNotification>(e =>
{
e.ToTable("UserNotifications");
e.HasIndex(n => n.SourceId).IsUnique();
e.HasIndex(n => new { n.UserId, n.IsDeleted, n.IsRead, n.CreatedAt });
e.Property(n => n.Type).HasMaxLength(64);
e.Property(n => n.Severity).HasMaxLength(16);
e.Property(n => n.ActionType).HasMaxLength(64);
});
// ---- HealthArchive ----
builder.Entity<HealthArchive>(e =>
{
e.HasIndex(a => a.UserId).IsUnique();
});
builder.Entity<HealthArchiveSurgery>(e =>
{
e.ToTable("HealthArchiveSurgeries");
e.HasIndex(s => new { s.HealthArchiveId, s.SortOrder });
e.Property(s => s.Type).HasMaxLength(256);
e.HasOne(s => s.HealthArchive)
.WithMany(a => a.Surgeries)
.HasForeignKey(s => s.HealthArchiveId)
.OnDelete(DeleteBehavior.Cascade);
});
builder.Entity<AiWriteCommandRecord>(e =>
{
e.ToTable("AiWriteCommands");

View File

@@ -1,12 +1,13 @@
using System.Text.Json;
using Health.Application.Exercises;
using Health.Infrastructure.Data.Records;
using Health.Application.Notifications;
namespace Health.Infrastructure.Exercises;
public sealed class ExerciseReminderProducer(AppDbContext db) : IExerciseReminderProducer
public sealed class ExerciseReminderProducer(AppDbContext db, IUserNotificationProducer notifications) : IExerciseReminderProducer
{
private readonly AppDbContext _db = db;
private readonly IUserNotificationProducer _notifications = notifications;
public async Task<int> ProduceDueAsync(DateTime utcNow, CancellationToken ct)
{
@@ -17,28 +18,22 @@ public sealed class ExerciseReminderProducer(AppDbContext db) : IExerciseReminde
.Include(x => x.Plan)
.Where(x => x.ScheduledDate == today && !x.IsCompleted && !x.IsRestDay && x.Plan.ReminderTime <= currentTime)
.ToListAsync(ct);
var sourceIds = dueItems.Select(x => x.Id).ToList();
var existing = await _db.NotificationOutbox.AsNoTracking()
.Where(x => sourceIds.Contains(x.SourceTaskId))
.Select(x => x.SourceTaskId)
.ToListAsync(ct);
var existingSet = existing.ToHashSet();
var now = DateTime.UtcNow;
foreach (var item in dueItems.Where(x => !existingSet.Contains(x.Id)))
var created = 0;
foreach (var item in dueItems)
{
await _db.NotificationOutbox.AddAsync(new NotificationOutboxRecord
{
Id = Guid.NewGuid(), UserId = item.Plan.UserId, SourceTaskId = item.Id,
Type = "ExerciseReminder",
Payload = JsonSerializer.Serialize(new
{
item.ExerciseType, item.DurationMinutes, item.ScheduledDate,
ReminderTime = item.Plan.ReminderTime,
}),
Status = "AwaitingProvider", AvailableAt = now, CreatedAt = now, UpdatedAt = now,
}, ct);
if (await _notifications.EnqueueAsync(
item.Plan.UserId,
item.Id,
new NotificationMessage(
"ExerciseReminder",
"今日运动计划",
$"今天安排了 {item.ExerciseType} {item.DurationMinutes} 分钟,完成后记得打卡。",
"info",
"exercise",
item.PlanId.ToString()),
ct))
created++;
}
if (_db.ChangeTracker.HasChanges()) await _db.SaveChangesAsync(ct);
return dueItems.Count - existingSet.Count;
return created;
}
}

View File

@@ -7,7 +7,9 @@ public sealed class EfHealthArchiveRepository(AppDbContext db) : IHealthArchiveR
private readonly AppDbContext _db = db;
public Task<HealthArchive?> GetByUserIdAsync(Guid userId, CancellationToken ct) =>
_db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == userId, ct);
_db.HealthArchives
.Include(a => a.Surgeries)
.FirstOrDefaultAsync(a => a.UserId == userId, ct);
public async Task AddAsync(HealthArchive archive, CancellationToken ct) =>
await _db.HealthArchives.AddAsync(archive, ct);

View File

@@ -56,12 +56,6 @@ public sealed class EfMedicationRepository(AppDbContext db) : IMedicationReposit
.Where(m => m.IsActive && m.TimeOfDay.Count > 0)
.ToListAsync(ct);
public Task<bool> HasTakenInWindowAsync(Guid userId, Guid medicationId, DateTime startUtc, DateTime endUtc, CancellationToken ct) =>
_db.MedicationLogs.AnyAsync(l =>
l.UserId == userId && l.MedicationId == medicationId
&& l.CreatedAt >= startUtc && l.CreatedAt < endUtc
&& l.Status == MedicationLogStatus.Taken, ct);
public async Task AddMedicationAsync(Medication medication, CancellationToken ct) =>
await _db.Medications.AddAsync(medication, ct);

View File

@@ -1,43 +1,35 @@
using System.Text.Json;
using Health.Application.Medications;
using Health.Infrastructure.Data.Records;
using Health.Application.Notifications;
using Microsoft.Extensions.Logging;
namespace Health.Infrastructure.Medications;
public sealed class OutboxMedicationReminderDispatcher(
AppDbContext db,
IUserNotificationProducer notifications,
ILogger<OutboxMedicationReminderDispatcher> logger) : IMedicationReminderDispatcher
{
private readonly AppDbContext _db = db;
private readonly IUserNotificationProducer _notifications = notifications;
private readonly ILogger<OutboxMedicationReminderDispatcher> _logger = logger;
public async Task DispatchAsync(MedicationReminderTask task, CancellationToken ct)
{
if (await _db.NotificationOutbox.AsNoTracking().AnyAsync(x => x.SourceTaskId == task.TaskId, ct))
return;
var now = DateTime.UtcNow;
await _db.NotificationOutbox.AddAsync(new NotificationOutboxRecord
var details = string.Join(" · ", new[]
{
Id = Guid.NewGuid(),
UserId = task.UserId,
SourceTaskId = task.TaskId,
Type = "MedicationReminder",
Payload = JsonSerializer.Serialize(new
{
task.MedicationId,
task.Name,
task.Dosage,
task.ScheduledDate,
task.ScheduledTime,
}),
Status = "AwaitingProvider",
AvailableAt = now,
CreatedAt = now,
UpdatedAt = now,
}, ct);
await _db.SaveChangesAsync(ct);
task.Dosage,
task.ScheduledTime.ToString("HH:mm")
}.Where(x => !string.IsNullOrWhiteSpace(x)));
await _notifications.EnqueueAsync(
task.UserId,
task.TaskId,
new NotificationMessage(
"MedicationReminder",
"用药时间到了",
$"请按计划服用{task.Name}{(details.Length > 0 ? $"{details}" : "")},服用后记得打卡。",
"info",
"medication",
task.MedicationId.ToString()),
ct);
_logger.LogInformation(
"用药提醒已写入通知 Outbox等待推送服务: {TaskId} {UserId}",

View File

@@ -7,20 +7,46 @@ public sealed class EfInAppNotificationRepository(AppDbContext db) : IInAppNotif
private readonly AppDbContext _db = db;
public async Task<IReadOnlyList<InAppNotificationRecord>> GetPendingAsync(Guid userId, CancellationToken ct) =>
await _db.NotificationOutbox.AsNoTracking()
.Where(x => x.UserId == userId && x.Status == "AwaitingProvider")
await _db.UserNotifications.AsNoTracking()
.Where(x => x.UserId == userId && !x.IsRead && !x.IsDeleted)
.OrderBy(x => x.CreatedAt)
.Take(10)
.Select(x => new InAppNotificationRecord(x.Id, x.Type, x.Payload, x.CreatedAt))
.Select(x => new InAppNotificationRecord(x.Id, x.Type, x.Title, x.Message,
x.Severity, x.ActionType, x.ActionTargetId, x.IsRead, x.CreatedAt))
.ToListAsync(ct);
public async Task<IReadOnlyList<InAppNotificationRecord>> GetHistoryAsync(Guid userId, CancellationToken ct) =>
await _db.UserNotifications.AsNoTracking()
.Where(x => x.UserId == userId && !x.IsDeleted)
.OrderByDescending(x => x.CreatedAt)
.Take(100)
.Select(x => new InAppNotificationRecord(x.Id, x.Type, x.Title, x.Message,
x.Severity, x.ActionType, x.ActionTargetId, x.IsRead, x.CreatedAt))
.ToListAsync(ct);
public async Task<bool> AcknowledgeAsync(Guid userId, Guid notificationId, CancellationToken ct)
{
var updated = await _db.NotificationOutbox
.Where(x => x.Id == notificationId && x.UserId == userId && x.Status == "AwaitingProvider")
var updated = await _db.UserNotifications
.Where(x => x.Id == notificationId && x.UserId == userId && !x.IsRead && !x.IsDeleted)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, "InAppDelivered")
.SetProperty(x => x.UpdatedAt, DateTime.UtcNow), ct);
.SetProperty(x => x.IsRead, true)
.SetProperty(x => x.ReadAt, DateTime.UtcNow), ct);
return updated > 0;
}
public Task<int> MarkAllReadAsync(Guid userId, CancellationToken ct) =>
_db.UserNotifications
.Where(x => x.UserId == userId && !x.IsRead && !x.IsDeleted)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.IsRead, true)
.SetProperty(x => x.ReadAt, DateTime.UtcNow), ct);
public async Task<bool> DeleteAsync(Guid userId, Guid notificationId, CancellationToken ct)
{
var deleted = await _db.UserNotifications
.Where(x => x.Id == notificationId && x.UserId == userId && !x.IsDeleted)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.IsDeleted, true), ct);
return deleted > 0;
}
}

View File

@@ -0,0 +1,139 @@
using System.Text.Json;
using Health.Application.Notifications;
using Health.Infrastructure.Data.Records;
using Npgsql;
namespace Health.Infrastructure.Notifications;
public sealed class EfUserNotificationProducer(AppDbContext db) : IUserNotificationProducer
{
private readonly AppDbContext _db = db;
public async Task<bool> EnqueueAsync(
Guid userId,
Guid sourceId,
NotificationMessage message,
CancellationToken ct)
{
if (await _db.NotificationOutbox.AsNoTracking().AnyAsync(x => x.SourceTaskId == sourceId, ct))
return false;
var now = DateTime.UtcNow;
await _db.NotificationOutbox.AddAsync(new NotificationOutboxRecord
{
Id = Guid.NewGuid(),
UserId = userId,
SourceTaskId = sourceId,
Type = message.Type,
Payload = JsonSerializer.Serialize(message),
Status = "Pending",
AvailableAt = now,
CreatedAt = now,
UpdatedAt = now,
}, ct);
try
{
await _db.SaveChangesAsync(ct);
return true;
}
catch (DbUpdateException ex) when (
ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation })
{
_db.ChangeTracker.Clear();
return false;
}
}
}
public sealed class EfNotificationOutboxProcessor(AppDbContext db) : INotificationOutboxProcessor
{
private const int MaxAttempts = 5;
private readonly AppDbContext _db = db;
public async Task RecoverStaleAsync(CancellationToken ct)
{
var now = DateTime.UtcNow;
await _db.NotificationOutbox
.Where(x => x.Status == "Processing" &&
x.UpdatedAt < now.AddMinutes(-5) && x.Attempts < MaxAttempts)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, "Pending")
.SetProperty(x => x.AvailableAt, now)
.SetProperty(x => x.UpdatedAt, now), ct);
await _db.NotificationOutbox
.Where(x => x.Status == "Processing" &&
x.UpdatedAt < now.AddMinutes(-5) && x.Attempts >= MaxAttempts)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, "Failed")
.SetProperty(x => x.LastError, "通知任务执行超时且已达到最大重试次数")
.SetProperty(x => x.UpdatedAt, now), ct);
}
public async Task<bool> ProcessNextAsync(CancellationToken ct)
{
var now = DateTime.UtcNow;
var candidate = await _db.NotificationOutbox.AsNoTracking()
.Where(x => x.Status == "Pending" &&
x.AvailableAt <= now && x.Attempts < MaxAttempts)
.OrderBy(x => x.CreatedAt)
.FirstOrDefaultAsync(ct);
if (candidate == null) return false;
var claimed = await _db.NotificationOutbox
.Where(x => x.Id == candidate.Id && x.Status == "Pending")
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, "Processing")
.SetProperty(x => x.Attempts, x => x.Attempts + 1)
.SetProperty(x => x.UpdatedAt, now), ct);
if (claimed == 0) return true;
try
{
var message = JsonSerializer.Deserialize<NotificationMessage>(candidate.Payload)
?? throw new InvalidOperationException("通知消息内容为空");
if (!await _db.UserNotifications.AsNoTracking()
.AnyAsync(x => x.SourceId == candidate.SourceTaskId, ct))
{
await _db.UserNotifications.AddAsync(new UserNotification
{
Id = Guid.NewGuid(),
UserId = candidate.UserId,
SourceId = candidate.SourceTaskId,
Type = message.Type,
Title = message.Title,
Message = message.Message,
Severity = message.Severity,
ActionType = message.ActionType,
ActionTargetId = message.ActionTargetId,
CreatedAt = candidate.CreatedAt,
}, ct);
// Persist the inbox item first. If completion fails, stale-task
// recovery can safely retry because SourceId is idempotent.
await _db.SaveChangesAsync(ct);
}
await _db.NotificationOutbox.Where(x => x.Id == candidate.Id)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, "Completed")
.SetProperty(x => x.LastError, (string?)null)
.SetProperty(x => x.UpdatedAt, DateTime.UtcNow), ct);
}
catch (Exception ex)
{
var attempts = candidate.Attempts + 1;
await _db.NotificationOutbox.Where(x => x.Id == candidate.Id)
.ExecuteUpdateAsync(setters => setters
.SetProperty(x => x.Status, attempts >= MaxAttempts ? "Failed" : "Pending")
.SetProperty(x => x.AvailableAt,
DateTime.UtcNow.AddSeconds(Math.Pow(2, attempts) * 5))
.SetProperty(x => x.LastError,
ex.Message.Length > 2000 ? ex.Message[..2000] : ex.Message)
.SetProperty(x => x.UpdatedAt, DateTime.UtcNow), ct);
}
return true;
}
}

View File

@@ -40,6 +40,8 @@ public sealed class EfUserRepository(AppDbContext db) : IUserRepository
await _db.FollowUps.Where(f => f.UserId == userId).ExecuteDeleteAsync(ct);
await _db.RefreshTokens.Where(t => t.UserId == userId).ExecuteDeleteAsync(ct);
await _db.DeviceTokens.Where(t => t.UserId == userId).ExecuteDeleteAsync(ct);
await _db.UserNotifications.Where(n => n.UserId == userId).ExecuteDeleteAsync(ct);
await _db.NotificationOutbox.Where(n => n.UserId == userId).ExecuteDeleteAsync(ct);
await _db.NotificationPreferences.Where(p => p.UserId == userId).ExecuteDeleteAsync(ct);
await _db.HealthArchives.Where(a => a.UserId == userId).ExecuteDeleteAsync(ct);
await _db.AiWriteCommands.Where(c => c.UserId == userId).ExecuteDeleteAsync(ct);

View File

@@ -0,0 +1,37 @@
using Health.Application.Notifications;
namespace Health.WebApi.BackgroundServices;
public sealed class NotificationOutboxWorker(
IServiceScopeFactory scopeFactory,
ILogger<NotificationOutboxWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var nextRecovery = DateTime.MinValue;
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
var processor = scope.ServiceProvider.GetRequiredService<INotificationOutboxProcessor>();
if (DateTime.UtcNow >= nextRecovery)
{
await processor.RecoverStaleAsync(stoppingToken);
nextRecovery = DateTime.UtcNow.AddMinutes(1);
}
if (!await processor.ProcessNextAsync(stoppingToken))
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "通知 Outbox 消费失败");
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
}
}
}
}

View File

@@ -132,6 +132,7 @@ public static class DoctorEndpoints
var user = await db.Users
.Include(u => u.HealthArchive)
.ThenInclude(a => a!.Surgeries)
.FirstOrDefaultAsync(u => u.Id == id && u.DoctorId == doctorId);
if (user == null)
return Results.Ok(new { code = 404, data = (object?)null, message = "患者不存在" });
@@ -179,7 +180,18 @@ public static class DoctorEndpoints
data = new
{
profile = new { user.Id, user.Phone, user.Name, user.Gender, BirthDate = user.BirthDate?.ToString("yyyy-MM-dd"), user.AvatarUrl },
archive = user.HealthArchive == null ? null : new { user.HealthArchive.Diagnosis, user.HealthArchive.SurgeryType, SurgeryDate = user.HealthArchive.SurgeryDate?.ToString("yyyy-MM-dd"), user.HealthArchive.Allergies, user.HealthArchive.DietRestrictions, user.HealthArchive.ChronicDiseases, user.HealthArchive.FamilyHistory },
archive = user.HealthArchive == null ? null : new
{
user.HealthArchive.Diagnosis,
user.HealthArchive.SurgeryType,
SurgeryDate = user.HealthArchive.SurgeryDate?.ToString("yyyy-MM-dd"),
surgeries = user.HealthArchive.Surgeries.OrderBy(s => s.SortOrder)
.Select(s => new { s.Type, Date = s.Date.HasValue ? s.Date.Value.ToString("yyyy-MM-dd") : null }),
user.HealthArchive.Allergies,
user.HealthArchive.DietRestrictions,
user.HealthArchive.ChronicDiseases,
user.HealthArchive.FamilyHistory
},
latestRecords,
trendRecords,
medications,

View File

@@ -17,6 +17,19 @@ public static class NotificationEndpoints
return Results.Ok(new { code = 0, data = result, message = (string?)null });
});
group.MapGet("", async (HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
{
var userId = GetUserId(http);
if (userId == Guid.Empty) return Results.Unauthorized();
var result = await notifications.GetHistoryAsync(userId, ct);
return Results.Ok(new
{
code = 0,
data = new { unreadCount = result.Count(x => !x.IsRead), items = result },
message = (string?)null
});
});
group.MapPost("/{id:guid}/acknowledge", async (Guid id, HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
{
var userId = GetUserId(http);
@@ -24,6 +37,25 @@ public static class NotificationEndpoints
var acknowledged = await notifications.AcknowledgeAsync(userId, id, ct);
return Results.Ok(new { code = 0, data = new { acknowledged }, message = (string?)null });
});
group.MapPost("/read-all", async (HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
{
var userId = GetUserId(http);
if (userId == Guid.Empty) return Results.Unauthorized();
var count = await notifications.MarkAllReadAsync(userId, ct);
return Results.Ok(new { code = 0, data = new { count }, message = (string?)null });
});
group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, IInAppNotificationService notifications, CancellationToken ct) =>
{
var userId = GetUserId(http);
if (userId == Guid.Empty) return Results.Unauthorized();
var deleted = await notifications.DeleteAsync(userId, id, ct);
return deleted
? Results.Ok(new { code = 0, data = new { deleted = true }, message = (string?)null })
: Results.NotFound(new { code = 404, data = (object?)null, message = "通知不存在" });
});
}
private static Guid GetUserId(HttpContext http) =>

View File

@@ -36,6 +36,9 @@ public static class UserEndpoints
group.MapPut("/health-archive", async (UpdateArchiveRequest req, HttpContext http, IHealthArchiveService archives, CancellationToken ct) =>
{
var surgeryDate = DateOnly.TryParse(req.SurgeryDate, out var parsed) ? parsed : (DateOnly?)null;
var surgeries = req.Surgeries?.Select(s => new HealthArchiveSurgeryInput(
s.Type,
DateOnly.TryParse(s.Date, out var date) ? date : null)).ToList();
await archives.UpdateAsync(
GetUserId(http),
new HealthArchiveUpdateRequest(
@@ -45,7 +48,8 @@ public static class UserEndpoints
req.Allergies,
req.DietRestrictions,
req.ChronicDiseases,
req.FamilyHistory),
req.FamilyHistory,
surgeries),
ct);
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
});
@@ -65,4 +69,7 @@ public sealed record UpdateProfileRequest(string? Name, string? Gender, string?
public sealed record UpdateArchiveRequest(
string? Diagnosis, string? SurgeryType, string? SurgeryDate,
List<string>? Allergies, List<string>? DietRestrictions,
List<string>? ChronicDiseases, string? FamilyHistory);
List<string>? ChronicDiseases, string? FamilyHistory,
List<UpdateArchiveSurgeryRequest>? Surgeries);
public sealed record UpdateArchiveSurgeryRequest(string Type, string? Date);

View File

@@ -1,6 +1,7 @@
using Health.Application.AI;
using Health.Application.Calendars;
using Health.Application.HealthArchives;
using Health.Application.HealthRecords;
using Health.Application.Exercises;
using Health.Domain.Entities;
using Health.Domain.Enums;
@@ -34,6 +35,67 @@ public sealed class ApplicationServiceTests
Assert.Equal(["青霉素"], repository.Archive.Allergies);
}
[Fact]
public async Task HealthArchive_ManualUpdateStoresMultipleStructuredSurgeries()
{
var userId = Guid.NewGuid();
var repository = new FakeHealthArchiveRepository(new HealthArchive
{
Id = Guid.NewGuid(), UserId = userId,
});
var service = new HealthArchiveService(repository);
var result = await service.UpdateAsync(
userId,
new HealthArchiveUpdateRequest(
null, null, null, null, null, null, null,
[
new HealthArchiveSurgeryInput("PCI", new DateOnly(2025, 3, 1)),
new HealthArchiveSurgeryInput("Appendectomy", new DateOnly(2010, 6, 2)),
]),
CancellationToken.None);
Assert.Equal(2, result.Surgeries.Count);
Assert.Equal("PCI", result.SurgeryType);
Assert.Equal(new DateOnly(2025, 3, 1), result.SurgeryDate);
Assert.Equal([0, 1], repository.Archive!.Surgeries.OrderBy(s => s.SortOrder).Select(s => s.SortOrder));
}
[Fact]
public async Task HealthTrend_365DaysUsesFullYearWindow()
{
var repository = new CapturingHealthRecordRepository();
var service = new HealthRecordService(repository);
var before = DateTime.UtcNow;
await service.GetTrendAsync(Guid.NewGuid(), HealthMetricType.Weight, 365, CancellationToken.None);
Assert.NotNull(repository.RecordedAfter);
Assert.InRange((before - repository.RecordedAfter!.Value).TotalDays, 364.99, 365.01);
}
[Fact]
public async Task HealthArchive_AiSurgeryUpdatePreservesLegacySurgery()
{
var userId = Guid.NewGuid();
var repository = new FakeHealthArchiveRepository(new HealthArchive
{
Id = Guid.NewGuid(), UserId = userId,
SurgeryType = "Legacy surgery", SurgeryDate = new DateOnly(2010, 1, 2),
});
var service = new HealthArchiveService(repository);
await service.ExecuteAiActionAsync(
userId,
"update_surgery",
new HealthArchiveUpdateRequest(null, "New surgery", new DateOnly(2026, 6, 20), null, null, null, null),
CancellationToken.None);
Assert.Equal(2, repository.Archive!.Surgeries.Count);
Assert.Contains(repository.Archive.Surgeries, s => s.Type == "Legacy surgery");
Assert.Contains(repository.Archive.Surgeries, s => s.Type == "New surgery");
}
[Fact]
public async Task Conversation_Open_DoesNotReturnAnotherUsersConversation()
{
@@ -113,6 +175,23 @@ public sealed class ApplicationServiceTests
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
}
private sealed class CapturingHealthRecordRepository : IHealthRecordRepository
{
public DateTime? RecordedAfter { get; private set; }
public Task<IReadOnlyList<HealthRecord>> ListAsync(Guid userId, HealthMetricType? type, DateTime? recordedAfter, int limit, CancellationToken ct) =>
Task.FromResult<IReadOnlyList<HealthRecord>>([]);
public Task<HealthRecord?> GetOwnedAsync(Guid userId, Guid id, CancellationToken ct) => Task.FromResult<HealthRecord?>(null);
public Task<HealthRecord?> GetLatestByTypeAsync(Guid userId, HealthMetricType type, CancellationToken ct) => Task.FromResult<HealthRecord?>(null);
public Task<IReadOnlyList<HealthRecord>> GetTrendAsync(Guid userId, HealthMetricType type, DateTime recordedAfter, CancellationToken ct)
{
RecordedAfter = recordedAfter;
return Task.FromResult<IReadOnlyList<HealthRecord>>([]);
}
public Task AddAsync(HealthRecord record, CancellationToken ct) => Task.CompletedTask;
public void Delete(HealthRecord record) { }
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
}
private sealed class FakeConversationRepository(Conversation conversation) : IAiConversationRepository
{
private readonly Conversation _conversation = conversation;

View File

@@ -1,6 +1,11 @@
using Health.Application.Medications;
using Health.Domain.Entities;
using Health.Domain.Enums;
using Health.Infrastructure.AI;
using Health.Infrastructure.Data;
using Health.Infrastructure.Data.Records;
using Health.Infrastructure.Medications;
using Health.Infrastructure.Notifications;
using Health.Infrastructure.Reports;
using Microsoft.EntityFrameworkCore;
@@ -57,6 +62,112 @@ public sealed class PersistencePipelineTests
Assert.Equal(2000, task.LastError!.Length);
}
[Fact]
public async Task ReportTask_OnlyEnqueuesFailureNotificationAtFinalAttempt()
{
await using var db = CreateDbContext();
var userId = Guid.NewGuid();
var report = new Report
{
Id = Guid.NewGuid(),
UserId = userId,
FileUrl = "report.jpg",
Status = ReportStatus.Analyzing,
};
var task = NewReportTask(attempts: 2);
task.ReportId = report.Id;
db.Reports.Add(report);
db.ReportAnalysisTasks.Add(task);
await db.SaveChangesAsync();
var queue = new EfReportAnalysisQueue(db, new EfUserNotificationProducer(db));
await queue.RetryAsync(task.Id, "temporary failure", CancellationToken.None);
Assert.Empty(db.NotificationOutbox);
task.Status = "Processing";
task.Attempts = 3;
await db.SaveChangesAsync();
await queue.RetryAsync(task.Id, "final failure", CancellationToken.None);
var notification = Assert.Single(db.NotificationOutbox);
Assert.Equal(task.Id, notification.SourceTaskId);
Assert.Equal("ReportAnalysisFailed", notification.Type);
Assert.Equal(userId, notification.UserId);
}
[Fact]
public async Task MedicationReminder_MorningDoseDoesNotSuppressEveningDose()
{
await using var db = CreateDbContext();
var userId = Guid.NewGuid();
var medicationId = Guid.NewGuid();
var scanTimeUtc = new DateTime(2026, 6, 20, 12, 2, 0, DateTimeKind.Utc);
db.Medications.Add(new Medication
{
Id = medicationId,
UserId = userId,
Name = "测试药物",
Frequency = MedicationFrequency.TwiceDaily,
TimeOfDay = [new TimeOnly(8, 0), new TimeOnly(20, 0)],
StartDate = new DateOnly(2026, 6, 20),
IsActive = true,
});
db.MedicationLogs.Add(new MedicationLog
{
Id = Guid.NewGuid(),
UserId = userId,
MedicationId = medicationId,
Status = MedicationLogStatus.Taken,
ScheduledTime = new TimeOnly(8, 0),
ConfirmedAt = new DateTime(2026, 6, 20, 0, 1, 0, DateTimeKind.Utc),
CreatedAt = new DateTime(2026, 6, 20, 0, 1, 0, DateTimeKind.Utc),
});
await db.SaveChangesAsync();
var scanner = new MedicationReminderScanner(new EfMedicationRepository(db));
var tasks = await scanner.ScanAsync(scanTimeUtc, CancellationToken.None);
var reminder = Assert.Single(tasks);
Assert.Equal(new TimeOnly(20, 0), reminder.ScheduledTime);
}
[Fact]
public async Task MedicationReminder_ConfirmedDoseIsNotRemindedAgain()
{
await using var db = CreateDbContext();
var userId = Guid.NewGuid();
var medicationId = Guid.NewGuid();
var confirmedAt = new DateTime(2026, 6, 20, 12, 0, 0, DateTimeKind.Utc);
db.Medications.Add(new Medication
{
Id = medicationId,
UserId = userId,
Name = "测试药物",
Frequency = MedicationFrequency.Daily,
TimeOfDay = [new TimeOnly(20, 0)],
StartDate = new DateOnly(2026, 6, 20),
IsActive = true,
});
db.MedicationLogs.Add(new MedicationLog
{
Id = Guid.NewGuid(),
UserId = userId,
MedicationId = medicationId,
Status = MedicationLogStatus.Taken,
ScheduledTime = new TimeOnly(20, 0),
ConfirmedAt = confirmedAt,
CreatedAt = confirmedAt,
});
await db.SaveChangesAsync();
var scanner = new MedicationReminderScanner(new EfMedicationRepository(db));
var tasks = await scanner.ScanAsync(
new DateTime(2026, 6, 20, 12, 2, 0, DateTimeKind.Utc),
CancellationToken.None);
Assert.Empty(tasks);
}
private static ReportAnalysisTaskRecord NewReportTask(int attempts) => new()
{
Id = Guid.NewGuid(),