feat: implement CV via OpenAI for forms scanning, generate DB migration, fixes, etc.

This commit is contained in:
2025-12-02 14:59:35 +01:00
parent a140df35c5
commit c0c01d92b2
26 changed files with 4871 additions and 110 deletions

View File

@@ -3,6 +3,7 @@
import React, { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { format, parseISO } from 'date-fns'
import {
Loader2,
LogOut,
@@ -148,7 +149,7 @@ export default function CaregiverDashboardPage() {
// Create order dialog
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [newOrderDate, setNewOrderDate] = useState(() => new Date().toISOString().split('T')[0])
const [newOrderDate, setNewOrderDate] = useState(() => format(new Date(), 'yyyy-MM-dd'))
const [newOrderMealType, setNewOrderMealType] = useState<'breakfast' | 'lunch' | 'dinner'>('breakfast')
const [creating, setCreating] = useState(false)
@@ -374,12 +375,7 @@ export default function CaregiverDashboardPage() {
}
const formatDate = (dateStr: string) => {
const date = new Date(dateStr)
return date.toLocaleDateString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
})
return format(parseISO(dateStr), 'EEE, MMM d')
}
if (loading) {

View File

@@ -3,6 +3,7 @@
import React, { useState, useEffect, useCallback } from 'react'
import { useRouter, useParams } from 'next/navigation'
import Link from 'next/link'
import { formatISO, format, parseISO } from 'date-fns'
import {
ArrowLeft,
Loader2,
@@ -17,6 +18,11 @@ import {
Users,
ChefHat,
ClipboardList,
Upload,
Trash2,
ImageIcon,
Sparkles,
Camera,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -51,6 +57,16 @@ import {
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { cn } from '@/lib/utils'
interface Resident {
@@ -64,11 +80,20 @@ interface Resident {
notes?: string
}
interface MediaFile {
id: number
url: string
alt?: string
filename?: string
thumbnailURL?: string
}
interface Meal {
id: number
resident: Resident | number
mealType: 'breakfast' | 'lunch' | 'dinner'
status: 'pending' | 'preparing' | 'prepared'
formImage?: MediaFile | number
breakfast?: BreakfastOptions
lunch?: LunchOptions
dinner?: DinnerOptions
@@ -248,6 +273,20 @@ export default function OrderDetailPage() {
const [dinner, setDinner] = useState<DinnerOptions>(defaultDinner)
const [savingMeal, setSavingMeal] = useState(false)
// Image upload state
const [formImageFile, setFormImageFile] = useState<File | null>(null)
const [formImagePreview, setFormImagePreview] = useState<string | null>(null)
const [formImageId, setFormImageId] = useState<number | null>(null)
const [existingFormImage, setExistingFormImage] = useState<MediaFile | null>(null)
const [uploadingImage, setUploadingImage] = useState(false)
const [analyzingImage, setAnalyzingImage] = useState(false)
const [analysisError, setAnalysisError] = useState<string | null>(null)
// Delete confirmation state
const [mealToDelete, setMealToDelete] = useState<number | null>(null)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [deletingMeal, setDeletingMeal] = useState(false)
const fetchData = useCallback(async () => {
setLoading(true)
try {
@@ -335,6 +374,13 @@ export default function OrderDetailPage() {
if (existingMeal.breakfast) setBreakfast(existingMeal.breakfast)
if (existingMeal.lunch) setLunch(existingMeal.lunch)
if (existingMeal.dinner) setDinner(existingMeal.dinner)
// Load existing form image
if (existingMeal.formImage && typeof existingMeal.formImage === 'object') {
setExistingFormImage(existingMeal.formImage)
setFormImageId(existingMeal.formImage.id)
} else if (typeof existingMeal.formImage === 'number') {
setFormImageId(existingMeal.formImage)
}
} else {
// Reset to defaults
setBreakfast(defaultBreakfast)
@@ -349,6 +395,144 @@ export default function OrderDetailPage() {
setShowMealForm(false)
setSelectedResident(null)
setEditingMeal(null)
// Reset image state
setFormImageFile(null)
setFormImagePreview(null)
setFormImageId(null)
setExistingFormImage(null)
setAnalysisError(null)
}
const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
setFormImageFile(file)
setExistingFormImage(null)
setAnalysisError(null)
// Create preview
const reader = new FileReader()
reader.onload = (event) => {
setFormImagePreview(event.target?.result as string)
}
reader.readAsDataURL(file)
}
const handleRemoveImage = () => {
setFormImageFile(null)
setFormImagePreview(null)
setFormImageId(null)
setExistingFormImage(null)
setAnalysisError(null)
}
const handleUploadImage = async (): Promise<number | null> => {
if (!formImageFile) return formImageId
setUploadingImage(true)
try {
const formData = new FormData()
formData.append('file', formImageFile)
formData.append('alt', `Meal order form for ${selectedResident?.name}`)
const res = await fetch('/api/media', {
method: 'POST',
body: formData,
credentials: 'include',
})
if (res.ok) {
const data = await res.json()
setFormImageId(data.doc.id)
return data.doc.id
} else {
console.error('Failed to upload image')
return null
}
} catch (err) {
console.error('Error uploading image:', err)
return null
} finally {
setUploadingImage(false)
}
}
const handleAnalyzeImage = async () => {
if (!formImagePreview && !existingFormImage) return
setAnalyzingImage(true)
setAnalysisError(null)
try {
const imageData: { imageBase64?: string; imageUrl?: string } = {}
if (formImagePreview) {
// Extract base64 data from the data URL
const base64Match = formImagePreview.match(/^data:image\/[^;]+;base64,(.+)$/)
if (base64Match) {
imageData.imageBase64 = base64Match[1]
}
} else if (existingFormImage?.url) {
imageData.imageUrl = existingFormImage.url
}
const res = await fetch('/api/analyze-form', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...imageData,
mealType: order?.mealType,
}),
credentials: 'include',
})
if (res.ok) {
const analysis = await res.json()
// Apply the analysis results to the form
if (analysis.confidence > 50) {
if (order?.mealType === 'breakfast' && analysis.breakfast) {
setBreakfast((prev) => ({
...prev,
...analysis.breakfast,
bread: { ...prev.bread, ...analysis.breakfast?.bread },
preparation: { ...prev.preparation, ...analysis.breakfast?.preparation },
spreads: { ...prev.spreads, ...analysis.breakfast?.spreads },
beverages: { ...prev.beverages, ...analysis.breakfast?.beverages },
additions: { ...prev.additions, ...analysis.breakfast?.additions },
}))
} else if (order?.mealType === 'lunch' && analysis.lunch) {
setLunch((prev) => ({
...prev,
...analysis.lunch,
specialPreparations: { ...prev.specialPreparations, ...analysis.lunch?.specialPreparations },
restrictions: { ...prev.restrictions, ...analysis.lunch?.restrictions },
}))
} else if (order?.mealType === 'dinner' && analysis.dinner) {
setDinner((prev) => ({
...prev,
...analysis.dinner,
bread: { ...prev.bread, ...analysis.dinner?.bread },
preparation: { ...prev.preparation, ...analysis.dinner?.preparation },
spreads: { ...prev.spreads, ...analysis.dinner?.spreads },
beverages: { ...prev.beverages, ...analysis.dinner?.beverages },
additions: { ...prev.additions, ...analysis.dinner?.additions },
}))
}
} else {
setAnalysisError(`Low confidence (${analysis.confidence}%). Please check the options manually.`)
}
} else {
const error = await res.json()
setAnalysisError(error.error || 'Failed to analyze image')
}
} catch (err) {
console.error('Error analyzing image:', err)
setAnalysisError('Failed to analyze the form image')
} finally {
setAnalyzingImage(false)
}
}
const handleSaveMeal = async () => {
@@ -356,12 +540,19 @@ export default function OrderDetailPage() {
setSavingMeal(true)
try {
// Upload image first if there's a new one
let imageId = formImageId
if (formImageFile) {
imageId = await handleUploadImage()
}
const mealData: Record<string, unknown> = {
order: order.id,
resident: selectedResident.id,
date: order.date,
mealType: order.mealType,
status: 'pending',
formImage: imageId || undefined,
}
if (order.mealType === 'breakfast') {
@@ -414,10 +605,16 @@ export default function OrderDetailPage() {
}
const handleDeleteMeal = async (mealId: number) => {
if (!order || !confirm('Are you sure you want to remove this meal?')) return
setMealToDelete(mealId)
setShowDeleteDialog(true)
}
const confirmDeleteMeal = async () => {
if (!order || !mealToDelete) return
setDeletingMeal(true)
try {
const res = await fetch(`/api/meals/${mealId}`, {
const res = await fetch(`/api/meals/${mealToDelete}`, {
method: 'DELETE',
credentials: 'include',
})
@@ -435,6 +632,10 @@ export default function OrderDetailPage() {
}
} catch (err) {
console.error('Error deleting meal:', err)
} finally {
setDeletingMeal(false)
setShowDeleteDialog(false)
setMealToDelete(null)
}
}
@@ -448,7 +649,7 @@ export default function OrderDetailPage() {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'submitted',
submittedAt: new Date().toISOString(),
submittedAt: formatISO(new Date()),
}),
credentials: 'include',
})
@@ -545,7 +746,9 @@ export default function OrderDetailPage() {
</Button>
<div>
<h1 className="text-xl font-semibold">{order.title}</h1>
<p className="text-sm text-muted-foreground">{order.date}</p>
<p className="text-sm text-muted-foreground">
{format(parseISO(order.date), 'EEEE, MMM d, yyyy')}
</p>
</div>
</div>
<div className="flex items-center gap-2">
@@ -786,6 +989,115 @@ export default function OrderDetailPage() {
</SheetHeader>
<div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
{/* Image Upload Section */}
{isDraft && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-semibold flex items-center gap-2">
<Camera className="h-4 w-4" />
Paper Form Image
</h3>
{(formImagePreview || existingFormImage) && (
<Button
variant="outline"
size="sm"
onClick={handleAnalyzeImage}
disabled={analyzingImage}
>
{analyzingImage ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Analyzing...
</>
) : (
<>
<Sparkles className="mr-2 h-4 w-4" />
Auto-fill from Image
</>
)}
</Button>
)}
</div>
{formImagePreview || existingFormImage ? (
<div className="relative">
<div className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border bg-muted">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={formImagePreview || existingFormImage?.url}
alt="Meal order form"
className="h-full w-full object-contain"
/>
</div>
<Button
variant="destructive"
size="icon"
className="absolute top-2 right-2"
onClick={handleRemoveImage}
>
<Trash2 className="h-4 w-4" />
</Button>
<div className="mt-2 text-sm text-muted-foreground text-center">
{formImageFile?.name || existingFormImage?.filename || 'Uploaded image'}
</div>
</div>
) : (
<label className="flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
<div className="p-3 rounded-full bg-muted">
<Upload className="h-6 w-6 text-muted-foreground" />
</div>
<div className="text-center">
<span className="text-sm font-medium">Upload paper form photo</span>
<p className="text-xs text-muted-foreground mt-1">
Take a photo of the paper meal order form to auto-fill options
</p>
</div>
<input
type="file"
accept="image/*"
capture="environment"
className="hidden"
onChange={handleImageSelect}
/>
</label>
)}
{analysisError && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{analysisError}</AlertDescription>
</Alert>
)}
{uploadingImage && (
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Uploading image...
</div>
)}
</div>
)}
{/* Show existing image in view mode */}
{!isDraft && existingFormImage && (
<div className="space-y-3">
<h3 className="font-semibold flex items-center gap-2">
<ImageIcon className="h-4 w-4" />
Paper Form Image
</h3>
<div className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border bg-muted">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={existingFormImage.url}
alt="Meal order form"
className="h-full w-full object-contain"
/>
</div>
</div>
)}
<Separator />
{(selectedResident?.aversions || selectedResident?.notes || selectedResident?.highCaloric) && (
<Alert>
<AlertTriangle className="h-4 w-4" />
@@ -1123,6 +1435,35 @@ export default function OrderDetailPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete Meal Confirmation Dialog */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove Meal</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to remove this meal? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deletingMeal}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={confirmDeleteMeal}
disabled={deletingMeal}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deletingMeal ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Removing...
</>
) : (
'Remove'
)}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}

View File

@@ -3,6 +3,7 @@
import React, { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { format } from 'date-fns'
import {
ArrowLeft,
Loader2,
@@ -176,7 +177,7 @@ function NewOrderContent() {
const [residents, setResidents] = useState<Resident[]>([])
const [selectedResident, setSelectedResident] = useState<Resident | null>(null)
const [mealType, setMealType] = useState<MealType | null>(initialMealType)
const [date, setDate] = useState(() => new Date().toISOString().split('T')[0])
const [date, setDate] = useState(() => format(new Date(), 'yyyy-MM-dd'))
const [breakfast, setBreakfast] = useState<BreakfastOptions>(defaultBreakfast)
const [lunch, setLunch] = useState<LunchOptions>(defaultLunch)
const [dinner, setDinner] = useState<DinnerOptions>(defaultDinner)

View File

@@ -3,6 +3,7 @@
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { format, parseISO } from 'date-fns'
import { ArrowLeft, Plus, Loader2, Send, Eye, Pencil, Check, ChefHat } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -40,7 +41,7 @@ export default function OrdersListPage() {
const router = useRouter()
const [orders, setOrders] = useState<MealOrder[]>([])
const [loading, setLoading] = useState(true)
const [dateFilter, setDateFilter] = useState(() => new Date().toISOString().split('T')[0])
const [dateFilter, setDateFilter] = useState(() => format(new Date(), 'yyyy-MM-dd'))
const [statusFilter, setStatusFilter] = useState<string>('all')
useEffect(() => {
@@ -254,7 +255,7 @@ export default function OrdersListPage() {
<TableCell className="font-medium">
{getMealTypeLabel(order.mealType)}
</TableCell>
<TableCell>{order.date}</TableCell>
<TableCell>{format(parseISO(order.date), 'MMM d, yyyy')}</TableCell>
<TableCell>{order.mealCount} residents</TableCell>
<TableCell>{getStatusBadge(order.status)}</TableCell>
<TableCell className="text-right">

View File

@@ -3,7 +3,7 @@
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Search, Loader2, Plus } from 'lucide-react'
import { ArrowLeft, Search, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
@@ -100,44 +100,38 @@ export default function ResidentsListPage() {
</CardContent>
</Card>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{filteredResidents.map((resident) => (
<Card key={resident.id}>
<CardContent className="p-4">
<div className="font-semibold text-lg">{resident.name}</div>
<div className="flex flex-wrap gap-2 text-sm text-muted-foreground mt-1">
<CardContent className="px-3 py-2">
<div className="flex items-center justify-between gap-2">
<div className="font-medium">{resident.name}</div>
{resident.highCaloric && (
<Badge variant="secondary" className="bg-yellow-100 text-yellow-800 text-xs px-1.5 py-0">
High Cal
</Badge>
)}
</div>
<div className="flex flex-wrap gap-x-2 text-xs text-muted-foreground">
<span>Room {resident.room}</span>
{resident.table && <span>Table {resident.table}</span>}
{resident.station && <span>{resident.station}</span>}
{resident.table && <span> Table {resident.table}</span>}
{resident.station && <span> {resident.station}</span>}
</div>
{resident.highCaloric && (
<Badge variant="secondary" className="mt-3 bg-yellow-100 text-yellow-800">
High Caloric
</Badge>
)}
{(resident.aversions || resident.notes) && (
<div className="mt-3 text-sm text-muted-foreground space-y-1">
<div className="mt-1 text-xs text-muted-foreground">
{resident.aversions && (
<div>
<div className="truncate">
<span className="font-medium">Aversions:</span> {resident.aversions}
</div>
)}
{resident.notes && (
<div>
<div className="truncate">
<span className="font-medium">Notes:</span> {resident.notes}
</div>
)}
</div>
)}
<Button asChild className="w-full mt-4">
<Link href={`/caregiver/orders/new?resident=${resident.id}`}>
<Plus className="mr-2 h-4 w-4" />
Create Order
</Link>
</Button>
</CardContent>
</Card>
))}