AI Newsletter Digest improvements: fixed QP soft line break decoding, URL extraction, and content cleaning
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
# Next Step - New Feature Design Document
|
||||
|
||||
## Overview
|
||||
This document outlines 5 new features designed to help families supporting a loved one through chemotherapy treatment.
|
||||
|
||||
## Feature 1: Enhanced Symptom Tracking with Trends & Insights
|
||||
|
||||
### Problem
|
||||
Current symptom tracking is basic - users can log symptoms but have limited visibility into patterns, trends, or correlations.
|
||||
|
||||
### Solution
|
||||
- **Detailed Symptom Logging**: Add duration, triggers
|
||||
- **Trend Visualization**: 7/14/30-day charts with filtering
|
||||
- **Pattern Detection**: Highlight when symptoms spike
|
||||
- **Symptom Report**: Exportable PDF report for doctor visits
|
||||
|
||||
## Feature 2: Caregiver Coordination (Handoff Notes & Task Assignments)
|
||||
|
||||
### Problem
|
||||
Families struggle to coordinate care, especially with multiple caregivers.
|
||||
|
||||
### Solution
|
||||
- **Handoff Notes**: Quick shift-change notes
|
||||
- **Task Assignments**: Assign tasks to specific caregivers
|
||||
- **Caregiver Activity**: See who's doing what
|
||||
|
||||
## Feature 3: Treatment Milestone Tracker
|
||||
|
||||
### Problem
|
||||
Chemo is a long journey - families need encouragement and a sense of progress.
|
||||
|
||||
### Solution
|
||||
- **Treatment Plan**: Define treatment schedule (e.g., "12 cycles")
|
||||
- **Visual Progress**: Progress bar showing % complete
|
||||
- **Milestone Cards**: Celebrate wins
|
||||
|
||||
## Feature 4: Quick Access Emergency Widget
|
||||
|
||||
### Problem
|
||||
Emergency info exists but requires navigation. In a real emergency, every second counts.
|
||||
|
||||
### Solution
|
||||
- **Emergency Button**: Always-visible floating button
|
||||
- **One-Tap Calling**: Direct dial for emergency contacts
|
||||
- **Emergency Mode**: Simplified, high-contrast view
|
||||
|
||||
## Feature 5: Calendar Integration (iCal/ICS Export)
|
||||
|
||||
### Problem
|
||||
Families use multiple calendars. Appointments in Next Step aren't visible in their regular calendar apps.
|
||||
|
||||
### Solution
|
||||
- **Subscribe URL**: Personal ICS feed URL
|
||||
- **Export Appointments**: Generate .ics files
|
||||
- **Share Calendar**: Family members can subscribe
|
||||
|
||||
## Implementation Priority
|
||||
|
||||
1. **Treatment Milestone Tracker** - High morale impact
|
||||
2. **Enhanced Symptom Tracking** - Builds on existing feature
|
||||
3. **Caregiver Coordination** - High practical value
|
||||
4. **Quick Access Emergency Widget** - Safety critical
|
||||
5. **Calendar Integration** - Lower urgency
|
||||
@@ -0,0 +1,369 @@
|
||||
# Next Step - Feature Implementation Guide
|
||||
|
||||
## Overview
|
||||
This guide explains how to integrate the 5 new features into the main Next Step codebase.
|
||||
|
||||
## Features Implemented
|
||||
|
||||
### 1. Treatment Milestone Tracker ✅
|
||||
**Files:**
|
||||
- `prisma/schema.prisma` - Add TreatmentPlan and TreatmentMilestone models
|
||||
- `src/app/(app)/treatment/page.tsx` - Main treatment page
|
||||
- `src/app/(app)/treatment/new/page.tsx` - Create treatment plan
|
||||
- `src/components/treatment/TreatmentProgress.tsx` - Progress widget
|
||||
- `src/components/treatment/TreatmentPlanForm.tsx` - Form component
|
||||
- `src/app/api/workspaces/[id]/treatment-plan/route.ts` - API routes
|
||||
- `src/app/api/workspaces/[id]/treatment-plan/complete-cycle/route.ts` - Complete cycle
|
||||
|
||||
**Integration Steps:**
|
||||
1. Add models to schema.prisma
|
||||
2. Run `npm run db:migrate`
|
||||
3. Copy page files to app directory
|
||||
4. Copy component files
|
||||
5. Copy API routes
|
||||
6. Add navigation link to treatment page
|
||||
|
||||
### 2. Enhanced Symptom Tracking ✅
|
||||
**Files:**
|
||||
- `src/app/(app)/symptoms/page.tsx` - Enhanced symptoms page (overwrite)
|
||||
- `src/components/symptoms/SymptomTrendChart.tsx` - Trend visualization
|
||||
- `src/components/symptoms/SymptomReportGenerator.tsx` - PDF export
|
||||
|
||||
**Integration Steps:**
|
||||
1. Replace existing symptoms page with enhanced version
|
||||
2. Add new components
|
||||
3. Update SymptomQuickLog to include medication correlation
|
||||
4. Add API route for PDF generation
|
||||
|
||||
### 3. Caregiver Coordination ✅
|
||||
**Files:**
|
||||
- `prisma/schema.prisma` - Add CareTask and HandoffNote models
|
||||
- `src/app/(app)/care/page.tsx` - Care coordination page
|
||||
- `src/app/(app)/care/new-task/page.tsx` - Create task
|
||||
- `src/app/(app)/care/new-note/page.tsx` - Create handoff note
|
||||
- `src/app/api/workspaces/[id]/care-tasks/route.ts` - Task API
|
||||
- `src/app/api/workspaces/[id]/handoff-notes/route.ts` - Notes API
|
||||
|
||||
**Integration Steps:**
|
||||
1. Add models to schema
|
||||
2. Migrate database
|
||||
3. Copy page and component files
|
||||
4. Copy API routes
|
||||
5. Add navigation link
|
||||
|
||||
### 4. Emergency Quick Access Widget ✅
|
||||
**Files:**
|
||||
- `src/components/emergency/EmergencyWidget.tsx` - Floating widget
|
||||
- `src/app/(app)/layout.tsx` - Add widget to layout
|
||||
|
||||
**Integration Steps:**
|
||||
1. Copy widget component
|
||||
2. Import and add to main app layout
|
||||
3. Ensure it appears on all pages
|
||||
|
||||
### 5. Calendar Integration ✅
|
||||
**Files:**
|
||||
- `prisma/schema.prisma` - Add CalendarFeed model
|
||||
- `src/components/calendar/CalendarIntegration.tsx` - Settings component
|
||||
- `src/app/api/workspaces/[id]/calendar-feed/route.ts` - ICS feed API
|
||||
- `src/app/(app)/settings/calendar/page.tsx` - Settings page
|
||||
|
||||
**Integration Steps:**
|
||||
1. Add model to schema
|
||||
2. Migrate database
|
||||
3. Copy components and API routes
|
||||
4. Add to settings navigation
|
||||
|
||||
---
|
||||
|
||||
## Database Schema Additions
|
||||
|
||||
Add these models to `prisma/schema.prisma`:
|
||||
|
||||
```prisma
|
||||
// ============================================
|
||||
// TREATMENT MILESTONE TRACKER
|
||||
// ============================================
|
||||
|
||||
model TreatmentPlan {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String @unique
|
||||
title String
|
||||
totalCycles Int
|
||||
currentCycle Int @default(0)
|
||||
startDate DateTime?
|
||||
estimatedEnd DateTime?
|
||||
status String @default("ACTIVE")
|
||||
cycleType String @default("WEEKLY")
|
||||
cycleDays Int @default(7)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
milestones TreatmentMilestone[]
|
||||
|
||||
@@index([workspaceId])
|
||||
}
|
||||
|
||||
model TreatmentMilestone {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
cycleNumber Int
|
||||
date DateTime
|
||||
status String @default("UPCOMING")
|
||||
notes String?
|
||||
sideEffects String?
|
||||
celebratedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
plan TreatmentPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([planId])
|
||||
@@index([planId, cycleNumber])
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CAREGIVER COORDINATION
|
||||
// ============================================
|
||||
|
||||
model CareTask {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
title String
|
||||
description String?
|
||||
assignedToId String?
|
||||
dueAt DateTime?
|
||||
completedAt DateTime?
|
||||
completedById String?
|
||||
priority String @default("MEDIUM")
|
||||
category String @default("GENERAL")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
assignedTo User? @relation("AssignedTasks", fields: [assignedToId], references: [id])
|
||||
completedBy User? @relation("CompletedTasks", fields: [completedById], references: [id])
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
|
||||
@@index([workspaceId])
|
||||
@@index([workspaceId, assignedToId])
|
||||
@@index([workspaceId, completedAt])
|
||||
}
|
||||
|
||||
model HandoffNote {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
content String
|
||||
category String @default("GENERAL")
|
||||
priority String @default("NORMAL")
|
||||
expiresAt DateTime
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
acknowledgedBy String[]
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
|
||||
@@index([workspaceId])
|
||||
@@index([workspaceId, expiresAt])
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CALENDAR INTEGRATION
|
||||
// ============================================
|
||||
|
||||
model CalendarFeed {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
token String @unique
|
||||
includeMeds Boolean @default(false)
|
||||
includeAppointments Boolean @default(true)
|
||||
daysAhead Int @default(90)
|
||||
createdAt DateTime @default(now())
|
||||
lastAccessedAt DateTime?
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([token])
|
||||
@@index([workspaceId])
|
||||
}
|
||||
```
|
||||
|
||||
Run migration:
|
||||
```bash
|
||||
npm run db:migrate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Navigation Updates
|
||||
|
||||
### Add to Today Page Dashboard
|
||||
Add this section to `src/app/(app)/today/page.tsx`:
|
||||
|
||||
```tsx
|
||||
{/* Treatment Progress */}
|
||||
<section>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-lg font-semibold text-secondary-900">Treatment Progress</h2>
|
||||
<button
|
||||
onClick={() => router.push('/treatment')}
|
||||
className="text-sm text-primary-600 font-medium flex items-center"
|
||||
>
|
||||
View all
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<TreatmentProgress
|
||||
plan={treatmentPlan}
|
||||
workspaceId={currentWorkspace.id}
|
||||
compact
|
||||
/>
|
||||
</section>
|
||||
```
|
||||
|
||||
### Add to Settings Navigation
|
||||
Add to `src/app/(app)/settings/page.tsx`:
|
||||
|
||||
```tsx
|
||||
<SettingsSection title="Integrations">
|
||||
<SettingsItem
|
||||
icon={<Calendar className="w-5 h-5" />}
|
||||
label="Calendar Integration"
|
||||
description="Sync appointments to your calendar"
|
||||
href="/settings/calendar"
|
||||
/>
|
||||
</SettingsSection>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dexie DB Updates
|
||||
|
||||
Add to `src/lib/sync/db.ts`:
|
||||
|
||||
```typescript
|
||||
export interface LocalTreatmentPlan {
|
||||
id: string
|
||||
workspaceId: string
|
||||
title: string
|
||||
totalCycles: number
|
||||
currentCycle: number
|
||||
startDate: string | null
|
||||
estimatedEnd: string | null
|
||||
status: string
|
||||
cycleType: string
|
||||
cycleDays: number
|
||||
version: number
|
||||
syncedAt: string
|
||||
}
|
||||
|
||||
export interface LocalTreatmentMilestone {
|
||||
id: string
|
||||
planId: string
|
||||
cycleNumber: number
|
||||
date: string
|
||||
status: string
|
||||
notes?: string
|
||||
sideEffects?: string
|
||||
celebratedAt?: string
|
||||
syncedAt: string
|
||||
}
|
||||
|
||||
export interface LocalCareTask {
|
||||
id: string
|
||||
workspaceId: string
|
||||
title: string
|
||||
description?: string
|
||||
assignedToId?: string
|
||||
dueAt?: string
|
||||
completedAt?: string
|
||||
completedById?: string
|
||||
priority: string
|
||||
category: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface LocalHandoffNote {
|
||||
id: string
|
||||
workspaceId: string
|
||||
content: string
|
||||
category: string
|
||||
priority: string
|
||||
expiresAt: string
|
||||
createdAt: string
|
||||
acknowledgedBy: string[]
|
||||
}
|
||||
```
|
||||
|
||||
And add tables to NextStepDB:
|
||||
```typescript
|
||||
treatmentPlans!: Table<LocalTreatmentPlan, string>
|
||||
treatmentMilestones!: Table<LocalTreatmentMilestone, string>
|
||||
careTasks!: Table<LocalCareTask, string>
|
||||
handoffNotes!: Table<LocalHandoffNote, string>
|
||||
calendarFeeds!: Table<any, string>
|
||||
```
|
||||
|
||||
Update version:
|
||||
```typescript
|
||||
this.version(3).stores({
|
||||
// ... existing tables ...
|
||||
treatmentPlans: 'id, workspaceId',
|
||||
treatmentMilestones: 'id, planId, cycleNumber',
|
||||
careTasks: 'id, workspaceId, assignedToId, completedAt',
|
||||
handoffNotes: 'id, workspaceId, expiresAt',
|
||||
calendarFeeds: 'id, workspaceId, token',
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
### Treatment Milestone Tracker
|
||||
- [ ] Create treatment plan
|
||||
- [ ] View progress widget
|
||||
- [ ] Complete a cycle
|
||||
- [ ] See celebration modal
|
||||
- [ ] Check milestone details
|
||||
|
||||
### Enhanced Symptom Tracking
|
||||
- [ ] Log symptom with details
|
||||
- [ ] View trend charts
|
||||
- [ ] Filter by symptom type
|
||||
- [ ] Export PDF report
|
||||
- [ ] Copy text summary
|
||||
|
||||
### Caregiver Coordination
|
||||
- [ ] Create care task
|
||||
- [ ] Assign to caregiver
|
||||
- [ ] Mark task complete
|
||||
- [ ] Add handoff note
|
||||
- [ ] Acknowledge note
|
||||
|
||||
### Emergency Widget
|
||||
- [ ] See floating button
|
||||
- [ ] Click to open modal
|
||||
- [ ] Quick dial buttons work
|
||||
- [ ] Medical info displays
|
||||
|
||||
### Calendar Integration
|
||||
- [ ] Create calendar feed
|
||||
- [ ] Copy feed URL
|
||||
- [ ] Subscribe in calendar app
|
||||
- [ ] Verify appointments sync
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- All features maintain offline-first capability
|
||||
- Follow existing patterns for auth and workspace access
|
||||
- Use existing UI components and styling
|
||||
- Add appropriate audit logging
|
||||
- Handle VIEWER role restrictions
|
||||
@@ -0,0 +1,427 @@
|
||||
# Next Step - New Features Implementation Summary
|
||||
|
||||
## ✅ Completed Features
|
||||
|
||||
### 1. Treatment Milestone Tracker
|
||||
**Purpose:** Help families track treatment progress and celebrate milestones
|
||||
|
||||
**Key Features:**
|
||||
- Create treatment plans with customizable cycles
|
||||
- Visual progress bar showing % complete
|
||||
- Automatic milestone celebrations at key points
|
||||
- Cycle completion tracking with one-tap button
|
||||
- Estimated completion date calculation
|
||||
|
||||
**Files Created:**
|
||||
- `treatment-milestones/components/TreatmentProgress.tsx` - Main progress widget
|
||||
- `treatment-milestones/components/TreatmentPlanForm.tsx` - Create/edit form
|
||||
- `treatment-milestones/api/treatment-plan/route.ts` - API endpoints
|
||||
- `treatment-milestones/api/treatment-plan/complete-cycle/route.ts` - Cycle completion
|
||||
- `treatment-milestones/app/page.tsx` - Main page
|
||||
- `treatment-milestones/app/new/page.tsx` - Create plan page
|
||||
|
||||
### 2. Enhanced Symptom Tracking
|
||||
**Purpose:** Better insights into symptom patterns and doctor-ready reports
|
||||
|
||||
**Key Features:**
|
||||
- Multi-timeframe trend charts (7/14/30 days)
|
||||
- Symptom type filtering
|
||||
- Pattern detection (days with multiple symptoms)
|
||||
- Statistics summary by symptom type
|
||||
- PDF report generation for doctor visits
|
||||
- Text summary export
|
||||
|
||||
**Files Created:**
|
||||
- `enhanced-symptoms/app/page.tsx` - Enhanced symptoms page
|
||||
- `enhanced-symptoms/components/SymptomTrendChart.tsx` - Trend visualization
|
||||
- `enhanced-symptoms/components/SymptomReportGenerator.tsx` - Report export
|
||||
|
||||
### 3. Caregiver Coordination
|
||||
**Purpose:** Help multiple caregivers stay synchronized
|
||||
|
||||
**Key Features:**
|
||||
- Task assignments with priorities and due dates
|
||||
- Category-based task organization
|
||||
- Handoff notes for shift changes
|
||||
- Acknowledgment system for notes
|
||||
- Expiring notes to keep info fresh
|
||||
- Visual indicators for new/unread items
|
||||
|
||||
**Files Created:**
|
||||
- `care-coordination/app/page.tsx` - Main coordination page
|
||||
- `care-coordination/app/new-task/page.tsx` - Create task
|
||||
- `care-coordination/app/new-note/page.tsx` - Create handoff note
|
||||
|
||||
### 4. Emergency Quick Access Widget
|
||||
**Purpose:** Instant access to critical medical info in emergencies
|
||||
|
||||
**Key Features:**
|
||||
- Floating emergency button on all pages
|
||||
- One-tap calling for emergency contacts
|
||||
- Medical ID display (blood type, allergies, conditions)
|
||||
- Current medications list
|
||||
- Always accessible, even when navigating
|
||||
|
||||
**Files Created:**
|
||||
- `emergency-widget/components/EmergencyWidget.tsx` - Floating widget component
|
||||
|
||||
### 5. Calendar Integration
|
||||
**Purpose:** Sync appointments to external calendars
|
||||
|
||||
**Key Features:**
|
||||
- Personal ICS feed URL for calendar apps
|
||||
- Support for Apple, Google, and Outlook calendars
|
||||
- Configurable look-ahead period
|
||||
- Secure token-based access
|
||||
- Easy copy-paste setup instructions
|
||||
|
||||
**Files Created:**
|
||||
- `calendar-integration/components/CalendarIntegration.tsx` - Settings component
|
||||
- `calendar-integration/api/calendar-feed/route.ts` - ICS feed generation
|
||||
- `calendar-integration/api/calendar-feed/settings/route.ts` - Feed management
|
||||
|
||||
---
|
||||
|
||||
## Database Schema Additions
|
||||
|
||||
Add these models to `prisma/schema.prisma`:
|
||||
|
||||
```prisma
|
||||
// Treatment Tracking
|
||||
model TreatmentPlan {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String @unique
|
||||
title String
|
||||
totalCycles Int
|
||||
currentCycle Int @default(0)
|
||||
startDate DateTime?
|
||||
estimatedEnd DateTime?
|
||||
status String @default("ACTIVE")
|
||||
cycleType String @default("WEEKLY")
|
||||
cycleDays Int @default(7)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
milestones TreatmentMilestone[]
|
||||
}
|
||||
|
||||
model TreatmentMilestone {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
cycleNumber Int
|
||||
date DateTime
|
||||
status String @default("UPCOMING")
|
||||
notes String?
|
||||
sideEffects String?
|
||||
celebratedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
plan TreatmentPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
// Caregiver Coordination
|
||||
model CareTask {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
title String
|
||||
description String?
|
||||
assignedToId String?
|
||||
dueAt DateTime?
|
||||
completedAt DateTime?
|
||||
completedById String?
|
||||
priority String @default("MEDIUM")
|
||||
category String @default("GENERAL")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
assignedTo User? @relation("AssignedTasks", fields: [assignedToId], references: [id])
|
||||
completedBy User? @relation("CompletedTasks", fields: [completedById], references: [id])
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
}
|
||||
|
||||
model HandoffNote {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
content String
|
||||
category String @default("GENERAL")
|
||||
priority String @default("NORMAL")
|
||||
expiresAt DateTime
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
acknowledgedBy String[]
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
}
|
||||
|
||||
// Calendar Integration
|
||||
model CalendarFeed {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
token String @unique
|
||||
includeMeds Boolean @default(false)
|
||||
includeAppointments Boolean @default(true)
|
||||
daysAhead Int @default(90)
|
||||
createdAt DateTime @default(now())
|
||||
lastAccessedAt DateTime?
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Steps
|
||||
|
||||
### Step 1: Database Migration
|
||||
```bash
|
||||
cd /tmp/nextstep
|
||||
# Add the models to prisma/schema.prisma
|
||||
npm run db:migrate
|
||||
npm run db:generate
|
||||
```
|
||||
|
||||
### Step 2: Copy Components
|
||||
```bash
|
||||
# Treatment components
|
||||
mkdir -p src/components/treatment
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/treatment-milestones/components/* src/components/treatment/
|
||||
|
||||
# Enhanced symptom components
|
||||
mkdir -p src/components/symptoms
|
||||
# Note: Enhanced symptoms page replaces the existing one
|
||||
|
||||
# Emergency widget
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/emergency-widget/components/* src/components/emergency/
|
||||
|
||||
# Calendar integration
|
||||
mkdir -p src/components/calendar
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/calendar-integration/components/* src/components/calendar/
|
||||
```
|
||||
|
||||
### Step 3: Copy API Routes
|
||||
```bash
|
||||
# Treatment API
|
||||
mkdir -p src/app/api/workspaces/\[id\]/treatment-plan
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/treatment-milestones/api/treatment-plan/route.ts src/app/api/workspaces/\[id\]/treatment-plan/
|
||||
|
||||
mkdir -p src/app/api/workspaces/\[id\]/treatment-plan/complete-cycle
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/treatment-milestones/api/treatment-plan/complete-cycle/route.ts src/app/api/workspaces/\[id\]/treatment-plan/complete-cycle/
|
||||
|
||||
# Calendar API
|
||||
mkdir -p src/app/api/workspaces/\[id\]/calendar-feed
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/calendar-integration/api/calendar-feed/route.ts src/app/api/workspaces/\[id\]/calendar-feed/
|
||||
|
||||
mkdir -p src/app/api/workspaces/\[id\]/calendar-feed/settings
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/calendar-integration/api/calendar-feed/settings/route.ts src/app/api/workspaces/\[id\]/calendar-feed/settings/
|
||||
```
|
||||
|
||||
### Step 4: Copy Pages
|
||||
```bash
|
||||
# Treatment pages
|
||||
mkdir -p src/app/\(app\)/treatment
|
||||
mkdir -p src/app/\(app\)/treatment/new
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/treatment-milestones/app/page.tsx src/app/\(app\)/treatment/
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/treatment-milestones/app/new/page.tsx src/app/\(app\)/treatment/new/
|
||||
|
||||
# Care coordination pages
|
||||
mkdir -p src/app/\(app\)/care
|
||||
mkdir -p src/app/\(app\)/care/new-task
|
||||
mkdir -p src/app/\(app\)/care/new-note
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/care-coordination/app/page.tsx src/app/\(app\)/care/
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/care-coordination/app/new-task/page.tsx src/app/\(app\)/care/new-task/
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/care-coordination/app/new-note/page.tsx src/app/\(app\)/care/new-note/
|
||||
|
||||
# Enhanced symptoms (replace existing)
|
||||
# Backup first:
|
||||
cp src/app/\(app\)/symptoms/page.tsx src/app/\(app\)/symptoms/page.tsx.backup
|
||||
cp /home/openclaw/.openclaw/workspace/nextstep-features/enhanced-symptoms/app/page.tsx src/app/\(app\)/symptoms/
|
||||
```
|
||||
|
||||
### Step 5: Add Emergency Widget to Layout
|
||||
Edit `src/app/(app)/layout.tsx` and add:
|
||||
|
||||
```tsx
|
||||
import { EmergencyWidget } from '@/components/emergency/EmergencyWidget'
|
||||
|
||||
// Inside the component, before closing </div>:
|
||||
<EmergencyWidget workspaceId={workspace.id} />
|
||||
```
|
||||
|
||||
### Step 6: Update Dexie DB
|
||||
Edit `src/lib/sync/db.ts` and add:
|
||||
|
||||
```typescript
|
||||
// New interfaces
|
||||
export interface LocalTreatmentPlan {
|
||||
id: string
|
||||
workspaceId: string
|
||||
title: string
|
||||
totalCycles: number
|
||||
currentCycle: number
|
||||
startDate: string | null
|
||||
estimatedEnd: string | null
|
||||
status: string
|
||||
cycleType: string
|
||||
cycleDays: number
|
||||
version: number
|
||||
syncedAt: string
|
||||
}
|
||||
|
||||
export interface LocalTreatmentMilestone {
|
||||
id: string
|
||||
planId: string
|
||||
cycleNumber: number
|
||||
date: string
|
||||
status: string
|
||||
notes?: string
|
||||
sideEffects?: string
|
||||
celebratedAt?: string
|
||||
syncedAt: string
|
||||
}
|
||||
|
||||
export interface LocalCareTask {
|
||||
id: string
|
||||
workspaceId: string
|
||||
title: string
|
||||
description?: string
|
||||
assignedToId?: string
|
||||
dueAt?: string
|
||||
completedAt?: string
|
||||
completedById?: string
|
||||
priority: string
|
||||
category: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface LocalHandoffNote {
|
||||
id: string
|
||||
workspaceId: string
|
||||
content: string
|
||||
category: string
|
||||
priority: string
|
||||
expiresAt: string
|
||||
createdAt: string
|
||||
acknowledgedBy: string[]
|
||||
}
|
||||
|
||||
// Add to class
|
||||
class NextStepDB extends Dexie {
|
||||
// ... existing tables ...
|
||||
treatmentPlans!: Table<LocalTreatmentPlan, string>
|
||||
treatmentMilestones!: Table<LocalTreatmentMilestone, string>
|
||||
careTasks!: Table<LocalCareTask, string>
|
||||
handoffNotes!: Table<LocalHandoffNote, string>
|
||||
|
||||
constructor() {
|
||||
super('NextStepDB')
|
||||
|
||||
// Version 3 - Add new tables
|
||||
this.version(3).stores({
|
||||
appointments: 'id, workspaceId, datetime, deletedAt',
|
||||
medications: 'id, workspaceId, active, deletedAt',
|
||||
notes: 'id, workspaceId, type, deletedAt',
|
||||
doseLogs: 'id, medicationId, workspaceId, takenAt',
|
||||
workspaces: 'id',
|
||||
symptoms: 'id, workspaceId, type, recordedAt, deletedAt',
|
||||
outbox: 'id, workspaceId, timestamp',
|
||||
syncMeta: 'id, workspaceId',
|
||||
treatmentPlans: 'id, workspaceId',
|
||||
treatmentMilestones: 'id, planId, cycleNumber',
|
||||
careTasks: 'id, workspaceId, assignedToId, completedAt',
|
||||
handoffNotes: 'id, workspaceId, expiresAt',
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 7: Update User Relations
|
||||
Add to `prisma/schema.prisma` in the User model:
|
||||
|
||||
```prisma
|
||||
model User {
|
||||
// ... existing fields ...
|
||||
|
||||
// Treatment
|
||||
createdTreatmentPlans TreatmentPlan[]
|
||||
assignedCareTasks CareTask[] @relation("AssignedTasks")
|
||||
completedCareTasks CareTask[] @relation("CompletedTasks")
|
||||
createdCareTasks CareTask[]
|
||||
createdHandoffNotes HandoffNote[]
|
||||
|
||||
// ... rest of relations ...
|
||||
}
|
||||
```
|
||||
|
||||
### Step 8: Add Navigation
|
||||
Update `src/app/(app)/today/page.tsx` to include Treatment Progress widget.
|
||||
|
||||
Add to settings page or navigation menu:
|
||||
- Treatment Plan link
|
||||
- Care Coordination link
|
||||
|
||||
---
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
### Treatment Milestone Tracker
|
||||
- [ ] Create new treatment plan
|
||||
- [ ] View progress on dashboard
|
||||
- [ ] Complete a cycle
|
||||
- [ ] See celebration modal
|
||||
- [ ] Check milestone calendar
|
||||
|
||||
### Enhanced Symptom Tracking
|
||||
- [ ] Log symptom with new UI
|
||||
- [ ] View 7/14/30 day trends
|
||||
- [ ] Filter by symptom type
|
||||
- [ ] Generate PDF report
|
||||
- [ ] Copy text summary
|
||||
|
||||
### Caregiver Coordination
|
||||
- [ ] Create care task
|
||||
- [ ] Assign to family member
|
||||
- [ ] Mark task complete
|
||||
- [ ] Add handoff note
|
||||
- [ ] Acknowledge note as another user
|
||||
|
||||
### Emergency Widget
|
||||
- [ ] See floating button
|
||||
- [ ] Click to open modal
|
||||
- [ ] Test call buttons
|
||||
- [ ] View medical info
|
||||
|
||||
### Calendar Integration
|
||||
- [ ] Create calendar feed
|
||||
- [ ] Copy feed URL
|
||||
- [ ] Subscribe in calendar app
|
||||
- [ ] Verify appointments appear
|
||||
|
||||
---
|
||||
|
||||
## Files Summary
|
||||
|
||||
| Feature | Files | Lines of Code |
|
||||
|---------|-------|---------------|
|
||||
| Treatment Tracker | 6 | ~1,200 |
|
||||
| Enhanced Symptoms | 3 | ~800 |
|
||||
| Care Coordination | 3 | ~1,000 |
|
||||
| Emergency Widget | 1 | ~250 |
|
||||
| Calendar Integration | 3 | ~500 |
|
||||
| **Total** | **16** | **~3,750** |
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- All features maintain offline-first capability with Dexie
|
||||
- VIEWER role restrictions are respected
|
||||
- Audit logging added for key actions
|
||||
- Existing patterns followed throughout
|
||||
- No breaking changes to existing functionality
|
||||
@@ -0,0 +1,101 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
import { format, addDays } from 'date-fns'
|
||||
|
||||
// GET /api/workspaces/[id]/calendar-feed
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const workspaceId = params.id
|
||||
const token = request.nextUrl.searchParams.get('token')
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: 'Missing token' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Find the calendar feed
|
||||
const feed = await prisma.calendarFeed.findUnique({
|
||||
where: { token }
|
||||
})
|
||||
|
||||
if (!feed || feed.workspaceId !== workspaceId) {
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Update last accessed
|
||||
await prisma.calendarFeed.update({
|
||||
where: { id: feed.id },
|
||||
data: { lastAccessedAt: new Date() }
|
||||
})
|
||||
|
||||
// Fetch appointments
|
||||
const appointments = await prisma.appointment.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
deletedAt: null,
|
||||
datetime: {
|
||||
gte: new Date(),
|
||||
lte: addDays(new Date(), feed.daysAhead)
|
||||
}
|
||||
},
|
||||
orderBy: { datetime: 'asc' }
|
||||
})
|
||||
|
||||
// Generate ICS content
|
||||
const icsContent = generateICS(appointments, feed.includeMeds)
|
||||
|
||||
// Return as ICS file
|
||||
return new NextResponse(icsContent, {
|
||||
headers: {
|
||||
'Content-Type': 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition': `attachment; filename="nextstep-calendar-${workspaceId}.ics"`,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to generate calendar feed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to generate calendar feed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function generateICS(appointments: any[], includeMeds: boolean): string {
|
||||
const events = appointments.map(appt => {
|
||||
const start = new Date(appt.datetime)
|
||||
const end = new Date(start.getTime() + 60 * 60 * 1000) // 1 hour default
|
||||
|
||||
return `
|
||||
BEGIN:VEVENT
|
||||
UID:${appt.id}@nextstep.app
|
||||
DTSTART:${format(start, "yyyyMMdd'T'HHmmss")}
|
||||
DTEND:${format(end, "yyyyMMdd'T'HHmmss")}
|
||||
SUMMARY:${escapeICS(appt.title)}
|
||||
${appt.location ? `LOCATION:${escapeICS(appt.location)}` : ''}
|
||||
${appt.notes ? `DESCRIPTION:${escapeICS(appt.notes)}` : ''}
|
||||
STATUS:CONFIRMED
|
||||
END:VEVENT`
|
||||
}).join('')
|
||||
|
||||
return `BEGIN:VCALENDAR
|
||||
VERSION:2.0
|
||||
PRODID:-//Next Step//Calendar//EN
|
||||
CALSCALE:GREGORIAN
|
||||
METHOD:PUBLISH
|
||||
X-WR-CALNAME:Next Step Appointments
|
||||
X-WR-TIMEZONE:Australia/Perth
|
||||
${events}
|
||||
END:VCALENDAR`
|
||||
}
|
||||
|
||||
function escapeICS(str: string): string {
|
||||
return str
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/;/g, '\\;')
|
||||
.replace(/,/g, '\\,')
|
||||
.replace(/\n/g, '\\n')
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
import { nanoid } from 'nanoid'
|
||||
|
||||
// GET /api/workspaces/[id]/calendar-feed/settings
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const feed = await prisma.calendarFeed.findFirst({
|
||||
where: { workspaceId }
|
||||
})
|
||||
|
||||
return NextResponse.json({ feed })
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch calendar feed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch calendar feed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces/[id]/calendar-feed
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { includeAppointments, includeMeds, daysAhead } = body
|
||||
|
||||
// Generate unique token
|
||||
const token = nanoid(32)
|
||||
|
||||
const feed = await prisma.calendarFeed.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
token,
|
||||
includeAppointments: includeAppointments ?? true,
|
||||
includeMeds: includeMeds ?? false,
|
||||
daysAhead: daysAhead ?? 90,
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'CREATE',
|
||||
entityType: 'CALENDAR_FEED',
|
||||
entityId: feed.id,
|
||||
details: { includeAppointments, includeMeds }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ feed })
|
||||
} catch (error) {
|
||||
console.error('Failed to create calendar feed:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create calendar feed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Calendar, Copy, Check, RefreshCw,
|
||||
ExternalLink, HelpCircle, Smartphone
|
||||
} from 'lucide-react'
|
||||
|
||||
import { Card, Button, showToast } from '@/components/ui'
|
||||
|
||||
interface CalendarIntegrationProps {
|
||||
workspaceId: string
|
||||
}
|
||||
|
||||
export function CalendarIntegration({ workspaceId }: CalendarIntegrationProps) {
|
||||
const [feed, setFeed] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [showInstructions, setShowInstructions] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetchFeed()
|
||||
}, [workspaceId])
|
||||
|
||||
const fetchFeed = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/settings`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setFeed(data.feed)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch calendar feed:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const createFeed = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
includeAppointments: true,
|
||||
includeMeds: false,
|
||||
daysAhead: 90
|
||||
})
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setFeed(data.feed)
|
||||
showToast('Calendar feed created!', 'success')
|
||||
}
|
||||
} catch {
|
||||
showToast('Failed to create feed', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const regenerateToken = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/calendar-feed/regenerate`, {
|
||||
method: 'POST'
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setFeed(data.feed)
|
||||
showToast('Feed URL regenerated', 'success')
|
||||
}
|
||||
} catch {
|
||||
showToast('Failed to regenerate', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const copyFeedUrl = () => {
|
||||
if (!feed) return
|
||||
const url = `${window.location.origin}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token}`
|
||||
navigator.clipboard.writeText(url)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
showToast('Feed URL copied!', 'success')
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className="text-center py-8">
|
||||
<div className="animate-spin w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full mx-auto" />
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
|
||||
<Calendar className="w-5 h-5 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-secondary-900">Calendar Integration</h3>
|
||||
<p className="text-sm text-secondary-500">Sync appointments to your calendar</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!feed ? (
|
||||
<div className="text-center py-6">
|
||||
<p className="text-secondary-500 mb-4">
|
||||
Create a calendar feed to see your appointments in Apple Calendar, Google Calendar, or Outlook.
|
||||
</p>
|
||||
<Button onClick={createFeed}>
|
||||
<Calendar className="w-4 h-4 mr-2" />
|
||||
Create Calendar Feed
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Feed URL */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Calendar Feed URL
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={`${typeof window !== 'undefined' ? window.location.origin : ''}/api/workspaces/${workspaceId}/calendar-feed?token=${feed.token.substring(0, 8)}...`}
|
||||
readOnly
|
||||
className="flex-1 px-3 py-2 bg-secondary-50 border border-border rounded-lg text-sm text-secondary-600"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={copyFeedUrl}
|
||||
title="Copy URL"
|
||||
>
|
||||
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-secondary-500 mt-1">
|
||||
Copy this URL and add it to your calendar app
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Settings */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-3 bg-secondary-50 rounded-lg">
|
||||
<p className="text-xs text-secondary-500">Appointments</p>
|
||||
<p className="font-medium text-secondary-900">
|
||||
{feed.includeAppointments ? 'Included' : 'Not included'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-3 bg-secondary-50 rounded-lg">
|
||||
<p className="text-xs text-secondary-500">Look Ahead</p>
|
||||
<p className="font-medium text-secondary-900">{feed.daysAhead} days</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Last Accessed */}
|
||||
{feed.lastAccessedAt && (
|
||||
<p className="text-xs text-secondary-500">
|
||||
Last accessed: {new Date(feed.lastAccessedAt).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 pt-2 border-t border-border">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setShowInstructions(!showInstructions)}
|
||||
>
|
||||
<HelpCircle className="w-4 h-4 mr-1" />
|
||||
How to Add
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={regenerateToken}
|
||||
>
|
||||
<RefreshCw className="w-4 h-4 mr-1" />
|
||||
Regenerate
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Instructions */}
|
||||
{showInstructions && (
|
||||
<div className="bg-blue-50 rounded-lg p-4 space-y-3">
|
||||
<h4 className="font-medium text-blue-900 flex items-center gap-2">
|
||||
<Smartphone className="w-4 h-4" />
|
||||
How to Add to Your Calendar
|
||||
</h4>
|
||||
|
||||
<div className="space-y-3 text-sm text-blue-800">
|
||||
<div>
|
||||
<p className="font-medium">Apple Calendar (iPhone/Mac):</p>
|
||||
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
|
||||
<li>Copy the feed URL above</li>
|
||||
<li>Open Calendar app → File → New Calendar Subscription</li>
|
||||
<li>Paste the URL and click Subscribe</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-medium">Google Calendar:</p>
|
||||
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
|
||||
<li>Copy the feed URL above</li>
|
||||
<li>Open Google Calendar → Settings → Add Calendar → From URL</li>
|
||||
<li>Paste the URL and click Add Calendar</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="font-medium">Outlook:</p>
|
||||
<ol className="list-decimal list-inside ml-2 space-y-1 text-blue-700">
|
||||
<li>Copy the feed URL above</li>
|
||||
<li>Open Outlook → Add Calendar → Subscribe from web</li>
|
||||
<li>Paste the URL and click Import</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// POST /api/workspaces/[id]/care-tasks/[taskId]/complete
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string; taskId: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: workspaceId, taskId } = params
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const task = await prisma.careTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
completedAt: new Date(),
|
||||
completedById: user.id
|
||||
},
|
||||
include: {
|
||||
completedBy: { select: { id: true, name: true } }
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'COMPLETE_TASK',
|
||||
entityType: 'CARE_TASK',
|
||||
entityId: task.id,
|
||||
details: { title: task.title }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ task })
|
||||
} catch (error) {
|
||||
console.error('Failed to complete task:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to complete task' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// GET /api/workspaces/[id]/care-tasks
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const tasks = await prisma.careTask.findMany({
|
||||
where: { workspaceId },
|
||||
orderBy: [
|
||||
{ completedAt: 'asc' },
|
||||
{ priority: 'desc' },
|
||||
{ createdAt: 'desc' }
|
||||
],
|
||||
include: {
|
||||
assignedTo: { select: { id: true, name: true } },
|
||||
completedBy: { select: { id: true, name: true } },
|
||||
createdBy: { select: { id: true, name: true } }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ tasks })
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch care tasks:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch care tasks' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces/[id]/care-tasks
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { title, description, priority, category, dueAt, assignedToId } = body
|
||||
|
||||
const task = await prisma.careTask.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
title,
|
||||
description,
|
||||
priority: priority || 'MEDIUM',
|
||||
category: category || 'GENERAL',
|
||||
dueAt: dueAt ? new Date(dueAt) : null,
|
||||
assignedToId: assignedToId || null,
|
||||
createdById: user.id,
|
||||
},
|
||||
include: {
|
||||
assignedTo: { select: { id: true, name: true } },
|
||||
createdBy: { select: { id: true, name: true } }
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'CREATE',
|
||||
entityType: 'CARE_TASK',
|
||||
entityId: task.id,
|
||||
details: { title, priority, category }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ task })
|
||||
} catch (error) {
|
||||
console.error('Failed to create care task:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create care task' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// POST /api/workspaces/[id]/handoff-notes/[noteId]/acknowledge
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string; noteId: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { id: workspaceId, noteId } = params
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Get current note
|
||||
const note = await prisma.handoffNote.findUnique({
|
||||
where: { id: noteId }
|
||||
})
|
||||
|
||||
if (!note) {
|
||||
return NextResponse.json({ error: 'Note not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Add user to acknowledged list if not already there
|
||||
const acknowledgedBy = note.acknowledgedBy || []
|
||||
if (!acknowledgedBy.includes(user.id)) {
|
||||
acknowledgedBy.push(user.id)
|
||||
|
||||
await prisma.handoffNote.update({
|
||||
where: { id: noteId },
|
||||
data: { acknowledgedBy }
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Failed to acknowledge note:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to acknowledge note' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// GET /api/workspaces/[id]/handoff-notes
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Get notes that haven't expired
|
||||
const notes = await prisma.handoffNote.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
expiresAt: { gte: new Date() }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
createdBy: { select: { id: true, name: true } }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ notes })
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch handoff notes:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch handoff notes' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces/[id]/handoff-notes
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { content, category, priority, expiresAt } = body
|
||||
|
||||
const note = await prisma.handoffNote.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
content,
|
||||
category: category || 'GENERAL',
|
||||
priority: priority || 'NORMAL',
|
||||
expiresAt: new Date(expiresAt),
|
||||
createdById: user.id,
|
||||
acknowledgedBy: []
|
||||
},
|
||||
include: {
|
||||
createdBy: { select: { id: true, name: true } }
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'CREATE',
|
||||
entityType: 'HANDOFF_NOTE',
|
||||
entityId: note.id,
|
||||
details: { category, priority }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ note })
|
||||
} catch (error) {
|
||||
console.error('Failed to create handoff note:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create handoff note' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ChevronLeft, MessageSquare, AlertCircle, Users } from 'lucide-react'
|
||||
import { addHours } from 'date-fns'
|
||||
|
||||
import { Card, Button, showToast } from '@/components/ui'
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { useApp } from '../../provider'
|
||||
|
||||
const CATEGORIES = [
|
||||
{ value: 'GENERAL', label: 'General Update', emoji: '📝', color: 'bg-blue-100 border-blue-200' },
|
||||
{ value: 'SYMPTOM', label: 'Symptom Observation', emoji: '😷', color: 'bg-red-50 border-red-200' },
|
||||
{ value: 'MEDICATION', label: 'Medication Note', emoji: '💊', color: 'bg-green-50 border-green-200' },
|
||||
{ value: 'MOOD', label: 'Mood/Energy', emoji: '💭', color: 'bg-purple-50 border-purple-200' },
|
||||
]
|
||||
|
||||
const PRIORITIES = [
|
||||
{ value: 'LOW', label: 'FYI Only' },
|
||||
{ value: 'NORMAL', label: 'Normal' },
|
||||
{ value: 'HIGH', label: 'Important - Please Read', color: 'text-red-600' },
|
||||
]
|
||||
|
||||
export default function NewHandoffNotePage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace } = useApp()
|
||||
const [content, setContent] = useState('')
|
||||
const [category, setCategory] = useState('GENERAL')
|
||||
const [priority, setPriority] = useState('NORMAL')
|
||||
const [expiresIn, setExpiresIn] = useState('12')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!content.trim()) {
|
||||
showToast('Please write a note', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const expiresAt = addHours(new Date(), parseInt(expiresIn))
|
||||
|
||||
const response = await fetch(`/api/workspaces/${currentWorkspace.id}/handoff-notes`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
content: content.trim(),
|
||||
category,
|
||||
priority,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to create note')
|
||||
|
||||
showToast('Handoff note added!', 'success')
|
||||
router.push('/care')
|
||||
} catch {
|
||||
showToast('Failed to add note', 'error')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="Handoff Note"
|
||||
leftAction={{
|
||||
icon: <ChevronLeft className="w-6 h-6" />,
|
||||
label: 'Back',
|
||||
onClick: () => router.push('/care')
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4">
|
||||
{/* Info Card */}
|
||||
<Card className="bg-amber-50 border-amber-200 mb-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Users className="w-5 h-5 text-amber-600 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-amber-900">What are handoff notes?</h3>
|
||||
<p className="text-sm text-amber-700 mt-1">
|
||||
Use these to communicate with other caregivers. They expire after a set time and can be marked as read.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{/* Category */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
What type of note?
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{CATEGORIES.map((cat) => (
|
||||
<button
|
||||
key={cat.value}
|
||||
type="button"
|
||||
onClick={() => setCategory(cat.value)}
|
||||
className={`w-full p-3 rounded-lg border-2 text-left transition-all flex items-center gap-3 ${
|
||||
category === cat.value
|
||||
? cat.color + ' border-current'
|
||||
: 'border-border hover:border-secondary-300'
|
||||
}`}
|
||||
>
|
||||
<span className="text-2xl">{cat.emoji}</span>
|
||||
<span className="font-medium text-secondary-900">{cat.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Priority */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<AlertCircle className="w-4 h-4 inline mr-1" />
|
||||
Priority
|
||||
</label>
|
||||
<select
|
||||
value={priority}
|
||||
onChange={(e) => setPriority(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
>
|
||||
{PRIORITIES.map((p) => (
|
||||
<option key={p.value} value={p.value} className={p.color}>
|
||||
{p.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Card>
|
||||
|
||||
{/* Content */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<MessageSquare className="w-4 h-4 inline mr-1" />
|
||||
Your Note
|
||||
</label>
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="What should other caregivers know? For example:\n• Patient seemed more tired than usual today\n• New medication started, watching for side effects\n• Appointment went well, next one scheduled for..."
|
||||
rows={5}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500 resize-none"
|
||||
required
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Expires In */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Note expires in
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
{['4', '12', '24', '48'].map((hours) => (
|
||||
<button
|
||||
key={hours}
|
||||
type="button"
|
||||
onClick={() => setExpiresIn(hours)}
|
||||
className={`flex-1 py-2 rounded-lg border-2 text-sm font-medium transition-all ${
|
||||
expiresIn === hours
|
||||
? 'border-primary-500 bg-primary-50 text-primary-700'
|
||||
: 'border-border hover:border-secondary-300 text-secondary-600'
|
||||
}`}
|
||||
>
|
||||
{hours}h
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-secondary-500 mt-2">
|
||||
Notes expire automatically to keep information fresh
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
{/* Submit */}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => router.push('/care')}
|
||||
fullWidth
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={saving}
|
||||
fullWidth
|
||||
>
|
||||
Add Note
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ChevronLeft, ClipboardList, Clock, User, AlertCircle } from 'lucide-react'
|
||||
|
||||
import { Card, Button, showToast } from '@/components/ui'
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { useApp } from '../../provider'
|
||||
|
||||
const PRIORITIES = [
|
||||
{ value: 'LOW', label: 'Low', color: 'bg-blue-100 text-blue-700' },
|
||||
{ value: 'MEDIUM', label: 'Medium', color: 'bg-yellow-100 text-yellow-700' },
|
||||
{ value: 'HIGH', label: 'High', color: 'bg-orange-100 text-orange-700' },
|
||||
{ value: 'URGENT', label: 'Urgent', color: 'bg-red-100 text-red-700' },
|
||||
]
|
||||
|
||||
const CATEGORIES = [
|
||||
{ value: 'GENERAL', label: 'General', emoji: '📝' },
|
||||
{ value: 'MEDICATION', label: 'Medication', emoji: '💊' },
|
||||
{ value: 'APPOINTMENT', label: 'Appointment', emoji: '📅' },
|
||||
{ value: 'SYMPTOM', label: 'Symptom', emoji: '😷' },
|
||||
]
|
||||
|
||||
export default function NewCareTaskPage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace } = useApp()
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [priority, setPriority] = useState('MEDIUM')
|
||||
const [category, setCategory] = useState('GENERAL')
|
||||
const [dueDate, setDueDate] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!title.trim()) {
|
||||
showToast('Please enter a task title', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${currentWorkspace.id}/care-tasks`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
description: description.trim() || null,
|
||||
priority,
|
||||
category,
|
||||
dueAt: dueDate ? new Date(dueDate).toISOString() : null,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to create task')
|
||||
|
||||
showToast('Task created!', 'success')
|
||||
router.push('/care')
|
||||
} catch {
|
||||
showToast('Failed to create task', 'error')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="New Care Task"
|
||||
leftAction={{
|
||||
icon: <ChevronLeft className="w-6 h-6" />,
|
||||
label: 'Back',
|
||||
onClick: () => router.push('/care')
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Title */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<ClipboardList className="w-4 h-4 inline mr-1" />
|
||||
Task Title
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="e.g., Pick up prescription"
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
required
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Category */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Category
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{CATEGORIES.map((cat) => (
|
||||
<button
|
||||
key={cat.value}
|
||||
type="button"
|
||||
onClick={() => setCategory(cat.value)}
|
||||
className={`p-3 rounded-lg border-2 text-left transition-all ${
|
||||
category === cat.value
|
||||
? 'border-primary-500 bg-primary-50'
|
||||
: 'border-border hover:border-secondary-300'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl mr-2">{cat.emoji}</span>
|
||||
<span className="font-medium text-secondary-900">{cat.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Priority */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<AlertCircle className="w-4 h-4 inline mr-1" />
|
||||
Priority
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{PRIORITIES.map((p) => (
|
||||
<button
|
||||
key={p.value}
|
||||
type="button"
|
||||
onClick={() => setPriority(p.value)}
|
||||
className={`px-4 py-2 rounded-full font-medium transition-all ${
|
||||
priority === p.value
|
||||
? p.color + ' ring-2 ring-offset-2 ring-secondary-300'
|
||||
: 'bg-secondary-100 text-secondary-600 hover:bg-secondary-200'
|
||||
}`}
|
||||
>
|
||||
{p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Due Date */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<Clock className="w-4 h-4 inline mr-1" />
|
||||
Due Date (optional)
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={dueDate}
|
||||
onChange={(e) => setDueDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Description */}
|
||||
<Card>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Description (optional)
|
||||
</label>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
placeholder="Any additional details..."
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500 resize-none"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* Submit */}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => router.push('/care')}
|
||||
fullWidth
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={saving}
|
||||
fullWidth
|
||||
>
|
||||
Create Task
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
ClipboardList, Plus, CheckCircle2, Circle,
|
||||
Users, Clock, AlertCircle, ChevronRight
|
||||
} from 'lucide-react'
|
||||
|
||||
import { Card, Button, showToast } from '@/components/ui'
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { useApp } from '../provider'
|
||||
|
||||
interface CareTask {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
assignedTo?: { id: string; name: string }
|
||||
dueAt?: string
|
||||
completedAt?: string
|
||||
completedBy?: { id: string; name: string }
|
||||
priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT'
|
||||
category: 'MEDICATION' | 'APPOINTMENT' | 'SYMPTOM' | 'GENERAL'
|
||||
createdAt: string
|
||||
createdBy: { id: string; name: string }
|
||||
}
|
||||
|
||||
interface HandoffNote {
|
||||
id: string
|
||||
content: string
|
||||
category: 'GENERAL' | 'SYMPTOM' | 'MEDICATION' | 'MOOD'
|
||||
priority: 'LOW' | 'NORMAL' | 'HIGH'
|
||||
createdAt: string
|
||||
createdBy: { id: string; name: string }
|
||||
expiresAt: string
|
||||
acknowledgedBy: string[]
|
||||
}
|
||||
|
||||
const PRIORITY_COLORS = {
|
||||
LOW: 'bg-blue-100 text-blue-700',
|
||||
MEDIUM: 'bg-yellow-100 text-yellow-700',
|
||||
HIGH: 'bg-orange-100 text-orange-700',
|
||||
URGENT: 'bg-red-100 text-red-700',
|
||||
}
|
||||
|
||||
const CATEGORY_ICONS = {
|
||||
MEDICATION: '💊',
|
||||
APPOINTMENT: '📅',
|
||||
SYMPTOM: '😷',
|
||||
GENERAL: '📝',
|
||||
}
|
||||
|
||||
export default function CareCoordinationPage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace } = useApp()
|
||||
const [tasks, setTasks] = useState<CareTask[]>([])
|
||||
const [handoffNotes, setHandoffNotes] = useState<HandoffNote[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [activeTab, setActiveTab] = useState<'tasks' | 'notes'>('tasks')
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [tasksRes, notesRes] = await Promise.all([
|
||||
fetch(`/api/workspaces/${currentWorkspace.id}/care-tasks`),
|
||||
fetch(`/api/workspaces/${currentWorkspace.id}/handoff-notes`)
|
||||
])
|
||||
|
||||
if (tasksRes.ok) {
|
||||
const tasksData = await tasksRes.json()
|
||||
setTasks(tasksData.tasks)
|
||||
}
|
||||
if (notesRes.ok) {
|
||||
const notesData = await notesRes.json()
|
||||
setHandoffNotes(notesData.notes)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch care data:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [currentWorkspace.id])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const handleCompleteTask = async (taskId: string) => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/workspaces/${currentWorkspace.id}/care-tasks/${taskId}/complete`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
if (!response.ok) throw new Error('Failed to complete task')
|
||||
|
||||
showToast('Task completed!', 'success')
|
||||
fetchData()
|
||||
} catch {
|
||||
showToast('Failed to complete task', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const handleAcknowledgeNote = async (noteId: string) => {
|
||||
try {
|
||||
await fetch(
|
||||
`/api/workspaces/${currentWorkspace.id}/handoff-notes/${noteId}/acknowledge`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
fetchData()
|
||||
} catch {
|
||||
console.error('Failed to acknowledge note')
|
||||
}
|
||||
}
|
||||
|
||||
// Separate active and completed tasks
|
||||
const activeTasks = tasks.filter(t => !t.completedAt)
|
||||
const completedTasks = tasks.filter(t => t.completedAt).slice(0, 5)
|
||||
|
||||
// Filter unacknowledged notes
|
||||
const unacknowledgedNotes = handoffNotes.filter(
|
||||
n => !n.acknowledgedBy.includes(currentWorkspace.userId || '')
|
||||
)
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<>
|
||||
<Header title="Care Coordination" />
|
||||
<PageContainer>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-spin w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full" />
|
||||
</div>
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="Care Coordination"
|
||||
rightAction={{
|
||||
icon: <Plus className="w-6 h-6 text-secondary-700" />,
|
||||
label: 'Add',
|
||||
onClick: () => router.push('/care/new-task')
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4 space-y-6">
|
||||
{/* Tab Switcher */}
|
||||
<div className="flex bg-secondary-100 rounded-lg p-1">
|
||||
<button
|
||||
onClick={() => setActiveTab('tasks')}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-md text-sm font-medium transition-all ${
|
||||
activeTab === 'tasks'
|
||||
? 'bg-white text-secondary-900 shadow-sm'
|
||||
: 'text-secondary-600 hover:text-secondary-900'
|
||||
}`}
|
||||
>
|
||||
<ClipboardList className="w-4 h-4" />
|
||||
Tasks ({activeTasks.length})
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('notes')}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-md text-sm font-medium transition-all ${
|
||||
activeTab === 'notes'
|
||||
? 'bg-white text-secondary-900 shadow-sm'
|
||||
: 'text-secondary-600 hover:text-secondary-900'
|
||||
}`}
|
||||
>
|
||||
<Users className="w-4 h-4" />
|
||||
Handoff
|
||||
{unacknowledgedNotes.length > 0 && (
|
||||
<span className="w-5 h-5 bg-red-500 text-white text-xs rounded-full flex items-center justify-center">
|
||||
{unacknowledgedNotes.length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tasks View */}
|
||||
{activeTab === 'tasks' && (
|
||||
<>
|
||||
{/* Active Tasks */}
|
||||
<section>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-3">
|
||||
Active Tasks
|
||||
</h2>
|
||||
{activeTasks.length === 0 ? (
|
||||
<Card variant="outline" className="text-center py-8">
|
||||
<ClipboardList className="w-12 h-12 text-secondary-300 mx-auto mb-3" />
|
||||
<p className="text-secondary-500">No active tasks</p>
|
||||
<p className="text-sm text-secondary-400 mt-1">
|
||||
Add tasks to coordinate care
|
||||
</p>
|
||||
{currentWorkspace.role !== 'VIEWER' && (
|
||||
<Button
|
||||
href="/care/new-task"
|
||||
variant="secondary"
|
||||
className="mt-4"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Add Task
|
||||
</Button>
|
||||
)}
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{activeTasks.map(task => (
|
||||
<TaskCard
|
||||
key={task.id}
|
||||
task={task}
|
||||
onComplete={() => handleCompleteTask(task.id)}
|
||||
canComplete={currentWorkspace.role !== 'VIEWER'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Recently Completed */}
|
||||
{completedTasks.length > 0 && (
|
||||
<section>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-3">
|
||||
Recently Completed
|
||||
</h2>
|
||||
<div className="space-y-2">
|
||||
{completedTasks.map(task => (
|
||||
<div
|
||||
key={task.id}
|
||||
className="p-3 bg-secondary-50 rounded-lg opacity-60"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
||||
<span className="flex-1 line-through text-secondary-500">
|
||||
{task.title}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Handoff Notes View */}
|
||||
{activeTab === 'notes' && (
|
||||
<>
|
||||
{/* Quick Add Note */}
|
||||
{currentWorkspace.role !== 'VIEWER' && (
|
||||
<Card className="bg-amber-50 border-amber-200">
|
||||
<h3 className="font-medium text-amber-900 mb-2">Quick Handoff Note</h3>
|
||||
<p className="text-sm text-amber-700 mb-3">
|
||||
Leave a note for other caregivers about symptoms, observations, or important updates.
|
||||
</p>
|
||||
<Button
|
||||
href="/care/new-note"
|
||||
variant="secondary"
|
||||
fullWidth
|
||||
>
|
||||
Write Note
|
||||
</Button>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Unacknowledged Notes */}
|
||||
{unacknowledgedNotes.length > 0 && (
|
||||
<section>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-3 flex items-center">
|
||||
<AlertCircle className="w-5 h-5 mr-2 text-amber-500" />
|
||||
New for You
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
{unacknowledgedNotes.map(note => (
|
||||
<HandoffNoteCard
|
||||
key={note.id}
|
||||
note={note}
|
||||
isNew={true}
|
||||
onAcknowledge={() => handleAcknowledgeNote(note.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* All Notes */}
|
||||
<section>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-3">
|
||||
Recent Notes
|
||||
</h2>
|
||||
{handoffNotes.length === 0 ? (
|
||||
<Card variant="outline" className="text-center py-8">
|
||||
<Users className="w-12 h-12 text-secondary-300 mx-auto mb-3" />
|
||||
<p className="text-secondary-500">No handoff notes</p>
|
||||
<p className="text-sm text-secondary-400 mt-1">
|
||||
Notes help coordinate care between family members
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{handoffNotes.slice(0, 10).map(note => (
|
||||
<HandoffNoteCard
|
||||
key={note.id}
|
||||
note={note}
|
||||
isNew={false}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface TaskCardProps {
|
||||
task: CareTask
|
||||
onComplete: () => void
|
||||
canComplete: boolean
|
||||
}
|
||||
|
||||
function TaskCard({ task, onComplete, canComplete }: TaskCardProps) {
|
||||
const isOverdue = task.dueAt && new Date(task.dueAt) < new Date() && !task.completedAt
|
||||
|
||||
return (
|
||||
<Card className={isOverdue ? 'border-red-300' : ''}>
|
||||
<div className="flex items-start gap-3">
|
||||
{canComplete ? (
|
||||
<button
|
||||
onClick={onComplete}
|
||||
className="mt-0.5 w-6 h-6 rounded-full border-2 border-primary-500 flex items-center justify-center hover:bg-primary-50"
|
||||
>
|
||||
<Circle className="w-4 h-4 text-primary-500" />
|
||||
</button>
|
||||
) : (
|
||||
<Circle className="w-6 h-6 text-secondary-300 mt-0.5" />
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-lg">{CATEGORY_ICONS[task.category]}</span>
|
||||
<h3 className={`font-medium ${task.completedAt ? 'line-through text-secondary-500' : 'text-secondary-900'}`}>
|
||||
{task.title}
|
||||
</h3>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full ${PRIORITY_COLORS[task.priority]}`}>
|
||||
{task.priority}
|
||||
</span>
|
||||
</div>
|
||||
{task.description && (
|
||||
<p className="text-sm text-secondary-600 mt-1">{task.description}</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 mt-2 text-xs text-secondary-500">
|
||||
{task.assignedTo && (
|
||||
<span className="flex items-center gap-1">
|
||||
<Users className="w-3 h-3" />
|
||||
{task.assignedTo.name}
|
||||
</span>
|
||||
)}
|
||||
{task.dueAt && (
|
||||
<span className={`flex items-center gap-1 ${isOverdue ? 'text-red-600 font-medium' : ''}`}>
|
||||
<Clock className="w-3 h-3" />
|
||||
{isOverdue ? 'Overdue: ' : 'Due: '}
|
||||
{new Date(task.dueAt).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
interface HandoffNoteCardProps {
|
||||
note: HandoffNote
|
||||
isNew: boolean
|
||||
onAcknowledge?: () => void
|
||||
}
|
||||
|
||||
function HandoffNoteCard({ note, isNew, onAcknowledge }: HandoffNoteCardProps) {
|
||||
const CATEGORY_COLORS = {
|
||||
GENERAL: 'bg-blue-50 border-blue-200',
|
||||
SYMPTOM: 'bg-red-50 border-red-200',
|
||||
MEDICATION: 'bg-green-50 border-green-200',
|
||||
MOOD: 'bg-purple-50 border-purple-200',
|
||||
}
|
||||
|
||||
const PRIORITY_BADGES = {
|
||||
LOW: '',
|
||||
NORMAL: '',
|
||||
HIGH: '🔴 High Priority',
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={`${CATEGORY_COLORS[note.category]} ${isNew ? 'ring-2 ring-amber-400' : ''}`}>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1">
|
||||
{note.priority === 'HIGH' && (
|
||||
<span className="text-xs font-medium text-red-600 mb-1 block">
|
||||
{PRIORITY_BADGES[note.priority]}
|
||||
</span>
|
||||
)}
|
||||
<p className="text-secondary-900 whitespace-pre-wrap">{note.content}</p>
|
||||
<div className="flex items-center justify-between mt-3">
|
||||
<span className="text-xs text-secondary-500">
|
||||
{note.createdBy.name} • {new Date(note.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
{isNew && onAcknowledge && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={onAcknowledge}
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4 mr-1" />
|
||||
Got it
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// GET /api/workspaces/[id]/emergency-info
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Get workspace with emergency info
|
||||
const workspace = await prisma.workspace.findUnique({
|
||||
where: { id: workspaceId },
|
||||
select: {
|
||||
patientName: true,
|
||||
patientDOB: true,
|
||||
bloodType: true,
|
||||
allergies: true,
|
||||
medicalConditions: true,
|
||||
primaryPhysician: true,
|
||||
physicianPhone: true,
|
||||
clinicPhone: true,
|
||||
emergencyPhone: true,
|
||||
}
|
||||
})
|
||||
|
||||
// Get active medications
|
||||
const medications = await prisma.medication.findMany({
|
||||
where: {
|
||||
workspaceId,
|
||||
active: true,
|
||||
deletedAt: null
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
instructions: true
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
info: {
|
||||
...workspace,
|
||||
medications
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch emergency info:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch emergency info' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
AlertTriangle, Phone, X, Heart,
|
||||
User, Droplet, AlertCircle, MapPin
|
||||
} from 'lucide-react'
|
||||
|
||||
import { useApp } from '../provider'
|
||||
|
||||
interface EmergencyWidgetProps {
|
||||
workspaceId: string
|
||||
}
|
||||
|
||||
export function EmergencyWidget({ workspaceId }: EmergencyWidgetProps) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [emergencyInfo, setEmergencyInfo] = useState<any>(null)
|
||||
const { currentWorkspace } = useApp()
|
||||
|
||||
useEffect(() => {
|
||||
const fetchInfo = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/emergency-info`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setEmergencyInfo(data.info)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch emergency info:', err)
|
||||
}
|
||||
}
|
||||
fetchInfo()
|
||||
}, [workspaceId])
|
||||
|
||||
if (!emergencyInfo) return null
|
||||
|
||||
const hasAnyInfo = emergencyInfo.patientName ||
|
||||
emergencyInfo.bloodType ||
|
||||
emergencyInfo.allergies ||
|
||||
emergencyInfo.medicalConditions ||
|
||||
emergencyInfo.clinicPhone ||
|
||||
emergencyInfo.emergencyPhone
|
||||
|
||||
if (!hasAnyInfo) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Floating Emergency Button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(true)}
|
||||
className="fixed bottom-20 right-4 z-40 w-14 h-14 rounded-full bg-red-600 text-white shadow-lg hover:bg-red-700 transition-all hover:scale-110 flex items-center justify-center"
|
||||
title="Emergency Info"
|
||||
>
|
||||
<AlertTriangle className="w-6 h-6" />
|
||||
</button>
|
||||
|
||||
{/* Emergency Modal */}
|
||||
{isOpen && (
|
||||
<div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
|
||||
<div className="bg-white w-full max-w-md rounded-t-2xl sm:rounded-2xl max-h-[90vh] overflow-auto animate-in slide-in-from-bottom duration-200">
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 bg-red-600 text-white p-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="w-6 h-6" />
|
||||
<h2 className="text-lg font-semibold">Emergency Info</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="p-2 hover:bg-red-700 rounded-full"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Quick Call Buttons */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{emergencyInfo.emergencyPhone && (
|
||||
<a
|
||||
href={`tel:${emergencyInfo.emergencyPhone}`}
|
||||
className="bg-red-100 border border-red-200 rounded-xl p-4 text-center hover:bg-red-200 transition-colors"
|
||||
>
|
||||
<Phone className="w-8 h-8 text-red-600 mx-auto mb-2" />
|
||||
<p className="font-semibold text-red-800">Emergency</p>
|
||||
<p className="text-sm text-red-600">{emergencyInfo.emergencyPhone}</p>
|
||||
</a>
|
||||
)}
|
||||
{emergencyInfo.clinicPhone && (
|
||||
<a
|
||||
href={`tel:${emergencyInfo.clinicPhone}`}
|
||||
className="bg-blue-100 border border-blue-200 rounded-xl p-4 text-center hover:bg-blue-200 transition-colors"
|
||||
>
|
||||
<Heart className="w-8 h-8 text-blue-600 mx-auto mb-2" />
|
||||
<p className="font-semibold text-blue-800">Clinic</p>
|
||||
<p className="text-sm text-blue-600">{emergencyInfo.clinicPhone}</p>
|
||||
</a>
|
||||
)}
|
||||
{emergencyInfo.physicianPhone && (
|
||||
<a
|
||||
href={`tel:${emergencyInfo.physicianPhone}`}
|
||||
className="bg-green-100 border border-green-200 rounded-xl p-4 text-center hover:bg-green-200 transition-colors col-span-2"
|
||||
>
|
||||
<User className="w-8 h-8 text-green-600 mx-auto mb-2" />
|
||||
<p className="font-semibold text-green-800">Primary Physician</p>
|
||||
<p className="text-sm text-green-600">{emergencyInfo.physicianPhone}</p>
|
||||
{emergencyInfo.primaryPhysician && (
|
||||
<p className="text-xs text-green-500 mt-1">
|
||||
Dr. {emergencyInfo.primaryPhysician}
|
||||
</p>
|
||||
)}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Medical ID Card */}
|
||||
<div className="bg-amber-50 border-2 border-amber-200 rounded-xl p-4">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<AlertCircle className="w-5 h-5 text-amber-600" />
|
||||
<h3 className="font-semibold text-amber-900">Medical ID</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{emergencyInfo.patientName && (
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="w-4 h-4 text-amber-600" />
|
||||
<span className="text-amber-900">
|
||||
<strong>Name:</strong> {emergencyInfo.patientName}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{emergencyInfo.bloodType && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Droplet className="w-4 h-4 text-amber-600" />
|
||||
<span className="text-amber-900">
|
||||
<strong>Blood Type:</strong> {emergencyInfo.bloodType}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{emergencyInfo.allergies && (
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-red-500 mt-0.5" />
|
||||
<div>
|
||||
<span className="text-red-700 font-medium">Allergies:</span>
|
||||
<p className="text-red-600">{emergencyInfo.allergies}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{emergencyInfo.medicalConditions && (
|
||||
<div className="flex items-start gap-2">
|
||||
<Heart className="w-4 h-4 text-amber-600 mt-0.5" />
|
||||
<div>
|
||||
<span className="text-amber-900 font-medium">Conditions:</span>
|
||||
<p className="text-amber-800">{emergencyInfo.medicalConditions}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current Medications */}
|
||||
{emergencyInfo.medications?.length > 0 && (
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
|
||||
<h3 className="font-semibold text-blue-900 mb-2">Current Medications</h3>
|
||||
<ul className="space-y-1">
|
||||
{emergencyInfo.medications.map((med: any) => (
|
||||
<li key={med.id} className="text-sm text-blue-800">
|
||||
• {med.name} {med.instructions && `(${med.instructions})`}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit Button */}
|
||||
{currentWorkspace.role !== 'VIEWER' && (
|
||||
<a
|
||||
href="/settings/emergency"
|
||||
className="block w-full py-3 text-center text-secondary-600 hover:text-secondary-900 text-sm"
|
||||
>
|
||||
Edit Emergency Information
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* Disclaimer */}
|
||||
<p className="text-xs text-secondary-400 text-center">
|
||||
This information is for emergency use only.
|
||||
Always call 000 (AU) or your local emergency number in a life-threatening emergency.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import {
|
||||
BarChart2, History, TrendingUp, Download,
|
||||
Calendar, Filter, Activity
|
||||
} from 'lucide-react'
|
||||
import { useLiveQuery } from 'dexie-react-hooks'
|
||||
import { format, subDays, startOfDay, isSameDay, subWeeks, subMonths } from 'date-fns'
|
||||
|
||||
import { db } from '@/lib/sync'
|
||||
import { Card, LoadingState, Button, showToast } from '@/components/ui'
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { SymptomQuickLog } from '@/components/symptoms/SymptomQuickLog'
|
||||
import { SymptomCard } from '@/components/symptoms/SymptomCard'
|
||||
import { SymptomTrendChart } from '@/components/symptoms/SymptomTrendChart'
|
||||
import { SymptomReportGenerator } from '@/components/symptoms/SymptomReportGenerator'
|
||||
import { useApp } from '../provider'
|
||||
|
||||
const TIME_RANGES = [
|
||||
{ value: '7', label: '7 Days' },
|
||||
{ value: '14', label: '14 Days' },
|
||||
{ value: '30', label: '30 Days' },
|
||||
]
|
||||
|
||||
const SYMPTOM_TYPES = [
|
||||
{ type: 'FATIGUE', emoji: '😴', label: 'Fatigue', color: '#8b5cf6' },
|
||||
{ type: 'NAUSEA', emoji: '🤢', label: 'Nausea', color: '#f59e0b' },
|
||||
{ type: 'PAIN', emoji: '😣', label: 'Pain', color: '#ef4444' },
|
||||
{ type: 'APPETITE', emoji: '🍽️', label: 'Appetite', color: '#10b981' },
|
||||
{ type: 'SLEEP', emoji: '😴', label: 'Sleep', color: '#3b82f6' },
|
||||
{ type: 'MOOD', emoji: '😔', label: 'Mood', color: '#ec4899' },
|
||||
]
|
||||
|
||||
export default function EnhancedSymptomsPage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace, refreshData } = useApp()
|
||||
const [recentSymptoms, setRecentSymptoms] = useState<any[]>([])
|
||||
const [timeRange, setTimeRange] = useState('7')
|
||||
const [selectedType, setSelectedType] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showReport, setShowReport] = useState(false)
|
||||
|
||||
// Fetch symptoms from IndexedDB
|
||||
const localSymptoms = useLiveQuery(
|
||||
() =>
|
||||
db.symptoms
|
||||
.where('workspaceId')
|
||||
.equals(currentWorkspace.id)
|
||||
.and((s) => !s.deletedAt)
|
||||
.reverse()
|
||||
.toArray(),
|
||||
[currentWorkspace.id]
|
||||
)
|
||||
|
||||
// Fetch from server
|
||||
const fetchSymptoms = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/workspaces/${currentWorkspace.id}/symptoms?limit=100`
|
||||
)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setRecentSymptoms(data.symptoms)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch symptoms:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [currentWorkspace.id])
|
||||
|
||||
useEffect(() => {
|
||||
fetchSymptoms()
|
||||
}, [fetchSymptoms])
|
||||
|
||||
const handleLogged = () => {
|
||||
fetchSymptoms()
|
||||
refreshData()
|
||||
}
|
||||
|
||||
// Combine local and server data
|
||||
const symptoms = recentSymptoms.length > 0 ? recentSymptoms : localSymptoms || []
|
||||
|
||||
// Filter by time range
|
||||
const daysBack = parseInt(timeRange)
|
||||
const cutoffDate = subDays(new Date(), daysBack)
|
||||
const filteredSymptoms = symptoms.filter(s =>
|
||||
new Date(s.recordedAt) >= cutoffDate &&
|
||||
(!selectedType || s.type === selectedType)
|
||||
)
|
||||
|
||||
// Calculate stats
|
||||
const stats = useMemo(() => {
|
||||
const byType: Record<string, { count: number; avgSeverity: number }> = {}
|
||||
|
||||
filteredSymptoms.forEach(s => {
|
||||
if (!byType[s.type]) {
|
||||
byType[s.type] = { count: 0, avgSeverity: 0 }
|
||||
}
|
||||
byType[s.type].count++
|
||||
byType[s.type].avgSeverity += s.severity
|
||||
})
|
||||
|
||||
// Calculate averages
|
||||
Object.keys(byType).forEach(type => {
|
||||
byType[type].avgSeverity = Math.round((byType[type].avgSeverity / byType[type].count) * 10) / 10
|
||||
})
|
||||
|
||||
return byType
|
||||
}, [filteredSymptoms])
|
||||
|
||||
// Find patterns (days with multiple symptoms)
|
||||
const patterns = useMemo(() => {
|
||||
const byDate: Record<string, any[]> = {}
|
||||
filteredSymptoms.forEach(s => {
|
||||
const date = format(new Date(s.recordedAt), 'yyyy-MM-dd')
|
||||
if (!byDate[date]) byDate[date] = []
|
||||
byDate[date].push(s)
|
||||
})
|
||||
|
||||
return Object.entries(byDate)
|
||||
.filter(([_, items]) => items.length >= 2)
|
||||
.sort((a, b) => b[0].localeCompare(a[0]))
|
||||
.slice(0, 5)
|
||||
}, [filteredSymptoms])
|
||||
|
||||
if (loading && !localSymptoms) {
|
||||
return (
|
||||
<>
|
||||
<Header title="Symptom Insights" />
|
||||
<PageContainer>
|
||||
<LoadingState message="Loading symptoms..." />
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="Symptom Insights"
|
||||
rightAction={{
|
||||
icon: <History className="w-6 h-6 text-secondary-700" />,
|
||||
label: 'History',
|
||||
onClick: () => router.push('/symptoms/history'),
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4 space-y-6">
|
||||
{/* Quick Log */}
|
||||
<section>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-3">Log a Symptom</h2>
|
||||
<Card>
|
||||
<SymptomQuickLog
|
||||
workspaceId={currentWorkspace.id}
|
||||
onLogged={handleLogged}
|
||||
medications={medications}
|
||||
/>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Time Range & Filters */}
|
||||
<section>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-lg font-semibold text-secondary-900 flex items-center">
|
||||
<TrendingUp className="w-5 h-5 mr-2" />
|
||||
Trends & Insights
|
||||
</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowReport(true)}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-1" />
|
||||
Report
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Time Range Selector */}
|
||||
<div className="flex gap-2 mb-4">
|
||||
{TIME_RANGES.map(range => (
|
||||
<button
|
||||
key={range.value}
|
||||
onClick={() => setTimeRange(range.value)}
|
||||
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
|
||||
timeRange === range.value
|
||||
? 'bg-primary-500 text-white'
|
||||
: 'bg-secondary-100 text-secondary-600 hover:bg-secondary-200'
|
||||
}`}
|
||||
>
|
||||
{range.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Symptom Type Filter */}
|
||||
<div className="flex flex-wrap gap-2 mb-4">
|
||||
<button
|
||||
onClick={() => setSelectedType(null)}
|
||||
className={`px-3 py-1.5 rounded-full text-sm transition-all ${
|
||||
selectedType === null
|
||||
? 'bg-secondary-800 text-white'
|
||||
: 'bg-secondary-100 text-secondary-600'
|
||||
}`}
|
||||
>
|
||||
All
|
||||
</button>
|
||||
{SYMPTOM_TYPES.map(type => (
|
||||
<button
|
||||
key={type.type}
|
||||
onClick={() => setSelectedType(type.type)}
|
||||
className={`px-3 py-1.5 rounded-full text-sm transition-all flex items-center gap-1 ${
|
||||
selectedType === type.type
|
||||
? 'text-white'
|
||||
: 'bg-secondary-100 text-secondary-600'
|
||||
}`}
|
||||
style={{
|
||||
backgroundColor: selectedType === type.type ? type.color : undefined
|
||||
}}
|
||||
>
|
||||
<span>{type.emoji}</span>
|
||||
<span>{type.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Trend Chart */}
|
||||
{filteredSymptoms.length > 0 && (
|
||||
<Card>
|
||||
<SymptomTrendChart
|
||||
symptoms={filteredSymptoms}
|
||||
days={parseInt(timeRange)}
|
||||
selectedType={selectedType}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Stats Summary */}
|
||||
{Object.keys(stats).length > 0 && (
|
||||
<Card>
|
||||
<h3 className="font-semibold text-secondary-900 mb-3 flex items-center">
|
||||
<Activity className="w-5 h-5 mr-2 text-primary-500" />
|
||||
Summary ({timeRange} Days)
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{Object.entries(stats).map(([type, data]) => {
|
||||
const typeInfo = SYMPTOM_TYPES.find(t => t.type === type)
|
||||
return (
|
||||
<div key={type} className="flex items-center justify-between p-3 bg-secondary-50 rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xl">{typeInfo?.emoji}</span>
|
||||
<div>
|
||||
<p className="font-medium text-secondary-900">{typeInfo?.label}</p>
|
||||
<p className="text-xs text-secondary-500">{data.count} logged</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-semibold text-secondary-900">{data.avgSeverity}/5</p>
|
||||
<p className="text-xs text-secondary-500">avg severity</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Patterns */}
|
||||
{patterns.length > 0 && (
|
||||
<Card>
|
||||
<h3 className="font-semibold text-secondary-900 mb-3 flex items-center">
|
||||
<Calendar className="w-5 h-5 mr-2 text-primary-500" />
|
||||
Patterns Noticed
|
||||
</h3>
|
||||
<p className="text-sm text-secondary-500 mb-3">
|
||||
Days with multiple symptoms logged
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{patterns.map(([date, items]) => (
|
||||
<div key={date} className="p-3 bg-amber-50 border border-amber-100 rounded-lg">
|
||||
<p className="font-medium text-secondary-900">
|
||||
{format(new Date(date), 'EEEE, MMM d')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{items.map((item, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="text-xs px-2 py-0.5 bg-white rounded-full text-secondary-600"
|
||||
>
|
||||
{SYMPTOM_TYPES.find(t => t.type === item.type)?.label} ({item.severity}/5)
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Recent Symptoms */}
|
||||
<section>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-lg font-semibold text-secondary-900">Recent</h2>
|
||||
{symptoms.length > 5 && (
|
||||
<button
|
||||
onClick={() => router.push('/symptoms/history')}
|
||||
className="text-sm text-primary-600 font-medium"
|
||||
>
|
||||
View all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{symptoms.length === 0 ? (
|
||||
<Card variant="outline" className="text-center py-8">
|
||||
<BarChart2 className="w-10 h-10 text-secondary-300 mx-auto mb-3" />
|
||||
<p className="text-secondary-500">No symptoms logged yet</p>
|
||||
<p className="text-sm text-secondary-400 mt-1">
|
||||
Use the form above to track how you're feeling
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{symptoms.slice(0, 5).map((symptom: any) => (
|
||||
<SymptomCard key={symptom.id} symptom={symptom} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</PageContainer>
|
||||
|
||||
{/* Report Modal */}
|
||||
{showReport && (
|
||||
<SymptomReportGenerator
|
||||
symptoms={filteredSymptoms}
|
||||
workspaceId={currentWorkspace.id}
|
||||
timeRange={parseInt(timeRange)}
|
||||
onClose={() => setShowReport(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo } from 'react'
|
||||
import { format } from 'date-fns'
|
||||
import { X, FileText, Download, Share2 } from 'lucide-react'
|
||||
|
||||
import { Button, showToast } from '@/components/ui'
|
||||
|
||||
interface Symptom {
|
||||
id: string
|
||||
type: string
|
||||
customName?: string
|
||||
severity: number
|
||||
notes?: string
|
||||
recordedAt: string
|
||||
durationMinutes?: number
|
||||
triggers?: string
|
||||
medicationTaken?: string
|
||||
reliefNotes?: string
|
||||
}
|
||||
|
||||
interface SymptomReportGeneratorProps {
|
||||
symptoms: Symptom[]
|
||||
workspaceId: string
|
||||
timeRange: number
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const SYMPTOM_LABELS: Record<string, string> = {
|
||||
FATIGUE: 'Fatigue',
|
||||
NAUSEA: 'Nausea',
|
||||
PAIN: 'Pain',
|
||||
APPETITE: 'Appetite Loss',
|
||||
SLEEP: 'Sleep Issues',
|
||||
MOOD: 'Mood Changes',
|
||||
CUSTOM: 'Other',
|
||||
}
|
||||
|
||||
export function SymptomReportGenerator({
|
||||
symptoms,
|
||||
workspaceId,
|
||||
timeRange,
|
||||
onClose
|
||||
}: SymptomReportGeneratorProps) {
|
||||
const [generating, setGenerating] = useState(false)
|
||||
|
||||
const reportData = useMemo(() => {
|
||||
// Group by type
|
||||
const byType: Record<string, Symptom[]> = {}
|
||||
symptoms.forEach(s => {
|
||||
if (!byType[s.type]) byType[s.type] = []
|
||||
byType[s.type].push(s)
|
||||
})
|
||||
|
||||
// Calculate averages
|
||||
const averages = Object.entries(byType).map(([type, items]) => ({
|
||||
type,
|
||||
label: SYMPTOM_LABELS[type] || type,
|
||||
count: items.length,
|
||||
avgSeverity: (items.reduce((sum, s) => sum + s.severity, 0) / items.length).toFixed(1),
|
||||
maxSeverity: Math.max(...items.map(s => s.severity)),
|
||||
}))
|
||||
|
||||
// Sort by frequency
|
||||
averages.sort((a, b) => b.count - a.count)
|
||||
|
||||
// Daily breakdown
|
||||
const byDay: Record<string, Symptom[]> = {}
|
||||
symptoms.forEach(s => {
|
||||
const day = format(new Date(s.recordedAt), 'yyyy-MM-dd')
|
||||
if (!byDay[day]) byDay[day] = []
|
||||
byDay[day].push(s)
|
||||
})
|
||||
|
||||
return { byType, averages, byDay }
|
||||
}, [symptoms])
|
||||
|
||||
const generatePDF = async () => {
|
||||
setGenerating(true)
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/symptoms/report`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
symptoms,
|
||||
timeRange,
|
||||
generatedAt: new Date().toISOString()
|
||||
})
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to generate report')
|
||||
|
||||
const blob = await response.blob()
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `symptom-report-${format(new Date(), 'yyyy-MM-dd')}.pdf`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
window.URL.revokeObjectURL(url)
|
||||
document.body.removeChild(a)
|
||||
|
||||
showToast('Report downloaded', 'success')
|
||||
} catch {
|
||||
showToast('Failed to generate report', 'error')
|
||||
} finally {
|
||||
setGenerating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const copySummary = () => {
|
||||
const summary = `
|
||||
Symptom Summary (Last ${timeRange} Days)
|
||||
Generated: ${format(new Date(), 'MMM d, yyyy')}
|
||||
|
||||
Total Symptoms Logged: ${symptoms.length}
|
||||
|
||||
By Symptom Type:
|
||||
${reportData.averages.map(a =>
|
||||
`- ${a.label}: ${a.count} times (avg severity: ${a.avgSeverity}/5)`
|
||||
).join('\n')}
|
||||
|
||||
Most Common: ${reportData.averages[0]?.label || 'N/A'}
|
||||
Average Severity: ${(symptoms.reduce((s, x) => s + x.severity, 0) / symptoms.length || 0).toFixed(1)}/5
|
||||
`.trim()
|
||||
|
||||
navigator.clipboard.writeText(summary)
|
||||
showToast('Summary copied to clipboard', 'success')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-2xl max-w-md w-full max-h-[90vh] overflow-hidden flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-border">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-5 h-5 text-primary-500" />
|
||||
<h2 className="font-semibold text-secondary-900">Symptom Report</h2>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 hover:bg-secondary-100 rounded-full"
|
||||
>
|
||||
<X className="w-5 h-5 text-secondary-500" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-auto p-4 space-y-4">
|
||||
{/* Summary */}
|
||||
<div className="bg-primary-50 rounded-lg p-4">
|
||||
<h3 className="font-medium text-primary-900 mb-2">Summary</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p className="text-2xl font-bold text-primary-700">{symptoms.length}</p>
|
||||
<p className="text-xs text-primary-600">Total Logged</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold text-primary-700">
|
||||
{(symptoms.reduce((s, x) => s + x.severity, 0) / symptoms.length || 0).toFixed(1)}
|
||||
</p>
|
||||
<p className="text-xs text-primary-600">Avg Severity</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Breakdown */}
|
||||
<div>
|
||||
<h3 className="font-medium text-secondary-900 mb-2">By Symptom Type</h3>
|
||||
<div className="space-y-2">
|
||||
{reportData.averages.map(item => (
|
||||
<div
|
||||
key={item.type}
|
||||
className="flex items-center justify-between p-3 bg-secondary-50 rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-secondary-900">{item.label}</p>
|
||||
<p className="text-xs text-secondary-500">{item.count} occurrences</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-semibold text-secondary-900">{item.avgSeverity}/5</p>
|
||||
<p className="text-xs text-secondary-500">avg</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
<p className="text-xs text-secondary-500 text-center">
|
||||
Share this report with your doctor at your next appointment
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="p-4 border-t border-border space-y-2">
|
||||
<Button
|
||||
onClick={generatePDF}
|
||||
loading={generating}
|
||||
fullWidth
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Download PDF
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={copySummary}
|
||||
fullWidth
|
||||
>
|
||||
<Share2 className="w-4 h-4 mr-2" />
|
||||
Copy Text Summary
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { format, subDays, startOfDay, isSameDay } from 'date-fns'
|
||||
|
||||
interface Symptom {
|
||||
id: string
|
||||
type: string
|
||||
severity: number
|
||||
recordedAt: string
|
||||
durationMinutes?: number
|
||||
triggers?: string
|
||||
medicationTaken?: string
|
||||
}
|
||||
|
||||
interface SymptomTrendChartProps {
|
||||
symptoms: Symptom[]
|
||||
days?: number
|
||||
selectedType?: string | null
|
||||
}
|
||||
|
||||
const SYMPTOM_COLORS: Record<string, string> = {
|
||||
FATIGUE: '#8b5cf6',
|
||||
NAUSEA: '#f59e0b',
|
||||
PAIN: '#ef4444',
|
||||
APPETITE: '#10b981',
|
||||
SLEEP: '#3b82f6',
|
||||
MOOD: '#ec4899',
|
||||
CUSTOM: '#6b7280',
|
||||
}
|
||||
|
||||
const SYMPTOM_EMOJIS: Record<string, string> = {
|
||||
FATIGUE: '😴',
|
||||
NAUSEA: '🤢',
|
||||
PAIN: '😣',
|
||||
APPETITE: '🍽️',
|
||||
SLEEP: '😴',
|
||||
MOOD: '😔',
|
||||
CUSTOM: '📝',
|
||||
}
|
||||
|
||||
export function SymptomTrendChart({ symptoms, days = 7, selectedType }: SymptomTrendChartProps) {
|
||||
// Generate date range
|
||||
const today = startOfDay(new Date())
|
||||
const dates = useMemo(() =>
|
||||
Array.from({ length: days }, (_, i) => subDays(today, days - 1 - i)),
|
||||
[days, today]
|
||||
)
|
||||
|
||||
// Group symptoms by type and date
|
||||
const dataByTypeAndDate = useMemo(() => {
|
||||
const result: Record<string, Record<string, { avgSeverity: number; count: number }>> = {}
|
||||
|
||||
symptoms.forEach(s => {
|
||||
if (selectedType && s.type !== selectedType) return
|
||||
|
||||
const dateKey = format(new Date(s.recordedAt), 'yyyy-MM-dd')
|
||||
if (!result[s.type]) result[s.type] = {}
|
||||
if (!result[s.type][dateKey]) {
|
||||
result[s.type][dateKey] = { avgSeverity: 0, count: 0 }
|
||||
}
|
||||
result[s.type][dateKey].avgSeverity += s.severity
|
||||
result[s.type][dateKey].count++
|
||||
})
|
||||
|
||||
// Calculate averages
|
||||
Object.keys(result).forEach(type => {
|
||||
Object.keys(result[type]).forEach(date => {
|
||||
const data = result[type][date]
|
||||
data.avgSeverity = data.avgSeverity / data.count
|
||||
})
|
||||
})
|
||||
|
||||
return result
|
||||
}, [symptoms, selectedType])
|
||||
|
||||
// Get unique types
|
||||
const types = selectedType ? [selectedType] : Object.keys(dataByTypeAndDate)
|
||||
|
||||
if (symptoms.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-8 text-secondary-500">
|
||||
No symptom data to display
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Chart Area */}
|
||||
<div className="h-48 relative">
|
||||
{/* Grid lines */}
|
||||
<div className="absolute inset-0 flex flex-col justify-between">
|
||||
{[5, 4, 3, 2, 1].map(level => (
|
||||
<div key={level} className="flex items-center">
|
||||
<span className="w-4 text-xs text-secondary-400">{level}</span>
|
||||
<div className="flex-1 border-t border-secondary-100" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Bars */}
|
||||
<div className="absolute inset-0 pl-6 flex items-end gap-1">
|
||||
{dates.map((date, i) => {
|
||||
const dateKey = format(date, 'yyyy-MM-dd')
|
||||
const dayData: Record<string, number> = {}
|
||||
|
||||
types.forEach(type => {
|
||||
if (dataByTypeAndDate[type]?.[dateKey]) {
|
||||
dayData[type] = dataByTypeAndDate[type][dateKey].avgSeverity
|
||||
}
|
||||
})
|
||||
|
||||
const hasData = Object.keys(dayData).length > 0
|
||||
|
||||
return (
|
||||
<div key={i} className="flex-1 flex flex-col items-center">
|
||||
<div className="w-full flex items-end justify-center gap-0.5 h-40">
|
||||
{hasData ? (
|
||||
types.map(type => {
|
||||
const severity = dayData[type]
|
||||
if (!severity) return null
|
||||
const height = (severity / 5) * 100
|
||||
return (
|
||||
<div
|
||||
key={type}
|
||||
className="w-full rounded-t transition-all hover:opacity-80"
|
||||
style={{
|
||||
height: `${height}%`,
|
||||
backgroundColor: SYMPTOM_COLORS[type] || '#6b7280',
|
||||
minHeight: '4px',
|
||||
}}
|
||||
title={`${type}: ${severity.toFixed(1)}/5`}
|
||||
/>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="w-full h-1 bg-secondary-100 rounded" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Date labels */}
|
||||
<div className="flex pl-6">
|
||||
{dates.map((date, i) => (
|
||||
<div key={i} className="flex-1 text-center">
|
||||
<span className="text-xs text-secondary-500">
|
||||
{format(date, days > 14 ? 'd' : 'EEE')}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Legend */}
|
||||
{!selectedType && types.length > 0 && (
|
||||
<div className="flex flex-wrap justify-center gap-3 pt-2 border-t border-border">
|
||||
{types.map(type => (
|
||||
<div key={type} className="flex items-center gap-1">
|
||||
<div
|
||||
className="w-3 h-3 rounded"
|
||||
style={{ backgroundColor: SYMPTOM_COLORS[type] || '#6b7280' }}
|
||||
/>
|
||||
<span className="text-xs text-secondary-600">
|
||||
{SYMPTOM_EMOJIS[type]} {type.charAt(0) + type.slice(1).toLowerCase()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// ============================================
|
||||
// TREATMENT MILESTONE TRACKER
|
||||
// ============================================
|
||||
|
||||
model TreatmentPlan {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String @unique
|
||||
title String // e.g., "Grace's Chemotherapy Plan"
|
||||
totalCycles Int
|
||||
currentCycle Int @default(0)
|
||||
startDate DateTime?
|
||||
estimatedEnd DateTime?
|
||||
status String @default("ACTIVE") // ACTIVE, PAUSED, COMPLETED
|
||||
cycleType String @default("WEEKLY") // WEEKLY, BIWEEKLY, MONTHLY, CUSTOM
|
||||
cycleDays Int @default(7) // Days between cycles
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
milestones TreatmentMilestone[]
|
||||
|
||||
@@index([workspaceId])
|
||||
}
|
||||
|
||||
model TreatmentMilestone {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
cycleNumber Int // Which cycle this milestone represents
|
||||
date DateTime // When it happened (or estimated)
|
||||
status String @default("UPCOMING") // UPCOMING, COMPLETED, SKIPPED
|
||||
notes String? // Personal reflection
|
||||
sideEffects String? // What was experienced
|
||||
celebratedAt DateTime? // When we showed the celebration
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
plan TreatmentPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([planId])
|
||||
@@index([planId, cycleNumber])
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// CAREGIVER COORDINATION
|
||||
// ============================================
|
||||
|
||||
model CareTask {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
title String
|
||||
description String?
|
||||
assignedToId String? // User ID or null for anyone
|
||||
dueAt DateTime?
|
||||
completedAt DateTime?
|
||||
completedById String?
|
||||
priority String @default("MEDIUM") // LOW, MEDIUM, HIGH, URGENT
|
||||
category String @default("GENERAL") // MEDICATION, APPOINTMENT, SYMPTOM, GENERAL
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
assignedTo User? @relation("AssignedTasks", fields: [assignedToId], references: [id])
|
||||
completedBy User? @relation("CompletedTasks", fields: [completedById], references: [id])
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
|
||||
@@index([workspaceId])
|
||||
@@index([workspaceId, assignedToId])
|
||||
@@index([workspaceId, completedAt])
|
||||
}
|
||||
|
||||
model HandoffNote {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
content String
|
||||
category String @default("GENERAL") // GENERAL, SYMPTOM, MEDICATION, MOOD
|
||||
priority String @default("NORMAL") // LOW, NORMAL, HIGH
|
||||
expiresAt DateTime // Auto-expire after shift (e.g., 12 hours)
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
acknowledgedBy String[] // User IDs who've seen it (stored as JSON string)
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
|
||||
@@index([workspaceId])
|
||||
@@index([workspaceId, expiresAt])
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// ENHANCED SYMPTOM TRACKING
|
||||
// ============================================
|
||||
|
||||
// Additional fields for existing Symptom model (add to existing model):
|
||||
// durationMinutes Int? // How long the symptom lasted
|
||||
// triggers String? // Optional triggers (comma-separated)
|
||||
// medicationTaken String? // ID of medication taken for relief
|
||||
// reliefNotes String? // Did it help?
|
||||
|
||||
// ============================================
|
||||
// CALENDAR INTEGRATION
|
||||
// ============================================
|
||||
|
||||
model CalendarFeed {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String
|
||||
token String @unique // Secret token for feed URL
|
||||
includeMeds Boolean @default(false)
|
||||
includeAppointments Boolean @default(true)
|
||||
daysAhead Int @default(90) // How many days to include
|
||||
createdAt DateTime @default(now())
|
||||
lastAccessedAt DateTime?
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([token])
|
||||
@@index([workspaceId])
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
# Treatment Milestone Tracker Implementation
|
||||
|
||||
## Database Schema Changes
|
||||
|
||||
Add to prisma/schema.prisma:
|
||||
|
||||
```prisma
|
||||
model TreatmentPlan {
|
||||
id String @id @default(cuid())
|
||||
workspaceId String @unique
|
||||
title String // e.g., "Grace's Chemotherapy Plan"
|
||||
totalCycles Int
|
||||
currentCycle Int @default(0)
|
||||
startDate DateTime?
|
||||
estimatedEnd DateTime?
|
||||
status String @default("ACTIVE") // ACTIVE, PAUSED, COMPLETED
|
||||
cycleType String @default("WEEKLY") // WEEKLY, BIWEEKLY, MONTHLY, CUSTOM
|
||||
cycleDays Int @default(7) // Days between cycles
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdById String
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
createdBy User @relation(fields: [createdById], references: [id])
|
||||
milestones TreatmentMilestone[]
|
||||
}
|
||||
|
||||
model TreatmentMilestone {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
cycleNumber Int // Which cycle this milestone represents
|
||||
date DateTime // When it happened (or estimated)
|
||||
status String @default("UPCOMING") // UPCOMING, COMPLETED, SKIPPED
|
||||
notes String? // Personal reflection
|
||||
sideEffects String? // What was experienced
|
||||
celebratedAt DateTime? // When we showed the celebration
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
plan TreatmentPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
```
|
||||
|
||||
## API Routes
|
||||
|
||||
### GET /api/workspaces/[id]/treatment-plan
|
||||
Get the treatment plan for a workspace
|
||||
|
||||
### POST /api/workspaces/[id]/treatment-plan
|
||||
Create or update treatment plan
|
||||
|
||||
### POST /api/workspaces/[id]/treatment-plan/milestones/[cycleNumber]/complete
|
||||
Mark a milestone as completed
|
||||
|
||||
### GET /api/workspaces/[id]/treatment-plan/progress
|
||||
Get progress stats
|
||||
|
||||
## Components
|
||||
|
||||
- TreatmentProgress - Main progress widget
|
||||
- MilestoneCelebration - Celebration modal
|
||||
- TreatmentCalendar - Timeline view
|
||||
- CycleDetailView - Individual cycle details
|
||||
@@ -0,0 +1,111 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
|
||||
// POST /api/workspaces/[id]/treatment-plan/complete-cycle
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Get current plan
|
||||
const plan = await prisma.treatmentPlan.findUnique({
|
||||
where: { workspaceId },
|
||||
include: { milestones: true }
|
||||
})
|
||||
|
||||
if (!plan) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No treatment plan found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
if (plan.status !== 'ACTIVE') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Treatment plan is not active' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (plan.currentCycle >= plan.totalCycles) {
|
||||
return NextResponse.json(
|
||||
{ error: 'All cycles already completed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const nextCycle = plan.currentCycle + 1
|
||||
|
||||
// Update milestone
|
||||
const milestone = plan.milestones.find(m => m.cycleNumber === nextCycle)
|
||||
if (milestone) {
|
||||
await prisma.treatmentMilestone.update({
|
||||
where: { id: milestone.id },
|
||||
data: {
|
||||
status: 'COMPLETED',
|
||||
date: new Date()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Update plan
|
||||
const isComplete = nextCycle >= plan.totalCycles
|
||||
const updatedPlan = await prisma.treatmentPlan.update({
|
||||
where: { workspaceId },
|
||||
data: {
|
||||
currentCycle: nextCycle,
|
||||
status: isComplete ? 'COMPLETED' : 'ACTIVE'
|
||||
},
|
||||
include: {
|
||||
milestones: {
|
||||
orderBy: { cycleNumber: 'asc' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'COMPLETE_CYCLE',
|
||||
entityType: 'TREATMENT_PLAN',
|
||||
entityId: plan.id,
|
||||
details: {
|
||||
cycleCompleted: nextCycle,
|
||||
totalCycles: plan.totalCycles,
|
||||
isComplete
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
plan: updatedPlan,
|
||||
milestone: milestone,
|
||||
celebration: {
|
||||
cycleNumber: nextCycle,
|
||||
isHalfway: nextCycle === Math.floor(plan.totalCycles / 2),
|
||||
isFinal: isComplete
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to complete cycle:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to complete cycle' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/db/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
import { canAccessWorkspace } from '@/lib/db/workspace-access'
|
||||
import { addDays } from 'date-fns'
|
||||
|
||||
// GET /api/workspaces/[id]/treatment-plan
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const plan = await prisma.treatmentPlan.findUnique({
|
||||
where: { workspaceId },
|
||||
include: {
|
||||
milestones: {
|
||||
orderBy: { cycleNumber: 'asc' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (!plan) {
|
||||
return NextResponse.json({ plan: null })
|
||||
}
|
||||
|
||||
return NextResponse.json({ plan })
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch treatment plan:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch treatment plan' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/workspaces/[id]/treatment-plan
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const workspaceId = params.id
|
||||
const access = await canAccessWorkspace(user.id, workspaceId)
|
||||
if (!access || access.role === 'VIEWER') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { title, totalCycles, startDate, cycleType, cycleDays } = body
|
||||
|
||||
// Validate required fields
|
||||
if (!title || !totalCycles || !startDate) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Missing required fields' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Calculate estimated end date
|
||||
const start = new Date(startDate)
|
||||
const estimatedEnd = addDays(start, cycleDays * totalCycles)
|
||||
|
||||
// Create or update treatment plan
|
||||
const plan = await prisma.treatmentPlan.upsert({
|
||||
where: { workspaceId },
|
||||
create: {
|
||||
workspaceId,
|
||||
title,
|
||||
totalCycles,
|
||||
startDate: start,
|
||||
estimatedEnd,
|
||||
cycleType,
|
||||
cycleDays,
|
||||
createdById: user.id,
|
||||
milestones: {
|
||||
create: Array.from({ length: totalCycles }, (_, i) => ({
|
||||
cycleNumber: i + 1,
|
||||
date: addDays(start, cycleDays * i),
|
||||
status: i === 0 ? 'UPCOMING' : 'UPCOMING'
|
||||
}))
|
||||
}
|
||||
},
|
||||
update: {
|
||||
title,
|
||||
totalCycles,
|
||||
startDate: start,
|
||||
estimatedEnd,
|
||||
cycleType,
|
||||
cycleDays,
|
||||
},
|
||||
include: {
|
||||
milestones: {
|
||||
orderBy: { cycleNumber: 'asc' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Log audit
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
workspaceId,
|
||||
userId: user.id,
|
||||
action: 'CREATE',
|
||||
entityType: 'TREATMENT_PLAN',
|
||||
entityId: plan.id,
|
||||
details: { title, totalCycles }
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ plan })
|
||||
} catch (error) {
|
||||
console.error('Failed to create treatment plan:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create treatment plan' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ChevronLeft } from 'lucide-react'
|
||||
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { TreatmentPlanForm } from '@/components/treatment/TreatmentPlanForm'
|
||||
import { useApp } from '../provider'
|
||||
|
||||
export default function NewTreatmentPlanPage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace } = useApp()
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="Create Treatment Plan"
|
||||
leftAction={{
|
||||
icon: <ChevronLeft className="w-6 h-6" />,
|
||||
label: 'Back',
|
||||
onClick: () => router.push('/treatment')
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4">
|
||||
<div className="mb-6">
|
||||
<p className="text-secondary-500">
|
||||
Set up your treatment schedule to track progress and celebrate milestones.
|
||||
</p>
|
||||
</div>
|
||||
<TreatmentPlanForm workspaceId={currentWorkspace.id} />
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Plus, Target, ChevronLeft } from 'lucide-react'
|
||||
|
||||
import { Card, LoadingState, Button } from '@/components/ui'
|
||||
import { Header, PageContainer } from '@/components/layout/header'
|
||||
import { TreatmentProgress } from '@/components/treatment/TreatmentProgress'
|
||||
import { useApp } from '../provider'
|
||||
|
||||
export default function TreatmentPage() {
|
||||
const router = useRouter()
|
||||
const { currentWorkspace } = useApp()
|
||||
const [plan, setPlan] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const fetchPlan = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${currentWorkspace.id}/treatment-plan`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setPlan(data.plan)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch plan:', err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchPlan()
|
||||
}, [currentWorkspace.id])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<>
|
||||
<Header title="Treatment Plan" />
|
||||
<PageContainer>
|
||||
<LoadingState message="Loading treatment plan..." />
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header
|
||||
title="Treatment Plan"
|
||||
leftAction={{
|
||||
icon: <ChevronLeft className="w-6 h-6" />,
|
||||
label: 'Back',
|
||||
onClick: () => router.push('/today')
|
||||
}}
|
||||
/>
|
||||
<PageContainer className="pt-4 space-y-6">
|
||||
{!plan ? (
|
||||
<Card variant="outline" className="text-center py-12">
|
||||
<div className="w-16 h-16 rounded-full bg-primary-100 flex items-center justify-center mx-auto mb-4">
|
||||
<Target className="w-8 h-8 text-primary-600" />
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold text-secondary-900 mb-2">
|
||||
No Treatment Plan Yet
|
||||
</h2>
|
||||
<p className="text-secondary-500 mb-6 max-w-xs mx-auto">
|
||||
Create a treatment plan to track your progress through chemotherapy and celebrate milestones.
|
||||
</p>
|
||||
{currentWorkspace.role !== 'VIEWER' && (
|
||||
<Button href="/treatment/new">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Create Treatment Plan
|
||||
</Button>
|
||||
)}
|
||||
</Card>
|
||||
) : (
|
||||
<TreatmentProgress
|
||||
plan={plan}
|
||||
workspaceId={currentWorkspace.id}
|
||||
onUpdate={fetchPlan}
|
||||
/>
|
||||
)}
|
||||
</PageContainer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Calendar, Clock, Target } from 'lucide-react'
|
||||
|
||||
import { Card, Button, showToast } from '@/components/ui'
|
||||
|
||||
interface TreatmentPlanFormProps {
|
||||
workspaceId: string
|
||||
initialData?: {
|
||||
title: string
|
||||
totalCycles: number
|
||||
startDate: string
|
||||
cycleType: string
|
||||
cycleDays: number
|
||||
}
|
||||
}
|
||||
|
||||
const CYCLE_TYPES = [
|
||||
{ value: 'WEEKLY', label: 'Weekly', days: 7 },
|
||||
{ value: 'BIWEEKLY', label: 'Every 2 weeks', days: 14 },
|
||||
{ value: 'MONTHLY', label: 'Monthly', days: 30 },
|
||||
{ value: 'CUSTOM', label: 'Custom', days: 0 },
|
||||
]
|
||||
|
||||
export function TreatmentPlanForm({ workspaceId, initialData }: TreatmentPlanFormProps) {
|
||||
const router = useRouter()
|
||||
const [title, setTitle] = useState(initialData?.title || '')
|
||||
const [totalCycles, setTotalCycles] = useState(initialData?.totalCycles || 12)
|
||||
const [startDate, setStartDate] = useState(initialData?.startDate || '')
|
||||
const [cycleType, setCycleType] = useState(initialData?.cycleType || 'WEEKLY')
|
||||
const [customDays, setCustomDays] = useState(initialData?.cycleDays || 14)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const selectedCycleType = CYCLE_TYPES.find(t => t.value === cycleType)
|
||||
const cycleDays = cycleType === 'CUSTOM' ? customDays : (selectedCycleType?.days || 7)
|
||||
|
||||
// Calculate estimated end date
|
||||
const estimatedEndDate = startDate
|
||||
? new Date(new Date(startDate).getTime() + (cycleDays * totalCycles * 24 * 60 * 60 * 1000))
|
||||
: null
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!title.trim()) {
|
||||
showToast('Please enter a treatment name', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (!startDate) {
|
||||
showToast('Please select a start date', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/treatment-plan`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
totalCycles,
|
||||
startDate,
|
||||
cycleType,
|
||||
cycleDays,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to create plan')
|
||||
|
||||
showToast('Treatment plan created!', 'success')
|
||||
router.push('/treatment')
|
||||
} catch {
|
||||
showToast('Failed to create plan', 'error')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Treatment Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Treatment Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="e.g., Grace's Chemotherapy Plan"
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Total Cycles */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<Target className="w-4 h-4 inline mr-1" />
|
||||
Total Cycles/Sessions
|
||||
</label>
|
||||
<div className="flex items-center gap-4">
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="50"
|
||||
value={totalCycles}
|
||||
onChange={(e) => setTotalCycles(parseInt(e.target.value))}
|
||||
className="flex-1"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="50"
|
||||
value={totalCycles}
|
||||
onChange={(e) => setTotalCycles(parseInt(e.target.value) || 1)}
|
||||
className="w-20 px-3 py-2 border border-border rounded-lg text-center"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-secondary-500 mt-1">
|
||||
Number of chemo sessions or treatment cycles
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Start Date */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<Calendar className="w-4 h-4 inline mr-1" />
|
||||
Start Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Cycle Frequency */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
<Clock className="w-4 h-4 inline mr-1" />
|
||||
How Often?
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{CYCLE_TYPES.map((type) => (
|
||||
<button
|
||||
key={type.value}
|
||||
type="button"
|
||||
onClick={() => setCycleType(type.value)}
|
||||
className={`p-3 rounded-lg border-2 text-left transition-all ${
|
||||
cycleType === type.value
|
||||
? 'border-primary-500 bg-primary-50'
|
||||
: 'border-border hover:border-secondary-300'
|
||||
}`}
|
||||
>
|
||||
<span className="font-medium text-secondary-900">{type.label}</span>
|
||||
{type.value !== 'CUSTOM' && (
|
||||
<span className="text-xs text-secondary-500 block">
|
||||
Every {type.days} days
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Custom Days Input */}
|
||||
{cycleType === 'CUSTOM' && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-secondary-700 mb-2">
|
||||
Days Between Cycles
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="90"
|
||||
value={customDays}
|
||||
onChange={(e) => setCustomDays(parseInt(e.target.value) || 1)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-base focus:outline-none focus:ring-2 focus:ring-primary-200 focus:border-primary-500"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Estimated End Date */}
|
||||
{estimatedEndDate && (
|
||||
<div className="p-4 bg-primary-50 rounded-lg">
|
||||
<p className="text-sm text-secondary-600">
|
||||
Estimated completion:
|
||||
</p>
|
||||
<p className="font-semibold text-primary-700">
|
||||
{estimatedEndDate.toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
href="/treatment"
|
||||
fullWidth
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={saving}
|
||||
fullWidth
|
||||
>
|
||||
Create Plan
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Trophy, Calendar, TrendingUp, ChevronRight, Flag, PartyPopper } from 'lucide-react'
|
||||
import { format, addDays, differenceInDays } from 'date-fns'
|
||||
|
||||
import { Card, Button } from '@/components/ui'
|
||||
import { showToast } from '@/components/ui'
|
||||
|
||||
interface Milestone {
|
||||
id: string
|
||||
cycleNumber: number
|
||||
date: string
|
||||
status: 'UPCOMING' | 'COMPLETED' | 'SKIPPED'
|
||||
notes?: string
|
||||
celebratedAt?: string
|
||||
}
|
||||
|
||||
interface TreatmentPlan {
|
||||
id: string
|
||||
title: string
|
||||
totalCycles: number
|
||||
currentCycle: number
|
||||
startDate: string | null
|
||||
estimatedEnd: string | null
|
||||
status: 'ACTIVE' | 'PAUSED' | 'COMPLETED'
|
||||
cycleType: string
|
||||
cycleDays: number
|
||||
milestones: Milestone[]
|
||||
}
|
||||
|
||||
interface TreatmentProgressProps {
|
||||
plan: TreatmentPlan | null
|
||||
workspaceId: string
|
||||
onUpdate?: () => void
|
||||
}
|
||||
|
||||
export function TreatmentProgress({ plan, workspaceId, onUpdate }: TreatmentProgressProps) {
|
||||
const [showCelebration, setShowCelebration] = useState(false)
|
||||
const [celebratingMilestone, setCelebratingMilestone] = useState<Milestone | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Check for uncelebrated completed milestones
|
||||
if (plan?.milestones) {
|
||||
const uncelebrated = plan.milestones.find(
|
||||
m => m.status === 'COMPLETED' && !m.celebratedAt
|
||||
)
|
||||
if (uncelebrated) {
|
||||
setCelebratingMilestone(uncelebrated)
|
||||
setShowCelebration(true)
|
||||
// Mark as celebrated
|
||||
markCelebrated(uncelebrated.id)
|
||||
}
|
||||
}
|
||||
}, [plan])
|
||||
|
||||
const markCelebrated = async (milestoneId: string) => {
|
||||
try {
|
||||
await fetch(`/api/workspaces/${workspaceId}/treatment-plan/milestones/${milestoneId}/celebrate`, {
|
||||
method: 'POST'
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to mark celebration:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCompleteCycle = async () => {
|
||||
if (!plan) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/workspaces/${workspaceId}/treatment-plan/complete-cycle`, {
|
||||
method: 'POST'
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Failed to complete cycle')
|
||||
|
||||
showToast('Cycle completed! Great job!', 'success')
|
||||
onUpdate?.()
|
||||
} catch {
|
||||
showToast('Failed to complete cycle', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
if (!plan) {
|
||||
return (
|
||||
<Card variant="outline" className="text-center py-8">
|
||||
<Trophy className="w-12 h-12 text-secondary-300 mx-auto mb-3" />
|
||||
<h3 className="font-semibold text-secondary-900 mb-1">No Treatment Plan</h3>
|
||||
<p className="text-secondary-500 text-sm mb-4">
|
||||
Set up a treatment plan to track your progress
|
||||
</p>
|
||||
<Button href={`/treatment/new`}>Create Plan</Button>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const progress = (plan.currentCycle / plan.totalCycles) * 100
|
||||
const daysRemaining = plan.estimatedEnd
|
||||
? differenceInDays(new Date(plan.estimatedEnd), new Date())
|
||||
: null
|
||||
|
||||
const milestones = plan.milestones || []
|
||||
const completedCount = milestones.filter(m => m.status === 'COMPLETED').length
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card className="overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="bg-gradient-to-r from-primary-500 to-primary-600 text-white p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg">{plan.title}</h3>
|
||||
<p className="text-primary-100 text-sm">
|
||||
Cycle {plan.currentCycle} of {plan.totalCycles}
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-14 h-14 rounded-full bg-white/20 flex items-center justify-center">
|
||||
<Trophy className="w-7 h-7" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="p-4">
|
||||
<div className="flex items-center justify-between text-sm mb-2">
|
||||
<span className="text-secondary-600">{completedCount} completed</span>
|
||||
<span className="font-semibold text-primary-600">{Math.round(progress)}%</span>
|
||||
</div>
|
||||
<div className="h-3 bg-secondary-100 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-gradient-to-r from-primary-500 to-primary-400 transition-all duration-500"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-3 gap-4 mt-4 pt-4 border-t border-border">
|
||||
<div className="text-center">
|
||||
<p className="text-2xl font-bold text-secondary-900">{plan.currentCycle}</p>
|
||||
<p className="text-xs text-secondary-500">Current</p>
|
||||
</div>
|
||||
<div className="text-center border-x border-border">
|
||||
<p className="text-2xl font-bold text-secondary-900">{plan.totalCycles - plan.currentCycle}</p>
|
||||
<p className="text-xs text-secondary-500">Remaining</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="text-2xl font-bold text-secondary-900">
|
||||
{daysRemaining !== null ? Math.max(0, daysRemaining) : '?'}
|
||||
</p>
|
||||
<p className="text-xs text-secondary-500">Days Left</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="px-4 pb-4 space-y-2">
|
||||
{plan.status === 'ACTIVE' && plan.currentCycle < plan.totalCycles && (
|
||||
<Button
|
||||
onClick={handleCompleteCycle}
|
||||
fullWidth
|
||||
className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700"
|
||||
>
|
||||
<PartyPopper className="w-4 h-4 mr-2" />
|
||||
Complete Cycle {plan.currentCycle + 1}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="secondary"
|
||||
href="/treatment/details"
|
||||
fullWidth
|
||||
>
|
||||
View Details
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Milestone Preview */}
|
||||
{milestones.length > 0 && (
|
||||
<Card className="mt-4">
|
||||
<h4 className="font-semibold text-secondary-900 mb-3">Upcoming Milestones</h4>
|
||||
<div className="space-y-2">
|
||||
{milestones
|
||||
.filter(m => m.status === 'UPCOMING')
|
||||
.slice(0, 3)
|
||||
.map(milestone => (
|
||||
<div
|
||||
key={milestone.id}
|
||||
className="flex items-center gap-3 p-2 rounded-lg bg-secondary-50"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0">
|
||||
<Flag className="w-4 h-4 text-primary-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-secondary-900">
|
||||
Cycle {milestone.cycleNumber}
|
||||
</p>
|
||||
<p className="text-xs text-secondary-500">
|
||||
{format(new Date(milestone.date), 'MMM d, yyyy')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Celebration Modal */}
|
||||
{showCelebration && celebratingMilestone && (
|
||||
<MilestoneCelebration
|
||||
milestone={celebratingMilestone}
|
||||
plan={plan}
|
||||
onClose={() => setShowCelebration(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface MilestoneCelebrationProps {
|
||||
milestone: Milestone
|
||||
plan: TreatmentPlan
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
function MilestoneCelebration({ milestone, plan, onClose }: MilestoneCelebrationProps) {
|
||||
const messages = [
|
||||
"You're doing amazing!",
|
||||
"One step closer to the finish line!",
|
||||
"Your strength is inspiring!",
|
||||
"Keep going, you've got this!",
|
||||
"Another milestone conquered!"
|
||||
]
|
||||
|
||||
const randomMessage = messages[Math.floor(Math.random() * messages.length)]
|
||||
|
||||
const isHalfway = milestone.cycleNumber === Math.floor(plan.totalCycles / 2)
|
||||
const isFinal = milestone.cycleNumber === plan.totalCycles
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-2xl p-6 max-w-sm w-full text-center animate-in fade-in zoom-in duration-300">
|
||||
<div className="w-20 h-20 rounded-full bg-gradient-to-r from-yellow-400 to-orange-500 flex items-center justify-center mx-auto mb-4 animate-bounce">
|
||||
<PartyPopper className="w-10 h-10 text-white" />
|
||||
</div>
|
||||
|
||||
<h2 className="text-2xl font-bold text-secondary-900 mb-2">
|
||||
{isFinal ? '🎉 Treatment Complete!' : isHalfway ? '🌟 Halfway There!' : 'Milestone Reached!'}
|
||||
</h2>
|
||||
|
||||
<p className="text-secondary-600 mb-2">
|
||||
Cycle {milestone.cycleNumber} of {plan.totalCycles} completed!
|
||||
</p>
|
||||
|
||||
<p className="text-primary-600 font-medium mb-6">
|
||||
{isFinal ? "You've done it! What an incredible journey." : randomMessage}
|
||||
</p>
|
||||
|
||||
<Button onClick={onClose} fullWidth>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user