feat: 后端架构重构 — Endpoint→Service→Repository分层 + AI确认机制 + 异步任务持久化
- 核心业务拆分为 Endpoint → Application Service → Repository 三层 - AI写入操作必须用户确认后才写库(确认卡片机制) - 报告/饮食/用药分析改为持久化任务队列(原子领取/重试/重启恢复) - 运动计划修复: 连续真实日期替代周模板 - 用药提醒去重 + 通知Outbox预留 - 认证收拢到AuthService, 管理员收拢到AdminService - AI会话加用户归属校验防串号 - 提示词调整为患者视角 - 开发假数据已关闭 - 21/21测试通过, 0警告0错误
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
using Health.Application.Diets;
|
||||
|
||||
namespace Health.WebApi.Endpoints;
|
||||
|
||||
public static class DietEndpoints
|
||||
@@ -6,82 +8,91 @@ public static class DietEndpoints
|
||||
{
|
||||
var group = app.MapGroup("/api/diet-records").RequireAuthorization();
|
||||
|
||||
group.MapGet("/", async (string? date, string? mealType, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
group.MapGet("/", async (string? date, string? mealType, HttpContext http, IDietService diets, 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).Select(r => new
|
||||
{
|
||||
r.Id, MealType = r.MealType.ToString(), r.TotalCalories, r.HealthScore, r.RecordedAt,
|
||||
foodItems = r.FoodItems.Select(f => new { f.Name, f.Portion, f.Calories })
|
||||
}).ToListAsync(ct);
|
||||
var records = await diets.ListAsync(userId, date, mealType, ct);
|
||||
return Results.Ok(new { code = 0, data = records, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPost("/", async (HttpRequest request, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
group.MapPost("/", async (HttpRequest request, HttpContext http, IDietService diets, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
request.EnableBuffering();
|
||||
using var reader = new StreamReader(request.Body);
|
||||
var body = await reader.ReadToEndAsync(ct);
|
||||
request.Body.Position = 0;
|
||||
using var json = JsonDocument.Parse(body);
|
||||
var root = json.RootElement;
|
||||
var record = new DietRecord
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = userId,
|
||||
MealType = Enum.TryParse<MealType>(root.TryGetProperty("mealType", out var mt) ? mt.GetString() : "Lunch", out var meal) ? meal : MealType.Lunch,
|
||||
TotalCalories = root.TryGetProperty("totalCalories", out var tc) ? tc.GetInt32() : null,
|
||||
HealthScore = root.TryGetProperty("healthScore", out var hs) ? hs.GetInt32() : null,
|
||||
RecordedAt = root.TryGetProperty("recordedAt", out var ra) && DateOnly.TryParse(ra.GetString(), out var d) ? d : DateOnly.FromDateTime(DateTime.UtcNow.AddHours(8)),
|
||||
};
|
||||
if (root.TryGetProperty("foodItems", out var items))
|
||||
{
|
||||
var i = 0;
|
||||
foreach (var fi in items.EnumerateArray())
|
||||
{
|
||||
record.FoodItems.Add(new DietFoodItem
|
||||
{
|
||||
Id = Guid.NewGuid(), Name = fi.TryGetProperty("name", out var n) ? n.GetString()! : "",
|
||||
Portion = fi.TryGetProperty("portion", out var p) ? p.GetString() : null,
|
||||
Calories = fi.TryGetProperty("calories", out var c) ? c.GetInt32() : null,
|
||||
SortOrder = fi.TryGetProperty("sortOrder", out var so) ? so.GetInt32() : i,
|
||||
});
|
||||
i++;
|
||||
}
|
||||
}
|
||||
db.DietRecords.Add(record);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { record.Id }, message = (string?)null });
|
||||
using var json = JsonDocument.Parse(await ReadBodyAsync(request, ct));
|
||||
var recordId = await diets.CreateAsync(userId, ReadCreateRequest(json.RootElement), ct);
|
||||
return Results.Ok(new { code = 0, data = new { id = recordId }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
group.MapDelete("/{id:guid}", async (Guid id, HttpContext http, IDietService diets, 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); }
|
||||
await diets.DeleteAsync(userId, id, ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
|
||||
group.MapPut("/{id:guid}", async (Guid id, HttpContext http, AppDbContext db, CancellationToken ct) =>
|
||||
group.MapPut("/{id:guid}", async (Guid id, HttpContext http, IDietService diets, CancellationToken ct) =>
|
||||
{
|
||||
var userId = GetUserId(http);
|
||||
var record = await db.DietRecords.FirstOrDefaultAsync(r => r.Id == id && r.UserId == userId, ct);
|
||||
if (record == null) return Results.Ok(new { code = 40004, message = "记录不存在" });
|
||||
using var json = JsonDocument.Parse(await ReadBodyAsync(http.Request, ct));
|
||||
var updated = await diets.UpdateAsync(userId, id, ReadPatchRequest(json.RootElement), ct);
|
||||
if (!updated) return Results.Ok(new { code = 40004, message = "记录不存在" });
|
||||
|
||||
using var reader = new StreamReader(http.Request.Body);
|
||||
var body = await reader.ReadToEndAsync(ct);
|
||||
var json = System.Text.Json.JsonDocument.Parse(body);
|
||||
if (json.RootElement.TryGetProperty("totalCalories", out var cal)) record.TotalCalories = (int?)cal.GetInt32();
|
||||
if (json.RootElement.TryGetProperty("healthScore", out var hs)) record.HealthScore = (int?)hs.GetInt32();
|
||||
await db.SaveChangesAsync(ct);
|
||||
return Results.Ok(new { code = 0, data = new { success = true }, message = (string?)null });
|
||||
});
|
||||
}
|
||||
|
||||
private static DietRecordCreateRequest ReadCreateRequest(JsonElement root)
|
||||
{
|
||||
var mealType = Enum.TryParse<MealType>(
|
||||
root.TryGetProperty("mealType", out var mt) ? mt.GetString() : "Lunch",
|
||||
out var meal)
|
||||
? meal
|
||||
: MealType.Lunch;
|
||||
var recordedAt = root.TryGetProperty("recordedAt", out var ra) && DateOnly.TryParse(ra.GetString(), out var d)
|
||||
? d
|
||||
: DateOnly.FromDateTime(DateTime.UtcNow.AddHours(8));
|
||||
|
||||
return new DietRecordCreateRequest(
|
||||
mealType,
|
||||
root.TryGetProperty("totalCalories", out var tc) ? tc.GetInt32() : null,
|
||||
root.TryGetProperty("healthScore", out var hs) ? hs.GetInt32() : null,
|
||||
recordedAt,
|
||||
ReadFoodItems(root));
|
||||
}
|
||||
|
||||
private static DietRecordPatchRequest ReadPatchRequest(JsonElement root) => new(
|
||||
root.TryGetProperty("totalCalories", out var cal) ? cal.GetInt32() : null,
|
||||
root.TryGetProperty("healthScore", out var hs) ? hs.GetInt32() : null);
|
||||
|
||||
private static List<DietFoodItemInput> ReadFoodItems(JsonElement root)
|
||||
{
|
||||
var result = new List<DietFoodItemInput>();
|
||||
if (!root.TryGetProperty("foodItems", out var items) || items.ValueKind != JsonValueKind.Array)
|
||||
return result;
|
||||
|
||||
var i = 0;
|
||||
foreach (var fi in items.EnumerateArray())
|
||||
{
|
||||
result.Add(new DietFoodItemInput(
|
||||
fi.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "",
|
||||
fi.TryGetProperty("portion", out var p) ? p.GetString() : null,
|
||||
fi.TryGetProperty("calories", out var c) ? c.GetInt32() : null,
|
||||
fi.TryGetProperty("sortOrder", out var so) ? so.GetInt32() : i));
|
||||
i++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static async Task<string> ReadBodyAsync(HttpRequest request, CancellationToken ct)
|
||||
{
|
||||
request.EnableBuffering();
|
||||
using var reader = new StreamReader(request.Body, leaveOpen: true);
|
||||
var body = await reader.ReadToEndAsync(ct);
|
||||
request.Body.Position = 0;
|
||||
return string.IsNullOrWhiteSpace(body) ? "{}" : body;
|
||||
}
|
||||
|
||||
private static Guid GetUserId(HttpContext http) =>
|
||||
Guid.TryParse(http.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user