Skip to content

ForliLabs/cura-vicina

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

119 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🏑 CuraVicina

Family-centric elderly care coordination platform for Forlì and Italy

CI TypeScript Next.js Prisma License

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


✨ Features

πŸ” Authentication & Security

  • 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

πŸ₯ Health & Care

  • 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

πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Family Coordination

  • 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)

πŸ’Š Services & Marketplace

  • 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

πŸ›οΈ B2G & Enterprise

  • 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

πŸ”§ Infrastructure

  • 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 fra1 region)
  • Cron jobs β€” daily digest (06:00), weekly report (Monday 08:00), onboarding emails (08:00)

πŸ—οΈ Architecture

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
Loading

For a deep-dive into data flow, domain models, and module relationships, see docs/ARCHITECTURE.md.


πŸš€ Quick Start

Prerequisites

  • Node.js 20+ and npm 10+
  • (Optional) Docker & Docker Compose for containerized deployment

Local Development

# 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:3000

Docker

docker compose up          # Starts app + PostgreSQL 16

Note: The Docker Compose DATABASE_URL currently defaults to SQLite (file:./dev.db). For PostgreSQL, update it to postgresql://curavicina:curavicina_dev@db:5432/curavicina.

Running Tests

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 UI

Other Commands

npm 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 server

πŸ“ Project Structure

cura-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

πŸ”§ Tech Stack

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)
Email 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

🌐 Environment Variables

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 Email
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.


πŸ“Š API Overview

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


πŸ—„οΈ Data Model

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


πŸ›οΈ Architecture Decisions

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

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (npm test)
  4. Commit using Conventional Commits: feat:, fix:, docs:, test:, refactor:, chore:
  5. Push and open a Pull Request

Development Notes

  • All external service integrations are designed to degrade gracefully β€” missing API keys disable specific features without breaking the app
  • Test coverage targets src/lib/**/*.ts exclusively
  • The seed script creates a demo family ("Famiglia Rossi") with realistic Italian data

πŸ“– Documentation

  • 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

πŸ“œ License

This project is licensed under the MIT License β€” see the LICENSE file for details.

πŸ”’ Security

For security vulnerabilities, please see SECURITY.md.


Made with ❀️ in Forlì, Italy
CuraVicina β€” Assistenza anziani familiare

About

Elderly care coordination for families, caregivers, and local support networks in Italy.

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages