weight-management-implementation-7f3662cc.plan.md 8.7 KB

Weight Management Implementation Plan

Overview

This document outlines the implementation of a comprehensive weight management system in the WeightComponent at campus_health_app/frontend/campus-health-app/src/app/modules/weight/weight.component.ts. All features will be implemented in a single component using ECharts for visualizations, with data persisted in localStorage and synced with backend API.

Implementation Steps

1. Dependencies Installation

Install required packages:

  • echarts: ^5.4.3 (charting library)
  • ngx-echarts: ^17.0.0 (Angular wrapper for ECharts)

2. Data Models Enhancement

Extend existing WeightRecord interface and add new interfaces:

  • WeightRecord: Add fields for measurementTime, measurementCondition (空腹/餐后), notes, tags (关键节点标记)
  • WeightGoal: targetWeight, targetBodyFat, targetDate, startWeight, startDate, weeklyTarget
  • AnomalyAlert: type, severity, message, detectedDate

3. Component Structure

Core Features Implementation:

A. Data Collection Module

  • Modal/Dialog component for weight input with fields:
    • Weight (kg), Body Fat (%), Muscle Mass (kg)
    • Measurement time picker, Condition selector (空腹/餐后)
    • Notes textarea, Tag selector for milestones
  • Validation: weight range 30-200kg, body fat 5-60%
  • Save to localStorage immediately, queue for backend sync

B. Goal Management Module

  • Goal setting dialog with:
    • Target weight and body fat percentage inputs
    • Target date picker with minimum date validation
    • Auto-calculate weekly target based on time difference
    • Display predicted completion date based on current trend
  • Store in localStorage under weightGoal key
  • Backend sync on save

C. Anomaly Detection Engine

  • Simple threshold-based detection:
    • Rapid weight change: >2kg/week or >0.5kg/day
    • Body fat anomaly: body fat% increases while weight decreases
    • Missing data: >7 days without measurement
    • Extreme values: outside personalized ±5% range
  • Generate alerts with severity levels (info/warning/danger)
  • Display in dedicated alert section at bottom

D. Multi-dimensional Filtering

  • Time period filters: 7天/30天/90天/全部
  • Date range picker for custom periods
  • Measurement condition filter: 全部/空腹/餐后
  • Tag-based filtering for milestone events
  • Comparison mode: compare current period vs previous period

4. Visualization Charts (ECharts Configuration)

Chart 1: Weight Trend Line Chart (Primary, 50% height)

// Three lines: actual weight (blue), target weight (red), planned trend (gray dashed)
// X-axis: time with custom markers for tagged events
// Y-axis: weight in kg
// Tooltip: show date, weight, body fat, measurement condition
// DataZoom: enable for mobile pinch-to-zoom
// MarkLine: for goal weight and start weight
// MarkPoint: for milestone events (开始运动日, 目标调整日)

Chart 2: Weekly/Monthly Weight Change Bar Chart

// Calculate weight delta per week/month
// Green bars for weight loss (negative values)
// Red bars for weight gain (positive values)
// Label on top of each bar showing exact value (e.g., "-0.6kg")
// Toggle between weekly/monthly view

Chart 3: Weight vs Body Fat Scatter Plot (Right side small chart)

// X-axis: weight (kg), Y-axis: body fat (%)
// Each point represents one measurement
// Color gradient based on date (older = lighter)
// Reference lines showing ideal trend (down-left diagonal)
// Tooltip showing date and values

Chart 4: Goal Progress Ring Chart (Top-right floating)

// Gauge/Pie chart showing progress percentage
// Inner text: "已减 3kg / 目标 5kg"
// Outer ring: progress arc (60% filled)
// Bottom text: "还需减 2kg,预计 11月30日完成"
// Color: green if on track, yellow if slow, red if off track

Chart 5: Summary Stats Cards (Above trend chart)

  • Current weight, Weight change from start, Days tracked
  • Average weekly change, Body fat change, Goal completion ETA

5. Layout Structure (Mobile-first)

┌─────────────────────────────────────┐
│ Header: 体重管理 [录入] [目标设置]    │
├─────────────────────────────────────┤
│ Summary Cards (3 cards in row)      │
├──────────────────────┬──────────────┤
│                      │  Goal Ring   │
│  Weight Trend Chart  │  (Floating)  │
│  (50% height)        │              │
│                      │              │
├──────────────────────┴──────────────┤
│ Filter Bar: [7天][30天][90天][自定义]│
├─────────────────────────────────────┤
│ Weekly/Monthly Change Bar Chart     │
├──────────────────────────────────────┤
│ Weight vs Body Fat Scatter Plot     │
├─────────────────────────────────────┤
│ Anomaly Alerts & Suggestions        │
└─────────────────────────────────────┘

6. Data Persistence Strategy

LocalStorage Structure:

{
  weightRecords: WeightRecord[],
  weightGoal: WeightGoal,
  pendingSync: { records: [], goal: null },
  lastSyncTime: timestamp
}

Backend Sync Logic:

  • On component init: fetch latest data from backend, merge with local
  • On data change: save to localStorage immediately, add to pendingSync queue
  • Periodic sync (every 5 minutes): POST pendingSync items to backend
  • Conflict resolution: backend timestamp wins
  • Offline support: queue operations, sync when online

7. Services & State Management

Create WeightDataService:

  • CRUD operations for weight records
  • Goal management methods
  • Sync coordinator between localStorage and backend
  • Observable streams for reactive UI updates

8. Mobile Optimization

  • Touch-friendly chart interactions (touch to show tooltip)
  • Responsive grid layout (charts stack vertically on small screens)
  • Optimize chart rendering for mobile performance
  • Use virtual scrolling for record list if >100 items

9. Key Implementation Details

Planned Trend Line Calculation:

// Linear interpolation from start weight to target weight
planWeight = startWeight - (daysElapsed / totalDays) * totalWeightToLose

Anomaly Detection Algorithm:

// Check last 7 days for rapid changes
if (Math.abs(weeklyChange) > 2) {
  alert = { type: 'rapid_change', severity: 'warning', message: '...' }
}

ETA Calculation:

// Based on average weekly change over last 4 weeks
avgWeeklyChange = sum(last4WeeksChanges) / 4
weeksRemaining = remainingWeight / Math.abs(avgWeeklyChange)
eta = new Date(now + weeksRemaining * 7 * 24 * 60 * 60 * 1000)

File Structure

campus_health_app/docs/
  └── weight-management-implementation.md  (this document)

campus_health_app/frontend/campus-health-app/src/app/
  ├── modules/weight/
  │   ├── weight.component.ts (main implementation)
  │   ├── weight.component.html (template with all charts)
  │   ├── weight.component.scss (mobile-first responsive styles)
  │   └── models/
  │       └── weight.models.ts (data interfaces)
  └── services/
      └── weight-data.service.ts (data management & sync)

Technical Specifications

  • Framework: Angular 17+ (standalone components)
  • Charts: ECharts 5.4.3 via ngx-echarts
  • Styling: SCSS with mobile-first breakpoints
  • Data Storage: LocalStorage + REST API sync
  • State Management: RxJS Observables
  • Type Safety: Full TypeScript typing for all data models

API Endpoints (Expected Backend)

GET    /api/weight/records?from={date}&to={date}
POST   /api/weight/records
PUT    /api/weight/records/{id}
DELETE /api/weight/records/{id}
GET    /api/weight/goal
POST   /api/weight/goal
PUT    /api/weight/goal

Testing Considerations

  • Mock data for 90 days to test all visualizations
  • Test edge cases: no data, single data point, goal achieved
  • Test offline mode and sync recovery
  • Validate mobile touch interactions
  • Performance test with 365+ data points

To-dos

  • Create weight-management-implementation.md in campus_health_app/docs with complete implementation guide