AI Newsletter Digest improvements: fixed QP soft line break decoding, URL extraction, and content cleaning

This commit is contained in:
Krilly
2026-03-04 13:29:22 +00:00
parent 29a98137a7
commit 57dd294675
13706 changed files with 2114953 additions and 237629 deletions

View File

@@ -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)}
/>
)}
</>
)
}

View File

@@ -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>
)
}

View File

@@ -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>
)
}