# Before/After Examples — Wave 1+2+3 Compression

> **Illustrative sample domain.** The endpoints, routes, and entity names below
> (booking/rooms, menu/items, reservations planner, etc.) are a SAMPLE domain used
> only to demonstrate the doc-compaction techniques — they are not part of any
> consumer's API. Apply the *technique* (the before→after transformation), not the
> example's vocabulary, to your own `${paths.references_dir}` docs.

Concrete cases validated on a real corpus. For each example: before, after, technique applied.

## Example 1 — API Endpoint (booking.md)

### Before (Wave 0) — 150+ linee per endpoint

```markdown
#### POST /api/v1/merchant/booking/rooms

Create a new booking room. This endpoint creates a new room in the store's
booking system. The room will be used to group tables together.

**Authentication**: This endpoint requires authentication via `withAuthNoParams`.
The session must have a valid merchantUserId with MERCHANT role. ADMIN users
can also access this endpoint on behalf of any merchant.

**Store Access Control**: The request must include a `storeId` query parameter
that identifies the target store. The system verifies that the authenticated
user has access to this store. Admin users have access to all stores.
Merchant users only have access to stores belonging to their merchant.

**Request Body**:
```json
{
  "storeId": "uuid-string",
  "name": "Sala Principale",
  "capacity": 50,
  "order": 1
}
```

**Request Body Fields**:
- `storeId` (string, required): The UUID of the store
- `name` (string, required): The display name, max 80 characters
- `capacity` (number, required): Maximum capacity, must be positive
- `order` (number, optional): Display order

**Response 201 Created**:
```json
{
  "id": "room-uuid",
  "storeId": "store-uuid",
  "name": "Sala Principale",
  "capacity": 50,
  "order": 1,
  "createdAt": "2026-04-05T10:30:00Z",
  "updatedAt": "2026-04-05T10:30:00Z"
}
```

**Response Fields**:
[Field list repeated...]

**Errors**:
- 400 "Nome sala obbligatorio" — if name is empty
- 400 "Capacità non valida" — if capacity < 1
- 409 "Sala duplicata" — if name exists
[etc]
```

### After (Wave 1) — 12 linee per endpoint

```markdown
### POST /api/v1/merchant/booking/rooms

**Auth**: withAuthNoParams  |  **Access**: ADMIN + MERCHANT (see §Store Access Control)

**Body**:
| Field | Type | Required | Desc |
|-------|------|----------|------|
| storeId | string | yes | Store UUID |
| name | string | yes | 1-80 chars |
| capacity | number | yes | >0 |
| order | number | no | Display sort |

**Returns**: [BookingRoom](./schemas.md#bookingroom)
**Errors**: NAME_REQUIRED, INVALID_CAPACITY, ROOM_DUPLICATE ([errors.md](../errors.md#booking---rooms))
```

**Saving**: 138 linee per endpoint × 26 endpoints = ~3600 linee. Total booking.md: 4201→1833 (-56%).

### Tecniche applicate

1. Store Access Control spiegato UNA VOLTA in intro, poi `see §Store Access Control`
2. Request body: tabella compatta invece di narrative + JSON example
3. Response: link a schema invece di JSON inline
4. Errors: codes invece di stringhe italiane + link alla sezione errors.md

## Example 2 — UI Reference (ui/merchant.md)

### Before — repetizioni su ogni pagina

```markdown
### /merchant/bookings/planner

**Purpose**: Drag-drop table reservations planner
**Protection**: This page requires authentication. Session must have
merchantUserId with MERCHANT role. ADMIN users can access any merchant's
pages by impersonating the merchant.
**Layout**: Uses MerchantResponsiveLayout which provides the standard
sidebar navigation, top bar with store switcher, and responsive container.
**Store switching**: Supports CT-0067 multi-store. When merchant has
multiple stores, user can switch via top bar dropdown. Current store
persisted in sessionStorage with Safari ITP fallback.
**Styling**: the project's design system (per `identity.design_philosophy` —
see `${paths.ui_guidelines}`).
**Disabled modules**: If merchant's license doesn't include this module,
the page is completely hidden from navigation.

[Content per planner...]
```

### After — Conventions block top + minimal per-page

```markdown
## Conventions (apply to all pages below)

- **Auth**: merchantUserId + MERCHANT role (ADMIN via impersonation)
- **Layout**: MerchantResponsiveLayout
- **Store switching**: CT-0067 multi-store, sessionStorage persist
- **Styling**: the project's design system (per `identity.design_philosophy`; see `${paths.ui_guidelines}`)
- **License gating**: disabled modules hidden from navigation

---

### /merchant/bookings/planner

**Purpose**: Drag-drop table reservations planner

[Content per planner...]
```

**Saving**: ~200 linee duplicate × 1 block = eliminate una volta = ~200 linee risparmio. Total merchant.md: 2780→1265 (-54%).

### Tecnica

Tutte le convenzioni che valgono per OGNI pagina → blocco Conventions all'inizio. Ogni pagina elenca SOLO cosa è specifico.

## Example 3 — Schema Reuse (menu.md)

### Before — schema inline per ogni endpoint

```markdown
#### POST /api/v1/merchant/menu/items

**Response**:
```json
{
  "id": "item-uuid",
  "categoryId": "cat-uuid",
  "name": "Margherita",
  "description": "Pizza tradizionale...",
  "basePrice": 9.50,
  "imageUrl": "https://...",
  "allergens": ["gluten", "dairy"],
  "nutritionalInfo": {
    "calories": 800,
    "carbs": 90,
    "protein": 30,
    "fat": 25
  },
  "variants": [...],
  "createdAt": "...",
  "updatedAt": "..."
}
```

#### GET /api/v1/merchant/menu/items/[id]

**Response**:
```json
{
  "id": "item-uuid",
  "categoryId": "cat-uuid",
  [same structure repeated]
}
```

[repeat 10x for each item endpoint]
```

### After — schema centrale + references

In `schemas.md`:
```markdown
## MenuItem
| Field | Type | Notes |
|-------|------|-------|
| id | string | UUID |
| categoryId | string | FK MenuCategory |
| name | string | 1-120 chars |
| description | string | 0-500 chars |
| basePrice | number | €, 2 decimals |
| imageUrl | string \| null | |
| allergens | string[] | CEE 1169/2011 list |
| nutritionalInfo | NutritionalInfo | nested |
| variants | MenuVariant[] | |

## NutritionalInfo
| Field | Type | Notes |
|-------|------|-------|
| calories | number | kcal per serving |
| carbs | number | g |
| protein | number | g |
| fat | number | g |
```

In `menu.md`:
```markdown
### POST /api/v1/merchant/menu/items

**Returns**: [MenuItem](./schemas.md#menuitem)

### GET /api/v1/merchant/menu/items/[id]

**Returns**: [MenuItem](./schemas.md#menuitem)
```

**Saving**: 20-30 linee JSON per endpoint × 10 endpoints = 250+ linee eliminate. Total menu.md: 1910→719 (-62%).

### Tecnica

Schemi riusati 2+ volte → sposta in `schemas.md`. Ogni endpoint linka invece di ripetere.

## Example 4 — Error Codes Enum (generic)

### Before — stringhe italiane hardcoded

```markdown
**Errors**:
- 400 "Nome sala obbligatorio"
- 400 "La capacità deve essere maggiore di zero"
- 404 "Sala non trovata"
- 409 "Esiste già una sala con questo nome"
- 403 "Non hai i permessi per questa operazione"
```

### After — error codes + central enum

In `errors.md`:
```markdown
## Booking — Rooms

| Code | HTTP | IT Message | Context |
|------|------|------------|---------|
| NAME_REQUIRED | 400 | Nome sala obbligatorio | POST/PATCH |
| INVALID_CAPACITY | 400 | Capacità non valida (deve essere >0) | POST/PATCH |
| ROOM_NOT_FOUND | 404 | Sala non trovata | GET/PATCH/DELETE |
| ROOM_DUPLICATE | 409 | Sala già esistente (nome duplicato) | POST/PATCH |
| FORBIDDEN | 403 | Permessi insufficienti | Any |
```

In `booking.md`:
```markdown
**Errors**: NAME_REQUIRED, INVALID_CAPACITY, ROOM_NOT_FOUND, ROOM_DUPLICATE, FORBIDDEN
```

### Tecnica

Error codes enum centralizzato + IT message → endpoint usa solo i codes. Vantaggi:
1. API consumers parsano codes stabili, non stringhe traducibili
2. Docs rimangono concise
3. Refactor error messages in UN SOLO POSTO

## Example 5 — PRD Compression (PRD-closedtable.md)

### Pattern: tabelle > narrative per requisiti

**Before**: "The system shall allow merchants to create booking rooms. Rooms represent physical areas of the restaurant. Each room has a name, capacity, and display order. The name must be unique within the store. The capacity must be positive..."

**After**:
```markdown
## Functional Requirements

| ID | Component | Requirement |
|----|-----------|-------------|
| FR-01 | BookingRoom | Merchant può creare room con name, capacity, order |
| FR-02 | BookingRoom | name unique per store |
| FR-03 | BookingRoom | capacity must be >0 |
```

Saving: 3-5 linee narrative → 1 linea tabella per requirement.

## Quando NON comprimere

- Sezioni con logic critica (es. state machine transitions, race condition handling): meglio prose che tabelle
- Esempi UX con dialog flow: tabella non rende
- Discussion Log / decision rationale: se compresso perde contesto
- Codice critico in code blocks: mantieni verbatim
