Family-centric elderly care coordination platform for Forlì and Italy
CuraVicina ("nearby care" in Italian) is a full-stack platform that coordinates caregivers, medications, appointments, and health monitoring for families caring for elderly loved ones. Built for the Italian healthcare ecosystem β with SPID/CIE digital identity, FSE 2.0 health records, INPS payroll compliance, and 112 emergency integration β it gives families peace of mind whether they're in ForlΓ¬ or across the country.
Key numbers: 57 API routes Β· 66 Prisma models Β· 31 dashboard pages Β· 31 unit test files Β· 13 UI components Β· 45+ library modules Β· 5 languages
- PBKDF2-SHA256 password hashing (310K iterations, WebCrypto API)
- SPID/CIE SAML 2.0 digital identity (mandatory for B2G integrations)
- Role-based access control:
family_admin,family_member,caregiver - Tiered API rate limiting, CORS, CSRF protection, input validation
- API key auth for municipality (B2G) endpoints
- Full audit trail with IP/action logging
- Smart bracelet integration β heart rate, SpOβ, blood pressure, temperature, fall detection, GPS
- Drug interaction engine β 12 clinically relevant Italian medication pairs, alias normalization
- Predictive fall risk scoring β weighted heuristic model (HRV, gait, sleep, activity, age, polypharmacy)
- Cognitive health β daily mood check-ins, screening questionnaires, wellness composite scoring
- Emergency SOS β one-tap 112 protocol with patient dossier, GPS, family notification blast
- FSE 2.0 integration β CDA2 document import/export from Italy's Fascicolo Sanitario Elettronico
- Geofencing β circle/polygon safe zones, zone enter/exit event logging, movement heatmaps
- Multi-patient dashboards with daily activity feed
- Daily digest emails & weekly care report cards
- Medication compliance streaks & engagement analytics
- Churn prediction & re-engagement quick actions
- In-app voice & video calls (Daily.co WebRTC)
- Async voice messages with transcription
- Rule-based AI care assistant (keyword intent detection)
- Caregiver marketplace β verified profiles, ratings, reviews, shift scheduling
- Stripe Connect β 15% commission, SEPA payouts, 48h escrow, dispute lifecycle
- Pharmacy network β haversine proximity search, refill ordering, supply-day alerts
- Telemedicine β video consultations, consultation notes, appointment linking
- Caregiver training β course modules, quiz gating, certificate issuance with verification codes
- Municipality portal β anonymized population metrics, social worker case management
- INPS/COLF payroll β CCNL 2024 wage tables, IRPEF brackets, quarterly MAV deadlines, TFR/13th month
- Multi-tenant β subdomain routing, per-tenant feature flags, environment presets
- Predictive analytics β health scoring, anomaly detection (z-score), trend analysis
- GDPR engine β granular consent (6 types), Art. 15 data export, Art. 17 cascading erasure, data retention
- Stripe Billing β 3 subscription tiers (Base/Plus/Premium), Italian VAT invoicing, SDI identifiers
- Observability β structured JSON logging, custom metrics, health checks, alert rules with cooldowns
- Monitoring β Sentry integration, incident lifecycle, web vitals thresholds, status page
- Delivery β Resend email + Twilio SMS with priority queuing and delivery logging
- PWA β Service Worker, IndexedDB offline sync, conflict resolution, cache strategies
- WCAG 2.1 AA accessibility with skip links, keyboard navigation, contrast compliance
- 5-language i18n β Italian, English, Romanian, Ukrainian, Moldovan (server-side, cookie-based)
- CI/CD β GitHub Actions, Docker multi-stage build, Vercel (Frankfurt
fra1region) - Cron jobs β daily digest (06:00), weekly report (Monday 08:00), onboarding emails (08:00)
graph TB
subgraph "Client Layer"
PWA[PWA + Service Worker]
IDB[IndexedDB<br/>Offline Cache]
end
subgraph "Next.js 16 Application"
Pages[31 Dashboard Pages]
API[57 API Routes]
SSE[SSE Real-Time Events]
Cron[Vercel Cron Jobs]
end
subgraph "Business Logic β src/lib/"
Auth[auth Β· security Β· spid-auth]
Health[drug-interactions Β· fall-risk<br/>geofencing Β· cognitive-health]
Care[emergency Β· engagement<br/>ai-assistant Β· analytics]
Payments[stripe-billing Β· stripe-connect<br/>payroll]
Comms[voice-video Β· delivery<br/>notifications Β· i18n]
Infra[observability Β· monitoring<br/>gdpr Β· offline-sync Β· tenant]
end
subgraph "Data Layer"
Prisma[Prisma 7 ORM<br/>66 Models]
SQLite[SQLite / LibSQL<br/>Development]
PG[PostgreSQL 16<br/>Production]
end
subgraph "External Services"
Stripe[Stripe<br/>Billing + Connect]
Resend[Resend<br/>Email]
Twilio[Twilio<br/>SMS]
Daily[Daily.co<br/>WebRTC]
SPID[SPID/CIE<br/>Identity]
FSE[FSE 2.0<br/>Health Records]
Sentry[Sentry<br/>Errors]
end
PWA --> API
PWA --> SSE
PWA <--> IDB
API --> Auth & Health & Care & Payments & Comms & Infra
Auth & Health & Care & Payments & Comms & Infra --> Prisma
Prisma --> SQLite
Prisma --> PG
Payments --> Stripe
Comms --> Resend & Twilio & Daily
Auth --> SPID
Health --> FSE
Infra --> Sentry
Cron --> API
For a deep-dive into data flow, domain models, and module relationships, see docs/ARCHITECTURE.md.
- Node.js 20+ and npm 10+
- (Optional) Docker & Docker Compose for containerized deployment
# 1. Clone and install
git clone https://github.com/forli/cura-vicina.git
cd cura-vicina
npm install
# 2. Configure environment
cp .env.example .env
# Only DATABASE_URL is required for local dev β all integrations degrade gracefully
# 3. Database setup
npx prisma generate # Generate Prisma client (66 models)
npx prisma db push # Apply schema to SQLite
npx tsx prisma/seed.ts # Seed demo family, patients, medications, vitals
# 4. Start development server
npm run dev # http://localhost:3000docker compose up # Starts app + PostgreSQL 16Note: The Docker Compose
DATABASE_URLcurrently defaults to SQLite (file:./dev.db). For PostgreSQL, update it topostgresql://curavicina:curavicina_dev@db:5432/curavicina.
npm test # Vitest β run all 31 test files
npm run test:watch # Watch mode
npm run test:coverage # V8 coverage report (src/lib/**)
npm run test:e2e # Playwright end-to-end tests
npm run test:e2e:ui # Playwright with UInpm run build # Production build (Next.js)
npm run lint # ESLint
npm run typecheck # TypeScript checks only
npm run ci # Local CI gate: lint + typecheck + tests
npm start # Start production servercura-vicina/
βββ prisma/
β βββ schema.prisma # 66 Prisma models across 9 domains
β βββ seed.ts # Demo data: Famiglia Rossi, 5 users, meds, vitals
β βββ migrations/ # Migration history
βββ src/
β βββ app/
β β βββ api/ # 57 API route handlers (Next.js App Router)
β β β βββ auth/ # login, register, logout, invite, me
β β β βββ billing/ # Stripe subscriptions
β β β βββ connect/ # Stripe Connect payouts
β β β βββ caregivers/ # Profiles, reviews, shifts
β β β βββ consultations/ # Telemedicine sessions + notes
β β β βββ cron/ # daily-digest, weekly-report, onboarding-emails
β β β βββ emergency/ # SOS trigger + resolution
β β β βββ medications/ # CRUD + interactions + refills
β β β βββ vitals/ # Readings + alert management
β β β βββ ... # 17 more route groups
β β βββ dashboard/ # 31 dashboard pages
β β β βββ analytics/ # Health insights, trends
β β β βββ billing/ # Subscription management
β β β βββ caregivers/ # Marketplace UI
β β β βββ emergency/ # SOS interface
β β β βββ medications/ # Drug management
β β β βββ municipality/ # B2G portal
β β β βββ ... # 24 more sections
β β βββ auth/ # Login/register pages
β β βββ accessibility/ # WCAG audit page
β β βββ layout.tsx # Root layout: locale, manifest, cookie consent
β β βββ page.tsx # Marketing landing page
β βββ components/ # 13 shared React components
β β βββ sos-button.tsx # Emergency SOS trigger
β β βββ realtime-events.tsx # SSE event stream consumer
β β βββ cookie-consent.tsx # GDPR cookie banner
β β βββ language-switcher.tsx # 5-locale switcher
β β βββ ...
β βββ lib/ # 45+ business logic modules
β β βββ auth.ts # PBKDF2 + session management
β β βββ security.ts # Rate limiting, CSRF, validation, API keys
β β βββ drug-interactions.ts # Medication safety engine
β β βββ fall-risk.ts # Predictive fall scoring
β β βββ geofencing.ts # Safe zone monitoring
β β βββ emergency.ts # SOS + 112 integration
β β βββ gdpr.ts # Consent, export, erasure
β β βββ stripe-billing.ts # Subscriptions + VAT
β β βββ stripe-connect.ts # Marketplace payments
β β βββ payroll.ts # INPS/COLF payroll engine
β β βββ voice-video.ts # WebRTC rooms + voice messages
β β βββ spid-auth.ts # SPID/CIE SAML flow
β β βββ i18n.ts # Server-side translations
β β βββ observability.ts # Logging, metrics, health checks
β β βββ monitoring.ts # Incidents, alerts, status page
β β βββ offline-sync.ts # Conflict resolution (server)
β β βββ offline-sync-client.ts # IndexedDB sync (browser)
β β βββ openapi.ts # OpenAPI 3.1 spec generator
β β βββ __tests__/ # 31 Vitest test files
β β βββ translations/ # it.ts, en.ts, ro.ts, uk.ts, md.ts
β βββ generated/ # Prisma generated client
βββ e2e/ # Playwright E2E tests
βββ public/ # Static assets, PWA manifest
βββ docker-compose.yml # App + PostgreSQL 16
βββ Dockerfile # Multi-stage Node 20 Alpine
βββ vercel.json # Vercel config: Frankfurt, cron, security headers
βββ vitest.config.ts # Vitest: node env, V8 coverage
| Layer | Technology | Details |
|---|---|---|
| Framework | Next.js 16 | App Router, Turbopack, React 19 |
| Language | TypeScript 5 | Strict mode |
| Styling | Tailwind CSS 4 | PostCSS pipeline |
| Database | Prisma 7 | LibSQL adapter (dev), PostgreSQL 16 (prod) |
| Auth | PBKDF2-SHA256 | 310K iterations, WebCrypto, 30-day sessions |
| Identity | SPID/CIE | SAML 2.0, AGID-certified for production |
| Payments | Stripe | Billing (3 tiers) + Connect Express (SEPA) |
| Resend | Transactional + digest emails | |
| SMS | Twilio | Emergency SOS + medication reminders |
| Video | Daily.co | Managed WebRTC, TURN/STUN |
| Testing | Vitest 4 + Playwright | V8 coverage, E2E critical flows |
| CI/CD | GitHub Actions | Build β lint β test pipeline |
| Deployment | Vercel / Docker | Frankfurt region, multi-stage build |
| Monitoring | Sentry + custom | Structured logging, alert rules, status page |
All integrations degrade gracefully when credentials are missing. Only DATABASE_URL is required for local development.
| Variable | Description | Required |
|---|---|---|
DATABASE_URL |
SQLite (file:./dev.db) or PostgreSQL connection |
β Always |
NEXT_PUBLIC_BASE_URL |
Application URL (default http://localhost:3000) |
β Production |
SESSION_SECRET |
32+ byte hex secret for session signing | β Production |
STRIPE_SECRET_KEY |
Stripe API key | Billing |
STRIPE_CONNECT_CLIENT_ID |
Stripe Connect app ID | Marketplace |
RESEND_API_KEY |
Resend email API key | |
TWILIO_ACCOUNT_SID |
Twilio account + auth token + from number | SMS |
SENTRY_DSN |
Sentry project DSN | Error tracking |
DAILY_API_KEY |
Daily.co API key + domain | Video calls |
SPID_ENTITY_ID |
SPID service provider entity ID | Digital identity |
See .env.example for the complete list with inline documentation.
CuraVicina exposes 57 API routes organized into 28 groups. API documentation is auto-generated via an OpenAPI 3.1 spec at /api/docs.
| Group | Endpoints | Auth | Description |
|---|---|---|---|
| Auth | /api/auth/login, register, logout, me, invite |
Mixed | PBKDF2 login, session management, family invites |
| SPID | /api/spid |
No | SPID provider listing + SAML AuthnRequest |
| Patients | /api/patients |
Yes | Multi-patient listing |
| Medications | /api/medications, interactions, refills |
No | CRUD, drug interaction checks, refill alerts |
| Vitals | /api/vitals, vitals/alerts |
Yes | Smart bracelet readings, alert management |
| Emergency | /api/emergency |
No | SOS trigger/resolve, active emergencies |
| Fall Risk | /api/fall-risk |
Yes | Predictive scoring + alert creation |
| Geofencing | /api/geofencing |
No | Safe zone management, GPS checking |
| Caregivers | /api/caregivers, [id], [id]/reviews, [id]/shifts |
Yes | Marketplace profiles, reviews, scheduling |
| Consultations | /api/consultations, [id], [id]/notes |
Yes | Telemedicine sessions |
| Billing | /api/billing |
Yes | Stripe subscription management |
| Connect | /api/connect |
No | Stripe Connect metrics + onboarding |
| Payroll | /api/payroll |
Yes | INPS/COLF payroll calculations |
| GDPR | /api/consent, data-requests |
Mixed | Consent management, data export/erasure |
| Engagement | /api/digest, notifications, events |
Mixed | Digests, push notifications, SSE stream |
| Communication | /api/calls, chat, voice-messages |
Mixed | WebRTC rooms, AI chat, async voice |
| Health Records | /api/health-records |
Yes | FSE 2.0 import/export |
| Pharmacy | /api/pharmacy |
No | Proximity search, refill ordering |
| Training | /api/training |
No | Courses, enrollment, certificates |
| Municipality | /api/municipality |
Yes | B2G portal analytics + cases |
| Analytics | /api/analytics |
No | Patient insights + health scoring |
| Delivery | /api/delivery |
No | Email/SMS queue + metrics |
| Reports | /api/reports |
Yes | Generated care reports |
| Observability | /api/health, metrics, status, security |
No | Health checks, metrics, audit log |
| Cron | /api/cron/daily-digest, weekly-report, onboarding-emails |
No | Scheduled jobs |
| Docs | /api/docs, docs/spec |
No | Swagger UI + OpenAPI 3.1 spec |
| Misc | /api/locale, sync, onboarding, moonshots |
Mixed | i18n, offline sync, onboarding flow |
Full endpoint reference with request/response schemas: docs/API.md
The Prisma schema defines 66 models organized across 9 domains:
| Domain | Models | Key Entities |
|---|---|---|
| Auth & Identity | 7 | User, Session, Family, FamilyInvite, SpidIdentity, OnboardingProgress, ConsentRecord |
| Health & Care | 14 | Patient, Medication, DrugInteraction, VitalReading, FallRiskScore, DailyCheckin, CognitiveAssessment, WellnessScore |
| Emergency & Safety | 3 | EmergencyEvent, SafeZone, GeofenceEvent |
| Caregivers & Marketplace | 8 | CaregiverProfile, CaregiverShift, CaregiverReview, ConnectAccount, ShiftPayment, PayoutRecord, PaymentDispute |
| Communication | 7 | Notification, RealtimeEvent, DeliveryLog, ChatMessage, VoiceMessageRecord, CallRecord, ScheduledCall |
| Billing & Payroll | 6 | Subscription, Invoice, Transaction, PayrollContract, Payslip, ComplianceEvent |
| Medical Records | 4 | Consultation, ConsultationNote, HealthRecord, Appointment |
| Analytics & AI | 8 | PatientInsight, AnalyticsSnapshot, CareTwinSnapshot, CareSimulation, CareAutopilotPolicy, CareAutopilotRun, CommunityHub, CommunityMission |
| Operations | 9 | Tenant, MunicipalityConfig, AuditLog, SocialWorkerCase, SystemHealthCheck, SyncCheckpoint, Course, Certificate, CarePassport |
Full ERD and relationship diagrams: docs/ARCHITECTURE.md
| Decision | Choice | Rationale |
|---|---|---|
| Password hashing | PBKDF2-SHA256 (310K iterations) | WebCrypto API native, no compiled native deps, OWASP-compliant |
| Real-time updates | Server-Sent Events (SSE) | Simpler than WebSocket, sufficient for unidirectional dashboard updates |
| Database strategy | SQLite (dev) β PostgreSQL (prod) | Fast local dev with file:./dev.db; production on PostgreSQL 16 |
| Auth protocol | SPID SAML 2.0 | Italian digital identity standard, mandatory for B2G/municipality access |
| Marketplace payments | Stripe Connect Express | Handles KYC, SEPA payouts, tax reporting, dispute resolution |
| i18n approach | Flat key maps, server-only | Zero client bundle bloat, 5 locales (IT/EN/RO/UK/MD) |
| PWA offline | Service Worker + IndexedDB | Critical for rural areas with limited connectivity |
| Video calls | Daily.co managed WebRTC | Avoids self-hosting TURN/STUN infrastructure |
| Drug interactions | Local rule-based engine | 12 curated Italian medication pairs; no external API dependency |
| Fall risk scoring | Weighted heuristic model | Rule-based v1 with clear path to ML model upgrade |
| Payroll engine | CCNL Colf 2024 tables | Hardcoded Italian domestic worker rates; annual update required |
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Run tests (
npm test) - Commit using Conventional Commits:
feat:,fix:,docs:,test:,refactor:,chore: - Push and open a Pull Request
- All external service integrations are designed to degrade gracefully β missing API keys disable specific features without breaking the app
- Test coverage targets
src/lib/**/*.tsexclusively - The seed script creates a demo family ("Famiglia Rossi") with realistic Italian data
- API Reference β Complete endpoint documentation with request/response schemas
- Architecture β System design, data flow diagrams, domain model ERD
- Security β Security model, vulnerability reporting, compliance details
This project is licensed under the MIT License β see the LICENSE file for details.
For security vulnerabilities, please see SECURITY.md.
Made with β€οΈ in ForlΓ¬, Italy
CuraVicina β Assistenza anziani familiare