# KADi — Backend & Web Application

A Next.js application for supplier development, factory analysis, and operational benchmarking. Built for on-site supplier audits, ramp-up assurance (Anlaufsicherung), and structured workshop execution. Deployed as a single-tenant instance for the BMW pilot (the multi-tenant control plane was removed 2026-05-26 — see `CHANGELOG.md`).

---

## Table of Contents

- [Overview](#overview)
- [Tech Stack](#tech-stack)
- [Prerequisites](#prerequisites)
- [Getting Started](#getting-started)
- [Environment Variables](#environment-variables)
- [Available Scripts](#available-scripts)
- [Project Structure](#project-structure)
- [Testing](#testing)
- [Database & Migrations](#database--migrations)
- [Deployment](#deployment)
- [Branch Strategy](#branch-strategy)
- [Additional Documentation](#additional-documentation)

---

## Overview

KADi is a web application supporting supplier development workflows, including:

- **Supplier assessments** with multi-language support (DE / EN / ZH)
- **Factory analysis (Fabrikanalyse)** based on structured questionnaires
- **OEE (Overall Equipment Effectiveness)** tracking and benchmarking
- **QAF (Quality Assessment Framework)** with comparison across suppliers
- **LSC Workshops** for structured on-site supplier engagements
- **Planning & Calendar** modules for audit tour management
- **Agenda, Notes, PMO, Intake** modules for workshop and supplier-onboarding workflows
- **Role-based admin APIs** for user and permission management

The application is designed as a Progressive Web App (PWA) with offline capabilities via service workers and IndexedDB (Dexie).

---

## Tech Stack

| Layer            | Technology                                                  |
| ---------------- | ----------------------------------------------------------- |
| Framework        | [Next.js 16](https://nextjs.org/) (App Router, Turbopack)   |
| Language         | TypeScript 5                                                |
| UI               | React 19, shadcn/ui, Radix UI, Tailwind CSS 4               |
| Backend / DB     | [Supabase](https://supabase.com/) (Postgres, Auth, Storage) |
| Client DB        | Dexie.js (IndexedDB) for offline support                    |
| Charts           | Recharts                                                    |
| Exports          | ExcelJS, PptxGenJS, jsPDF                                   |
| Testing          | Vitest + v8 coverage                                        |
| Linting / Format | ESLint 9, Prettier 3                                        |
| Deployment       | Vercel                                                      |

---

## Prerequisites

- **Node.js** ≥ 20.9 (next 16 floor). The validated dev / CI baseline is **24.x** — use it to match (`.nvmrc` pins `24`).
- **npm** ≥ 10.x (npm is used throughout this repo; the lockfile is `package-lock.json`)
- **Supabase project** (URL + keys — see [Environment Variables](#environment-variables))
- **Git** for version control

---

## Getting Started

### 1. Clone the repository

```bash
git clone https://github.com/KADiCon/Kadi-v2.git
cd Kadi-v2
```

### 2. Install dependencies

```bash
npm install
```

### 3. Configure environment variables

Copy the example env file and fill in your Supabase credentials:

```bash
cp .env.example .env.local
```

Then edit `.env.local` — see [Environment Variables](#environment-variables) below.

### 4. Start the development server

```bash
npm run dev
```

The app runs at [http://localhost:3000](http://localhost:3000) with Turbopack for fast HMR.

---

## Environment Variables

All required variables are listed in [`.env.example`](.env.example). Copy it to `.env.local` and fill in the values.

| Variable                             | Required | Description                                        |
| ------------------------------------ | -------- | -------------------------------------------------- |
| `NEXT_PUBLIC_SUPABASE_URL`           | ✅       | Your Supabase project URL                          |
| `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` | ✅     | Supabase anon / publishable key (client-safe)      |
| `SUPABASE_SERVICE_ROLE_KEY`          | ✅       | Supabase service role key (server-only, **never** expose to client) |
| `NEXT_PUBLIC_APP_ENV`                | ✅       | `development` / `staging` / `production`           |
| `NEXT_TELEMETRY_DISABLED`            | ⚪       | Set to `1` to disable Next.js telemetry            |

> ⚠️ **Security:** Never commit `.env.local` or any file containing real keys. The `SUPABASE_SERVICE_ROLE_KEY` bypasses Row Level Security and must remain server-side only.

---

## Available Scripts

| Command                 | Description                                         |
| ----------------------- | --------------------------------------------------- |
| `npm run dev`           | Start dev server with Turbopack                     |
| `npm run build`         | Build for production (includes service worker versioning) |
| `npm run start`         | Start the production server                         |
| `npm run lint`          | Run ESLint                                          |
| `npm run format`        | Format all `.ts` / `.tsx` files with Prettier       |
| `npm run typecheck`     | Run TypeScript type checking without emitting files |
| `npm run test`          | Run Vitest test suite (single run)                  |
| `npm run test:watch`    | Run Vitest in watch mode                            |
| `npm run test:coverage` | Run tests with v8 coverage report                   |
| `npm run check:portability` | Run the full portability gate (profiles, forbidden-strings, boundaries, openapi, csp, secrets, hardcoded-colors, bmw-fonts). Run before every PR. Use `CHECK_FORBIDDEN_LEVEL=error npm run check:portability` for the strict CI-equivalent mode. |
| `npm run new:module -- <name>` | Scaffold a new `lib/` module (ADR-019 golden path) |

---

## Project Structure

```
.
├── app/                        # Next.js App Router (pages, layouts, API routes)
│   ├── api/                    # API route handlers
│   │   ├── admin/              # Admin endpoints (users, audit, views)
│   │   ├── v1/                 # Public v1 API (assignments, projects, oee)
│   │   ├── demo/               # Demo data lifecycle
│   │   ├── planning/ wertstrom/ qaf-template/ repository/ holidays/  # module endpoints
│   │   └── ...
│   ├── assessment/             # Supplier assessments (DE / EN / ZH)
│   ├── fabrikanalyse/          # Factory analysis module
│   ├── oee/                    # OEE tracking
│   ├── kalender/ planning/     # Calendar / audit tour planning
│   ├── lsc-workshop/           # LSC workshop execution
│   ├── pmo/ intake/ notes/     # PMO, supplier intake, project notes
│   └── repository/             # Document repository
├── components/                 # Reusable React components (shadcn/ui)
├── lib/                        # Core business logic (module barrels: lib/<module>/index.ts)
│   ├── agenda/ pmo/ intake/ notes/ oee/ reporting/  # feature modules
│   ├── auth/ security/ gdpr/   # auth, CSP/CSRF/rate-limit, GDPR
│   ├── supabase/               # Supabase clients (client / server / middleware) + privileged-env
│   ├── offline/                # Dexie/IndexedDB offline queue + repository
│   └── duplicates/             # De-duplication logic
├── hooks/                      # Custom React hooks
├── docs/                       # Project documentation (ADRs, foundation, vendor-handover)
│   └── adr/                    # Architecture Decision Records
├── scripts/                    # Build & utility scripts (check:*, sync-bmw-fonts, new-module)
├── public/                     # Static assets + service worker (sw.js)
├── __tests__/                  # Vitest test files
├── MO-23 … MO-27, MO-LSC, MO-OEE  # Module-schema SQL (cataloged in MIGRATIONS.md)
├── supabase-*.sql              # Supabase migrations & seed files (see MIGRATIONS.md)
├── middleware.ts               # Next.js 16 middleware (session refresh, CSP nonce)
└── next.config.mjs             # Next.js configuration
```

---

## Testing

The project uses [Vitest](https://vitest.dev/) for unit and integration tests.

```bash
npm run test              # single run
npm run test:watch        # watch mode
npm run test:coverage     # with coverage report
```

Test files are located in `__tests__/` and follow the naming pattern `*.test.ts`.

---

## Database & Migrations

Database schema and migrations are managed as plain SQL files in the repo root (plus the `MO-*` module-schema folders). There is **no Supabase CLI migration tracking** — migrations are applied manually in order.

**[`MIGRATIONS.md`](MIGRATIONS.md) is the single source of truth**: it classifies every SQL file (schema / module-schema / rls / seed / rollback / review-only), documents the verified apply order, the RLS effect of each file, and the recommended fresh-database bootstrap (`supabase/bootstrap/supabase-bootstrap-from-prod.sql`).

> 📌 Do **not** apply any SQL file to production without operator approval — see the warning at the top of `MIGRATIONS.md`. For the most recent live RLS state, see [`docs/foundation/rls-audit-2026-04-21.md`](docs/foundation/rls-audit-2026-04-21.md).

---

## Deployment

The application is deployed on **Vercel**.

- **Production branch:** `main`
- **Build command:** `npm run build` (runs service worker versioning, then `next build`)
- **Environment variables:** configure all variables from `.env.example` in the Vercel project settings
- **Single-tenant deployment:** one instance per customer (BMW pilot). The former multi-tenant owner/provisioning API was removed 2026-05-26.

---

## Branch Strategy

`main` is the production branch (deployed to Vercel). Feature work happens on short-lived branches off `main`. The full branch / commit / PR / CI-gate workflow is documented in [`CONTRIBUTING.md`](CONTRIBUTING.md).

**Workflow (summary):**

1. Create a feature branch off `main` (e.g., `feat/supplier-search`)
2. Commit with conventional commit messages (e.g., `feat:`, `fix:`, `refactor:`, `chore:`)
3. Run `npm run typecheck`, `npm run lint`, `npm run test`, and `CHECK_FORBIDDEN_LEVEL=error npm run check:portability` before pushing
4. Push and open a Pull Request against `main`; merge after review and green CI

---

## Additional Documentation

| File                          | Description                                           |
| ----------------------------- | ----------------------------------------------------- |
| [`GETTING_STARTED.md`](GETTING_STARTED.md) | Detailed local setup (vendor-oriented)        |
| [`CONTRIBUTING.md`](CONTRIBUTING.md) | Branch / commit / PR workflow & CI gates       |
| [`AGENTS.md`](AGENTS.md)      | Human code-review guidelines (P0/P1/P2 framing)       |
| [`CLAUDE.md`](CLAUDE.md)      | AI-agent operating context (tech stack, conventions)  |
| [`API_SPEC.md`](API_SPEC.md)  | Full API specification (data contracts)               |
| [`MIGRATIONS.md`](MIGRATIONS.md) | Database migrations — classification & apply order |
| [`DEPLOYMENT.md`](DEPLOYMENT.md) | Build & deployment guide                           |
| [`SECURITY.md`](SECURITY.md)  | Security policy & disclosure                           |
| [`CHANGELOG.md`](CHANGELOG.md) | Version history & release notes                      |
| [`PRODUCT_SPEC.md`](PRODUCT_SPEC.md) | Product specification & feature scope          |
| [`docs/adr/`](docs/adr/)      | Architecture Decision Records (ADRs)                  |
| [`docs/vendor-handover/`](docs/vendor-handover/) | Vendor / Adesso handover package           |

---

## License

Internal project — all rights reserved.

---

## Contact

For questions, bug reports, or feature requests, please open an issue on GitHub or reach out to the project maintainers.
