docs: establish project foundation and technical documentation

- Add frontend speficication with section-based layout and countdown
  states
- Add backend specification with FastAPI, SQLite WAL, and Authelia auth
  guard
- Add infrastructure specification with Traefik split-routing and appctl
  manifest
- Add project roadmap, README gitignore, and updated UNLICENSE
This commit is contained in:
kiskaadee committed 2026-09-30 20:23:02 -05:00
1 parent ba0be7d925
commit 9dbcf72295
8 files changed
+1410

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
# Dependencies
frontend/node_modules/
# Python
backend/__pycache__/
backend/**/__pycache__/
*.pyc
*.pyo
.venv/
# Build output
frontend/dist/
# Data (volume-mounted, contains SQLite DB)
data/
# Environment
.env
*.env.local
# IDE
.vscode/
.idea/
# OS
.DS_Store
Thumbs.db
View File
Whitespace-only changes.
+28
View File
@@ -1 +1,29 @@
# bdinvite
Interactive digital birthday invitation with RSVP.
## Overview
A mobile-first invitation app with animated golden bokeh particles, an RSVP form with semantic state feedback, a live countdown timer, and an admin dashboard for managing responses and invitation content.
- **Guest**: `demos.roadtotech.me/birthday/`
- **Admin**: `demos.roadtotech.me/birthday/admin` (Authelia-protected)
## Stack
| Layer | Technology |
|---|---|
| Frontend | React, Vite, TypeScript, Canvas 2D, CSS Modules |
| Backend | FastAPI, SQLAlchemy, Pydantic, SQLite (WAL) |
| Infrastructure | Docker (multi-stage), Traefik, Authelia SSO |
## Documentation
- [Frontend Specification](specs/front.md)
- [Backend Specification](specs/backend.md)
- [Infrastructure Specification](specs/infra.md)
- [Roadmap](ROADMAP.md)
## License
[Unlicense](UNLICENSE) — public domain.
+78
View File
@@ -0,0 +1,78 @@
# Roadmap
## Phase 0 — Documentation Foundation
- [x] Frontend specification
- [x] Backend specification
- [x] Infrastructure specification
- [x] Project README
- [x] Roadmap
- [x] License (Unlicense)
## Phase 1 — Backend
- [ ] Project scaffolding (`pyproject.toml`, app directory)
- [ ] SQLite database with WAL mode
- [ ] SQLAlchemy models (`RSVP`, `InvitationConfig`)
- [ ] Pydantic request/response schemas
- [ ] Config seeding and CRUD
- [ ] `POST /birthday/api/rsvp` with phone normalization
- [ ] `GET /birthday/api/config`
- [ ] Admin endpoints with `Remote-User` guard
- [ ] CSV export endpoint
- [ ] SPA catch-all route
- [ ] Backend tests
## Phase 2 — Frontend Scaffolding
- [ ] Vite + React + TypeScript setup
- [ ] React Router with `basename=/birthday`
- [ ] API client (`/birthday/api/*`)
- [ ] Config loading state (`CONFIG_LOADING` → `INVITATION` | `CONFIG_ERROR`)
- [ ] Self-hosted font files (display script + Montserrat)
- [ ] CSS Modules setup and global styles
- [ ] TypeScript interfaces for config and API responses
## Phase 3 — Guest Experience
- [ ] Invitation hero section (fixed aspect ratio)
- [ ] Canvas 2D particle background (golden bokeh)
- [ ] RSVP CTA with smooth scroll transition
- [ ] RSVP form with client-side validation (Colombian phone format)
- [ ] Submission state machine (`SUBMITTING` → `SUCCESS` | `DUPLICATE` | `ERROR`)
- [ ] Confirmation section: personalized message
- [ ] Countdown timer (timezone-aware, `NOS VEMOS EN DD:HH:MM:SS`)
- [ ] Map preview (circular static image, link to `mapUrl`)
- [ ] Venue info (compact name + address)
- [ ] `sessionStorage` post-RSVP state preservation
- [ ] Accessibility (semantic HTML, keyboard nav, aria-live, focus states)
- [ ] `prefers-reduced-motion` support (static particles)
- [ ] Responsive behavior (mobile-first, desktop stage)
## Phase 4 — Admin Dashboard
- [ ] Admin layout shell (header, navigation)
- [ ] RSVP table with total count
- [ ] Search/filter RSVPs
- [ ] CSV export download button
- [ ] Config editor form (flat fields, Pydantic-validated)
- [ ] Text preview of invitation content
## Phase 5 — Infrastructure & Deployment
- [ ] Dockerfile (multi-stage build)
- [ ] `docker-compose.yml` with split Traefik routing
- [ ] `app.yaml` manifest for `appctl`
- [ ] `.gitignore` finalized
- [ ] Local Docker build verification
- [ ] Deployment to `demos.roadtotech.me`
- [ ] Post-deployment verification
- [ ] Authelia admin route verification
## Future
- [ ] Font selection (visual comparison of candidates)
- [ ] Application-owned map preview asset (replace URL with static file)
- [ ] Miniature rendered invitation preview in admin config editor
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
- [ ] CSV import
+24
View File
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
+436
View File
@@ -0,0 +1,436 @@
# Digital Invitation — Backend Specification
> **Status:** Frozen · **Version:** 1.0 · **Date:** 2026-10-01
---
## 1. Purpose
This document is the authoritative backend specification for **bdinvite** — an interactive digital birthday invitation with RSVP functionality. Implementation follows this spec. All API contracts, data models, authentication boundaries, and runtime behaviors described herein are normative.
---
## 2. Architecture
| Concern | Technology |
|---|---|
| Application Framework | FastAPI with Uvicorn |
| Runtime | Python 3.11+ |
| Database | SQLite with WAL mode |
| ORM | SQLAlchemy 2.0 |
| Validation & Settings | Pydantic v2 / pydantic-settings |
| Dependency Management | uv |
| Base Image | `ghcr.io/astral-sh/uv:python3.11-bookworm-slim` |
The application runs as a **single container**. FastAPI serves both the API routes and the built React SPA as static files. There is no separate web server, no reverse-proxy sidecar, and no background worker process within the container.
```mermaid
flowchart LR
subgraph Container
FastAPI["FastAPI + Uvicorn"]
SQLite["SQLite (WAL)"]
SPA["React SPA (static)"]
FastAPI --> SQLite
FastAPI --> SPA
end
Client["Browser"] --> FastAPI
```
---
## 3. Directory Structure
```
backend/
├── pyproject.toml
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app, lifespan, static file mount, SPA catch-all
│ ├── config.py # Pydantic Settings (env-based)
│ ├── database.py # SQLite WAL engine, session factory, Base
│ ├── models.py # SQLAlchemy models
│ ├── schemas.py # Pydantic request/response schemas
│ ├── routes/
│ │ ├── __init__.py
│ │ ├── rsvp.py # POST /birthday/api/rsvp
│ │ ├── config.py # GET /birthday/api/config
│ │ └── admin.py # Admin endpoints
│ └── services/
│ ├── __init__.py
│ ├── rsvp.py # RSVP business logic + phone normalization
│ └── config.py # Config CRUD + seed defaults
└── tests/
├── __init__.py
├── test_rsvp.py
└── test_config.py
```
---
## 4. Database
### 4.1 Engine Configuration
- **Database file:** `/app/data/bdinvite.db`
- **Volume mount:** `./data:/app/data`
- **Connection string:** `sqlite:///./data/bdinvite.db`
- **WAL mode:** Enabled at engine creation via `PRAGMA journal_mode=WAL;`
- **Threading:** `check_same_thread=False` (required for SQLite with FastAPI's async/threaded model)
- **Table creation:** `metadata.create_all()` runs on application startup via FastAPI's lifespan handler
### 4.2 RSVP Table (`rsvps`)
| Column | Type | Constraints |
|---|---|---|
| `id` | INTEGER | PRIMARY KEY, autoincrement |
| `name` | TEXT | NOT NULL |
| `phone` | TEXT | NOT NULL, UNIQUE |
| `email` | TEXT | nullable |
| `created_at` | DATETIME | NOT NULL, default = `utcnow` |
The `phone` column stores the **normalized 10-digit Colombian number** (digits only, no country code). The `UNIQUE` constraint on `phone` enforces duplicate detection at the storage level.
### 4.3 InvitationConfig Table (`invitation_config`)
This table holds exactly **one row** (`id = 1`). The row is seeded with defaults on first startup if no row exists.
| Column | Type | Default |
|---|---|---|
| `id` | INTEGER | PRIMARY KEY (always `1`) |
| `title` | TEXT | `"Birthday Party"` |
| `invitation_text` | TEXT | `"You're invited to the birthday party honoring"` |
| `honoree_name` | TEXT | `"Isabelle Snow"` |
| `event_date` | TEXT | `"2026-10-28"` (ISO 8601 date) |
| `event_time` | TEXT | `"19:00"` (HH:MM, 24-hour) |
| `event_timezone` | TEXT | `"America/Bogota"` (IANA timezone identifier) |
| `address_name` | TEXT | `"Fresco Ristorante"` |
| `address_lines` | TEXT | `"514 S Brand Blvd\nGlendale, CA 91204"` (newline-separated) |
| `map_preview_url` | TEXT | URL to static map preview image |
| `map_url` | TEXT | Google Maps (or other map service) link |
| `rsvp_heading` | TEXT | `"¿Nos vemos?"` |
| `rsvp_cta` | TEXT | `"CONFIRMA TU ASISTENCIA"` |
| `submit_label` | TEXT | `"TE VEO AHÍ"` |
| `msg_success` | TEXT | `"¡Perfecto! Tu asistencia ha sido confirmada."` |
| `msg_success_greeting` | TEXT | `"Gracias, {name}."` (`{name}` is replaced client-side) |
| `msg_duplicate` | TEXT | `"Parece que ya tenemos tus datos registrados."` |
| `msg_error` | TEXT | `"No pudimos registrar tu asistencia. Inténtalo nuevamente."` |
| `msg_config_error` | TEXT | `"No pudimos cargar la invitación. Inténtalo nuevamente."` |
| `countdown_label` | TEXT | `"NOS VEMOS EN"` |
| `countdown_in_progress` | TEXT | `"EVENTO EN CURSO"` |
| `countdown_finished` | TEXT | `"EVENTO FINALIZADO"` |
| `updated_at` | DATETIME | UTC |
---
## 5. API Contract
All API routes are mounted under `/birthday/api/`. Admin routes are mounted under `/birthday/api/admin/`.
```mermaid
flowchart LR
subgraph Public
A["GET /birthday/api/config"]
B["POST /birthday/api/rsvp"]
end
subgraph Admin["Admin (Remote-User required)"]
C["GET /birthday/api/admin/rsvps"]
D["GET /birthday/api/admin/export"]
E["GET /birthday/api/admin/config"]
F["PUT /birthday/api/admin/config"]
end
```
### 5.1 Public Endpoints
#### `GET /birthday/api/config`
Serves the invitation configuration to the guest frontend.
- **Auth:** None (public)
- **Response `200`:** Full `InvitationConfig` object — all fields from the config table.
- **Response `500`:** `{"result": "ERROR"}` (if no config row exists — should not happen after seeding)
#### `POST /birthday/api/rsvp`
Submit an RSVP.
- **Auth:** None (public)
**Request body:**
```json
{
"name": "Andrés García",
"phone": "300 123 4567",
"email": "andres@example.com"
}
```
**Field validation:**
| Field | Required | Rules |
|---|---|---|
| `name` | Yes | Non-empty, max 100 characters, whitespace-normalized |
| `phone` | Yes | Validated as Colombian format (see §7 Phone Normalization) |
| `email` | No | Validated as email format if provided |
**Responses:**
- **`201` — Success:**
```json
{ "result": "SUCCESS", "name": "Andrés García" }
```
- **`409` — Duplicate phone:**
```json
{ "result": "DUPLICATE" }
```
- **`422` — Validation error:**
```json
{ "result": "VALIDATION_ERROR", "errors": { "phone": "Formato de teléfono inválido" } }
```
- **`500` — Server error:**
```json
{ "result": "ERROR" }
```
The `result` field is a string discriminator. The frontend switches on this value.
### 5.2 Admin Endpoints
All admin endpoints require the `Remote-User` header (injected by Authelia ForwardAuth). A missing header produces a `401` response.
#### `GET /birthday/api/admin/rsvps`
List all RSVPs.
- **Query params:** `?search=<term>` (optional) — filters by name, phone, or email substring match
- **Response `200`:**
```json
{
"count": 37,
"rsvps": [
{
"id": 1,
"name": "Ana García",
"phone": "3001234567",
"email": "ana@example.com",
"created_at": "2026-09-30T12:00:00Z"
}
]
}
```
#### `GET /birthday/api/admin/export`
Download all RSVPs as CSV.
- **Response:** `text/csv` with `Content-Disposition: attachment; filename="rsvps.csv"`
- **Columns:** `name`, `phone`, `email`, `created_at`
- **`created_at` format:** ISO 8601 UTC
#### `GET /birthday/api/admin/config`
Get full configuration. Same shape as the public `GET /birthday/api/config`.
#### `PUT /birthday/api/admin/config`
Update configuration (full object replacement).
- **Request body:** Full config object (Pydantic-validated)
- **Response `200`:** Updated config object
- **Validation rules:**
- `event_date` is a valid ISO 8601 date
- `event_time` is a valid `HH:MM` (24-hour) string
- `event_timezone` is a valid IANA timezone identifier
- URL fields are valid URLs
- Text fields are non-empty where required
---
## 6. Error Handling
The backend never exposes raw exceptions, SQL errors, or stack traces to the client. A global exception handler catches unhandled exceptions and returns the generic `ERROR` response.
| Scenario | HTTP Status | Response Body |
|---|---|---|
| Successful RSVP | `201` | `{"result": "SUCCESS", "name": "..."}` |
| Duplicate phone | `409` | `{"result": "DUPLICATE"}` |
| Validation failure | `422` | `{"result": "VALIDATION_ERROR", "errors": {...}}` |
| Unexpected error | `500` | `{"result": "ERROR"}` |
| Unauthenticated admin | `401` | `{"detail": "Not authenticated"}` |
---
## 7. Phone Normalization
All phone numbers are normalized to **10-digit Colombian mobile format** before storage and uniqueness checks.
**Algorithm:**
1. Strip all non-digit characters (spaces, dashes, parentheses, plus sign).
2. If the resulting digit string starts with `"57"` **and** has exactly 12 digits, remove the `"57"` prefix (country code).
3. The result must be exactly **10 digits** AND start with `"3"`.
4. If either condition fails: return validation error with message `"Formato de teléfono inválido"`.
**Examples:**
| Input | Normalized | Valid |
|---|---|---|
| `"+57 300 123 4567"` | `3001234567` | ✓ |
| `"300-123-4567"` | `3001234567` | ✓ |
| `"3001234567"` | `3001234567` | ✓ |
| `"(300) 123 4567"` | `3001234567` | ✓ |
| `"57300123 4567"` | `3001234567` | ✓ |
| `"123456"` | — | ✗ (not 10 digits) |
| `"1234567890"` | — | ✗ (doesn't start with `3`) |
| `"+1 555 123 4567"` | — | ✗ (not Colombian format) |
---
## 8. Duplicate Detection
A submission is a duplicate if the **normalized phone number** matches an existing RSVP record. Phone is the unique identifier because:
- Phone is **required** — every RSVP has one.
- Email is **optional** — cannot be relied on for deduplication.
- Name alone is **insufficient** — common names exist.
The `UNIQUE` constraint on the `phone` column enforces this at the storage level. The service layer catches the `IntegrityError` from SQLAlchemy and returns the `DUPLICATE` result.
---
## 9. Config Management
- The invitation configuration is a **singleton row** (`id = 1`) in the `invitation_config` table.
- On application startup (FastAPI lifespan), if no config row exists, seed it with defaults.
- `GET /birthday/api/config` returns the current config for the guest frontend.
- `PUT /birthday/api/admin/config` replaces the config (full object replacement, Pydantic-validated).
- The frontend fetches config on page load and renders the invitation from it.
- Changes via the admin dashboard take effect **immediately** — no cache, no restart required.
---
## 10. Admin Authentication
There is **no** app-level login page, JWT, session management, or password handling.
Authentication is delegated entirely to **Authelia** at the Traefik reverse proxy level:
1. Authelia's ForwardAuth middleware intercepts requests to `/birthday/admin/*`.
2. After successful authentication, Authelia injects headers: `Remote-User`, `Remote-Email`, `Remote-Groups`, `Remote-Name`.
3. The backend reads and verifies these headers on every admin request.
> **Security Invariant:** Every admin API endpoint independently verifies the `Remote-User` header. No admin endpoint relies on React routing, URL obscurity, or browser-side authorization for security.
**Implementation:**
```python
from fastapi import Depends, Header, HTTPException
def require_admin(remote_user: str | None = Header(None, alias="Remote-User")):
if not remote_user:
raise HTTPException(status_code=401, detail="Not authenticated")
return remote_user
# Usage: every admin route depends on this
@router.get("/rsvps")
def list_rsvps(admin: str = Depends(require_admin), db: Session = Depends(get_db)):
...
```
---
## 11. Timestamp Policy
Two distinct timestamp domains exist in this application:
### 11.1 Persistence Timestamps
`created_at` and `updated_at` are **always UTC**. Stored as UTC in the database. The backend uses `datetime.utcnow()` or equivalent. The frontend/admin converts to display timezone as needed.
### 11.2 Event Date/Time
`event_date`, `event_time`, and `event_timezone` are stored as **separate fields** representing a locale-specific instant:
| Field | Format | Example |
|---|---|---|
| `event_date` | ISO 8601 date | `"2026-10-28"` |
| `event_time` | HH:MM (24-hour) | `"19:00"` |
| `event_timezone` | IANA timezone | `"America/Bogota"` |
The frontend constructs a timezone-aware instant from these three fields for countdown calculation.
These are **separate concerns**. Persistence timestamps are infrastructure; event time is business data.
---
## 12. SPA Serving
FastAPI serves the built React application. **Registration order matters:**
1. API routes are registered first (prefix `/birthday/api/` and `/birthday/api/admin/`).
2. Static assets are mounted at `/birthday/assets/` (Vite build output directory).
3. A catch-all route serves `static/index.html` for any `/birthday/{path}` not matching API or asset routes.
This enables React Router client-side routing under `/birthday/`.
```python
# Order matters:
app.include_router(rsvp_router, prefix="/birthday/api")
app.include_router(config_router, prefix="/birthday/api")
app.include_router(admin_router, prefix="/birthday/api/admin")
app.mount("/birthday/assets", StaticFiles(directory="static/assets"), name="assets")
@app.get("/birthday/{full_path:path}")
async def spa_catch_all(full_path: str):
return FileResponse("static/index.html")
```
---
## 13. Application Settings
Environment-based configuration via Pydantic Settings. Values are overridable via environment variables or a `.env` file.
```python
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
SERVICE_NAME: str = "bdinvite"
SERVICE_DOMAIN: str = "demos.roadtotech.me"
BASE_PATH: str = "/birthday"
APP_PORT: int = 8000
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
```
---
## 14. Dependencies
```toml
[project]
name = "bdinvite"
version = "0.1.0"
description = "Birthday Invitation RSVP Backend"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115.0",
"uvicorn>=0.30.0",
"sqlalchemy>=2.0.0",
"pydantic>=2.0.0",
"pydantic-settings>=2.0.0",
]
[dependency-groups]
dev = [
"httpx>=0.27.0",
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
]
```
+448
View File
@@ -0,0 +1,448 @@
# Digital Invitation — Frontend Specification
## 1. Purpose
A responsive, mobile-first digital birthday invitation that reproduces the visual character of a physical invitation while adding an interactive RSVP flow.
The application has two distinct experiences:
### Guest Experience
A highly designed invitation served publicly at `/birthday/`, consisting of:
1. **Invitation hero**: Fixed-aspect-ratio vertical composition with animated golden bokeh particles, title, honoree, date/time, and RSVP call-to-action
2. **RSVP form**: Name, phone, and optional email fields matching the invitation's visual world
3. **Submission feedback**: Explicit semantic feedback (Success, Duplicate, Error)
4. **Event reminder & logistics**: Countdown timer to the event, circular map preview, venue details, and navigation link
### Admin Experience
A simple dashboard served at `/birthday/admin` (Authelia-protected) allowing the event organizer to:
1. View invitee responses in a searchable table
2. Monitor response count
3. Export responses as CSV
4. Edit invitation copy and event logistics via a form with live text preview
The guest experience is the primary design focus. The admin dashboard deliberately does **not** use the invitation's visual effects.
---
## 2. Design Principles
### 2.1 The Invitation is a Physical Object (Section-Based Composition)
The invitation hero maintains a fixed vertical aspect ratio (9:16) regardless of viewport width. The browser provides a responsive **stage** around it on wider screens.
The page itself is a scrollable viewport composed of discrete sections:
```text
PAGE (Scrollable Viewport)
│
├── Invitation Hero Section (Fixed vertical aspect ratio, desktop stage)
│
├── RSVP Section (Revealed via CTA click, matching visual world)
│
└── Confirmation Section (Replaces RSVP on success; countdown + logistics)
```
The invitation hero itself is **not** an overflow-scrolling container. The page scrolls smoothly across these visual sections, maintaining balanced compositions within each viewport.
```text
Desktop Stage
┌────────────────────────────────────────────┐
│ │
│ ┌──────────────────┐ │
│ │ │ │
│ │ INVITATION │ (9:16 card) │
│ │ HERO │ │
│ │ │ │
│ └──────────────────┘ │
│ │
└────────────────────────────────────────────┘
```
On mobile, the section expands to occupy the available width while preserving vertical proportions.
---
### 2.2 One Visual Composition
There are not separate mobile and desktop invitation designs. The visual card scales responsively within the viewport. Desktop provides surrounding staging; mobile provides full viewport width to the invitation.
---
### 2.3 Decoration Must Not Interfere with Information
The animated particle background is subordinate to content:
- Particles concentrate toward upper-left and lower-right corners
- The central content area remains substantially darker and sparse
- Movement is extremely slow (ambient life, not spectacle)
- Particles vary in radius, opacity, and soft golden blur
- Never compromises text readability
---
### 2.4 The RSVP Interaction is Part of the Invitation
The RSVP form and confirmation states inherit the invitation's visual identity:
- Dark background (`#0a0a0a`)
- Golden accents (`#d4a843`, `#f0d68a`)
- Typography system
- Ambient particle canvas spanning the entire page behind all sections
---
### 2.5 Content is Configuration, Not Code
Event-specific copy is never hardcoded in presentation components:
- Fetched on load from `GET /birthday/api/config`
- Admin can modify event details dynamically without rebuilding the frontend
---
### 2.6 Explicit Configuration Loading & Error States
Before rendering the invitation, the frontend manages configuration lifecycle explicitly:
```text
CONFIG_LOADING
│
├── success ──────→ INVITATION
│
└── failure/error ─→ CONFIG_ERROR
```
If the API fails to load or returns invalid data:
- Renders a graceful fallback:
> **No pudimos cargar la invitación.**
> Inténtalo nuevamente.
- Includes a retry button
- Never exposes broken components or undefined text values to the guest
---
### 2.7 Typography System (Self-Hosted)
The design contrasts an organic handwritten script with a clean geometric sans-serif:
- **Display Script**: Configurable script font (candidates: Great Vibes, Alex Brush, Sacramento, Allison, Whisper) used for "Birthday Party" and the honoree name
- **Body & Metadata**: Montserrat (weights 300, 400, 500, 600, 700) with generous letter-spacing for dates, labels, and copy
- **Self-Hosted Invariant**: All web fonts are bundled and served from `/birthday/fonts/` (WOFF2 format) to ensure deterministic rendering and zero third-party CDN dependencies
---
## 3. Guest Experience Lifecycle
```text
PAGE LOAD
│
▼
CONFIG_LOADING
│ │
fail │ │ success
▼ ▼
CONFIG_ERROR INVITATION HERO
│
CTA click (smooth scroll)
│
▼
RSVP FORM
│
submit
│
▼
SUBMITTING
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
SUCCESS DUPLICATE ERROR
│ │ │
▼ ▼ ▼
CONFIRMATION "¡UPS!" "ALGO SALIÓ
& COUNTDOWN (duplicate) MAL"
│ │
▼ ▼
MAP & LOGISTICS (retry)
```
---
## 4. State 1 — Invitation Hero
Displays the invitation cover in a centered 9:16 stage:
```text
┌─────────────────────────────┐
│ │
│ Birthday Party │ ← Display Script
│ │
│ YOU'RE INVITED TO THE │ ← Montserrat, tracked
│ BIRTHDAY PARTY HONORING │
│ │
│ Isabelle Snow │ ← Display Script
│ │
│ OCT 7:00 PM │ ← Montserrat, 500
│ 28 FRIDAY │
│ │
│ │
│ CONFIRMA TU ASISTENCIA │ ← CTA Button
│ ↓ │
│ │
└─────────────────────────────┘
```
The address is intentionally omitted from the hero to focus attention on the RSVP action.
---
## 5. RSVP Call-To-Action (CTA)
Default copy:
> **CONFIRMA TU ASISTENCIA**
> ↓
Interaction:
- Click or keyboard activation smoothly scrolls the viewport to the RSVP section
- Focus is moved to the first input field
- Fully keyboard accessible (`<button>` with visible `:focus-visible` gold ring)
- Supports `prefers-reduced-motion` (instant jump instead of smooth scroll)
---
## 6. State 2 — RSVP Form
Appears below the invitation hero section:
```text
┌─────────────────────────────┐
│ │
│ ¿NOS VEMOS? │
│ │
│ NOMBRE COMPLETO │
│ [_______________________] │
│ │
│ TELÉFONO (MÓVIL) │
│ [_______________________] │
│ │
│ CORREO · OPCIONAL │
│ [_______________________] │
│ │
│ TE VEO AHÍ │
│ │
└─────────────────────────────┘
```
### Form Fields & Validation
1. **Full Name (`name`)**:
- Required, trimmed, max 100 characters
- Inline error: *"Por favor, ingresa tu nombre completo."*
2. **Phone Number (`phone`)**:
- Required
- Validated against Colombian mobile format: 10 digits starting with `3` (e.g. `300 123 4567` or `+57 300 123 4567`)
- Normalization removes non-digits and leading `57` country code before submission
- Inline error: *"Ingresa un número móvil válido (10 dígitos)."*
3. **Email (`email`)**:
- Optional
- If provided, validated against standard email format
- Inline error: *"Ingresa un correo electrónico válido."*
4. **Submit Button (`submit_label`)**:
- Default: *"TE VEO AHÍ"* (configurable)
- Disables during submission to prevent double submits
---
## 7. Submission State
When submitted:
1. Inputs are disabled
2. Submit button shows loading spinner or text: *"ENVIANDO..."*
3. Form dispatches `POST /birthday/api/rsvp`
4. Evaluates the semantic response discriminator
---
## 8. State 3 — Submission Responses
### 8.1 Successful Submission & Confirmation
When backend returns `{ "result": "SUCCESS", "name": "..." }`:
- Viewport smoothly transitions into the **Confirmation Section**
- Saves a session marker in browser storage:
```ts
sessionStorage.setItem('bdinvite:rsvp-submitted', JSON.stringify({
name: data.name,
timestamp: Date.now()
}));
```
- If the guest refreshes the page during the session, the confirmation section is displayed immediately, avoiding duplicate prompt friction.
#### Visual Hierarchy & Layout:
```text
┌─────────────────────────────┐
│ │
│ │
│ ¡PERFECTO! │
│ │
│ Tu asistencia ha sido │
│ confirmada. │
│ │
│ Gracias, Andrés. │
│ │
│ · │
│ · │
│ NOS VEMOS EN │
│ 12 : 04 : 37 : 22 │
│ │
│ · │
│ │
│ ╭──────╮ │
│ ╭─┤ ├─╮ │
│ │ │ MAP │ │ │
│ ╰─┤ ├─╯ │
│ ╰──────╯ │
│ │
│ FRESCO RISTORANTE │
│ 514 S Brand Blvd │
│ Glendale, CA 91204 │
│ │
│ VER UBICACIÓN ↗ │
│ │
└─────────────────────────────┘
```
---
## 9. Countdown Component
The countdown calculates remaining time against the event's **absolute instant** using its configured IANA timezone (`America/Bogota`):
```ts
interface EventTimeConfig {
event_date: string; // "2026-10-28"
event_time: string; // "19:00"
event_timezone: string; // "America/Bogota"
}
```
The countdown does **not** assume hardcoded UTC offsets. It computes the target instant in UTC using browser timezone utilities (`Intl.DateTimeFormat`):
```text
targetInstant = parseInTimezone(event_date, event_time, event_timezone)
remainingMs = targetInstant - Date.now()
```
### Countdown Display States:
1. **Before Event** (`remainingMs > 0`):
```text
NOS VEMOS EN
12 : 04 : 37 : 22
(Días : Horas : Min : Seg)
```
2. **Event Day / In Progress** (within event duration window):
```text
EVENTO EN CURSO
```
3. **Event Concluded**:
```text
EVENTO FINALIZADO
```
---
## 10. Map Preview & Location Details
The map is rendered as a clean, circular preview widget linked to the external navigation destination:
- **Treatment**: Circular crop (~140px diameter), subtle golden border `1px solid rgba(212, 168, 67, 0.3)`
- **Hover/Active**: Scales smoothly (`transform: scale(1.05)`), border brightens
- **Venue Copy**: Clean text block listing venue name and address
- **External Link**: Text link `VER UBICACIÓN ↗` opening `map_url` in a new tab (`target="_blank" rel="noopener noreferrer"`)
- **Asset**: Uses `map_preview_url` (v1 configurable URL, architected for future self-hosted static asset)
---
## 11. Duplicate Submission State
When backend returns `{ "result": "DUPLICATE" }`:
- Form presents the duplicate feedback message:
> **¡UPS!**
> Parece que ya tenemos tus datos registrados.
> Si necesitas modificar tu información, ponte en contacto con nosotros.
- Does not expose existing database records or personal details
- Offers a button to return to the invitation or edit fields
---
## 12. Unexpected Error & Network Failure
When backend returns `{ "result": "ERROR" }` or fetch throws a network exception:
- Message:
> **ALGO SALIÓ MAL**
> No pudimos registrar tu asistencia. Inténtalo nuevamente.
- Button: **INTENTAR DE NUEVO**
- Preserves user input values so the user does not have to retype their details
---
## 13. Particle Background Engine
Implemented on an HTML5 `<canvas>` element:
- Positioned fixed behind all page sections (`z-index: 0`, `pointer-events: none`)
- Canvas dimensions dynamically track `window.innerWidth` and `window.innerHeight`
### Particle Attributes
```ts
interface Particle {
x: number;
y: number;
radius: number; // 2px - 10px
opacity: number; // 0.15 - 0.7
blur: number; // 2px - 12px
goldHue: number; // Warm gold to soft amber
vx: number; // -0.15 to +0.15 px/frame
vy: number; // -0.15 to +0.15 px/frame
twinkleSpeed: number; // 0.005 - 0.02
twinklePhase: number; // 0 to 2π
}
```
### Spatial Distribution
- Weighted random distribution:
- 40% probability: Upper-left quadrant
- 40% probability: Lower-right quadrant
- 20% probability: Uniformly sparse across center
- Particle density: ~120 on viewport > 768px; ~80 on mobile viewports
### Accessibility / Reduced Motion
- If `@media (prefers-reduced-motion: reduce)` is detected:
- Renders a single static frame of particles
- Animation loop is halted immediately
- Smooth scroll behavior reverts to immediate jump
---
## 14. Admin Experience
Served under route `/birthday/admin` and protected at the reverse-proxy level by Authelia ForwardAuth.
### 14.1 RSVP Table View
- **Total Count**: Live tally of confirmed invitees
- **Search Bar**: Substring filtering by name, phone, or email
- **Table Columns**:
- Name
- Phone (formatted Colombian mobile)
- Email (or em-dash if omitted)
- Submission Date/Time (converted from UTC to browser-local)
- **CSV Export**: *"Descargar CSV"* button triggering `GET /birthday/api/admin/export`
### 14.2 Configuration Editor
A flat form allowing the host to edit dynamic invitation data:
- Honoree Name
- Event Date, Event Time, Event Timezone
- Invitation Title & Intro Copy
- Venue Name & Address Lines
- Map Preview URL & External Map URL
- RSVP Button Copy & Feedback Messages
Includes a **Text Preview** block showing the hierarchical composition of the text fields before saving.
---
## 15. Routing & URL Structure
The application operates with base path `/birthday/` via React Router:
- `/birthday/` → Guest experience (Invitation hero, RSVP flow, Confirmation)
- `/birthday/admin` → Admin dashboard (RSVP table, CSV export)
- `/birthday/admin/config` → Invitation configuration editor
- `*` → Redirects to `/birthday/`
+369
View File
@@ -0,0 +1,369 @@
# Digital Invitation — Infrastructure Specification
> **Status**: Frozen · **Workload**: `bdinvite` · **Host**: `roadtotech.me` (NixOS homelab)
---
## 1. Platform Context
The application runs on the `roadtotech.me` homelab appliance — a NixOS server providing:
| Component | Role |
|---|---|
| **Traefik v3.6** | Reverse proxy with wildcard DNS/TLS for `*.roadtotech.me` (ACME DNS-01 via Dynu) |
| **Authelia** | SSO with LLDAP backend; session cookies valid across `*.roadtotech.me` |
| **`appctl`** | Orchestration tool for Sites workloads (reads `app.yaml` manifests, injects env, controls Docker Compose) |
| **Docker Compose** | Container lifecycle management |
| **`proxy-net`** | External Docker network shared between Traefik and workload containers |
The application lives at `~/Sites/bdinvite` on the server.
---
## 2. Container Architecture
A **single container** produced by a multi-stage Docker build:
- **Stage 1** (`node:20-alpine`): Builds the React frontend (`npm ci` → `npm run build`)
- **Stage 2** (`ghcr.io/astral-sh/uv:python3.11-bookworm-slim`): Runs FastAPI with uvicorn; frontend build output (`dist/`) is copied in as `./static`
| Property | Value |
|---|---|
| Container name | `bdinvite` |
| Internal port | `8000` |
| Volume mount | `./data:/app/data` (SQLite persistence) |
| Restart policy | `unless-stopped` |
---
## 3. Dockerfile
```dockerfile
# Stage 1: Build React frontend
FROM node:20-alpine AS frontend-build
WORKDIR /build
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
# Stage 2: Python runtime
FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1
COPY backend/pyproject.toml backend/uv.lock* ./
RUN uv sync --frozen --no-install-project --no-dev
COPY backend/ .
COPY --from=frontend-build /build/dist ./static
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
```
---
## 4. Traefik Routing
This application uses **path-based routing** on `demos.roadtotech.me`. Three Traefik routers are defined on the same container, all targeting a single service (`bdinvite-svc`) on container port 8000.
`demos.roadtotech.me` is covered by the existing wildcard DNS (`*.roadtotech.me`) and wildcard TLS certificate. No Core/NixOS changes are required.
### 4.1 Public Router — `bdinvite-public` (priority 10)
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday`)`` |
| Entrypoint | `websecure` (port 443) |
| TLS | Enabled (wildcard cert from ACME DNS-01) |
| Middleware | *None* — **public access** |
| Priority | 10 |
Catches all `/birthday/*` traffic that does not match a higher-priority router.
### 4.2 Admin Router — `bdinvite-admin` (priority 20)
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday/admin`)`` |
| Entrypoint | `websecure` (port 443) |
| TLS | Enabled |
| Middleware | `authelia-auth@docker` (ForwardAuth) |
| Priority | 20 |
Higher priority ensures `/birthday/admin/*` requests are intercepted before the generic public router.
### 4.3 HTTP Redirect Router — `bdinvite-red`
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday`)`` |
| Entrypoint | `web` (port 80) |
| Middleware | `https-redirect@docker` |
Redirects all HTTP traffic to HTTPS.
---
## 5. Authelia Integration
Authelia runs as a core infrastructure service (container: `authelia`, internal port 9091) on `proxy-net`. The ForwardAuth middleware is defined on the Traefik container:
```yaml
- "traefik.http.middlewares.authelia-auth.forwardauth.address=http://authelia:9091/api/verify?rd=https://auth.${DOMAIN}/"
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
```
### 5.1 Admin Authentication Flow
```
1. User visits https://demos.roadtotech.me/birthday/admin
2. Traefik matches bdinvite-admin router (priority 20)
3. Traefik forwards request to Authelia at http://authelia:9091/api/verify
4. IF unauthenticated:
→ Authelia returns 401
→ Traefik redirects browser to https://auth.roadtotech.me/?rd=https://demos.roadtotech.me/birthday/admin
5. User authenticates at Authelia portal
6. Authelia sets authelia_session cookie (valid across *.roadtotech.me)
7. Subsequent requests:
→ Authelia returns 200
→ Traefik forwards identity headers to the backend:
Remote-User, Remote-Email, Remote-Groups, Remote-Name
8. Backend reads Remote-User header to identify the admin
```
The backend performs **no authentication of its own** — no login page, no JWT, no session management.
---
## 6. docker-compose.yml
```yaml
services:
bdinvite:
build: .
container_name: bdinvite
restart: unless-stopped
volumes:
- ./data:/app/data
environment:
- BASE_PATH=/birthday
networks:
- proxy-net
labels:
- "diun.enable=false"
- "traefik.enable=true"
# Public router (invitation + public API)
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
- "traefik.http.routers.bdinvite-public.tls=true"
- "traefik.http.routers.bdinvite-public.priority=10"
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
# HTTP to HTTPS redirect
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-red.entrypoints=web"
- "traefik.http.routers.bdinvite-red.middlewares=https-redirect@docker"
# Service target
- "traefik.http.services.bdinvite-svc.loadbalancer.server.port=8000"
networks:
proxy-net:
external: true
```
---
## 7. appctl Manifest (app.yaml)
```yaml
name: "bdinvite"
aliases:
- "birthday"
- "invite"
domain: "demos.roadtotech.me"
description: "Interactive Digital Birthday Invitation with RSVP"
visible: true
auth: false
networks:
- proxy-net
env:
BASE_PATH: "/birthday"
homepage:
title: "Birthday Invite"
group: "Applications"
icon: "party.png"
container: "bdinvite"
weight: 30
```
`auth: false` because the public guest route exists. Authelia protection is applied selectively via Traefik labels, not universally to the entire domain.
### 7.1 Injected Environment Variables
`appctl` injects these standard environment variables from the manifest:
| Variable | Value |
|---|---|
| `SERVICE_NAME` | `bdinvite` |
| `CONTAINER_NAME` | `bdinvite` |
| `SERVICE_DOMAIN` | `demos.roadtotech.me` |
| `DOMAIN` | `demos.roadtotech.me` |
| `PROXY_NETWORK` | `proxy-net` |
| `BASE_PATH` | `/birthday` |
Additional secrets are sourced from `/run/secrets/traefik-deployments.env`.
---
## 8. Network Topology
```
Guest Browser
│
▼ HTTPS
demos.roadtotech.me (Traefik :443)
│
├─ /birthday/* (priority 10, public)
│ │
│ ▼
│ bdinvite:8000 (FastAPI)
│
└─ /birthday/admin/* (priority 20, Authelia)
│
▼ ForwardAuth
authelia:9091
│
├── 200 OK → bdinvite:8000 (+ Remote-User header)
│
└── 401 → redirect to auth.roadtotech.me
```
All containers communicate over the `proxy-net` external Docker network. Traefik discovers routing configuration via Docker labels on the `bdinvite` container.
---
## 9. Local Development
### 9.1 Backend Only
```bash
cd backend
uv sync --dev
uv run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```
### 9.2 Frontend Only (Separate Terminal)
```bash
cd frontend
npm install
npm run dev
```
Vite's dev server proxies `/birthday/api` to `http://localhost:8000`.
### 9.3 Full Docker Build
```bash
cd Sites/bdinvite
docker compose build
docker compose up -d
curl -s http://localhost:8000/birthday/api/config | python3 -m json.tool
```
---
## 10. Deployment Procedure
The user owns all production transitions. Agents provide deployment runbooks but never execute deployment commands.
After changes are validated locally:
1. Commit changes on feature branch
2. Push to Gitea remote
3. Merge to `main` (user action)
4. On server:
```bash
cd ~/Sites/bdinvite
git fetch && git pull origin main
appctl restart bdinvite
# Or for full rebuild:
docker compose up -d --build
```
Or via `appctl`:
```bash
appctl update bdinvite
```
`appctl update` performs: verify clean working tree → `git pull --ff-only` → `docker compose pull` → `docker compose up -d` → `appctl sync`.
---
## 11. Post-Deployment Verification
```bash
# Container status
ssh server-local "docker ps -a | grep bdinvite"
# Container logs
ssh server-local "docker logs --tail 20 bdinvite"
# API health
ssh server-local "curl -s http://localhost:8000/birthday/api/config | python3 -m json.tool"
# Public access (returns HTML)
curl -s https://demos.roadtotech.me/birthday/ | head -5
# Authelia protection (redirects to auth portal)
curl -sI https://demos.roadtotech.me/birthday/admin
# Admin API without auth (returns 401)
curl -sI https://demos.roadtotech.me/birthday/api/admin/rsvps
# appctl status
ssh server-local "appctl info bdinvite"
```
---
## 12. Rollback Procedure
```bash
# On server:
cd ~/Sites/bdinvite
git log --oneline -5 # identify previous good commit
git checkout <commit-hash>
docker compose up -d --build
# Verify rollback:
ssh server-local "docker logs --tail 10 bdinvite"
curl -s https://demos.roadtotech.me/birthday/api/config
# If database migration issues, restore from backup:
# (SQLite file is in ./data/bdinvite.db)
cp data/bdinvite.db.bak data/bdinvite.db
docker compose restart
```
---
## 13. Data Persistence
| Item | Detail |
|---|---|
| Database | SQLite at `./data/bdinvite.db` (volume-mounted via `./data:/app/data`) |
| Git tracking | `data/` directory is gitignored |
| Backups | Operator responsibility |
| WAL mode files | `-wal` and `-shm` are transient; managed by SQLite |