Skip to content

ForliLabs/terra-ferma

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

142 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ”๏ธ TerraFerma

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.

Next.js 16 TypeScript Prisma Vitest License


Table of Contents


Overview

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

Key Features

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

Architecture

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
Loading

๐Ÿ“– For detailed architecture documentation with data flow diagrams, see docs/ARCHITECTURE.md

๐Ÿ“ For release highlights and repository evolution, see CHANGELOG.md.

Tech Stack

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

Getting Started

Prerequisites

  • Node.js โ‰ฅ 20
  • npm โ‰ฅ 10

Installation

# 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 dev

Open http://localhost:3000 to see the application.

Docker

# 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-ferma

Project Structure

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

Available Scripts

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

Environment Variables

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)

Testing

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.

Deployment

Vercel (recommended)

The project includes vercel.json configuration. Connect your repository to Vercel and set environment variables in the Vercel dashboard.

Docker

The included Dockerfile uses a multi-stage build:

  1. deps โ€” Install node_modules
  2. builder โ€” Generate Prisma client, build Next.js
  3. runner โ€” Minimal Alpine image with standalone output
docker compose up --build

Production checklist

  • 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

Documentation

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

License

This project is released under the MIT License.


Built for the resilience of Romagna ๐Ÿ‡ฎ๐Ÿ‡น

About

Flood resilience and risk monitoring tools for communities, businesses, and municipalities.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages