feat: 用药打卡全面重构 - 按次追踪 + 独立打卡页 + 任务区汇总
- 后端用药提醒改为按次粒度(每个服药时间独立判断) - 新增 per-dose 打卡/取消打卡 API - 新增 MedicationCheckInPage 独立打卡页(每药每时间单独toggle) - 用药列表删底部弹窗(编辑/停药),点药品直接进该药打卡页 - 任务区用药汇总为一行(过期待服已服) - 支持隔天(EveryOtherDay)/每周频率判断 - 删历史对话功能(ConversationItem + conversationListProvider + UI)
This commit is contained in:
@@ -58,11 +58,12 @@ public enum MedicationLogStatus
|
||||
/// </summary>
|
||||
public enum MedicationFrequency
|
||||
{
|
||||
Daily, // 每天一次
|
||||
TwiceDaily, // 每天两次
|
||||
Daily, // 每天一次
|
||||
TwiceDaily, // 每天两次
|
||||
ThreeTimesDaily, // 每天三次
|
||||
Weekly, // 每周
|
||||
AsNeeded // 必要时
|
||||
EveryOtherDay, // 隔天一次
|
||||
Weekly, // 每周
|
||||
AsNeeded // 必要时
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -9,8 +9,17 @@ public static class ExerciseAgentHandler
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "manage_exercise", Description = "运动计划管理",
|
||||
Parameters = new { type = "object", properties = new { action = new { type = "string" } }, required = new[] { "action" } }
|
||||
Name = "manage_exercise", Description = "运动计划管理(创建/查询/打卡)",
|
||||
Parameters = new { type = "object", properties = new {
|
||||
action = new { type = "string", description = "create/query/checkin" },
|
||||
week_start_date = new { type = "string", description = "开始日期 yyyy-MM-dd" },
|
||||
items = new { type = "array", description = "每天的运动项目", items = new { type = "object", properties = new {
|
||||
day_of_week = new { type = "integer", description = "0=周日 1=周一...6=周六" },
|
||||
exercise_type = new { type = "string", description = "运动类型,如散步/慢跑/游泳/太极" },
|
||||
duration_minutes = new { type = "integer", description = "时长(分钟)" },
|
||||
is_rest_day = new { type = "boolean", description = "是否休息日" }
|
||||
}}}
|
||||
}, required = new[] { "action" } }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -48,7 +57,13 @@ public static class ExerciseAgentHandler
|
||||
}
|
||||
db.ExercisePlans.Add(plan);
|
||||
await db.SaveChangesAsync();
|
||||
return new { success = true, plan_id = plan.Id };
|
||||
var firstItem = plan.Items.FirstOrDefault();
|
||||
return new {
|
||||
success = true, plan_id = plan.Id,
|
||||
exercise_type = firstItem?.ExerciseType ?? "运动",
|
||||
duration_minutes = firstItem?.DurationMinutes ?? 30,
|
||||
day_count = plan.Items.Count,
|
||||
};
|
||||
|
||||
case "checkin":
|
||||
var itemId = args.TryGetProperty("item_id", out var iid) ? iid.GetGuid() : Guid.Empty;
|
||||
|
||||
@@ -9,8 +9,16 @@ public static class MedicationAgentHandler
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "manage_medication", Description = "用药管理",
|
||||
Parameters = new { type = "object", properties = new { action = new { type = "string" }, name = new { type = "string" }, dosage = new { type = "string" } }, required = new[] { "action" } }
|
||||
Name = "manage_medication", Description = "用药管理(创建/查询/确认服药)",
|
||||
Parameters = new { type = "object", properties = new {
|
||||
action = new { type = "string", description = "create/query/confirm" },
|
||||
name = new { type = "string", description = "药品名称" },
|
||||
dosage = new { type = "string", description = "剂量,如 100mg" },
|
||||
frequency = new { type = "string", description = "频率,如 Daily/EveryOtherDay/Weekly" },
|
||||
time_of_day = new { type = "array", items = new { type = "string" }, description = "服药时间,如 [\"08:00\",\"20:00\"]" },
|
||||
duration_days = new { type = "integer", description = "服用天数" },
|
||||
start_date = new { type = "string", description = "开始日期 yyyy-MM-dd" },
|
||||
}, required = new[] { "action" } }
|
||||
}
|
||||
};
|
||||
|
||||
@@ -40,16 +48,43 @@ public static class MedicationAgentHandler
|
||||
|
||||
private static async Task<object> CreateMedication(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var name = args.TryGetProperty("name", out var n) ? n.GetString()! : "";
|
||||
var dosage = args.TryGetProperty("dosage", out var dg) ? dg.GetString() : null;
|
||||
var frequencyStr = args.TryGetProperty("frequency", out var f) ? f.GetString() : "Daily";
|
||||
var frequency = Enum.TryParse<MedicationFrequency>(frequencyStr, out var fr) ? fr : MedicationFrequency.Daily;
|
||||
|
||||
List<TimeOnly> times = [];
|
||||
if (args.TryGetProperty("time_of_day", out var tod) && tod.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var t in tod.EnumerateArray())
|
||||
{
|
||||
if (TimeOnly.TryParse(t.GetString(), out var parsed)) times.Add(parsed);
|
||||
}
|
||||
}
|
||||
|
||||
var durationDays = args.TryGetProperty("duration_days", out var dd) ? dd.GetInt32() : 0;
|
||||
var startDateStr = args.TryGetProperty("start_date", out var sd) && sd.GetString() is string sds ? sds : null;
|
||||
|
||||
var med = new Medication
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId,
|
||||
Name = args.TryGetProperty("name", out var n) ? n.GetString()! : "",
|
||||
Dosage = args.TryGetProperty("dosage", out var dg) ? dg.GetString() : null,
|
||||
Name = name, Dosage = dosage, Frequency = frequency,
|
||||
TimeOfDay = times.Count > 0 ? times : [new TimeOnly(8, 0)],
|
||||
Source = MedicationSource.AiEntry, IsActive = true,
|
||||
StartDate = DateOnly.TryParse(startDateStr, out var parsedDate) ? parsedDate : DateOnly.FromDateTime(DateTime.Now),
|
||||
EndDate = durationDays > 0 ? DateOnly.FromDateTime(DateTime.Now).AddDays(durationDays) : null,
|
||||
};
|
||||
db.Medications.Add(med);
|
||||
await db.SaveChangesAsync();
|
||||
return new { success = true, medication_id = med.Id, med.Name };
|
||||
|
||||
var timeLabels = times.Count > 0 ? string.Join(", ", times.Select(t => t.ToString("HH:mm"))) : "08:00";
|
||||
return new {
|
||||
success = true, medication_id = med.Id,
|
||||
name = med.Name, dosage = med.Dosage,
|
||||
frequency = med.Frequency.ToString(), time = timeLabels,
|
||||
start_date = med.StartDate?.ToString("yyyy-MM-dd"),
|
||||
duration_days = durationDays,
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<object> QueryMedications(AppDbContext db, Guid userId)
|
||||
|
||||
@@ -132,6 +132,16 @@ public sealed class PromptManager
|
||||
5. 健康档案查询/修改 → 调用 check_archive / manage_archive
|
||||
6. 历史数据查询 → 调用 query_health_records
|
||||
|
||||
运动计划参数格式(manage_exercise):
|
||||
- action="create", week_start_date="今天日期(YYYY-MM-DD)"
|
||||
- items: [{"day_of_week":0-6(周日=0),"exercise_type":"散步","duration_minutes":30,"is_rest_day":false}, ...]
|
||||
- 未说持续多久则默认创建7天
|
||||
- 用户说"坚持10天"则创建10天,说"到6月20日"则算天数
|
||||
- items 数量必须等于持续天数
|
||||
|
||||
用药管理参数格式(manage_medication):
|
||||
- action="create", name="药名", dosage="剂量", frequency="Daily", time_of_day=["08:00","20:00"], duration_days=7
|
||||
|
||||
规则:
|
||||
- 用户可能一句话涉及多个领域,全部处理
|
||||
- 数值明确+指标明确→直接录入,不要追问
|
||||
|
||||
@@ -132,7 +132,7 @@ public static class AiChatEndpoints
|
||||
if (!string.IsNullOrEmpty(content))
|
||||
{
|
||||
fullResponse += content;
|
||||
await SseWriteAsync(http, new { action = "answer", data = content, type = messageType }, ct);
|
||||
await SseWriteAsync(http, new { action = "answer", data = content, type = messageType, metadata = metadata.Count > 0 ? metadata : null }, ct);
|
||||
}
|
||||
}
|
||||
catch (JsonException) { /* 跳过解析失败的 chunk */ }
|
||||
@@ -338,11 +338,12 @@ public static class AiChatEndpoints
|
||||
AgentType.Report => ReportAgentHandler.Tools,
|
||||
AgentType.Exercise => ExerciseAgentHandler.Tools,
|
||||
AgentType.Unified => [
|
||||
..HealthDataAgentHandler.Tools,
|
||||
..DietAgentHandler.Tools,
|
||||
..MedicationAgentHandler.Tools,
|
||||
..ExerciseAgentHandler.Tools,
|
||||
..CommonAgentHandler.Tools,
|
||||
HealthDataAgentHandler.RecordHealthDataTool,
|
||||
CommonAgentHandler.QueryHealthRecordsTool,
|
||||
DietAgentHandler.EstimateFoodTool,
|
||||
MedicationAgentHandler.ManageMedicationTool,
|
||||
ExerciseAgentHandler.ManageExerciseTool,
|
||||
CommonAgentHandler.CheckArchiveTool,
|
||||
],
|
||||
_ => CommonAgentHandler.Tools,
|
||||
};
|
||||
@@ -442,6 +443,31 @@ public static class AiChatEndpoints
|
||||
metadata["name"] = name.ToString();
|
||||
if (resultDict.TryGetValue("dosage", out var dosage))
|
||||
metadata["dosage"] = dosage.ToString();
|
||||
if (resultDict.TryGetValue("time", out var time))
|
||||
metadata["time"] = time.ToString();
|
||||
if (resultDict.TryGetValue("frequency", out var freq))
|
||||
metadata["frequency"] = freq.ToString();
|
||||
if (resultDict.TryGetValue("duration_days", out var dd2) && dd2 is int d2)
|
||||
metadata["duration_days"] = d2;
|
||||
if (resultDict.TryGetValue("start_date", out var sd))
|
||||
metadata["startDate"] = sd.ToString();
|
||||
}
|
||||
break;
|
||||
case "manage_exercise":
|
||||
messageType = "data_confirm";
|
||||
if (resultDict != null)
|
||||
{
|
||||
metadata["type"] = "exercise";
|
||||
metadata["value"] = "";
|
||||
if (resultDict.TryGetValue("exercise_type", out var et))
|
||||
metadata["value"] = et.ToString();
|
||||
if (resultDict.TryGetValue("duration_minutes", out var dm) && dm is int mins)
|
||||
metadata["unit"] = $"每天{mins}分钟";
|
||||
if (resultDict.TryGetValue("day_count", out var dc) && dc is int days)
|
||||
metadata["durationDays"] = days;
|
||||
if (resultDict.TryGetValue("success", out var es) && es is bool eb && eb)
|
||||
metadata["success"] = true;
|
||||
metadata["recordTime"] = DateTime.UtcNow.AddHours(8).ToString("MM月dd日 HH:mm");
|
||||
}
|
||||
break;
|
||||
case "estimate_food_text":
|
||||
|
||||
@@ -108,32 +108,141 @@ public static class MedicationEndpoints
|
||||
var userId = GetUserId(http);
|
||||
var beijingNow = DateTime.UtcNow.AddHours(8);
|
||||
var now = TimeOnly.FromDateTime(beijingNow);
|
||||
var windowFuture = now.AddHours(2); // 接下来2小时
|
||||
var windowPast = now.AddHours(-1); // 过去1小时内(过了还没吃就该提醒)
|
||||
var today = DateOnly.FromDateTime(beijingNow);
|
||||
var todayUtc = DateTime.SpecifyKind(beijingNow.Date, DateTimeKind.Utc);
|
||||
|
||||
// 只查活跃且在有效期内的药
|
||||
var meds = await db.Medications
|
||||
.Where(m => m.UserId == userId && m.IsActive && m.TimeOfDay != null)
|
||||
.Where(m => m.UserId == userId && m.IsActive && m.TimeOfDay != null
|
||||
&& m.StartDate <= today && (m.EndDate == null || m.EndDate >= today))
|
||||
.ToListAsync(ct);
|
||||
|
||||
// 同时包含:未来2小时内 + 过去1小时内(防止过了时间就不提醒)
|
||||
var due = meds.Where(m => m.TimeOfDay!.Any(t =>
|
||||
InTimeWindow(t, now, windowFuture) || InTimeWindow(t, windowPast, now)
|
||||
)).ToList();
|
||||
// 查询今天所有服药记录
|
||||
var logs = await db.MedicationLogs
|
||||
.Where(l => l.UserId == userId && l.ConfirmedAt >= todayUtc)
|
||||
.ToListAsync(ct);
|
||||
|
||||
var todayStart = DateTime.SpecifyKind(beijingNow.Date, DateTimeKind.Utc);
|
||||
var dueMeds = new List<object>();
|
||||
foreach (var m in due)
|
||||
// 按次生成提醒
|
||||
var reminders = new List<object>();
|
||||
foreach (var m in meds)
|
||||
{
|
||||
var logged = await db.MedicationLogs.AnyAsync(l =>
|
||||
l.MedicationId == m.Id
|
||||
&& l.CreatedAt >= todayStart
|
||||
&& l.Status == MedicationLogStatus.Taken, ct);
|
||||
if (!logged)
|
||||
dueMeds.Add(new { m.Id, m.Name, m.Dosage, m.TimeOfDay });
|
||||
// 处理隔天/每周的逻辑
|
||||
var dosesToday = GetDosesForToday(m, today);
|
||||
if (!dosesToday) continue;
|
||||
|
||||
foreach (var t in m.TimeOfDay!)
|
||||
{
|
||||
var scheduledTime = t;
|
||||
var doseTimeBeijing = today.ToDateTime(scheduledTime);
|
||||
|
||||
// 查该药该时间是否已打卡
|
||||
var alreadyLogged = logs.Any(l =>
|
||||
l.MedicationId == m.Id && l.ScheduledTime == scheduledTime);
|
||||
|
||||
string status;
|
||||
if (alreadyLogged)
|
||||
{
|
||||
var log = logs.First(l => l.MedicationId == m.Id && l.ScheduledTime == scheduledTime);
|
||||
status = log.Status == MedicationLogStatus.Taken ? "taken" : "skipped";
|
||||
}
|
||||
else if (scheduledTime <= now.AddMinutes(-30))
|
||||
{
|
||||
status = "overdue"; // 过了30分钟还没吃
|
||||
}
|
||||
else if (scheduledTime <= now.AddHours(3))
|
||||
{
|
||||
status = "upcoming"; // 未来3小时内
|
||||
}
|
||||
else
|
||||
{
|
||||
continue; // 太远,不显示
|
||||
}
|
||||
|
||||
reminders.Add(new
|
||||
{
|
||||
m.Id, m.Name, m.Dosage,
|
||||
scheduledTime = scheduledTime.ToString("HH:mm"),
|
||||
status,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Results.Ok(new { code = 0, data = dueMeds, message = (string?)null });
|
||||
// overdue 在前,upcoming 在后,taken 在最后
|
||||
reminders = reminders.OrderBy(r =>
|
||||
((dynamic)r).status == "overdue" ? 0 :
|
||||
((dynamic)r).status == "upcoming" ? 1 : 2
|
||||
).ToList();
|
||||
|
||||
return Results.Ok(new { code = 0, data = reminders, message = (string?)null });
|
||||
});
|
||||
|
||||
// 按次打卡
|
||||
group.MapPost("/{id:guid}/confirm-dose", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var med = await db.Medications.FirstOrDefaultAsync(m => m.Id == id && m.UserId == userId, ct);
|
||||
if (med == null) return Results.Ok(new { code = 404, message = "药品不存在" });
|
||||
|
||||
using var reader = new System.IO.StreamReader(http.Request.Body);
|
||||
var body = await reader.ReadToEndAsync(ct);
|
||||
var json = System.Text.Json.JsonDocument.Parse(body);
|
||||
var timeStr = json.RootElement.GetProperty("scheduledTime").GetString()!;
|
||||
var statusStr = json.RootElement.TryGetProperty("status", out var st) ? st.GetString() : "taken";
|
||||
var scheduledTime = TimeOnly.Parse(timeStr);
|
||||
var status = statusStr == "taken" ? MedicationLogStatus.Taken : MedicationLogStatus.Skipped;
|
||||
|
||||
// 防止重复打卡
|
||||
var todayUtc = DateTime.SpecifyKind(DateTime.UtcNow.AddHours(8).Date, DateTimeKind.Utc);
|
||||
var existing = await db.MedicationLogs.AnyAsync(l =>
|
||||
l.MedicationId == id && l.UserId == userId
|
||||
&& l.ScheduledTime == scheduledTime && l.ConfirmedAt >= todayUtc, ct);
|
||||
if (existing) return Results.Ok(new { code = 0, data = new { success = false, message = "已打卡" }, message = (string?)null });
|
||||
|
||||
db.MedicationLogs.Add(new MedicationLog
|
||||
{
|
||||
Id = Guid.NewGuid(), MedicationId = id, UserId = userId,
|
||||
Status = status, ScheduledTime = scheduledTime, ConfirmedAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 取消打卡(删掉对应 log)
|
||||
group.MapDelete("/{id:guid}/confirm-dose/{time}", async (Guid id, string time, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var scheduledTime = TimeOnly.Parse(time);
|
||||
var todayUtc = DateTime.SpecifyKind(DateTime.UtcNow.AddHours(8).Date, DateTimeKind.Utc);
|
||||
var log = await db.MedicationLogs
|
||||
.Where(l => l.MedicationId == id && l.UserId == userId
|
||||
&& l.ScheduledTime == scheduledTime && l.ConfirmedAt >= todayUtc)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
if (log != null) { db.MedicationLogs.Remove(log); await db.SaveChangesAsync(ct); }
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断今天是否该吃药(处理隔天/每周频率)
|
||||
/// </summary>
|
||||
private static bool GetDosesForToday(Medication m, DateOnly today)
|
||||
{
|
||||
if (m.Frequency == MedicationFrequency.Daily) return true;
|
||||
if (m.Frequency == MedicationFrequency.TwiceDaily) return true;
|
||||
if (m.Frequency == MedicationFrequency.ThreeTimesDaily) return true;
|
||||
if (m.Frequency == MedicationFrequency.AsNeeded) return true;
|
||||
|
||||
var startDate = m.StartDate ?? today;
|
||||
if (m.Frequency == MedicationFrequency.EveryOtherDay)
|
||||
{
|
||||
var daysSinceStart = today.DayNumber - startDate.DayNumber;
|
||||
return daysSinceStart % 2 == 0;
|
||||
}
|
||||
if (m.Frequency == MedicationFrequency.Weekly)
|
||||
{
|
||||
return today.DayOfWeek == startDate.DayOfWeek;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool InTimeWindow(TimeOnly t, TimeOnly start, TimeOnly end) =>
|
||||
|
||||
Reference in New Issue
Block a user