Flood Risk & Resilience Operating System for Romagna
TerraFerma is a SaaS platform that transforms flood risk management from reactive damage control into a continuous, data-driven resilience cycle. Built for businesses, municipalities, and insurers in the Emilia-Romagna region of Italy, it integrates real-time hydrometric data from ARPAE, AI-powered flood prediction, multi-channel alerts, regulatory compliance automation, and insurance orchestration into a single control plane.
- Overview
- Key Features
- Architecture
- Tech Stack
- Getting Started
- Project Structure
- Available Scripts
- Environment Variables
- Testing
- Deployment
- Documentation
- License
TerraFerma was born from the devastating 2023 Romagna floods, which exposed critical gaps in flood preparedness for businesses and municipalities. The platform provides:
- Real-time monitoring of river levels across the Montone, Rabbi, Ronco, and Bidente basins
- AI flood prediction with 6h/12h/24h probability horizons
- Automated compliance with Italian PAI (Piano Assetto Idrogeologico) regulations
- Insurance orchestration including parametric policies with auto-payout
- PNRR grant tracking for flood resilience investments
The platform uses an event-driven architecture centered on the Risk Intelligence Bus, which connects 36+ domain modules through typed events with cascade tracking and correlation IDs.
ARPAE Sensors โ Prediction Engine โ Alert System โ Impact Assessment
โ
Insurance Claims โ Evidence Chain โ Compliance
| Category | Features |
|---|---|
| Data Ingestion | Real ARPAE pipeline, federated sensor network, IoT device management |
| Intelligence | Flood prediction (simulated XGBoost/LSTM), watershed cascade modeling, alert correlation |
| Risk Management | PAI zone classification, risk scoring, portfolio analysis, investment optimization |
| Compliance | Regulatory change monitoring, automated task creation, compliance orchestration, evidence chain |
| Insurance | Dynamic premium pricing, parametric policies, claims lifecycle, insurer marketplace |
| Operations | Multi-channel alerts (email/SMS/push/WhatsApp), evacuation planning, BCP generation |
| Public Sector | PNRR grant matching, municipal dashboard, citizen alerts, data exchange agreements |
| Platform | GraphQL federation, webhook delivery, embeddable risk widgets, developer SDK, RBAC |
| Observability | Health checks, structured logging (Pino), Sentry integration, API latency tracking |
| Billing | Stripe subscription management, tier-based feature gating, usage metering |
graph TB
subgraph External
ARPAE[ARPAE Dext3r API]
Stripe[Stripe Billing]
Sensors[IoT Sensors]
end
subgraph Ingestion
Pipeline[ARPAE Pipeline]
IoTGw[IoT Gateway]
FedSensors[Federated Sensors]
end
subgraph "Risk Intelligence Bus"
Bus((Event Bus))
end
subgraph Intelligence
Prediction[Prediction Engine]
Watershed[Watershed Model]
Cascade[Cascade Simulator]
Correlation[Alert Correlation]
end
subgraph Operations
Alerts[Alert Engine]
Impact[Impact Assessment]
Evidence[Evidence Chain]
BCP[BCP Generator]
Evacuation[Evacuation Planner]
end
subgraph Financial
Insurance[Insurance Engine]
Pricing[Premium Pricing]
Portfolio[Portfolio Manager]
PNRR[PNRR Tracker]
end
subgraph Compliance
Regulatory[Regulatory Monitor]
CompEngine[Compliance Engine]
Orchestrator[Compliance Orchestrator]
end
subgraph Platform
GraphQL[GraphQL Federation]
Webhooks[Webhook Delivery]
SDK[Developer SDK]
RBAC[RBAC Engine]
Billing[Billing Engine]
end
ARPAE --> Pipeline
Sensors --> IoTGw
Pipeline --> Bus
IoTGw --> Bus
FedSensors --> Bus
Bus --> Prediction
Bus --> Alerts
Bus --> Impact
Bus --> Insurance
Bus --> Regulatory
Bus --> Watershed
Prediction --> Bus
Alerts --> Bus
Impact --> Bus
Insurance --> Bus
Stripe --> Billing
GraphQL --> Bus
Webhooks --> Bus
end
๐ For detailed architecture documentation with data flow diagrams, see docs/ARCHITECTURE.md
๐ For release highlights and repository evolution, see CHANGELOG.md.
| Layer | Technology |
|---|---|
| Framework | Next.js 16 (App Router) |
| Language | TypeScript 5 |
| Database | libSQL (dev) / PostgreSQL via Prisma 7 (60 models) |
| Billing | Stripe (subscriptions, webhooks, customer portal) |
| Logging | Pino (structured JSON, pino-pretty in dev) |
| Testing | Vitest (110+ test cases across 20 test files) |
| Styling | Tailwind CSS 4 |
| Components | Lucide React icons, CVA + clsx + tailwind-merge |
| Deployment | Docker (multi-stage), Vercel, standalone output |
| Observability | Sentry (buffer mode), custom health checks |
- Node.js โฅ 20
- npm โฅ 10
# Clone the repository
git clone <repository-url>
cd terra-ferma
# Install dependencies
npm install
# Copy environment variables
cp .env.example .env
# Generate Prisma client
npm run db:generate
# Push schema and seed database
npm run db:reset
# Start the development server
npm run devOpen http://localhost:3000 to see the application.
# Build and run with Docker Compose
docker compose up --build
# Or build the image directly
docker build -t terra-ferma .
docker run -p 3000:3000 --env-file .env terra-fermaterra-ferma/
โโโ prisma/
โ โโโ schema.prisma # 60 models across 9 domains
โ โโโ seed.ts # Demo data seeding
โโโ src/
โ โโโ app/
โ โ โโโ (marketing)/ # Public pages (pricing, verticals)
โ โ โโโ api/ # 67 API route handlers
โ โ โ โโโ v1/ # Versioned public API (auth + validation)
โ โ โ โโโ arpae/ # ARPAE data pipeline endpoints
โ โ โ โโโ billing/ # Stripe checkout/portal/webhooks
โ โ โ โโโ auth/ # Login, register, session
โ โ โ โโโ ... # Domain-specific endpoints
โ โ โโโ auth/ # Auth pages
โ โ โโโ dashboard/ # 22 dashboard views
โ โ โโโ developer/ # Developer portal (docs, SDK, GraphQL)
โ โ โโโ emergency/ # Emergency response page
โ โ โโโ onboarding/ # User onboarding flow
โ โ โโโ risk-check/ # Public risk assessment tool
โ โ โโโ status/ # System status page
โ โโโ components/ # React UI components
โ โโโ generated/ # Prisma generated client
โ โโโ lib/ # Core business logic (36 modules)
โ โโโ arpae/ # ARPAE data pipeline & stations
โ โโโ alerts/ # Multi-channel alert engine
โ โโโ auth/ # Authentication middleware
โ โโโ backtesting/ # Prediction backtesting engine
โ โโโ billing/ # Stripe billing engine
โ โโโ bus/ # Risk Intelligence Bus (event system)
โ โโโ cascade-simulator/ # Flood cascade modeling
โ โโโ compliance/ # Compliance engine
โ โโโ compliance-orchestrator/ # Automated compliance workflows
โ โโโ evidence-chain/ # Forensic evidence packaging
โ โโโ graphql-federation/# Unified GraphQL query layer
โ โโโ insurance/ # Claims + parametric policies
โ โโโ prediction/ # AI flood prediction engine
โ โโโ pricing/ # Dynamic premium calculator
โ โโโ rbac/ # Role-based access control
โ โโโ watershed/ # Watershed topology modeling
โ โโโ ... # 20+ additional domain modules
โโโ docker-compose.yml
โโโ Dockerfile # Multi-stage (deps โ build โ runner)
โโโ vitest.config.ts
โโโ package.json
| Command | Description |
|---|---|
npm run dev |
Start development server |
npm run build |
Production build (4GB heap) |
npm start |
Start production server |
npm run lint |
Run ESLint |
npm run typecheck |
TypeScript type checking |
npm run db:generate |
Generate Prisma client |
npm run db:migrate |
Run Prisma migrations (dev) |
npm run db:push |
Push schema to database |
npm run db:seed |
Seed demo data |
npm run db:reset |
Reset database and re-seed |
npm test |
Run all tests |
npm run test:watch |
Run tests in watch mode |
npm run test:coverage |
Run tests with coverage report |
Copy .env.example to .env and configure:
| Variable | Required | Description |
|---|---|---|
DATABASE_URL |
Yes | Database connection (file:./dev.db for local) |
NEXT_PUBLIC_APP_URL |
No | Public app URL (default: http://localhost:3000) |
STRIPE_SECRET_KEY |
No | Stripe API key for billing |
STRIPE_WEBHOOK_SECRET |
No | Stripe webhook signature secret |
STRIPE_PRO_PRICE_ID |
No | Stripe price ID for Pro tier |
STRIPE_ENTERPRISE_PRICE_ID |
No | Stripe price ID for Enterprise tier |
ARPAE_API_URL |
No | ARPAE Dext3r API URL |
CRON_SECRET |
No | Secret for cron endpoint auth |
VAPID_PUBLIC_KEY |
No | VAPID key for web push notifications |
VAPID_PRIVATE_KEY |
No | VAPID private key |
SENTRY_DSN |
No | Sentry error tracking DSN |
RESEND_API_KEY |
No | Resend email delivery API key |
TWILIO_ACCOUNT_SID |
No | Twilio SMS account SID |
TWILIO_AUTH_TOKEN |
No | Twilio auth token |
TWILIO_PHONE_NUMBER |
No | Twilio sender phone number |
DEMO_MODE |
No | Enable demo mode (true/false) |
Tests use Vitest with module-level isolation:
# Run all tests
npm test
# Run with watch mode
npm run test:watch
# Run with coverage
npm run test:coverage
# Run a specific module's tests
npx vitest run src/lib/bus/__tests__/Test coverage spans 20 test files across critical modules including the bus engine, prediction engine, billing gating, RBAC, alert delivery, cascade simulator, compliance orchestrator, and more.
The project includes vercel.json configuration. Connect your repository to Vercel and set environment variables in the Vercel dashboard.
The included Dockerfile uses a multi-stage build:
- deps โ Install
node_modules - builder โ Generate Prisma client, build Next.js
- runner โ Minimal Alpine image with standalone output
docker compose up --build- Set
NODE_ENV=production - Configure PostgreSQL
DATABASE_URL(e.g., Neon, Supabase) - Set Stripe keys and webhook secret
- Configure ARPAE API URL and cron secret
- Set Sentry DSN for error tracking
- Configure alert delivery (Resend, Twilio)
- Generate VAPID keys for push notifications
- Set
DEMO_MODE=false
| Document | Description |
|---|---|
| docs/ARCHITECTURE.md | System architecture, data flow diagrams, module interactions |
| docs/API.md | Full API reference for all 67 endpoints |
| AGENTS.md | Agent configuration for AI-assisted development |
| CHANGELOG.md | Iteration-by-iteration product and platform changes |
This project is released under the MIT License.
Built for the resilience of Romagna ๐ฎ๐น