From 14d7c30d3d093dc634d947f3430374f0635ad8c3 Mon Sep 17 00:00:00 2001 From: MingNian <1281442923@qq.com> Date: Tue, 2 Jun 2026 11:11:29 +0800 Subject: [PATCH] =?UTF-8?q?Initial=20commit:=20=E5=81=A5=E5=BA=B7=E7=AE=A1?= =?UTF-8?q?=E5=AE=B6=20AI=20=E5=81=A5=E5=BA=B7=E9=99=AA=E4=BC=B4=E5=8A=A9?= =?UTF-8?q?=E6=89=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .gitignore | 37 + CLAUDE.md | 26 + backend/.env.example | 22 + backend/HealthManager.slnx | 11 + .../Health.Application.csproj | 13 + .../Health.Domain/Entities/Consultation.cs | 53 + .../Health.Domain/Entities/Conversation.cs | 39 + .../src/Health.Domain/Entities/DietRecord.cs | 39 + .../Health.Domain/Entities/ExercisePlan.cs | 33 + .../Health.Domain/Entities/HealthRecord.cs | 23 + .../src/Health.Domain/Entities/Medication.cs | 41 + backend/src/Health.Domain/Entities/Report.cs | 26 + .../Health.Domain/Entities/SupportEntities.cs | 99 ++ backend/src/Health.Domain/Entities/User.cs | 29 + .../src/Health.Domain/Enums/HealthEnums.cs | 152 ++ .../src/Health.Domain/Health.Domain.csproj | 9 + .../src/Health.Infrastructure/AI/AiClients.cs | 152 ++ .../AI/OpenAiCompatibleClient.cs | 235 +++ .../Health.Infrastructure/AI/PromptManager.cs | 116 ++ .../Data/AppDbContext.cs | 136 ++ .../Health.Infrastructure/Data/DataSeeder.cs | 47 + .../Data/DevDataSeeder.cs | 144 ++ .../Health.Infrastructure.csproj | 22 + .../Services/JwtProvider.cs | 80 ++ .../Services/SmsService.cs | 26 + .../BackgroundServices/CleanupService.cs | 61 + .../MedicationReminderService.cs | 72 + .../Endpoints/AiChatEndpoints.cs | 572 ++++++++ .../Health.WebApi/Endpoints/AuthEndpoints.cs | 190 +++ .../Endpoints/HealthEndpoints.cs | 132 ++ .../Endpoints/RemainingEndpoints.cs | 266 ++++ .../Health.WebApi/Endpoints/UserEndpoints.cs | 89 ++ .../src/Health.WebApi/Health.WebApi.csproj | 20 + backend/src/Health.WebApi/Health.WebApi.http | 6 + .../Middleware/ExceptionMiddleware.cs | 42 + backend/src/Health.WebApi/Program.cs | 124 ++ .../Properties/launchSettings.json | 23 + .../appsettings.Development.json | 8 + backend/src/Health.WebApi/appsettings.json | 24 + backend/tests/Health.Tests/AuthTests.cs | 143 ++ backend/tests/Health.Tests/EntityTests.cs | 221 +++ .../tests/Health.Tests/Health.Tests.csproj | 29 + backend/tests/Health.Tests/UnitTest1.cs | 10 + docker-compose.yml | 35 + health_app/.gitignore | 45 + health_app/.metadata | 30 + health_app/README.md | 16 + health_app/analysis_options.yaml | 28 + health_app/android/.gitignore | 14 + health_app/android/app/build.gradle.kts | 44 + .../android/app/src/debug/AndroidManifest.xml | 7 + .../android/app/src/main/AndroidManifest.xml | 45 + .../healthmanager/health_app/MainActivity.kt | 5 + .../res/drawable-v21/launch_background.xml | 12 + .../main/res/drawable/launch_background.xml | 12 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 544 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 442 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 721 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 1031 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 1443 bytes .../app/src/main/res/values-night/styles.xml | 18 + .../app/src/main/res/values/styles.xml | 18 + .../app/src/profile/AndroidManifest.xml | 7 + health_app/android/build.gradle.kts | 26 + health_app/android/gradle.properties | 3 + .../gradle/wrapper/gradle-wrapper.properties | 5 + health_app/android/settings.gradle.kts | 22 + health_app/ios/.gitignore | 34 + health_app/ios/Flutter/AppFrameworkInfo.plist | 26 + health_app/ios/Flutter/Debug.xcconfig | 1 + health_app/ios/Flutter/Release.xcconfig | 1 + .../ios/Runner.xcodeproj/project.pbxproj | 616 ++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../xcshareddata/xcschemes/Runner.xcscheme | 101 ++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + health_app/ios/Runner/AppDelegate.swift | 13 + .../AppIcon.appiconset/Contents.json | 122 ++ .../Icon-App-1024x1024@1x.png | Bin 0 -> 10932 bytes .../AppIcon.appiconset/Icon-App-20x20@1x.png | Bin 0 -> 295 bytes .../AppIcon.appiconset/Icon-App-20x20@2x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-20x20@3x.png | Bin 0 -> 450 bytes .../AppIcon.appiconset/Icon-App-29x29@1x.png | Bin 0 -> 282 bytes .../AppIcon.appiconset/Icon-App-29x29@2x.png | Bin 0 -> 462 bytes .../AppIcon.appiconset/Icon-App-29x29@3x.png | Bin 0 -> 704 bytes .../AppIcon.appiconset/Icon-App-40x40@1x.png | Bin 0 -> 406 bytes .../AppIcon.appiconset/Icon-App-40x40@2x.png | Bin 0 -> 586 bytes .../AppIcon.appiconset/Icon-App-40x40@3x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@2x.png | Bin 0 -> 862 bytes .../AppIcon.appiconset/Icon-App-60x60@3x.png | Bin 0 -> 1674 bytes .../AppIcon.appiconset/Icon-App-76x76@1x.png | Bin 0 -> 762 bytes .../AppIcon.appiconset/Icon-App-76x76@2x.png | Bin 0 -> 1226 bytes .../Icon-App-83.5x83.5@2x.png | Bin 0 -> 1418 bytes .../LaunchImage.imageset/Contents.json | 23 + .../LaunchImage.imageset/LaunchImage.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@2x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@3x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/README.md | 5 + .../Runner/Base.lproj/LaunchScreen.storyboard | 37 + .../ios/Runner/Base.lproj/Main.storyboard | 26 + health_app/ios/Runner/Info.plist | 49 + .../ios/Runner/Runner-Bridging-Header.h | 1 + health_app/ios/RunnerTests/RunnerTests.swift | 12 + health_app/lib/app.dart | 18 + health_app/lib/core/api_client.dart | 99 ++ health_app/lib/core/app_router.dart | 57 + health_app/lib/core/app_theme.dart | 77 + health_app/lib/core/secure_storage.dart | 35 + health_app/lib/main.dart | 8 + health_app/lib/pages/auth/login_page.dart | 184 +++ health_app/lib/pages/chart/trend_page.dart | 79 ++ .../consultation/consultation_pages.dart | 93 ++ health_app/lib/pages/home/home_page.dart | 174 +++ .../home/widgets/chat_messages_view.dart | 88 ++ .../medication/medication_list_page.dart | 80 ++ .../lib/pages/profile/profile_page.dart | 69 + health_app/lib/pages/remaining_pages.dart | 196 +++ health_app/lib/pages/report/report_pages.dart | 25 + .../lib/pages/settings/settings_pages.dart | 67 + health_app/lib/providers/auth_provider.dart | 139 ++ health_app/lib/providers/chat_provider.dart | 159 +++ health_app/lib/providers/data_providers.dart | 58 + health_app/lib/services/health_service.dart | 158 +++ health_app/lib/utils/sse_handler.dart | 84 ++ health_app/lib/widgets/agent_bar.dart | 61 + health_app/lib/widgets/health_drawer.dart | 119 ++ health_app/pubspec.lock | 898 ++++++++++++ health_app/pubspec.yaml | 44 + health_app/test/widget_test.dart | 83 ++ health_app/web/favicon.png | Bin 0 -> 917 bytes health_app/web/icons/Icon-192.png | Bin 0 -> 5292 bytes health_app/web/icons/Icon-512.png | Bin 0 -> 8252 bytes health_app/web/icons/Icon-maskable-192.png | Bin 0 -> 5594 bytes health_app/web/icons/Icon-maskable-512.png | Bin 0 -> 20998 bytes health_app/web/index.html | 38 + health_app/web/manifest.json | 35 + start-dev.bat | 3 + start-dev.ps1 | 36 + 健康管家-技术设计文档-v2.md | 1254 +++++++++++++++++ 健康管家-需求规格文档-v2.md | 804 +++++++++++ 健康管家-页面设计文档.md | 967 +++++++++++++ 144 files changed, 11436 insertions(+) create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 backend/.env.example create mode 100644 backend/HealthManager.slnx create mode 100644 backend/src/Health.Application/Health.Application.csproj create mode 100644 backend/src/Health.Domain/Entities/Consultation.cs create mode 100644 backend/src/Health.Domain/Entities/Conversation.cs create mode 100644 backend/src/Health.Domain/Entities/DietRecord.cs create mode 100644 backend/src/Health.Domain/Entities/ExercisePlan.cs create mode 100644 backend/src/Health.Domain/Entities/HealthRecord.cs create mode 100644 backend/src/Health.Domain/Entities/Medication.cs create mode 100644 backend/src/Health.Domain/Entities/Report.cs create mode 100644 backend/src/Health.Domain/Entities/SupportEntities.cs create mode 100644 backend/src/Health.Domain/Entities/User.cs create mode 100644 backend/src/Health.Domain/Enums/HealthEnums.cs create mode 100644 backend/src/Health.Domain/Health.Domain.csproj create mode 100644 backend/src/Health.Infrastructure/AI/AiClients.cs create mode 100644 backend/src/Health.Infrastructure/AI/OpenAiCompatibleClient.cs create mode 100644 backend/src/Health.Infrastructure/AI/PromptManager.cs create mode 100644 backend/src/Health.Infrastructure/Data/AppDbContext.cs create mode 100644 backend/src/Health.Infrastructure/Data/DataSeeder.cs create mode 100644 backend/src/Health.Infrastructure/Data/DevDataSeeder.cs create mode 100644 backend/src/Health.Infrastructure/Health.Infrastructure.csproj create mode 100644 backend/src/Health.Infrastructure/Services/JwtProvider.cs create mode 100644 backend/src/Health.Infrastructure/Services/SmsService.cs create mode 100644 backend/src/Health.WebApi/BackgroundServices/CleanupService.cs create mode 100644 backend/src/Health.WebApi/BackgroundServices/MedicationReminderService.cs create mode 100644 backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs create mode 100644 backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs create mode 100644 backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs create mode 100644 backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs create mode 100644 backend/src/Health.WebApi/Endpoints/UserEndpoints.cs create mode 100644 backend/src/Health.WebApi/Health.WebApi.csproj create mode 100644 backend/src/Health.WebApi/Health.WebApi.http create mode 100644 backend/src/Health.WebApi/Middleware/ExceptionMiddleware.cs create mode 100644 backend/src/Health.WebApi/Program.cs create mode 100644 backend/src/Health.WebApi/Properties/launchSettings.json create mode 100644 backend/src/Health.WebApi/appsettings.Development.json create mode 100644 backend/src/Health.WebApi/appsettings.json create mode 100644 backend/tests/Health.Tests/AuthTests.cs create mode 100644 backend/tests/Health.Tests/EntityTests.cs create mode 100644 backend/tests/Health.Tests/Health.Tests.csproj create mode 100644 backend/tests/Health.Tests/UnitTest1.cs create mode 100644 docker-compose.yml create mode 100644 health_app/.gitignore create mode 100644 health_app/.metadata create mode 100644 health_app/README.md create mode 100644 health_app/analysis_options.yaml create mode 100644 health_app/android/.gitignore create mode 100644 health_app/android/app/build.gradle.kts create mode 100644 health_app/android/app/src/debug/AndroidManifest.xml create mode 100644 health_app/android/app/src/main/AndroidManifest.xml create mode 100644 health_app/android/app/src/main/kotlin/com/healthmanager/health_app/MainActivity.kt create mode 100644 health_app/android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 health_app/android/app/src/main/res/drawable/launch_background.xml create mode 100644 health_app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 health_app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 health_app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 health_app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 health_app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 health_app/android/app/src/main/res/values-night/styles.xml create mode 100644 health_app/android/app/src/main/res/values/styles.xml create mode 100644 health_app/android/app/src/profile/AndroidManifest.xml create mode 100644 health_app/android/build.gradle.kts create mode 100644 health_app/android/gradle.properties create mode 100644 health_app/android/gradle/wrapper/gradle-wrapper.properties create mode 100644 health_app/android/settings.gradle.kts create mode 100644 health_app/ios/.gitignore create mode 100644 health_app/ios/Flutter/AppFrameworkInfo.plist create mode 100644 health_app/ios/Flutter/Debug.xcconfig create mode 100644 health_app/ios/Flutter/Release.xcconfig create mode 100644 health_app/ios/Runner.xcodeproj/project.pbxproj create mode 100644 health_app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 health_app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme create mode 100644 health_app/ios/Runner.xcworkspace/contents.xcworkspacedata create mode 100644 health_app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 health_app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 health_app/ios/Runner/AppDelegate.swift create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json create mode 100644 health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png create mode 100644 health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png create mode 100644 health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md create mode 100644 health_app/ios/Runner/Base.lproj/LaunchScreen.storyboard create mode 100644 health_app/ios/Runner/Base.lproj/Main.storyboard create mode 100644 health_app/ios/Runner/Info.plist create mode 100644 health_app/ios/Runner/Runner-Bridging-Header.h create mode 100644 health_app/ios/RunnerTests/RunnerTests.swift create mode 100644 health_app/lib/app.dart create mode 100644 health_app/lib/core/api_client.dart create mode 100644 health_app/lib/core/app_router.dart create mode 100644 health_app/lib/core/app_theme.dart create mode 100644 health_app/lib/core/secure_storage.dart create mode 100644 health_app/lib/main.dart create mode 100644 health_app/lib/pages/auth/login_page.dart create mode 100644 health_app/lib/pages/chart/trend_page.dart create mode 100644 health_app/lib/pages/consultation/consultation_pages.dart create mode 100644 health_app/lib/pages/home/home_page.dart create mode 100644 health_app/lib/pages/home/widgets/chat_messages_view.dart create mode 100644 health_app/lib/pages/medication/medication_list_page.dart create mode 100644 health_app/lib/pages/profile/profile_page.dart create mode 100644 health_app/lib/pages/remaining_pages.dart create mode 100644 health_app/lib/pages/report/report_pages.dart create mode 100644 health_app/lib/pages/settings/settings_pages.dart create mode 100644 health_app/lib/providers/auth_provider.dart create mode 100644 health_app/lib/providers/chat_provider.dart create mode 100644 health_app/lib/providers/data_providers.dart create mode 100644 health_app/lib/services/health_service.dart create mode 100644 health_app/lib/utils/sse_handler.dart create mode 100644 health_app/lib/widgets/agent_bar.dart create mode 100644 health_app/lib/widgets/health_drawer.dart create mode 100644 health_app/pubspec.lock create mode 100644 health_app/pubspec.yaml create mode 100644 health_app/test/widget_test.dart create mode 100644 health_app/web/favicon.png create mode 100644 health_app/web/icons/Icon-192.png create mode 100644 health_app/web/icons/Icon-512.png create mode 100644 health_app/web/icons/Icon-maskable-192.png create mode 100644 health_app/web/icons/Icon-maskable-512.png create mode 100644 health_app/web/index.html create mode 100644 health_app/web/manifest.json create mode 100644 start-dev.bat create mode 100644 start-dev.ps1 create mode 100644 健康管家-技术设计文档-v2.md create mode 100644 健康管家-需求规格文档-v2.md create mode 100644 健康管家-页面设计文档.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a1be7d2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Secrets +.env +*.pem +*.key +*.pfx + +# .NET build outputs +backend/**/bin/ +backend/**/obj/ + +# Flutter build outputs +health_app/build/ +health_app/.dart_tool/ +health_app/.flutter-plugins* +health_app/.packages + +# Android +health_app/android/.gradle/ +health_app/android/app/build/ +health_app/android/local.properties + +# iOS +health_app/ios/Pods/ +health_app/ios/.symlinks/ + +# IDE +.idea/ +*.suo +*.user +*.userosscache +*.sln.docstates +.vs/ +.vscode/ + +# OS +.DS_Store +Thumbs.db diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..6c3197c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,26 @@ +# AI APP — 编码规范 + +## 后端 C# (.NET 10) + +- 主构造函数:`public class Service(DbContext db) { }` +- 静态方法必须标记 `static` +- 集合表达式:`[]` / `[..src]` +- `TryGetValue` 替代 `GetValueOrDefault` +- 空 catch 必须指定异常类型 +- DTO 用 `record` 类型 +- `private static readonly` 缓存可复用对象 +- 本地函数优于 `Func` 赋值 +- file-scoped namespace、global using、target-typed `new()`、`Nullable=enable` +- Minimal API 扩展方法模式:`public static class XxxEndpoints { }` +- AI 请求用 `HttpClient` 直连,不引入第三方 AI SDK +- **文件命名 snake_case**:`auth_service.cs`、`auth_endpoints.cs` + +## 前端 Flutter (Dart) + +-前端用sqlite存储信息,不用shared_preferences +- 用 Riverpod 管理所有状态和页面跳转 +## 运行与测试 + +- 测试时自行启动后端,通过浏览器 DevTools 发送请求验证 +- Flutter 用 `flutter run` 连模拟器/真机 + diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..60ba196 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,22 @@ +# 数据库 +DB_CONNECTION=Host=localhost;Database=health_manager;Username=postgres;Password=postgres123 + +# JWT +JWT_SECRET=your-jwt-secret-min-32-chars +JWT_ISSUER=health-manager +JWT_AUDIENCE=health-manager-app + +# DeepSeek LLM +DEEPSEEK_BASE_URL=https://api.deepseek.com/v1 +DEEPSEEK_API_KEY=sk-your-key-here +DEEPSEEK_MODEL=deepseek-chat + +# 千问 VLM +QWEN_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 +QWEN_API_KEY=sk-your-key-here +QWEN_VISION_MODEL=qwen-vl-max + +# MinIO +MINIO_ENDPOINT=localhost:9000 +MINIO_ACCESS_KEY=minioadmin +MINIO_SECRET_KEY=minioadmin123 diff --git a/backend/HealthManager.slnx b/backend/HealthManager.slnx new file mode 100644 index 0000000..84e5d56 --- /dev/null +++ b/backend/HealthManager.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/backend/src/Health.Application/Health.Application.csproj b/backend/src/Health.Application/Health.Application.csproj new file mode 100644 index 0000000..3590d18 --- /dev/null +++ b/backend/src/Health.Application/Health.Application.csproj @@ -0,0 +1,13 @@ + + + + + + + + net10.0 + enable + enable + + + diff --git a/backend/src/Health.Domain/Entities/Consultation.cs b/backend/src/Health.Domain/Entities/Consultation.cs new file mode 100644 index 0000000..8054948 --- /dev/null +++ b/backend/src/Health.Domain/Entities/Consultation.cs @@ -0,0 +1,53 @@ +using Health.Domain.Enums; + +namespace Health.Domain.Entities; + +/// +/// 问诊会话 +/// +public sealed class Consultation +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public Guid DoctorId { get; set; } + public ConsultationStatus Status { get; set; } + public int Month { get; set; } // 所属月份,用于配额计算 + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime? ClosedAt { get; set; } + + public User User { get; set; } = null!; + public Doctor Doctor { get; set; } = null!; + public ICollection Messages { get; set; } = []; +} + +/// +/// 问诊消息 +/// +public sealed class ConsultationMessage +{ + public Guid Id { get; set; } + public Guid ConsultationId { get; set; } + public ConsultationSenderType SenderType { get; set; } + public string? SenderName { get; set; } + public string Content { get; set; } = string.Empty; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public Consultation Consultation { get; set; } = null!; +} + +/// +/// 医生 +/// +public sealed class Doctor +{ + public Guid Id { get; set; } + public string Name { get; set; } = string.Empty; + public string? Title { get; set; } // 主任医师/副主任医师 + public string? Department { get; set; } // 心血管内科/营养科 + public string? AvatarUrl { get; set; } + public string? Introduction { get; set; } + public bool IsActive { get; set; } = true; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public ICollection Consultations { get; set; } = []; +} diff --git a/backend/src/Health.Domain/Entities/Conversation.cs b/backend/src/Health.Domain/Entities/Conversation.cs new file mode 100644 index 0000000..e3a6270 --- /dev/null +++ b/backend/src/Health.Domain/Entities/Conversation.cs @@ -0,0 +1,39 @@ +using Health.Domain.Enums; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Health.Domain.Entities; + +/// +/// AI 对话会话 +/// +public sealed class Conversation +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public AgentType AgentType { get; set; } + public string? Title { get; set; } + public string? Summary { get; set; } // 侧滑抽屉显示用摘要 + public int MessageCount { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; + public ICollection Messages { get; set; } = []; +} + +/// +/// AI 对话消息 +/// +public sealed class ConversationMessage +{ + public Guid Id { get; set; } + public Guid ConversationId { get; set; } + public MessageRole Role { get; set; } + public string Content { get; set; } = string.Empty; + public string? Intent { get; set; } // health_record / diet / medication / exercise / report / chat + [Column(TypeName = "jsonb")] + public string? MetadataJson { get; set; } // 结构化数据(录入数值、食物列表、卡片数据等) + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public Conversation Conversation { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/DietRecord.cs b/backend/src/Health.Domain/Entities/DietRecord.cs new file mode 100644 index 0000000..631e2df --- /dev/null +++ b/backend/src/Health.Domain/Entities/DietRecord.cs @@ -0,0 +1,39 @@ +using Health.Domain.Enums; + +namespace Health.Domain.Entities; + +/// +/// 饮食记录 +/// +public sealed class DietRecord +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public MealType MealType { get; set; } + public int? TotalCalories { get; set; } + public int? HealthScore { get; set; } // 1-5 星 + public DateOnly RecordedAt { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; + public ICollection FoodItems { get; set; } = []; +} + +/// +/// 饮食记录中的食物条目 +/// +public sealed class DietFoodItem +{ + public Guid Id { get; set; } + public Guid DietRecordId { get; set; } + public string Name { get; set; } = string.Empty; + public string? Portion { get; set; } + public int? Calories { get; set; } + public decimal? ProteinGrams { get; set; } + public decimal? CarbsGrams { get; set; } + public decimal? FatGrams { get; set; } + public string? Warning { get; set; } + public int SortOrder { get; set; } + + public DietRecord DietRecord { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/ExercisePlan.cs b/backend/src/Health.Domain/Entities/ExercisePlan.cs new file mode 100644 index 0000000..595e204 --- /dev/null +++ b/backend/src/Health.Domain/Entities/ExercisePlan.cs @@ -0,0 +1,33 @@ +namespace Health.Domain.Entities; + +/// +/// 运动计划(按周) +/// +public sealed class ExercisePlan +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public DateOnly WeekStartDate { get; set; } // 本周一 + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; + public ICollection Items { get; set; } = []; +} + +/// +/// 运动计划每日条目 +/// +public sealed class ExercisePlanItem +{ + public Guid Id { get; set; } + public Guid PlanId { get; set; } + public int DayOfWeek { get; set; } // 0=周一, 6=周日 + public string ExerciseType { get; set; } = string.Empty; // 散步/慢跑/游泳 + public int DurationMinutes { get; set; } + public bool IsCompleted { get; set; } + public DateTime? CompletedAt { get; set; } + public bool IsRestDay { get; set; } + + public ExercisePlan Plan { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/HealthRecord.cs b/backend/src/Health.Domain/Entities/HealthRecord.cs new file mode 100644 index 0000000..ec627d1 --- /dev/null +++ b/backend/src/Health.Domain/Entities/HealthRecord.cs @@ -0,0 +1,23 @@ +using Health.Domain.Enums; + +namespace Health.Domain.Entities; + +/// +/// 健康数据记录(血压/心率/血糖/血氧/体重) +/// +public sealed class HealthRecord +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public HealthMetricType MetricType { get; set; } + public int? Systolic { get; set; } // 血压收缩压 + public int? Diastolic { get; set; } // 血压舒张压 + public decimal? Value { get; set; } // 通用数值(心率/血糖/血氧/体重) + public string? Unit { get; set; } // 单位 + public HealthRecordSource Source { get; set; } + public bool IsAbnormal { get; set; } + public DateTime RecordedAt { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/Medication.cs b/backend/src/Health.Domain/Entities/Medication.cs new file mode 100644 index 0000000..d3f5fdc --- /dev/null +++ b/backend/src/Health.Domain/Entities/Medication.cs @@ -0,0 +1,41 @@ +using Health.Domain.Enums; + +namespace Health.Domain.Entities; + +/// +/// 用药计划 +/// +public sealed class Medication +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Name { get; set; } = string.Empty; + public string? Dosage { get; set; } + public MedicationFrequency Frequency { get; set; } + public List TimeOfDay { get; set; } = []; // PostgreSQL TIME[] 数组 + public DateOnly? StartDate { get; set; } + public DateOnly? EndDate { get; set; } + public bool IsActive { get; set; } = true; + public MedicationSource Source { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; + public ICollection Logs { get; set; } = []; +} + +/// +/// 用药打卡记录 +/// +public sealed class MedicationLog +{ + public Guid Id { get; set; } + public Guid MedicationId { get; set; } + public Guid UserId { get; set; } + public MedicationLogStatus Status { get; set; } + public TimeOnly ScheduledTime { get; set; } + public DateTime? ConfirmedAt { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public Medication Medication { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/Report.cs b/backend/src/Health.Domain/Entities/Report.cs new file mode 100644 index 0000000..4aacc02 --- /dev/null +++ b/backend/src/Health.Domain/Entities/Report.cs @@ -0,0 +1,26 @@ +using Health.Domain.Enums; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Health.Domain.Entities; + +/// +/// 检查报告 +/// +public sealed class Report +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string FileUrl { get; set; } = string.Empty; + public ReportFileType FileType { get; set; } + public ReportCategory Category { get; set; } + public string? AiSummary { get; set; } // AI 预解读结果 + [Column(TypeName = "jsonb")] + public string? AiIndicators { get; set; } // JSONB: [{name, value, unit, range, status}] + public ReportStatus Status { get; set; } + public string? DoctorComment { get; set; } // 医生审核意见 + public string? DoctorName { get; set; } + public DateTime? ReviewedAt { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/SupportEntities.cs b/backend/src/Health.Domain/Entities/SupportEntities.cs new file mode 100644 index 0000000..e0328f3 --- /dev/null +++ b/backend/src/Health.Domain/Entities/SupportEntities.cs @@ -0,0 +1,99 @@ +using Health.Domain.Enums; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Health.Domain.Entities; + +/// +/// 复查/随访计划 +/// +public sealed class FollowUp +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Title { get; set; } = string.Empty; + public string? DoctorName { get; set; } + public string? Department { get; set; } + public DateTime ScheduledAt { get; set; } + public string? Notes { get; set; } + public FollowUpStatus Status { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} + +/// +/// 健康档案 +/// +public sealed class HealthArchive +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string? Diagnosis { get; set; } // 主要诊断 + public string? SurgeryType { get; set; } // 手术类型 + public DateOnly? SurgeryDate { get; set; } // 手术日期 + public List Allergies { get; set; } = []; // 过敏信息 + public List DietRestrictions { get; set; } = []; // 饮食限制 + public List ChronicDiseases { get; set; } = []; // 慢病史 + public string? FamilyHistory { get; set; } // 家族病史 + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} + +/// +/// 刷新令牌 +/// +public sealed class RefreshToken +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Token { get; set; } = string.Empty; + public DateTime ExpiresAt { get; set; } + public bool IsRevoked { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} + +/// +/// 短信验证码 +/// +public sealed class VerificationCode +{ + public Guid Id { get; set; } + public string Phone { get; set; } = string.Empty; + public string Code { get; set; } = string.Empty; + public DateTime ExpiresAt { get; set; } + public bool IsUsed { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} + +/// +/// 通知偏好 +/// +public sealed class NotificationPreference +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public bool MedicationReminder { get; set; } = true; + public bool FollowUpReminder { get; set; } = true; + public bool DoctorReply { get; set; } = true; + public bool AbnormalAlert { get; set; } = true; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} + +/// +/// 设备推送 token +/// +public sealed class DeviceToken +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public string Platform { get; set; } = string.Empty; // ios / android + public string PushToken { get; set; } = string.Empty; + public bool IsActive { get; set; } = true; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + public User User { get; set; } = null!; +} diff --git a/backend/src/Health.Domain/Entities/User.cs b/backend/src/Health.Domain/Entities/User.cs new file mode 100644 index 0000000..dcfa7c1 --- /dev/null +++ b/backend/src/Health.Domain/Entities/User.cs @@ -0,0 +1,29 @@ +namespace Health.Domain.Entities; + +/// +/// 用户(患者) +/// +public sealed class User +{ + public Guid Id { get; set; } + public string Phone { get; set; } = string.Empty; + public string? Name { get; set; } + public string? Gender { get; set; } + public DateOnly? BirthDate { get; set; } + public string? AvatarUrl { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime UpdatedAt { get; set; } = DateTime.UtcNow; + + // 导航属性 + public ICollection HealthRecords { get; set; } = []; + public ICollection Medications { get; set; } = []; + public ICollection DietRecords { get; set; } = []; + public ICollection ExercisePlans { get; set; } = []; + public ICollection Reports { get; set; } = []; + public ICollection Conversations { get; set; } = []; + public ICollection Consultations { get; set; } = []; + public ICollection FollowUps { get; set; } = []; + public ICollection DeviceTokens { get; set; } = []; + public HealthArchive? HealthArchive { get; set; } + public NotificationPreference? NotificationPreference { get; set; } +} diff --git a/backend/src/Health.Domain/Enums/HealthEnums.cs b/backend/src/Health.Domain/Enums/HealthEnums.cs new file mode 100644 index 0000000..7497b3b --- /dev/null +++ b/backend/src/Health.Domain/Enums/HealthEnums.cs @@ -0,0 +1,152 @@ +namespace Health.Domain.Enums; + +/// +/// 健康指标类型 +/// +public enum HealthMetricType +{ + BloodPressure, // 血压(收缩压+舒张压) + HeartRate, // 心率 + Glucose, // 血糖 + SpO2, // 血氧 + Weight // 体重 +} + +/// +/// 数据录入来源 +/// +public enum HealthRecordSource +{ + AiEntry, // AI 对话录入 + DeviceSync, // 设备自动同步 + Manual // 手动录入 +} + +/// +/// 餐次类型 +/// +public enum MealType +{ + Breakfast, // 早餐 + Lunch, // 午餐 + Dinner, // 晚餐 + Snack // 加餐 +} + +/// +/// 用药计划来源 +/// +public enum MedicationSource +{ + Prescription, // 处方 + AiEntry, // AI 对话 + Manual // 手动 +} + +/// +/// 服药打卡状态 +/// +public enum MedicationLogStatus +{ + Taken, // 已服用 + Missed, // 漏服 + Skipped // 跳过 +} + +/// +/// 用药频次 +/// +public enum MedicationFrequency +{ + Daily, // 每天一次 + TwiceDaily, // 每天两次 + ThreeTimesDaily, // 每天三次 + Weekly, // 每周 + AsNeeded // 必要时 +} + +/// +/// 报告状态 +/// +public enum ReportStatus +{ + PendingDoctor, // 待医生确认 + DoctorReviewed // 医生已确认 +} + +/// +/// 报告文件类型 +/// +public enum ReportFileType +{ + Image, // 图片 + Pdf // PDF +} + +/// +/// 报告类别 +/// +public enum ReportCategory +{ + BloodTest, // 血常规 + Biochemistry, // 生化全项 + Ecg, // 心电图 + Ultrasound, // 彩超 + Discharge, // 出院小结 + Other // 其他 +} + +/// +/// 问诊会话状态 +/// +public enum ConsultationStatus +{ + AiTalking, // AI 分身对话中 + WaitingDoctor, // 等待医生 + DoctorReplied, // 医生已回复 + Closed // 已结束 +} + +/// +/// 问诊消息发送方类型 +/// +public enum ConsultationSenderType +{ + User, // 患者 + Doctor, // 医生 + Ai // AI 分身 +} + +/// +/// 复查随访状态 +/// +public enum FollowUpStatus +{ + Upcoming, // 即将到来 + Completed, // 已完成 + Cancelled // 已取消 +} + +/// +/// AI Agent 类型 +/// +public enum AgentType +{ + Default, // 默认对话 + Consultation, // AI 问诊 + Health, // 记数据 + Diet, // 拍饮食 + Medication, // 药管家 + Report, // 看报告 + Exercise // 运动计划 +} + +/// +/// 对话消息角色 +/// +public enum MessageRole +{ + User, // 用户 + Assistant, // AI + Tool // 工具返回 +} diff --git a/backend/src/Health.Domain/Health.Domain.csproj b/backend/src/Health.Domain/Health.Domain.csproj new file mode 100644 index 0000000..b760144 --- /dev/null +++ b/backend/src/Health.Domain/Health.Domain.csproj @@ -0,0 +1,9 @@ + + + + net10.0 + enable + enable + + + diff --git a/backend/src/Health.Infrastructure/AI/AiClients.cs b/backend/src/Health.Infrastructure/AI/AiClients.cs new file mode 100644 index 0000000..0180f3d --- /dev/null +++ b/backend/src/Health.Infrastructure/AI/AiClients.cs @@ -0,0 +1,152 @@ +using Microsoft.Extensions.Configuration; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; + +namespace Health.Infrastructure.AI; + +/// +/// DeepSeek LLM 客户端(对话 + Tool Calling) +/// +public sealed class DeepSeekClient +{ + private readonly HttpClient _http; + private readonly string _model; + private readonly JsonSerializerOptions _jsonOptions; + + public DeepSeekClient(HttpClient http, IConfiguration config) + { + _http = http; + _model = config["DEEPSEEK_MODEL"] ?? "deepseek-chat"; + _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + PropertyNameCaseInsensitive = true + }; + } + + /// + /// 流式 Chat Completions + /// + public async IAsyncEnumerable ChatStreamAsync( + List messages, + List? tools = null, + int maxTokens = 2048, + float temperature = 0.7f, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default) + { + var request = new ChatCompletionRequest + { + Model = _model, Messages = messages, Stream = true, + MaxTokens = maxTokens, Temperature = temperature, Tools = tools, + }; + if (tools?.Count > 0) request.ToolChoice = "auto"; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var httpRequest = new HttpRequestMessage(HttpMethod.Post, "chat/completions") { Content = content }; + httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); + + using var response = await _http.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, ct); + response.EnsureSuccessStatusCode(); + + using var stream = await response.Content.ReadAsStreamAsync(ct); + using var reader = new StreamReader(stream); + + string? line; + while ((line = await reader.ReadLineAsync(ct)) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + if (!line.StartsWith("data: ")) continue; + var data = line["data: ".Length..]; + if (data == "[DONE]") break; + yield return data; + } + } + + /// + /// 非流式 Chat Completions(用于 Tool Calling) + /// + public async Task ChatAsync( + List messages, + List? tools = null, + int maxTokens = 2048, + float temperature = 0.7f, + CancellationToken ct = default) + { + var request = new ChatCompletionRequest + { + Model = _model, Messages = messages, Stream = false, + MaxTokens = maxTokens, Temperature = temperature, Tools = tools, + }; + if (tools?.Count > 0) request.ToolChoice = "auto"; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _http.PostAsync("chat/completions", content, ct); + response.EnsureSuccessStatusCode(); + + var body = await response.Content.ReadAsStringAsync(ct); + return JsonSerializer.Deserialize(body, _jsonOptions)!; + } +} + +/// +/// 千问 VL 视觉客户端(食物识别 + 报告解读) +/// +public sealed class QwenVisionClient +{ + private readonly HttpClient _http; + private readonly string _model; + private readonly JsonSerializerOptions _jsonOptions; + + public QwenVisionClient(HttpClient http, IConfiguration config) + { + _http = http; + _model = config["QWEN_VISION_MODEL"] ?? "qwen-vl-max"; + _jsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + PropertyNameCaseInsensitive = true + }; + } + + public async Task VisionAsync( + string systemPrompt, + List imageUrls, + string? userText = null, + int maxTokens = 2048, + CancellationToken ct = default) + { + var messages = new List(); + if (!string.IsNullOrEmpty(systemPrompt)) + messages.Add(new ChatMessage { Role = "system", Content = systemPrompt }); + + var contentParts = new List(); + foreach (var url in imageUrls) + contentParts.Add(new { type = "image_url", image_url = new { url } }); + if (!string.IsNullOrEmpty(userText)) + contentParts.Add(new { type = "text", text = userText }); + + var userMessage = new ChatMessage + { + Role = "user", + Content = JsonSerializer.Serialize(contentParts, _jsonOptions) + }; + messages.Add(userMessage); + + var request = new ChatCompletionRequest + { + Model = _model, Messages = messages, MaxTokens = maxTokens, Stream = false, + }; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + var response = await _http.PostAsync("chat/completions", content, ct); + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(ct); + return JsonSerializer.Deserialize(body, _jsonOptions)!; + } +} diff --git a/backend/src/Health.Infrastructure/AI/OpenAiCompatibleClient.cs b/backend/src/Health.Infrastructure/AI/OpenAiCompatibleClient.cs new file mode 100644 index 0000000..dd8f479 --- /dev/null +++ b/backend/src/Health.Infrastructure/AI/OpenAiCompatibleClient.cs @@ -0,0 +1,235 @@ +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; + +namespace Health.Infrastructure.AI; + +/// +/// OpenAI 兼容协议 HTTP 客户端,统一调用 DeepSeek / 千问 VL +/// +public sealed class OpenAiCompatibleClient +{ + private readonly HttpClient _http; + private readonly string _model; + private readonly JsonSerializerOptions _jsonOptions; + + public OpenAiCompatibleClient(string baseUrl, string apiKey, string model) + { + _http = new HttpClient + { + BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/"), + Timeout = TimeSpan.FromSeconds(60) + }; + _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); + _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + _model = model; + _jsonOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + PropertyNameCaseInsensitive = true + }; + } + + /// + /// 流式 Chat Completions(SSE) + /// + public async IAsyncEnumerable ChatStreamAsync( + List messages, + List? tools = null, + int maxTokens = 2048, + float temperature = 0.7f) + { + var request = new ChatCompletionRequest + { + Model = _model, + Messages = messages, + Stream = true, + MaxTokens = maxTokens, + Temperature = temperature, + Tools = tools, + }; + + if (tools?.Count > 0) + request.ToolChoice = "auto"; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var httpRequest = new HttpRequestMessage(HttpMethod.Post, "chat/completions") + { + Content = content + }; + httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); + + var response = await _http.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead); + response.EnsureSuccessStatusCode(); + + using var stream = await response.Content.ReadAsStreamAsync(); + using var reader = new StreamReader(stream); + + string? line; + while ((line = await reader.ReadLineAsync()) != null) + { + if (string.IsNullOrWhiteSpace(line)) continue; + if (!line.StartsWith("data: ")) continue; + + var data = line["data: ".Length..]; + if (data == "[DONE]") break; + + yield return data; + } + } + + /// + /// 非流式 Chat Completions + /// + public async Task ChatAsync( + List messages, + List? tools = null, + int maxTokens = 2048, + float temperature = 0.7f) + { + var request = new ChatCompletionRequest + { + Model = _model, + Messages = messages, + Stream = false, + MaxTokens = maxTokens, + Temperature = temperature, + Tools = tools, + }; + + if (tools?.Count > 0) + request.ToolChoice = "auto"; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + + var response = await _http.PostAsync("chat/completions", content); + response.EnsureSuccessStatusCode(); + + var body = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(body, _jsonOptions)!; + } + + /// + /// Vision 图片理解(非流式) + /// + public async Task VisionAsync( + string systemPrompt, + List imageUrls, + string? userText = null, + int maxTokens = 2048) + { + var messages = new List(); + + if (!string.IsNullOrEmpty(systemPrompt)) + messages.Add(new ChatMessage { Role = "system", Content = systemPrompt }); + + // 构建多模态消息内容 + var contentParts = new List(); + foreach (var url in imageUrls) + contentParts.Add(new { type = "image_url", image_url = new { url } }); + if (!string.IsNullOrEmpty(userText)) + contentParts.Add(new { type = "text", text = userText }); + + var userMessage = new ChatMessage + { + Role = "user", + Content = JsonSerializer.Serialize(contentParts, _jsonOptions) + }; + + messages.Add(userMessage); + + var request = new ChatCompletionRequest + { + Model = _model, + Messages = messages, + MaxTokens = maxTokens, + Stream = false, + }; + + var json = JsonSerializer.Serialize(request, _jsonOptions); + var content = new StringContent(json, Encoding.UTF8, "application/json"); + var response = await _http.PostAsync("chat/completions", content); + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(body, _jsonOptions)!; + } +} + +#region 请求/响应模型 + +public sealed class ChatCompletionRequest +{ + public string Model { get; set; } = string.Empty; + public List Messages { get; set; } = []; + public bool Stream { get; set; } + public int MaxTokens { get; set; } = 2048; + public float Temperature { get; set; } = 0.7f; + public List? Tools { get; set; } + public string? ToolChoice { get; set; } +} + +public sealed class ChatMessage +{ + public string Role { get; set; } = string.Empty; + public string Content { get; set; } = string.Empty; + public string? ToolCallId { get; set; } + public List? ToolCalls { get; set; } +} + +public sealed class ToolDefinition +{ + public string Type { get; set; } = "function"; + public ToolFunction Function { get; set; } = new(); +} + +public sealed class ToolFunction +{ + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public object Parameters { get; set; } = new(); +} + +public sealed class ToolCall +{ + public string Id { get; set; } = string.Empty; + public string Type { get; set; } = "function"; + public ToolCallFunction Function { get; set; } = new(); +} + +public sealed class ToolCallFunction +{ + public string Name { get; set; } = string.Empty; + public string Arguments { get; set; } = string.Empty; +} + +public sealed class ChatCompletionResponse +{ + public string Id { get; set; } = string.Empty; + public List Choices { get; set; } = []; +} + +public sealed class Choice +{ + public int Index { get; set; } + public ResponseMessage? Message { get; set; } + public ResponseDelta? Delta { get; set; } + public string? FinishReason { get; set; } +} + +public sealed class ResponseMessage +{ + public string Role { get; set; } = string.Empty; + public string? Content { get; set; } + public List? ToolCalls { get; set; } +} + +public sealed class ResponseDelta +{ + public string? Content { get; set; } + public string? Role { get; set; } +} + +#endregion diff --git a/backend/src/Health.Infrastructure/AI/PromptManager.cs b/backend/src/Health.Infrastructure/AI/PromptManager.cs new file mode 100644 index 0000000..cf27012 --- /dev/null +++ b/backend/src/Health.Infrastructure/AI/PromptManager.cs @@ -0,0 +1,116 @@ +using Health.Domain.Enums; + +namespace Health.Infrastructure.AI; + +/// +/// System Prompt 模板管理 +/// +public sealed class PromptManager +{ + /// + /// 获取指定 Agent 的 System Prompt + /// + public string GetSystemPrompt(AgentType agentType) => agentType switch + { + AgentType.Default => DefaultPrompt, + AgentType.Consultation => ConsultationPrompt, + AgentType.Health => HealthDataPrompt, + AgentType.Diet => DietPrompt, + AgentType.Medication => MedicationPrompt, + AgentType.Report => ReportPrompt, + AgentType.Exercise => ExercisePrompt, + _ => DefaultPrompt + }; + + private const string DefaultPrompt = """ + 你是一个心脏术后康复患者的私人 AI 健康管家,名叫"阿福"。 + 语气温暖、专业、像朋友一样关怀患者。 + + 职责: + 1. 理解用户的健康需求,解析健康数据 + 2. 主动查看患者近期数据,发现异常时提醒 + 3. 回答健康知识问题 + 4. 每次回复末尾,如有需要提醒的事项,简短温馨地提醒一句 + + 规则: + - 不要提供超出你能力范围的医疗建议 + - 遇到紧急症状(剧烈胸痛、呼吸困难)立即建议就医 + - 饮食/运动建议要结合患者档案中的疾病和限制 + """; + + private const string ConsultationPrompt = """ + 你是一个心血管内科医生助手,负责对心脏术后患者进行多轮问诊。 + + 规则: + 1. 每次只问一个问题,不要一次问多个 + 2. 给出 2-3 个快捷选项让患者点击 + 3. 问诊步骤:先问感受 → 持续时间 → 伴随症状 → 近期用药 → 给出初步分析 + 4. 遇到以下情况建议立即就医:剧烈胸痛、呼吸困难、心悸 + 5. 遇到以下情况建议转医生:血压持续>160/100、心率>120或<50 + 6. 所有分析末尾标注"以上为AI分析,具体请咨询医生" + 7. 问诊结束给出结构化小结 + """; + + private const string HealthDataPrompt = """ + 你是一个健康数据录入助手。 + + 规则: + 1. 解析用户消息中的指标和数值(血压/心率/血糖/血氧/体重) + 2. 指标明确+数值明确→直接录入 + 3. 数值明确但指标模糊(如只说"120")→追问是"收缩压还是血糖?" + 4. 时间模糊→取当前时间,在确认卡片中告知用户 + 5. 数值超出正常范围→附带异常提醒 + 6. 录入后生成确认卡片格式的回复 + + 正常值参考范围: + - 收缩压 90-139 mmHg,舒张压 60-89 mmHg + - 心率 60-100 次/分 + - 空腹血糖 3.9-6.1 mmol/L + - 血氧 95-100% + """; + + private const string DietPrompt = """ + 你是一个营养分析专家,专门为心脏术后患者提供饮食指导。 + + 规则: + 1. 收到VLM食物识别结果后,结合患者档案进行综合分析 + 2. 总热量汇总 + 3. 逐项判断"能不能吃"(基于疾病诊断/过敏/饮食限制/近期指标) + 4. 给出 1-5 星健康评分 + 5. 单项警告 + 整体饮食建议 + 6. 追问餐次归属(早餐/午餐/晚餐/加餐) + """; + + private const string MedicationPrompt = """ + 你是一个用药管理专家。 + + 规则: + 1. 解析用户口中的药品信息(药名/剂量/频次/时间) + 2. "早饭后"等模糊时间→追问具体几点 + 3. 解析完成后展示确认卡片 + 4. 处方拍照→提取药品信息→生成用药计划→让用户确认 + 5. 回答用药相关疑问 + """; + + private const string ReportPrompt = """ + 你是一个医学报告解读专家。 + + 规则: + 1. 收到报告图片后,提取所有指标及其数值 + 2. 标注异常指标(偏高/偏低/正常) + 3. 给出初步分析 + 4. 所有内容标注"AI预解读,待医生确认" + 5. 图像类报告(彩超/CT)注明"需医生人工审阅" + """; + + private const string ExercisePrompt = """ + 你是一个运动康复教练,专门为心脏术后患者制定运动计划。 + + 规则: + 1. 帮助用户设定每周运动计划(类型/时长/天数) + 2. 以周为单位,每天指定运动类型和时长 + 3. 推荐适合心脏康复的运动:散步、慢跑、太极、游泳等 + 4. 运动强度要循序渐进 + 5. 避免剧烈运动 + """; +} diff --git a/backend/src/Health.Infrastructure/Data/AppDbContext.cs b/backend/src/Health.Infrastructure/Data/AppDbContext.cs new file mode 100644 index 0000000..fa93333 --- /dev/null +++ b/backend/src/Health.Infrastructure/Data/AppDbContext.cs @@ -0,0 +1,136 @@ +using Health.Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Health.Infrastructure.Data; + +/// +/// 应用程序数据库上下文 +/// +public sealed class AppDbContext : DbContext +{ + public AppDbContext(DbContextOptions options) : base(options) { } + + // 核心业务表 + public DbSet Users => Set(); + public DbSet HealthRecords => Set(); + public DbSet Medications => Set(); + public DbSet MedicationLogs => Set(); + public DbSet DietRecords => Set(); + public DbSet DietFoodItems => Set(); + public DbSet ExercisePlans => Set(); + public DbSet ExercisePlanItems => Set(); + public DbSet Reports => Set(); + public DbSet Conversations => Set(); + public DbSet ConversationMessages => Set(); + public DbSet Consultations => Set(); + public DbSet ConsultationMessages => Set(); + public DbSet Doctors => Set(); + public DbSet FollowUps => Set(); + public DbSet HealthArchives => Set(); + + // 支撑表 + public DbSet RefreshTokens => Set(); + public DbSet VerificationCodes => Set(); + public DbSet NotificationPreferences => Set(); + public DbSet DeviceTokens => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + // ---- User ---- + builder.Entity(e => + { + e.HasIndex(u => u.Phone).IsUnique(); + }); + + // ---- HealthRecord ---- + builder.Entity(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(); + e.Property(r => r.Source).HasConversion(); + }); + + // ---- Medication ---- + builder.Entity(e => + { + e.HasIndex(m => new { m.UserId, m.IsActive }); + e.Property(m => m.Frequency).HasConversion(); + e.Property(m => m.Source).HasConversion(); + e.Property(m => m.TimeOfDay).HasColumnType("time[]"); + }); + + builder.Entity(e => + { + e.HasIndex(l => new { l.MedicationId, l.CreatedAt }).IsDescending(false, true); + e.Property(l => l.Status).HasConversion(); + }); + + // ---- Diet ---- + builder.Entity(e => + { + e.HasIndex(d => new { d.UserId, d.RecordedAt }).IsDescending(false, true); + e.Property(d => d.MealType).HasConversion(); + }); + + // ---- ExercisePlan ---- + builder.Entity(e => + { + e.HasIndex(p => new { p.UserId, p.WeekStartDate }).IsDescending(false, true); + }); + + // ---- Report ---- + builder.Entity(e => + { + e.Property(r => r.FileType).HasConversion(); + e.Property(r => r.Category).HasConversion(); + e.Property(r => r.Status).HasConversion(); + }); + + // ---- Conversation ---- + builder.Entity(e => + { + e.HasIndex(c => new { c.UserId, c.UpdatedAt }).IsDescending(false, true); + e.Property(c => c.AgentType).HasConversion(); + }); + + builder.Entity(e => + { + e.HasIndex(m => new { m.ConversationId, m.CreatedAt }); + e.Property(m => m.Role).HasConversion(); + }); + + // ---- Consultation ---- + builder.Entity(e => + { + e.Property(c => c.Status).HasConversion(); + }); + + builder.Entity(e => + { + e.HasIndex(m => new { m.ConsultationId, m.CreatedAt }).IsDescending(false, true); + e.Property(m => m.SenderType).HasConversion(); + }); + + // ---- VerificationCode ---- + builder.Entity(e => + { + e.HasIndex(v => new { v.Phone, v.CreatedAt }).IsDescending(false, true); + }); + + // ---- NotificationPreference ---- + builder.Entity(e => + { + e.HasIndex(n => n.UserId).IsUnique(); + }); + + // ---- HealthArchive ---- + builder.Entity(e => + { + e.HasIndex(a => a.UserId).IsUnique(); + }); + } +} diff --git a/backend/src/Health.Infrastructure/Data/DataSeeder.cs b/backend/src/Health.Infrastructure/Data/DataSeeder.cs new file mode 100644 index 0000000..2a07977 --- /dev/null +++ b/backend/src/Health.Infrastructure/Data/DataSeeder.cs @@ -0,0 +1,47 @@ +using Health.Domain.Entities; + +namespace Health.Infrastructure.Data; + +/// +/// 数据库种子数据 +/// +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(); + } + } +} diff --git a/backend/src/Health.Infrastructure/Data/DevDataSeeder.cs b/backend/src/Health.Infrastructure/Data/DevDataSeeder.cs new file mode 100644 index 0000000..3ffb16f --- /dev/null +++ b/backend/src/Health.Infrastructure/Data/DevDataSeeder.cs @@ -0,0 +1,144 @@ +using Health.Domain.Entities; +using Health.Domain.Enums; +using Microsoft.Extensions.Configuration; + +namespace Health.Infrastructure.Data; + +/// +/// 开发环境测试数据填充。生产环境不要调用! +/// 开关:DEVDATA_ENABLED=true 才会执行 +/// +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}"); + } +} diff --git a/backend/src/Health.Infrastructure/Health.Infrastructure.csproj b/backend/src/Health.Infrastructure/Health.Infrastructure.csproj new file mode 100644 index 0000000..508b7dc --- /dev/null +++ b/backend/src/Health.Infrastructure/Health.Infrastructure.csproj @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + net10.0 + enable + enable + + + diff --git a/backend/src/Health.Infrastructure/Services/JwtProvider.cs b/backend/src/Health.Infrastructure/Services/JwtProvider.cs new file mode 100644 index 0000000..3896e3f --- /dev/null +++ b/backend/src/Health.Infrastructure/Services/JwtProvider.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; + +namespace Health.Infrastructure.Services; + +/// +/// JWT Token 生成与验证服务 +/// +public sealed class JwtProvider +{ + private readonly string _secret; + private readonly string _issuer; + private readonly string _audience; + + public JwtProvider(IConfiguration configuration) + { + _secret = configuration["JWT_SECRET"] ?? "dev-secret-key-change-in-production-min-32-chars!!"; + _issuer = configuration["JWT_ISSUER"] ?? "health-manager"; + _audience = configuration["JWT_AUDIENCE"] ?? "health-manager-app"; + } + + /// + /// 生成 access_token(30 分钟有效) + /// + public string GenerateAccessToken(Guid userId, string phone) + { + var claims = new[] + { + new Claim(ClaimTypes.NameIdentifier, userId.ToString()), + new Claim(ClaimTypes.MobilePhone, phone), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + }; + + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret)); + var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: _issuer, + audience: _audience, + claims: claims, + expires: DateTime.UtcNow.AddMinutes(30), + signingCredentials: credentials + ); + + return new JwtSecurityTokenHandler().WriteToken(token); + } + + /// + /// 生成 refresh_token(30 天有效) + /// + public string GenerateRefreshToken() + { + var randomBytes = new byte[64]; + using var rng = RandomNumberGenerator.Create(); + rng.GetBytes(randomBytes); + return Convert.ToBase64String(randomBytes); + } + + /// + /// 验证 JWT token 并返回 ClaimsPrincipal + /// + public TokenValidationParameters GetValidationParameters() + { + return new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = _issuer, + ValidAudience = _audience, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret)), + ClockSkew = TimeSpan.Zero + }; + } +} diff --git a/backend/src/Health.Infrastructure/Services/SmsService.cs b/backend/src/Health.Infrastructure/Services/SmsService.cs new file mode 100644 index 0000000..fa1c2d0 --- /dev/null +++ b/backend/src/Health.Infrastructure/Services/SmsService.cs @@ -0,0 +1,26 @@ +namespace Health.Infrastructure.Services; + +/// +/// 短信验证码服务(开发阶段直接返回成功) +/// +public sealed class SmsService +{ + /// + /// 发送验证码(开发阶段不做真实发送) + /// + public Task SendCodeAsync(string phone, string code) + { + // 开发阶段:直接在控制台输出,不做真实发送 + Console.WriteLine($"[SMS DEV] 发送验证码到 {phone}: {code}"); + return Task.FromResult(true); + } + + /// + /// 生成 6 位随机数字验证码 + /// + public string GenerateCode() + { + // Next(min, max) 的 max 是 exclusive 的,所以用 1000000 保证 6 位 + return Random.Shared.Next(100000, 1000000).ToString(); + } +} diff --git a/backend/src/Health.WebApi/BackgroundServices/CleanupService.cs b/backend/src/Health.WebApi/BackgroundServices/CleanupService.cs new file mode 100644 index 0000000..783b44b --- /dev/null +++ b/backend/src/Health.WebApi/BackgroundServices/CleanupService.cs @@ -0,0 +1,61 @@ +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.WebApi.BackgroundServices; + +/// +/// 数据清理后台服务(每小时检查一次) +/// +public sealed class CleanupService : BackgroundService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + + public CleanupService(IServiceScopeFactory scopeFactory, ILogger logger) + { + _scopeFactory = scopeFactory; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // 清理 30 天前的对话记录 + var cutoff = DateTime.UtcNow.AddDays(-30); + var oldConversations = await db.Conversations + .Where(c => c.CreatedAt < cutoff) + .ToListAsync(stoppingToken); + + if (oldConversations.Count > 0) + { + db.Conversations.RemoveRange(oldConversations); + await db.SaveChangesAsync(stoppingToken); + _logger.LogInformation("清理 {Count} 条过期对话", oldConversations.Count); + } + + // 清理过期验证码 + var expiredCodes = await db.VerificationCodes + .Where(v => v.ExpiresAt < DateTime.UtcNow) + .ToListAsync(stoppingToken); + + if (expiredCodes.Count > 0) + { + db.VerificationCodes.RemoveRange(expiredCodes); + await db.SaveChangesAsync(stoppingToken); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "数据清理异常"); + } + + await Task.Delay(TimeSpan.FromHours(1), stoppingToken); + } + } +} diff --git a/backend/src/Health.WebApi/BackgroundServices/MedicationReminderService.cs b/backend/src/Health.WebApi/BackgroundServices/MedicationReminderService.cs new file mode 100644 index 0000000..6db9727 --- /dev/null +++ b/backend/src/Health.WebApi/BackgroundServices/MedicationReminderService.cs @@ -0,0 +1,72 @@ +using Health.Domain.Entities; +using Health.Domain.Enums; +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.WebApi.BackgroundServices; + +/// +/// 用药提醒定时扫描服务(每分钟检查一次) +/// +public sealed class MedicationReminderService : BackgroundService +{ + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + + public MedicationReminderService(IServiceScopeFactory scopeFactory, ILogger logger) + { + _scopeFactory = scopeFactory; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + _logger.LogInformation("用药提醒服务已启动"); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + await ProcessReminders(stoppingToken); + } + catch (Exception ex) + { + _logger.LogError(ex, "用药提醒扫描异常"); + } + + await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); + } + } + + private async Task ProcessReminders(CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + // 使用北京时间(UTC+8) + var beijingNow = DateTime.UtcNow.AddHours(8); + var beijingTime = TimeOnly.FromDateTime(beijingNow); + var today = DateOnly.FromDateTime(beijingNow); + + // 查询:启用的用药计划 AND 服药时间在当前时间前后5分钟窗口内(防止服务重启错过提醒) + var windowStart = beijingTime.AddMinutes(-5); + var medications = await db.Medications + .Where(m => m.IsActive) + .Where(m => m.TimeOfDay.Any(t => t >= windowStart && t <= beijingTime)) + .ToListAsync(ct); + + foreach (var med in medications) + { + // 检查今天是否已打卡 + var alreadyLogged = await db.MedicationLogs + .AnyAsync(l => l.MedicationId == med.Id + && l.CreatedAt.Date == beijingNow.Date + && l.Status == MedicationLogStatus.Taken, ct); + + if (alreadyLogged) continue; + + // TODO: 调用极光推送发送用药提醒 + _logger.LogInformation("用药提醒: 用户 {UserId} 药品 {Name} {Dosage} 时间 {Time}", + med.UserId, med.Name, med.Dosage, beijingTime); + } + } +} diff --git a/backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs b/backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs new file mode 100644 index 0000000..b8a4f1d --- /dev/null +++ b/backend/src/Health.WebApi/Endpoints/AiChatEndpoints.cs @@ -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; + +/// +/// AI 对话 SSE 端点——支持 7 个 Agent +/// +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, 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 + { + 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()) + { + 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(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(); + 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 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 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 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 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(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 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 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 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 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 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 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 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" } } } + } + }; +} + +/// AI 对话请求 +public sealed record ChatRequest(string Message, string? ConversationId); diff --git a/backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs b/backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs new file mode 100644 index 0000000..b81684f --- /dev/null +++ b/backend/src/Health.WebApi/Endpoints/AuthEndpoints.cs @@ -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; + +/// +/// 认证相关 API 端点 +/// +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); diff --git a/backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs b/backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs new file mode 100644 index 0000000..ca52c7e --- /dev/null +++ b/backend/src/Health.WebApi/Endpoints/HealthEndpoints.cs @@ -0,0 +1,132 @@ +using Health.Domain.Entities; +using Health.Domain.Enums; +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.WebApi.Endpoints; + +/// +/// 健康数据 API 端点 +/// +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(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(); + + 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(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); diff --git a/backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs b/backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs new file mode 100644 index 0000000..70fcb6b --- /dev/null +++ b/backend/src/Health.WebApi/Endpoints/RemainingEndpoints.cs @@ -0,0 +1,266 @@ +using Health.Domain.Entities; +using Health.Domain.Enums; +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.WebApi.Endpoints; + +/// +/// 饮食、用药、报告、问诊、运动、文件端点 +/// +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, 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(); + 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? 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? 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? Items); +public sealed record ExerciseItemDto(int DayOfWeek, string ExerciseType, int DurationMinutes, bool IsRestDay); diff --git a/backend/src/Health.WebApi/Endpoints/UserEndpoints.cs b/backend/src/Health.WebApi/Endpoints/UserEndpoints.cs new file mode 100644 index 0000000..24ac71b --- /dev/null +++ b/backend/src/Health.WebApi/Endpoints/UserEndpoints.cs @@ -0,0 +1,89 @@ +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.WebApi.Endpoints; + +/// +/// 用户与健康档案 API 端点 +/// +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? Allergies, List? DietRestrictions, + List? ChronicDiseases, string? FamilyHistory); diff --git a/backend/src/Health.WebApi/Health.WebApi.csproj b/backend/src/Health.WebApi/Health.WebApi.csproj new file mode 100644 index 0000000..d5e873c --- /dev/null +++ b/backend/src/Health.WebApi/Health.WebApi.csproj @@ -0,0 +1,20 @@ + + + + net10.0 + enable + enable + + + + + + + + + + + + + + diff --git a/backend/src/Health.WebApi/Health.WebApi.http b/backend/src/Health.WebApi/Health.WebApi.http new file mode 100644 index 0000000..ab0c6e7 --- /dev/null +++ b/backend/src/Health.WebApi/Health.WebApi.http @@ -0,0 +1,6 @@ +@Health.WebApi_HostAddress = http://localhost:5277 + +GET {{Health.WebApi_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/backend/src/Health.WebApi/Middleware/ExceptionMiddleware.cs b/backend/src/Health.WebApi/Middleware/ExceptionMiddleware.cs new file mode 100644 index 0000000..59aa416 --- /dev/null +++ b/backend/src/Health.WebApi/Middleware/ExceptionMiddleware.cs @@ -0,0 +1,42 @@ +using System.Net; +using System.Text.Json; + +namespace Health.WebApi.Middleware; + +/// +/// 全局异常处理中间件——统一返回 {code, data, message} 格式 +/// +public sealed class ExceptionMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + public ExceptionMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = logger; + } + + public async Task InvokeAsync(HttpContext context) + { + try + { + await _next(context); + } + catch (Exception ex) + { + // 生产环境不暴露内部异常详情 + _logger.LogError(ex, "未处理的异常: {Path}", context.Request.Path); + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + context.Response.ContentType = "application/json"; + + var result = new + { + code = 50000, + data = (object?)null, + message = "服务器内部错误,请稍后重试" + }; + await context.Response.WriteAsync(JsonSerializer.Serialize(result)); + } + } +} diff --git a/backend/src/Health.WebApi/Program.cs b/backend/src/Health.WebApi/Program.cs new file mode 100644 index 0000000..c3dc020 --- /dev/null +++ b/backend/src/Health.WebApi/Program.cs @@ -0,0 +1,124 @@ +using System.Text; +using Health.Infrastructure.AI; +using Health.Infrastructure.Data; +using Health.Infrastructure.Services; +using Health.WebApi.BackgroundServices; +using Health.WebApi.Endpoints; +using Health.WebApi.Middleware; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; + +// 加载 .env 文件(开发环境) +var envPath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", ".env"); +if (File.Exists(envPath)) +{ + foreach (var line in File.ReadAllLines(envPath)) + { + var trimmed = line.Trim(); + if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith('#')) continue; + var eqIdx = trimmed.IndexOf('='); + if (eqIdx <= 0) continue; + var key = trimmed[..eqIdx].Trim(); + var value = trimmed[(eqIdx + 1)..].Trim(); + Environment.SetEnvironmentVariable(key, value); + } +} + +var builder = WebApplication.CreateBuilder(args); + +// ---- 数据库 ---- +builder.Services.AddDbContext(options => + options.UseNpgsql(builder.Configuration.GetConnectionString("Default") ?? builder.Configuration["DB_CONNECTION"] ?? "Host=localhost;Database=health_manager;Username=postgres;Password=postgres")); + +// ---- JWT 认证 ---- +var jwtSecret = builder.Configuration["JWT_SECRET"]; +if (string.IsNullOrEmpty(jwtSecret) && !builder.Environment.IsDevelopment()) + throw new InvalidOperationException("JWT_SECRET 环境变量未配置,生产环境必须设置"); +jwtSecret ??= "dev-secret-key-change-in-production-min-32-chars!!"; +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ValidIssuer = builder.Configuration["JWT_ISSUER"] ?? "health-manager", + ValidAudience = builder.Configuration["JWT_AUDIENCE"] ?? "health-manager-app", + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)), + ClockSkew = TimeSpan.Zero + }; + }); +builder.Services.AddAuthorization(); + +// ---- 业务服务 ---- +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); + +// ---- AI 客户端(使用 IHttpClientFactory 区分 LLM 和 VLM)---- +builder.Services.AddHttpClient(client => +{ + client.BaseAddress = new Uri((builder.Configuration["DEEPSEEK_BASE_URL"] ?? "https://api.deepseek.com/v1").TrimEnd('/') + "/"); + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", builder.Configuration["DEEPSEEK_API_KEY"] ?? ""); + client.Timeout = TimeSpan.FromSeconds(60); +}); +builder.Services.AddHttpClient(client => +{ + client.BaseAddress = new Uri((builder.Configuration["QWEN_BASE_URL"] ?? "https://dashscope.aliyuncs.com/compatible-mode/v1").TrimEnd('/') + "/"); + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", builder.Configuration["QWEN_API_KEY"] ?? ""); + client.Timeout = TimeSpan.FromSeconds(60); +}); + +// ---- 后台服务 ---- +builder.Services.AddHostedService(); +builder.Services.AddHostedService(); + +// ---- OpenAPI ---- +builder.Services.AddOpenApi(); + +// ---- CORS ---- +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); + }); + // 生产环境:policy.WithOrigins("https://yourdomain.com").AllowAnyMethod().AllowAnyHeader(); +}); + +var app = builder.Build(); + +// ---- 中间件管道(ExceptionMiddleware 放最前面)---- +app.UseMiddleware(); +app.UseCors(); +app.UseAuthentication(); +app.UseAuthorization(); + +if (app.Environment.IsDevelopment()) + app.MapOpenApi(); + +// ---- 初始化数据库(开发环境:每次重建)---- +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + await db.Database.EnsureCreatedAsync(); + await DataSeeder.SeedAsync(db); + await DevDataSeeder.SeedIfEnabled(db, app.Configuration); +} + +// ---- 注册 API 端点 ---- +app.MapAuthEndpoints(); +app.MapHealthEndpoints(); +app.MapDietEndpoints(); +app.MapMedicationEndpoints(); +app.MapReportEndpoints(); +app.MapConsultationEndpoints(); +app.MapExerciseEndpoints(); +app.MapUserEndpoints(); +app.MapAiChatEndpoints(); +app.MapFileEndpoints(); + +app.Run(); diff --git a/backend/src/Health.WebApi/Properties/launchSettings.json b/backend/src/Health.WebApi/Properties/launchSettings.json new file mode 100644 index 0000000..76eddb6 --- /dev/null +++ b/backend/src/Health.WebApi/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5277", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7102;http://localhost:5277", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/backend/src/Health.WebApi/appsettings.Development.json b/backend/src/Health.WebApi/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/backend/src/Health.WebApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/backend/src/Health.WebApi/appsettings.json b/backend/src/Health.WebApi/appsettings.json new file mode 100644 index 0000000..a24f856 --- /dev/null +++ b/backend/src/Health.WebApi/appsettings.json @@ -0,0 +1,24 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "Default": "Host=localhost;Database=health_manager;Username=postgres;Password=postgres123" + }, + "JWT_SECRET": "dev-secret-key-change-in-production-min-32-chars!!", + "JWT_ISSUER": "health-manager", + "JWT_AUDIENCE": "health-manager-app", + "DEEPSEEK_BASE_URL": "https://api.deepseek.com/v1", + "DEEPSEEK_API_KEY": "sk-your-key-here", + "DEEPSEEK_MODEL": "deepseek-chat", + "QWEN_BASE_URL": "https://dashscope.aliyuncs.com/compatible-mode/v1", + "QWEN_API_KEY": "sk-your-key-here", + "QWEN_VISION_MODEL": "qwen-vl-max", + "MINIO_ENDPOINT": "localhost:9000", + "MINIO_ACCESS_KEY": "minioadmin", + "MINIO_SECRET_KEY": "minioadmin123" +} diff --git a/backend/tests/Health.Tests/AuthTests.cs b/backend/tests/Health.Tests/AuthTests.cs new file mode 100644 index 0000000..c5a3dc3 --- /dev/null +++ b/backend/tests/Health.Tests/AuthTests.cs @@ -0,0 +1,143 @@ +using Health.Domain.Entities; +using Health.Infrastructure.Data; +using Health.Infrastructure.Services; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; + +namespace Health.Tests; + +/// +/// 认证流程测试 +/// +public class AuthTests +{ + private AppDbContext CreateDbContext() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new AppDbContext(options); + } + + private IConfiguration CreateConfig() + { + var settings = new Dictionary + { + { "JWT_SECRET", "test-secret-key-for-unit-tests-min-32-chars!!" }, + { "JWT_ISSUER", "health-manager" }, + { "JWT_AUDIENCE", "health-manager-app" } + }; + return new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); + } + + [Fact] + public async Task SendSms_Should_Create_VerificationCode() + { + // Arrange + using var db = CreateDbContext(); + var sms = new SmsService(); + + // Act + var code = sms.GenerateCode(); + db.VerificationCodes.Add(new VerificationCode + { + Id = Guid.NewGuid(), Phone = "13800138000", Code = code, + ExpiresAt = DateTime.UtcNow.AddMinutes(5), + }); + await db.SaveChangesAsync(); + + // Assert + var saved = await db.VerificationCodes.FirstOrDefaultAsync(v => v.Phone == "13800138000"); + Assert.NotNull(saved); + Assert.Equal(code, saved!.Code); + Assert.True(saved.ExpiresAt > DateTime.UtcNow); + } + + [Fact] + public async Task Login_Should_Create_User_And_Return_Token() + { + // Arrange + using var db = CreateDbContext(); + var config = CreateConfig(); + var jwt = new JwtProvider(config); + + var phone = "13800138000"; + + // Act + var user = new User { Id = Guid.NewGuid(), Phone = phone, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var accessToken = jwt.GenerateAccessToken(user.Id, phone); + var refreshToken = jwt.GenerateRefreshToken(); + db.RefreshTokens.Add(new RefreshToken { Id = Guid.NewGuid(), UserId = user.Id, Token = refreshToken, ExpiresAt = DateTime.UtcNow.AddDays(30) }); + await db.SaveChangesAsync(); + + // Assert + Assert.NotNull(accessToken); + Assert.True(accessToken.Length > 50); + Assert.NotNull(refreshToken); + Assert.True(refreshToken.Length > 50); + + var savedUser = await db.Users.FirstOrDefaultAsync(u => u.Phone == phone); + Assert.NotNull(savedUser); + + var savedToken = await db.RefreshTokens.FirstOrDefaultAsync(t => t.Token == refreshToken); + Assert.NotNull(savedToken); + } + + [Fact] + public async Task RefreshToken_Should_Revoke_Old_And_Issue_New() + { + // Arrange + using var db = CreateDbContext(); + var config = CreateConfig(); + var jwt = new JwtProvider(config); + + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + + var oldRefresh = jwt.GenerateRefreshToken(); + db.RefreshTokens.Add(new RefreshToken { Id = Guid.NewGuid(), UserId = user.Id, Token = oldRefresh, ExpiresAt = DateTime.UtcNow.AddDays(30) }); + await db.SaveChangesAsync(); + + // Act — 吊销旧 token,签发新 token + var old = await db.RefreshTokens.FirstOrDefaultAsync(t => t.Token == oldRefresh && !t.IsRevoked); + Assert.NotNull(old); + old!.IsRevoked = true; + + var newToken = jwt.GenerateRefreshToken(); + db.RefreshTokens.Add(new RefreshToken { Id = Guid.NewGuid(), UserId = user.Id, Token = newToken, ExpiresAt = DateTime.UtcNow.AddDays(30) }); + await db.SaveChangesAsync(); + + // Assert + var revoked = await db.RefreshTokens.FirstOrDefaultAsync(t => t.Token == oldRefresh); + Assert.True(revoked!.IsRevoked); + + var active = await db.RefreshTokens.FirstOrDefaultAsync(t => t.Token == newToken && !t.IsRevoked); + Assert.NotNull(active); + } + + [Fact] + public async Task VerificationCode_Expired_Should_Fail_Login() + { + // Arrange + using var db = CreateDbContext(); + var expiredCode = new VerificationCode + { + Id = Guid.NewGuid(), Phone = "13800138000", Code = "123456", + ExpiresAt = DateTime.UtcNow.AddMinutes(-1), // 已过期 + }; + db.VerificationCodes.Add(expiredCode); + await db.SaveChangesAsync(); + + // Act + var valid = await db.VerificationCodes + .Where(v => v.Phone == "13800138000" && v.Code == "123456" + && v.ExpiresAt > DateTime.UtcNow && !v.IsUsed) + .FirstOrDefaultAsync(); + + // Assert — 过期的验证码查不到 + Assert.Null(valid); + } +} diff --git a/backend/tests/Health.Tests/EntityTests.cs b/backend/tests/Health.Tests/EntityTests.cs new file mode 100644 index 0000000..baffb7b --- /dev/null +++ b/backend/tests/Health.Tests/EntityTests.cs @@ -0,0 +1,221 @@ +using Health.Domain.Entities; +using Health.Domain.Enums; +using Health.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace Health.Tests; + +/// +/// 实体和数据库操作测试 +/// +public class EntityTests +{ + private AppDbContext CreateDbContext() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + return new AppDbContext(options); + } + + [Fact] + public async Task Create_HealthRecord_Should_Persist() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var record = new HealthRecord + { + Id = Guid.NewGuid(), UserId = user.Id, MetricType = HealthMetricType.BloodPressure, + Systolic = 128, Diastolic = 82, Unit = "mmHg", + Source = HealthRecordSource.AiEntry, RecordedAt = DateTime.UtcNow, + IsAbnormal = false, + }; + db.HealthRecords.Add(record); + await db.SaveChangesAsync(); + + var saved = await db.HealthRecords.FirstOrDefaultAsync(r => r.UserId == user.Id); + Assert.NotNull(saved); + Assert.Equal(128, saved!.Systolic); + Assert.Equal(82, saved.Diastolic); + Assert.Equal(HealthMetricType.BloodPressure, saved.MetricType); + } + + [Fact] + public async Task Abnormal_BloodPressure_Should_Flag_IsAbnormal() + { + var record = new HealthRecord + { + Systolic = 155, Diastolic = 95, MetricType = HealthMetricType.BloodPressure, + }; + var isAbnormal = record.Systolic >= 140 || record.Diastolic >= 90 + || record.Systolic <= 89 || record.Diastolic <= 59; + + Assert.True(isAbnormal); + } + + [Fact] + public async Task Normal_BloodPressure_Should_Not_Flag() + { + var record = new HealthRecord + { + Systolic = 128, Diastolic = 82, MetricType = HealthMetricType.BloodPressure, + }; + var isAbnormal = record.Systolic >= 140 || record.Diastolic >= 90 + || record.Systolic <= 89 || record.Diastolic <= 59; + + Assert.False(isAbnormal); + } + + [Fact] + public async Task Create_Medication_Should_Persist_With_TimeOfDay() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var med = new Medication + { + Id = Guid.NewGuid(), UserId = user.Id, Name = "阿司匹林", Dosage = "100mg", + Frequency = MedicationFrequency.Daily, + TimeOfDay = [new TimeOnly(8, 0)], + Source = MedicationSource.AiEntry, IsActive = true, + }; + db.Medications.Add(med); + await db.SaveChangesAsync(); + + var saved = await db.Medications.FirstOrDefaultAsync(m => m.UserId == user.Id); + Assert.NotNull(saved); + Assert.Equal("阿司匹林", saved!.Name); + Assert.Equal("100mg", saved.Dosage); + Assert.Single(saved.TimeOfDay); + Assert.Equal(8, saved.TimeOfDay[0].Hour); + } + + [Fact] + public async Task Medication_Confirm_Should_Create_Log() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + + var med = new Medication { Id = Guid.NewGuid(), UserId = user.Id, Name = "阿托伐他汀", Dosage = "20mg", Frequency = MedicationFrequency.Daily, Source = MedicationSource.Prescription, IsActive = true }; + db.Medications.Add(med); + await db.SaveChangesAsync(); + + // 打卡 + var log = new MedicationLog + { + Id = Guid.NewGuid(), MedicationId = med.Id, UserId = user.Id, + Status = MedicationLogStatus.Taken, ScheduledTime = new TimeOnly(20, 0), + ConfirmedAt = DateTime.UtcNow, + }; + db.MedicationLogs.Add(log); + await db.SaveChangesAsync(); + + var saved = await db.MedicationLogs.FirstOrDefaultAsync(l => l.MedicationId == med.Id); + Assert.NotNull(saved); + Assert.Equal(MedicationLogStatus.Taken, saved!.Status); + } + + [Fact] + public async Task Conversation_With_Messages_Should_Work() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var conv = new Conversation { Id = Guid.NewGuid(), UserId = user.Id, AgentType = AgentType.Default, Title = "血压咨询", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Conversations.Add(conv); + + var msg1 = new ConversationMessage { Id = Guid.NewGuid(), ConversationId = conv.Id, Role = MessageRole.User, Content = "血压 135/85", CreatedAt = DateTime.UtcNow }; + var msg2 = new ConversationMessage { Id = Guid.NewGuid(), ConversationId = conv.Id, Role = MessageRole.Assistant, Content = "收到!已记录", CreatedAt = DateTime.UtcNow }; + db.ConversationMessages.AddRange(msg1, msg2); + conv.MessageCount = 2; + await db.SaveChangesAsync(); + + var messages = await db.ConversationMessages.Where(m => m.ConversationId == conv.Id).OrderBy(m => m.CreatedAt).ToListAsync(); + Assert.Equal(2, messages.Count); + Assert.Equal("血压 135/85", messages[0].Content); + Assert.Equal("收到!已记录", messages[1].Content); + } + + [Fact] + public async Task DietRecord_With_FoodItems_Should_Work() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var diet = new DietRecord + { + Id = Guid.NewGuid(), UserId = user.Id, MealType = MealType.Lunch, + TotalCalories = 644, HealthScore = 3, RecordedAt = DateOnly.FromDateTime(DateTime.Now), + }; + diet.FoodItems.Add(new DietFoodItem { Id = Guid.NewGuid(), Name = "米饭", Portion = "1碗", Calories = 174, SortOrder = 1 }); + diet.FoodItems.Add(new DietFoodItem { Id = Guid.NewGuid(), Name = "红烧肉", Portion = "5块", Calories = 470, Warning = "脂肪偏高", SortOrder = 2 }); + db.DietRecords.Add(diet); + await db.SaveChangesAsync(); + + var saved = await db.DietRecords.Include(d => d.FoodItems).FirstOrDefaultAsync(d => d.UserId == user.Id); + Assert.NotNull(saved); + Assert.Equal(2, saved!.FoodItems.Count); + Assert.Equal(644, saved.TotalCalories); + } + + [Fact] + public async Task HealthArchive_Should_Store_All_Fields() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var archive = new HealthArchive + { + Id = Guid.NewGuid(), UserId = user.Id, Diagnosis = "冠心病", + SurgeryType = "PCI支架植入术", SurgeryDate = new DateOnly(2026, 3, 15), + Allergies = ["青霉素"], + DietRestrictions = ["低盐", "低脂"], + ChronicDiseases = ["高血压", "高血脂"], + FamilyHistory = "父亲冠心病", + }; + db.HealthArchives.Add(archive); + await db.SaveChangesAsync(); + + var saved = await db.HealthArchives.FirstOrDefaultAsync(a => a.UserId == user.Id); + Assert.NotNull(saved); + Assert.Equal("冠心病", saved!.Diagnosis); + Assert.Equal(2, saved.DietRestrictions.Count); + Assert.Contains("低盐", saved.DietRestrictions); + } + + [Fact] + public async Task ExercisePlan_Weekly_Tracking_Should_Work() + { + using var db = CreateDbContext(); + var user = new User { Id = Guid.NewGuid(), Phone = "13800138000", CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; + db.Users.Add(user); + await db.SaveChangesAsync(); + + var monday = new DateOnly(2026, 6, 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 }); + plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 1, ExerciseType = "慢跑", DurationMinutes = 20 }); + plan.Items.Add(new ExercisePlanItem { Id = Guid.NewGuid(), DayOfWeek = 2, IsRestDay = true }); + db.ExercisePlans.Add(plan); + await db.SaveChangesAsync(); + + var saved = await db.ExercisePlans.Include(p => p.Items).FirstOrDefaultAsync(p => p.UserId == user.Id); + Assert.NotNull(saved); + Assert.Equal(3, saved!.Items.Count); + + var completed = saved.Items.Count(i => i.IsCompleted); + Assert.Equal(1, completed); + } +} diff --git a/backend/tests/Health.Tests/Health.Tests.csproj b/backend/tests/Health.Tests/Health.Tests.csproj new file mode 100644 index 0000000..d526567 --- /dev/null +++ b/backend/tests/Health.Tests/Health.Tests.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/backend/tests/Health.Tests/UnitTest1.cs b/backend/tests/Health.Tests/UnitTest1.cs new file mode 100644 index 0000000..3cd0114 --- /dev/null +++ b/backend/tests/Health.Tests/UnitTest1.cs @@ -0,0 +1,10 @@ +namespace Health.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..063e45c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,35 @@ +version: '3.8' + +services: + # PostgreSQL 数据库 + postgres: + image: postgres:18 + container_name: health_postgres + environment: + POSTGRES_DB: health_manager + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres123 + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql/data + restart: unless-stopped + + # MinIO 对象存储 + minio: + image: minio/minio:latest + container_name: health_minio + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: minioadmin + MINIO_ROOT_PASSWORD: minioadmin123 + ports: + - "9000:9000" # API + - "9001:9001" # Web 控制台 + volumes: + - miniodata:/data + restart: unless-stopped + +volumes: + pgdata: + miniodata: diff --git a/health_app/.gitignore b/health_app/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/health_app/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/health_app/.metadata b/health_app/.metadata new file mode 100644 index 0000000..644060a --- /dev/null +++ b/health_app/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "3b62efc2a3da49882f43c372e0bc53daef7295a6" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: web + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/health_app/README.md b/health_app/README.md new file mode 100644 index 0000000..71aea38 --- /dev/null +++ b/health_app/README.md @@ -0,0 +1,16 @@ +# health_app + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/health_app/analysis_options.yaml b/health_app/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/health_app/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/health_app/android/.gitignore b/health_app/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/health_app/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/health_app/android/app/build.gradle.kts b/health_app/android/app/build.gradle.kts new file mode 100644 index 0000000..d4761da --- /dev/null +++ b/health_app/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.healthmanager.health_app" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.healthmanager.health_app" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/health_app/android/app/src/debug/AndroidManifest.xml b/health_app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/health_app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/health_app/android/app/src/main/AndroidManifest.xml b/health_app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2ada763 --- /dev/null +++ b/health_app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/health_app/android/app/src/main/kotlin/com/healthmanager/health_app/MainActivity.kt b/health_app/android/app/src/main/kotlin/com/healthmanager/health_app/MainActivity.kt new file mode 100644 index 0000000..6e29721 --- /dev/null +++ b/health_app/android/app/src/main/kotlin/com/healthmanager/health_app/MainActivity.kt @@ -0,0 +1,5 @@ +package com.healthmanager.health_app + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/health_app/android/app/src/main/res/drawable-v21/launch_background.xml b/health_app/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/health_app/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/health_app/android/app/src/main/res/drawable/launch_background.xml b/health_app/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/health_app/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/health_app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/health_app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 GIT binary patch literal 544 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY3?!3`olAj~WQl7;NpOBzNqJ&XDuZK6ep0G} zXKrG8YEWuoN@d~6R2!h8bpbvhu0Wd6uZuB!w&u2PAxD2eNXD>P5D~Wn-+_Wa#27Xc zC?Zj|6r#X(-D3u$NCt}(Ms06KgJ4FxJVv{GM)!I~&n8Bnc94O7-Hd)cjDZswgC;Qs zO=b+9!WcT8F?0rF7!Uys2bs@gozCP?z~o%U|N3vA*22NaGQG zlg@K`O_XuxvZ&Ks^m&R!`&1=spLvfx7oGDKDwpwW`#iqdw@AL`7MR}m`rwr|mZgU`8P7SBkL78fFf!WnuYWm$5Z0 zNXhDbCv&49sM544K|?c)WrFfiZvCi9h0O)B3Pgg&ebxsLQ05GG~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/health_app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/health_app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be GIT binary patch literal 442 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA3?vioaBc-sk|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*D5Xx&nMcT!A!W`0S9QKQy;}1Cl^CgaH=;G9cpY;r$Q>i*pfB zP2drbID<_#qf;rPZx^FqH)F_D#*k@@q03KywUtLX8Ua?`H+NMzkczFPK3lFz@i_kW%1NOn0|D2I9n9wzH8m|-tHjsw|9>@K=iMBhxvkv6m8Y-l zytQ?X=U+MF$@3 zt`~i=@j|6y)RWMK--}M|=T`o&^Ni>IoWKHEbBXz7?A@mgWoL>!*SXo`SZH-*HSdS+ yn*9;$7;m`l>wYBC5bq;=U}IMqLzqbYCidGC!)_gkIk_C@Uy!y&wkt5C($~2D>~)O*cj@FGjOCM)M>_ixfudOh)?xMu#Fs z#}Y=@YDTwOM)x{K_j*Q;dPdJ?Mz0n|pLRx{4n|)f>SXlmV)XB04CrSJn#dS5nK2lM zrZ9#~WelCp7&e13Y$jvaEXHskn$2V!!DN-nWS__6T*l;H&Fopn?A6HZ-6WRLFP=R` zqG+CE#d4|IbyAI+rJJ`&x9*T`+a=p|0O(+s{UBcyZdkhj=yS1>AirP+0R;mf2uMgM zC}@~JfByORAh4SyRgi&!(cja>F(l*O+nd+@4m$|6K6KDn_&uvCpV23&>G9HJp{xgg zoq1^2_p9@|WEo z*X_Uko@K)qYYv~>43eQGMdbiGbo>E~Q& zrYBH{QP^@Sti!`2)uG{irBBq@y*$B zi#&(U-*=fp74j)RyIw49+0MRPMRU)+a2r*PJ$L5roHt2$UjExCTZSbq%V!HeS7J$N zdG@vOZB4v_lF7Plrx+hxo7(fCV&}fHq)$ literal 0 HcmV?d00001 diff --git a/health_app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/health_app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^6F``Q8Ax83A=Cw=BuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFa`(sgt!6~Yi|1%a`XoT0ojZ}lNrNjb9xjc(B0U1_% zz5^97Xt*%oq$rQy4?0GKNfJ44uvxI)gC`h-NZ|&0-7(qS@?b!5r36oQ}zyZrNO3 zMO=Or+<~>+A&uN&E!^Sl+>xE!QC-|oJv`ApDhqC^EWD|@=#J`=d#Xzxs4ah}w&Jnc z$|q_opQ^2TrnVZ0o~wh<3t%W&flvYGe#$xqda2bR_R zvPYgMcHgjZ5nSA^lJr%;<&0do;O^tDDh~=pIxA#coaCY>&N%M2^tq^U%3DB@ynvKo}b?yu-bFc-u0JHzced$sg7S3zqI(2 z#Km{dPr7I=pQ5>FuK#)QwK?Y`E`B?nP+}U)I#c1+FM*1kNvWG|a(TpksZQ3B@sD~b zpQ2)*V*TdwjFOtHvV|;OsiDqHi=6%)o4b!)x$)%9pGTsE z-JL={-Ffv+T87W(Xpooq<`r*VzWQcgBN$$`u}f>-ZQI1BB8ykN*=e4rIsJx9>z}*o zo~|9I;xof literal 0 HcmV?d00001 diff --git a/health_app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/health_app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 GIT binary patch literal 1443 zcmb`G{WsKk6vsdJTdFg%tJav9_E4vzrOaqkWF|A724Nly!y+?N9`YV6wZ}5(X(D_N(?!*n3`|_r0Hc?=PQw&*vnU?QTFY zB_MsH|!j$PP;I}?dppoE_gA(4uc!jV&0!l7_;&p2^pxNo>PEcNJv za5_RT$o2Mf!<+r?&EbHH6nMoTsDOa;mN(wv8RNsHpG)`^ymG-S5By8=l9iVXzN_eG%Xg2@Xeq76tTZ*dGh~Lo9vl;Zfs+W#BydUw zCkZ$o1LqWQO$FC9aKlLl*7x9^0q%0}$OMlp@Kk_jHXOjofdePND+j!A{q!8~Jn+s3 z?~~w@4?egS02}8NuulUA=L~QQfm;MzCGd)XhiftT;+zFO&JVyp2mBww?;QByS_1w! zrQlx%{^cMj0|Bo1FjwY@Q8?Hx0cIPF*@-ZRFpPc#bBw{5@tD(5%sClzIfl8WU~V#u zm5Q;_F!wa$BSpqhN>W@2De?TKWR*!ujY;Yylk_X5#~V!L*Gw~;$%4Q8~Mad z@`-kG?yb$a9cHIApZDVZ^U6Xkp<*4rU82O7%}0jjHlK{id@?-wpN*fCHXyXh(bLt* zPc}H-x0e4E&nQ>y%B-(EL=9}RyC%MyX=upHuFhAk&MLbsF0LP-q`XnH78@fT+pKPW zu72MW`|?8ht^tz$iC}ZwLp4tB;Q49K!QCF3@!iB1qOI=?w z7In!}F~ij(18UYUjnbmC!qKhPo%24?8U1x{7o(+?^Zu0Hx81|FuS?bJ0jgBhEMzf< zCgUq7r2OCB(`XkKcN-TL>u5y#dD6D!)5W?`O5)V^>jb)P)GBdy%t$uUMpf$SNV31$ zb||OojAbvMP?T@$h_ZiFLFVHDmbyMhJF|-_)HX3%m=CDI+ID$0^C>kzxprBW)hw(v zr!Gmda);ICoQyhV_oP5+C%?jcG8v+D@9f?Dk*!BxY}dazmrT@64UrP3hlslANK)bq z$67n83eh}OeW&SV@HG95P|bjfqJ7gw$e+`Hxo!4cx`jdK1bJ>YDSpGKLPZ^1cv$ek zIB?0S<#tX?SJCLWdMd{-ME?$hc7A$zBOdIJ)4!KcAwb=VMov)nK;9z>x~rfT1>dS+ zZ6#`2v@`jgbqq)P22H)Tx2CpmM^o1$B+xT6`(v%5xJ(?j#>Q$+rx_R|7TzDZe{J6q zG1*EcU%tE?!kO%^M;3aM6JN*LAKUVb^xz8-Pxo#jR5(-KBeLJvA@-gxNHx0M-ZJLl z;#JwQoh~9V?`UVo#}{6ka@II>++D@%KqGpMdlQ}?9E*wFcf5(#XQnP$Dk5~%iX^>f z%$y;?M0BLp{O3a(-4A?ewryHrrD%cx#Q^%KY1H zNre$ve+vceSLZcNY4U(RBX&)oZn*Py()h)XkE?PL$!bNb{N5FVI2Y%LKEm%yvpyTP z(1P?z~7YxD~Rf<(a@_y` literal 0 HcmV?d00001 diff --git a/health_app/android/app/src/main/res/values-night/styles.xml b/health_app/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/health_app/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/health_app/android/app/src/main/res/values/styles.xml b/health_app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/health_app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/health_app/android/app/src/profile/AndroidManifest.xml b/health_app/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/health_app/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/health_app/android/build.gradle.kts b/health_app/android/build.gradle.kts new file mode 100644 index 0000000..2c0b9ad --- /dev/null +++ b/health_app/android/build.gradle.kts @@ -0,0 +1,26 @@ +allprojects { + repositories { + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/health_app/android/gradle.properties b/health_app/android/gradle.properties new file mode 100644 index 0000000..9b6c50e --- /dev/null +++ b/health_app/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -Duser.language=en -Duser.country=US +android.useAndroidX=true +android.overridePathCheck=true diff --git a/health_app/android/gradle/wrapper/gradle-wrapper.properties b/health_app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/health_app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/health_app/android/settings.gradle.kts b/health_app/android/settings.gradle.kts new file mode 100644 index 0000000..2a693b9 --- /dev/null +++ b/health_app/android/settings.gradle.kts @@ -0,0 +1,22 @@ +pluginManagement { + val flutterSdkPath = "C:/flutter_sdk" + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + maven { url = uri("https://maven.aliyun.com/repository/google") } + maven { url = uri("https://maven.aliyun.com/repository/public") } + maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") } + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/health_app/ios/.gitignore b/health_app/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/health_app/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/health_app/ios/Flutter/AppFrameworkInfo.plist b/health_app/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..1dc6cf7 --- /dev/null +++ b/health_app/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/health_app/ios/Flutter/Debug.xcconfig b/health_app/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/health_app/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/health_app/ios/Flutter/Release.xcconfig b/health_app/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/health_app/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/health_app/ios/Runner.xcodeproj/project.pbxproj b/health_app/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7f2721f --- /dev/null +++ b/health_app/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.healthmanager.healthApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/health_app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/health_app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/health_app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/health_app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/health_app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/health_app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/health_app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/health_app/ios/Runner.xcworkspace/contents.xcworkspacedata b/health_app/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/health_app/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/health_app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/health_app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/health_app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/health_app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/health_app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/health_app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/health_app/ios/Runner/AppDelegate.swift b/health_app/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/health_app/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..dc9ada4725e9b0ddb1deab583e5b5102493aa332 GIT binary patch literal 10932 zcmeHN2~<R zh`|8`A_PQ1nSu(UMFx?8j8PC!!VDphaL#`F42fd#7Vlc`zIE4n%Y~eiz4y1j|NDpi z?<@|pSJ-HM`qifhf@m%MamgwK83`XpBA<+azdF#2QsT{X@z0A9Bq>~TVErigKH1~P zRX-!h-f0NJ4Mh++{D}J+K>~~rq}d%o%+4dogzXp7RxX4C>Km5XE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P6NMff(*^re zYqvDuO`K@`mjm_Jd;mW_tP`3$cS?R$jR1ZN09$YO%_iBqh5ftzSpMQQtxKFU=FYmP zeY^jph+g<4>YO;U^O>-NFLn~-RqlHvnZl2yd2A{Yc1G@Ga$d+Q&(f^tnPf+Z7serIU};17+2DU_f4Z z@GaPFut27d?!YiD+QP@)T=77cR9~MK@bd~pY%X(h%L={{OIb8IQmf-!xmZkm8A0Ga zQSWONI17_ru5wpHg3jI@i9D+_Y|pCqVuHJNdHUauTD=R$JcD2K_liQisqG$(sm=k9;L* z!L?*4B~ql7uioSX$zWJ?;q-SWXRFhz2Jt4%fOHA=Bwf|RzhwqdXGr78y$J)LR7&3T zE1WWz*>GPWKZ0%|@%6=fyx)5rzUpI;bCj>3RKzNG_1w$fIFCZ&UR0(7S?g}`&Pg$M zf`SLsz8wK82Vyj7;RyKmY{a8G{2BHG%w!^T|Njr!h9TO2LaP^_f22Q1=l$QiU84ao zHe_#{S6;qrC6w~7{y(hs-?-j?lbOfgH^E=XcSgnwW*eEz{_Z<_xN#0001NP)t-s|Ns9~ z#rXRE|M&d=0au&!`~QyF`q}dRnBDt}*!qXo`c{v z{Djr|@Adh0(D_%#_&mM$D6{kE_x{oE{l@J5@%H*?%=t~i_`ufYOPkAEn!pfkr2$fs z652Tz0001XNklqeeKN4RM4i{jKqmiC$?+xN>3Apn^ z0QfuZLym_5b<*QdmkHjHlj811{If)dl(Z2K0A+ekGtrFJb?g|wt#k#pV-#A~bK=OT ts8>{%cPtyC${m|1#B1A6#u!Q;umknL1chzTM$P~L002ovPDHLkV1lTfnu!1a literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..797d452e458972bab9d994556c8305db4c827017 GIT binary patch literal 406 zcmV;H0crk;P))>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed2d933e1120817fe9182483a228007b18ab6ae GIT binary patch literal 450 zcmV;z0X_bSP)iGWQ_5NJQ_~rNh*z)}eT%KUb z`7gNk0#AwF^#0T0?hIa^`~Ck;!}#m+_uT050aTR(J!bU#|IzRL%^UsMS#KsYnTF*!YeDOytlP4VhV?b} z%rz_<=#CPc)tU1MZTq~*2=8~iZ!lSa<{9b@2Jl;?IEV8)=fG217*|@)CCYgFze-x? zIFODUIA>nWKpE+bn~n7;-89sa>#DR>TSlqWk*!2hSN6D~Qb#VqbP~4Fk&m`@1$JGr zXPIdeRE&b2Thd#{MtDK$px*d3-Wx``>!oimf%|A-&-q*6KAH)e$3|6JV%HX{Hig)k suLT-RhftRq8b9;(V=235Wa|I=027H2wCDra;{X5v07*qoM6N<$f;9x^2LJ#7 literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd7b0099ca80c806f8fe495613e8d6c69460d76 GIT binary patch literal 282 zcmV+#0p(^bcu7P-R4C8Q z&e;xxFbF_Vrezo%_kH*OKhshZ6BFpG-Y1e10`QXJKbND7AMQ&cMj60B5TNObaZxYybcN07*qoM6N<$g3m;S%K!iX literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..fe730945a01f64a61e2235dbe3f45b08f7729182 GIT binary patch literal 462 zcmV;<0WtoGP)-}iV`2<;=$?g5M=KQbZ{F&YRNy7Nn@%_*5{gvDM0aKI4?ESmw z{NnZg)A0R`+4?NF_RZexyVB&^^ZvN!{I28tr{Vje;QNTz`dG&Jz0~Ek&f2;*Z7>B|cg}xYpxEFY+0YrKLF;^Q+-HreN0P{&i zK~zY`?b7ECf-n?@;d<&orQ*Q7KoR%4|C>{W^h6@&01>0SKS`dn{Q}GT%Qj_{PLZ_& zs`MFI#j-(>?bvdZ!8^xTwlY{qA)T4QLbY@j(!YJ7aXJervHy6HaG_2SB`6CC{He}f zHVw(fJWApwPq!6VY7r1w-Fs)@ox~N+q|w~e;JI~C4Vf^@d>Wvj=fl`^u9x9wd9 zR%3*Q+)t%S!MU_`id^@&Y{y7-r98lZX0?YrHlfmwb?#}^1b{8g&KzmkE(L>Z&)179 zp<)v6Y}pRl100G2FL_t(o!|l{-Q-VMg#&MKg7c{O0 z2wJImOS3Gy*Z2Qifdv~JYOp;v+U)a|nLoc7hNH;I$;lzDt$}rkaFw1mYK5_0Q(Sut zvbEloxON7$+HSOgC9Z8ltuC&0OSF!-mXv5caV>#bc3@hBPX@I$58-z}(ZZE!t-aOG zpjNkbau@>yEzH(5Yj4kZiMH32XI!4~gVXNnjAvRx;Sdg^`>2DpUEwoMhTs_st8pKG z(%SHyHdU&v%f36~uERh!bd`!T2dw;z6PrOTQ7Vt*#9F2uHlUVnb#ev_o^fh}Dzmq} zWtlk35}k=?xj28uO|5>>$yXadTUE@@IPpgH`gJ~Ro4>jd1IF|(+IX>8M4Ps{PNvmI zNj4D+XgN83gPt_Gm}`Ybv{;+&yu-C(Grdiahmo~BjG-l&mWM+{e5M1sm&=xduwgM9 z`8OEh`=F3r`^E{n_;%9weN{cf2%7=VzC@cYj+lg>+3|D|_1C@{hcU(DyQG_BvBWe? zvTv``=%b1zrol#=R`JB)>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..502f463a9bc882b461c96aadf492d1729e49e725 GIT binary patch literal 586 zcmV-Q0=4~#P)+}#`wDE{8-2Mebf5<{{PqV{TgVcv*r8?UZ3{-|G?_}T*&y;@cqf{ z{Q*~+qr%%p!1pS*_Uicl#q9lc(D`!D`LN62sNwq{oYw(Wmhk)k<@f$!$@ng~_5)Ru z0Z)trIA5^j{DIW^c+vT2%lW+2<(RtE2wR;4O@)Tm`Xr*?A(qYoM}7i5Yxw>D(&6ou zxz!_Xr~yNF+waPe00049Nkl*;a!v6h%{rlvIH#gW3s8p;bFr=l}mRqpW2h zw=OA%hdyL~z+UHOzl0eKhEr$YYOL-c-%Y<)=j?(bzDweB7{b+%_ypvm_cG{SvM=DK zhv{K@m>#Bw>2W$eUI#iU)Wdgs8Y3U+A$Gd&{+j)d)BmGKx+43U_!tik_YlN)>$7G! zhkE!s;%oku3;IwG3U^2kw?z+HM)jB{@zFhK8P#KMSytSthr+4!c(5c%+^UBn`0X*2 zy3(k600_CSZj?O$Qu%&$;|TGUJrptR(HzyIx>5E(2r{eA(<6t3e3I0B)7d6s7?Z5J zZ!rtKvA{MiEBm&KFtoifx>5P^Z=vl)95XJn()aS5%ad(s?4-=Tkis9IGu{`Fy8r+H07*qoM6N<$f20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0ec303439225b78712f49115768196d8d76f6790 GIT binary patch literal 862 zcmV-k1EKthP)20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..e9f5fea27c705180eb716271f41b582e76dcbd90 GIT binary patch literal 1674 zcmV;526g#~P){YQnis^a@{&-nmRmq)<&%Mztj67_#M}W?l>kYSliK<%xAp;0j{!}J0!o7b zE>q9${Lb$D&h7k=+4=!ek^n+`0zq>LL1O?lVyea53S5x`Nqqo2YyeuIrQrJj9XjOp z{;T5qbj3}&1vg1VK~#9!?b~^C5-}JC@Pyrv-6dSEqJqT}#j9#dJ@GzT@B8}x zU&J@bBI>f6w6en+CeI)3^kC*U?}X%OD8$Fd$H&LV$H&LV$H&LV#|K5~mLYf|VqzOc zkc7qL~0sOYuM{tG`rYEDV{DWY`Z8&)kW*hc2VkBuY+^Yx&92j&StN}Wp=LD zxoGxXw6f&8sB^u})h@b@z0RBeD`K7RMR9deyL(ZJu#39Z>rT)^>v}Khq8U-IbIvT> z?4pV9qGj=2)TNH3d)=De<+^w;>S7m_eFKTvzeaBeir45xY!^m!FmxnljbSS_3o=g( z->^wC9%qkR{kbGnW8MfFew_o9h3(r55Is`L$8KI@d+*%{=Nx+FXJ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)`k#0YE+?e)5&#r7J#c`3Z7x!LpTc01dx zrdC3{Z;joZ^KN&))zB_i)I9fWedoN>Zl-6_Iz+^G&*ak2jpF07*qoM6N<$f;w%0(f|Me literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/health_app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0467bf12aa4d28f374bb26596605a46dcbb3e7c8 GIT binary patch literal 1418 zcmV;51$Fv~P)q zKfU)WzW*n(@|xWGCA9ScMt*e9`2kdxPQ&&>|-UCa7_51w+ zLUsW@ZzZSW0y$)Hp~e9%PvP|a03ks1`~K?q{u;6NC8*{AOqIUq{CL&;p56Lf$oQGq z^={4hPQv)y=I|4n+?>7Fim=dxt1 z2H+Dm+1+fh+IF>G0SjJMkQQre1x4|G*Z==(Ot&kCnUrL4I(rf(ucITwmuHf^hXiJT zkdTm&kdTm&kdTm&kdP`esgWG0BcWCVkVZ&2dUwN`cgM8QJb`Z7Z~e<&Yj2(}>Tmf` zm1{eLgw!b{bXkjWbF%dTkTZEJWyWOb##Lfw4EK2}<0d6%>AGS{po>WCOy&f$Tay_> z?NBlkpo@s-O;0V%Y_Xa-G#_O08q5LR*~F%&)}{}r&L%Sbs8AS4t7Y0NEx*{soY=0MZExqA5XHQkqi#4gW3 zqODM^iyZl;dvf)-bOXtOru(s)Uc7~BFx{w-FK;2{`VA?(g&@3z&bfLFyctOH!cVsF z7IL=fo-qBndRUm;kAdXR4e6>k-z|21AaN%ubeVrHl*<|s&Ax@W-t?LR(P-24A5=>a z*R9#QvjzF8n%@1Nw@?CG@6(%>+-0ASK~jEmCV|&a*7-GKT72W<(TbSjf)&Eme6nGE z>Gkj4Sq&2e+-G%|+NM8OOm5zVl9{Z8Dd8A5z3y8mZ=4Bv4%>as_{9cN#bm~;h>62( zdqY93Zy}v&c4n($Vv!UybR8ocs7#zbfX1IY-*w~)p}XyZ-SFC~4w>BvMVr`dFbelV{lLL0bx7@*ZZdebr3`sP;? zVImji)kG)(6Juv0lz@q`F!k1FE;CQ(D0iG$wchPbKZQELlsZ#~rt8#90Y_Xh&3U-< z{s<&cCV_1`^TD^ia9!*mQDq& zn2{r`j};V|uV%_wsP!zB?m%;FeaRe+X47K0e+KE!8C{gAWF8)lCd1u1%~|M!XNRvw zvtqy3iz0WSpWdhn6$hP8PaRBmp)q`#PCA`Vd#Tc$@f1tAcM>f_I@bC)hkI9|o(Iqv zo}Piadq!j76}004RBio<`)70k^`K1NK)q>w?p^C6J2ZC!+UppiK6&y3Kmbv&O!oYF z34$0Z;QO!JOY#!`qyGH<3Pd}Pt@q*A0V=3SVtWKRR8d8Z&@)3qLPA19LPA19LPEUC YUoZo%k(ykuW&i*H07*qoM6N<$f+CH{y8r+H literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/health_app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/health_app/ios/Runner/Base.lproj/LaunchScreen.storyboard b/health_app/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/health_app/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/health_app/ios/Runner/Base.lproj/Main.storyboard b/health_app/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/health_app/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/health_app/ios/Runner/Info.plist b/health_app/ios/Runner/Info.plist new file mode 100644 index 0000000..39e7dfe --- /dev/null +++ b/health_app/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Health App + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + health_app + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/health_app/ios/Runner/Runner-Bridging-Header.h b/health_app/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/health_app/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/health_app/ios/RunnerTests/RunnerTests.swift b/health_app/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/health_app/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/health_app/lib/app.dart b/health_app/lib/app.dart new file mode 100644 index 0000000..0d7d077 --- /dev/null +++ b/health_app/lib/app.dart @@ -0,0 +1,18 @@ +import 'package:flutter/material.dart'; +import 'core/app_router.dart'; +import 'core/app_theme.dart'; + +/// 健康管家 App 根组件 +class HealthApp extends StatelessWidget { + const HealthApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp.router( + title: '健康管家', + debugShowCheckedModeBanner: false, + theme: AppTheme.lightTheme, + routerConfig: AppRouter.router, + ); + } +} diff --git a/health_app/lib/core/api_client.dart b/health_app/lib/core/api_client.dart new file mode 100644 index 0000000..beb228d --- /dev/null +++ b/health_app/lib/core/api_client.dart @@ -0,0 +1,99 @@ +import 'package:dio/dio.dart'; +import 'secure_storage.dart'; + +/// API 基础地址 +const String baseUrl = 'http://10.4.172.93:5000'; + +/// Dio HTTP 客户端封装——带 token 注入、401 自动刷新 +class ApiClient { + final Dio _dio; + final SecureStorage _storage; + + ApiClient({required SecureStorage storage}) + : _storage = storage, + _dio = Dio(BaseOptions( + baseUrl: baseUrl, + connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(seconds: 60), + headers: {'Content-Type': 'application/json'}, + )) { + _dio.interceptors.add(_AuthInterceptor(this)); + _dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: false)); + } + + Dio get dio => _dio; + + Future get accessToken => _storage.readAccessToken(); + Future get refreshToken => _storage.readRefreshToken(); + + Future saveTokens(String access, String refresh) async { + await _storage.writeAccessToken(access); + await _storage.writeRefreshToken(refresh); + } + + Future clearTokens() async { + await _storage.deleteAll(); + } + + /// 带 token 的 GET 请求 + Future get(String path, {Map? queryParameters}) async { + return _dio.get(path, queryParameters: queryParameters); + } + + /// 带 token 的 POST 请求 + Future post(String path, {dynamic data}) async { + return _dio.post(path, data: data); + } + + /// 带 token 的 PUT 请求 + Future put(String path, {dynamic data}) async { + return _dio.put(path, data: data); + } + + /// 带 token 的 DELETE 请求 + Future delete(String path) async { + return _dio.delete(path); + } +} + +/// 认证拦截器:自动注入 token + 401 刷新 +class _AuthInterceptor extends Interceptor { + final ApiClient _client; + + _AuthInterceptor(this._client); + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) async { + if (!options.path.contains('/auth/')) { + final token = await _client.accessToken; + if (token != null) { + options.headers['Authorization'] = 'Bearer $token'; + } + } + handler.next(options); + } + + @override + void onError(DioException err, ErrorInterceptorHandler handler) async { + if (err.response?.statusCode == 401) { + final refresh = await _client.refreshToken; + if (refresh != null) { + try { + final response = await Dio(BaseOptions(baseUrl: baseUrl)) + .post('/api/auth/refresh', data: {'refreshToken': refresh}); + final data = response.data['data']; + if (data != null) { + await _client.saveTokens(data['accessToken'], data['refreshToken']); + final opts = err.requestOptions; + final token = data['accessToken']; + opts.headers['Authorization'] = 'Bearer $token'; + final retryResponse = await Dio(BaseOptions(baseUrl: baseUrl)).fetch(opts); + return handler.resolve(retryResponse); + } + } catch (_) {} + } + await _client.clearTokens(); + } + handler.next(err); + } +} diff --git a/health_app/lib/core/app_router.dart b/health_app/lib/core/app_router.dart new file mode 100644 index 0000000..3126c2b --- /dev/null +++ b/health_app/lib/core/app_router.dart @@ -0,0 +1,57 @@ +import 'package:go_router/go_router.dart'; +import '../pages/auth/login_page.dart'; +import '../pages/home/home_page.dart'; +import '../pages/chart/trend_page.dart'; +import '../pages/medication/medication_list_page.dart'; +import '../pages/report/report_pages.dart'; +import '../pages/consultation/consultation_pages.dart'; +import '../pages/settings/settings_pages.dart'; +import '../pages/profile/profile_page.dart'; +import '../pages/remaining_pages.dart'; + +/// 应用路由配置 +class AppRouter { + AppRouter._(); + + static final GoRouter router = GoRouter( + initialLocation: '/login', + routes: [ + GoRoute(path: '/login', builder: (_, _) => const LoginPage()), + GoRoute(path: '/home', builder: (_, _) => const HomePage()), + GoRoute(path: '/trend/:type', builder: (_, state) => TrendPage(metricType: state.pathParameters['type']!)), + GoRoute(path: '/calendar', builder: (_, _) => const HealthCalendarPage()), + + // 用药 + GoRoute(path: '/medications', builder: (_, _) => const MedicationListPage()), + GoRoute(path: '/medications/add', builder: (_, _) => const MedicationEditPage()), + GoRoute(path: '/medications/:id/edit', builder: (_, state) => MedicationEditPage(id: state.pathParameters['id'])), + + // 报告 + GoRoute(path: '/reports', builder: (_, _) => const ReportListPage()), + GoRoute(path: '/reports/:id', builder: (_, state) => ReportDetailPage(id: state.pathParameters['id']!)), + + // 问诊 + GoRoute(path: '/doctors', builder: (_, _) => const DoctorListPage()), + GoRoute(path: '/consultation/:id', builder: (_, state) => DoctorChatPage(id: state.pathParameters['id']!)), + + // 运动 + GoRoute(path: '/exercise-plan', builder: (_, _) => const ExercisePlanPage()), + + // 饮食 + GoRoute(path: '/diet-records', builder: (_, _) => const DietRecordListPage()), + + // 个人中心 + GoRoute(path: '/profile', builder: (_, _) => const ProfilePage()), + GoRoute(path: '/profile/edit', builder: (_, _) => const EditProfilePage()), + GoRoute(path: '/health-archive', builder: (_, _) => const HealthArchivePage()), + + // 复查 + GoRoute(path: '/followups', builder: (_, _) => const FollowUpListPage()), + + // 设置 + GoRoute(path: '/settings', builder: (_, _) => const SettingsPage()), + GoRoute(path: '/settings/notifications', builder: (_, _) => const NotificationPrefsPage()), + GoRoute(path: '/page/:type', builder: (_, state) => StaticTextPage(type: state.pathParameters['type']!)), + ], + ); +} diff --git a/health_app/lib/core/app_theme.dart b/health_app/lib/core/app_theme.dart new file mode 100644 index 0000000..b281a79 --- /dev/null +++ b/health_app/lib/core/app_theme.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; + +/// 健康管家主题配置——薰衣草紫 + 温暖治愈风 +class AppTheme { + AppTheme._(); + + static const Color primaryColor = Color(0xFF635BFF); + static const Color primaryLight = Color(0xFFEDEBFF); + static const Color primaryDark = Color(0xFF4B44D6); + static const Color background = Color(0xFFF8F9FF); + static const Color cardWhite = Color(0xFFFFFFFF); + static const Color textPrimary = Color(0xFF1A1A1A); + static const Color textSecondary = Color(0xFF666666); + static const Color textPlaceholder = Color(0xFF999999); + static const Color successGreen = Color(0xFF43A047); + static const Color errorRed = Color(0xFFE53935); + static const Color warningYellow = Color(0xFFF9A825); + static const Color secondaryButton = Color(0xFFE5E5F7); + + static ThemeData get lightTheme => ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed( + seedColor: primaryColor, + primary: primaryColor, + surface: background, + brightness: Brightness.light, + ), + scaffoldBackgroundColor: background, + appBarTheme: const AppBarTheme( + backgroundColor: cardWhite, + foregroundColor: textPrimary, + elevation: 0, + centerTitle: true, + ), + cardTheme: CardThemeData( + color: cardWhite, + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: cardWhite, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: secondaryButton, width: 1.5), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: secondaryButton, width: 1.5), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: primaryColor, width: 1.5), + ), + hintStyle: const TextStyle(color: textPlaceholder, fontSize: 16), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + backgroundColor: primaryColor, + foregroundColor: Colors.white, + minimumSize: const Size(double.infinity, 48), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + ), + textTheme: const TextTheme( + headlineLarge: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: textPrimary), + titleLarge: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: textPrimary), + bodyLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w400, color: textPrimary), + bodyMedium: TextStyle(fontSize: 16, fontWeight: FontWeight.w400, color: textSecondary), + labelMedium: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: textSecondary), + labelSmall: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: textSecondary), + ), + ); +} diff --git a/health_app/lib/core/secure_storage.dart b/health_app/lib/core/secure_storage.dart new file mode 100644 index 0000000..5ff2259 --- /dev/null +++ b/health_app/lib/core/secure_storage.dart @@ -0,0 +1,35 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +/// Token 安全存储(iOS Keychain / Android EncryptedSharedPreferences / Web 内存) +class SecureStorage { + final FlutterSecureStorage _storage; + static final Map _webFallback = {}; + + SecureStorage() : _storage = const FlutterSecureStorage(); + static const _access = 'access_token'; + static const _refresh = 'refresh_token'; + + bool get _isWeb => kIsWeb; + + Future writeAccessToken(String t) async { + if (_isWeb) { _webFallback[_access] = t; return; } + await _storage.write(key: _access, value: t); + } + Future readAccessToken() async { + if (_isWeb) return _webFallback[_access]; + return _storage.read(key: _access); + } + Future writeRefreshToken(String t) async { + if (_isWeb) { _webFallback[_refresh] = t; return; } + await _storage.write(key: _refresh, value: t); + } + Future readRefreshToken() async { + if (_isWeb) return _webFallback[_refresh]; + return _storage.read(key: _refresh); + } + Future deleteAll() async { + if (_isWeb) { _webFallback.clear(); return; } + await _storage.deleteAll(); + } +} diff --git a/health_app/lib/main.dart b/health_app/lib/main.dart new file mode 100644 index 0000000..b8b273b --- /dev/null +++ b/health_app/lib/main.dart @@ -0,0 +1,8 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'app.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + runApp(const ProviderScope(child: HealthApp())); +} diff --git a/health_app/lib/pages/auth/login_page.dart b/health_app/lib/pages/auth/login_page.dart new file mode 100644 index 0000000..36c6be0 --- /dev/null +++ b/health_app/lib/pages/auth/login_page.dart @@ -0,0 +1,184 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../providers/auth_provider.dart'; + +/// 登录页——手机号 + 验证码 +class LoginPage extends ConsumerStatefulWidget { + const LoginPage({super.key}); + + @override + ConsumerState createState() => _LoginPageState(); +} + +class _LoginPageState extends ConsumerState { + final _phoneCtrl = TextEditingController(); + final _codeCtrl = TextEditingController(); + bool _agreed = false; + bool _sending = false; + int _countdown = 0; + bool _loading = false; + String? _error; + + @override + void dispose() { + _phoneCtrl.dispose(); + _codeCtrl.dispose(); + super.dispose(); + } + + Future _sendSms() async { + final phone = _phoneCtrl.text.trim(); + if (phone.length != 11 || !phone.startsWith('1')) { + setState(() => _error = '请输入正确的手机号'); + return; + } + setState(() { _sending = true; _error = null; }); + final result = await ref.read(authProvider.notifier).sendSms(phone); + setState(() { _sending = false; }); + if (result.error != null) { + setState(() => _error = result.error); + return; + } + // 开发阶段自动填充验证码 + if (result.devCode != null) { + _codeCtrl.text = result.devCode!; + } + setState(() => _countdown = 60); + _startCountdown(); + } + + void _startCountdown() async { + for (var i = 60; i > 0; i--) { + await Future.delayed(const Duration(seconds: 1)); + if (!mounted) return; + setState(() => _countdown = i - 1); + } + } + + Future _login() async { + if (!_agreed) { + setState(() => _error = '请阅读并同意服务协议和隐私政策'); + return; + } + setState(() { _loading = true; _error = null; }); + final err = await ref.read(authProvider.notifier).login( + _phoneCtrl.text.trim(), + _codeCtrl.text.trim(), + ); + setState(() => _loading = false); + if (err != null) { + setState(() => _error = err); + return; + } + if (mounted) context.go('/home'); + } + + @override + Widget build(BuildContext context) { + final authState = ref.watch(authProvider); + + // 已登录直接跳转 + if (authState.isLoggedIn && !authState.isLoading) { + WidgetsBinding.instance.addPostFrameCallback((_) => context.go('/home')); + } + + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + children: [ + const SizedBox(height: 80), + // Logo + Icon(Icons.local_hospital, size: 64, color: Theme.of(context).colorScheme.primary), + const SizedBox(height: 16), + Text('健康管家', style: Theme.of(context).textTheme.headlineLarge), + const SizedBox(height: 8), + Text('您的 AI 健康陪伴助手', style: Theme.of(context).textTheme.bodyMedium), + const SizedBox(height: 48), + + // 手机号 + TextField( + controller: _phoneCtrl, + keyboardType: TextInputType.phone, + maxLength: 11, + decoration: const InputDecoration( + hintText: '手机号', + prefixText: '+86 ', + counterText: '', + ), + ), + const SizedBox(height: 16), + + // 验证码 + Row( + children: [ + Expanded( + child: TextField( + controller: _codeCtrl, + keyboardType: TextInputType.number, + maxLength: 6, + decoration: const InputDecoration(hintText: '验证码', counterText: ''), + ), + ), + const SizedBox(width: 12), + SizedBox( + width: 120, + height: 48, + child: ElevatedButton( + onPressed: (_countdown > 0 || _sending) ? null : _sendSms, + style: ElevatedButton.styleFrom( + backgroundColor: _countdown > 0 ? Colors.grey[300] : null, + ), + child: Text( + _sending ? '发送中' : _countdown > 0 ? '${_countdown}s' : '获取验证码', + style: TextStyle(fontSize: 14, color: _countdown > 0 ? Colors.grey[600] : null), + ), + ), + ), + ], + ), + const SizedBox(height: 16), + + // 协议勾选 + Row( + children: [ + Checkbox(value: _agreed, onChanged: (v) => setState(() => _agreed = v ?? false)), + GestureDetector( + onTap: () => setState(() => _agreed = !_agreed), + child: Text('已阅读并同意《服务协议》《隐私政策》', style: Theme.of(context).textTheme.labelMedium), + ), + ], + ), + const SizedBox(height: 24), + + // 登录按钮 + if (_error != null) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text(_error!, style: const TextStyle(color: AppColors.errorRed, fontSize: 14)), + ), + SizedBox( + width: double.infinity, + height: 48, + child: ElevatedButton( + onPressed: _loading ? null : _login, + child: _loading + ? const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) + : const Text('登 录'), + ), + ), + const SizedBox(height: 80), + ], + ), + ), + ), + ); + } +} + +/// 引用 AppTheme 颜色 +class AppColors { + static const Color errorRed = Color(0xFFE53935); +} diff --git a/health_app/lib/pages/chart/trend_page.dart b/health_app/lib/pages/chart/trend_page.dart new file mode 100644 index 0000000..87a14a5 --- /dev/null +++ b/health_app/lib/pages/chart/trend_page.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../providers/data_providers.dart'; + +/// 趋势图表页面 +class TrendPage extends ConsumerStatefulWidget { + final String metricType; + const TrendPage({super.key, required this.metricType}); + @override ConsumerState createState() => _TrendPageState(); +} + +class _TrendPageState extends ConsumerState { + int _period = 7; + + @override Widget build(BuildContext context) { + final labels = {'blood_pressure': '血压趋势', 'heart_rate': '心率趋势', 'glucose': '血糖趋势', 'spo2': '血氧趋势', 'weight': '体重趋势'}; + final service = ref.watch(healthServiceProvider); + + return Scaffold( + appBar: AppBar(title: Text(labels[widget.metricType] ?? '趋势图表')), + body: Column(children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + _TimeChip(label: '7天', selected: _period == 7, onTap: () => setState(() => _period = 7)), + const SizedBox(width: 8), _TimeChip(label: '30天', selected: _period == 30, onTap: () => setState(() => _period = 30)), + const SizedBox(width: 8), _TimeChip(label: '90天', selected: _period == 90, onTap: () => setState(() => _period = 90)), + ]), + ), + Expanded(child: FutureBuilder>>( + future: service.getTrend(widget.metricType, period: _period), + builder: (ctx, snap) { + if (snap.connectionState == ConnectionState.waiting) return const Center(child: CircularProgressIndicator()); + if (!snap.hasData || snap.data!.isEmpty) { + return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.show_chart, size: 64, color: Colors.grey[300]), + const SizedBox(height: 12), Text('暂无足够数据', style: Theme.of(context).textTheme.bodyMedium), + ])); + } + final records = snap.data!; + return ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 16), + itemCount: records.length, + itemBuilder: (ctx, i) { + final r = records[i]; + String value; + if (widget.metricType == 'blood_pressure') { + value = '${r['systolic'] ?? '--'}/${r['diastolic'] ?? '--'} mmHg'; + } else { + value = '${r['value'] ?? '--'}'; + } + final isAbnormal = r['isAbnormal'] == true; + final date = r['recordedAt'] != null ? DateTime.parse(r['recordedAt']).toLocal().toString().substring(0, 16) : '--'; + return ListTile( + title: Text(value, style: TextStyle(fontSize: 16, color: isAbnormal ? const Color(0xFFE53935) : null)), + subtitle: Text(date, style: const TextStyle(fontSize: 14, color: Color(0xFF999999))), + trailing: isAbnormal ? const Icon(Icons.warning_amber, color: Color(0xFFE53935), size: 20) : const Icon(Icons.check_circle, color: Color(0xFF43A047), size: 20), + ); + }, + ); + }, + )), + ]), + ); + } +} + +class _TimeChip extends StatelessWidget { + final String label; final bool selected; final VoidCallback onTap; + const _TimeChip({required this.label, required this.selected, required this.onTap}); + @override Widget build(BuildContext context) => GestureDetector( + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + decoration: BoxDecoration(color: selected ? const Color(0xFF635BFF) : Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: const Color(0xFF635BFF))), + child: Text(label, style: TextStyle(fontSize: 14, color: selected ? Colors.white : const Color(0xFF635BFF))), + ), + ); +} diff --git a/health_app/lib/pages/consultation/consultation_pages.dart b/health_app/lib/pages/consultation/consultation_pages.dart new file mode 100644 index 0000000..cdfe668 --- /dev/null +++ b/health_app/lib/pages/consultation/consultation_pages.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../providers/data_providers.dart'; + +/// 医生列表页 +class DoctorListPage extends ConsumerWidget { + const DoctorListPage({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) { + final doctors = ref.watch(doctorListProvider); + return Scaffold( + appBar: AppBar(title: const Text('选择医生')), + body: doctors.when( + data: (list) { + if (list.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.person_search, size: 64, color: Colors.grey[300]), + const SizedBox(height: 12), + Text('暂无可用医生', style: Theme.of(context).textTheme.bodyMedium), + ], + ), + ); + } + return ListView.builder( + itemCount: list.length, + itemBuilder: (ctx, i) { + final d = list[i]; + return Card( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row(children: [ + CircleAvatar( + radius: 28, + backgroundColor: const Color(0xFFEDEBFF), + child: Text( + (d['name'] as String?)?.isNotEmpty == true ? d['name']![0] : '?', + style: const TextStyle(fontSize: 22, color: Color(0xFF635BFF)), + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Text(d['name'] ?? '', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)), + const SizedBox(width: 8), + Text(d['title'] ?? '', style: const TextStyle(fontSize: 14, color: Color(0xFF666666))), + ]), + const SizedBox(height: 4), + Text(d['department'] ?? '', style: const TextStyle(fontSize: 14, color: Color(0xFF635BFF))), + const SizedBox(height: 2), + Text(d['introduction'] ?? '', style: const TextStyle(fontSize: 14, color: Color(0xFF999999))), + ], + ), + ), + ElevatedButton( + onPressed: () async { + // TODO: 点击「咨询」创建问诊并跳转聊天页 + }, + child: const Text('咨询'), + ), + ]), + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, _) => Center( + child: Text('加载失败', style: Theme.of(context).textTheme.bodyMedium), + ), + ), + ); + } +} + +/// 问诊对话页 +class DoctorChatPage extends ConsumerWidget { + final String id; + const DoctorChatPage({super.key, required this.id}); + @override + Widget build(BuildContext context, WidgetRef ref) => Scaffold( + appBar: AppBar(title: const Text('问诊对话')), + body: Center( + child: Text('问诊 #$id', style: Theme.of(context).textTheme.bodyLarge), + ), + ); +} diff --git a/health_app/lib/pages/home/home_page.dart b/health_app/lib/pages/home/home_page.dart new file mode 100644 index 0000000..481564e --- /dev/null +++ b/health_app/lib/pages/home/home_page.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../providers/chat_provider.dart'; +import '../../widgets/agent_bar.dart'; +import '../../widgets/health_drawer.dart'; +import 'widgets/chat_messages_view.dart'; + +/// 首页——主界面 +class HomePage extends ConsumerStatefulWidget { + const HomePage({super.key}); + @override + ConsumerState createState() => _HomePageState(); +} + +class _HomePageState extends ConsumerState { + final _textCtrl = TextEditingController(); + final _scrollCtrl = ScrollController(); + bool _taskCardsExpanded = true; + + @override + void dispose() { + _textCtrl.dispose(); + _scrollCtrl.dispose(); + super.dispose(); + } + + void _sendMessage() { + final text = _textCtrl.text.trim(); + if (text.isEmpty) return; + _textCtrl.clear(); + ref.read(chatProvider.notifier).sendMessage(text); + } + + @override + Widget build(BuildContext context) { + final chatState = ref.watch(chatProvider); + final selectedAgent = ref.watch(selectedAgentProvider); + + return Scaffold( + drawer: const HealthDrawer(), + body: SafeArea( + child: Column(children: [ + _buildHeader(context), + if (_taskCardsExpanded) _buildTaskCards(chatState), + Expanded(child: ChatMessagesView(scrollCtrl: _scrollCtrl, messages: chatState.messages)), + if (selectedAgent != null) _buildAgentPanel(context, selectedAgent), + const AgentBar(), + _buildInputBar(), + ]), + ), + ); + } + + Widget _buildHeader(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row(children: [ + Builder(builder: (ctx) => IconButton( + icon: const Icon(Icons.menu, size: 24), + onPressed: () => Scaffold.of(ctx).openDrawer(), + )), + const Spacer(), + Text('健康管家', style: Theme.of(context).textTheme.titleLarge), + const Spacer(), + const SizedBox(width: 48), + ]), + ); + } + + Widget _buildTaskCards(ChatState chatState) { + return GestureDetector( + onVerticalDragUpdate: (d) { if (d.delta.dy < -10) setState(() => _taskCardsExpanded = false); }, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFFEDEBFF), + borderRadius: BorderRadius.circular(12), + ), + child: Column(children: [ + Row(children: [ + const Icon(Icons.wb_sunny, size: 18, color: Color(0xFF635BFF)), + const SizedBox(width: 8), + const Text('早上好!', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)), + const Spacer(), + GestureDetector( + onTap: () => setState(() => _taskCardsExpanded = false), + child: const Icon(Icons.keyboard_arrow_up, size: 20, color: Color(0xFF666666)), + ), + ]), + if (chatState.noticeText != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(chatState.noticeText!, style: const TextStyle(fontSize: 14, color: Color(0xFF666666))), + ), + ]), + ), + ); + } + + Widget _buildAgentPanel(BuildContext context, ActiveAgent agent) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.vertical(top: Radius.circular(16)), + boxShadow: [BoxShadow(color: const Color(0xFF635BFF).withAlpha(20), blurRadius: 8, offset: const Offset(0, -2))], + ), + child: Column(mainAxisSize: MainAxisSize.min, children: _getAgentButtons(agent)), + ); + } + + List _getAgentButtons(ActiveAgent agent) { + final buttons = []; + if (agent == ActiveAgent.health) { + buttons.add(_panelBtn('手动录入血压', Icons.favorite)); + buttons.add(_panelBtn('手动录入血糖', Icons.bloodtype)); + buttons.add(_panelBtn('手动录入心率', Icons.monitor_heart)); + } else if (agent == ActiveAgent.diet) { + buttons.add(_panelBtn('拍照', Icons.camera_alt)); + buttons.add(_panelBtn('上传照片', Icons.photo_library)); + } else if (agent == ActiveAgent.medication) { + buttons.add(_panelBtn('用药管理', Icons.medication)); + buttons.add(_panelBtn('用药提醒', Icons.alarm)); + } else if (agent == ActiveAgent.consultation) { + buttons.add(_panelBtn('找医生', Icons.person_search)); + } else if (agent == ActiveAgent.exercise) { + buttons.add(_panelBtn('查看本周计划', Icons.calendar_view_week)); + buttons.add(_panelBtn('创建新计划', Icons.add_circle_outline)); + } + return buttons; + } + + Widget _panelBtn(String label, IconData icon) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: () {}, + icon: Icon(icon, size: 20), + label: Text(label), + style: OutlinedButton.styleFrom( + foregroundColor: const Color(0xFF635BFF), + side: const BorderSide(color: Color(0xFF635BFF)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), + padding: const EdgeInsets.symmetric(vertical: 12), + ), + ), + ), + ); + } + + Widget _buildInputBar() { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.white, + border: Border(top: BorderSide(color: Colors.grey.shade200)), + ), + child: Row(children: [ + IconButton(icon: const Icon(Icons.attach_file, size: 24, color: Color(0xFF666666)), onPressed: () {}), + Expanded( + child: TextField( + controller: _textCtrl, + decoration: const InputDecoration(hintText: '输入你想说的...', contentPadding: EdgeInsets.symmetric(horizontal: 12), border: InputBorder.none), + onSubmitted: (_) => _sendMessage(), + ), + ), + IconButton(icon: const Icon(Icons.send, size: 24, color: Color(0xFF635BFF)), onPressed: _sendMessage), + ]), + ); + } +} diff --git a/health_app/lib/pages/home/widgets/chat_messages_view.dart b/health_app/lib/pages/home/widgets/chat_messages_view.dart new file mode 100644 index 0000000..8f63405 --- /dev/null +++ b/health_app/lib/pages/home/widgets/chat_messages_view.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../../providers/chat_provider.dart'; + +/// 对话消息列表 +class ChatMessagesView extends ConsumerWidget { + final ScrollController scrollCtrl; + final List messages; + + const ChatMessagesView({super.key, required this.scrollCtrl, required this.messages}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final chatState = ref.watch(chatProvider); + + if (messages.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.chat_bubble_outline, size: 48, color: Colors.grey[300]), + const SizedBox(height: 12), + Text('开始和 AI 健康管家对话吧', style: Theme.of(context).textTheme.bodyMedium), + ], + ), + ); + } + + return ListView.builder( + controller: scrollCtrl, + reverse: true, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + itemCount: messages.length, + itemBuilder: (context, index) { + final msg = messages[messages.length - 1 - index]; + return _buildMessageBubble(context, msg, chatState); + }, + ); + } + + Widget _buildMessageBubble(BuildContext context, ChatMessage msg, ChatState chatState) { + final isUser = msg.isUser; + return Align( + alignment: isUser ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.only(bottom: 12), + constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.78), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: isUser ? const Color(0xFF635BFF) : Colors.white, + borderRadius: BorderRadius.circular(16), + border: isUser ? null : const Border(left: BorderSide(color: Color(0xFF635BFF), width: 3)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isUser && chatState.isStreaming && msg.content.isEmpty) + _buildThinkingIndicator() + else + Text( + msg.content.isEmpty && !isUser ? '...' : msg.content, + style: TextStyle(fontSize: 16, color: isUser ? Colors.white : const Color(0xFF1A1A1A)), + ), + if (!isUser && msg.content.isNotEmpty && !chatState.isStreaming) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + 'AI 健康管家 · 仅供参考', + style: TextStyle(fontSize: 12, color: Colors.grey[400]), + ), + ), + ], + ), + ), + ); + } + + Widget _buildThinkingIndicator() { + return const Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)), + SizedBox(width: 8), + Text('思考中...', style: TextStyle(fontSize: 14, color: Color(0xFF999999))), + ], + ); + } +} diff --git a/health_app/lib/pages/medication/medication_list_page.dart b/health_app/lib/pages/medication/medication_list_page.dart new file mode 100644 index 0000000..35bf7bc --- /dev/null +++ b/health_app/lib/pages/medication/medication_list_page.dart @@ -0,0 +1,80 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../providers/data_providers.dart'; + +/// 用药列表页 +class MedicationListPage extends ConsumerWidget { + const MedicationListPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) { + final meds = ref.watch(medicationListProvider); + return Scaffold( + appBar: AppBar(title: const Text('我的用药')), + body: meds.when( + data: (list) { + if (list.isEmpty) return _empty(context); + return ListView.builder( + itemCount: list.length, + itemBuilder: (ctx, i) { + final m = list[i]; + final times = (m['timeOfDay'] as List?)?.cast() ?? []; + return Card( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: ListTile( + leading: const Icon(Icons.medication, color: Color(0xFF635BFF)), + title: Text('${m['name']} ${m['dosage'] ?? ''}', style: const TextStyle(fontSize: 16)), + subtitle: Text('每天 ${times.join("、")}', style: const TextStyle(fontSize: 14, color: Color(0xFF666666))), + trailing: IconButton(icon: const Icon(Icons.check_circle_outline, color: Color(0xFF43A047)), onPressed: () async { + await ref.read(medicationServiceProvider).confirm(m['id']); + ref.invalidate(medicationListProvider); + }), + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, _) => _empty(context), + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () => context.push('/medications/add').then((_) => ref.invalidate(medicationListProvider)), + icon: const Icon(Icons.add), label: const Text('添加药品'), + ), + ); + } + Widget _empty(BuildContext context) => Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.medication, size: 64, color: Colors.grey[300]), + const SizedBox(height: 12), Text('暂无用药计划', style: Theme.of(context).textTheme.bodyMedium), + const SizedBox(height: 8), Text('可通过 AI 对话或手动添加', style: Theme.of(context).textTheme.labelMedium), + ])); +} + +/// 编辑用药页 +class MedicationEditPage extends ConsumerStatefulWidget { + final String? id; + const MedicationEditPage({super.key, this.id}); + @override ConsumerState createState() => _MedicationEditPageState(); +} +class _MedicationEditPageState extends ConsumerState { + final _nameCtrl = TextEditingController(); final _dosageCtrl = TextEditingController(); final _timeCtrl = TextEditingController(); + @override void dispose() { _nameCtrl.dispose(); _dosageCtrl.dispose(); _timeCtrl.dispose(); super.dispose(); } + + Future _save() async { + await ref.read(medicationServiceProvider).create({ + 'name': _nameCtrl.text, 'dosage': _dosageCtrl.text, + 'frequency': 'Daily', 'timeOfDay': [if (_timeCtrl.text.isNotEmpty) _timeCtrl.text], + 'source': 'Manual', 'startDate': DateTime.now().toIso8601String().substring(0, 10), + }); + if (mounted) context.pop(); + } + + @override Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('添加药品')), + body: ListView(padding: const EdgeInsets.all(16), children: [ + TextField(controller: _nameCtrl, decoration: const InputDecoration(labelText: '药品名称', hintText: '如:阿司匹林')), + const SizedBox(height: 16), TextField(controller: _dosageCtrl, decoration: const InputDecoration(labelText: '剂量', hintText: '如:100mg')), + const SizedBox(height: 16), TextField(controller: _timeCtrl, decoration: const InputDecoration(labelText: '服药时间', hintText: '如:08:00:00')), + const SizedBox(height: 32), SizedBox(width: double.infinity, height: 48, child: ElevatedButton(onPressed: _save, child: const Text('保存'))), + ]), + ); +} diff --git a/health_app/lib/pages/profile/profile_page.dart b/health_app/lib/pages/profile/profile_page.dart new file mode 100644 index 0000000..d54e73e --- /dev/null +++ b/health_app/lib/pages/profile/profile_page.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../providers/auth_provider.dart'; + +/// 个人中心页面 +class ProfilePage extends ConsumerWidget { + const ProfilePage({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final auth = ref.watch(authProvider); + final user = auth.user; + + return Scaffold( + appBar: AppBar(title: const Text('个人中心')), + body: ListView( + children: [ + // 头像区 + Container( + padding: const EdgeInsets.all(24), + color: const Color(0xFFEDEBFF), + child: Column( + children: [ + CircleAvatar( + radius: 40, + backgroundColor: const Color(0xFF635BFF), + child: Text( + (user?.name ?? '?')[0], + style: const TextStyle(fontSize: 32, color: Colors.white), + ), + ), + const SizedBox(height: 12), + Text(user?.name ?? '未设置', style: Theme.of(context).textTheme.titleLarge), + const SizedBox(height: 4), + Text(user?.phone ?? '', style: Theme.of(context).textTheme.bodyMedium), + ], + ), + ), + const SizedBox(height: 8), + _MenuItem(icon: Icons.person, title: '编辑资料', onTap: () => context.push('/profile/edit')), + _MenuItem(icon: Icons.folder, title: '健康档案', onTap: () => context.push('/health-archive')), + _MenuItem(icon: Icons.devices, title: '设备管理', onTap: () {}), + const Divider(), + _MenuItem(icon: Icons.settings, title: '设置', onTap: () => context.push('/settings')), + _MenuItem(icon: Icons.info, title: '关于', onTap: () => context.push('/page/about')), + const Divider(), + _MenuItem( + icon: Icons.logout, title: '退出登录', textColor: const Color(0xFFE53935), + onTap: () async { + final ok = await showDialog(context: context, builder: (ctx) => AlertDialog( + title: const Text('退出登录'), content: const Text('确定退出?'), + actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), + TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定'))])); + if (ok == true) { await ref.read(authProvider.notifier).logout(); if (context.mounted) context.go('/login'); } + }, + ), + ], + ), + ); + } +} + +class _MenuItem extends StatelessWidget { + final IconData icon; final String title; final VoidCallback onTap; final Color? textColor; + const _MenuItem({required this.icon, required this.title, required this.onTap, this.textColor}); + @override + Widget build(BuildContext context) => ListTile(leading: Icon(icon, color: const Color(0xFF666666)), title: Text(title, style: TextStyle(fontSize: 16, color: textColor ?? const Color(0xFF1A1A1A))), trailing: const Icon(Icons.chevron_right, size: 20), onTap: onTap); +} diff --git a/health_app/lib/pages/remaining_pages.dart b/health_app/lib/pages/remaining_pages.dart new file mode 100644 index 0000000..57604a6 --- /dev/null +++ b/health_app/lib/pages/remaining_pages.dart @@ -0,0 +1,196 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../providers/data_providers.dart'; + +/// 饮食记录列表 +class DietRecordListPage extends ConsumerWidget { + const DietRecordListPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) { + final service = ref.watch(dietServiceProvider); + return Scaffold( + appBar: AppBar(title: const Text('饮食记录')), + body: FutureBuilder>>( + future: service.getRecords(), + builder: (ctx, snap) { + if (snap.connectionState == ConnectionState.waiting) return const Center(child: CircularProgressIndicator()); + if (!snap.hasData || snap.data!.isEmpty) return _empty(context, '饮食记录', '暂无饮食记录,可通过「拍饮食」录入'); + return ListView.builder( + itemCount: snap.data!.length, + itemBuilder: (ctx, i) { + final d = snap.data![i]; + final items = (d['foodItems'] as List?)?.cast>() ?? []; + return Card( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: ListTile( + title: Text('${d['mealType'] ?? ''} ${d['totalCalories'] ?? 0}千卡'), + subtitle: Text(items.map((f) => f['name']).join(' | ')), + trailing: _starWidget(d['healthScore']), + ), + ); + }, + ); + }, + ), + ); + } + Widget _starWidget(dynamic score) { + final s = score is int ? score : 3; + return Row(mainAxisSize: MainAxisSize.min, children: List.generate(5, (i) => Icon(Icons.star, size: 16, color: i < s ? const Color(0xFFF9A825) : Colors.grey[300]))); + } +} + +/// 运动计划页 +class ExercisePlanPage extends ConsumerWidget { + const ExercisePlanPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) { + final plan = ref.watch(currentExercisePlanProvider); + return Scaffold( + appBar: AppBar(title: const Text('运动计划')), + body: plan.when( + data: (data) { + if (data == null) return _empty(context, '运动计划', '暂无运动计划'); + final items = (data['items'] as List?)?.cast>() ?? []; + final weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']; + return ListView.builder( + itemCount: items.length, + itemBuilder: (ctx, i) { + final item = items[i]; + final day = item['dayOfWeek'] is int ? item['dayOfWeek'] as int : i; + final isRest = item['isRestDay'] == true; + final isDone = item['isCompleted'] == true; + return ListTile( + leading: Icon(isDone ? Icons.check_circle : Icons.circle_outlined, color: isDone ? const Color(0xFF43A047) : Colors.grey), + title: Text('${weekDays[day]} ${isRest ? '休息日' : '${item['exerciseType']} ${item['durationMinutes']}分钟'}'), + trailing: isDone ? const Text('✅ 已完成', style: TextStyle(fontSize: 14, color: Color(0xFF43A047))) : const Text('待完成', style: TextStyle(fontSize: 14, color: Color(0xFF999999))), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (_, _) => _empty(context, '运动计划', '暂无运动计划'), + ), + ); + } +} + +/// 复查列表 +class FollowUpListPage extends ConsumerWidget { + const FollowUpListPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) => _empty(context, '复查随访', '暂无复查安排'); +} + +/// 健康档案 +class HealthArchivePage extends ConsumerWidget { + const HealthArchivePage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) { + final service = ref.watch(userServiceProvider); + return Scaffold( + appBar: AppBar(title: const Text('健康档案')), + body: FutureBuilder?>( + future: service.getHealthArchive(), + builder: (ctx, snap) { + if (snap.connectionState == ConnectionState.waiting) return const Center(child: CircularProgressIndicator()); + final data = snap.data; + if (data == null || data.isEmpty) return _empty(context, '暂无健康档案', '可通过 AI 对话或手动填写'); + return ListView( + padding: const EdgeInsets.all(16), + children: [ + _Section(title: '基本信息', children: [ + _Field('诊断', data['diagnosis']), _Field('手术类型', data['surgeryType']), + _Field('手术日期', data['surgeryDate']), + ]), + _Section(title: '病史与限制', children: [ + _Field('过敏史', _listStr(data['allergies'])), + _Field('饮食限制', _listStr(data['dietRestrictions'])), + _Field('慢性病史', _listStr(data['chronicDiseases'])), + _Field('家族病史', data['familyHistory']), + ]), + ], + ); + }, + ), + ); + } + String _listStr(dynamic list) => list is List ? list.join('、') : '--'; +} + +class _Section extends StatelessWidget { + final String title; final List children; + const _Section({required this.title, required this.children}); + @override Widget build(BuildContext context) => Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Padding(padding: const EdgeInsets.only(bottom: 8, top: 16), child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0xFF1A1A1A)))), + ...children, + ]); +} + +class _Field extends StatelessWidget { + final String label; final String? value; + const _Field(this.label, this.value); + @override Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + SizedBox(width: 80, child: Text('$label:', style: const TextStyle(fontSize: 14, color: Color(0xFF666666)))), + Expanded(child: Text(value ?? '--', style: const TextStyle(fontSize: 14, color: Color(0xFF1A1A1A)))), + ]), + ); +} + +/// 编辑资料 +class EditProfilePage extends ConsumerStatefulWidget { + const EditProfilePage({super.key}); + @override ConsumerState createState() => _EditProfilePageState(); +} +class _EditProfilePageState extends ConsumerState { + final _nameCtrl = TextEditingController(); final _genderCtrl = TextEditingController(); final _birthCtrl = TextEditingController(); + @override void dispose() { _nameCtrl.dispose(); _genderCtrl.dispose(); _birthCtrl.dispose(); super.dispose(); } + @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) => _load()); } + void _load() async { + final p = await ref.read(userServiceProvider).getProfile(); + if (p != null && mounted) { + setState(() { _nameCtrl.text = p['name'] ?? ''; _genderCtrl.text = p['gender'] ?? ''; _birthCtrl.text = p['birthDate'] ?? ''; }); + } + } + Future _save() async { + await ref.read(userServiceProvider).updateProfile(name: _nameCtrl.text, gender: _genderCtrl.text, birthDate: _birthCtrl.text); + if (mounted) Navigator.pop(context); + } + @override Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('编辑资料')), + body: ListView(padding: const EdgeInsets.all(16), children: [ + TextField(controller: _nameCtrl, decoration: const InputDecoration(labelText: '姓名')), + const SizedBox(height: 16), TextField(controller: _genderCtrl, decoration: const InputDecoration(labelText: '性别')), + const SizedBox(height: 16), TextField(controller: _birthCtrl, decoration: const InputDecoration(labelText: '出生日期', hintText: 'YYYY-MM-DD')), + const SizedBox(height: 32), SizedBox(width: double.infinity, child: ElevatedButton(onPressed: _save, child: const Text('保存'))), + ]), + ); +} + +/// 健康日历 +class HealthCalendarPage extends ConsumerWidget { + const HealthCalendarPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) => _empty(context, '健康日历', '暂无数据'); +} + +/// 静态文本页 +class StaticTextPage extends ConsumerWidget { + final String type; + const StaticTextPage({super.key, required this.type}); + @override Widget build(BuildContext context, WidgetRef ref) { + final titles = {'privacy': '隐私政策', 'terms': '服务协议', 'about': '关于'}; + return Scaffold(appBar: AppBar(title: Text(titles[type] ?? '')), body: const Center(child: Padding(padding: EdgeInsets.all(16), child: Text('内容后期填充', style: TextStyle(color: Color(0xFF999999)))))); + } +} + +/// 设备管理(占位) +class DeviceManagementPage extends ConsumerWidget { + const DeviceManagementPage({super.key}); + @override Widget build(BuildContext context, WidgetRef ref) => _empty(context, '设备管理', '暂无绑定设备'); +} + +Widget _empty(BuildContext context, String title, String subtitle) => Scaffold( + appBar: AppBar(title: Text(title)), + body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.inbox_outlined, size: 64, color: Colors.grey[300]), + const SizedBox(height: 12), Text(subtitle, style: Theme.of(context).textTheme.bodyMedium), + ])), +); diff --git a/health_app/lib/pages/report/report_pages.dart b/health_app/lib/pages/report/report_pages.dart new file mode 100644 index 0000000..4eb7649 --- /dev/null +++ b/health_app/lib/pages/report/report_pages.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +/// 报告列表页 +class ReportListPage extends ConsumerWidget { + const ReportListPage({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) => _emptyPage(context, '暂无报告', '可到「看报告」上传'); +} + +/// 报告详情页 +class ReportDetailPage extends ConsumerWidget { + final String id; + const ReportDetailPage({super.key, required this.id}); + @override + Widget build(BuildContext context, WidgetRef ref) => _emptyPage(context, '报告详情', '报告 #$id'); +} + +Widget _emptyPage(BuildContext context, String title, String subtitle) => Scaffold( + appBar: AppBar(title: Text(title)), + body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.description, size: 64, color: Colors.grey[300]), + const SizedBox(height: 12), Text(subtitle, style: Theme.of(context).textTheme.bodyMedium), + ])), +); diff --git a/health_app/lib/pages/settings/settings_pages.dart b/health_app/lib/pages/settings/settings_pages.dart new file mode 100644 index 0000000..1ed4ee3 --- /dev/null +++ b/health_app/lib/pages/settings/settings_pages.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../../providers/auth_provider.dart'; + +/// 设置页 +class SettingsPage extends ConsumerWidget { + const SettingsPage({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) => Scaffold( + appBar: AppBar(title: const Text('设置')), + body: ListView(children: [ + _SetItem(icon: Icons.shield, title: '隐私保护中心', onTap: () => context.push('/page/privacy')), + _SetItem(icon: Icons.notifications, title: '通知偏好', onTap: () => context.push('/settings/notifications')), + _SetItem(icon: Icons.text_fields, title: '字体大小', trailing: _FontSlider()), + _SetItem(icon: Icons.article, title: '协议与公告', onTap: () => context.push('/page/terms')), + _SetItem(icon: Icons.info, title: '关于', onTap: () => context.push('/page/about')), + const Divider(), + _SetItem(icon: Icons.logout, title: '退出登录', textColor: const Color(0xFFE53935), onTap: () async { + final ok = await showDialog(context: context, builder: (ctx) => AlertDialog( + title: const Text('退出登录'), content: const Text('确定退出?'), + actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定'))])); + if (ok == true) { await ref.read(authProvider.notifier).logout(); if (context.mounted) context.go('/login'); } + }), + ]), + ); +} + +class _SetItem extends StatelessWidget { + final IconData icon; final String title; final VoidCallback? onTap; final Widget? trailing; final Color? textColor; + const _SetItem({required this.icon, required this.title, this.onTap, this.trailing, this.textColor}); + @override + Widget build(BuildContext context) => ListTile(leading: Icon(icon, color: const Color(0xFF666666)), title: Text(title, style: TextStyle(fontSize: 16, color: textColor)), trailing: trailing ?? const Icon(Icons.chevron_right, size: 20), onTap: onTap); +} + +class _FontSlider extends StatefulWidget { + @override State<_FontSlider> createState() => _FontSliderState(); +} +class _FontSliderState extends State<_FontSlider> { + double _value = 1.0; + @override Widget build(BuildContext context) => SizedBox(width: 120, child: Slider(value: _value, min: 0.8, max: 1.6, divisions: 8, label: '${_value.toStringAsFixed(1)}x', onChanged: (v) => setState(() => _value = v))); +} + +/// 通知偏好页 +class NotificationPrefsPage extends ConsumerWidget { + const NotificationPrefsPage({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) => Scaffold( + appBar: AppBar(title: const Text('通知偏好')), + body: ListView(children: [ + _SwitchTile(icon: Icons.medication, title: '用药提醒'), + _SwitchTile(icon: Icons.calendar_month, title: '复查提醒'), + _SwitchTile(icon: Icons.chat, title: '医生回复'), + _SwitchTile(icon: Icons.warning_amber, title: '异常警告'), + ]), + ); +} + +class _SwitchTile extends StatefulWidget { + final IconData icon; final String title; + const _SwitchTile({required this.icon, required this.title}); + @override State<_SwitchTile> createState() => _SwitchTileState(); +} +class _SwitchTileState extends State<_SwitchTile> { + bool _on = true; + @override Widget build(BuildContext context) => SwitchListTile(secondary: Icon(widget.icon), title: Text(widget.title), value: _on, onChanged: (v) => setState(() => _on = v)); +} diff --git a/health_app/lib/providers/auth_provider.dart b/health_app/lib/providers/auth_provider.dart new file mode 100644 index 0000000..deb8148 --- /dev/null +++ b/health_app/lib/providers/auth_provider.dart @@ -0,0 +1,139 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:dio/dio.dart'; +import '../core/api_client.dart'; +import '../core/secure_storage.dart'; + +/// 用户简要信息 +class UserInfo { + final String id; + final String phone; + final String? name; + final String? avatarUrl; + + UserInfo({required this.id, required this.phone, this.name, this.avatarUrl}); +} + +/// 认证状态 +class AuthState { + final UserInfo? user; + final bool isLoggedIn; + final bool isLoading; + + const AuthState({this.user, this.isLoggedIn = false, this.isLoading = true}); +} + +/// 认证 Provider +final authProvider = NotifierProvider(AuthNotifier.new); + +final secureStorageProvider = Provider((ref) => SecureStorage()); + +final apiClientProvider = Provider((ref) { + return ApiClient(storage: ref.watch(secureStorageProvider)); +}); + +class AuthNotifier extends Notifier { + @override + AuthState build() { + _checkAuth(); + return const AuthState(isLoading: true); + } + + Future _checkAuth() async { + final storage = ref.read(secureStorageProvider); + final refresh = await storage.readRefreshToken(); + if (refresh == null) { + state = const AuthState(isLoggedIn: false, isLoading: false); + return; + } + + try { + final response = await Dio(BaseOptions(baseUrl: baseUrl)) + .post('/api/auth/refresh', data: {'refreshToken': refresh}); + final data = response.data['data']; + if (data != null) { + await storage.writeAccessToken(data['accessToken']); + await storage.writeRefreshToken(data['refreshToken']); + state = AuthState( + isLoggedIn: true, + isLoading: false, + user: UserInfo(id: '', phone: '', name: data['user']?['name']), + ); + _loadProfile(); + } else { + state = const AuthState(isLoggedIn: false, isLoading: false); + } + } catch (_) { + state = const AuthState(isLoggedIn: false, isLoading: false); + } + } + + Future _loadProfile() async { + try { + final api = ref.read(apiClientProvider); + final response = await api.get('/api/user/profile'); + final user = response.data['data']; + if (user != null) { + state = AuthState( + isLoggedIn: true, + isLoading: false, + user: UserInfo( + id: user['id'] ?? '', + phone: user['phone'] ?? '', + name: user['name'], + avatarUrl: user['avatarUrl'], + ), + ); + } + } catch (_) {} + } + + /// 发送验证码,返回 (error, devCode) + Future<({String? error, String? devCode})> sendSms(String phone) async { + try { + final api = ref.read(apiClientProvider); + final response = await api.post('/api/auth/send-sms', data: {'phone': phone}); + final devCode = response.data['data']?['devCode'] as String?; + return (error: null, devCode: devCode); + } catch (e) { + return (error: '发送失败: $e', devCode: null); + } + } + + /// 验证码登录 + Future login(String phone, String code) async { + try { + final api = ref.read(apiClientProvider); + final response = await api.post('/api/auth/login', data: {'phone': phone, 'smsCode': code}); + final data = response.data['data']; + if (data == null) return response.data['message'] ?? '登录失败'; + + await api.saveTokens(data['accessToken'], data['refreshToken']); + final user = data['user']; + state = AuthState( + isLoggedIn: true, + isLoading: false, + user: UserInfo( + id: user['id'] ?? '', + phone: user['phone'] ?? '', + name: user['name'], + avatarUrl: user['avatarUrl'], + ), + ); + return null; + } catch (e) { + return '登录失败: $e'; + } + } + + /// 登出 + Future logout() async { + final api = ref.read(apiClientProvider); + final storage = ref.read(secureStorageProvider); + final refresh = await storage.readRefreshToken(); + if (refresh != null) { + try { await api.post('/api/auth/logout', data: {'refreshToken': refresh}); } catch (_) {} + } + await api.clearTokens(); + state = const AuthState(isLoggedIn: false, isLoading: false); + } +} diff --git a/health_app/lib/providers/chat_provider.dart b/health_app/lib/providers/chat_provider.dart new file mode 100644 index 0000000..432fc87 --- /dev/null +++ b/health_app/lib/providers/chat_provider.dart @@ -0,0 +1,159 @@ +import 'dart:async'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'auth_provider.dart'; +import '../utils/sse_handler.dart'; + +class ChatMessage { + final String id; + final String role; + String content; + final DateTime createdAt; + ChatMessage( + {required this.id, + required this.role, + required this.content, + required this.createdAt}); + bool get isUser => role == 'user'; +} + +enum ActiveAgent { default_, consultation, health, diet, medication, report, exercise } + +class ChatState { + final ActiveAgent activeAgent; + final List messages; + final String? conversationId; + final bool isStreaming; + final String? noticeText; + const ChatState({ + this.activeAgent = ActiveAgent.default_, + this.messages = const [], + this.conversationId, + this.isStreaming = false, + this.noticeText, + }); + ChatState copyWith({ActiveAgent? activeAgent, List? messages, + String? conversationId, bool? isStreaming, String? noticeText, + bool clearNotice = false}) => + ChatState( + activeAgent: activeAgent ?? this.activeAgent, + messages: messages ?? this.messages, + conversationId: conversationId ?? this.conversationId, + isStreaming: isStreaming ?? this.isStreaming, + noticeText: clearNotice ? null : (noticeText ?? this.noticeText), + ); +} + +class SelectedAgentNotifier extends Notifier { + @override + ActiveAgent? build() => null; + void select(ActiveAgent? a) => state = a; +} + +final selectedAgentProvider = + NotifierProvider(SelectedAgentNotifier.new); +final chatProvider = NotifierProvider(ChatNotifier.new); + +class ChatNotifier extends Notifier { + StreamSubscription>? _subscription; + + @override + ChatState build() => const ChatState(); + + void setAgent(ActiveAgent a) { + _subscription?.cancel(); + state = state.activeAgent == a ? const ChatState() : ChatState(activeAgent: a); + } + + Future sendMessage(String text) async { + if (text.trim().isEmpty || state.isStreaming) return; + + final userMsg = ChatMessage( + id: '${DateTime.now().millisecondsSinceEpoch}', + role: 'user', + content: text, + createdAt: DateTime.now(), + ); + state = state.copyWith( + messages: [...state.messages, userMsg], isStreaming: true); + + final aiMsg = ChatMessage( + id: '${DateTime.now().millisecondsSinceEpoch}_ai', + role: 'assistant', + content: '', + createdAt: DateTime.now(), + ); + + try { + final token = await ref.read(apiClientProvider).accessToken; + if (token == null) { + _addError(aiMsg, '未登录,请重新登录'); + return; + } + + final agentPath = + state.activeAgent.name.replaceFirst('default_', 'default'); + final stream = SseHandler.connect( + agentType: agentPath, + message: text, + conversationId: state.conversationId, + token: token, + ); + + await for (final event in stream) { + _processEvent(event, aiMsg); + } + } catch (e) { + _addError(aiMsg, '网络异常,请稍后重试'); + } + } + + void _addError(ChatMessage aiMsg, String errorText) { + state = state.copyWith( + messages: [ + ...state.messages, + ChatMessage( + id: 'err_${DateTime.now().millisecondsSinceEpoch}', + role: 'assistant', + content: errorText, + createdAt: DateTime.now(), + ), + ], + isStreaming: false, + clearNotice: true, + ); + } + + void _processEvent(Map j, ChatMessage aiMsg) { + final a = j['action'] as String?; + switch (a) { + case 'conversation_id': + state = state.copyWith(conversationId: j['data']?.toString()); + case 'answer': + aiMsg.content += (j['data'] as String?) ?? ''; + _update(aiMsg); + case 'notice': + state = state.copyWith(noticeText: j['message'] as String?); + case 'status': + _done(aiMsg); + case 'error': + _done(aiMsg); + } + } + + void _update(ChatMessage m) { + final u = state.messages.toList(); + final i = u.indexWhere((x) => x.id == m.id); + if (i >= 0) { + u[i] = m; + } else if (m.content.isNotEmpty) { + u.add(m); + } + state = state.copyWith(messages: u); + } + + void _done(ChatMessage m) { + final u = state.messages.toList(); + if (!u.any((x) => x.id == m.id) && m.content.isNotEmpty) u.add(m); + state = state.copyWith(messages: u, isStreaming: false, clearNotice: true); + } +} diff --git a/health_app/lib/providers/data_providers.dart b/health_app/lib/providers/data_providers.dart new file mode 100644 index 0000000..9e40c4f --- /dev/null +++ b/health_app/lib/providers/data_providers.dart @@ -0,0 +1,58 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'auth_provider.dart'; +import '../services/health_service.dart'; + +/// 健康数据服务 +final healthServiceProvider = Provider((ref) { + return HealthService(ref.watch(apiClientProvider)); +}); + +final userServiceProvider = Provider((ref) { + return UserService(ref.watch(apiClientProvider)); +}); + +final medicationServiceProvider = Provider((ref) { + return MedicationService(ref.watch(apiClientProvider)); +}); + +final dietServiceProvider = Provider((ref) { + return DietService(ref.watch(apiClientProvider)); +}); + +final consultationServiceProvider = Provider((ref) { + return ConsultationService(ref.watch(apiClientProvider)); +}); + +final exerciseServiceProvider = Provider((ref) { + return ExerciseService(ref.watch(apiClientProvider)); +}); + +/// 最新健康数据 Provider +final latestHealthProvider = FutureProvider>((ref) async { + final service = ref.watch(healthServiceProvider); + return service.getLatest(); +}); + +/// 用药列表 Provider +final medicationListProvider = FutureProvider>>((ref) async { + final service = ref.watch(medicationServiceProvider); + return service.getList(); +}); + +/// 医生列表 Provider +final doctorListProvider = FutureProvider>>((ref) async { + final service = ref.watch(consultationServiceProvider); + return service.getDoctors(); +}); + +/// 问诊配额 Provider +final consultationQuotaProvider = FutureProvider>((ref) async { + final service = ref.watch(consultationServiceProvider); + return service.getQuota(); +}); + +/// 当前运动计划 Provider +final currentExercisePlanProvider = FutureProvider?>((ref) async { + final service = ref.watch(exerciseServiceProvider); + return service.getCurrentPlan(); +}); diff --git a/health_app/lib/services/health_service.dart b/health_app/lib/services/health_service.dart new file mode 100644 index 0000000..ece40f4 --- /dev/null +++ b/health_app/lib/services/health_service.dart @@ -0,0 +1,158 @@ +import '../core/api_client.dart'; + +/// 健康数据服务 +class HealthService { + final ApiClient _api; + HealthService(this._api); + + /// 获取各指标最新值 + Future> getLatest() async { + final res = await _api.get('/api/health-records/latest'); + return res.data['data'] ?? {}; + } + + /// 获取趋势数据 + Future>> getTrend(String type, {int period = 7}) async { + final res = await _api.get('/api/health-records/trend', queryParameters: {'type': type, 'period': period}); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } + + /// 获取记录列表 + Future>> getRecords({String? type, int? days}) async { + final params = {}; + if (type != null) params['type'] = type; + if (days != null) params['days'] = days; + final res = await _api.get('/api/health-records', queryParameters: params); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } +} + +/// 用户服务 +class UserService { + final ApiClient _api; + UserService(this._api); + + Future?> getProfile() async { + final res = await _api.get('/api/user/profile'); + return res.data['data']; + } + + Future updateProfile({String? name, String? gender, String? birthDate}) async { + await _api.put('/api/user/profile', data: {'name': name, 'gender': gender, 'birthDate': birthDate}); + } + + Future?> getHealthArchive() async { + final res = await _api.get('/api/user/health-archive'); + return res.data['data']; + } + + Future updateHealthArchive(Map data) async { + await _api.put('/api/user/health-archive', data: data); + } + + Future deleteAccount() async { + await _api.delete('/api/user/account'); + } +} + +/// 用药服务 +class MedicationService { + final ApiClient _api; + MedicationService(this._api); + + Future>> getList() async { + final res = await _api.get('/api/medications'); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } + + Future create(Map data) async { + await _api.post('/api/medications', data: data); + } + + Future update(String id, Map data) async { + await _api.put('/api/medications/$id', data: data); + } + + Future delete(String id) async { + await _api.delete('/api/medications/$id'); + } + + Future confirm(String id) async { + await _api.post('/api/medications/$id/confirm'); + } +} + +/// 饮食服务 +class DietService { + final ApiClient _api; + DietService(this._api); + + Future>> getRecords({String? date, String? mealType}) async { + final params = {}; + if (date != null) params['date'] = date; + if (mealType != null) params['mealType'] = mealType; + final res = await _api.get('/api/diet-records', queryParameters: params); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } + + Future create(Map data) async { + await _api.post('/api/diet-records', data: data); + } +} + +/// 问诊服务 +class ConsultationService { + final ApiClient _api; + ConsultationService(this._api); + + Future>> getDoctors() async { + final res = await _api.get('/doctors'); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } + + Future> getQuota() async { + final res = await _api.get('/user/consultation-quota'); + return res.data['data'] ?? {}; + } + + Future> createConsultation(String doctorId) async { + final res = await _api.post('/consultations', data: {'doctorId': doctorId}); + return res.data['data']; + } + + Future>> getMessages(String consultationId, {String? after}) async { + final params = {}; + if (after != null) params['after'] = after; + final res = await _api.get('/consultations/$consultationId/messages', queryParameters: params); + final list = res.data['data'] as List? ?? []; + return list.cast>(); + } + + Future sendMessage(String consultationId, String content) async { + await _api.post('/consultations/$consultationId/messages', data: {'content': content}); + } +} + +/// 运动服务 +class ExerciseService { + final ApiClient _api; + ExerciseService(this._api); + + Future?> getCurrentPlan() async { + final res = await _api.get('/exercise-plans/current'); + return res.data['data']; + } + + Future createPlan(Map data) async { + await _api.post('/exercise-plans', data: data); + } + + Future checkIn(String itemId) async { + await _api.post('/exercise-plans/items/$itemId/checkin'); + } +} diff --git a/health_app/lib/utils/sse_handler.dart b/health_app/lib/utils/sse_handler.dart new file mode 100644 index 0000000..8ca498f --- /dev/null +++ b/health_app/lib/utils/sse_handler.dart @@ -0,0 +1,84 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:dio/dio.dart'; +import '../core/api_client.dart'; + +/// 跨平台 SSE 流处理(基于 Dio 流式响应,支持 Android/iOS/Web) +class SseHandler { + /// 连接 SSE 端点,返回事件流 + static Stream> connect({ + required String agentType, + required String message, + String? conversationId, + required String token, + }) { + final params = { + 'message': message, + 'token': token, + }; + if (conversationId != null) { + params['conversationId'] = conversationId; + } + final query = params.entries + .map((e) => '${e.key}=${Uri.encodeComponent(e.value)}') + .join('&'); + final url = '$baseUrl/api/ai/$agentType/chat?$query'; + + final controller = StreamController>(); + _connect(controller, url); + return controller.stream; + } + + static Future _connect( + StreamController> controller, + String url, + ) async { + try { + final dio = Dio(BaseOptions( + connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(minutes: 5), + )); + + final response = await dio.get( + url, + options: Options(responseType: ResponseType.stream), + ); + + final stream = response.data.stream as Stream>; + var buffer = ''; + + await for (final chunk in stream) { + if (controller.isClosed) break; + final text = utf8.decode(chunk, allowMalformed: true); + buffer += text; + + // 按行解析 SSE 数据 + while (buffer.contains('\n')) { + final newlineIdx = buffer.indexOf('\n'); + var line = buffer.substring(0, newlineIdx).trim(); + buffer = buffer.substring(newlineIdx + 1); + + if (line.isEmpty || !line.startsWith('data: ')) continue; + final data = line.substring(6); + + if (data == '[DONE]') { + controller.close(); + return; + } + + try { + controller.add(jsonDecode(data) as Map); + } catch (_) { + // 跳过无法解析的行 + } + } + } + controller.close(); + } catch (e) { + if (!controller.isClosed) { + controller.add({'action': 'error', 'message': e.toString()}); + controller.close(); + } + } + } +} diff --git a/health_app/lib/widgets/agent_bar.dart b/health_app/lib/widgets/agent_bar.dart new file mode 100644 index 0000000..2d5eaeb --- /dev/null +++ b/health_app/lib/widgets/agent_bar.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../providers/chat_provider.dart'; + +/// 智能体胶囊栏——横向滑动 +class AgentBar extends ConsumerWidget { + const AgentBar({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final selected = ref.watch(selectedAgentProvider); + final chatNotifier = ref.read(chatProvider.notifier); + + void onTap(ActiveAgent agent) { + final notifier = ref.read(selectedAgentProvider.notifier); + notifier.select(agent == selected ? null : agent); + chatNotifier.setAgent(agent); + } + + return Container( + height: 48, + color: Colors.white, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12), + children: [ + _buildCapsule('AI问诊', Icons.medical_services, ActiveAgent.consultation, selected, onTap), + _buildCapsule('记数据', Icons.edit_note, ActiveAgent.health, selected, onTap), + _buildCapsule('拍饮食', Icons.restaurant, ActiveAgent.diet, selected, onTap), + _buildCapsule('药管家', Icons.medication, ActiveAgent.medication, selected, onTap), + _buildCapsule('看报告', Icons.description, ActiveAgent.report, selected, onTap), + _buildCapsule('运动计划', Icons.fitness_center, ActiveAgent.exercise, selected, onTap), + ], + ), + ); + } + + Widget _buildCapsule(String label, IconData icon, ActiveAgent agent, ActiveAgent? selected, void Function(ActiveAgent) onTap) { + final isSelected = selected == agent; + return GestureDetector( + onTap: () => onTap(agent), + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 4, vertical: 6), + padding: const EdgeInsets.symmetric(horizontal: 14), + decoration: BoxDecoration( + color: isSelected ? const Color(0xFF635BFF) : Colors.white, + border: Border.all(color: const Color(0xFF635BFF)), + borderRadius: BorderRadius.circular(24), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: isSelected ? Colors.white : const Color(0xFF635BFF)), + const SizedBox(width: 6), + Text(label, style: TextStyle(fontSize: 13, color: isSelected ? Colors.white : const Color(0xFF635BFF))), + ], + ), + ), + ); + } +} diff --git a/health_app/lib/widgets/health_drawer.dart b/health_app/lib/widgets/health_drawer.dart new file mode 100644 index 0000000..d3a0015 --- /dev/null +++ b/health_app/lib/widgets/health_drawer.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import '../providers/auth_provider.dart'; +import '../providers/data_providers.dart'; + +/// 侧滑抽屉——健康概览 + 历史对话 + 菜单 +class HealthDrawer extends ConsumerWidget { + const HealthDrawer({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final auth = ref.watch(authProvider); + final user = auth.user; + final latestHealth = ref.watch(latestHealthProvider); + + return Drawer( + child: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 用户信息 + Container( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () => context.push('/profile'), + child: CircleAvatar( + radius: 28, + backgroundColor: const Color(0xFFEDEBFF), + child: Icon(Icons.person, size: 32, color: Theme.of(context).colorScheme.primary), + ), + ), + const SizedBox(height: 12), + Text(user?.name ?? '未设置昵称', style: Theme.of(context).textTheme.titleMedium), + if (user != null) const SizedBox(height: 4), + Text(user?.phone ?? '', style: Theme.of(context).textTheme.labelMedium), + ], + ), + ), + _DrawerItem(icon: Icons.settings, label: '设置', onTap: () => context.push('/settings')), + const Divider(), + + // 健康概览——接真实数据 + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Text('健康概览', style: Theme.of(context).textTheme.labelMedium!.copyWith(fontWeight: FontWeight.w600)), + ), + latestHealth.when( + data: (data) => Column(children: [ + _HealthMetric(icon: Icons.favorite, label: '血压', value: _bpText(data['BloodPressure']), onTap: () => context.push('/trend/blood_pressure')), + _HealthMetric(icon: Icons.monitor_heart, label: '心率', value: _metricText(data['HeartRate'], '次/分'), onTap: () => context.push('/trend/heart_rate')), + _HealthMetric(icon: Icons.bloodtype, label: '血糖', value: _metricText(data['Glucose'], 'mmol/L'), onTap: () => context.push('/trend/glucose')), + _HealthMetric(icon: Icons.air, label: '血氧', value: _metricText(data['SpO2'], '%'), onTap: () => context.push('/trend/spo2')), + ]), + loading: () => const Padding(padding: EdgeInsets.all(16), child: Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)))), + error: (_, _) => Column(children: [ + _HealthMetric(icon: Icons.favorite, label: '血压', value: '--'), + _HealthMetric(icon: Icons.monitor_heart, label: '心率', value: '--'), + _HealthMetric(icon: Icons.bloodtype, label: '血糖', value: '--'), + _HealthMetric(icon: Icons.air, label: '血氧', value: '--'), + ]), + ), + + const Divider(), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Text('历史对话', style: Theme.of(context).textTheme.labelMedium!.copyWith(fontWeight: FontWeight.w600)), + ), + const Expanded(child: Center(child: Text('暂无历史对话', style: TextStyle(color: Color(0xFF999999), fontSize: 14)))), + + const Divider(), + _DrawerItem(icon: Icons.logout, label: '退出登录', onTap: () async { + final ok = await showDialog(context: context, builder: (ctx) => AlertDialog( + title: const Text('退出登录'), content: const Text('确定退出?'), + actions: [TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')), TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定'))])); + if (ok == true) { await ref.read(authProvider.notifier).logout(); if (context.mounted) context.go('/login'); } + }), + ], + ), + ), + ); + } + + String _bpText(dynamic bp) { + if (bp == null) return '--'; + if (bp is Map) return '${bp['systolic'] ?? '--'}/${bp['diastolic'] ?? '--'}'; + return '--'; + } + + String _metricText(dynamic metric, String unit) { + if (metric == null) return '--'; + if (metric is Map) { + final v = metric['value']; + return v != null ? '$v $unit' : '--'; + } + return '--'; + } +} + +class _DrawerItem extends StatelessWidget { + final IconData icon; final String label; final VoidCallback onTap; + const _DrawerItem({required this.icon, required this.label, required this.onTap}); + @override Widget build(BuildContext context) => ListTile(leading: Icon(icon, size: 20, color: const Color(0xFF666666)), title: Text(label, style: const TextStyle(fontSize: 16)), onTap: onTap, dense: true); +} + +class _HealthMetric extends StatelessWidget { + final IconData icon; final String label; final String value; final VoidCallback? onTap; + const _HealthMetric({required this.icon, required this.label, required this.value, this.onTap}); + @override Widget build(BuildContext context) => ListTile( + leading: Icon(icon, size: 18, color: const Color(0xFF635BFF)), + title: Text(label, style: const TextStyle(fontSize: 16, color: Color(0xFF1A1A1A))), + trailing: Text(value, style: TextStyle(fontSize: 16, color: value == '--' ? const Color(0xFF999999) : const Color(0xFF1A1A1A))), + dense: true, + onTap: onTap, + ); +} diff --git a/health_app/pubspec.lock b/health_app/pubspec.lock new file mode 100644 index 0000000..c0f78e8 --- /dev/null +++ b/health_app/pubspec.lock @@ -0,0 +1,898 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d + url: "https://pub.dev" + source: hosted + version: "91.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08 + url: "https://pub.dev" + source: hosted + version: "8.4.1" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "67cf6d84013f9c601e42a6f8a6b74c4c0d9dc1a1619d775f2b28b732d3551b85" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dbus: + dependency: transitive + description: + name: dbus + sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 + url: "https://pub.dev" + source: hosted + version: "0.7.12" + dio: + dependency: "direct main" + description: + name: dio + sha256: aff32c08f92787a557dd5c0145ac91536481831a01b4648136373cddb0e64f8c + url: "https://pub.dev" + source: hosted + version: "5.9.2" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "2f9e64323a7c3c7ef69567d5c800424a11f8337b8b228bad02524c9fb3c1f340" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" + url: "https://pub.dev" + source: hosted + version: "2.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: "57d9a1dd5063f85fa3107fb42d1faffda52fdc948cefd5fe5ea85267a5fc7343" + url: "https://pub.dev" + source: hosted + version: "10.3.10" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" + fl_chart: + dependency: "direct main" + description: + name: fl_chart + sha256: d0f0d49112f2f4b192481c16d05b6418bd7820e021e265a3c22db98acf7ed7fb + url: "https://pub.dev" + source: hosted + version: "0.68.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "4e166be88e1dbbaa34a280bdb744aeae73b7ef25fdf8db7a3bb776760a3648e2" + url: "https://pub.dev" + source: hosted + version: "3.3.1" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + url: "https://pub.dev" + source: hosted + version: "9.2.4" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + flutter_secure_storage_macos: + dependency: transitive + description: + name: flutter_secure_storage_macos + sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + url: "https://pub.dev" + source: hosted + version: "3.1.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: f02fd7d2a4dc512fec615529824fdd217fecb3a3d3de68360293a551f21634b3 + url: "https://pub.dev" + source: hosted + version: "14.8.1" + hooks: + dependency: transitive + description: + name: hooks + sha256: a41af4e8fc687cd6d33de9751eb936c8c0204ebe2bcb6c15ecf707504bf47f31 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.dev" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.dev" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" + url: "https://pub.dev" + source: hosted + version: "9.4.1" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.dev" + source: hosted + version: "1.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "8c22216be8ad3ef2b44af3a329693558c98eca7b8bd4ef495c92db0bba279f83" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + url: "https://pub.dev" + source: hosted + version: "0.10.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: transitive + description: + name: test + sha256: "75906bf273541b676716d1ca7627a17e4c4070a3a16272b7a3dc7da3b9f3f6b7" + url: "https://pub.dev" + source: hosted + version: "1.26.3" + test_api: + dependency: transitive + description: + name: test_api + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + test_core: + dependency: transitive + description: + name: test_core + sha256: "0cc24b5ff94b38d2ae73e1eb43cc302b77964fbf67abad1e296025b78deb53d0" + url: "https://pub.dev" + source: hosted + version: "0.6.12" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.7 <4.0.0" + flutter: ">=3.38.4" diff --git a/health_app/pubspec.yaml b/health_app/pubspec.yaml new file mode 100644 index 0000000..3295c83 --- /dev/null +++ b/health_app/pubspec.yaml @@ -0,0 +1,44 @@ +name: health_app +description: "健康管家 - AI 健康陪伴助手" +publish_to: 'none' +version: 1.0.0+1 + +environment: + sdk: ^3.10.7 + +dependencies: + flutter: + sdk: flutter + + # 状态管理 + flutter_riverpod: ^3.2.0 + + # HTTP 网络 + dio: ^5.4.0 + + # 安全存储 + flutter_secure_storage: ^9.2.0 + + # 路由 + go_router: ^14.0.0 + + # 图表 + fl_chart: ^0.68.0 + + # 相机 & 图片 & 文件 + image_picker: ^1.0.0 + file_picker: ^10.3.7 + + # 推送(后期集成) + # jpush_flutter: ^3.4.5 + + # 基础图标 + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + uses-material-design: true diff --git a/health_app/test/widget_test.dart b/health_app/test/widget_test.dart new file mode 100644 index 0000000..454b1be --- /dev/null +++ b/health_app/test/widget_test.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:health_app/core/app_theme.dart'; +import 'package:health_app/pages/auth/login_page.dart'; +import 'package:health_app/widgets/agent_bar.dart'; + +void main() { + testWidgets('主题颜色正确', (tester) async { + expect(AppTheme.primaryColor, const Color(0xFF635BFF)); + expect(AppTheme.background, const Color(0xFFF8F9FF)); + expect(AppTheme.errorRed, const Color(0xFFE53935)); + expect(AppTheme.successGreen, const Color(0xFF43A047)); + }); + + testWidgets('登录页渲染正常', (tester) async { + await tester.pumpWidget(const ProviderScope(child: MaterialApp(home: LoginPage()))); + await tester.pumpAndSettle(); + + expect(find.text('健康管家'), findsOneWidget); + expect(find.text('登 录'), findsOneWidget); + }); + + testWidgets('获取验证码按钮存在', (tester) async { + await tester.pumpWidget(const ProviderScope(child: MaterialApp(home: LoginPage()))); + await tester.pumpAndSettle(); + + expect(find.text('获取验证码'), findsOneWidget); + }); + + testWidgets('智能体胶囊栏渲染 6 个胶囊', (tester) async { + await tester.pumpWidget(const ProviderScope(child: MaterialApp(home: Scaffold(body: AgentBar())))); + await tester.pumpAndSettle(); + + expect(find.text('AI问诊'), findsOneWidget); + expect(find.text('记数据'), findsOneWidget); + expect(find.text('拍饮食'), findsOneWidget); + expect(find.text('药管家'), findsOneWidget); + expect(find.text('看报告'), findsOneWidget); + expect(find.text('运动计划'), findsOneWidget); + }); + + testWidgets('AI 气泡样式', (tester) async { + await tester.pumpWidget(MaterialApp( + theme: AppTheme.lightTheme, + home: Scaffold(body: Align( + alignment: Alignment.centerLeft, + child: Container( + constraints: const BoxConstraints(maxWidth: 300), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: const Border(left: BorderSide(color: Color(0xFF635BFF), width: 3)), + ), + child: const Text('收到!已记录', style: TextStyle(fontSize: 16)), + ), + )), + )); + await tester.pumpAndSettle(); + expect(find.text('收到!已记录'), findsOneWidget); + }); + + testWidgets('用户气泡样式', (tester) async { + await tester.pumpWidget(MaterialApp( + theme: AppTheme.lightTheme, + home: Scaffold(body: Align( + alignment: Alignment.centerRight, + child: Container( + constraints: const BoxConstraints(maxWidth: 300), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF635BFF), + borderRadius: BorderRadius.circular(16), + ), + child: const Text('血压 135/85', style: TextStyle(fontSize: 16, color: Colors.white)), + ), + )), + )); + await tester.pumpAndSettle(); + expect(find.text('血压 135/85'), findsOneWidget); + }); +} diff --git a/health_app/web/favicon.png b/health_app/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8aaa46ac1ae21512746f852a42ba87e4165dfdd1 GIT binary patch literal 917 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|I14-?iy0X7 zltGxWVyS%@P(fs7NJL45ua8x7ey(0(N`6wRUPW#JP&EUCO@$SZnVVXYs8ErclUHn2 zVXFjIVFhG^g!Ppaz)DK8ZIvQ?0~DO|i&7O#^-S~(l1AfjnEK zjFOT9D}DX)@^Za$W4-*MbbUihOG|wNBYh(yU7!lx;>x^|#0uTKVr7USFmqf|i<65o z3raHc^AtelCMM;Vme?vOfh>Xph&xL%(-1c06+^uR^q@XSM&D4+Kp$>4P^%3{)XKjo zGZknv$b36P8?Z_gF{nK@`XI}Z90TzwSQO}0J1!f2c(B=V`5aP@1P1a|PZ!4!3&Gl8 zTYqUsf!gYFyJnXpu0!n&N*SYAX-%d(5gVjrHJWqXQshj@!Zm{!01WsQrH~9=kTxW#6SvuapgMqt>$=j#%eyGrQzr zP{L-3gsMA^$I1&gsBAEL+vxi1*Igl=8#8`5?A-T5=z-sk46WA1IUT)AIZHx1rdUrf zVJrJn<74DDw`j)Ki#gt}mIT-Q`XRa2-jQXQoI%w`nb|XblvzK${ZzlV)m-XcwC(od z71_OEC5Bt9GEXosOXaPTYOia#R4ID2TiU~`zVMl08TV_C%DnU4^+HE>9(CE4D6?Fz oujB08i7adh9xk7*FX66dWH6F5TM;?E2b5PlUHx3vIVCg!0Dx9vYXATM literal 0 HcmV?d00001 diff --git a/health_app/web/icons/Icon-192.png b/health_app/web/icons/Icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..b749bfef07473333cf1dd31e9eed89862a5d52aa GIT binary patch literal 5292 zcmZ`-2T+sGz6~)*FVZ`aW+(v>MIm&M-g^@e2u-B-DoB?qO+b1Tq<5uCCv>ESfRum& zp%X;f!~1{tzL__3=gjVJ=j=J>+nMj%ncXj1Q(b|Ckbw{Y0FWpt%4y%$uD=Z*c-x~o zE;IoE;xa#7Ll5nj-e4CuXB&G*IM~D21r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RZ^#8Mf5aWNVhjAS^|DQO+q$)oeob_&ZLFL(zur$)); zU19yRm)z<4&4-M}7!9+^Wl}Uk?`S$#V2%pQ*SIH5KI-mn%i;Z7-)m$mN9CnI$G7?# zo`zVrUwoSL&_dJ92YhX5TKqaRkfPgC4=Q&=K+;_aDs&OU0&{WFH}kKX6uNQC6%oUH z2DZa1s3%Vtk|bglbxep-w)PbFG!J17`<$g8lVhqD2w;Z0zGsh-r zxZ13G$G<48leNqR!DCVt9)@}(zMI5w6Wo=N zpP1*3DI;~h2WDWgcKn*f!+ORD)f$DZFwgKBafEZmeXQMAsq9sxP9A)7zOYnkHT9JU zRA`umgmP9d6=PHmFIgx=0$(sjb>+0CHG)K@cPG{IxaJ&Ueo8)0RWgV9+gO7+Bl1(F z7!BslJ2MP*PWJ;x)QXbR$6jEr5q3 z(3}F@YO_P1NyTdEXRLU6fp?9V2-S=E+YaeLL{Y)W%6`k7$(EW8EZSA*(+;e5@jgD^I zaJQ2|oCM1n!A&-8`;#RDcZyk*+RPkn_r8?Ak@agHiSp*qFNX)&i21HE?yuZ;-C<3C zwJGd1lx5UzViP7sZJ&|LqH*mryb}y|%AOw+v)yc`qM)03qyyrqhX?ub`Cjwx2PrR! z)_z>5*!*$x1=Qa-0uE7jy0z`>|Ni#X+uV|%_81F7)b+nf%iz=`fF4g5UfHS_?PHbr zB;0$bK@=di?f`dS(j{l3-tSCfp~zUuva+=EWxJcRfp(<$@vd(GigM&~vaYZ0c#BTs z3ijkxMl=vw5AS&DcXQ%eeKt!uKvh2l3W?&3=dBHU=Gz?O!40S&&~ei2vg**c$o;i89~6DVns zG>9a*`k5)NI9|?W!@9>rzJ;9EJ=YlJTx1r1BA?H`LWijk(rTax9(OAu;q4_wTj-yj z1%W4GW&K4T=uEGb+E!>W0SD_C0RR91 literal 0 HcmV?d00001 diff --git a/health_app/web/icons/Icon-512.png b/health_app/web/icons/Icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..88cfd48dff1169879ba46840804b412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.png b/health_app/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9b4d76e525556d5d89141648c724331630325d GIT binary patch literal 5594 zcmdT|`#%%j|KDb2V@0DPm$^(Lx5}lO%Yv(=e*7hl@QqKS50#~#^IQPxBmuh|i9sXnt4ch@VT0F7% zMtrs@KWIOo+QV@lSs66A>2pz6-`9Jk=0vv&u?)^F@HZ)-6HT=B7LF;rdj zskUyBfbojcX#CS>WrIWo9D=DIwcXM8=I5D{SGf$~=gh-$LwY?*)cD%38%sCc?5OsX z-XfkyL-1`VavZ?>(pI-xp-kYq=1hsnyP^TLb%0vKRSo^~r{x?ISLY1i7KjSp z*0h&jG(Rkkq2+G_6eS>n&6>&Xk+ngOMcYrk<8KrukQHzfx675^^s$~<@d$9X{VBbg z2Fd4Z%g`!-P}d#`?B4#S-9x*eNlOVRnDrn#jY@~$jfQ-~3Od;A;x-BI1BEDdvr`pI z#D)d)!2_`GiZOUu1crb!hqH=ezs0qk<_xDm_Kkw?r*?0C3|Io6>$!kyDl;eH=aqg$B zsH_|ZD?jP2dc=)|L>DZmGyYKa06~5?C2Lc0#D%62p(YS;%_DRCB1k(+eLGXVMe+=4 zkKiJ%!N6^mxqM=wq`0+yoE#VHF%R<{mMamR9o_1JH8jfnJ?NPLs$9U!9!dq8 z0B{dI2!M|sYGH&9TAY34OlpIsQ4i5bnbG>?cWwat1I13|r|_inLE?FS@Hxdxn_YZN z3jfUO*X9Q@?HZ>Q{W0z60!bbGh557XIKu1?)u|cf%go`pwo}CD=0tau-}t@R2OrSH zQzZr%JfYa`>2!g??76=GJ$%ECbQh7Q2wLRp9QoyiRHP7VE^>JHm>9EqR3<$Y=Z1K^SHuwxCy-5@z3 zVM{XNNm}yM*pRdLKp??+_2&!bp#`=(Lh1vR{~j%n;cJv~9lXeMv)@}Odta)RnK|6* zC+IVSWumLo%{6bLDpn)Gz>6r&;Qs0^+Sz_yx_KNz9Dlt^ax`4>;EWrIT#(lJ_40<= z750fHZ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|vwS>$-`fuRSp3927qOv|NC3T3G-0 zA{K`|+tQy1yqE$ShWt8ny&5~)%ITb@^+x$w0)f&om;P8B)@}=Wzy59BwUfZ1vqw87 za2lB8J(&*l#(V}Id8SyQ0C(2amzkz3EqG&Ed0Jq1)$|&>4_|NIe=5|n=3?siFV0fI z{As5DLW^gs|B-b4C;Hd(SM-S~GQhzb>HgF2|2Usww0nL^;x@1eaB)=+Clj+$fF@H( z-fqP??~QMT$KI-#m;QC*&6vkp&8699G3)Bq0*kFZXINw=b9OVaed(3(3kS|IZ)CM? zJdnW&%t8MveBuK21uiYj)_a{Fnw0OErMzMN?d$QoPwkhOwcP&p+t>P)4tHlYw-pPN z^oJ=uc$Sl>pv@fZH~ZqxSvdhF@F1s=oZawpr^-#l{IIOGG=T%QXjtwPhIg-F@k@uIlr?J->Ia zpEUQ*=4g|XYn4Gez&aHr*;t$u3oODPmc2Ku)2Og|xjc%w;q!Zz+zY)*3{7V8bK4;& zYV82FZ+8?v)`J|G1w4I0fWdKg|2b#iaazCv;|?(W-q}$o&Y}Q5d@BRk^jL7#{kbCK zSgkyu;=DV+or2)AxCBgq-nj5=@n^`%T#V+xBGEkW4lCqrE)LMv#f;AvD__cQ@Eg3`~x| zW+h9mofSXCq5|M)9|ez(#X?-sxB%Go8};sJ?2abp(Y!lyi>k)|{M*Z$c{e1-K4ky` MPgg&ebxsLQ025IeI{*Lx literal 0 HcmV?d00001 diff --git a/health_app/web/index.html b/health_app/web/index.html new file mode 100644 index 0000000..452e090 --- /dev/null +++ b/health_app/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + health_app + + + + + + diff --git a/health_app/web/manifest.json b/health_app/web/manifest.json new file mode 100644 index 0000000..2fbe3ea --- /dev/null +++ b/health_app/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "health_app", + "short_name": "health_app", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/start-dev.bat b/start-dev.bat new file mode 100644 index 0000000..0c16045 --- /dev/null +++ b/start-dev.bat @@ -0,0 +1,3 @@ +@echo off +cd /d D:\健康管家 +powershell -ExecutionPolicy Bypass -NoExit -Command "& 'D:\健康管家\start-dev.ps1'" diff --git a/start-dev.ps1 b/start-dev.ps1 new file mode 100644 index 0000000..1efaeff --- /dev/null +++ b/start-dev.ps1 @@ -0,0 +1,36 @@ +# 健康管家 - 一键启动 +Write-Host "========================================" -ForegroundColor Cyan +Write-Host " 健康管家开发环境启动" -ForegroundColor Cyan +Write-Host "========================================" -ForegroundColor Cyan + +# 1. PostgreSQL +Write-Host "`n[1/3] 启动 PostgreSQL..." -ForegroundColor Yellow +$pgBin = "D:\PostgreSQL\18\pgsql\bin" +$pgData = "D:\PostgreSQL\18\pgsql\data" +try { + & "$pgBin\pg_ctl.exe" -D $pgData start 2>$null + Write-Host " PostgreSQL OK" -ForegroundColor Green +} catch { + Write-Host " PostgreSQL 已在运行或启动失败" -ForegroundColor Gray +} + +# 2. Backend +Write-Host "`n[2/3] 启动后端..." -ForegroundColor Yellow +$backendDir = "D:\健康管家\backend\src\Health.WebApi" +Start-Process cmd -ArgumentList "/k cd /d `"$backendDir`" && dotnet run --urls http://localhost:5000" +Write-Host " 后端窗口已打开,等待就绪..." -ForegroundColor Green + +# 3. Frontend +Write-Host "`n[3/3] 等待 15 秒后启动前端..." -ForegroundColor Yellow +Start-Sleep 15 +$frontendDir = "D:\健康管家\health_app" +$flutter = "C:\Users\明年\flutter\bin\flutter.bat" +Start-Process cmd -ArgumentList "/k cd /d `"$frontendDir`" && `"$flutter`" run -d edge" +Write-Host " 前端窗口已打开" -ForegroundColor Green + +Write-Host "`n========================================" -ForegroundColor Cyan +Write-Host " 后端: http://localhost:5000" -ForegroundColor Green +Write-Host " 前端: 等待浏览器自动打开" -ForegroundColor Green +Write-Host "========================================" -ForegroundColor Cyan +Write-Host "`n窗口可以关闭,不会影响运行中的服务" +Read-Host "按 Enter 退出" diff --git a/健康管家-技术设计文档-v2.md b/健康管家-技术设计文档-v2.md new file mode 100644 index 0000000..de213dc --- /dev/null +++ b/健康管家-技术设计文档-v2.md @@ -0,0 +1,1254 @@ +# 健康管家 — 技术设计文档 V2 + +> 基于需求规格文档 V2,技术栈确定为 .NET 10 + Flutter + PostgreSQL。 + +--- + +## 一、整体架构 + +``` +Flutter App(iOS + Android) + │ + ├── HTTPS REST(业务 CRUD) + ├── SSE(AI 对话流式输出) + └── HTTPS 轮询(医患消息,15s间隔) + + ▼ +.NET 10 ASP.NET Core Minimal API + │ + ├── HttpClient → DeepSeek(LLM 对话 + Tool Calling) + ├── HttpClient → 千问 VL(食物图片识别) + ├── EF Core → PostgreSQL(主数据库) + ├── MinIO SDK → MinIO(文件/图片存储) + └── 极光推送 SDK → 极光推送(Android/iOS 通知) +``` + +- 后端:.NET 10,C# 12,4 层 Clean Architecture +- 前端:Flutter,Dart,Riverpod +- AI 调用:纯 HttpClient 直连各模型厂商 API(OpenAI 兼容协议),不使用任何模型厂商 SDK +- 不允许前端直接调 AI 模型 API,全部经 .NET 后端中转 + +--- + +## 二、后端架构 + +### 2.1 目录结构 + +``` +HealthManager/ +├── src/ +│ ├── Health.Domain/ # 领域层 +│ │ ├── Entities/ # 实体:User, HealthRecord, Medication, DietRecord 等 +│ │ ├── Enums/ # 枚举:HealthMetricType, MealType, ReportStatus 等 +│ │ └── Interfaces/ # 仓储接口 +│ │ +│ ├── Health.Application/ # 应用层 +│ │ ├── DTOs/ # 数据传输对象 +│ │ ├── Services/ # 业务服务 +│ │ │ ├── AuthService.cs # 认证 +│ │ │ ├── HealthService.cs # 健康数据 +│ │ │ ├── DietService.cs # 饮食记录 +│ │ │ ├── MedicationService.cs # 用药管理 +│ │ │ ├── ReportService.cs # 报告管理 +│ │ │ ├── ConsultationService.cs # 问诊 +│ │ │ ├── ExerciseService.cs # 运动计划 +│ │ │ └── UserService.cs # 用户/健康档案 +│ │ └── Interfaces/ # 服务接口 +│ │ +│ ├── Health.Infrastructure/ # 基础设施层 +│ │ ├── Data/ +│ │ │ ├── AppDbContext.cs # EF Core 上下文 +│ │ │ └── Migrations/ # 数据库迁移 +│ │ ├── Services/ +│ │ │ ├── JwtProvider.cs # JWT 生成与验证 +│ │ │ ├── SmsService.cs # 短信发送 +│ │ │ ├── PushService.cs # 极光推送 +│ │ │ └── MinioStorageService.cs # 文件存储 +│ │ └── AI/ # AI 服务模块 +│ │ ├── OpenAiCompatibleClient.cs # OpenAI 兼容 HTTP 客户端(统一调 DeepSeek/千问) +│ │ ├── AiChatService.cs # AI 对话编排(意图识别 + Tool Calling) +│ │ ├── AgentHandlers/ # 7 个 Agent 的处理器 +│ │ │ ├── DefaultAgentHandler.cs # 默认对话 +│ │ │ ├── ConsultationAgentHandler.cs # AI 问诊 +│ │ │ ├── HealthDataAgentHandler.cs # 记数据 +│ │ │ ├── DietAgentHandler.cs # 拍饮食 +│ │ │ ├── MedicationAgentHandler.cs # 药管家 +│ │ │ ├── ReportAgentHandler.cs # 看报告 +│ │ │ └── ExerciseAgentHandler.cs # 运动计划 +│ │ └── PromptManager.cs # System Prompt 模板管理 +│ │ +│ └── Health.WebApi/ # 接口层 +│ ├── Program.cs # 启动配置 +│ ├── Endpoints/ # Minimal API 端点 +│ │ ├── AuthEndpoints.cs +│ │ ├── HealthEndpoints.cs +│ │ ├── DietEndpoints.cs +│ │ ├── MedicationEndpoints.cs +│ │ ├── ReportEndpoints.cs +│ │ ├── ConsultationEndpoints.cs +│ │ ├── ExerciseEndpoints.cs +│ │ ├── UserEndpoints.cs +│ │ ├── AiChatEndpoints.cs # AI 对话 SSE +│ │ └── FileEndpoints.cs +│ ├── Middleware/ # 中间件 +│ │ └── ExceptionMiddleware.cs +│ └── BackgroundServices/ # 后台服务 +│ └── MedicationReminderService.cs # 用药提醒定时扫描 +``` + +### 2.2 API 响应格式 + +所有 API 返回统一结构: + +```json +// 成功 +{ "code": 0, "data": { ... }, "message": null } + +// 业务错误 +{ "code": 40001, "data": null, "message": "验证码错误" } + +// 系统异常 +{ "code": 50000, "data": null, "message": "服务器内部错误" } +``` + +- `code = 0`:成功 +- `code = 4xxxx`:客户端错误 +- `code = 5xxxx`:服务端错误 + +--- + +### 2.3 7 个 Agent 设计 + +每个 Agent 本质上是:一个 SSE 端点 + 独立的 System Prompt + 独立的 Tool Set。 + +#### Agent 架构模式 + +``` +Flutter 端 → GET /api/ai/{agent_type}/chat?message=xxx + │ + ▼ + AgentHandler.Process(message, userId, sessionId) + │ + ├── 1. 加载上下文(System Prompt + 患者数据 + 对话历史) + ├── 2. 调用 DeepSeek(stream: true) + ├── 3. Tool Calling 循环(如果 LLM 返回 tool_calls) + │ ├── 执行 Tool + │ ├── 结果追加到消息历史 + │ └── 再次调用 LLM + ├── 4. 流式输出回复(SSE data: 逐 token) + └── 5. 保存对话记录到 PostgreSQL +``` + +#### 7 个 Agent 对照表 + +| Agent | Path | System Prompt 定位 | Tool Set | +|-------|------|-------------------|----------| +| 默认对话 | `/api/ai/default/chat` | 通用健康管家 | query_health_records, check_abnormal | +| AI 问诊 | `/api/ai/consultation/chat` | 医生助手,多轮追问 | query_health_records, check_archive, request_doctor | +| 记数据 | `/api/ai/health/chat` | 健康数据录入助手 | record_health_data, query_health_records | +| 拍饮食 | `/api/ai/diet/chat` | 营养分析专家 | analyze_food_image(VLM), estimate_food_text, check_archive | +| 药管家 | `/api/ai/medication/chat` | 用药管理专家 | manage_medication(create/query/confirm), check_archive | +| 看报告 | `/api/ai/report/chat` | 报告解读专家 | analyze_report(VLM), query_health_records | +| 运动计划 | `/api/ai/exercise/chat` | 运动康复教练 | manage_exercise_plan(create/query/checkin) | + +### 2.4 Tool Calling 设计 + +| Tool | 功能 | 参数 | +|------|------|------| +| `record_health_data` | 录入健康数据 | type, systolic?, diastolic?, heart_rate?, glucose?, spo2?, weight?, recorded_at | +| `query_health_records` | 查询近期健康数据 | type?, days? | +| `check_abnormal` | 检查是否有异常指标 | — | +| `check_archive` | 查询患者档案 | — | +| `analyze_food_image` | VLM 食物识别 | image_url | +| `estimate_food_text` | 文字描述估算食物 | text | +| `manage_medication` | 用药管理 | action(create/query/confirm/update), name?, dosage?, time? | +| `manage_exercise_plan` | 运动计划 | action(create/query/checkin), exercises?, day? | +| `analyze_report` | 报告 AI 预解读 | image_url | +| `request_doctor` | 转医生 | reason, urgency_level | + +### 2.5 AI 服务模块 + +#### OpenAiCompatibleClient + +统一的 OpenAI 兼容协议 HTTP 客户端,支持: +- Chat Completions(含 streaming) +- Vision(图片理解) +- Tool Calling(Function Calling) +- JSON Mode +- 多 BaseUrl 切换(DeepSeek / 千问 VL) +- 自动重试 + +```csharp +// 调用示例 +var client = new OpenAiCompatibleClient(new() +{ + BaseUrl = "https://api.deepseek.com/v1", + ApiKey = config["DEEPSEEK_API_KEY"], + Model = "deepseek-chat" +}); + +await foreach (var token in client.ChatStreamAsync(messages, tools)) +{ + // SSE 输出给前端 +} +``` + +#### AiChatService + +每个 Agent 对话的核心编排逻辑: + +```csharp +public async IAsyncEnumerable ProcessAgentChat( + AgentType agentType, + string message, + string userId, + string? conversationId) +{ + // 1. 加载 System Prompt + var systemPrompt = _promptManager.GetSystemPrompt(agentType); + + // 2. 注入患者上下文 + var patientContext = await LoadPatientContext(userId); + + // 3. 加载对话历史 + var history = await LoadConversationHistory(conversationId, userId); + + // 4. 构建消息 + var messages = BuildMessages(systemPrompt, patientContext, history, message); + + // 5. Tool Calling 循环 + var tools = _toolRegistry.GetTools(agentType); + var maxIterations = 5; + + for (int i = 0; i < maxIterations; i++) + { + var response = await _aiClient.ChatAsync(messages, tools, stream: true); + + if (response.FinishReason == "stop") + { + // 流式输出文本 + await foreach (var token in response.Stream) + yield return token; + break; + } + else if (response.FinishReason == "tool_calls") + { + // 执行 Tool + foreach (var toolCall in response.ToolCalls) + { + var result = await _toolExecutor.Execute(toolCall); + messages.Add(new { role = "tool", content = result, tool_call_id = toolCall.Id }); + } + // 继续循环 + } + } + + // 6. 保存对话记录 + await SaveConversation(userId, conversationId, messages); +} +``` + +#### PromptManager + +System Prompt 模板管理: + +``` +默认对话: + 你是一个心脏术后康复患者的私人 AI 健康管家。 + 你的名字叫"阿福",语气温暖专业。 + 每次回复末尾,如果有需要提醒的事项,简短提醒一句。 + +AI 问诊: + 你是一个心血管内科医生助手,负责对患者进行多轮问诊。 + 规则: + 1. 每次只问一个问题,不要一次问多个 + 2. 给出快捷选项让患者点击 + 3. 遇到胸痛/呼吸困难/心悸 → 建议立即就医 + 4. 血压持续>160/100 或心率异常 → 建议转医生 + 5. 问诊结束后给出初步分析 + +记数据: + 你是一个健康数据录入助手。 + 规则: + 1. 解析用户口中的指标和数值 + 2. 指标模糊时追问确认 + 3. 时间模糊时取当前时间并告知用户 + 4. 异常值时附带提醒 + 5. 录入后展示确认卡片 + +拍饮食: + 你是一个营养分析专家。 + 规则: + 1. 等待VLM识别结果后再做分析 + 2. 结合患者档案判断"能不能吃" + 3. 给出单项警告和整体建议 + 4. 追问餐次归类 + ... + +(其余 Agent 同理) +``` + +### 2.6 配置管理 + +所有敏感配置放环境变量(`.env` / appsettings): + +``` +# LLM +DEEPSEEK_API_KEY=sk-xxxxx +DEEPSEEK_BASE_URL=https://api.deepseek.com/v1 +DEEPSEEK_MODEL=deepseek-chat + +# VLM +QWEN_API_KEY=sk-xxxxx +QWEN_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 +QWEN_VISION_MODEL=qwen-vl-max + +# 基础设施 +JWT_SECRET=xxxxx +DB_CONNECTION=Host=localhost;Database=health_manager;... +MINIO_ENDPOINT=localhost:9000 +MINIO_ACCESS_KEY=xxxxx +MINIO_SECRET_KEY=xxxxx + +# 推送 +JPUSH_APP_KEY=xxxxx +JPUSH_MASTER_SECRET=xxxxx + +# 短信 +SMS_PROVIDER=xxx +SMS_API_KEY=xxxxx +``` + +--- + +## 三、数据库设计 + +### 3.1 核心表 + +| 表名 | 说明 | +|------|------| +| `users` | 用户表 | +| `health_records` | 健康记录(血压/心率/血糖/血氧/体重) | +| `medications` | 用药计划 | +| `medication_logs` | 用药打卡记录 | +| `diet_records` | 饮食记录 | +| `diet_food_items` | 饮食记录中的食物条目 | +| `exercise_plans` | 运动计划(按周) | +| `exercise_plan_items` | 运动计划每日条目 | +| `reports` | 检查报告 | +| `conversations` | AI 对话会话 | +| `conversation_messages` | AI 对话消息 | +| `consultations` | 问诊会话 | +| `consultation_messages` | 问诊消息 | +| `follow_ups` | 复查/随访计划 | +| `health_archives` | 健康档案 | +| `refresh_tokens` | 刷新令牌 | +| `verification_codes` | 验证码 | +| `notification_preferences` | 通知偏好 | +| `device_tokens` | 设备推送 token | +| `devices` | 绑定设备(预留) | + +### 3.2 关键表结构 + +#### users + +```sql +id UUID PRIMARY KEY +phone VARCHAR(20) UNIQUE NOT NULL +name VARCHAR(50) +gender VARCHAR(10) +birth_date DATE +avatar_url VARCHAR(500) +created_at TIMESTAMP +updated_at TIMESTAMP +``` + +#### health_records + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +metric_type VARCHAR(20) NOT NULL -- blood_pressure / heart_rate / glucose / spo2 / weight +systolic INTEGER -- 血压专用 +diastolic INTEGER -- 血压专用 +value DECIMAL -- 通用数值(心率/血糖/血氧/体重) +unit VARCHAR(20) +source VARCHAR(20) NOT NULL -- ai_entry / device_sync / manual +is_abnormal BOOLEAN +recorded_at TIMESTAMP +created_at TIMESTAMP +``` + +#### medications + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +name VARCHAR(100) NOT NULL +dosage VARCHAR(50) +frequency VARCHAR(50) -- daily / twice_daily / weekly 等 +time_of_day TIME[] -- PostgreSQL 数组,如 {08:00,20:00} +start_date DATE +end_date DATE +is_active BOOLEAN +source VARCHAR(20) -- prescription / ai_entry / manual +created_at TIMESTAMP +updated_at TIMESTAMP +``` + +#### diet_records + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +meal_type VARCHAR(10) -- breakfast / lunch / dinner / snack +total_calories INTEGER +health_score INTEGER -- 1-5 +recorded_at DATE +created_at TIMESTAMP +``` + +#### diet_food_items + +```sql +id UUID PRIMARY KEY +diet_record_id UUID REFERENCES diet_records(id) +name VARCHAR(100) +portion VARCHAR(50) +calories INTEGER +protein_g DECIMAL +carbs_g DECIMAL +fat_g DECIMAL +warning TEXT +sort_order INTEGER +``` + +#### health_archives + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) UNIQUE +diagnosis TEXT -- 主要诊断 +surgery_type VARCHAR(100) -- 手术类型 +surgery_date DATE -- 手术日期 +allergies TEXT[] -- 过敏信息 +diet_restrictions TEXT[] -- 饮食限制 +chronic_diseases TEXT[] -- 慢病史 +family_history TEXT -- 家族病史 +updated_at TIMESTAMP +``` + +#### medication_logs + +```sql +id UUID PRIMARY KEY +medication_id UUID REFERENCES medications(id) +user_id UUID REFERENCES users(id) +status VARCHAR(20) NOT NULL -- taken / missed / skipped +scheduled_time TIME NOT NULL +confirmed_at TIMESTAMP +created_at TIMESTAMP +``` + +#### exercise_plans + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +week_start_date DATE NOT NULL -- 本周一 +created_at TIMESTAMP +updated_at TIMESTAMP +``` + +#### exercise_plan_items + +```sql +id UUID PRIMARY KEY +plan_id UUID REFERENCES exercise_plans(id) +day_of_week INTEGER NOT NULL -- 0=周一, 6=周日 +exercise_type VARCHAR(100) NOT NULL -- 散步/慢跑/游泳 等 +duration_minutes INTEGER NOT NULL +is_completed BOOLEAN DEFAULT FALSE +completed_at TIMESTAMP +is_rest_day BOOLEAN DEFAULT FALSE -- 休息日 +``` + +#### reports + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +file_url VARCHAR(500) NOT NULL +file_type VARCHAR(20) -- image / pdf +report_type VARCHAR(50) -- blood_test / ecg / ultrasound / other +ai_summary TEXT -- AI 预解读结果(JSON) +ai_indicators JSONB -- 提取的指标 [{name, value, unit, range, status}] +status VARCHAR(20) NOT NULL -- pending_doctor / doctor_reviewed +doctor_comment TEXT -- 医生审核意见 +doctor_name VARCHAR(50) -- 审核医生 +reviewed_at TIMESTAMP +created_at TIMESTAMP +``` + +#### conversations + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +agent_type VARCHAR(20) NOT NULL -- default / consultation / health / diet 等 +title VARCHAR(200) +summary VARCHAR(500) -- 侧滑抽屉显示用的摘要 +message_count INTEGER DEFAULT 0 +created_at TIMESTAMP +updated_at TIMESTAMP +``` + +#### conversation_messages + +```sql +id UUID PRIMARY KEY +conversation_id UUID REFERENCES conversations(id) +role VARCHAR(10) NOT NULL -- user / assistant / tool +content TEXT NOT NULL +intent VARCHAR(30) -- health_record / diet / medication / exercise / report / chat +metadata_json JSONB -- 结构化数据(录入数值、食物列表、卡片数据等) +created_at TIMESTAMP +``` + +#### consultations + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +doctor_id UUID REFERENCES doctors(id) +status VARCHAR(20) NOT NULL -- ai_talking / waiting_doctor / doctor_replied / closed +month INTEGER NOT NULL -- 所属月份,用于配额计算 +created_at TIMESTAMP +closed_at TIMESTAMP +``` + +#### consultation_messages + +```sql +id UUID PRIMARY KEY +consultation_id UUID REFERENCES consultations(id) +sender_type VARCHAR(10) NOT NULL -- user / doctor / ai +sender_name VARCHAR(50) +content TEXT NOT NULL +created_at TIMESTAMP +``` + +#### doctors + +```sql +id UUID PRIMARY KEY +name VARCHAR(50) NOT NULL +title VARCHAR(50) -- 主任医师/副主任医师 +department VARCHAR(50) -- 心血管内科/营养科 等 +avatar_url VARCHAR(500) +introduction TEXT +is_active BOOLEAN DEFAULT TRUE +created_at TIMESTAMP +``` + +#### follow_ups + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +title VARCHAR(200) NOT NULL +doctor_name VARCHAR(50) +department VARCHAR(50) +scheduled_at TIMESTAMP NOT NULL +notes TEXT +status VARCHAR(20) NOT NULL -- upcoming / completed / cancelled +created_at TIMESTAMP +``` + +#### refresh_tokens + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +token VARCHAR(500) UNIQUE NOT NULL +expires_at TIMESTAMP NOT NULL +is_revoked BOOLEAN DEFAULT FALSE +created_at TIMESTAMP +``` + +#### verification_codes + +```sql +id UUID PRIMARY KEY +phone VARCHAR(20) NOT NULL +code VARCHAR(6) NOT NULL +expires_at TIMESTAMP NOT NULL +is_used BOOLEAN DEFAULT FALSE +created_at TIMESTAMP +``` + +#### notification_preferences + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) UNIQUE +medication_reminder BOOLEAN DEFAULT TRUE +followup_reminder BOOLEAN DEFAULT TRUE +doctor_reply BOOLEAN DEFAULT TRUE +abnormal_alert BOOLEAN DEFAULT TRUE +updated_at TIMESTAMP +``` + +#### device_tokens + +```sql +id UUID PRIMARY KEY +user_id UUID REFERENCES users(id) +platform VARCHAR(10) NOT NULL -- ios / android +push_token VARCHAR(500) NOT NULL +is_active BOOLEAN DEFAULT TRUE +created_at TIMESTAMP +updated_at TIMESTAMP +``` + +### 3.3 索引设计 + +```sql +-- 健康记录:按用户+时间查询高频 +CREATE INDEX idx_health_records_user_time ON health_records(user_id, recorded_at DESC); +CREATE INDEX idx_health_records_user_type ON health_records(user_id, metric_type); + +-- 用药:按时段扫描提醒 +CREATE INDEX idx_medications_active_time ON medications(user_id, is_active); +CREATE INDEX idx_medication_logs_medication ON medication_logs(medication_id, created_at DESC); + +-- 对话:按用户+时间 +CREATE INDEX idx_conversations_user_time ON conversations(user_id, updated_at DESC); +CREATE INDEX idx_conversation_messages_conv ON conversation_messages(conversation_id, created_at); + +-- 问诊:轮询新消息 +CREATE INDEX idx_consultation_messages_consult ON consultation_messages(consultation_id, created_at DESC); + +-- 饮食:按日期查询 +CREATE INDEX idx_diet_records_user_date ON diet_records(user_id, recorded_at DESC); + +-- 验证码:清理过期 +CREATE INDEX idx_verification_codes_phone ON verification_codes(phone, created_at DESC); +``` + +--- + +## 四、API 设计 + +### 4.1 认证 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/auth/send-sms` | 发送短信验证码 `{phone}`(开发阶段直接返回成功,不做真实发送) | +| POST | `/api/auth/login` | 验证码登录 `{phone, smsCode}`(开发阶段任意6位数字通过) | +| POST | `/api/auth/refresh` | 刷新 token `{refreshToken}` → `{accessToken, refreshToken}` | +| POST | `/api/auth/logout` | 登出 `{refreshToken}` | + +**Token 策略:** +- `access_token`:30 分钟,前端内存持有 +- `refresh_token`:30 天,flutter_secure_storage 存储 +- 前端收到 401 → Dio 拦截器自动用 refresh_token 换新 access_token → 重试原请求 +- 刷新时同时下发新的 refresh_token(续期 30 天),旧 refresh_token 立即失效 +- 连续 30 天未使用 App 导致 refresh_token 过期 → 需重新登录 +- 一次登录长期有效,除非主动退出或 30 天未使用 + +### 4.2 AI 对话 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/ai/{agent_type}/chat` | SSE 流式对话 | +| GET | `/api/ai/conversations` | 获取对话列表 | +| GET | `/api/ai/conversations/{id}` | 获取对话历史 | +| DELETE | `/api/ai/conversations/{id}` | 删除对话 | + +**查询参数:** `message`, `conversationId?`(不传则新建对话) + +**agent_type**:`default` / `consultation` / `health` / `diet` / `medication` / `report` / `exercise` + +**SSE 事件格式:** +``` +data: {"action":"notice","message":"正在分析..."} // Tool Calling 前先发提示 +data: {"action":"notice","message":"正在记录血压数据..."} // 每次调 Tool 前都发 +data: {"action":"answer","data":"你"} +data: {"action":"answer","data":"的"} +data: {"action":"answer","data":"血压"} +data: {"action":"answer","data":"是"} +... +data: {"action":"tool_result","tool":"record_health_data","data":{...}} +data: {"action":"answer","data":"已记录"} +... +data: {"action":"conversation_id","data":"abc123"} +data: [DONE] +``` + +每次 Tool Calling 循环调 Tool 前,先发一条 notice 事件,避免用户对着空白等待。 + +### 4.3 VLM 食物识别 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/ai/analyze-food-image` | 上传食物照片 | + +**请求:** `multipart/form-data`,字段 `images`(支持多张) + +**响应:** +```json +{ + "foods": [ + { + "name": "米饭", "portion": "约1碗", "calories": 174, + "proteinGrams": 3.9, "carbsGrams": 38.9, "fatGrams": 0.3 + } + ], + "totalCalories": 644, + "warnings": ["红烧肉脂肪偏高"], + "score": 3 +} +``` + +### 4.4 健康数据 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/health-records` | 查询 `?type=&days=` | +| POST | `/api/health-records` | 新增(AI Tool 或手动) | +| PUT | `/api/health-records/{id}` | 修改 | +| GET | `/api/health-records/latest` | 获取各指标最新值 | +| GET | `/api/health-records/trend` | 趋势数据 `?type=&period=7/30/90` | + +### 4.5 用药管理 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/medications` | 获取用药列表 | +| POST | `/api/medications` | 添加用药 | +| PUT | `/api/medications/{id}` | 修改用药 | +| DELETE | `/api/medications/{id}` | 删除用药 | +| POST | `/api/medications/{id}/confirm` | 确认服药打卡 | + +### 4.6 饮食记录 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/diet-records` | 查询 `?date=&meal_type=` | +| POST | `/api/diet-records` | 新增 | +| PUT | `/api/diet-records/{id}` | 修改 | +| DELETE | `/api/diet-records/{id}` | 删除 | + +### 4.7 运动计划 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/exercise-plans/current` | 获取本周计划 | +| POST | `/api/exercise-plans` | 创建计划 | +| PUT | `/api/exercise-plans/{id}` | 修改计划 | +| POST | `/api/exercise-plans/items/{id}/checkin` | 打卡某日运动 | + +### 4.8 报告管理 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/reports/upload` | 上传报告文件 | +| GET | `/api/reports` | 报告列表 | +| GET | `/api/reports/{id}` | 报告详情(含 AI 解读) | +| PUT | `/api/reports/{id}/doctor-review` | 医生审核(医生端) | + +### 4.9 问诊 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/doctors` | 可咨询的医生列表 | +| POST | `/api/consultations` | 创建问诊 | +| GET | `/api/consultations` | 问诊列表 | +| GET | `/api/consultations/{id}` | 问诊详情(含消息) | +| POST | `/api/consultations/{id}/messages` | 发送消息 | +| GET | `/api/consultations/{id}/messages?after={msgId}` | 轮询新消息 | +| GET | `/api/user/consultation-quota` | 剩余问诊次数 | + +### 4.10 用户与档案 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/user/profile` | 获取个人信息 | +| PUT | `/api/user/profile` | 修改资料 | +| GET | `/api/user/health-archive` | 获取健康档案 | +| PUT | `/api/user/health-archive` | 更新健康档案 | +| DELETE | `/api/user/account` | 注销账号 | + +### 4.11 文件上传 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/files/upload` | 上传文件(食物图/报告/处方) | +| GET | `/api/files/{id}` | 获取文件 | +| DELETE | `/api/files/{id}` | 删除文件 | + +### 4.12 推送与通知 API + +| 方法 | 路径 | 说明 | +|------|------|------| +| POST | `/api/notifications/register-device` | 注册设备推送 token | +| GET | `/api/notifications/preferences` | 获取通知偏好 | +| PUT | `/api/notifications/preferences` | 更新通知偏好 | + +--- + +## 五、前端架构(Flutter) + +### 5.1 目录结构 + +参考 YYZ 项目的组织方式: + +``` +lib/ +├── main.dart # 入口 +├── app.dart # MaterialApp + 主题 + 路由 +│ +├── core/ # 全局基础设施 +│ ├── api_client.dart # Dio 封装:token 注入、401 自动刷新、统一报错 +│ ├── app_theme.dart # 薰衣草紫主题 +│ ├── app_router.dart # GoRouter 配置 +│ └── secure_storage.dart # Token 安全存储 +│ +├── models/ # 数据模型(freezed) +│ ├── user.dart +│ ├── health_record.dart +│ ├── food_record.dart +│ ├── medication.dart +│ ├── exercise_plan.dart +│ ├── consultation.dart +│ ├── report.dart +│ └── ai_message.dart +│ +├── providers/ # Riverpod 状态管理 +│ ├── auth_provider.dart # 认证状态 +│ ├── chat_provider.dart # 对话状态(当前 Agent + 消息列表) +│ ├── health_data_provider.dart # 健康数据 +│ ├── medication_provider.dart # 用药 +│ ├── diet_provider.dart # 饮食 +│ ├── exercise_provider.dart # 运动计划 +│ ├── consultation_provider.dart # 问诊 +│ └── report_provider.dart # 报告 +│ +├── services/ # 业务服务层 +│ ├── auth_service.dart # 认证 +│ ├── ai_service.dart # AI 对话(SSE 流式) +│ ├── health_service.dart # 健康数据 CRUD +│ ├── diet_service.dart # 饮食 CRUD +│ ├── medication_service.dart # 用药 CRUD +│ ├── exercise_service.dart # 运动计划 +│ ├── consultation_service.dart # 问诊 +│ ├── report_service.dart # 报告 +│ └── user_service.dart # 用户/档案 +│ +├── pages/ # 页面 +│ ├── auth/ +│ │ └── login_page.dart # 登录 +│ │ +│ ├── home/ +│ │ ├── home_page.dart # 首页骨架(抽屉 + 卡片 + 对话流 + 输入框) +│ │ └── widgets/ # 首页专属组件 +│ │ ├── task_card_area.dart # 任务卡片区 +│ │ ├── agent_panel.dart # Agent 功能面板 +│ │ ├── chat_bubble.dart # 聊天气泡 +│ │ ├── data_confirm_card.dart# 数据确认卡片 +│ │ ├── diet_result_card.dart # 饮食分析卡片 +│ │ ├── food_edit_sheet.dart # 食物编辑面板 +│ │ ├── medication_card.dart # 用药确认卡片 +│ │ ├── report_card.dart # 报告解读卡片 +│ │ └── health_drawer.dart # 侧滑抽屉 +│ │ +│ ├── profile/ +│ │ ├── profile_page.dart # 个人中心 +│ │ ├── edit_profile_page.dart # 编辑资料 +│ │ └── health_archive_page.dart # 健康档案 +│ │ +│ ├── chart/ +│ │ └── trend_page.dart # 趋势图表 +│ │ +│ ├── calendar/ +│ │ └── health_calendar_page.dart # 健康日历 +│ │ +│ ├── medication/ +│ │ ├── medication_list_page.dart # 用药列表 +│ │ └── medication_edit_page.dart # 编辑用药 +│ │ +│ ├── report/ +│ │ ├── report_list_page.dart # 报告列表 +│ │ └── report_detail_page.dart # 报告详情 +│ │ +│ ├── consultation/ +│ │ ├── doctor_list_page.dart # 医生列表 +│ │ └── doctor_chat_page.dart # 问诊对话 +│ │ +│ ├── exercise/ +│ │ └── exercise_plan_page.dart # 运动计划管理 +│ │ +│ ├── diet/ +│ │ └── diet_record_list_page.dart# 饮食记录列表 +│ │ +│ ├── followup/ +│ │ └── followup_list_page.dart # 复查列表 +│ │ +│ └── settings/ +│ ├── settings_page.dart # 设置 +│ ├── notification_prefs_page.dart +│ └── static_text_page.dart # 隐私/协议/关于(纯文本) +│ +├── widgets/ # 通用组件 +│ ├── app_button.dart # 主/次/文字按钮 +│ ├── app_card.dart # 卡片容器 +│ ├── app_input.dart # 输入框 +│ ├── capsule_button.dart # 胶囊按钮 +│ ├── loading_widget.dart # 加载动画 +│ └── empty_state.dart # 空状态 +│ +└── utils/ + ├── sse_handler.dart # SSE 流处理 + ├── markdown_utils.dart # Markdown 渲染 + └── format.dart # 日期/数值格式化 +``` + +### 5.2 状态管理 + +使用 Riverpod(Notifier + NotifierProvider),参考 YYZ 模式: + +```dart +// 认证 +final authProvider = NotifierProvider(AuthNotifier.new); + +// 聊天(核心) +final chatProvider = NotifierProvider(ChatNotifier.new); +// ChatState: 当前 agent_type、消息列表、conversationId、是否流式中 + +// 各业务域 +final healthDataProvider = NotifierProvider(...); +final medicationProvider = NotifierProvider(...); +... +``` + +### 5.3 HTTP 请求层 + +```dart +// Dio 封装 +class ApiClient { + late final Dio _dio; + + // 拦截器 1:自动带 Authorization: Bearer {accessToken} + // 拦截器 2:收到 401 → 自动调 /api/auth/refresh → 重试 + // 拦截器 3:统一错误处理 +} +``` + +所有 Service 层返回类型安全的模型对象,页面不直接处理 JSON。 + +### 5.4 路由设计 + +| 路由 | 页面 | 说明 | +|------|------|------| +| `/login` | 登录页 | 手机号+验证码登录 | +| `/home` | 首页 | 对话流 + 任务卡片区 + Agent 面板 + 输入框 | +| `/trend/:type` | 趋势图表 | 单指标折线图,7/30/90天切换 | +| `/calendar` | 健康日历 | 月视图,标记用药/运动/复查 | +| `/medications` | 用药列表 | 当前用药计划列表 | +| `/medications/:id/edit` | 编辑用药 | 修改药品名/剂量/时间 | +| `/reports` | 报告列表 | 按时间倒序 | +| `/reports/:id` | 报告详情 | AI解读 + 医生审核 + 原始图片 | +| `/doctors` | 医生列表 | 可选医生(3-4名) | +| `/consultation/:id` | 问诊对话 | 患者与医生文字聊天 | +| `/exercise-plan` | 运动计划 | 本周每天的运动安排+打卡 | +| `/diet-records` | 饮食记录列表 | 按日期查看历史饮食 | +| `/profile` | 个人中心 | 头像+诊断+菜单入口 | +| `/profile/edit` | 编辑资料 | 姓名/性别/出生日期 | +| `/health-archive` | 健康档案 | 完整健康信息(6大类) | +| `/followups` | 复查列表 | 即将到来/已完成 | +| `/settings` | 设置 | 隐私/通知/字体/协议/关于/退出 | +| `/settings/notifications` | 通知偏好 | 四类推送独立开关 | +| `/page/:type` | 静态文本页 | 隐私政策/服务协议/关于 | + +### 5.5 首页组件交互 + +- **任务卡片区**:`AnimatedContainer` + `GestureDetector` 折叠/展开 +- **对话流**:`ListView.builder` + `reverse: true` +- **Agent 面板**:底部弹出 `AnimatedContainer`,面板内容随 agent_type 切换 +- **输入框**:`TextField` + `Row`,附件按钮 📎 + 系统键盘语音转文字 +- **侧滑抽屉**:`Scaffold` + `Drawer` + +### 5.6 Agent 切换流程 + +``` +用户点击胶囊 [记数据] + → 胶囊高亮 + → chatProvider.setAgentType(AgentType.health) + → 底部弹出记数据面板(手动录入入口) + → AI 对话上下文切换到记数据 + → 用户输入 → POST /api/ai/health/chat → SSE 流式 + +用户再次点击 [记数据] + → 胶囊恢复 + → 面板收起 + → chatProvider.setAgentType(AgentType.default) +``` + +### 5.7 消息类型 Widget + +| 消息类型 | Widget | 说明 | +|---------|--------|------| +| 纯文本 | ChatBubble | AI 左白底紫左边框,用户右紫底白字 | +| 数据确认 | DataConfirmCard | "已记录:血压 135/85 ✅" + 可点击编辑 | +| 饮食分析 | DietResultCard | 食物列表 + 热量 + 评分 + 警告 + "能不能吃" | +| 用药确认 | MedicationConfirmCard | 药名 + 剂量 + [确认] [修改] | +| 报告解读 | ReportCard | 指标列表 + AI 分析 + "待医生确认" | +| 快捷选项 | QuickOptionsRow | 一行可点击按钮,如 [闷痛] [刺痛] | + +### 5.8 SSE 流处理 + +参考 YYZ 的 `ChatStreamHandler` 模式: + +```dart +class SseHandler { + // 订阅 Dio 流式响应 + // 解析 SSE 事件:answer / notice / tool_result / conversation_id / [DONE] + // 逐步追加 token 到当前 AI 消息 + // 处理 tool_result 更新消息中的结构化数据 + // onDone → 标记消息 status: 'done' +} +``` + +### 5.9 平台支持 + +- Android 最低:7.0(API 24) +- iOS 最低:15.0 +- 不做暗黑模式 + +### 5.10 Flutter 依赖 + +```yaml +dependencies: + flutter: + sdk: flutter + + # 状态管理 + flutter_riverpod: ^3.2.0 + + # HTTP + dio: ^5.4.0 + + # 安全存储 + flutter_secure_storage: ^9.2.0 + + # 路由 + go_router: ^14.0.0 + + # 图表 + fl_chart: ^0.68.0 + + # 本地存储 + shared_preferences: ^2.2.0 # 轻量键值存储(字体大小等设置) + + # 相机 & 图片 + image_picker: ^1.0.0 + file_picker: ^10.3.7 + + # 推送 + jpush_flutter: ^4.0.0 # 极光推送 + +dev_dependencies: + flutter_test: + sdk: flutter + freezed: ^2.5.0 + json_serializable: ^6.8.0 + build_runner: ^2.4.0 +``` + +--- + +## 六、定时任务 + +### 6.1 用药提醒扫描 + +.NET `BackgroundService` 每分钟扫描一次: + +```csharp +public class MedicationReminderService : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + // 1. 查询:reminder_enabled = true AND 服药时间 ≤ 当前时间 AND 今天未打卡 + // 2. 对每条 → 查用户 device_token → 调用极光推送 + // 3. 记录推送日志 + // 4. 检查漏服(超时未打卡 → 再推 → 标记漏服) + + await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); + } + } +} +``` + +### 6.2 漏服检测 + +- 服药时间已过 15 分钟未打卡 → 再推一次 +- 服药时间已过 30 分钟未打卡 → 再推一次 +- 服药时间已过 1 小时未打卡 → 标记漏服,停止提醒 + +### 6.3 其他定时任务 + +| 任务 | 频率 | 说明 | +|------|------|------| +| 复查提醒 | 每天 1 次 | 检查未来 3 天内的复查计划 → 推送 | +| 对话记录清理 | 每天 1 次 | 删除 30 天前的对话 | +| 验证码清理 | 每小时 1 次 | 删除过期验证码 | + +--- + +## 七、文件存储 + +### 7.1 MinIO 存储桶 + +| 存储桶 | 内容 | 生命周期 | +|------|------|------| +| `food-images` | 食物照片 | 30 天 | +| `report-images` | 报告图片/PDF | 永久 | +| `avatars` | 用户头像 | 永久 | + +### 7.2 上传流程 + +``` +Flutter → Dio multipart → .NET API → 存入 MinIO → 返回文件 URL + → VLM 食物识别时:文件 URL 传给千问 VL +``` + +### 7.3 图片上传规格 + +| 参数 | 食物照片 | 报告图片/PDF | +|------|---------|------------| +| 支持格式 | JPEG / PNG / HEIC | JPEG / PNG / HEIC / PDF | +| 最大文件 | 10MB | 10MB | +| 前端处理 | 原图上传,不压缩 | 原图上传,不压缩 | + +--- + +## 八、推送通知 + +### 8.1 推送架构 + +``` +.NET BackgroundService → 极光推送 SDK → 极光服务器 → APNs (iOS) / 极光通道 (Android) +``` + +- 设备注册时 Flutter 获取极光 registration ID → 上报后端存入 device_tokens 表 +- 后端推送时查 device_tokens → 调用极光推送 API + +### 8.2 推送类型 + +| 类型 | 触发 | iOS | Android | +|------|------|-----|---------| +| 用药提醒 | BackgroundService | 极光 → APNs | 极光通道 | +| 复查提醒 | BackgroundService | 同上 | 同上 | +| 医生回复 | 医生发消息时 | 同上 | 同上 | +| 异常警告 | 硬件上传异常时(后期) | 同上 | 同上 | + +### 8.3 点击行为 + +| 通知类型 | 点击后跳转 | +|---------|----------| +| 用药提醒 | 首页 + 自动打开药管家 | +| 复查提醒 | 复查详情 | +| 医生回复 | 该问诊对话 | +| 异常警告 | 该指标趋势页 | + +--- + +## 九、AI 模型配置 + +| 用途 | 模型 | API 地址 | +|------|------|------| +| LLM 对话 | DeepSeek `deepseek-chat` | `https://api.deepseek.com/v1` | +| VLM 食物识别 | 千问 `qwen-vl-max` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | +| VLM 备用 | 火山引擎 `doubao-vision-pro` | `https://ark.cn-beijing.volces.com/api/v3` | + +--- + +## 十、部署 + +### 10.1 本地开发 + +- `dotnet run` 启动后端 +- PostgreSQL + MinIO 用 Docker 本地拉起 +- Flutter `flutter run` 连模拟器/真机调试 + +### 10.2 后期上云 + +- .NET 10 Web API,Docker 单容器部署 +- PostgreSQL → 阿里云 RDS +- MinIO → 阿里云 OSS +- 配置通过环境变量注入 + +--- + +## 十一、开发顺序 + +### 第一阶段:基础设施 + +| # | 任务 | +|---|------| +| 1 | .NET 后端项目搭建 + Clean Architecture 骨架 | +| 2 | PostgreSQL 数据库初始化 + EF Core 迁移 | +| 3 | JWT 认证系统 | +| 4 | Flutter 项目搭建 + 路由 + 主题 | +| 5 | Dio 封装 + 401 拦截器 | +| 6 | OpenAiCompatibleClient 实现 | + +### 第二阶段:核心 AI + +| # | 任务 | +|---|------| +| 7 | PromptManager + 7 个 Agent 的 System Prompt | +| 8 | Tool Calling 引擎 | +| 9 | 默认对话 Agent + SSE 流式 | +| 10 | 记数据 Agent | +| 11 | 药管家 Agent | +| 12 | 拍饮食 Agent(含 VLM) | +| 13 | AI 问诊 Agent | +| 14 | 看报告 Agent | +| 15 | 运动计划 Agent | + +### 第三阶段:业务功能 + +| # | 任务 | +|---|------| +| 16 | 健康数据 CRUD API | +| 17 | 饮食记录 API | +| 18 | 用药管理 API + 服药提醒后台任务 | +| 19 | 运动计划 API | +| 20 | 报告上传 + AI 解读 API | +| 21 | 问诊 API(医生列表 + 消息轮询) | + +### 第四阶段:前端 + +| # | 任务 | +|---|------| +| 22 | 登录页 | +| 23 | 首页骨架(抽屉 + 卡片区 + 对话流 + 输入框) | +| 24 | 6 个 Agent 面板 UI | +| 25 | SSE 流处理 + 消息气泡 | +| 26 | 数据确认卡片 / 饮食分析卡片 / 用药确认卡片 | +| 27 | 侧滑抽屉(健康概览 + 历史对话) | +| 28 | 各功能页面(个人中心、健康档案、趋势图、报告等) | + +### 第五阶段:联调 + 完善 + +| # | 任务 | +|---|------| +| 29 | 极光推送集成 | +| 30 | MinIO 文件存储集成 | +| 31 | 短信服务对接 | +| 32 | 异常处理完善 | +| 33 | 联调测试 | diff --git a/健康管家-需求规格文档-v2.md b/健康管家-需求规格文档-v2.md new file mode 100644 index 0000000..54ba4d8 --- /dev/null +++ b/健康管家-需求规格文档-v2.md @@ -0,0 +1,804 @@ +# 健康管家 — 需求规格文档 V2 + +> 基于原始需求文档,经多轮讨论后重新整理。本文档覆盖全部功能,不做分期,一次性设计完整。 + +--- + +## 一、产品概述 + +### 1.1 产品定位 + +面向心脏术后康复患者的私人 AI 健康管家。以对话为核心交互方式(参考蚂蚁阿福),患者通过自然语言记录健康数据、获取饮食运动建议、管理用药、解读报告。配合公司自有医疗硬件(后期接入),实现居家自检。每月享有 2-3 次与签约医生的真人问诊机会。 + +### 1.2 用户角色 + +- **患者**:心脏术后康复患者(如冠心病 PCI 术后),年龄偏大,手机操作能力参差不齐 +- **医生**:公司签约的私人医生团队,通过 Web 后台管理患者、审阅报告、在线问诊 + +### 1.3 核心设计理念 + +**"对话即入口,对话即服务"** —— 用户打开 App 看到的是一个对话框。所有功能通过对话完成,AI 理解用户意图并执行。 + +### 1.4 商业模式 + +硬件 + App + 医生服务打包付费。患者购买产品 → 下载 App → 手机号登录 → 开始使用。 + +--- + +## 二、患者获取流程 + +患者自行购买产品 → 下载 App → 手机号验证码登录(登录即注册)→ 进入首页 → AI 主动问候 → 通过对话逐步完善健康档案。 + +``` +购买产品 → 下载App → 手机号登录 → AI问候 → 对话建档 +``` + +--- + +## 三、登录与认证 + +### 3.1 登录方式 + +- **手机号 + 短信验证码登录**(登录即注册,无单独注册流程) +- 微信登录(后期加,首次需绑定手机号) +- Apple ID 登录(后期加,首次需绑定手机号) +- 登录前必须勾选同意《服务协议》《隐私协议》 + +### 3.2 登录状态 + +- 登录一次后长期有效,用户日常打开 App 直接进首页 +- 仅在 token 全部过期后才需要重新登录 + +### 3.3 业务规则 + +- 开发阶段验证码任意 6 位数字通过;生产环境对接短信服务商(待定) +- 不强制填昵称,登录后去个人中心自行修改 +- 不加入脸/指纹解锁和实名认证 + +--- + +## 四、首页 + +### 4.1 整体布局 + +``` +┌──────────────────────────────────┐ +│ 左上角头像 → 侧滑抽屉 │ +│ │ +│ 任务卡片区(可折叠) │ ← 有任务才显示对应卡片 +│ - AI 主动问候(带数据) │ +│ - 用药提醒卡片 │ +│ - 健康打卡进度 │ +│ - 今日数据摘要 │ +│ - 异常指标警告 │ +│ - 复查/随访提醒 │ +│ │ +│ 对话流 │ ← 跟 AI 的聊天内容 +│ │ +├──────────────────────────────────┤ +│ 智能体栏(横向滑动胶囊按钮) │ +│ [AI问诊] [记数据] [拍饮食] │ +│ [药管家] [看报告] [运动计划] │ +├──────────────────────────────────┤ +│ [📎] [输入框...(系统键盘语音转文字)] [📤] │ +└──────────────────────────────────┘ +``` + +### 4.2 AI 问候 + +- 每次打开 App 自动进入新对话 +- AI 根据时间段主动问候,仅当健康数据存在异常时附带提醒 +- 异常示例:"早上好!昨天心率 105,有点偏高,注意休息哦" +- 无异常时纯问候:"早上好!今天有什么可以帮您的?" +- 用药、运动、打卡等日常提醒由任务卡片区负责,不在问候语中出现 + +**首次使用**: +- 新用户(零数据、档案全空)首次打开 App +- AI 问候后主动引导建档:"我是你的AI健康管家,为了更好地帮助你,我们先来完善一下你的健康档案吧?" +- 不强制,用户可跳过,但 AI 会在后续对话中适时提醒 +- 侧滑抽屉健康概览各指标显示"--" + +### 4.3 任务卡片区 + +**显示规则:** +- 有相关任务时才显示对应卡片,无任务时不占空间 +- 用户向上滑动对话流时卡片区自动折叠 +- 有新任务提醒时卡片区自动展开 +- 用户可手动点击箭头折叠/展开 +- 默认展开 +- 多卡片时按行排列 + +**卡片交互规则:** +- 每张卡片为一行,左侧显示任务内容,右侧配有操作按钮 +- 每张卡片同时是该功能模块的快捷入口,点击卡片可进入对应管理界面 +- √ 按钮为快捷打卡:点击效果等同于进入管理界面完成打卡 + +**卡片类型:** + +| 卡片 | 触发条件 | 显示内容 | 交互 | +|------|---------|---------|------| +| 用药提醒 | 到服药时间 | "💊 计划 8:00 吃 阿司匹林 100mg" | 右侧 [✓] 按钮,点击即打卡;超时未打卡卡片变红 | +| 运动打卡 | 今日有运动计划未完成 | "🏃 今日待运动:跑步 30 分钟" | 右侧 [✓] 按钮,点击即完成;超期未完成卡片变红 | +| 指标测量 | 今日有指标未测量 | "🩺 今日待测量:血压" | 点击进入记数据界面,不设 ✓ 打卡 | +| 异常警告 | 健康数据超出正常范围 | "⚠️ 昨日心率 105,偏高" | 点击进入该指标趋势页 | +| 数据摘要 | 今日已有健康记录 | "今日已记录:血压 128/82、心率 72" | 点击进入健康数据详情 | +| 复查提醒 | 未来 3 天内有复查安排 | "📋 后天 15:00 心内科复查" | 点击进入复查详情 | + +### 4.4 对话流 + +- 用户和 AI 的聊天记录,新消息出现在底部 +- 支持多种消息类型:文本气泡、数据确认卡片、饮食记录卡片、报告解读卡片、用药确认卡片、图片 +- 每次打开 App 自动进入新对话 +- 对话记录保留 30 天 +- 历史对话可通过侧滑抽屉中的对话列表回看、继续聊、删除 + +### 4.5 无传统底部 Tab Bar + +底部黄金位置留给 AI 输入框。功能入口全部上移到智能体栏和侧滑抽屉。 + +--- + +## 五、智能体系统 + +### 5.1 交互模式 + +- 智能体栏横向滑动,6 个胶囊按钮 +- **点击胶囊** → 胶囊高亮变色 → 从底部弹出该智能体的功能面板 → 对话上下文切换至该智能体 +- **再次点击同一胶囊** → 面板收起 → 胶囊恢复默认 → 回到默认对话 +- 所有智能体均支持 **AI 对话 + 手动操作双通道** + +### 5.2 AI 问诊 + +**入口**:点击 [AI问诊] 胶囊 + +**面板内容**:[找医生] 按钮 + +**AI 对话流程**: +1. AI 先查看患者全部信息(病史、用药、近期数据) +2. AI 多轮阶段化追问,每步给出快捷选项 +3. AI 给出初步分析 + 建议: + - 日常问题 → AI 直接回答 + - 轻微症状 → AI 追问 + 给出建议 + - 紧急情况(胸痛、呼吸困难等)→ 建议立即就医 + - 用户主动要求 → 转医生 + +**转医生流程**: +1. 用户点 [找医生] → 显示可选医生列表(公司签约的 3-4 名不同科室医生) +2. 选择医生 → 查看本月剩余次数 → 确认 +3. 先与医生的 AI 分身对话(医生有空时在 Web 后台查看并回复) +4. 医生在 Web 后台可实时看到 AI 与患者的对话内容 +5. 对话结束 → 扣除本月 1 次机会 + +**医生 AI 分身**: +- 每个医生有自己的 AI 分身(形象、口吻不同) +- AI 回复末尾标注"以上为 AI 分析,具体请咨询 X 主任" +- 以下情况建议转真人:胸痛、呼吸困难、心悸;血压持续 >160/100;心率异常;用户明确要求 + +### 5.3 记数据 + +**入口**:点击 [记数据] 胶囊 + +**面板内容**:[手动录入血压] [手动录入血糖] [手动录入心率] [手动录入血氧] [手动录入体重] + +**支持指标**:血压(收缩压+舒张压)、心率、血糖、血氧、体重 + +**AI 对话录入**: +- 用户说"血压 135/85" → AI 解析指标+数值→填入对应页面→回复确认卡片 +- 用户说"120"(缺指标)→ AI 追问"是收缩压还是血糖?" +- 用户说"早上血压 135/85"(缺时间)→ 取当前时间,告知用户 + +**录入来源标记**:记录列表中标注是否"设备自动同步",AI 对话录入和手动录入不区分来源 + +**异常提醒**:数值超出正常范围时,AI 在确认卡片中附带提醒 + +**正常值参考范围**(医生可为具体患者调整): + +| 指标 | 正常范围 | 偏高警戒 | 偏低警戒 | +|------|---------|---------|---------| +| 收缩压 | 90-139 mmHg | ≥140 | ≤89 | +| 舒张压 | 60-89 mmHg | ≥90 | ≤59 | +| 心率 | 60-100 次/分 | ≥101 | ≤59 | +| 空腹血糖 | 3.9-6.1 mmol/L | ≥7.0 | ≤3.8 | +| 血氧 | 95-100% | — | ≤94 | +| 体重 | BMI 18.5-24 | 个体化 | 个体化 | + +### 5.4 拍饮食 + +**入口**:点击 [拍饮食] 胶囊 + +**面板内容**:[拍照] [上传照片](支持多张) + +**VLM 识别**:使用千问 VL 模型 + +**流程**: +1. 用户拍照或从相册选图(支持多张,多张识别更准) +2. 显示照片 + "正在分析食物..." +3. VLM 识别食物种类、估算份量 +4. 面板展示识别结果(食物列表,每项可编辑/删除/新增) +5. 用户确认无误后点 [确定] +6. AI 基于最终确认的食物数据生成评价:总热量、健康评分、单项警告、整体饮食建议 +7. AI 追问餐次:[早餐] [午餐] [晚餐] [加餐],未选择时 AI 根据时间推断 +8. [确认保存] [取消] + +**编辑规则**:用户修改食物数据后,AI 基于最新结果重新生成评价 + +**"能不能吃"判断依据**:疾病诊断、过敏信息、药物相克、医生饮食建议、近期健康指标 + +**编辑界面**: +- 识别结果直接在面板中展示,每条食物独立一行 +- 每项可修改:食物名(文本输入)、份量(文本输入) +- 支持删除任意食物条目 +- 支持手动添加新食物条目 +- 修改后热量自动重算 +- 对话修正作为补充:对 AI 说"我只吃了半碗" → AI 自动更新记录 + +**识别失败处理**: +- 手动修正识别结果 +- 补充文字描述 +- 放弃识别,完全自己填写 +- 超过 15 秒提示"分析超时,请重试" +- 一顿饭最多识别 8 种食物 + +### 5.5 药管家 + +**入口**:点击 [药管家] 胶囊 + +**面板内容**:[用药管理] [用药提醒] + +**用药计划来源**: +1. 医生处方(拍照上传 → AI 解析 → 生成计划 → 患者确认) +2. AI 对话录入(用户说"我每天早上吃阿司匹林 100mg" → AI 解析 → 展示确认卡片) +3. 手动表单录入(点 [用药管理] → 填写药品名/剂量/时间) + +**AI 对话示例**: +``` +用户: "医生让我吃阿托伐他汀 20mg,从今天开始,每日一次,晚饭后吃" +AI: "晚饭后具体是几点吃呢?" +用户: "8点" +AI: "收到!已创建用药计划: + 💊 阿托伐他汀 20mg 每天 20:00 + 需要调整吗?" + [确认] [修改时间] [改剂量] +``` + +**时间转换规则**:用户使用模糊时间描述(早饭后/晚饭后等)时,AI 必须追问具体时间点,不做默认映射。 + +**服药提醒**: +- 到预设时间 → 推送通知 → 点通知进 App → 确认卡片 +- [我已服用] → 记录打卡 → AI:"真棒!已记录 ✅" +- [晚点提醒] → 15 分钟后再推 → 30 分钟仍未确认 → 标记"漏服" +- 漏服后 1 小时再提醒一次 + +**暂不做**:拍药盒识别、药物库存管理、药物相互作用检查 + +### 5.6 看报告 + +**入口**:点击 [看报告] 胶囊 → 直接调起相机 / 文件选择器 + +**支持格式**:拍照、从相册选图、PDF 文件 + +**解读范围**:数值类报告(血常规、生化全项等)AI 可提取指标并预解读;图像类报告(彩超、CT、心电图等)AI 可能无法准确解读,标注"需医生人工审阅" + +**AI 预解读流程**: +1. 上传完成后显示进度: + - ① 🔍 扫描报告图片... ✓ + - ② 🏷️ 识别报告类型 ✓ + - ③ 📊 提取关键指标... ✓ + - ④ 📝 生成解读报告... ✓ +2. AI 预解读结果展示: + - 提取所有指标及其数值 + - 异常指标标注(红色偏高、黄色偏低、绿色正常) + - AI 初步分析 + - 标注"AI 预解读,待医生确认" + - [查看原始图片] 按钮 +3. **用户可立即查看 AI 预解读结果** +4. 医生在 Web 后台审阅 → 确认/修改/补充 → 最终结果推送通知给患者 +5. 最终结果标记"医生已确认" + +### 5.7 运动计划 + +**入口**:点击 [运动计划] 胶囊 + +**面板内容**:[查看本周计划] [创建新计划] + +**计划内容**:以周为单位,每天指定运动类型和时长 +- 示例:「周一:散步 30 分钟」「周二:慢跑 20 分钟」「周三:休息」... + +**设定方式**: +- AI 对话设定:用户说"我想定个运动计划,每周一三五散步 30 分钟" → AI 拆解为每日条目 → 展示确认 +- 手动设定:面板中点 [创建新计划] → 逐天填写 + +**打卡与追踪**: +- 首页任务卡片区显示当日运动任务,右侧 [✓] 快捷打卡 +- 当日完成则标记为已完成,未完成则卡片持续显示 +- 每天全部完成 = 本周计划完成 +- 不设 AI 鼓励消息 +- 支持随时修改或放弃(对 AI 说或手动编辑) + +--- + +## 六、AI 对话系统 + +### 6.1 对话是功能入口 + +用户不需要在菜单中找功能。直接对 AI 说话,AI 理解意图并执行: + +| 用户说 | AI 做什么 | +|--------|----------| +| "血压 135/85" | 解析指标+数值→记录健康数据→回复确认卡片 | +| "中午吃了牛肉面" | 解析食物→估算热量营养→记录饮食→回复分析结果 | +| "散步了 30 分钟" | 解析运动→估算消耗→记录运动 | +| "我每天早上吃阿司匹林" | 创建用药计划→设定提醒 | +| "最近胸口不舒服" | 启动 AI 问诊追问流程 | +| "帮我看看这份报告" | 触发报告解读流程 | +| "血压多少算正常" | 回答健康知识问题 | + +### 6.2 数据录入规则 + +- **直接录入**:指标明确 + 数值明确 + 时间明确(如"早上血压 135/85") +- **取默认值**:指标明确 + 数值明确 + 时间模糊 → 取当前时间,告知用户 +- **追问**:数值明确但指标模糊(如只说"120")→ AI 追问并提供选项 +- **走问诊流程**:纯症状描述(如"感觉有点头晕") + +### 6.3 AI 回复内容类型 + +- **数据确认卡片** — "已记录:血压 135/85 ✅" + 可点击编辑 +- **饮食分析卡片** — 食物列表 + 热量 + 评分 + 警告 +- **用药确认卡片** — 药名 + 剂量 + 时间 + [确认] [修改] +- **报告解读卡片** — 指标列表 + AI 分析 + "待医生确认"标签 +- **用药提醒卡片** — 药名 + 剂量 + [我已服用] [晚点提醒] + +### 6.4 对话生命周期 + +- 每次打开 App → 自动进入新对话,上一段对话自动转为历史记录 +- 退出 App → 当前对话保留,成为历史对话 +- 对话记录保留 30 天 +- 历史对话可回看、继续聊、删除 +- 不设手动「新建对话」按钮 + +### 6.5 输入框附件 + +输入框旁的 📎 按钮: + +| 操作 | 用途 | +|------|------| +| 📸 拍照 | 拍食物(触发饮食识别)、拍报告(触发报告解读) | +| 🖼️ 从相册选 | 上传已有照片 | +| 📎 传文件 | 上传 PDF 报告 | + +**已决定**: +- AI 回答风格:专业严谨 +- AI 回复直接流式展示文字,不需要"正在输入..."动画 +- 语音输入使用系统键盘自带语音转文字,不额外开发 + +--- + +## 七、拍照识别饮食 + +### 7.1 技术方案 + +使用千问 VL(qwen-vl-max)作为 VLM 模型,后端 httpx 直连调用。火山引擎豆包 Vision 作为备用。 + +### 7.2 识别结果要求 + +每张照片返回: +- 食物名称列表(每项含:名称、份量描述、热量千卡、蛋白质克、碳水克、脂肪克) +- 总热量 +- 单项警告(针对特定食物的警告) +- 整体饮食建议 +- 健康评分(1-5 星) + +### 7.3 餐次归属 + +拍照后需要用户选择餐次(早餐/午餐/晚餐/加餐)。未选择时 AI 根据当前时间推断并追问确认。所有饮食记录按日期+餐次归档,支持后续健康趋势追溯。 + +### 7.4 识别失败处理 + +- 允许手动修正识别结果 +- 允许补充文字描述 +- 允许放弃识别,完全自己填写 +- 正常识别时间 1-5 秒,超过 15 秒提示超时 +- 一顿饭最多识别 8 种食物 + +--- + +## 八、健康数据管理 + +### 8.1 数据类型 + +| 指标 | 录入方式 | 来源标记 | +|------|---------|---------| +| 血压(收缩压+舒张压) | AI 对话 / 蓝牙设备自动同步 | AI 录入 / 设备同步 / 手动修正 | +| 心率 | 同上 | 同上 | +| 血糖 | 同上 | 同上 | +| 血氧 | 同上 | 同上 | +| 体重 | AI 对话 | 同上 | + +### 8.2 录入规则 + +- **AI 对话录入**:AI 解析后展示确认卡片,用户可修改 +- **设备自动同步(后期)**:全自动入库,不需要逐条确认 +- 默认测量时间:未提时间 → 取当前时间,在确认卡片中告知用户 +- 异常值提醒:数值超出正常范围时附带提醒 +- **数据冲突**:同一指标短时间内多次录入时,后者覆盖前者,不做合并 + +### 8.3 趋势图表 + +- 每种指标展示趋势折线图(7 天 / 30 天 / 90 天可选) +- 血压用双轴图(收缩压 + 舒张压同框) +- 点击数据点看详情 +- 支持双指缩放、滑动查看历史 +- 支持导出图片分享给医生 + +### 8.4 健康日历 + +- 月视图日历 +- 标记类型:用药情况、运动完成、复查/随访日期 +- 点击某天弹出当日健康摘要 + +--- + +## 九、运动记录 + +### 9.1 录入方式 + +- **AI 对话录入**:用户说"散步了 30 分钟" → AI 识别运动类型、时长、估算消耗热量 +- **硬件同步(后期)**:手表/手环自动同步 +- **手动修改**:AI 录入后可进入编辑页修改 + +### 9.2 AI 能力 + +- 自动识别运动类型 +- 自动估算消耗热量 +- 支持用户修正 + +--- + +## 十、饮食记录 + +### 10.1 录入方式 + +- **AI 对话录入**:用户说"中午吃了牛肉面" → AI 解析食物 + 估算份量和热量 +- **拍照识别**:通过「拍饮食」智能体 +- **手动修改**:录入后可进入编辑页修改 + +### 10.2 AI 能力 + +- 自动拆解同一餐多个食物 +- 根据描述估算份量和热量 +- 模糊份量自行判断 + +--- + +## 十一、用药管理 + +### 11.1 用药计划来源 + +1. **医生处方**(拍照上传 → AI 解析 → 生成计划 → 患者确认) +2. **AI 对话**(用户口述用药信息 → AI 解析 → 展示确认卡片) +3. **手动表单**(药管家面板 → 填写药品名/剂量/时间) + +### 11.2 服药提醒 + +``` +到服药时间 → 推送通知 → 点通知进入 App → 确认卡片 + ├── [我已服用] → 打卡 → 记录 ✅ + ├── [晚点提醒] → 15分钟后再次推送 + └── 30分钟未确认 → 标记"漏服" → 1小时后再次提醒 +``` + +### 11.3 暂不做 + +- 拍药盒识别 +- 药物库存管理 +- 药物相互作用检查 + +--- + +## 十二、报告管理 + +### 12.1 上传 + +- 从「看报告」智能体进入,直接调起相机/文件选择 +- 支持拍照、从相册选图、PDF 文件 + +### 12.2 解读流程 + +1. 上传 → AI 预解读(用户可立即查看) +2. AI 结果标注"AI 预解读,待医生确认" +3. 医生在 Web 后台审阅、修改、补充 +4. 最终结果推送通知给患者 +5. 最终结果标记"医生已确认" + +### 12.3 解读结果展示 + +- 提取指标及数值 +- 异常标注(红偏高/黄偏低/绿正常) +- AI 初步分析 +- [查看原始图片] +- 多报告对比(后期) + +--- + +## 十三、复查/随访 + +- 医生端创建的复查/随访计划自动同步到患者端 +- 支持复查提醒推送(提前 1-3 天通知) +- 复查列表:即将到来 / 已完成 +- 术后复查节点参考:术后 3/6/9/12 周(依医嘱) + +--- + +## 十四、侧滑抽屉 + +### 14.1 入口 + +左上角头像图标点击打开(从左侧滑出) + +### 14.2 内容 + +``` +┌──────────────┬──────────────────┐ +│ │ │ +│ 👤 张三 │ │ +│ 冠心病支架术后│ │ +│ │ │ +│ [头像点击→个人中心] │ +│ [设置] │ +│ │ │ +│ ❤️ 血压 128/82 (最新) │ +│ 💓 心率 72 │ +│ 💉 血糖 5.2 │ +│ 🫁 血氧 98% │ +│ │ │ +│ 📋 历史对话记录 │ +│ - 2026-05-30 血压咨询 │ +│ - 2026-05-28 饮食分析 │ +│ ... │ +│ │ │ +│ 退出登录 │ +└──────────────┴──────────────────┘ +``` + +- 头像点击 → 个人中心(含账号切换等) +- 设置 → 设置页面(具体内容后续讨论) +- 健康概览:显示各项指标最近一次上传的值,未测过的指标显示"--" +- 历史对话记录:按时间倒序排列,每条显示日期 + 摘要 +- 点击某条历史对话 → 当前对话自动转为历史记录 → 所选对话成为当前活跃对话,可继续聊 +- 要回到之前的对话 → 从历史记录中重新选择 +- 支持删除历史对话 + +--- + +## 十五、个人中心 + +### 15.1 入口 + +侧滑抽屉 → 点击头像 + +### 15.2 菜单 + +- 头像 + 姓名 + 诊断信息 +- 健康档案:完整个人健康信息 +- 设备管理:查看已绑定设备(一期为入口占位,后期蓝牙对接) +- 家属关联(后期) +- 通知偏好设置 +- 修改资料:可编辑姓名、性别、出生日期,手机号不可改 +- 设置:隐私保护中心、通知偏好、字体大小、协议与公告、关于、退出登录(隐私保护中心、协议与公告、关于均为文本展示页,内容后期填充) + +--- + +## 十六、健康档案 + +### 16.1 信息收集方式 + +- **AI 对话自动填写**:AI 在与用户对话中了解信息后自动填充 +- **用户手动填写/修改**:从个人中心 → 健康档案进入,手动编辑 + +### 16.2 档案内容 + +| 类别 | 字段 | +|------|------| +| 基本信息 | 姓名、性别、出生日期、身高、体重 | +| 诊断信息 | 主要诊断(冠心病/心梗等)、手术类型(PCI支架等)、手术日期 | +| 病史 | 高血压、糖尿病、高血脂等慢病史、既往手术史 | +| 过敏 | 药物过敏、食物过敏 | +| 饮食限制 | 低盐、低脂、低糖、忌辣等 | +| 家族病史 | 父母/兄弟姐妹心血管病史 | + +### 16.3 档案维护规则 + +**填写方式**:AI 对话自动填写 + 用户手动填写/修改,两条路均可 + +**冲突处理**:AI 在对话中识别到信息与档案现有记录矛盾时,主动反问确认 +- 示例:档案记录"心梗",用户对话中说"冠心病" → AI:"我注意到你之前记录的是心梗,现在提到的是冠心病,需要我更新吗?" +- 不做字段锁定,不做静默覆盖,用户始终知情 + +### 16.4 档案数据流 + +``` +AI对话了解信息 ──→ 自动填充档案字段 + │ + 用户手动编辑 ←┘ + │ + AI 发现矛盾时反问 + │ + ▼ + 档案持久化存储 + │ + ▼ + AI 对话时作为上下文注入(用于"能不能吃"判断、异常判断等) +``` + +### 16.5 医生视角(患者画像) + +医生在 Web 后台可查看患者的完整健康档案:基本信息、健康数据历史、用药记录、检查报告、饮食运动记录 + +--- + +## 十七、设备绑定 + +### 17.1 策略 + +- 保留设备管理入口(个人中心),暂不做真实蓝牙连接 +- 预留蓝牙数据同步接口 +- 后期对接公司自有硬件(血压计、血氧仪、血糖仪等)以及主流第三方设备 + +### 17.2 后期规划 + +- 蓝牙扫描与绑定 +- 多设备同时连接 +- 设备数据自动同步到健康记录,标记数据来源 + +--- + +## 十八、推送通知 + +### 18.1 推送类型 + +| 类型 | 内容示例 | 触发条件 | +|------|---------|---------| +| 用药提醒 | "🔔 该吃阿司匹林了(100mg)" | 到预设服药时间 | +| 复查提醒 | "📋 后天下午 3 点心内科复查" | 复查前 1-3 天 | +| 医生回复 | "王主任回复了您的消息" | 医生在问诊中发消息 | +| 异常警告 | "⚠️ 检测到心率偏高(105 次/分)" | 硬件上传异常数据 | + +### 18.2 点击行为 + +| 通知类型 | 点击后跳转 | +|---------|----------| +| 用药提醒 | 首页 + 自动打开药管家面板 | +| 复查提醒 | 首页 + 复查详情 | +| 医生回复 | 直接进入该问诊对话 | +| 异常警告 | 首页 + 该指标趋势页 | + +### 18.3 技术方案 + +- iOS:APNs +- Android:FCM +- 推送文案人性化、温暖 +- 通知偏好:四类推送(用药提醒、复查提醒、医生回复、异常警告)各设独立开关,用户可分别开启/关闭 + +--- + +## 十九、在线问诊 + +### 19.1 业务模型 + +- 私人医疗 App,患者付费使用 +- 每月 2-3 次真人医生问诊机会 +- 超出套餐暂不限次数,先跑通流程 +- 平时由 AI 处理大部分问题 +- 不存在"紧急问诊"场景——真正紧急的情况患者直接去医院 + +### 19.2 转人工流程 + +``` +用户在「AI问诊」中 → 点 [找医生] → 查看剩余次数 → 确认 + │ + ▼ +选择医生 → 先与医生 AI 分身对话 + │ + ▼ +医生在 Web 后台有空时查看、回复 + │ + ▼ +对话结束 → 扣除本月 1 次机会 +``` + +### 19.3 医生 AI 分身 + +- 每个医生有自己的 AI 分身(形象、口吻不同) +- AI 回答末尾标注"以上为 AI 分析,具体请咨询 X 主任" +- 以下情况建议转真人:胸痛/呼吸困难/心悸;血压持续 >160/100;心率 >120 或 <50;用户明确要求 + +### 19.4 通知 + +- App 前台 → 聊天界面实时显示新消息 +- App 后台/关闭 → 推送通知,显示消息摘要,点击进入聊天 + +--- + +## 二十、异常处理 + +### 20.1 网络异常 + +- 无网络时显示"无网络连接"全屏提示,阻挡所有操作 +- 网络恢复后自动恢复正常 + +### 20.2 AI 异常 + +| 情况 | 处理 | +|------|------| +| AI 响应超时(>30 秒) | 提示"回复时间较长,请稍候或重试",提供 [重试] 按钮 | +| AI 返回乱码/格式错误 | 提示"AI 回复异常,请重试",自动重试一次 | +| AI 拒答(超出能力范围) | 直接告知"这个问题我暂时无法回答,建议咨询您的医生" | +| VLM 识别超时(>15 秒) | 提示"分析超时,请重试或手动填写" | + +### 20.3 空状态 + +| 页面 | 无数据时显示 | +|------|------------| +| 对话流 | AI 问候语 | +| 任务卡片区 | 不显示(无卡片) | +| 健康概览 | 各项指标显示 "--" | +| 历史对话 | "暂无历史对话" | +| 健康档案 | 各字段显示空白,提示"可通过 AI 对话或手动填写" | +| 报告列表 | "暂无报告" | +| 用药列表 | "暂无用药计划" | +| 运动计划 | "暂无运动计划,点击创建" | +| 饮食记录 | "暂无饮食记录" | +| 复查列表 | "暂无复查安排" | +| 趋势图表 | "暂无足够数据生成趋势图" | + +### 20.4 账号注销 + +- 入口:设置 → 退出登录旁 → 注销账号 +- 流程:二次确认 → 清除服务端全部数据 → 清除本地数据 → 返回登录页 +- 注销后数据不可恢复 + +--- + +## 二十一、性能预期 + +- VLM 食物识别等待时间:1-5 秒 +- AI 对话回复时间:尽可能快,流式逐字展示 +- App 启动到首页:< 2 秒 +- VLM 超时时间:15 秒 + +--- + +## 二十二、数据归属与隐私 + +- 用户数据归用户和其绑定医生可见 +- 不对外共享 +- 对话记录保留 30 天 + +--- + +## 二十三、暂不做 + +- 面容/指纹解锁 +- 实名认证 +- 药盒拍照识别 +- 药物库存管理 +- 药物相互作用检查 +- 健康积分体系 +- 导出 PDF 报告 +- 多报告对比(后期) +- 家属关联(后期) +- 设备蓝牙连接(后期) + +--- + +## 二十四、待定事项 + +| # | 事项 | 状态 | +|---|------|------| +| 1 | 微信/Apple ID 登录 | 后期加,第一期只做手机号 | +| 2 | 语音输入 | 用系统键盘自带,不额外开发 | +| 3 | 医生端 | Web 后台,先不做,等患者端跑通 | +| 4 | 短信服务商 | 待定 | +| 5 | 问诊配额具体次数 | 先按 3 次/月 | +| 6 | 硬件数据同步 | 留接口,硬件出来后对接 | +| 7 | 智能体面板内具体快捷按钮 | 后续可调整 | diff --git a/健康管家-页面设计文档.md b/健康管家-页面设计文档.md new file mode 100644 index 0000000..2c144f7 --- /dev/null +++ b/健康管家-页面设计文档.md @@ -0,0 +1,967 @@ +# 健康管家 — 页面设计文档 + +> 本文档逐一描述每个页面的布局、组件、交互、状态。配合需求规格文档 V2 和技术设计文档 V2 使用。 + +--- +你是一名顶级移动端产品设计师和Flutter UI工程师。 + +不要设计功能。 + +不要思考业务。 + +只关注视觉表现。 + +================================================== + +产品定位: + +AI健康陪伴助手 + +不是: + +医院系统 + +不是: + +企业后台 + +不是: + +健康管理工具 + +================================================== + +视觉参考: + +支付宝蚂蚁阿福 + +Apple Health + +Headspace + +Calm + +================================================== + +用户第一眼看到页面时必须觉得: + +温暖 + +轻松 + +有陪伴感 + +有生命力 + +高级 + +可信赖 + +================================================== + +不要出现: + +后台管理系统感 + +表格感 + +数据中心感 + +医院感 + +安卓原生感 + +Material3默认感 + +================================================== + +视觉关键词: + +Soft + +Friendly + +Companion + +Minimal + +Premium + +AI-first + +================================================== + +设计原则: + +聊天优先于表单 + +卡片优先于列表 + +陪伴优先于工具 + +情感优先于数据 + +================================================== + +页面整体留白必须充足。 + +不要塞满内容。 + +每个页面只保留最重要的信息。 + +================================================== + +所有页面必须看起来像: + +一个会关心用户的AI + +而不是一个记录数据的软件。 + +================================================== + +视觉密度: + +低密度 + +大量留白 + +================================================== + +圆角: + +非常圆润 + +卡片24+ + +按钮20+ + +胶囊999 + +================================================== + +颜色: + +以浅紫色为核心 + +大面积白色 + +少量渐变 + +少量高饱和色 + +================================================== + +阴影: + +非常轻 + +几乎感受不到 + +================================================== + +背景: + +不是纯白 + +使用浅灰白 + +局部加入柔和渐变 + +================================================== + +图标: + +圆润 + +可爱 + +避免锐利线条 + +================================================== + +所有页面必须符合: + +Dribbble作品级别 + +Behance展示级别 + +而不是业务系统页面。 + +================================================== + +最终目标: + +用户第一眼认为: + +“这是一个AI健康管家。” + +而不是: + +“这是一个健康管理APP。” + + + +请把整个产品设计成: + +支付宝阿福 × Apple Health × AI Companion。 + +用户打开App时, +感觉自己是在和一个关心自己的AI交流, + +而不是在使用一个健康记录工具。 +## P1. 登录页 `/login` + +### 功能 +手机号 + 验证码登录(登录即注册) + +### 布局 +``` +┌──────────────────────────────────┐ +│ │ +│ 🏥 健康管家 │ Logo + App 名称 +│ │ +│ ┌──────────────────────────────┐│ +│ │ +86 │ 输入手机号... ││ 手机号输入框 +│ └──────────────────────────────┘│ +│ │ +│ ┌────────────────┐ ┌──────────┐│ +│ │ 输入验证码... │ │ 获取验证码 ││ 验证码输入框 + 发送按钮 +│ └────────────────┘ └──────────┘│ +│ │ +│ ┌──────────────────────────────┐│ +│ │ 登 录 ││ 主按钮(紫底白字) +│ └──────────────────────────────┘│ +│ │ +│ ☐ 已阅读并同意《服务协议》《隐私政策》│ 协议勾选 +│ │ +└──────────────────────────────────┘ +``` + +### 交互 +- 输入手机号 → [获取验证码] 按钮亮起 +- 点击 [获取验证码] → 倒计时 60 秒 → 按钮变灰 +- 开发阶段:验证码输入任意 6 位数字即可 +- 输入 6 位验证码 + 勾选协议 → [登录] 亮起 +- 登录成功 → 跳转 `/home` +- 登录失败 → 红色提示文字 + +### 状态 +| 状态 | 显示 | +|------|------| +| 正常 | 如上 | +| 手机号格式错误 | "请输入正确的手机号" | +| 验证码错误 | "验证码错误,请重新输入" | +| 网络错误 | "网络连接失败,请检查网络" | +| 加载中 | [登录] 按钮显示 loading 动画 | + +--- + +## P2. 首页 `/home` + +### 功能 +App 主界面,包含对话流、任务卡片区、Agent 面板、输入框、侧滑抽屉 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ☰ ←│ 顶部:左侧菜单按钮 → 抽屉 +│ │ +│ ┌ 任务卡片区(可折叠)───────────┐│ +│ │ 💊 计划8:00吃阿司匹林 [✓] ││ 用药提醒卡片 +│ │ 🏃 今日待运动:散步30分钟 [✓] ││ 运动打卡卡片 +│ │ 🩺 今日待测量:血压 ││ 指标测量提醒 +│ └──────────────────────────────┘│ +│ │ +│ ┌ 对话流 ───────────────────────┐│ +│ │ ││ +│ │ AI: 早上好!昨天心率105... ││ AI 气泡(白底紫左边框) +│ │ ││ +│ │ 用户: 血压135/85 ││ 用户气泡(紫底白字右对齐) +│ │ ││ +│ │ AI: 收到!已记录血压 135/85 ✅││ +│ │ ││ +│ └────────────────────────────────┘│ +│ │ +│ ┌ Agent 面板(点击胶囊后出现)───┐│ ← 仅当有激活的 Agent 时显示 +│ │ [手动录入血压] [手动录入血糖] ││ +│ │ ... ││ +│ └────────────────────────────────┘│ +│ │ +├──────────────────────────────────┤ +│ [胶囊1][胶囊2][胶囊3]...[胶囊6] │ 智能体胶囊栏(横向滑动) +├──────────────────────────────────┤ +│ [📎] │ 输入你想说的... │ [📤] │ 输入框(系统键盘语音) +└──────────────────────────────────┘ +``` + +### 组件树 +``` +HomePage (Scaffold) + ├── Drawer (HealthDrawer) + ├── Body: Column + │ ├── TaskCardArea (可折叠) + │ │ ├── MedicationCard + │ │ ├── ExerciseCard + │ │ └── MeasurementCard + │ ├── Expanded: ChatMessagesView (ListView.builder) + │ │ ├── ChatBubble (AI) + │ │ ├── ChatBubble (User) + │ │ ├── DataConfirmCard + │ │ ├── DietResultCard + │ │ ├── MedicationConfirmCard + │ │ ├── ReportCard + │ │ └── QuickOptionsRow + │ └── AgentPanel (AnimatedContainer, 条件显示) + ├── Bottom: Column + │ ├── AgentBar (SingleChildScrollView horizontal) + │ │ └── CapsuleButton × 6 + │ └── InputBar + │ ├── AttachButton (📎) + │ ├── TextField + │ └── SendButton (📤) +``` + +### 交互 +- 输入消息 → [📤] 发送 → 消息上屏 → SSE 流式返回 → AI 逐字显示 +- 点击胶囊 → 胶囊高亮 → AgentPanel 出现 → 对话切换到该 Agent +- 再次点击同一胶囊 → 胶囊恢复 → AgentPanel 消失 → 对话回到默认 +- 向上滑动对话流 → 任务卡片区自动折叠 +- 任务卡片 ✓ 点击 → 快捷打卡 +- 左上角菜单 → 打开侧滑抽屉 + +### 状态 +| 状态 | 显示 | +|------|------| +| 首次打开(零数据) | AI 问候语 + 引导建档 | +| 正常有数据 | AI 问候(带异常提醒) + 任务卡片 | +| SSE 流式中 | AI 气泡逐字增长 + Tool Calling 中间提示 | +| 网络错误 | 全屏"无网络连接" | +| 无任务卡片 | 卡片区不显示,对话流占满 | + +--- + +## P3. 侧滑抽屉(HealthDrawer) + +### 功能 +不跳转页面,从左侧滑出的抽屉面板 + +### 布局 +``` +┌──────────────┬──────────────────┐ +│ │ │ +│ 👤 张三 │ 点击 → P12 │ +│ 冠心病支架术后│ 个人中心 │ +│ │ │ +│ ⚙️ 设置 │ 点击 → P17 │ +│ │ │ +│ ❤️ 血压 128/82 │ 最新测量值 +│ 💓 心率 72 │ 未测显示 "--" +│ 💉 血糖 5.2 │ +│ 🫁 血氧 98% │ +│ │ │ +│ 📋 历史对话 │ +│ 05-31 血压咨询 + 胸闷 │ 日期 + 摘要 +│ 05-30 饮食分析 │ +│ 05-28 用药调整 │ +│ ... │ +│ │ │ +│ [退出登录] │ +└──────────────┴──────────────────┘ +``` + +### 交互 +- 点击头像 → 跳转 P12 个人中心 +- 点击设置 → 跳转 P17 设置 +- 点击最新指标 → 跳转 P4 趋势图表 +- 点击历史对话 → 加载该对话到首页对话流 +- 退出登录 → 确认弹窗 → 清除 token → 跳转 P1 + +--- + +## P4. 趋势图表页 `/trend/:type` + +### 功能 +查看某个健康指标的历史趋势曲线 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 血压趋势 │ 顶栏 +├──────────────────────────────────┤ +│ [7天] [30天] [90天] │ 时间切换 +├──────────────────────────────────┤ +│ │ +│ 📈 折线图 │ 血压:双轴(收缩压+舒张压) +│ │ 其他:单轴 +│ 支持双指缩放、滑动 │ +│ │ +├──────────────────────────────────┤ +│ 最近 7 天 │ +│ 05/31 128/82 ✅ │ 数据列表 +│ 05/30 135/85 ⚠️ 偏高 │ +│ 05/29 -- 未测量 │ +│ ... │ +└──────────────────────────────────┘ +``` + +### 状态 +| 状态 | 显示 | +|------|------| +| 有数据 | 折线图 + 数据列表 | +| 数据不足(<2条) | "暂无足够数据生成趋势图" | +| 从未测量 | "--" + 引导去记数据 | + +--- + +## P5. 健康日历页 `/calendar` + +### 功能 +月视图日历,标记用药/运动/复查 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 2026年6月 │ 顶栏 + 月份切换 +├──────────────────────────────────┤ +│ 一 二 三 四 五 六 日 │ +│ 1 2 3 4 │ +│ 5 6 7 8 9 10 11 │ +│ ... │ +│ 💊 💊 📋 │ 用药=紫点 运动=绿点 复查=黄标记 +│ │ +├──────────────────────────────────┤ +│ 6月3日 │ 当日摘要 +│ 💊 阿司匹林 ✓ │ +│ 🏃 散步30分钟 ✓ │ +│ 🩺 血压 128/82 │ +└──────────────────────────────────┘ +``` + +--- + +## P6. 用药列表页 `/medications` + +### 功能 +查看当前用药计划 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 我的用药 │ +├──────────────────────────────────┤ +│ 💊 阿司匹林 100mg │ 每条药品卡片 +│ 每天 08:00 早饭后 │ 点击 → P7 编辑 +│ 2026/05/01 - 长期 │ +│ 来源:处方 │ +│ [✓ 今日已打卡] │ +├──────────────────────────────────┤ +│ 💊 阿托伐他汀 20mg │ +│ 每天 20:00 晚饭后 │ +│ 来源:AI 录入 │ +│ [○ 待打卡] │ +├──────────────────────────────────┤ +│ [+ 添加药品] │ 跳转 P7 新建 +└──────────────────────────────────┘ +``` + +### 空状态 +``` +┌──────────────────────────────────┐ +│ 💊 │ +│ 暂无用药计划 │ +│ 可通过AI对话或手动添加 │ +│ [去药管家] │ +└──────────────────────────────────┘ +``` + +--- + +## P7. 编辑用药页 `/medications/:id/edit` + +### 功能 +新增/修改用药计划 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 添加药品 / 编辑药品 │ +├──────────────────────────────────┤ +│ 药品名称 [_______________] │ +│ 剂量 [______] mg/片/粒 │ +│ 服药时间 [08:00] [20:00] │ 支持多个时间 +│ [+ 添加时间] │ +│ 起始日期 [2026/06/01] │ +│ 结束日期 [长期] │ +│ │ +│ [删除该药品] [保存] │ +└──────────────────────────────────┘ +``` + +--- + +## P8. 报告列表页 `/reports` + +### 功能 +查看已上传的报告 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 我的报告 │ +├──────────────────────────────────┤ +│ 📋 血常规 2026/05/28 │ +│ 状态:医生已确认 ✅ │ +│ │ +│ 📋 心电图 2026/05/15 │ +│ 状态:待医生确认 ⏳ │ +│ │ +│ 📋 出院小结 2026/05/01 │ +│ 状态:医生已确认 ✅ │ +└──────────────────────────────────┘ +``` + +### 空状态 +``` +┌──────────────────────────────────┐ +│ 📋 │ +│ 暂无报告 │ +│ 可到「看报告」上传 │ +└──────────────────────────────────┘ +``` + +--- + +## P9. 报告详情页 `/reports/:id` + +### 功能 +查看报告 AI 解读 + 原始图片 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 报告详情 │ +├──────────────────────────────────┤ +│ 报告类型:血常规 │ +│ 上传时间:2026/05/28 14:30 │ +│ 状态:⏳ 待医生确认 │ +├──────────────────────────────────┤ +│ AI 预解读结果 │ +│ │ +│ 指标列表: │ +│ 白细胞 8.5×10⁹/L 正常 ✅ │ +│ 红细胞 4.2×10¹²/L 正常 ✅ │ +│ 血红蛋白 105 g/L 偏低 ⚠️ │ +│ ... │ +│ │ +│ AI 分析:血红蛋白略偏低... │ +│ ⚠️ AI 预解读,待医生确认 │ +├──────────────────────────────────┤ +│ [查看原始图片] │ +└──────────────────────────────────┘ +``` + +--- + +## P10. 医生列表页 `/doctors` + +### 功能 +选择要咨询的医生 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 选择医生 │ +│ 本月剩余 3 次 │ +├──────────────────────────────────┤ +│ 👨‍⚕️ 王建国 主任医师 │ 医生卡片 +│ 心血管内科 │ +│ 擅长冠心病术后管理 │ +│ [咨询王主任] │ +├──────────────────────────────────┤ +│ 👩‍⚕️ 李芳 副主任医师 │ +│ 营养科 │ +│ 擅长术后营养指导 │ +│ [咨询李主任] │ +└──────────────────────────────────┘ +``` + +--- + +## P11. 问诊对话页 `/consultation/:id` + +### 功能 +患者与医生的文字聊天(含 AI 分身对话) + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 王建国 主任 │ +│ 以上为AI分身回复 │ 医生未亲自回复时的提示 +├──────────────────────────────────┤ +│ │ +│ AI分身: 根据您的描述... │ AI 分身气泡 +│ 以上为AI分析,具体请咨询王主任 │ +│ │ +│ 患者: 我最近两天胸口有点闷 │ +│ │ +│ 医生: 持续多久了?做过什么检查? │ 医生亲自回复 +│ │ +├──────────────────────────────────┤ +│ │ 输入消息... │ [📤] │ +└──────────────────────────────────┘ +``` + +### 状态 +| 状态 | 显示 | +|------|------| +| AI 分身对话中 | 回复末尾标注 AI 免责声明 | +| 医生已读未回 | "医生已读" | +| 医生已回复 | 正常消息气泡 | +| 问诊已结束 | 输入框锁定,显示"本次问诊已结束" | +| 问诊配额用完 | 显示"本月问诊次数已用完" | + +--- + +## P12. 个人中心页 `/profile` + +### 功能 +用户信息 + 功能菜单 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 个人中心 │ +├──────────────────────────────────┤ +│ 👤 张三 │ +│ 冠心病支架术后 12周 │ +│ 138****1234 │ +│ [编辑] │ 跳转 P13 +├──────────────────────────────────┤ +│ 📋 健康档案 > │ 跳转 P14 +│ 📱 设备管理 > │ 跳转占位页 +│ 🔔 通知偏好 > │ 跳转 P18 +│ ⚙️ 设置 > │ 跳转 P17 +│ ❓ 关于 > │ 跳转 P19 +│ 🚪 退出登录 > │ 确认弹窗 +└──────────────────────────────────┘ +``` + +--- + +## P13. 编辑资料页 `/profile/edit` + +### 功能 +修改个人基本信息 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 编辑资料 │ +├──────────────────────────────────┤ +│ 头像 [👤 点击更换] │ +│ 姓名 [张三____________] │ +│ 性别 [男] [女] │ +│ 出生日期 [1970-03-15] │ +│ 手机号 138****1234(不可改) │ +│ │ +│ [保存] │ +└──────────────────────────────────┘ +``` + +--- + +## P14. 健康档案页 `/health-archive` + +### 功能 +查看和编辑完整健康信息 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 健康档案 [编辑] │ +├──────────────────────────────────┤ +│ 📋 基本信息 │ +│ 姓名:张三 性别:男 │ +│ 出生:1970-03-15 │ +│ 身高:170cm 体重:72kg │ +├──────────────────────────────────┤ +│ 🩺 诊断信息 │ +│ 主要诊断:冠心病 │ +│ 手术类型:PCI支架植入术 │ +│ 手术日期:2026-03-15 │ +├──────────────────────────────────┤ +│ 🏥 病史与限制 │ +│ 过敏史:无 │ +│ 饮食限制:低盐 低脂 │ +│ 慢性病史:高血压 高血脂 │ +│ 家族病史:父亲冠心病 │ +├──────────────────────────────────┤ +│ 📊 健康数据(本周平均) │ +│ 血压 130/82 心率 74 │ +│ [查看趋势] │ +├──────────────────────────────────┤ +│ 📋 检查报告 3份 [查看] │ +│ 💊 当前用药 2种 [查看] │ +│ 🎯 运动计划 进行中 [查看] │ +└──────────────────────────────────┘ +``` + +### 交互 +- 点击 [编辑] → 各字段变为可编辑状态 +- 点击各功能入口 → 跳转对应页面 +- AI 对话中了解到的信息自动填充到对应字段 + +--- + +## P15. 饮食记录列表页 `/diet-records` + +### 功能 +按日期查看历史饮食记录 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 饮食记录 │ +├──────────────────────────────────┤ +│ 2026-06-01 │ 按日期分组 +│ 🍽️ 午餐 644千卡 ★★★☆☆ │ +│ 米饭 1碗 | 红烧肉 5块 │ +│ │ +│ 2026-05-31 │ +│ 🍽️ 晚餐 520千卡 ★★★★☆ │ +│ 面条 1碗 | 青菜 1份 │ +│ 🍽️ 午餐 380千卡 ★★★★☆ │ +│ 三明治 1个 │ +└──────────────────────────────────┘ +``` + +### 空状态 +``` +┌──────────────────────────────────┐ +│ 🍽️ │ +│ 暂无饮食记录 │ +│ 可通过「拍饮食」或对话录入 │ +└──────────────────────────────────┘ +``` + +--- + +## P16. 运动计划页 `/exercise-plan` + +### 功能 +查看和编辑本周运动计划 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 运动计划 │ +│ 2026年 第23周 │ +├──────────────────────────────────┤ +│ 周一 散步 30分钟 ✅ 已完成 │ 每日条目 +│ 周二 慢跑 20分钟 ○ 待完成 │ +│ 周三 游泳 30分钟 ○ 待完成 │ +│ 周四 休息日 │ +│ 周五 散步 30分钟 ○ 待完成 │ +│ 周六 休息日 │ +│ 周日 散步 30分钟 ○ 待完成 │ +├──────────────────────────────────┤ +│ [修改计划] [本周已完成 1/5] │ +└──────────────────────────────────┘ +``` + +### 空状态 +``` +┌──────────────────────────────────┐ +│ 🏃 │ +│ 暂无运动计划 │ +│ 可通过「运动计划」或对话创建 │ +│ [创建计划] │ +└──────────────────────────────────┘ +``` + +--- + +## P17. 设置页 `/settings` + +### 功能 +App 设置 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 设置 │ +├──────────────────────────────────┤ +│ 隐私保护中心 > │ P19 文本页 +│ 通知偏好 > │ P18 +│ 字体大小 ───●───── │ 滑动条 0.8x-1.6x +│ 协议与公告 > │ P19 文本页 +│ 关于 > │ P19 文本页 +│ │ +│ [退出登录] │ 确认弹窗 +│ [注销账号] │ 二次确认 + 清数据 +└──────────────────────────────────┘ +``` + +--- + +## P18. 通知偏好页 `/settings/notifications` + +### 功能 +各类型推送独立开关 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 通知偏好 │ +├──────────────────────────────────┤ +│ 💊 用药提醒 [🔘] │ 开关 +│ 📋 复查提醒 [🔘] │ +│ 💬 医生回复 [🔘] │ +│ ⚠️ 异常警告 [🔘] │ +└──────────────────────────────────┘ +``` + +--- + +## P19. 静态文本页 `/page/:type` + +### 功能 +展示隐私政策 / 服务协议 / 关于 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 隐私政策 │ 标题随 type 变化 +├──────────────────────────────────┤ +│ │ +│ 纯文本内容(后期填充) │ +│ │ +└──────────────────────────────────┘ +``` + +--- + +## P20. 复查列表页 `/followups` + +### 功能 +查看复查/随访安排 + +### 布局 +``` +┌──────────────────────────────────┐ +│ ← 返回 复查随访 │ +├──────────────────────────────────┤ +│ 即将到来 │ +│ 📋 心内科复查 06/05 15:00 │ +│ 地点:市一医院 3楼 │ +│ 提醒:后天 │ +├──────────────────────────────────┤ +│ 已完成 │ +│ ✅ 术后3周复查 04/05 │ +│ ✅ 术后6周复查 04/26 │ +└──────────────────────────────────┘ +``` + +### 空状态 +``` +┌──────────────────────────────────┐ +│ 📋 │ +│ 暂无复查安排 │ +│ 医生端创建后自动同步 │ +└──────────────────────────────────┘ +``` + +--- + +## 页面汇总 + +| # | 路由 | 页面 | 类型 | +|---|------|------|------| +| 1 | `/login` | 登录页 | 独立页面 | +| 2 | `/home` | 首页(含抽屉+面板+胶囊栏) | 独立页面 | +| 3 | — | 侧滑抽屉 | 组件(非页面) | +| 4 | `/trend/:type` | 趋势图表 | 独立页面 | +| 5 | `/calendar` | 健康日历 | 独立页面 | +| 6 | `/medications` | 用药列表 | 独立页面 | +| 7 | `/medications/:id/edit` | 编辑用药 | 独立页面 | +| 8 | `/reports` | 报告列表 | 独立页面 | +| 9 | `/reports/:id` | 报告详情 | 独立页面 | +| 10 | `/doctors` | 医生列表 | 独立页面 | +| 11 | `/consultation/:id` | 问诊对话 | 独立页面 | +| 12 | `/profile` | 个人中心 | 独立页面 | +| 13 | `/profile/edit` | 编辑资料 | 独立页面 | +| 14 | `/health-archive` | 健康档案 | 独立页面 | +| 15 | `/diet-records` | 饮食记录列表 | 独立页面 | +| 16 | `/exercise-plan` | 运动计划 | 独立页面 | +| 17 | `/settings` | 设置 | 独立页面 | +| 18 | `/settings/notifications` | 通知偏好 | 独立页面 | +| 19 | `/page/:type` | 静态文本页 | 独立页面 | +| 20 | `/followups` | 复查列表 | 独立页面 | + +**总计:20 个独立页面 + 1 个侧滑抽屉组件 + 6 个 Agent 面板组件** + +--- + +## Agent 面板设计(首页内嵌,非独立页面) + +### 默认对话(无面板) +只有对话流,无额外面板。 + +### 记数据面板 +``` +┌──────────────────────────────────┐ +│ 📊 记数据 │ +│ [手动录入血压] [手动录入血糖] │ 快捷按钮 +│ [手动录入心率] [手动录入血氧] │ +│ [手动录入体重] │ +│ │ +│ 或直接对我说: │ +│ "血压 135/85" │ +└──────────────────────────────────┘ +``` + +### 拍饮食面板 +``` +┌──────────────────────────────────┐ +│ 📸 拍饮食 │ +│ [拍照] [上传照片](支持多张) │ +│ │ +│ 或直接对我说: │ +│ "中午吃了牛肉面" │ +└──────────────────────────────────┘ +``` + +### 药管家面板 +``` +┌──────────────────────────────────┐ +│ 💊 药管家 │ +│ [用药管理] [用药提醒] │ +│ │ +│ 或直接对我说: │ +│ "医生让我吃阿托伐他汀 20mg" │ +└──────────────────────────────────┘ +``` + +### AI 问诊面板 +``` +┌──────────────────────────────────┐ +│ 🩺 AI 问诊 │ +│ [找医生] │ +│ │ +│ 或直接对我说你的症状 │ +└──────────────────────────────────┘ +``` + +### 看报告(无面板) +点击直接调起相机/文件选择器,不弹出面板。 + +### 运动计划面板 +``` +┌──────────────────────────────────┐ +│ 🏃 运动计划 │ +│ [查看本周计划] [创建新计划] │ +│ │ +│ 或直接对我说: │ +│ "我想每周一三五散步 30 分钟" │ +└──────────────────────────────────┘ +```