Initial commit: 健康管家 AI 健康陪伴助手
- Backend: .NET 10 Minimal API + EF Core + PostgreSQL - Frontend: Flutter + Riverpod + GoRouter + Dio - AI: DeepSeek LLM + Qwen VLM (OpenAI-compatible) - Auth: SMS + JWT (access/refresh tokens) - Features: AI chat, health tracking, medication management, diet analysis, exercise plans, doctor consultations, report analysis
This commit is contained in:
572
backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs
Normal file
572
backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs
Normal file
@@ -0,0 +1,572 @@
|
||||
using System.Text.Json;
|
||||
using Health.Domain.Entities;
|
||||
using Health.Domain.Enums;
|
||||
using Health.Infrastructure.AI;
|
||||
using Health.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// AI 对话 SSE 端点——支持 7 个 Agent
|
||||
/// </summary>
|
||||
public static class AiChatEndpoints
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
};
|
||||
|
||||
public static void MapAiChatEndpoints(this WebApplication app)
|
||||
{
|
||||
// SSE 流式对话(GET 方式,token 通过 query string 传递)
|
||||
app.MapGet("/api/ai/{agentType}/chat", async (
|
||||
string message,
|
||||
string? conversationId,
|
||||
string token,
|
||||
string agentType,
|
||||
HttpContext http,
|
||||
AppDbContext db,
|
||||
DeepSeekClient llmClient,
|
||||
PromptManager promptManager,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
// 支持 token 通过 query string(浏览器 EventSource)或 header 传递
|
||||
var userId = GetUserId(http) ?? GetUserIdFromToken(token);
|
||||
if (userId == null)
|
||||
{
|
||||
http.Response.StatusCode = 401;
|
||||
http.Response.ContentType = "application/json";
|
||||
await http.Response.WriteAsync(JsonSerializer.Serialize(new { code = 40002, data = (object?)null, message = "未登录" }), ct);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Enum.TryParse<AgentType>(agentType, ignoreCase: true, out var parsedType))
|
||||
parsedType = AgentType.Default;
|
||||
|
||||
// SSE 响应头
|
||||
http.Response.ContentType = "text/event-stream";
|
||||
http.Response.Headers.CacheControl = "no-cache";
|
||||
http.Response.Headers.Connection = "keep-alive";
|
||||
http.Response.Headers["X-Accel-Buffering"] = "no";
|
||||
|
||||
// 创建或获取对话
|
||||
Conversation? conversation = null;
|
||||
if (!string.IsNullOrEmpty(conversationId) && Guid.TryParse(conversationId, out var convId))
|
||||
conversation = await db.Conversations.FindAsync([convId], ct);
|
||||
|
||||
if (conversation == null)
|
||||
{
|
||||
conversation = new Conversation
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId.Value, AgentType = parsedType,
|
||||
Title = message.Length > 30 ? message[..30] : message,
|
||||
CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
db.Conversations.Add(conversation);
|
||||
await db.SaveChangesAsync(ct);
|
||||
await SseWriteAsync(http, new { action = "conversation_id", data = conversation.Id.ToString() }, ct);
|
||||
}
|
||||
|
||||
// 保存用户消息
|
||||
var userMsg = new ConversationMessage
|
||||
{
|
||||
Id = Guid.NewGuid(), ConversationId = conversation.Id, Role = MessageRole.User,
|
||||
Content = message, CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
db.ConversationMessages.Add(userMsg);
|
||||
conversation.MessageCount++;
|
||||
conversation.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// 加载上下文
|
||||
var systemPrompt = promptManager.GetSystemPrompt(parsedType);
|
||||
var patientContext = await BuildPatientContext(db, userId.Value, ct);
|
||||
|
||||
var messages = new List<ChatMessage>
|
||||
{
|
||||
new() { Role = "system", Content = systemPrompt + "\n\n当前患者信息:\n" + patientContext },
|
||||
};
|
||||
|
||||
// 加载历史对话(最近 10 条)
|
||||
var history = await db.ConversationMessages
|
||||
.Where(m => m.ConversationId == conversation.Id)
|
||||
.OrderByDescending(m => m.CreatedAt)
|
||||
.Take(12)
|
||||
.ToListAsync(ct);
|
||||
|
||||
foreach (var h in history.Reverse<ConversationMessage>())
|
||||
{
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = h.Role == MessageRole.User ? "user" : "assistant",
|
||||
Content = h.Content,
|
||||
});
|
||||
}
|
||||
|
||||
// Tool Calling 循环
|
||||
var tools = GetToolsForAgent(parsedType);
|
||||
var maxIterations = 5;
|
||||
var fullResponse = "";
|
||||
var completedNormally = false;
|
||||
|
||||
for (int i = 0; i < maxIterations; i++)
|
||||
{
|
||||
await SseWriteAsync(http, new { action = "notice", message = i == 0 ? "正在分析..." : "正在处理..." }, ct);
|
||||
|
||||
var response = await llmClient.ChatAsync(messages, tools: tools.Count > 0 ? tools : null, ct: ct);
|
||||
|
||||
var choice = response.Choices?.FirstOrDefault();
|
||||
if (choice == null) break;
|
||||
|
||||
if (choice.FinishReason == "stop")
|
||||
{
|
||||
// 流式输出最终回复(带上完整的 tool call 历史,方便 LLM 利用工具结果生成回复)
|
||||
await foreach (var chunk in llmClient.ChatStreamAsync(messages, tools: null, ct: ct))
|
||||
{
|
||||
try
|
||||
{
|
||||
var delta = JsonSerializer.Deserialize<ChatCompletionResponse>(chunk, JsonOpts);
|
||||
var content = delta?.Choices?.FirstOrDefault()?.Delta?.Content;
|
||||
if (!string.IsNullOrEmpty(content))
|
||||
{
|
||||
fullResponse += content;
|
||||
await SseWriteAsync(http, new { action = "answer", data = content }, ct);
|
||||
}
|
||||
}
|
||||
catch { /* 跳过解析失败的 chunk */ }
|
||||
}
|
||||
completedNormally = true;
|
||||
break;
|
||||
}
|
||||
else if (choice.FinishReason == "tool_calls" && choice.Message?.ToolCalls != null)
|
||||
{
|
||||
// 一条 assistant 消息包含所有 tool calls(符合 OpenAI 协议)
|
||||
messages.Add(new ChatMessage
|
||||
{
|
||||
Role = "assistant",
|
||||
Content = choice.Message.Content ?? "",
|
||||
ToolCalls = choice.Message.ToolCalls,
|
||||
});
|
||||
|
||||
foreach (var tc in choice.Message.ToolCalls)
|
||||
{
|
||||
object toolResult;
|
||||
try
|
||||
{
|
||||
toolResult = await ExecuteToolCall(tc.Function.Name, tc.Function.Arguments, db, userId.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
toolResult = new { success = false, message = $"工具执行异常: {ex.Message}" };
|
||||
}
|
||||
await SseWriteAsync(http, new { action = "tool_result", tool = tc.Function.Name, data = toolResult }, ct);
|
||||
|
||||
messages.Add(new ChatMessage { Role = "tool", Content = JsonSerializer.Serialize(toolResult, JsonOpts), ToolCallId = tc.Id });
|
||||
}
|
||||
}
|
||||
else break;
|
||||
}
|
||||
|
||||
// 保存 AI 回复
|
||||
if (!string.IsNullOrEmpty(fullResponse))
|
||||
{
|
||||
db.ConversationMessages.Add(new ConversationMessage
|
||||
{
|
||||
Id = Guid.NewGuid(), ConversationId = conversation.Id, Role = MessageRole.Assistant,
|
||||
Content = fullResponse, CreatedAt = DateTime.UtcNow,
|
||||
});
|
||||
conversation.MessageCount++;
|
||||
conversation.Summary = fullResponse.Length > 100 ? fullResponse[..100] : fullResponse;
|
||||
conversation.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
await SseWriteAsync(http, new { action = "status", data = completedNormally ? "done" : "error" }, ct);
|
||||
await http.Response.WriteAsync("data: [DONE]\n\n", ct);
|
||||
});
|
||||
|
||||
// 获取对话列表
|
||||
app.MapGet("/api/ai/conversations", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
if (userId == null) return Results.Json(new { code = 40002, data = (object?)null, message = "未登录" }, statusCode: 401);
|
||||
|
||||
var conversations = await db.Conversations
|
||||
.Where(c => c.UserId == userId.Value)
|
||||
.OrderByDescending(c => c.UpdatedAt)
|
||||
.Select(c => new { c.Id, AgentType = c.AgentType.ToString(), c.Title, c.Summary, c.MessageCount, c.CreatedAt, c.UpdatedAt })
|
||||
.ToListAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = conversations, message = (string?)null });
|
||||
});
|
||||
|
||||
// 获取对话历史
|
||||
app.MapGet("/api/ai/conversations/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
if (userId == null) return Results.Json(new { code = 40002 }, statusCode: 401);
|
||||
|
||||
var messages = await db.ConversationMessages
|
||||
.Where(m => m.ConversationId == id && m.Conversation.UserId == userId.Value)
|
||||
.OrderBy(m => m.CreatedAt)
|
||||
.Select(m => new { m.Id, Role = m.Role.ToString(), m.Content, m.Intent, m.MetadataJson, m.CreatedAt })
|
||||
.ToListAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = messages, message = (string?)null });
|
||||
});
|
||||
|
||||
// 删除对话
|
||||
app.MapDelete("/api/ai/conversations/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
if (userId == null) return Results.Json(new { code = 40002 }, statusCode: 401);
|
||||
|
||||
var conv = await db.Conversations.FirstOrDefaultAsync(c => c.Id == id && c.UserId == userId.Value, ct);
|
||||
if (conv != null)
|
||||
{
|
||||
db.Conversations.Remove(conv);
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
// VLM 食物识别
|
||||
app.MapPost("/api/ai/analyze-food-image", async (
|
||||
HttpRequest httpRequest, HttpContext http,
|
||||
QwenVisionClient visionClient, AppDbContext db,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
if (userId == null) return Results.Json(new { code = 40002 }, statusCode: 401);
|
||||
|
||||
var form = await httpRequest.ReadFormAsync(ct);
|
||||
var files = form.Files.GetFiles("images");
|
||||
if (files == null || files.Count == 0)
|
||||
return Results.Ok(new { code = 40001, data = (object?)null, message = "请上传至少一张图片" });
|
||||
|
||||
var imageUrls = new List<string>();
|
||||
var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
|
||||
Directory.CreateDirectory(uploadsDir);
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (file.Length > 10 * 1024 * 1024)
|
||||
return Results.Ok(new { code = 40001, data = (object?)null, message = "文件大小超过 10MB 限制" });
|
||||
|
||||
var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
|
||||
if (ext is not ".jpg" and not ".jpeg" and not ".png" and not ".heic")
|
||||
return Results.Ok(new { code = 40001, data = (object?)null, message = "不支持的图片格式,仅支持 JPG/PNG/HEIC" });
|
||||
|
||||
var safeName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
|
||||
var filePath = Path.Combine(uploadsDir, safeName);
|
||||
using var stream = new FileStream(filePath, FileMode.Create);
|
||||
await file.CopyToAsync(stream, ct);
|
||||
imageUrls.Add($"file://{filePath}");
|
||||
}
|
||||
|
||||
var prompt = """
|
||||
识别图片中的所有食物,返回 JSON 格式:
|
||||
{
|
||||
"foods": [{"name":"食物名","portion":"份量描述","calories":数字,"proteinGrams":数字,"carbsGrams":数字,"fatGrams":数字,"warning":null或警告文字}],
|
||||
"totalCalories":总热量数字,
|
||||
"warnings":["整体警告"],
|
||||
"score":1-5评分
|
||||
}
|
||||
请只返回 JSON,不要加任何其他文字。
|
||||
""";
|
||||
|
||||
try
|
||||
{
|
||||
var response = await visionClient.VisionAsync(prompt, imageUrls, ct: ct);
|
||||
var result = response.Choices?.FirstOrDefault()?.Message?.Content ?? "{}";
|
||||
return Results.Ok(new { code = 0, data = result, message = (string?)null });
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return Results.Ok(new { code = 50001, data = (object?)null, message = $"食物识别失败,请重试" });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task SseWriteAsync(HttpContext http, object data, CancellationToken ct)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(data, JsonOpts);
|
||||
await http.Response.WriteAsync($"data: {json}\n\n", ct);
|
||||
await http.Response.Body.FlushAsync(ct);
|
||||
}
|
||||
|
||||
private static Guid? GetUserId(HttpContext http) =>
|
||||
Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : null;
|
||||
|
||||
/// 从 query string token 解析用户 ID(浏览器 EventSource 用)
|
||||
private static Guid? GetUserIdFromToken(string? token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return null;
|
||||
try
|
||||
{
|
||||
var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
|
||||
var jwt = handler.ReadJwtToken(token);
|
||||
var sub = jwt.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
return sub != null && Guid.TryParse(sub, out var id) ? id : null;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static List<ToolDefinition> GetToolsForAgent(AgentType agentType) => agentType switch
|
||||
{
|
||||
AgentType.Health => [RecordHealthDataTool, QueryHealthRecordsTool],
|
||||
AgentType.Medication => [ManageMedicationTool, CheckArchiveTool],
|
||||
AgentType.Diet => [EstimateFoodTool, CheckArchiveTool],
|
||||
AgentType.Consultation => [QueryHealthRecordsTool, CheckArchiveTool, RequestDoctorTool],
|
||||
AgentType.Report => [AnalyzeReportTool, QueryHealthRecordsTool],
|
||||
AgentType.Exercise => [ManageExerciseTool],
|
||||
_ => [QueryHealthRecordsTool, CheckArchiveTool],
|
||||
};
|
||||
|
||||
private static async Task<object> ExecuteToolCall(string toolName, string arguments, AppDbContext db, Guid userId)
|
||||
{
|
||||
using var jsonDoc = JsonDocument.Parse(arguments);
|
||||
var root = jsonDoc.RootElement;
|
||||
|
||||
return toolName switch
|
||||
{
|
||||
"record_health_data" => await ExecuteRecordHealthData(db, userId, root),
|
||||
"query_health_records" => await ExecuteQueryHealthRecords(db, userId, root),
|
||||
"check_archive" => await ExecuteCheckArchive(db, userId),
|
||||
"manage_medication" => await ExecuteManageMedication(db, userId, root),
|
||||
"manage_exercise" => await ExecuteManageExercise(db, userId, root),
|
||||
_ => new { success = false, message = $"未知工具: {toolName}" }
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<object> ExecuteRecordHealthData(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var type = args.TryGetProperty("type", out var t) ? t.GetString()! : "";
|
||||
var record = new HealthRecord
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId, Source = HealthRecordSource.AiEntry,
|
||||
RecordedAt = args.TryGetProperty("recorded_at", out var ra) && ra.TryGetDateTime(out var dt) ? dt : DateTime.UtcNow,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case "blood_pressure":
|
||||
record.MetricType = HealthMetricType.BloodPressure;
|
||||
record.Systolic = args.TryGetProperty("systolic", out var s) ? s.GetInt32() : null;
|
||||
record.Diastolic = args.TryGetProperty("diastolic", out var d) ? d.GetInt32() : null;
|
||||
record.Unit = "mmHg";
|
||||
record.IsAbnormal = record.Systolic >= 140 || record.Diastolic >= 90 || record.Systolic <= 89 || record.Diastolic <= 59;
|
||||
break;
|
||||
case "heart_rate":
|
||||
record.MetricType = HealthMetricType.HeartRate;
|
||||
record.Value = args.TryGetProperty("heart_rate", out var hr) ? hr.GetDecimal() : null;
|
||||
record.Unit = "次/分";
|
||||
record.IsAbnormal = record.Value > 100 || record.Value < 60;
|
||||
break;
|
||||
case "glucose":
|
||||
record.MetricType = HealthMetricType.Glucose;
|
||||
record.Value = args.TryGetProperty("glucose", out var g) ? g.GetDecimal() : null;
|
||||
record.Unit = "mmol/L";
|
||||
record.IsAbnormal = record.Value >= 7.0m || record.Value <= 3.8m;
|
||||
break;
|
||||
case "spo2":
|
||||
record.MetricType = HealthMetricType.SpO2;
|
||||
record.Value = args.TryGetProperty("spo2", out var o) ? o.GetDecimal() : null;
|
||||
record.Unit = "%";
|
||||
record.IsAbnormal = record.Value <= 94;
|
||||
break;
|
||||
case "weight":
|
||||
record.MetricType = HealthMetricType.Weight;
|
||||
record.Value = args.TryGetProperty("weight", out var w) ? w.GetDecimal() : null;
|
||||
record.Unit = "kg";
|
||||
break;
|
||||
default:
|
||||
return new { success = false, message = $"未知指标类型: {type}" };
|
||||
}
|
||||
|
||||
db.HealthRecords.Add(record);
|
||||
await db.SaveChangesAsync();
|
||||
return new { success = true, record_id = record.Id, type = record.MetricType.ToString() };
|
||||
}
|
||||
|
||||
private static async Task<object> ExecuteQueryHealthRecords(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var type = args.TryGetProperty("type", out var t) ? t.GetString() : null;
|
||||
var days = args.TryGetProperty("days", out var d) ? d.GetInt32() : 7;
|
||||
|
||||
var query = db.HealthRecords.Where(r => r.UserId == userId);
|
||||
if (!string.IsNullOrEmpty(type) && Enum.TryParse<HealthMetricType>(type, ignoreCase: true, out var mt))
|
||||
query = query.Where(r => r.MetricType == mt);
|
||||
|
||||
query = query.Where(r => r.RecordedAt >= DateTime.UtcNow.AddDays(-days));
|
||||
|
||||
var records = await query.OrderByDescending(r => r.RecordedAt).Take(30).Select(r => new
|
||||
{
|
||||
r.Id, Type = r.MetricType.ToString(), r.Systolic, r.Diastolic, r.Value, r.Unit, r.IsAbnormal, r.RecordedAt,
|
||||
}).ToListAsync();
|
||||
|
||||
return new { count = records.Count, records };
|
||||
}
|
||||
|
||||
private static async Task<object> ExecuteCheckArchive(AppDbContext db, Guid userId)
|
||||
{
|
||||
var archive = await db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == userId);
|
||||
if (archive == null) return new { found = false };
|
||||
return new
|
||||
{
|
||||
found = true, archive.Diagnosis, archive.SurgeryType,
|
||||
SurgeryDate = archive.SurgeryDate?.ToString("yyyy-MM-dd"),
|
||||
archive.Allergies, archive.DietRestrictions, archive.ChronicDiseases, archive.FamilyHistory,
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<object> ExecuteManageMedication(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var action = args.TryGetProperty("action", out var a) ? a.GetString()! : "query";
|
||||
return action switch
|
||||
{
|
||||
"create" => await CreateMedication(db, userId, args),
|
||||
"query" => await QueryMedications(db, userId),
|
||||
"confirm" => await ConfirmMedication(db, userId, args),
|
||||
_ => new { success = false, message = $"未知操作: {action}" }
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<object> CreateMedication(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
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,
|
||||
Source = MedicationSource.AiEntry, IsActive = true,
|
||||
};
|
||||
db.Medications.Add(med);
|
||||
await db.SaveChangesAsync();
|
||||
return new { success = true, medication_id = med.Id, med.Name };
|
||||
}
|
||||
|
||||
private static async Task<object> QueryMedications(AppDbContext db, Guid userId)
|
||||
{
|
||||
var meds = await db.Medications.Where(m => m.UserId == userId && m.IsActive)
|
||||
.Select(m => new { m.Id, m.Name, m.Dosage, m.TimeOfDay }).ToListAsync();
|
||||
return new { count = meds.Count, medications = meds };
|
||||
}
|
||||
|
||||
private static async Task<object> ConfirmMedication(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var medId = args.TryGetProperty("medication_id", out var mid) ? mid.GetGuid() : Guid.Empty;
|
||||
db.MedicationLogs.Add(new MedicationLog
|
||||
{
|
||||
Id = Guid.NewGuid(), MedicationId = medId, UserId = userId,
|
||||
Status = MedicationLogStatus.Taken, ScheduledTime = TimeOnly.FromDateTime(DateTime.Now), ConfirmedAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
return new { success = true };
|
||||
}
|
||||
|
||||
private static async Task<object> ExecuteManageExercise(AppDbContext db, Guid userId, JsonElement args)
|
||||
{
|
||||
var action = args.TryGetProperty("action", out var a) ? a.GetString()! : "query";
|
||||
if (action != "query") return new { success = false, message = "运动计划管理暂未实现" };
|
||||
|
||||
var plan = await db.ExercisePlans.Where(p => p.UserId == userId)
|
||||
.OrderByDescending(p => p.WeekStartDate).FirstOrDefaultAsync();
|
||||
if (plan == null) return new { found = false };
|
||||
var items = await db.ExercisePlanItems.Where(i => i.PlanId == plan.Id).OrderBy(i => i.DayOfWeek).ToListAsync();
|
||||
return new { found = true, plan_id = plan.Id, items = items.Select(i => new { i.DayOfWeek, i.ExerciseType, i.DurationMinutes, i.IsCompleted }) };
|
||||
}
|
||||
|
||||
private static async Task<string> BuildPatientContext(AppDbContext db, Guid userId, CancellationToken ct)
|
||||
{
|
||||
var archive = await db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == userId, ct);
|
||||
var recentRecords = await db.HealthRecords.Where(r => r.UserId == userId)
|
||||
.OrderByDescending(r => r.RecordedAt).Take(10).ToListAsync(ct);
|
||||
|
||||
var sb = new System.Text.StringBuilder();
|
||||
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.Allergies.Count > 0) sb.AppendLine($"过敏: {string.Join(", ", archive.Allergies)}");
|
||||
if (archive.DietRestrictions.Count > 0) sb.AppendLine($"饮食限制: {string.Join(", ", archive.DietRestrictions)}");
|
||||
}
|
||||
if (recentRecords.Count > 0)
|
||||
{
|
||||
sb.AppendLine("近期健康数据:");
|
||||
foreach (var r in recentRecords)
|
||||
sb.AppendLine($" {r.MetricType}: {RecordValue(r)} ({r.RecordedAt:MM-dd HH:mm})");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string RecordValue(HealthRecord r) => r.MetricType switch
|
||||
{
|
||||
HealthMetricType.BloodPressure => $"{r.Systolic}/{r.Diastolic}",
|
||||
HealthMetricType.HeartRate => $"{r.Value}次/分",
|
||||
HealthMetricType.Glucose => $"{r.Value}",
|
||||
HealthMetricType.SpO2 => $"{r.Value}%",
|
||||
HealthMetricType.Weight => $"{r.Value}kg",
|
||||
_ => "—"
|
||||
};
|
||||
|
||||
// ---- Tool Definitions ----
|
||||
private static readonly ToolDefinition RecordHealthDataTool = new()
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "record_health_data", Description = "记录健康数据(血压/心率/血糖/血氧/体重)",
|
||||
Parameters = new { type = "object", properties = new { type = new { type = "string" }, systolic = new { type = "integer" }, diastolic = new { type = "integer" }, heart_rate = new { type = "number" }, glucose = new { type = "number" }, spo2 = new { type = "number" }, weight = new { type = "number" } }, required = new[] { "type" } }
|
||||
}
|
||||
};
|
||||
private static readonly ToolDefinition QueryHealthRecordsTool = new()
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "query_health_records", Description = "查询近期健康数据",
|
||||
Parameters = new { type = "object", properties = new { type = new { type = "string" }, days = new { type = "integer" } } }
|
||||
}
|
||||
};
|
||||
private static readonly ToolDefinition CheckArchiveTool = new()
|
||||
{
|
||||
Function = new() { Name = "check_archive", Description = "查询患者健康档案", Parameters = new { type = "object", properties = new { } } }
|
||||
};
|
||||
private static readonly ToolDefinition ManageMedicationTool = new()
|
||||
{
|
||||
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" } }
|
||||
}
|
||||
};
|
||||
private static readonly ToolDefinition ManageExerciseTool = new()
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "manage_exercise", Description = "运动计划管理",
|
||||
Parameters = new { type = "object", properties = new { action = new { type = "string" } }, required = new[] { "action" } }
|
||||
}
|
||||
};
|
||||
private static readonly ToolDefinition EstimateFoodTool = new()
|
||||
{
|
||||
Function = new() { Name = "estimate_food_text", Description = "根据文字描述估算食物份量和热量", Parameters = new { type = "object", properties = new { text = new { type = "string" } }, required = new[] { "text" } } }
|
||||
};
|
||||
private static readonly ToolDefinition AnalyzeReportTool = new()
|
||||
{
|
||||
Function = new() { Name = "analyze_report", Description = "分析报告图片", Parameters = new { type = "object", properties = new { image_url = new { type = "string" } }, required = new[] { "image_url" } } }
|
||||
};
|
||||
private static readonly ToolDefinition RequestDoctorTool = new()
|
||||
{
|
||||
Function = new()
|
||||
{
|
||||
Name = "request_doctor", Description = "请求转接真人医生",
|
||||
Parameters = new { type = "object", properties = new { reason = new { type = "string" }, urgency_level = new { type = "string" } } }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>AI 对话请求</summary>
|
||||
public sealed record ChatRequest(string Message, string? ConversationId);
|
||||
190
backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs
Normal file
190
backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs
Normal file
@@ -0,0 +1,190 @@
|
||||
using System.Text.Json;
|
||||
using Health.Domain.Entities;
|
||||
using Health.Infrastructure.Data;
|
||||
using Health.Infrastructure.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// 认证相关 API 端点
|
||||
/// </summary>
|
||||
public static class AuthEndpoints
|
||||
{
|
||||
public static void MapAuthEndpoints(this WebApplication app)
|
||||
{
|
||||
// 发送短信验证码
|
||||
app.MapPost("/api/auth/send-sms", async (
|
||||
SendSmsRequest request,
|
||||
AppDbContext db,
|
||||
SmsService sms,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
// 生成验证码
|
||||
var code = sms.GenerateCode();
|
||||
var vc = new VerificationCode
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Phone = request.Phone,
|
||||
Code = code,
|
||||
ExpiresAt = DateTime.UtcNow.AddMinutes(5),
|
||||
};
|
||||
db.VerificationCodes.Add(vc);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// 开发阶段:直接返回验证码(生产环境需去掉 devCode)
|
||||
await sms.SendCodeAsync(request.Phone, code);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { success = true, devCode = code }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 手机号+验证码登录
|
||||
app.MapPost("/api/auth/login", async (
|
||||
LoginRequest request,
|
||||
AppDbContext db,
|
||||
JwtProvider jwt,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
// 开发阶段:任意6位数字通过
|
||||
var validCode = await db.VerificationCodes
|
||||
.Where(v => v.Phone == request.Phone
|
||||
&& v.Code == request.SmsCode
|
||||
&& v.ExpiresAt > DateTime.UtcNow
|
||||
&& !v.IsUsed)
|
||||
.OrderByDescending(v => v.CreatedAt)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
if (validCode == null)
|
||||
return Results.Ok(new { code = 40001, data = (object?)null, message = "验证码错误或已过期" });
|
||||
|
||||
validCode.IsUsed = true;
|
||||
|
||||
// 查找或创建用户
|
||||
var user = await db.Users.FirstOrDefaultAsync(u => u.Phone == request.Phone, ct);
|
||||
var isNew = false;
|
||||
if (user == null)
|
||||
{
|
||||
user = new User
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Phone = request.Phone,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
db.Users.Add(user);
|
||||
isNew = true;
|
||||
|
||||
// 创建默认通知偏好
|
||||
db.NotificationPreferences.Add(new NotificationPreference
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = user.Id,
|
||||
});
|
||||
|
||||
// 创建空健康档案
|
||||
db.HealthArchives.Add(new HealthArchive
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = user.Id,
|
||||
});
|
||||
}
|
||||
|
||||
user.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
// 生成 token
|
||||
var accessToken = jwt.GenerateAccessToken(user.Id, user.Phone);
|
||||
var refreshToken = jwt.GenerateRefreshToken();
|
||||
|
||||
// 保存 refresh token
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = user.Id,
|
||||
Token = refreshToken,
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new
|
||||
{
|
||||
code = 0,
|
||||
data = new
|
||||
{
|
||||
accessToken,
|
||||
refreshToken,
|
||||
user = new
|
||||
{
|
||||
user.Id,
|
||||
user.Phone,
|
||||
user.Name,
|
||||
user.Gender,
|
||||
BirthDate = user.BirthDate?.ToString("yyyy-MM-dd"),
|
||||
user.AvatarUrl,
|
||||
isNew
|
||||
}
|
||||
},
|
||||
message = (string?)null
|
||||
});
|
||||
});
|
||||
|
||||
// 刷新 token
|
||||
app.MapPost("/api/auth/refresh", async (
|
||||
RefreshRequest request,
|
||||
AppDbContext db,
|
||||
JwtProvider jwt,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
var oldToken = await db.RefreshTokens
|
||||
.FirstOrDefaultAsync(t => t.Token == request.RefreshToken && !t.IsRevoked, ct);
|
||||
|
||||
if (oldToken == null || oldToken.ExpiresAt < DateTime.UtcNow)
|
||||
return Results.Ok(new { code = 40002, data = (object?)null, message = "登录已过期,请重新登录" });
|
||||
|
||||
// 吊销旧 token
|
||||
oldToken.IsRevoked = true;
|
||||
|
||||
var user = await db.Users.FindAsync([oldToken.UserId], ct);
|
||||
if (user == null)
|
||||
return Results.Ok(new { code = 40002, data = (object?)null, message = "用户不存在" });
|
||||
|
||||
// 生成新 token(续期)
|
||||
var accessToken = jwt.GenerateAccessToken(user.Id, user.Phone);
|
||||
var newRefreshToken = jwt.GenerateRefreshToken();
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = user.Id,
|
||||
Token = newRefreshToken,
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new
|
||||
{
|
||||
code = 0,
|
||||
data = new { accessToken, refreshToken = newRefreshToken },
|
||||
message = (string?)null
|
||||
});
|
||||
});
|
||||
|
||||
// 登出
|
||||
app.MapPost("/api/auth/logout", async (
|
||||
RefreshRequest request,
|
||||
AppDbContext db,
|
||||
CancellationToken ct) =>
|
||||
{
|
||||
var token = await db.RefreshTokens
|
||||
.FirstOrDefaultAsync(t => t.Token == request.RefreshToken, ct);
|
||||
if (token != null) token.IsRevoked = true;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 请求 DTO ----
|
||||
public sealed record SendSmsRequest(string Phone);
|
||||
public sealed record LoginRequest(string Phone, string SmsCode);
|
||||
public sealed record RefreshRequest(string RefreshToken);
|
||||
132
backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs
Normal file
132
backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs
Normal file
@@ -0,0 +1,132 @@
|
||||
using Health.Domain.Entities;
|
||||
using Health.Domain.Enums;
|
||||
using Health.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// 健康数据 API 端点
|
||||
/// </summary>
|
||||
public static class HealthEndpoints
|
||||
{
|
||||
public static void MapHealthEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/health-records").RequireAuthorization();
|
||||
|
||||
// 查询健康记录
|
||||
group.MapGet("/", async (
|
||||
string? type, int? days,
|
||||
HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var query = db.HealthRecords.Where(r => r.UserId == userId);
|
||||
|
||||
if (!string.IsNullOrEmpty(type) && Enum.TryParse<HealthMetricType>(type, ignoreCase: true, out var mt))
|
||||
query = query.Where(r => r.MetricType == mt);
|
||||
|
||||
if (days.HasValue)
|
||||
query = query.Where(r => r.RecordedAt >= DateTime.UtcNow.AddDays(-days.Value));
|
||||
|
||||
var records = await query.OrderByDescending(r => r.RecordedAt).Take(100)
|
||||
.Select(r => new
|
||||
{
|
||||
r.Id, Type = r.MetricType.ToString(), r.Systolic, r.Diastolic, r.Value, r.Unit,
|
||||
Source = r.Source.ToString(), r.IsAbnormal, r.RecordedAt
|
||||
}).ToListAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = records, message = (string?)null });
|
||||
});
|
||||
|
||||
// 新增健康记录
|
||||
group.MapPost("/", async (CreateHealthRecordRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var record = new HealthRecord
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId, MetricType = req.Type,
|
||||
Systolic = req.Systolic, Diastolic = req.Diastolic, Value = req.Value,
|
||||
Unit = req.Unit, Source = req.Source, RecordedAt = req.RecordedAt ?? DateTime.UtcNow,
|
||||
IsAbnormal = CheckAbnormal(req),
|
||||
};
|
||||
db.HealthRecords.Add(record);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { record.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 修改健康记录
|
||||
group.MapPut("/{id:guid}", async (Guid id, CreateHealthRecordRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var record = await db.HealthRecords.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
|
||||
if (record == null) return Results.Ok(new { code = 40004, data = (object?)null, message = "记录不存在" });
|
||||
|
||||
record.Systolic = req.Systolic;
|
||||
record.Diastolic = req.Diastolic;
|
||||
record.Value = req.Value;
|
||||
record.Unit = req.Unit;
|
||||
record.RecordedAt = req.RecordedAt ?? record.RecordedAt;
|
||||
record.IsAbnormal = CheckAbnormal(req);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 获取各指标最新值
|
||||
group.MapGet("/latest", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var types = new[] { HealthMetricType.BloodPressure, HealthMetricType.HeartRate, HealthMetricType.Glucose, HealthMetricType.SpO2, HealthMetricType.Weight };
|
||||
var result = new Dictionary<string, object?>();
|
||||
|
||||
foreach (var t in types)
|
||||
{
|
||||
var latest = await db.HealthRecords
|
||||
.Where(r => r.UserId == userId && r.MetricType == t)
|
||||
.OrderByDescending(r => r.RecordedAt)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
|
||||
result[t.ToString()] = latest == null ? null : new
|
||||
{
|
||||
latest.Systolic, latest.Diastolic, latest.Value, latest.Unit, latest.RecordedAt
|
||||
};
|
||||
}
|
||||
|
||||
return Results.Ok(new { code = 0, data = result, message = (string?)null });
|
||||
});
|
||||
|
||||
// 趋势数据
|
||||
group.MapGet("/trend", async (string type, int period, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
if (!Enum.TryParse<HealthMetricType>(type, ignoreCase: true, out var mt))
|
||||
return Results.Ok(new { code = 40001, data = (object?)null, message = "不支持的指标类型" });
|
||||
|
||||
var days = period switch { 7 => 7, 30 => 30, 90 => 90, _ => 7 };
|
||||
var records = await db.HealthRecords
|
||||
.Where(r => r.UserId == userId && r.MetricType == mt && r.RecordedAt >= DateTime.UtcNow.AddDays(-days))
|
||||
.OrderBy(r => r.RecordedAt)
|
||||
.Select(r => new { r.Id, r.Systolic, r.Diastolic, r.Value, r.IsAbnormal, r.RecordedAt })
|
||||
.ToListAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = records, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
private static bool CheckAbnormal(CreateHealthRecordRequest req) => req.Type switch
|
||||
{
|
||||
HealthMetricType.BloodPressure => req.Systolic >= 140 || req.Diastolic >= 90 || req.Systolic <= 89 || req.Diastolic <= 59,
|
||||
HealthMetricType.HeartRate => req.Value > 100 || req.Value < 60,
|
||||
HealthMetricType.Glucose => req.Value >= 7.0m || req.Value <= 3.8m,
|
||||
HealthMetricType.SpO2 => req.Value <= 94,
|
||||
_ => false
|
||||
};
|
||||
|
||||
private static Guid GetUserId(HttpContext http) =>
|
||||
Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
public sealed record CreateHealthRecordRequest(
|
||||
HealthMetricType Type, int? Systolic, int? Diastolic, decimal? Value,
|
||||
string? Unit, HealthRecordSource Source, DateTime? RecordedAt);
|
||||
266
backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs
Normal file
266
backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using Health.Domain.Entities;
|
||||
using Health.Domain.Enums;
|
||||
using Health.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// 饮食、用药、报告、问诊、运动、文件端点
|
||||
/// </summary>
|
||||
public static class RemainingEndpoints
|
||||
{
|
||||
public static void MapDietEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/diet-records").RequireAuthorization();
|
||||
|
||||
group.MapGet("/", async (string? date, string? mealType, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var query = db.DietRecords.Include(d => d.FoodItems).Where(d => d.UserId == userId);
|
||||
if (DateOnly.TryParse(date, out var d)) query = query.Where(r => r.RecordedAt == d);
|
||||
if (Enum.TryParse<MealType>(mealType, ignoreCase: true, out var mt)) query = query.Where(r => r.MealType == mt);
|
||||
var records = await query.OrderByDescending(r => r.RecordedAt).ToListAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = records, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/", async (CreateDietRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var record = new DietRecord
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId, MealType = req.MealType,
|
||||
TotalCalories = req.TotalCalories, HealthScore = req.HealthScore, RecordedAt = req.RecordedAt ?? DateOnly.FromDateTime(DateTime.Now),
|
||||
};
|
||||
if (req.FoodItems != null)
|
||||
foreach (var fi in req.FoodItems)
|
||||
record.FoodItems.Add(new DietFoodItem { Id = Guid.NewGuid(), Name = fi.Name, Portion = fi.Portion, Calories = fi.Calories, ProteinGrams = fi.ProteinGrams, CarbsGrams = fi.CarbsGrams, FatGrams = fi.FatGrams, Warning = fi.Warning, SortOrder = fi.SortOrder });
|
||||
db.DietRecords.Add(record);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { record.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var record = await db.DietRecords.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
|
||||
if (record != null) { db.DietRecords.Remove(record); await db.SaveChangesAsync(ct); }
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapMedicationEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/medications").RequireAuthorization();
|
||||
|
||||
group.MapGet("/", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var meds = await db.Medications.Where(m => m.UserId == userId).OrderByDescending(m => m.CreatedAt).ToListAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = meds, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/", async (CreateMedicationRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var med = new Medication
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId, Name = req.Name, Dosage = req.Dosage,
|
||||
Frequency = req.Frequency, TimeOfDay = req.TimeOfDay ?? [],
|
||||
StartDate = req.StartDate, EndDate = req.EndDate, IsActive = true, Source = req.Source,
|
||||
};
|
||||
db.Medications.Add(med);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { med.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPut("/{id:guid}", async (Guid id, CreateMedicationRequest req, 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 = 40004, message = "不存在" });
|
||||
med.Name = req.Name; med.Dosage = req.Dosage; med.Frequency = req.Frequency;
|
||||
med.TimeOfDay = req.TimeOfDay ?? med.TimeOfDay; med.StartDate = req.StartDate; med.EndDate = req.EndDate;
|
||||
med.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapDelete("/{id:guid}", 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) { db.Medications.Remove(med); await db.SaveChangesAsync(ct); }
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/{id:guid}/confirm", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var log = new MedicationLog
|
||||
{
|
||||
Id = Guid.NewGuid(), MedicationId = id, UserId = userId,
|
||||
Status = MedicationLogStatus.Taken, ScheduledTime = TimeOnly.FromDateTime(DateTime.Now), ConfirmedAt = DateTime.UtcNow,
|
||||
};
|
||||
db.MedicationLogs.Add(log);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapReportEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/reports").RequireAuthorization();
|
||||
|
||||
group.MapGet("/", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var reports = await db.Reports.Where(r => r.UserId == userId).OrderByDescending(r => r.CreatedAt).ToListAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = reports, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapGet("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var report = await db.Reports.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
|
||||
return report == null ? Results.Ok(new { code = 40004, message = "不存在" }) : Results.Ok(new { code = 0, data = report, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapConsultationEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api").RequireAuthorization();
|
||||
|
||||
group.MapGet("/doctors", async (AppDbContext db) =>
|
||||
{
|
||||
var doctors = await db.Doctors.Where(d => d.IsActive).Select(d => new { d.Id, d.Name, d.Title, d.Department, d.Introduction }).ToListAsync();
|
||||
return Results.Ok(new { code = 0, data = doctors, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapGet("/consultations", async (HttpContext http, AppDbContext db) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var consultations = await db.Consultations.Where(c => c.UserId == userId).OrderByDescending(c => c.CreatedAt).ToListAsync();
|
||||
return Results.Ok(new { code = 0, data = consultations, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/consultations", async (CreateConsultationRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var consultation = new Consultation
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId, DoctorId = req.DoctorId,
|
||||
Status = ConsultationStatus.AiTalking,
|
||||
Month = DateTime.UtcNow.Year * 100 + DateTime.UtcNow.Month,
|
||||
};
|
||||
db.Consultations.Add(consultation);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { consultation.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapGet("/consultations/{id:guid}/messages", async (Guid id, string? after, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var query = db.ConsultationMessages.Where(m => m.ConsultationId == id && m.Consultation.UserId == userId);
|
||||
if (Guid.TryParse(after, out var afterId))
|
||||
query = query.Where(m => m.Id.CompareTo(afterId) > 0);
|
||||
var messages = await query.OrderBy(m => m.CreatedAt).Take(50).Select(m => new { m.Id, SenderType = m.SenderType.ToString(), m.SenderName, m.Content, m.CreatedAt }).ToListAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = messages, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/consultations/{id:guid}/messages", async (Guid id, SendMessageRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var msg = new ConsultationMessage { Id = Guid.NewGuid(), ConsultationId = id, SenderType = ConsultationSenderType.User, Content = req.Content, SenderName = null, CreatedAt = DateTime.UtcNow };
|
||||
db.ConsultationMessages.Add(msg);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { msg.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapGet("/user/consultation-quota", async (HttpContext http, AppDbContext db) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var now = DateTime.UtcNow;
|
||||
// 用年月组合值避免跨年问题:202601=2026年1月
|
||||
var currentPeriod = now.Year * 100 + now.Month;
|
||||
var used = await db.Consultations.CountAsync(c => c.UserId == userId && c.Month == currentPeriod);
|
||||
return Results.Ok(new { code = 0, data = new { total = 3, used, remaining = 3 - used }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapExerciseEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/exercise-plans").RequireAuthorization();
|
||||
|
||||
group.MapGet("/current", async (HttpContext http, AppDbContext db) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var today = DateOnly.FromDateTime(DateTime.Now);
|
||||
var monday = today.AddDays(-(int)today.DayOfWeek + 1);
|
||||
var plan = await db.ExercisePlans.Include(p => p.Items).FirstOrDefaultAsync(p => p.UserId == userId && p.WeekStartDate == monday);
|
||||
return Results.Ok(new { code = 0, data = plan, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/", async (CreateExercisePlanRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var plan = new ExercisePlan { Id = Guid.NewGuid(), UserId = userId, WeekStartDate = req.WeekStartDate };
|
||||
if (req.Items != null)
|
||||
foreach (var item in req.Items)
|
||||
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = item.DayOfWeek, ExerciseType = item.ExerciseType, DurationMinutes = item.DurationMinutes, IsRestDay = item.IsRestDay });
|
||||
db.ExercisePlans.Add(plan);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { plan.Id }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/items/{itemId:guid}/checkin", async (Guid itemId, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var item = await db.ExercisePlanItems.FindAsync([itemId], ct);
|
||||
if (item == null) return Results.Ok(new { code = 40004, message = "不存在" });
|
||||
item.IsCompleted = true; item.CompletedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapFileEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/files").RequireAuthorization();
|
||||
|
||||
group.MapPost("/upload", async (HttpRequest request) =>
|
||||
{
|
||||
var form = await request.ReadFormAsync();
|
||||
var files = form.Files;
|
||||
var results = new List<object>();
|
||||
var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
|
||||
Directory.CreateDirectory(uploadsDir);
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
var fileId = Guid.NewGuid().ToString();
|
||||
var ext = Path.GetExtension(file.FileName);
|
||||
var filePath = Path.Combine(uploadsDir, $"{fileId}{ext}");
|
||||
using var stream = new FileStream(filePath, FileMode.Create);
|
||||
await file.CopyToAsync(stream);
|
||||
results.Add(new { id = fileId, name = file.FileName, size = file.Length });
|
||||
}
|
||||
|
||||
return Results.Ok(new { code = 0, data = results, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
private static Guid GetUserId(HttpContext http) =>
|
||||
Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
// ---- 请求 DTO ----
|
||||
public sealed record CreateDietRequest(MealType MealType, int? TotalCalories, int? HealthScore, DateOnly? RecordedAt, List<FoodItemDto>? FoodItems);
|
||||
public sealed record FoodItemDto(string Name, string? Portion, int? Calories, decimal? ProteinGrams, decimal? CarbsGrams, decimal? FatGrams, string? Warning, int SortOrder);
|
||||
|
||||
public sealed record CreateMedicationRequest(string Name, string? Dosage, MedicationFrequency Frequency, List<TimeOnly>? TimeOfDay, DateOnly? StartDate, DateOnly? EndDate, MedicationSource Source);
|
||||
|
||||
public sealed record CreateConsultationRequest(Guid DoctorId);
|
||||
public sealed record SendMessageRequest(string Content);
|
||||
|
||||
public sealed record CreateExercisePlanRequest(DateOnly WeekStartDate, List<ExerciseItemDto>? Items);
|
||||
public sealed record ExerciseItemDto(int DayOfWeek, string ExerciseType, int DurationMinutes, bool IsRestDay);
|
||||
89
backend/src/Health.WebApi/Endpoints/UserEndpoints.cs
Normal file
89
backend/src/Health.WebApi/Endpoints/UserEndpoints.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using Health.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
/// <summary>
|
||||
/// 用户与健康档案 API 端点
|
||||
/// </summary>
|
||||
public static class UserEndpoints
|
||||
{
|
||||
public static void MapUserEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/api/user").RequireAuthorization();
|
||||
|
||||
// 获取个人信息
|
||||
group.MapGet("/profile", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var user = await db.Users.Select(u => new
|
||||
{
|
||||
u.Id, u.Phone, u.Name, u.Gender, BirthDate = u.BirthDate != null ? u.BirthDate.Value.ToString("yyyy-MM-dd") : null, u.AvatarUrl
|
||||
}).FirstOrDefaultAsync(u => u.Id == userId, ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = user, message = (string?)null });
|
||||
});
|
||||
|
||||
// 修改资料
|
||||
group.MapPut("/profile", async (UpdateProfileRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var user = await db.Users.FindAsync([userId], ct);
|
||||
if (user == null) return Results.Ok(new { code = 40004, message = "用户不存在" });
|
||||
|
||||
user.Name = req.Name ?? user.Name;
|
||||
user.Gender = req.Gender ?? user.Gender;
|
||||
if (DateOnly.TryParse(req.BirthDate, out var bd)) user.BirthDate = bd;
|
||||
user.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 获取健康档案
|
||||
group.MapGet("/health-archive", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var archive = await db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == userId, ct);
|
||||
return Results.Ok(new { code = 0, data = archive, message = (string?)null });
|
||||
});
|
||||
|
||||
// 更新健康档案
|
||||
group.MapPut("/health-archive", async (UpdateArchiveRequest req, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var archive = await db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == userId, ct);
|
||||
if (archive == null) return Results.Ok(new { code = 40004, message = "档案不存在" });
|
||||
|
||||
archive.Diagnosis = req.Diagnosis ?? archive.Diagnosis;
|
||||
archive.SurgeryType = req.SurgeryType ?? archive.SurgeryType;
|
||||
if (DateOnly.TryParse(req.SurgeryDate, out var sd)) archive.SurgeryDate = sd;
|
||||
if (req.Allergies != null) archive.Allergies = req.Allergies;
|
||||
if (req.DietRestrictions != null) archive.DietRestrictions = req.DietRestrictions;
|
||||
if (req.ChronicDiseases != null) archive.ChronicDiseases = req.ChronicDiseases;
|
||||
archive.FamilyHistory = req.FamilyHistory ?? archive.FamilyHistory;
|
||||
archive.UpdatedAt = DateTime.UtcNow;
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
// 注销账号
|
||||
group.MapDelete("/account", async (HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var user = await db.Users.FindAsync([userId], ct);
|
||||
if (user != null) { db.Users.Remove(user); await db.SaveChangesAsync(ct); }
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
private static Guid GetUserId(HttpContext http) =>
|
||||
Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
public sealed record UpdateProfileRequest(string? Name, string? Gender, string? BirthDate);
|
||||
public sealed record UpdateArchiveRequest(
|
||||
string? Diagnosis, string? SurgeryType, string? SurgeryDate,
|
||||
List<string>? Allergies, List<string>? DietRestrictions,
|
||||
List<string>? ChronicDiseases, string? FamilyHistory);
|
||||
Reference in New Issue
Block a user