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:
MingNian
2026-06-02 11:11:29 +08:00
commit 14d7c30d3d
144 changed files with 11436 additions and 0 deletions

View File

@@ -0,0 +1,136 @@
using Health.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Health.Infrastructure.Data;
/// <summary>
/// 应用程序数据库上下文
/// </summary>
public sealed class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
// 核心业务表
public DbSet<User> Users => Set<User>();
public DbSet<HealthRecord> HealthRecords => Set<HealthRecord>();
public DbSet<Medication> Medications => Set<Medication>();
public DbSet<MedicationLog> MedicationLogs => Set<MedicationLog>();
public DbSet<DietRecord> DietRecords => Set<DietRecord>();
public DbSet<DietFoodItem> DietFoodItems => Set<DietFoodItem>();
public DbSet<ExercisePlan> ExercisePlans => Set<ExercisePlan>();
public DbSet<ExercisePlanItem> ExercisePlanItems => Set<ExercisePlanItem>();
public DbSet<Report> Reports => Set<Report>();
public DbSet<Conversation> Conversations => Set<Conversation>();
public DbSet<ConversationMessage> ConversationMessages => Set<ConversationMessage>();
public DbSet<Consultation> Consultations => Set<Consultation>();
public DbSet<ConsultationMessage> ConsultationMessages => Set<ConsultationMessage>();
public DbSet<Doctor> Doctors => Set<Doctor>();
public DbSet<FollowUp> FollowUps => Set<FollowUp>();
public DbSet<HealthArchive> HealthArchives => Set<HealthArchive>();
// 支撑表
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<VerificationCode> VerificationCodes => Set<VerificationCode>();
public DbSet<NotificationPreference> NotificationPreferences => Set<NotificationPreference>();
public DbSet<DeviceToken> DeviceTokens => Set<DeviceToken>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// ---- User ----
builder.Entity<User>(e =>
{
e.HasIndex(u => u.Phone).IsUnique();
});
// ---- HealthRecord ----
builder.Entity<HealthRecord>(e =>
{
e.HasIndex(r => new { r.UserId, r.RecordedAt }).IsDescending(false, true);
e.HasIndex(r => new { r.UserId, r.MetricType });
e.Property(r => r.MetricType).HasConversion<string>();
e.Property(r => r.Source).HasConversion<string>();
});
// ---- Medication ----
builder.Entity<Medication>(e =>
{
e.HasIndex(m => new { m.UserId, m.IsActive });
e.Property(m => m.Frequency).HasConversion<string>();
e.Property(m => m.Source).HasConversion<string>();
e.Property(m => m.TimeOfDay).HasColumnType("time[]");
});
builder.Entity<MedicationLog>(e =>
{
e.HasIndex(l => new { l.MedicationId, l.CreatedAt }).IsDescending(false, true);
e.Property(l => l.Status).HasConversion<string>();
});
// ---- Diet ----
builder.Entity<DietRecord>(e =>
{
e.HasIndex(d => new { d.UserId, d.RecordedAt }).IsDescending(false, true);
e.Property(d => d.MealType).HasConversion<string>();
});
// ---- ExercisePlan ----
builder.Entity<ExercisePlan>(e =>
{
e.HasIndex(p => new { p.UserId, p.WeekStartDate }).IsDescending(false, true);
});
// ---- Report ----
builder.Entity<Report>(e =>
{
e.Property(r => r.FileType).HasConversion<string>();
e.Property(r => r.Category).HasConversion<string>();
e.Property(r => r.Status).HasConversion<string>();
});
// ---- Conversation ----
builder.Entity<Conversation>(e =>
{
e.HasIndex(c => new { c.UserId, c.UpdatedAt }).IsDescending(false, true);
e.Property(c => c.AgentType).HasConversion<string>();
});
builder.Entity<ConversationMessage>(e =>
{
e.HasIndex(m => new { m.ConversationId, m.CreatedAt });
e.Property(m => m.Role).HasConversion<string>();
});
// ---- Consultation ----
builder.Entity<Consultation>(e =>
{
e.Property(c => c.Status).HasConversion<string>();
});
builder.Entity<ConsultationMessage>(e =>
{
e.HasIndex(m => new { m.ConsultationId, m.CreatedAt }).IsDescending(false, true);
e.Property(m => m.SenderType).HasConversion<string>();
});
// ---- VerificationCode ----
builder.Entity<VerificationCode>(e =>
{
e.HasIndex(v => new { v.Phone, v.CreatedAt }).IsDescending(false, true);
});
// ---- NotificationPreference ----
builder.Entity<NotificationPreference>(e =>
{
e.HasIndex(n => n.UserId).IsUnique();
});
// ---- HealthArchive ----
builder.Entity<HealthArchive>(e =>
{
e.HasIndex(a => a.UserId).IsUnique();
});
}
}

View File

@@ -0,0 +1,47 @@
using Health.Domain.Entities;
namespace Health.Infrastructure.Data;
/// <summary>
/// 数据库种子数据
/// </summary>
public static class DataSeeder
{
public static async Task SeedAsync(AppDbContext db)
{
// 种子医生数据
if (!db.Doctors.Any())
{
db.Doctors.AddRange(
new Doctor
{
Id = Guid.NewGuid(),
Name = "王建国",
Title = "主任医师",
Department = "心血管内科",
Introduction = "擅长冠心病术后管理、心脏康复指导",
IsActive = true
},
new Doctor
{
Id = Guid.NewGuid(),
Name = "李芳",
Title = "副主任医师",
Department = "营养科",
Introduction = "擅长术后营养指导、膳食规划",
IsActive = true
},
new Doctor
{
Id = Guid.NewGuid(),
Name = "张明",
Title = "主任医师",
Department = "心脏康复科",
Introduction = "擅长心脏术后运动康复、心肺功能评估",
IsActive = true
}
);
await db.SaveChangesAsync();
}
}
}

View File

@@ -0,0 +1,144 @@
using Health.Domain.Entities;
using Health.Domain.Enums;
using Microsoft.Extensions.Configuration;
namespace Health.Infrastructure.Data;
/// <summary>
/// 开发环境测试数据填充。生产环境不要调用!
/// 开关DEVDATA_ENABLED=true 才会执行
/// </summary>
public static class DevDataSeeder
{
public static async Task SeedIfEnabled(AppDbContext db, IConfiguration config)
{
// 通过环境变量控制DEVDATA_ENABLED=true 才填充测试数据
var enabled = config["DEVDATA_ENABLED"]?.ToLowerInvariant();
if (enabled != "true") return;
// 检查是否已有测试用户(避免重复填充)
if (db.Users.Any(u => u.Phone == "13800000001")) return;
// ---- 创建测试患者 ----
var user = new User
{
Id = Guid.NewGuid(), Phone = "13800000001", Name = "张三",
Gender = "男", BirthDate = new DateOnly(1970, 3, 15),
CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow,
};
db.Users.Add(user);
await db.SaveChangesAsync();
// ---- 健康档案 ----
db.HealthArchives.Add(new HealthArchive
{
Id = Guid.NewGuid(), UserId = user.Id,
Diagnosis = "冠心病", SurgeryType = "PCI支架植入术",
SurgeryDate = new DateOnly(2026, 3, 15),
Allergies = ["青霉素"], DietRestrictions = ["低盐", "低脂"],
ChronicDiseases = ["高血压", "高血脂"],
FamilyHistory = "父亲冠心病",
UpdatedAt = DateTime.UtcNow,
});
// ---- 健康数据(过去 7 天)----
var random = new Random(42);
for (int i = 7; i >= 0; i--)
{
var date = DateTime.UtcNow.AddDays(-i);
// 血压
db.HealthRecords.Add(new HealthRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.BloodPressure,
Systolic = 120 + random.Next(-5, 15), Diastolic = 75 + random.Next(-5, 10),
Unit = "mmHg", Source = HealthRecordSource.AiEntry,
IsAbnormal = false, RecordedAt = date,
});
// 心率
db.HealthRecords.Add(new HealthRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.HeartRate,
Value = 68 + random.Next(-5, 10), Unit = "次/分",
Source = HealthRecordSource.AiEntry,
IsAbnormal = false, RecordedAt = date,
});
// 血糖
db.HealthRecords.Add(new HealthRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.Glucose,
Value = 5.0m + (decimal)(random.NextDouble() * 1.5),
Unit = "mmol/L", Source = HealthRecordSource.AiEntry,
IsAbnormal = false, RecordedAt = date,
});
// 血氧
db.HealthRecords.Add(new HealthRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.SpO2,
Value = 96 + random.Next(0, 3), Unit = "%",
Source = HealthRecordSource.AiEntry,
IsAbnormal = false, RecordedAt = date,
});
}
// 一条异常血压
db.HealthRecords.Add(new HealthRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.BloodPressure,
Systolic = 148, Diastolic = 92, Unit = "mmHg",
Source = HealthRecordSource.AiEntry, IsAbnormal = true,
RecordedAt = DateTime.UtcNow.AddDays(-1),
});
// ---- 用药计划 ----
db.Medications.Add(new Medication
{
Id = Guid.NewGuid(), UserId = user.Id, Name = "阿司匹林", Dosage = "100mg",
Frequency = MedicationFrequency.Daily, TimeOfDay = [new TimeOnly(8, 0)],
Source = MedicationSource.Prescription, IsActive = true, StartDate = new DateOnly(2026, 4, 1),
});
db.Medications.Add(new Medication
{
Id = Guid.NewGuid(), UserId = user.Id, Name = "阿托伐他汀", Dosage = "20mg",
Frequency = MedicationFrequency.Daily, TimeOfDay = [new TimeOnly(20, 0)],
Source = MedicationSource.Prescription, IsActive = true, StartDate = new DateOnly(2026, 4, 1),
});
// ---- 运动计划 ----
var monday = DateOnly.FromDateTime(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1));
var plan = new ExercisePlan { Id = Guid.NewGuid(), UserId = user.Id, WeekStartDate = monday };
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 0, ExerciseType = "散步", DurationMinutes = 30, IsCompleted = true, CompletedAt = DateTime.UtcNow.AddDays(-1) });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 1, ExerciseType = "慢跑", DurationMinutes = 20 });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 2, ExerciseType = "散步", DurationMinutes = 30 });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 3, IsRestDay = true });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 4, ExerciseType = "太极", DurationMinutes = 40 });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 5, IsRestDay = true });
plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 6, ExerciseType = "散步", DurationMinutes = 30 });
db.ExercisePlans.Add(plan);
// ---- 饮食记录 ----
var lunch = new DietRecord
{
Id = Guid.NewGuid(), UserId = user.Id, MealType = MealType.Lunch,
TotalCalories = 644, HealthScore = 3, RecordedAt = DateOnly.FromDateTime(DateTime.Now),
};
lunch.FoodItems.Add(new DietFoodItem { Id = Guid.NewGuid(), Name = "米饭", Portion = "约1碗", Calories = 174, SortOrder = 1 });
lunch.FoodItems.Add(new DietFoodItem { Id = Guid.NewGuid(), Name = "红烧肉", Portion = "约5块", Calories = 470, Warning = "脂肪含量偏高", SortOrder = 2 });
db.DietRecords.Add(lunch);
// ---- 复查计划 ----
db.FollowUps.Add(new FollowUp
{
Id = Guid.NewGuid(), UserId = user.Id, Title = "心内科复查",
DoctorName = "王建国", Department = "心血管内科",
ScheduledAt = DateTime.UtcNow.AddDays(3), Status = FollowUpStatus.Upcoming,
});
db.FollowUps.Add(new FollowUp
{
Id = Guid.NewGuid(), UserId = user.Id, Title = "术后3周复查",
DoctorName = "王建国", Department = "心血管内科",
ScheduledAt = DateTime.UtcNow.AddDays(-14), Status = FollowUpStatus.Completed,
});
await db.SaveChangesAsync();
Console.WriteLine($"[DEV] 测试数据已填充:用户 {user.Phone}");
}
}