feat: 后端架构重构 — Endpoint→Service→Repository分层 + AI确认机制 + 异步任务持久化
- 核心业务拆分为 Endpoint → Application Service → Repository 三层 - AI写入操作必须用户确认后才写库(确认卡片机制) - 报告/饮食/用药分析改为持久化任务队列(原子领取/重试/重启恢复) - 运动计划修复: 连续真实日期替代周模板 - 用药提醒去重 + 通知Outbox预留 - 认证收拢到AuthService, 管理员收拢到AdminService - AI会话加用户归属校验防串号 - 提示词调整为患者视角 - 开发假数据已关闭 - 21/21测试通过, 0警告0错误
This commit is contained in:
@@ -21,9 +21,10 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Health.Application\Health.Application.csproj" />
|
||||
<ProjectReference Include="..\..\src\Health.WebApi\Health.WebApi.csproj" />
|
||||
<ProjectReference Include="..\..\src\Health.Domain\Health.Domain.csproj" />
|
||||
<ProjectReference Include="..\..\src\Health.Infrastructure\Health.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
149
backend/tests/Health.Tests/application_service_tests.cs
Normal file
149
backend/tests/Health.Tests/application_service_tests.cs
Normal file
@@ -0,0 +1,149 @@
|
||||
using Health.Application.AI;
|
||||
using Health.Application.Calendars;
|
||||
using Health.Application.HealthArchives;
|
||||
using Health.Application.Exercises;
|
||||
using Health.Domain.Entities;
|
||||
using Health.Domain.Enums;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class ApplicationServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task HealthArchive_AiUpdate_OnlyChangesRequestedSection()
|
||||
{
|
||||
var userId = Guid.NewGuid();
|
||||
var repository = new FakeHealthArchiveRepository(new HealthArchive
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Diagnosis = "原诊断",
|
||||
Allergies = ["青霉素"]
|
||||
});
|
||||
var service = new HealthArchiveService(repository);
|
||||
|
||||
var result = await service.ExecuteAiActionAsync(
|
||||
userId,
|
||||
"update_diagnosis",
|
||||
new HealthArchiveUpdateRequest("新诊断", "不应写入的手术", null, null, null, null, null),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.True((bool)result.GetType().GetProperty("success")!.GetValue(result)!);
|
||||
Assert.Equal("新诊断", repository.Archive!.Diagnosis);
|
||||
Assert.Null(repository.Archive.SurgeryType);
|
||||
Assert.Equal(["青霉素"], repository.Archive.Allergies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Conversation_Open_DoesNotReturnAnotherUsersConversation()
|
||||
{
|
||||
var ownerId = Guid.NewGuid();
|
||||
var conversation = new Conversation { Id = Guid.NewGuid(), UserId = ownerId, AgentType = AgentType.Health };
|
||||
var service = new AiConversationService(new FakeConversationRepository(conversation));
|
||||
|
||||
var result = await service.OpenAsync(Guid.NewGuid(), conversation.Id, AgentType.Health, "测试", CancellationToken.None);
|
||||
|
||||
Assert.False(result.Found);
|
||||
Assert.False(result.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Calendar_Month_AggregatesMedicationExerciseAndFollowUp()
|
||||
{
|
||||
var date = new DateOnly(2026, 6, 19);
|
||||
var medication = new Medication
|
||||
{
|
||||
Id = Guid.NewGuid(), IsActive = true, Name = "阿司匹林", StartDate = date.AddDays(-1), TimeOfDay = [new TimeOnly(8, 0)]
|
||||
};
|
||||
var plan = new ExercisePlan { Id = Guid.NewGuid(), StartDate = date, EndDate = date, ReminderTime = new TimeOnly(19, 0) };
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = date, ExerciseType = "散步", DurationMinutes = 30 });
|
||||
var followUp = new FollowUp { Id = Guid.NewGuid(), ScheduledAt = date.ToDateTime(new TimeOnly(9, 0)), Title = "复查" };
|
||||
var service = new CalendarService(new FakeCalendarRepository(new CalendarDataSnapshot([medication], [plan], [followUp])));
|
||||
|
||||
var result = await service.GetMonthAsync(Guid.NewGuid(), 2026, 6, CancellationToken.None);
|
||||
|
||||
var target = Assert.Single(result, item =>
|
||||
item.GetType().GetProperty("date")!.GetValue(item)?.ToString() == "2026-06-19");
|
||||
var events = (IEnumerable<string>)target.GetType().GetProperty("events")!.GetValue(target)!;
|
||||
Assert.Equal(["medication", "exercise", "followup"], events);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExercisePlan_TenDays_CreatesTenUniqueConsecutiveDates()
|
||||
{
|
||||
var repository = new FakeExerciseRepository();
|
||||
var service = new ExerciseService(repository);
|
||||
var start = new DateOnly(2026, 6, 20);
|
||||
|
||||
await service.CreateAsync(Guid.NewGuid(), new ExercisePlanCreateRequest(start, start.AddDays(9), "跑步", 30, new TimeOnly(19, 0)), CancellationToken.None);
|
||||
|
||||
var plan = Assert.IsType<ExercisePlan>(repository.Plan);
|
||||
Assert.Equal(start.AddDays(9), plan.EndDate);
|
||||
Assert.Equal(10, plan.Items.Count);
|
||||
Assert.Equal(10, plan.Items.Select(x => x.ScheduledDate).Distinct().Count());
|
||||
Assert.Equal(Enumerable.Range(0, 10).Select(start.AddDays), plan.Items.OrderBy(x => x.ScheduledDate).Select(x => x.ScheduledDate));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExercisePlan_CurrentUsesExactScheduledDate()
|
||||
{
|
||||
var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(8));
|
||||
var repository = new FakeExerciseRepository();
|
||||
var plan = new ExercisePlan
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = Guid.NewGuid(), StartDate = today, EndDate = today.AddDays(9), ReminderTime = new TimeOnly(19, 0),
|
||||
};
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = today, ExerciseType = "跑步", DurationMinutes = 30 });
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = today.AddDays(7), ExerciseType = "跑步", DurationMinutes = 30 });
|
||||
repository.SetPlan(plan);
|
||||
var service = new ExerciseService(repository);
|
||||
|
||||
var current = await service.GetCurrentAsync(plan.UserId, CancellationToken.None);
|
||||
|
||||
Assert.NotNull(current);
|
||||
Assert.Equal(today, current!.Items.Single(x => x.ScheduledDate == today).ScheduledDate);
|
||||
Assert.Equal(2, current.Items.Count);
|
||||
}
|
||||
|
||||
private sealed class FakeHealthArchiveRepository(HealthArchive? archive) : IHealthArchiveRepository
|
||||
{
|
||||
public HealthArchive? Archive { get; private set; } = archive;
|
||||
public Task<HealthArchive?> GetByUserIdAsync(Guid userId, CancellationToken ct) => Task.FromResult(Archive?.UserId == userId ? Archive : null);
|
||||
public Task AddAsync(HealthArchive value, CancellationToken ct) { Archive = value; return Task.CompletedTask; }
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class FakeConversationRepository(Conversation conversation) : IAiConversationRepository
|
||||
{
|
||||
private readonly Conversation _conversation = conversation;
|
||||
public Task<Conversation?> GetOwnedAsync(Guid userId, Guid conversationId, CancellationToken ct) => Task.FromResult(_conversation.Id == conversationId && _conversation.UserId == userId ? _conversation : null);
|
||||
public Task<Conversation?> GetAsync(Guid conversationId, CancellationToken ct) => Task.FromResult(_conversation.Id == conversationId ? _conversation : null);
|
||||
public Task<IReadOnlyList<Conversation>> ListAsync(Guid userId, CancellationToken ct) => Task.FromResult<IReadOnlyList<Conversation>>([]);
|
||||
public Task<IReadOnlyList<ConversationMessage>> GetMessagesAsync(Guid conversationId, CancellationToken ct) => Task.FromResult<IReadOnlyList<ConversationMessage>>([]);
|
||||
public Task<IReadOnlyList<ConversationMessage>> GetRecentMessagesAsync(Guid conversationId, int limit, CancellationToken ct) => Task.FromResult<IReadOnlyList<ConversationMessage>>([]);
|
||||
public Task AddConversationAsync(Conversation value, CancellationToken ct) => Task.CompletedTask;
|
||||
public Task AddMessageAsync(ConversationMessage message, CancellationToken ct) => Task.CompletedTask;
|
||||
public void Delete(Conversation value) { }
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class FakeCalendarRepository(CalendarDataSnapshot snapshot) : ICalendarRepository
|
||||
{
|
||||
public Task<CalendarDataSnapshot> GetSnapshotAsync(Guid userId, DateOnly start, DateOnly end, CancellationToken ct) => Task.FromResult(snapshot);
|
||||
}
|
||||
|
||||
private sealed class FakeExerciseRepository : IExerciseRepository
|
||||
{
|
||||
public ExercisePlan? Plan { get; private set; }
|
||||
public void SetPlan(ExercisePlan plan) => Plan = plan;
|
||||
public Task<IReadOnlyList<ExercisePlan>> ListActiveOnAsync(Guid userId, DateOnly date, CancellationToken ct) => Task.FromResult<IReadOnlyList<ExercisePlan>>(
|
||||
Plan != null && Plan.UserId == userId && Plan.StartDate <= date && Plan.EndDate >= date ? [Plan] : []);
|
||||
public Task<IReadOnlyList<ExercisePlan>> ListAsync(Guid userId, int limit, CancellationToken ct) => Task.FromResult<IReadOnlyList<ExercisePlan>>([]);
|
||||
public Task<ExercisePlan?> GetOwnedPlanAsync(Guid userId, Guid planId, CancellationToken ct) => Task.FromResult(Plan);
|
||||
public Task<ExercisePlan?> GetLatestAsync(Guid userId, CancellationToken ct) => Task.FromResult(Plan);
|
||||
public Task<ExercisePlanItem?> GetOwnedItemAsync(Guid userId, Guid itemId, CancellationToken ct) => Task.FromResult(Plan?.Items.FirstOrDefault(x => x.Id == itemId));
|
||||
public Task AddAsync(ExercisePlan plan, CancellationToken ct) { Plan = plan; return Task.CompletedTask; }
|
||||
public void Delete(ExercisePlan plan) { Plan = null; }
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -204,10 +204,10 @@ public class EntityTests
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var monday = new DateOnly(2026, 6, 1);
|
||||
var plan = new ExercisePlan { Id = Guid.NewGuid(), UserId = user.Id, WeekStartDate = monday };
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 0, ExerciseType = "散步", DurationMinutes = 30, IsCompleted = true, CompletedAt = DateTime.UtcNow });
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 1, ExerciseType = "慢跑", DurationMinutes = 20 });
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 2, IsRestDay = true });
|
||||
var plan = new ExercisePlan { Id = Guid.NewGuid(), UserId = user.Id, StartDate = monday, EndDate = monday.AddDays(2), ReminderTime = new TimeOnly(19, 0) };
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = monday, ExerciseType = "散步", DurationMinutes = 30, IsCompleted = true, CompletedAt = DateTime.UtcNow });
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = monday.AddDays(1), ExerciseType = "慢跑", DurationMinutes = 20 });
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), ScheduledDate = monday.AddDays(2), IsRestDay = true });
|
||||
db.ExercisePlans.Add(plan);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
|
||||
76
backend/tests/Health.Tests/persistence_pipeline_tests.cs
Normal file
76
backend/tests/Health.Tests/persistence_pipeline_tests.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using Health.Infrastructure.AI;
|
||||
using Health.Infrastructure.Data;
|
||||
using Health.Infrastructure.Data.Records;
|
||||
using Health.Infrastructure.Reports;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class PersistencePipelineTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AiConfirmation_CanOnlyBeTakenOnceByOwner()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var store = new EfAiWriteConfirmationStore(db);
|
||||
var ownerId = Guid.NewGuid();
|
||||
var command = await store.CreateAsync(ownerId, "record_health_data", "{}", TimeSpan.FromMinutes(10), CancellationToken.None);
|
||||
|
||||
var wrongUser = await store.TakeAsync(command.Id, Guid.NewGuid(), CancellationToken.None);
|
||||
var firstTake = await store.TakeAsync(command.Id, ownerId, CancellationToken.None);
|
||||
var secondTake = await store.TakeAsync(command.Id, ownerId, CancellationToken.None);
|
||||
|
||||
Assert.Null(wrongUser);
|
||||
Assert.NotNull(firstTake);
|
||||
Assert.Null(secondTake);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportTask_RetryUsesBackoffBeforeMaxAttempts()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var task = NewReportTask(attempts: 1);
|
||||
db.ReportAnalysisTasks.Add(task);
|
||||
await db.SaveChangesAsync();
|
||||
var queue = new EfReportAnalysisQueue(db);
|
||||
var before = DateTime.UtcNow;
|
||||
|
||||
await queue.RetryAsync(task.Id, "temporary failure", CancellationToken.None);
|
||||
|
||||
Assert.Equal("Pending", task.Status);
|
||||
Assert.True(task.AvailableAt > before);
|
||||
Assert.Equal("temporary failure", task.LastError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportTask_RetryMarksFailedAtMaxAttempts()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var task = NewReportTask(attempts: 3);
|
||||
db.ReportAnalysisTasks.Add(task);
|
||||
await db.SaveChangesAsync();
|
||||
var queue = new EfReportAnalysisQueue(db);
|
||||
|
||||
await queue.RetryAsync(task.Id, new string('x', 2500), CancellationToken.None);
|
||||
|
||||
Assert.Equal("Failed", task.Status);
|
||||
Assert.Equal(2000, task.LastError!.Length);
|
||||
}
|
||||
|
||||
private static ReportAnalysisTaskRecord NewReportTask(int attempts) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
ReportId = Guid.NewGuid(),
|
||||
FilePath = "report.jpg",
|
||||
Status = "Processing",
|
||||
Attempts = attempts,
|
||||
AvailableAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
private static AppDbContext CreateDbContext() => new(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options);
|
||||
}
|
||||
Reference in New Issue
Block a user