feat: 二级页面色彩刷新 + 用药/通知/设备重构 + 后端健康档案/通知管线增强 + 大量测试
## 后端 - 健康档案: 新增手术状态字段 + EF 迁移; HealthArchiveService 新增查询方法 - 健康记录: HealthRecordService 新增批量/统计方法; 契约扩展 - 用药: 新增 MedicationScheduleStatus 枚举; MedicationService 排班逻辑调整 - 通知: EfUserNotificationPipeline 重构; 新增 EfReminderCatchUpService; 通知管线支持更多场景 - 用户: UserService 账号删除逻辑; 新增 local_account_file_cleanup; EfUserRepository 扩展 - AI: medication_agent_handler 微调; prompt_manager 优化; AiConversationService 上下文处理 - Endpoint: doctor/medication/exercise/health/notification/user 等多接口调整 - BackgroundService: health_record_reminder_service 重构, 提醒补漏逻辑 - 测试: 新增 account_deletion/doctor_endpoint/medication_schedule/medication_update/prompt_manager 测试 ## 前端 - UI 系统: app_theme 大幅重构; app_colors/app_design_tokens/app_module_visuals 调整; 二级页面色彩刷新 - 主页: home_page 背景渐变 + 消息列表提取 _HomeMessages + 通知检查逻辑; chat_messages_view 全面重构 - 用药: medication_list/edit/checkin 三页重构, 新增 medication_ui_logic 抽取 - 通知: notification_prefs_page 重构, 新增 notification_prefs_logic; notification_center 优化 - 设备: device_management 重构, 新增 device_sync_ui_logic; device_scan 优化 - 趋势图: trend_page 大幅重构 - 登录: login_page 重构 - 个人资料: 新增 profile_edit_page; profile_page 优化 - 运动: 新增 exercise/ 目录 + care_plan_ui_logic - 其他: remaining_pages/report_pages/health_drawer/admin/doctor 等多页面调整 - 组件: common_widgets/app_empty_state/app_error_state/app_future_view/app_toast/ai_content 优化 - Provider: chat_provider/consultation_provider/data_providers/auth_provider 调整 - AndroidManifest: 移除多余权限 - 测试: 新增 ai_content/care_plan/home_message/login_flow/medication_checkin/medication_ui/notification_prefs/profile_device/secondary_page/swipe_delete 等大量测试 ## 文档 - 新增 ui-design-system.md 设计系统文档 - 新增 secondary-page-color-refresh 计划 + specs 目录
This commit is contained in:
120
backend/tests/Health.Tests/account_deletion_tests.cs
Normal file
120
backend/tests/Health.Tests/account_deletion_tests.cs
Normal file
@@ -0,0 +1,120 @@
|
||||
using Health.Application.Users;
|
||||
using Health.Domain.Entities;
|
||||
using Health.Infrastructure.Users;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class AccountDeletionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task LocalCleanup_DeletesOwnedUploadsWithoutTouchingOtherFiles()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"health-account-delete-{Guid.NewGuid():N}");
|
||||
var userId = Guid.NewGuid();
|
||||
var userDirectory = Path.Combine(root, "users", userId.ToString("N"));
|
||||
var reportPath = Path.Combine(root, "reports", "owned-report.pdf");
|
||||
var chatImagePath = Path.Combine(root, "owned-chat.jpg");
|
||||
var otherUserPath = Path.Combine(root, "users", Guid.NewGuid().ToString("N"), "keep.jpg");
|
||||
var outsidePath = Path.Combine(Path.GetDirectoryName(root)!, "outside-account-file.txt");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(userDirectory);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(reportPath)!);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(otherUserPath)!);
|
||||
await File.WriteAllTextAsync(Path.Combine(userDirectory, "unlinked-upload.jpg"), "owned");
|
||||
await File.WriteAllTextAsync(reportPath, "owned");
|
||||
await File.WriteAllTextAsync(chatImagePath, "owned");
|
||||
await File.WriteAllTextAsync(otherUserPath, "other");
|
||||
await File.WriteAllTextAsync(outsidePath, "outside");
|
||||
|
||||
var cleanup = new LocalAccountFileCleanup(root);
|
||||
var references = new AccountFileReferences(
|
||||
["/uploads/reports/owned-report.pdf", "/uploads/../outside-account-file.txt"],
|
||||
["{\"imageUrl\":\"/uploads/owned-chat.jpg\"}"]);
|
||||
|
||||
await cleanup.DeleteAsync(userId, references, CancellationToken.None);
|
||||
|
||||
Assert.False(Directory.Exists(userDirectory));
|
||||
Assert.False(File.Exists(reportPath));
|
||||
Assert.False(File.Exists(chatImagePath));
|
||||
Assert.True(File.Exists(otherUserPath));
|
||||
Assert.True(File.Exists(outsidePath));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
|
||||
if (File.Exists(outsidePath)) File.Delete(outsidePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserService_CleansFilesBeforeDeletingDatabaseData()
|
||||
{
|
||||
var calls = new List<string>();
|
||||
var references = new AccountFileReferences(["/uploads/reports/report.pdf"], []);
|
||||
var repository = new FakeUserRepository(references, calls);
|
||||
var cleanup = new FakeAccountFileCleanup(calls);
|
||||
var service = new UserService(repository, cleanup);
|
||||
|
||||
await service.DeleteAccountAsync(Guid.NewGuid(), CancellationToken.None);
|
||||
|
||||
Assert.Equal(["references", "files", "database"], calls);
|
||||
Assert.Same(references, cleanup.ReceivedReferences);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserService_DoesNotDeleteDatabaseWhenFileCleanupFails()
|
||||
{
|
||||
var calls = new List<string>();
|
||||
var repository = new FakeUserRepository(new AccountFileReferences([], []), calls);
|
||||
var service = new UserService(repository, new FailingAccountFileCleanup(calls));
|
||||
|
||||
await Assert.ThrowsAsync<IOException>(() =>
|
||||
service.DeleteAccountAsync(Guid.NewGuid(), CancellationToken.None));
|
||||
|
||||
Assert.Equal(["references", "files"], calls);
|
||||
}
|
||||
|
||||
private sealed class FakeUserRepository(
|
||||
AccountFileReferences references,
|
||||
List<string> calls) : IUserRepository
|
||||
{
|
||||
public Task<User?> GetAsync(Guid userId, CancellationToken ct) => Task.FromResult<User?>(null);
|
||||
|
||||
public Task<AccountFileReferences> GetAccountFileReferencesAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
calls.Add("references");
|
||||
return Task.FromResult(references);
|
||||
}
|
||||
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task DeleteAccountDataAsync(Guid userId, CancellationToken ct)
|
||||
{
|
||||
calls.Add("database");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeAccountFileCleanup(List<string> calls) : IAccountFileCleanup
|
||||
{
|
||||
public AccountFileReferences? ReceivedReferences { get; private set; }
|
||||
|
||||
public Task DeleteAsync(Guid userId, AccountFileReferences references, CancellationToken ct)
|
||||
{
|
||||
calls.Add("files");
|
||||
ReceivedReferences = references;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingAccountFileCleanup(List<string> calls) : IAccountFileCleanup
|
||||
{
|
||||
public Task DeleteAsync(Guid userId, AccountFileReferences references, CancellationToken ct)
|
||||
{
|
||||
calls.Add("files");
|
||||
throw new IOException("file is locked");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,8 @@ public sealed class ApplicationServiceTests
|
||||
var userId = Guid.NewGuid();
|
||||
var repository = new FakeHealthArchiveRepository(new HealthArchive
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId,
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
});
|
||||
var service = new HealthArchiveService(repository);
|
||||
|
||||
@@ -75,14 +76,35 @@ public sealed class ApplicationServiceTests
|
||||
Assert.InRange((before - repository.RecordedAfter!.Value).TotalDays, 364.99, 365.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HealthRecords_BatchPersistsAllReadingsWithOneSave()
|
||||
{
|
||||
var repository = new CapturingHealthRecordRepository();
|
||||
var service = new HealthRecordService(repository);
|
||||
|
||||
var ids = await service.CreateManyAsync(
|
||||
Guid.NewGuid(),
|
||||
[
|
||||
new HealthRecordUpsertRequest(HealthMetricType.BloodPressure, 116, 89, null, "mmHg", HealthRecordSource.DeviceSync, DateTime.UtcNow),
|
||||
new HealthRecordUpsertRequest(HealthMetricType.HeartRate, null, null, 72, "bpm", HealthRecordSource.DeviceSync, DateTime.UtcNow),
|
||||
],
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, ids.Count);
|
||||
Assert.Equal(2, repository.Added.Count);
|
||||
Assert.Equal(1, repository.SaveCount);
|
||||
}
|
||||
|
||||
[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),
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
SurgeryType = "Legacy surgery",
|
||||
SurgeryDate = new DateOnly(2010, 1, 2),
|
||||
});
|
||||
var service = new HealthArchiveService(repository);
|
||||
|
||||
@@ -110,13 +132,71 @@ public sealed class ApplicationServiceTests
|
||||
Assert.False(result.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Conversation_List_ReturnsAtMostThirtyRecentItems()
|
||||
{
|
||||
var userId = Guid.NewGuid();
|
||||
var conversations = Enumerable.Range(0, 35)
|
||||
.Select(index => new Conversation
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
AgentType = AgentType.Unified,
|
||||
UpdatedAt = DateTime.UtcNow.AddMinutes(-index),
|
||||
})
|
||||
.ToList();
|
||||
var service = new AiConversationService(new ListConversationRepository(conversations));
|
||||
|
||||
var result = await service.ListAsync(userId, CancellationToken.None);
|
||||
|
||||
Assert.Equal(30, result.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Conversation_Delete_ReportsWhetherARecordWasActuallyDeleted()
|
||||
{
|
||||
var method = typeof(IAiConversationService).GetMethod(nameof(IAiConversationService.DeleteAsync));
|
||||
|
||||
Assert.NotNull(method);
|
||||
Assert.Equal(typeof(Task<bool>), method!.ReturnType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Conversation_Open_ReactivatesTheSameOwnedConversation()
|
||||
{
|
||||
var userId = Guid.NewGuid();
|
||||
var conversation = new Conversation
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
AgentType = AgentType.Unified,
|
||||
UpdatedAt = DateTime.UtcNow.AddDays(-1),
|
||||
};
|
||||
var service = new AiConversationService(new FakeConversationRepository(conversation));
|
||||
|
||||
var result = await service.OpenAsync(
|
||||
userId,
|
||||
conversation.Id,
|
||||
AgentType.Unified,
|
||||
"新的追问",
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.True(result.Found);
|
||||
Assert.False(result.Created);
|
||||
Assert.Equal(conversation.Id, result.ConversationId);
|
||||
}
|
||||
|
||||
[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)]
|
||||
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 });
|
||||
@@ -154,7 +234,11 @@ public sealed class ApplicationServiceTests
|
||||
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),
|
||||
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 });
|
||||
@@ -175,11 +259,19 @@ public sealed class ApplicationServiceTests
|
||||
var repository = new FakeExerciseRepository();
|
||||
var plan = new ExercisePlan
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = Guid.NewGuid(), StartDate = today.AddDays(-1), EndDate = today, ReminderTime = new TimeOnly(19, 0),
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
StartDate = today.AddDays(-1),
|
||||
EndDate = today,
|
||||
ReminderTime = new TimeOnly(19, 0),
|
||||
};
|
||||
var item = new ExercisePlanItem
|
||||
{
|
||||
Id = Guid.NewGuid(), Plan = plan, ScheduledDate = today.AddDays(-1), ExerciseType = "散步", DurationMinutes = 30,
|
||||
Id = Guid.NewGuid(),
|
||||
Plan = plan,
|
||||
ScheduledDate = today.AddDays(-1),
|
||||
ExerciseType = "散步",
|
||||
DurationMinutes = 30,
|
||||
};
|
||||
plan.Items.Add(item);
|
||||
repository.SetPlan(plan);
|
||||
@@ -199,6 +291,8 @@ public sealed class ApplicationServiceTests
|
||||
private sealed class CapturingHealthRecordRepository : IHealthRecordRepository
|
||||
{
|
||||
public DateTime? RecordedAfter { get; private set; }
|
||||
public List<HealthRecord> Added { get; } = [];
|
||||
public int SaveCount { 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);
|
||||
@@ -208,9 +302,9 @@ public sealed class ApplicationServiceTests
|
||||
RecordedAfter = recordedAfter;
|
||||
return Task.FromResult<IReadOnlyList<HealthRecord>>([]);
|
||||
}
|
||||
public Task AddAsync(HealthRecord record, CancellationToken ct) => Task.CompletedTask;
|
||||
public Task AddAsync(HealthRecord record, CancellationToken ct) { Added.Add(record); return Task.CompletedTask; }
|
||||
public void Delete(HealthRecord record) { }
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
public Task SaveChangesAsync(CancellationToken ct) { SaveCount++; return Task.CompletedTask; }
|
||||
}
|
||||
|
||||
private sealed class FakeConversationRepository(Conversation conversation) : IAiConversationRepository
|
||||
@@ -228,6 +322,33 @@ public sealed class ApplicationServiceTests
|
||||
public Task SaveChangesAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class ListConversationRepository(List<Conversation> conversations) : IAiConversationRepository
|
||||
{
|
||||
private readonly List<Conversation> _conversations = conversations;
|
||||
public Task<Conversation?> GetOwnedAsync(Guid userId, Guid conversationId, CancellationToken ct) =>
|
||||
Task.FromResult(_conversations.FirstOrDefault(item => item.Id == conversationId && item.UserId == userId));
|
||||
public Task<Conversation?> GetAsync(Guid conversationId, CancellationToken ct) =>
|
||||
Task.FromResult(_conversations.FirstOrDefault(item => item.Id == conversationId));
|
||||
public Task<IReadOnlyList<Conversation>> ListAsync(Guid userId, CancellationToken ct) =>
|
||||
Task.FromResult<IReadOnlyList<Conversation>>(_conversations
|
||||
.Where(item => item.UserId == userId)
|
||||
.OrderByDescending(item => item.UpdatedAt)
|
||||
.ToList());
|
||||
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)
|
||||
{
|
||||
_conversations.Add(value);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public Task AddMessageAsync(ConversationMessage message, CancellationToken ct) => Task.CompletedTask;
|
||||
public Task<int> DeleteLegacyDietCommentaryArtifactsAsync(Guid userId, string promptPrefix, CancellationToken ct) => Task.FromResult(0);
|
||||
public void Delete(Conversation value) => _conversations.Remove(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);
|
||||
|
||||
17
backend/tests/Health.Tests/doctor_endpoint_tests.cs
Normal file
17
backend/tests/Health.Tests/doctor_endpoint_tests.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using Health.WebApi.Endpoints;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class DoctorEndpointTests
|
||||
{
|
||||
[Fact]
|
||||
public void BeijingDayRange_MapsEarlyUtcTimeToTheCorrectLocalDate()
|
||||
{
|
||||
var utcNow = new DateTime(2026, 7, 13, 17, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
var (startUtc, endUtc) = DoctorEndpoints.GetBeijingDayRange(utcNow);
|
||||
|
||||
Assert.Equal(new DateTime(2026, 7, 13, 16, 0, 0, DateTimeKind.Utc), startUtc);
|
||||
Assert.Equal(new DateTime(2026, 7, 14, 16, 0, 0, DateTimeKind.Utc), endUtc);
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,7 @@ public class EntityTests
|
||||
DietRestrictions = ["低盐", "低脂"],
|
||||
ChronicDiseases = ["高血压", "高血脂"],
|
||||
FamilyHistory = "父亲冠心病",
|
||||
SurgeryHistoryStatus = "有",
|
||||
};
|
||||
db.HealthArchives.Add(archive);
|
||||
await db.SaveChangesAsync();
|
||||
@@ -193,6 +194,7 @@ public class EntityTests
|
||||
Assert.Equal("冠心病", saved!.Diagnosis);
|
||||
Assert.Equal(2, saved.DietRestrictions.Count);
|
||||
Assert.Contains("低盐", saved.DietRestrictions);
|
||||
Assert.Equal("有", saved.SurgeryHistoryStatus);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
29
backend/tests/Health.Tests/medication_schedule_tests.cs
Normal file
29
backend/tests/Health.Tests/medication_schedule_tests.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using Health.Application.Medications;
|
||||
using Health.Domain.Enums;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class MedicationScheduleTests
|
||||
{
|
||||
[Fact]
|
||||
public void FutureDoseOutsideReminderWindow_RemainsVisibleAsScheduled()
|
||||
{
|
||||
var status = MedicationScheduleStatus.Resolve(
|
||||
new TimeOnly(18, 0),
|
||||
new TimeOnly(8, 0),
|
||||
logStatus: null);
|
||||
|
||||
Assert.Equal("scheduled", status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoggedDose_UsesItsActualStatus()
|
||||
{
|
||||
var status = MedicationScheduleStatus.Resolve(
|
||||
new TimeOnly(8, 0),
|
||||
new TimeOnly(12, 0),
|
||||
MedicationLogStatus.Taken);
|
||||
|
||||
Assert.Equal("taken", status);
|
||||
}
|
||||
}
|
||||
54
backend/tests/Health.Tests/medication_update_tests.cs
Normal file
54
backend/tests/Health.Tests/medication_update_tests.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using Health.Application.Medications;
|
||||
using Health.Domain.Entities;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class MedicationUpdateTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Update_CanClearAnExistingEndDate()
|
||||
{
|
||||
var medication = new Medication
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = Guid.NewGuid(),
|
||||
Name = "阿司匹林",
|
||||
StartDate = new DateOnly(2026, 7, 1),
|
||||
EndDate = new DateOnly(2026, 7, 31),
|
||||
};
|
||||
var repository = new FakeMedicationRepository(medication);
|
||||
var service = new MedicationService(repository);
|
||||
|
||||
var updated = await service.UpdateAsync(
|
||||
medication.UserId,
|
||||
medication.Id,
|
||||
new MedicationPatchRequest(
|
||||
null, null, null, null, null, null, null,
|
||||
ClearEndDate: true),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.True(updated);
|
||||
Assert.Null(medication.EndDate);
|
||||
Assert.True(repository.Saved);
|
||||
}
|
||||
|
||||
private sealed class FakeMedicationRepository(Medication medication) : IMedicationRepository
|
||||
{
|
||||
public bool Saved { get; private set; }
|
||||
|
||||
public Task<IReadOnlyList<Medication>> ListAsync(Guid userId, string? filter, CancellationToken ct) => Task.FromResult<IReadOnlyList<Medication>>([medication]);
|
||||
public Task<IReadOnlyList<Medication>> ListActiveForRemindersAsync(Guid userId, DateOnly today, CancellationToken ct) => Task.FromResult<IReadOnlyList<Medication>>([medication]);
|
||||
public Task<IReadOnlyList<MedicationLog>> ListLogsInWindowAsync(Guid userId, DateTime startUtc, DateTime endUtc, CancellationToken ct) => Task.FromResult<IReadOnlyList<MedicationLog>>([]);
|
||||
public Task<Medication?> GetOwnedAsync(Guid userId, Guid medicationId, CancellationToken ct) => Task.FromResult<Medication?>(medication.UserId == userId && medication.Id == medicationId ? medication : null);
|
||||
public Task<bool> ExistsOwnedAsync(Guid userId, Guid medicationId, CancellationToken ct) => Task.FromResult(medication.UserId == userId && medication.Id == medicationId);
|
||||
public Task<MedicationLog?> GetTodayTakenLogAsync(Guid userId, Guid medicationId, DateTime startUtc, DateTime endUtc, CancellationToken ct) => Task.FromResult<MedicationLog?>(null);
|
||||
public Task<bool> DoseLogExistsAsync(Guid userId, Guid medicationId, TimeOnly scheduledTime, DateTime startUtc, DateTime endUtc, CancellationToken ct) => Task.FromResult(false);
|
||||
public Task<MedicationLog?> GetDoseLogAsync(Guid userId, Guid medicationId, TimeOnly scheduledTime, DateTime startUtc, DateTime endUtc, CancellationToken ct) => Task.FromResult<MedicationLog?>(null);
|
||||
public Task<IReadOnlyList<Medication>> ListActiveForReminderScanAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<Medication>>([medication]);
|
||||
public Task AddMedicationAsync(Medication value, CancellationToken ct) => Task.CompletedTask;
|
||||
public Task AddLogAsync(MedicationLog log, CancellationToken ct) => Task.CompletedTask;
|
||||
public void DeleteMedication(Medication value) { }
|
||||
public void DeleteLog(MedicationLog log) { }
|
||||
public Task SaveChangesAsync(CancellationToken ct) { Saved = true; return Task.CompletedTask; }
|
||||
}
|
||||
}
|
||||
@@ -213,6 +213,178 @@ public sealed class PersistencePipelineTests
|
||||
Assert.Empty(tasks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotificationOutbox_PushDisabledDoesNotCreateInAppNotification()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var userId = Guid.NewGuid();
|
||||
var sourceId = Guid.NewGuid();
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
PushEnabled = false,
|
||||
MedicationReminder = true,
|
||||
HealthRecordReminder = false,
|
||||
});
|
||||
db.NotificationOutbox.Add(new NotificationOutboxRecord
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
SourceTaskId = sourceId,
|
||||
Type = "MedicationReminder",
|
||||
Payload = """
|
||||
{"Type":"MedicationReminder","Title":"用药时间到了","Message":"请按计划服药","Severity":"info","ActionType":"medication","ActionTargetId":null}
|
||||
""",
|
||||
Status = "Pending",
|
||||
AvailableAt = DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var processor = new EfNotificationOutboxProcessor(db);
|
||||
|
||||
await processor.ProcessNextAsync(CancellationToken.None);
|
||||
|
||||
Assert.Empty(db.UserNotifications);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReminderCatchUp_PushDisabledDoesNotCreateHealthRecordReminder()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var userId = Guid.NewGuid();
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
PushEnabled = false,
|
||||
HealthRecordReminder = true,
|
||||
HealthRecordReminderBloodPressure = true,
|
||||
HealthRecordReminderHeartRate = false,
|
||||
HealthRecordReminderGlucose = false,
|
||||
HealthRecordReminderSpO2 = false,
|
||||
HealthRecordReminderWeight = false,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var service = new EfReminderCatchUpService(db);
|
||||
var nowUtc = new DateTime(2026, 7, 13, 5, 0, 0, DateTimeKind.Utc); // 13:00 Beijing
|
||||
|
||||
var created = await service.CheckDueAsync(userId, nowUtc, CancellationToken.None);
|
||||
var secondPass = await service.CheckDueAsync(userId, nowUtc, CancellationToken.None);
|
||||
|
||||
Assert.Equal(0, created.CreatedCount);
|
||||
Assert.Equal(0, secondPass.CreatedCount);
|
||||
Assert.Empty(db.UserNotifications);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReminderCatchUp_PushEnabledCreatesOnlySelectedMissingMetric()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var userId = Guid.NewGuid();
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
PushEnabled = true,
|
||||
HealthRecordReminder = true,
|
||||
HealthRecordReminderBloodPressure = true,
|
||||
HealthRecordReminderHeartRate = false,
|
||||
HealthRecordReminderGlucose = false,
|
||||
HealthRecordReminderSpO2 = false,
|
||||
HealthRecordReminderWeight = false,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var service = new EfReminderCatchUpService(db);
|
||||
var nowUtc = new DateTime(2026, 7, 13, 5, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var result = await service.CheckDueAsync(userId, nowUtc, CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, result.CreatedCount);
|
||||
var notification = Assert.Single(db.UserNotifications);
|
||||
Assert.Contains("血压", notification.Message);
|
||||
Assert.DoesNotContain("心率", notification.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReminderCatchUp_DndStillPreventsReminder()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var userId = Guid.NewGuid();
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
PushEnabled = true,
|
||||
HealthRecordReminder = true,
|
||||
HealthRecordReminderBloodPressure = true,
|
||||
DndEnabled = true,
|
||||
DndStartMinutes = 12 * 60,
|
||||
DndEndMinutes = 14 * 60,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var service = new EfReminderCatchUpService(db);
|
||||
var nowUtc = new DateTime(2026, 7, 13, 5, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var result = await service.CheckDueAsync(userId, nowUtc, CancellationToken.None);
|
||||
|
||||
Assert.Equal(0, result.CreatedCount);
|
||||
Assert.Empty(db.UserNotifications);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReminderCatchUp_CreatesMedicationAndExerciseRemindersForDueItems()
|
||||
{
|
||||
await using var db = CreateDbContext();
|
||||
var userId = Guid.NewGuid();
|
||||
var date = new DateOnly(2026, 7, 13);
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
PushEnabled = true,
|
||||
MedicationReminder = true,
|
||||
HealthRecordReminder = false,
|
||||
});
|
||||
db.Medications.Add(new Medication
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
Name = "测试药物",
|
||||
Dosage = "1片",
|
||||
Frequency = MedicationFrequency.Daily,
|
||||
TimeOfDay = [new TimeOnly(8, 0)],
|
||||
StartDate = date,
|
||||
IsActive = true,
|
||||
});
|
||||
var plan = new ExercisePlan
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
StartDate = date,
|
||||
EndDate = date,
|
||||
ReminderTime = new TimeOnly(9, 0),
|
||||
};
|
||||
plan.Items.Add(new ExercisePlanItem
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
ScheduledDate = date,
|
||||
ExerciseType = "散步",
|
||||
DurationMinutes = 30,
|
||||
});
|
||||
db.ExercisePlans.Add(plan);
|
||||
await db.SaveChangesAsync();
|
||||
var service = new EfReminderCatchUpService(db);
|
||||
var nowUtc = new DateTime(2026, 7, 13, 2, 0, 0, DateTimeKind.Utc); // 10:00 Beijing
|
||||
|
||||
var created = await service.CheckDueAsync(userId, nowUtc, CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, created.CreatedCount);
|
||||
Assert.Contains(db.UserNotifications, x => x.Type == "MedicationReminder");
|
||||
Assert.Contains(db.UserNotifications, x => x.Type == "ExerciseReminder");
|
||||
}
|
||||
|
||||
private static ReportAnalysisTaskRecord NewReportTask(int attempts) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
|
||||
18
backend/tests/Health.Tests/prompt_manager_tests.cs
Normal file
18
backend/tests/Health.Tests/prompt_manager_tests.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using Health.Infrastructure.AI;
|
||||
using Health.Domain.Enums;
|
||||
|
||||
namespace Health.Tests;
|
||||
|
||||
public sealed class PromptManagerTests
|
||||
{
|
||||
[Fact]
|
||||
public void UnifiedPrompt_DistinguishesQuestionsFromEntryRequests()
|
||||
{
|
||||
var prompt = new PromptManager().GetSystemPrompt(AgentType.Unified);
|
||||
|
||||
Assert.Contains("先判断用户是在咨询数值,还是希望记录数据", prompt);
|
||||
Assert.Contains("血氧98%是不是太高了", prompt);
|
||||
Assert.Contains("先回答问题,不调用 record_health_data", prompt);
|
||||
Assert.Contains("帮我记录血压116/89", prompt);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user