docs(api): align SRS v1.1, architecture, ADRs 0001-0005, and AGENTS.md technical blueprint
- Document separated booking/payment state engine, 48-hour payment follow-up queue, and deliberate slot release in SRS.md and architecture.md. - Add ADR-0005 for server-side Google OAuth2 and Turso admin_allowlist. - Rewrite AGENTS.md as a local technical blueprint defining SQLModel + Repository layers, pytest-mock boundaries, and mutmut audits. Refs: #1, #3, #6
This commit is contained in:
1 parent
3be395a594
commit
20eb811687
9 files changed
+319
-229
No files matched your search
@@ -1,52 +1,62 @@
|
||||
# Armonía del Ser: API - Agent Guidelines & Workflow Rules
|
||||
# Repository Technical Blueprint: `armonia-api`
|
||||
|
||||
This document specifies mandatory workflows, constraints, and verification gates for AI agents operating in `armonia-api`.
|
||||
This file defines the local toolchain, code implementation boundaries, testing invariants, and structural index for `armonia-api`. For cross-repo Git branching rules, TDD lifecycle, or Gitea (`tea`) issue tracking, consult the workspace root [`../AGENTS.md`](../AGENTS.md).
|
||||
|
||||
---
|
||||
|
||||
## 1. Core Operating Constraints
|
||||
## 1. Local Toolchain & Nix Environment (`flake.nix` + `uv`)
|
||||
|
||||
- **No Direct Commits to `main`**: Agents must never commit directly to `main`. All work must be developed on descriptive feature, bugfix, or chore branches (`feat/*`, `fix/*`, `chore/*`).
|
||||
- **No Destructive Git Actions**: Commands such as `git reset --hard`, `git restore <file>`, `git clean -fd`, and force-pushes (`git push --force`) are strictly prohibited without the user's explicit yes.
|
||||
- **Secret Redaction**: Never print, commit, or log sensitive information (Turso tokens, GCP credentials, API keys).
|
||||
- **Session Modes**:
|
||||
- `learning`: The user drives and writes the reasoning, the agent asks guiding questions.
|
||||
- `delivery`: The agent may draft code and plans, presenting rationale and trade-offs.
|
||||
This repository is provisioned via a declarative Nix `devShell` (`flake.nix` + `.envrc`) and managed exclusively via `uv`.
|
||||
- **Nix DevShell:** Ensure commands run inside the Nix environment (`direnv` activates automatically on `cd`, or prefix with `nix develop -c <cmd>`).
|
||||
- **Package Management:** Do not invoke raw `python`, `pip`, or `virtualenv` commands directly. Always use `uv run`, `uv add`, or `uv sync` so `pyproject.toml` and `uv.lock` remain synchronized.
|
||||
- **Verification Gates (Pre-Commit Checklist):**
|
||||
Before proposing or executing any commit, run and pass all four checks with zero errors or warnings:
|
||||
```bash
|
||||
uv run ruff format --check .
|
||||
uv run ruff check .
|
||||
uv run pyright
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Verification Gates (Pre-Commit Checklist)
|
||||
## 2. Codebase Implementation Rules & Layered Architecture
|
||||
|
||||
Before proposing or executing any commit, run and verify:
|
||||
To keep `armonia-api` infrastructure-agnostic (portable across Turso `libSQL`, local SQLite, PostgreSQL, or future storage engines), enforce strict separation of concerns across `app/`:
|
||||
|
||||
1. **Ruff Formatting**:
|
||||
```bash
|
||||
uv run ruff format --check .
|
||||
```
|
||||
2. **Ruff Linting**:
|
||||
```bash
|
||||
uv run ruff check .
|
||||
```
|
||||
3. **Static Type Checking (Pyright)**:
|
||||
```bash
|
||||
uv run pyright
|
||||
```
|
||||
4. **Automated Test Suite (Pytest)**:
|
||||
```bash
|
||||
uv run pytest
|
||||
```
|
||||
### Routers (`app/routers/`)
|
||||
- **HTTP Transport Only:** Routers handle path/query parameters, request schema validation, FastAPI auth dependencies (`require_admin`), HTTP status codes, and response serialization.
|
||||
- **Zero Direct Data Access:** Never embed raw SQL statements or direct ORM `Session` queries inside router endpoints. Delegate business workflows to `app/services/` and persistence to `app/repositories/`.
|
||||
|
||||
No commit may be generated if any of these checks fail or report unhandled errors.
|
||||
### Services (`app/services/`)
|
||||
- **Consumer-Agnostic Domain Logic:** Business rules (48-hour follow-up evaluation, 1-on-1 mandatory buffer collision math, WhatsApp deep-link generation, and Google Calendar synchronization) live in `app/services/`.
|
||||
- **Framework Independence:** Keep service functions decoupled from `fastapi.Depends` and HTTP exceptions so CLI scripts, background jobs, or tests can invoke them directly.
|
||||
|
||||
### Repositories & Models (`app/repositories/` & `app/models/`)
|
||||
- **Data Access Boundary:** Repositories encapsulate all database reads/writes and translate between `SQLModel` table rows and domain/schema objects.
|
||||
- **Engine Portability:** Configure database connectivity in `app/db/database.py` using `SQLModel` + `sqlalchemy-libsql` (`sqlite+libsql://` for Turso Cloud, falling back cleanly to `sqlite:///local.db` for local execution).
|
||||
|
||||
### Schemas (`app/schemas/`)
|
||||
- **Strict API Contracts:** Maintain explicit Pydantic v2 / SQLModel schemas separating input payloads (`*Create`, `*Update`, `*Request`) from output responses (`*Read`, `*Response`).
|
||||
|
||||
### Core & Auth (`app/core/`)
|
||||
- **Server-Side Security Boundary:** Google OAuth secrets, HMAC session signing, and Turso `admin_allowlist` + `admin_audit_log` verification (`app/core/auth.py`) remain strictly server-side.
|
||||
|
||||
---
|
||||
|
||||
## 3. Architecture & Domain Directives
|
||||
## 3. Local Test Invariants (`tests/`)
|
||||
|
||||
- **Database Abstraction**: Use `libsql-client` with clean fallback to local SQLite (`file:local.db`). In local testing, tests run against in-memory or temporary local SQLite instances without needing cloud credentials.
|
||||
- **Anti-Ghosting Booking State Machine**:
|
||||
- `PENDING_PAYMENT`: Initial state upon client reservation. Slot held tentatively for 2 hours.
|
||||
- `CONFIRMED`: Acknowledged by Jazmin via the Admin Dashboard after checking bank deposit.
|
||||
- `EXPIRED`: Automatic timeout if no SPEI proof is acknowledged.
|
||||
- `CANCELLED`: Explicit cancellation.
|
||||
- `NO_SHOW`: Marked if client failed to attend.
|
||||
- **Consumer Agnostic**: Keep service functions and database queries decoupled from the FastAPI routers so they can be seamlessly consumed by an MCP server, WhatsApp webhook worker, or background job runner in the future.
|
||||
- **Real Local SQLite for Persistence Tests:** Integration and repository tests must run against an isolated local SQLite instance (`file:test_armonia.db` / `sqlite:///test_armonia.db` configured in `tests/conftest.py`). Never make network requests to live Turso Cloud clusters during `pytest` runs, and never mock out SQL/database queries in repository tests (which creates tautological tests).
|
||||
- **Mocking External I/O Boundaries (`pytest-mock`):** Always isolate external network side-effects—specifically Google Calendar API synchronization (`app/services/calendar.py`) and external OAuth token exchanges—using `pytest-mock` (`mocker` fixture) so the test suite runs deterministically offline.
|
||||
- **Fixtures Policy:** Centralize database lifecycle setup, test clients, and mock administrator principals inside `tests/conftest.py`.
|
||||
- **Mutation Testing Audit (`mutmut`):** Once domain rules are extracted into `app/services/`, use `mutmut` (`uv run mutmut run`) scoped to `app/services/` as a pre-PR quality audit to verify that unit tests catch boundary and off-by-one mutations (e.g., 15-minute buffer collision intervals and 48-hour follow-up cutoffs).
|
||||
|
||||
---
|
||||
|
||||
## 4. Local Structural Maps & Documentation Index
|
||||
|
||||
Before modifying domain rules, state transitions, or database schemas, read these canonical specifications to prevent logic drift:
|
||||
- **Software Requirements Specification:** [`docs/SRS.md`](./docs/SRS.md)
|
||||
- **System Topology & State Machines (Booking / Payment / 48h Queue):** [`docs/architecture.md`](./docs/architecture.md)
|
||||
- **Architectural Decision Records (ADRs):** [`docs/decisions/0001-*.md`](./docs/decisions/) through [`0005-*.md`](./docs/decisions/)
|
||||
- **Relational Schema Reference:** [`app/db/schema.sql`](./app/db/schema.sql) (and `app/models/` during/after the SQLModel migration)
|
||||
@@ -1,45 +1,44 @@
|
||||
# Armonía del Ser: Core API (`armonia-api`)
|
||||
|
||||
Backend API service for **Armonía del Ser**—a holistic therapy, meditation, and personal growth center in Mexico.
|
||||
Backend API service for **Armonía del Ser**—a holistic therapy, meditation, and personal growth center founded by **Jasmin** in Mexico.
|
||||
|
||||
Built with **FastAPI** and **Turso (libSQL)** to manage services, appointments, client records, and payment acknowledgments at zero infrastructure cost.
|
||||
Built with **FastAPI** and **Turso (libSQL)** to serve as the operational source of truth between **Google Calendar**, **Turso**, and the **Admin Dashboard (`armonia-dashboard`)** protected with a server-side allowlist for **Google OAuth**.
|
||||
|
||||
---
|
||||
|
||||
## Architecture & Design
|
||||
|
||||
```
|
||||
[Clients / Landing UI] [Admin Dashboard (Jazmín)]
|
||||
│ │
|
||||
[Clients / Landing UI] [Admin Dashboard (Jasmin & Assistant)]
|
||||
│ │ (Google OAuth + Turso Allowlist)
|
||||
▼ ▼
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ FastAPI Core Service │
|
||||
│ - Services Catalog (Group & 1-on-1) │
|
||||
│ - Booking State Machine (Pending -> Confirmed) │
|
||||
│ - Payment Verification & Acknowledgment │
|
||||
│ - Dynamic WhatsApp Deep-Link Generator │
|
||||
│ - Separated Booking & Payment State Engine │
|
||||
│ - 48-Hour Payment Follow-Up Queue & Delayed Exceptions │
|
||||
│ - Deliberate Slot Release & Audit Trail │
|
||||
│ - Google OAuth2 + Turso Allowlist Guard │
|
||||
└──────────────┬─────────────────────────────┬─────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
[Turso Database] [Google Calendar API]
|
||||
(SQLite / libSQL at edge) (Tentative [PENDIENTE] hold
|
||||
-> Locked [CONFIRMADO])
|
||||
(SQLite / libSQL at edge) (Schedule coordination &
|
||||
recoverable sync health)
|
||||
```
|
||||
|
||||
### Key Principles
|
||||
|
||||
1. **Anti-Ghosting Payment Workflow**:
|
||||
- A client reserves a spot -> Booking is saved as `PENDING_PAYMENT` with a unique folio (`ADS-XXXX`).
|
||||
- A tentative hold is placed on Google Calendar.
|
||||
- Client is redirected to WhatsApp with pre-filled transfer details (SPEI CLABE + Folio).
|
||||
- Once Jazmín verifies the deposit in her banking app, she acknowledges it via the Admin Dashboard (`armonia-dashboard`).
|
||||
- Booking transitions to `CONFIRMED`, locking the calendar event and sending confirmation details.
|
||||
2. **Zero-Cost Infrastructure**:
|
||||
1. **Separated Booking & Payment States**:
|
||||
- `booking_status` (`RESERVED`, `RELEASED`, `CANCELLED`, `COMPLETED`, `NO_SHOW`) is modeled orthogonally from `payment_arrangement` (`PREPAID_DEFAULT`, `DELAYED_ALLOWED`, `PACKAGE_REDEEMED`) and `payment_status` (`AWAITING_ACKNOWLEDGMENT`, `ACKNOWLEDGED`, `NOT_APPLICABLE`).
|
||||
2. **Prepayment by Default, Explicit Delayed-Payment Exceptions**:
|
||||
- Most bookings require prepayment (`PREPAID_DEFAULT`). Authorized administrators can explicitly authorize a delayed-payment exception (`DELAYED_ALLOWED`), keeping `payment_status = 'AWAITING_ACKNOWLEDGMENT'` until payment is actually settled.
|
||||
3. **Deliberate Slot Release & 48-Hour Follow-Up Visibility**:
|
||||
- Bookings never expire automatically on a timer. At 48 hours prior to a session, unacknowledged bookings appear in `GET /bookings/follow-up-queue` so the assistant can manually follow up via WhatsApp and either acknowledge payment, authorize delayed payment, or deliberately release the slot (`RELEASED`).
|
||||
4. **Google OAuth + Turso Allowlist**:
|
||||
- Administrative endpoints verify the caller's Google OAuth session against Turso's `admin_allowlist` table on every request and record all mutations in `admin_audit_log`.
|
||||
5. **Zero-Cost Infrastructure**:
|
||||
- Runs containerized on **Google Cloud Run** free tier (scale-to-zero, $0/month).
|
||||
- Data stored in **Turso** free tier (up to 9 GB storage, billions of monthly row reads).
|
||||
- In local development and automated testing, seamlessly falls back to standard file-based SQLite (`file:local.db`).
|
||||
3. **Consumer Agnostic**:
|
||||
- Designed to serve both web frontends (`armonia-dashboard`, `armonia-landing`) and future headless consumers (an MCP server for AI pair programming, a WhatsApp Business Cloud API webhook, or an LLM booking assistant).
|
||||
- Data stored in **Turso** free tier, with local fallback to file-based SQLite (`file:local.db`).
|
||||
|
||||
---
|
||||
|
||||
@@ -47,10 +46,12 @@ Built with **FastAPI** and **Turso (libSQL)** to manage services, appointments,
|
||||
|
||||
| Entity | Purpose |
|
||||
| :--- | :--- |
|
||||
| `services` | Catalog of offerings (Círculos de Cacao, Meditaciones, Constelaciones, Psicoterapia), format (`ONLINE` / `PRESENCIAL`), type (`GROUP` / `ONE_ON_ONE`), capacity, and price in MXN. |
|
||||
| `admin_allowlist` | Authorized administrator emails (`OWNER`, `ASSISTANT`, `ADMIN`), active status, and last login timestamp. |
|
||||
| `services` | Catalog of offerings (Círculos de Cacao, Meditaciones, Constelaciones, Psicoterapia), format (`ONLINE` / `PRESENCIAL`), type (`GROUP` / `ONE_ON_ONE`), capacity, mandatory buffer, and price in MXN. |
|
||||
| `clients` | Client directory (name, phone / WhatsApp, email, notes). |
|
||||
| `bookings` | Appointments linked to a service and client, tracking status (`PENDING_PAYMENT`, `CONFIRMED`, `CANCELLED`, `EXPIRED`, `NO_SHOW`), folio, and expiration. |
|
||||
| `payments` | Audit record of SPEI/OXXO payment verification, notes, and acknowledgment timestamp. |
|
||||
| `bookings` | Appointments tracking `booking_status`, `payment_arrangement`, `payment_status`, folio (`ADS-XXXX`), exception/release/acknowledgment audit metadata, and Google Calendar sync health. |
|
||||
| `payments` | Audit record of SPEI/OXXO/cash payment acknowledgment (`acknowledged_by`, `acknowledged_at`, notes). |
|
||||
| `admin_audit_log` | Immutable log of administrative actions (`ACKNOWLEDGE_PAYMENT`, `AUTHORIZE_DELAYED_PAYMENT`, `RELEASE_BOOKING`, etc.). |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+69
-41
@@ -2,37 +2,41 @@
|
||||
|
||||
## Project: Armonía del Ser Core API (`armonia-api`)
|
||||
|
||||
**Document Version:** 1.0.0
|
||||
**Status:** Approved
|
||||
**Document Version:** 1.1.0
|
||||
**Status:** Approved (Revised per Operational Clarification with Jasmin's Assistant)
|
||||
**Date:** 2026-10-18
|
||||
**Scope:** Backend Domain Model, Scheduling State Engine, Payment Verification, and External Integrations
|
||||
**Scope:** Backend Domain Model, Separated Booking & Payment State Engine, 48-Hour Follow-Up Queue, Google OAuth + Turso Admin Allowlist, and Google Calendar Synchronization
|
||||
|
||||
---
|
||||
|
||||
## 1. Introduction & Business Context
|
||||
|
||||
### 1.1 Purpose
|
||||
This document specifies the software requirements for the backend platform of **Armonía del Ser**, an established holistic wellness and psychotherapy practice founded by Jazmín in Mexico. The system addresses operational disorganization, schedule collisions, consultation tardiness, and payment default ("ghosting") while maintaining a strict **$0/month infrastructure cost**.
|
||||
This document specifies the software requirements for the backend platform of **Armonía del Ser**, an established holistic wellness and psychotherapy practice founded by **Jasmin** in Mexico.
|
||||
|
||||
The primary goal of the first deliverable is a tight, reliable backend sitting between **Google Calendar**, **Turso (libSQL)**, and the **Admin Dashboard (`armonia-dashboard`)** protected with a server-side allowlist for **Google OAuth**. Rather than making automated business decisions on Jasmin's behalf, the platform maintains the single operational source of truth and gives Jasmin and her assistant clear visibility to record and follow through on their decisions, while maintaining a strict **$0/month infrastructure cost**.
|
||||
|
||||
### 1.2 Business Profile
|
||||
- **Entity:** Armonía del Ser (operating 20+ years in Mexico).
|
||||
- **Entity:** Armonía del Ser (operating 20+ years in Tulancingo, Hgo., Mexico).
|
||||
- **Offerings:** Individual psychotherapy (*Atención Psicológica*), weekly recurring circles (*Círculos de Cacao*, *Meditación con cuencos*, *Constelaciones Familiares*), multi-session packages, and low-cost community workshops (*Curso de Abundancia*).
|
||||
- **Modalities:** In-person (*Presencial*) and Virtual (*Online* via Google Meet).
|
||||
- **Payment Culture:** High unbanked / cash / SPEI transfer prevalence; low credit card usage. Payments are authenticated manually via SPEI bank vouchers (comprobantes) or cash.
|
||||
- **Payment Culture:** High unbanked / cash / SPEI transfer prevalence; low credit card usage. Payments are verified manually via SPEI bank vouchers (comprobantes) or cash and acknowledged in the dashboard.
|
||||
- **Communication Channel:** WhatsApp (`+52 775 148 7912`) is used manually by Jasmin's assistant to follow up with clients; a WhatsApp bot is explicitly out of scope for the first deliverable.
|
||||
|
||||
---
|
||||
|
||||
## 2. User & Stakeholder Personas
|
||||
|
||||
1. **Jazmín (Owner & Principal Therapist):**
|
||||
1. **Jasmin (Owner & Principal Therapist):**
|
||||
- Conducts individual and group therapies.
|
||||
- Needs automated calendar protection (buffer times) and a 1-tap payment acknowledgment queue to prevent client ghosting.
|
||||
- Needs mandatory schedule buffer times (15–20 minutes), accurate Google Calendar coordination, and visibility into which sessions are paid or authorized for delayed payment.
|
||||
2. **Assistant / Co-Organizer:**
|
||||
- Registers clients via WhatsApp and in-person requests.
|
||||
- Tracks course attendance and marks symbolic payments ($50 MXN).
|
||||
- Reviews the 48-hour payment follow-up queue, manually contacts clients via WhatsApp to confirm payment intentions, acknowledges SPEI/cash payments, records authorized delayed-payment exceptions, or deliberately releases slots.
|
||||
- Tracks course attendance and marks symbolic workshop payments ($50 MXN).
|
||||
3. **Clients (Consultantes / Participantes):**
|
||||
- Discover services via word-of-mouth or Instagram/social funnels.
|
||||
- Reserve spots online or via WhatsApp, receive transparent SPEI payment instructions with unique folios, and send payment vouchers.
|
||||
- Discover services via word-of-mouth or social funnels.
|
||||
- Reserve spots online or via WhatsApp, receive transparent SPEI payment instructions with unique folios (`ADS-XXXX`), and coordinate with the assistant on WhatsApp.
|
||||
|
||||
---
|
||||
|
||||
@@ -40,36 +44,67 @@ This document specifies the software requirements for the backend platform of **
|
||||
|
||||
### 3.1 Service Catalog Management (`FR-CAT`)
|
||||
- **FR-CAT-1:** The system shall support two distinct service types: `GROUP` (fixed recurring weekly schedule, attendee capacity ~10-25) and `ONE_ON_ONE` (dynamic appointment slots).
|
||||
- **FR-CAT-2:** Each service shall define name, slug, description, modality (`PRESENCIAL` or `ONLINE`), price in MXN, duration in minutes, and active status.
|
||||
- **FR-CAT-2:** Each service shall define name, slug, description, modality (`PRESENCIAL` or `ONLINE`), price in MXN, duration in minutes, mandatory buffer in minutes, and active status.
|
||||
|
||||
### 3.2 Anti-Ghosting Reservation State Machine (`FR-RSV`)
|
||||
- **FR-RSV-1:** When a reservation is created, the system shall assign it the status `PENDING_PAYMENT` with an automated time-to-live (`expires_at = now() + 2 hours`).
|
||||
- **FR-RSV-2:** The system shall generate a unique human-readable reservation folio (`ADS-XXXX`).
|
||||
- **FR-RSV-3:** The reservation endpoint shall return a pre-formatted WhatsApp deep link (`wa.me`) containing:
|
||||
- Therapist contact number.
|
||||
- Service title and appointment date/time.
|
||||
- Unique reservation folio (`ADS-XXXX`).
|
||||
- Total amount due in MXN.
|
||||
- Bank transfer coordinates: Bank name, CLABE, and Beneficiary name.
|
||||
- **FR-RSV-4:** A reservation shall transition from `PENDING_PAYMENT` to `CONFIRMED` only upon explicit acknowledgment via the payment verification endpoint.
|
||||
### 3.2 Orthogonal Booking & Payment State Model (`FR-RSV`)
|
||||
To avoid coupling schedule reservation state with financial settlement or exceptions, every booking tracks three distinct, orthogonal axes:
|
||||
- **FR-RSV-1 (`booking_status`):** Represents whether the schedule slot is active:
|
||||
- `RESERVED`: Active booking holding a schedule slot.
|
||||
- `RELEASED`: Slot deliberately released by an authorized administrator so another client can take the place.
|
||||
- `CANCELLED`: Explicitly cancelled by client or therapist.
|
||||
- `COMPLETED`: Session took place.
|
||||
- `NO_SHOW`: Client failed to attend.
|
||||
- **FR-RSV-2 (`payment_arrangement`):** Represents the agreed timing/mechanism of payment:
|
||||
- `PREPAID_DEFAULT`: Standard rule; payment is expected before the session.
|
||||
- `DELAYED_ALLOWED`: Explicit administrative exception allowing the session to proceed with payment outstanding (traceable as a delayed payment).
|
||||
- `PACKAGE_REDEEMED`: Covered by an existing multi-session package credit.
|
||||
- **FR-RSV-3 (`payment_status`):** Represents actual financial settlement:
|
||||
- `AWAITING_ACKNOWLEDGMENT`: Payment has not yet been verified/acknowledged by an administrator.
|
||||
- `ACKNOWLEDGED`: Administrator verified the SPEI/cash deposit and recorded the acknowledgment.
|
||||
- `NOT_APPLICABLE`: Covered by a package redemption or slot released/cancelled prior to session with no outstanding balance.
|
||||
- **FR-RSV-4 (Prepayment Default & Delayed-Payment Exception):**
|
||||
- Prepayment is the default (`PREPAID_DEFAULT`), not an absolute requirement.
|
||||
- An authorized administrator may explicitly record a delayed-payment exception (`DELAYED_ALLOWED`), capturing `exception_authorized_by`, `exception_authorized_at`, and `exception_notes`.
|
||||
- Authorizing `DELAYED_ALLOWED` **must never** silently mark `payment_status` as `ACKNOWLEDGED`.
|
||||
- **FR-RSV-5 (Deliberate Slot Release — No Automatic Expiration):**
|
||||
- The backend **must not** automatically expire or release a booking based on a timer or background job.
|
||||
- Only an authorized administrator can transition a booking to `RELEASED` (recording `released_by`, `released_at`, and `release_reason`).
|
||||
- **FR-RSV-6 (48-Hour Follow-Up Visibility Queue):**
|
||||
- At a configurable threshold before `scheduled_at` (initially **48 hours**), any `RESERVED` booking with `payment_status = 'AWAITING_ACKNOWLEDGMENT'` shall surface in a dedicated dashboard follow-up endpoint (`GET /bookings/follow-up-queue`).
|
||||
- The 48-hour threshold is a derived, queryable visibility condition — it does not mutate the booking state.
|
||||
- Bookings with `payment_arrangement = 'DELAYED_ALLOWED'` and `payment_status = 'AWAITING_ACKNOWLEDGMENT'` also remain visible in the follow-up/receivables view until acknowledged.
|
||||
- **FR-RSV-7 (Payment Acknowledgment as Audited Action):**
|
||||
- When an administrator verifies payment in their banking workflow and submits acknowledgment, the system records `acknowledged_by` (admin email) and `acknowledged_at` (UTC timestamp) on both the payment record and the booking.
|
||||
- **FR-RSV-8 (WhatsApp Deep Link & Folio):**
|
||||
- Every booking generates a unique human-readable folio (`ADS-XXXX`) and a pre-formatted `wa.me` deep link for manual client communication.
|
||||
|
||||
### 3.3 Mandatory Schedule Buffer Times (`FR-BUF`)
|
||||
- **FR-BUF-1:** To resolve chronic delay cascades caused by emotional consultation overruns, individual therapy sessions (e.g. 60 min) must enforce a **mandatory buffer interval** (minimum 15–20 minutes) following the appointment.
|
||||
- **FR-BUF-2:** No two individual appointments may be scheduled back-to-back without this buffer interval.
|
||||
- **FR-BUF-1:** Individual therapy sessions (e.g. 60 min) must enforce a **mandatory buffer interval** (minimum 15–20 minutes) following the appointment.
|
||||
- **FR-BUF-2:** No two active (`RESERVED`) individual appointments may overlap when including their post-session buffer intervals. Releasing (`RELEASED`) or cancelling (`CANCELLED`) a booking frees its slot and buffer immediately.
|
||||
|
||||
### 3.4 Multi-Session Packages & Balances (`FR-PKG`)
|
||||
- **FR-PKG-1:** The system shall support client packages (e.g., 5 or 10 psychotherapy sessions).
|
||||
- **FR-PKG-2:** The package entity shall track `total_sessions`, `completed_sessions`, and `remaining_sessions` to eliminate verbal confusion at session ends.
|
||||
- **FR-PKG-3:** The system shall track financial status for the package (`FULLY_PAID`, `PARTIAL_DEPOSIT`, `OVERDUE`).
|
||||
- **FR-PKG-2:** The package entity shall track `total_sessions`, `completed_sessions`, and `remaining_sessions`.
|
||||
- **FR-PKG-3:** The system shall track financial status for the package (`PAID`, `PARTIAL`, `PENDING`).
|
||||
|
||||
### 3.5 Group Course Attendance & Payment Ledger (`FR-ATT`)
|
||||
- **FR-ATT-1:** The system shall provide a digital replacement for physical paper attendance sheets for recurring workshops (e.g., *Curso de Abundancia y Prosperidad*, $50 MXN/session).
|
||||
- **FR-ATT-2:** For any course instance, the administrator or assistant shall be able to toggle attendance (`attended: true/false`) and record payment method (`SPEI`, `CASH`).
|
||||
- **FR-ATT-2:** Administrators shall be able to record and review workshop attendance and payments.
|
||||
|
||||
### 3.6 Google Calendar Two-Way Synchronization (`FR-CAL`)
|
||||
- **FR-CAL-1:** Upon reservation creation (`PENDING_PAYMENT`), the API shall insert a tentative Google Calendar event with prefix `[PENDIENTE]` (Color: Yellow).
|
||||
- **FR-CAL-2:** Upon payment verification (`CONFIRMED`), the API shall update the Google Calendar event to `[CONFIRMADO]` (Color: Green) and attach location/Google Meet links.
|
||||
- **FR-CAL-3:** If a reservation expires without payment, the API shall delete or mark the tentative event as cancelled.
|
||||
### 3.6 Google Calendar Coordination (`FR-CAL`)
|
||||
- **FR-CAL-1:** `armonia-api` owns the authoritative business record in Turso while Google Calendar represents the schedule.
|
||||
- **FR-CAL-2:** Calendar events reflect the booking and payment arrangement state:
|
||||
- `[PAGO PENDIENTE]` when `RESERVED` + `PREPAID_DEFAULT` + `AWAITING_ACKNOWLEDGMENT`.
|
||||
- `[PAGO DIFERIDO]` when `RESERVED` + `DELAYED_ALLOWED` + `AWAITING_ACKNOWLEDGMENT`.
|
||||
- `[CONFIRMADO]` when `RESERVED` + (`ACKNOWLEDGED` or `PACKAGE_REDEEMED`).
|
||||
- Deleted/cancelled from Google Calendar when `booking_status` transitions to `RELEASED` or `CANCELLED`.
|
||||
- **FR-CAL-3 (Visible & Recoverable Integration State):** Every booking tracks `gcal_event_id`, `gcal_sync_status` (`PENDING`, `SYNCED`, `FAILED`, `NOT_CONFIGURED`), `gcal_sync_error`, and `gcal_synced_at`. Calendar API failures must not silently corrupt or roll back the Turso business record, and administrators can trigger a retry (`POST /bookings/{id}/sync-calendar`).
|
||||
|
||||
### 3.7 Administrator Authentication & Allowlist (`FR-AUTH`)
|
||||
- **FR-AUTH-1:** The backend shall implement Google OAuth2 Authorization Code flow (`/auth/google/login`, `/auth/google/callback`) keeping OAuth client secrets and session-signing secrets exclusively on the server.
|
||||
- **FR-AUTH-2:** The backend shall verify the Google identity and ensure `email_verified == true`.
|
||||
- **FR-AUTH-3:** Every authenticated session and administrative request shall verify the user's email against a server-controlled `admin_allowlist` table in Turso (`is_active = 1`), seeded at startup from `ADMIN_BOOTSTRAP_EMAILS`.
|
||||
- **FR-AUTH-4:** All sensitive administrative mutations (payment acknowledgment, delayed-payment authorization, booking release, status changes) shall record the acting administrator's email in `admin_audit_log` and on the target record.
|
||||
|
||||
---
|
||||
|
||||
@@ -77,18 +112,11 @@ This document specifies the software requirements for the backend platform of **
|
||||
|
||||
### 4.1 Cost & Operational Efficiency
|
||||
- **NFR-COST-1:** Zero persistent operational expenditure ($0/month ongoing cost).
|
||||
- **NFR-COST-2:** Compute must execute on serverless containers (Google Cloud Run free tier) scaling to zero.
|
||||
- **NFR-COST-3:** Data persistence must reside on edge SQLite (Turso free tier) with zero idle billing.
|
||||
- **NFR-COST-2:** Compute executes on serverless containers (Google Cloud Run free tier) scaling to zero — no background cron workers required for the 48-hour visibility threshold.
|
||||
- **NFR-COST-3:** Data persistence resides on edge SQLite (Turso free tier) with zero idle billing.
|
||||
|
||||
### 4.2 Portability & Local Testability
|
||||
- **NFR-PORT-1:** In local development and continuous integration environments, the system must execute against file-based or in-memory SQLite (`file:local.db`) without requiring remote Turso credentials.
|
||||
|
||||
### 4.3 Extensibility & Consumer Decoupling
|
||||
- **NFR-EXT-1:** The API service layer must remain agnostic of specific web frontends, enabling direct consumption by:
|
||||
- Mobile Admin Dashboard (`armonia-dashboard`).
|
||||
- Public Client Landing (`armonia-landing`).
|
||||
- Future WhatsApp Cloud API automated webhooks.
|
||||
- Future AI pair programming / Model Context Protocol (MCP) servers.
|
||||
- **NFR-PORT-1:** In local development and CI environments, the system executes against file-based SQLite (`file:local.db`) without requiring remote Turso or live Google Cloud credentials.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+102
-87
@@ -9,124 +9,139 @@
|
||||
```
|
||||
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
|
||||
│ armonia-landing │ │ armonia-dashboard │
|
||||
│ (Public Client Experience) │ │ (Jazmín & Assistant UI) │
|
||||
│ (Public Client Experience) │ │ (Jasmin & Assistant UI) │
|
||||
│ Cloudflare Pages (Edge) │ │ Cloudflare Pages (Edge) │
|
||||
└────────────────┬────────────────┘ └────────────────┬────────────────┘
|
||||
│ (Public Booking Flow) │ (Admin & Payment Actions)
|
||||
│ (Public Booking Flow) │ (Google OAuth + Allowlisted Admin Actions)
|
||||
▼ ▼
|
||||
┌───────────────────────────────────────────────────────────────────────────┐
|
||||
│ armonia-api (FastAPI / Python 3.13) │
|
||||
│ │
|
||||
│ ┌───────────────────────┐ ┌──────────────────────┐ ┌────────────────┐ │
|
||||
│ │ Services & Catalog │ │ Anti-Ghosting State │ │ Attendance & │ │
|
||||
│ │ Catalog Engine │ │ Machine & Buffers │ │ Package Ledger │ │
|
||||
│ │ Google OAuth Guard & │ │ Orthogonal Booking & │ │ 48h Follow-Up │ │
|
||||
│ │ Turso Allowlist │ │ Payment State Engine │ │ & Audit Log │ │
|
||||
│ └───────────┬───────────┘ └──────────┬───────────┘ └────────┬───────┘ │
|
||||
│ │ │ │ │
|
||||
│ ▼ ▼ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Database Adapter (libsql-client) │ │
|
||||
│ └──────────────────────────────┬─────────────────────────────┘ │
|
||||
└──────────────────────────────────────┼────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────────────┴─────────────────────┐
|
||||
▼ ▼
|
||||
[Turso Edge Database] [Local SQLite3 File]
|
||||
(libsql://armonia-db.turso.io) (file:local.db)
|
||||
│ │ Database Adapter (libsql-client) + Calendar Adapter │ │
|
||||
│ └──────────────┬─────────────────────────────────┬───────────┘ │
|
||||
└──────────────────────┼─────────────────────────────────┼──────────────────┘
|
||||
│ │
|
||||
┌─────────────┴─────────────┐ ▼
|
||||
▼ ▼ [Google Calendar API]
|
||||
[Turso Edge Database] [Local SQLite3 File] (Schedule Representation &
|
||||
(libsql://armonia-db) (file:local.db) Recoverable Sync Status)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. The Anti-Ghosting Booking State Machine
|
||||
## 2. Separated Booking Lifecycle & Payment State Model
|
||||
|
||||
A booking and its payment represent distinct operational facts. Combining them into a single state machine makes delayed-payment exceptions and post-session settlements brittle. `armonia-api` models three orthogonal axes on every booking:
|
||||
|
||||
1. **`booking_status`**: Is this booking still holding a schedule slot? (`RESERVED`, `RELEASED`, `CANCELLED`, `COMPLETED`, `NO_SHOW`)
|
||||
2. **`payment_arrangement`**: Is payment expected prior to the session, explicitly allowed afterward, or covered by a package? (`PREPAID_DEFAULT`, `DELAYED_ALLOWED`, `PACKAGE_REDEEMED`)
|
||||
3. **`payment_status`**: Has the money actually been verified and acknowledged? (`AWAITING_ACKNOWLEDGMENT`, `ACKNOWLEDGED`, `NOT_APPLICABLE`)
|
||||
|
||||
### 2.1 Booking Lifecycle (`booking_status`)
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> PENDING_PAYMENT : Client submits reservation (Expires in 2h)
|
||||
[*] --> RESERVED : Booking created (slot held)
|
||||
|
||||
PENDING_PAYMENT --> CONFIRMED : Jazmín acknowledges SPEI/Cash deposit
|
||||
PENDING_PAYMENT --> EXPIRED : 2-hour timeout reached without payment
|
||||
PENDING_PAYMENT --> CANCELLED : Client or Therapist cancels
|
||||
|
||||
CONFIRMED --> COMPLETED : Consultation conducted successfully
|
||||
CONFIRMED --> NO_SHOW : Client failed to attend without notice
|
||||
CONFIRMED --> CANCELLED : Rescheduled or refunded cancellation
|
||||
RESERVED --> COMPLETED : Session occurred
|
||||
RESERVED --> RELEASED : Admin deliberately releases slot after manual follow-up
|
||||
RESERVED --> CANCELLED : Client or Jasmin cancels
|
||||
RESERVED --> NO_SHOW : Client failed to attend
|
||||
```
|
||||
|
||||
### Event Transitions & Side-Effects
|
||||
### 2.2 Payment Arrangement & Payment Status Lifecycle
|
||||
|
||||
| Transition | Trigger | Calendar Side-Effect | Notification / WhatsApp |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `-> PENDING_PAYMENT` | Client submits reservation | Creates tentative event `[PENDIENTE] Nombre` (Yellow) | Pre-fills `wa.me` message with CLABE and Folio `ADS-XXXX` |
|
||||
| `PENDING -> CONFIRMED` | Jazmín taps "Acreditar Pago" | Updates event to `[CONFIRMADO] Nombre` (Green) + Meet link | Sends confirmation message to client |
|
||||
| `PENDING -> EXPIRED` | Background sweep (timeout) | Deletes tentative hold event | Frees slot for other clients |
|
||||
| `CONFIRMED -> NO_SHOW` | Post-session audit | Marks status as `NO_SHOW` in audit log | Records history for future booking policies |
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
state "Payment Arrangement" as PA {
|
||||
[*] --> PREPAID_DEFAULT : Standard booking
|
||||
[*] --> PACKAGE_REDEEMED : Package credit used
|
||||
PREPAID_DEFAULT --> DELAYED_ALLOWED : Admin authorizes delayed-payment exception
|
||||
}
|
||||
|
||||
state "Payment Status" as PS {
|
||||
[*] --> AWAITING_ACKNOWLEDGMENT : Standard booking (amount > 0)
|
||||
[*] --> NOT_APPLICABLE : Package redemption
|
||||
AWAITING_ACKNOWLEDGMENT --> ACKNOWLEDGED : Admin verifies SPEI/Cash deposit
|
||||
AWAITING_ACKNOWLEDGMENT --> NOT_APPLICABLE : Released/cancelled before session with no balance owed
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3 Operational Combinations & Google Calendar Side-Effects
|
||||
|
||||
| `booking_status` | `payment_arrangement` | `payment_status` | Operational Meaning | Google Calendar Event |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| `RESERVED` | `PREPAID_DEFAULT` | `AWAITING_ACKNOWLEDGMENT` | Slot held; payment expected prior to session (enters 48h follow-up queue when $\le 48\text{h}$ away) | `[PAGO PENDIENTE] Folio - Cliente` (Yellow) |
|
||||
| `RESERVED` | `DELAYED_ALLOWED` | `AWAITING_ACKNOWLEDGMENT` | Admin authorized exception; session proceeds with delayed payment tracked | `[PAGO DIFERIDO] Folio - Cliente` (Orange) |
|
||||
| `RESERVED` | `PREPAID_DEFAULT` / `DELAYED_ALLOWED` | `ACKNOWLEDGED` | Payment verified by admin (`acknowledged_by`, `acknowledged_at`) | `[CONFIRMADO] Folio - Cliente` (Green) |
|
||||
| `RESERVED` | `PACKAGE_REDEEMED` | `NOT_APPLICABLE` | Covered by multi-session package credit | `[CONFIRMADO] Folio - Cliente` (Green) |
|
||||
| `RELEASED` | `PREPAID_DEFAULT` | `NOT_APPLICABLE` | Admin deliberately released slot after follow-up; slot freed | Event deleted / cancelled |
|
||||
| `COMPLETED` | `DELAYED_ALLOWED` | `AWAITING_ACKNOWLEDGMENT` | Session took place under exception; payment still outstanding | `[PAGO DIFERIDO] Folio - Cliente` |
|
||||
| `COMPLETED` | Any | `ACKNOWLEDGED` | Session took place and payment is settled | `[CONFIRMADO] Folio - Cliente` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Buffer-Time Collision Prevention Algorithm
|
||||
## 3. The 48-Hour Payment Follow-Up Workflow
|
||||
|
||||
Rather than running a background worker that mutates or expires bookings automatically, the 48-hour attention threshold is a **derived query condition** evaluated when the dashboard requests `GET /bookings/follow-up-queue`:
|
||||
|
||||
$$\text{Needs Follow-Up} \iff \text{booking\_status} = \text{RESERVED} \land \text{payment\_status} = \text{AWAITING\_ACKNOWLEDGMENT} \land (\text{scheduled\_at} \le \text{now} + 48\text{h} \lor \text{payment\_arrangement} = \text{DELAYED\_ALLOWED})$$
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant D as armonia-dashboard (Admin)
|
||||
participant A as armonia-api
|
||||
participant T as Turso (libSQL)
|
||||
participant G as Google Calendar
|
||||
|
||||
D->>A: GET /bookings/follow-up-queue (window_hours=48)
|
||||
A->>T: Query RESERVED + AWAITING_ACKNOWLEDGMENT within 48h (or DELAYED_ALLOWED)
|
||||
T-->>A: Bookings requiring attention + WhatsApp deep links
|
||||
A-->>D: Render Follow-Up Queue
|
||||
|
||||
D->>C: Assistant contacts client manually via WhatsApp
|
||||
alt Client sends payment proof & admin verifies bank deposit
|
||||
D->>A: POST /payments/acknowledge
|
||||
A->>T: Set payment_status=ACKNOWLEDGED, record acknowledged_by + audit log
|
||||
A->>G: Update event to [CONFIRMADO]
|
||||
else Jasmin authorizes delayed-payment exception
|
||||
D->>A: POST /bookings/{id}/authorize-delayed-payment
|
||||
A->>T: Set payment_arrangement=DELAYED_ALLOWED, keep AWAITING_ACKNOWLEDGMENT + audit log
|
||||
A->>G: Update event to [PAGO DIFERIDO]
|
||||
else Client gives up slot or does not respond by agreed cutoff
|
||||
D->>A: POST /bookings/{id}/release
|
||||
A->>T: Set booking_status=RELEASED, record released_by + audit log
|
||||
A->>G: Delete/cancel Calendar event (slot freed)
|
||||
end
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Buffer-Time Collision Prevention Algorithm
|
||||
|
||||
To resolve consultation overruns, individual appointment availability enforces a post-session buffer:
|
||||
|
||||
$$\text{Blocked Interval} = [\text{Start Time}, \text{Start Time} + \text{Duration} + \text{Buffer (15 min)}]$$
|
||||
|
||||
```
|
||||
[Consultation Slot: 10:00 - 11:00] + [Buffer: 11:00 - 11:15]
|
||||
Next Available: 11:15
|
||||
```
|
||||
|
||||
When checking availability for a requested slot $[T_{start}, T_{end}]$:
|
||||
1. Fetch existing bookings on the requested day where status $\in \{\text{PENDING\_PAYMENT}, \text{CONFIRMED}\}$.
|
||||
2. Fetch busy blocks from Google Calendar API.
|
||||
3. Compute overlap:
|
||||
$$\text{Overlap} \iff \max(T_{start}, E_{start}) < \min(T_{end} + \text{Buffer}, E_{end})$$
|
||||
4. If overlap detected, slot is rejected as unavailable.
|
||||
When checking availability for a requested slot $[T_{\text{start}}, T_{\text{end}}]$:
|
||||
1. Fetch existing `ONE_ON_ONE` bookings where `booking_status = 'RESERVED'`. (Bookings marked `RELEASED` or `CANCELLED` do not block the schedule.)
|
||||
2. Compute overlap:
|
||||
$$\text{Overlap} \iff \max(T_{\text{start}}, E_{\text{start}}) < \min(T_{\text{end}} + \text{Buffer}, E_{\text{end}} + E_{\text{buffer}})$$
|
||||
3. If overlap is detected, the slot is rejected with `409 Conflict`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Multi-Session Package & Course Attendance Schema
|
||||
## 5. Security Boundary: Google OAuth & Turso Administrator Allowlist
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
CLIENTS ||--o{ PACKAGES : "purchases"
|
||||
PACKAGES ||--o{ BOOKINGS : "redeems"
|
||||
SERVICES ||--o{ PACKAGES : "applies to"
|
||||
OCCURRENCES ||--o{ ATTENDANCE : "has"
|
||||
CLIENTS ||--o{ ATTENDANCE : "attends"
|
||||
|
||||
PACKAGES {
|
||||
string id PK
|
||||
string client_id FK
|
||||
string service_id FK
|
||||
int total_sessions
|
||||
int completed_sessions
|
||||
int price_paid_mxn
|
||||
string financial_status "PAID | PARTIAL | PENDING"
|
||||
datetime created_at
|
||||
}
|
||||
|
||||
OCCURRENCES {
|
||||
string id PK
|
||||
string service_id FK
|
||||
datetime scheduled_at
|
||||
string topic "e.g. Clase 3: Abundancia"
|
||||
}
|
||||
|
||||
ATTENDANCE {
|
||||
string id PK
|
||||
string occurrence_id FK
|
||||
string client_id FK
|
||||
boolean attended
|
||||
int amount_paid_mxn
|
||||
string payment_method "SPEI | CASH"
|
||||
datetime recorded_at
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Future Extensibility: MCP & LLM Agent Readiness
|
||||
|
||||
The business layer is implemented as pure Python service functions returning Pydantic domain models, completely independent of the FastAPI routing layer.
|
||||
|
||||
This enables future exposure via:
|
||||
1. **Model Context Protocol (MCP)**: An MCP server exposing tools (`list_available_slots`, `reserve_session`, `verify_payment`, `get_client_package_status`) directly to Claude, Cursor, or Antigravity agents.
|
||||
2. **WhatsApp AI Bot**: A webhook listening to incoming WhatsApp messages from clients, querying `armonia-api` for availability, and answering booking inquiries conversationally.
|
||||
1. **Server-Side OAuth Secrets**: `GOOGLE_OAUTH_CLIENT_ID`, `GOOGLE_OAUTH_CLIENT_SECRET`, and `SESSION_SECRET_KEY` reside exclusively in `armonia-api`.
|
||||
2. **Turso `admin_allowlist` Table**: Stores authorized administrator emails (`email PRIMARY KEY`, `full_name`, `role`, `is_active`, `last_login_at`), seeded on startup from `ADMIN_BOOTSTRAP_EMAILS`.
|
||||
3. **Per-Request Verification**: Every protected administrative endpoint validates the HMAC-signed session token/cookie and verifies that the authenticated email has `is_active = 1` in `admin_allowlist`.
|
||||
4. **Immutable Audit Trail**: Every administrative action (`ACKNOWLEDGE_PAYMENT`, `AUTHORIZE_DELAYED_PAYMENT`, `RELEASE_BOOKING`, `UPDATE_BOOKING_STATUS`, `ALLOWLIST_CHANGE`) writes a structured row to `admin_audit_log`.
|
||||
@@ -6,7 +6,7 @@ Accepted
|
||||
## Context
|
||||
Armonía del Ser operates on a low-margin business model where recurring software subscription fees or persistent virtual private server (VPS) costs would outweigh the operational benefits. We require a relational database that:
|
||||
1. Incurs **$0/month** in operational overhead for the anticipated volume (< 500 bookings/month).
|
||||
2. Provides relational schema enforcement, constraints, and atomic operations (unlike Google Sheets).
|
||||
2. Provides relational schema enforcement, constraints, and atomic operations (unlike Google Sheets) for bookings, payment acknowledgments, administrator allowlists, and audit logs.
|
||||
3. Executes seamlessly in local development and automated CI/CD testing without requiring remote cloud network calls or credentials.
|
||||
|
||||
## Decision
|
||||
@@ -21,4 +21,4 @@ We adopt **Turso (libSQL)** as the primary production database, coupled with `li
|
||||
- **Relational Integrity**: Foreign keys and enum constraints prevent data corruption.
|
||||
|
||||
### Negative / Trade-offs
|
||||
- Turso does not provide a native visual spreadsheet UI for non-technical users. Jazmín cannot open the raw database table directly; she interacts with the data exclusively through `armonia-dashboard` and Google Calendar.
|
||||
- Turso does not provide a native visual spreadsheet UI for non-technical users. Jasmin cannot open the raw database table directly; she and her assistant interact with the data exclusively through `armonia-dashboard` and Google Calendar.
|
||||
@@ -1,27 +1,33 @@
|
||||
# ADR 0002: Anti-Ghosting Payment Verification Workflow via WhatsApp Deep Links
|
||||
# ADR 0002: Separated Booking Lifecycle, Delayed-Payment Exceptions, and 48-Hour Follow-Up Visibility
|
||||
|
||||
## Status
|
||||
Accepted
|
||||
Accepted (Amended 2026-10-18 per Operational Clarification with Jasmin's Assistant)
|
||||
|
||||
## Context
|
||||
A major operational pain point for Jazmín is financial default: clients allowed to pay *after* their therapy session often cease responding to WhatsApp messages ("ghosting").
|
||||
However, implementing a traditional payment gateway like Stripe or Conekta is not viable because:
|
||||
1. Credit card penetration is low among local wellness clients in Mexico; most prefer cash or SPEI bank transfers.
|
||||
2. Payment gateway transaction fees (3.6% + $3 MXN + VAT) erode low-ticket therapy margins.
|
||||
3. Complex checkout forms create drop-offs on mobile devices.
|
||||
Initially, we assumed that all bookings should require prepayment within a strict 2-hour automatic expiration window (`PENDING_PAYMENT` $\rightarrow$ `EXPIRED`). However, operational clarification with Jasmin's assistant revealed three critical realities:
|
||||
1. **Prepayment is the default, not an absolute rule**: While most sessions require payment before the appointment, Jasmin occasionally allows trusted clients to pay later. Those sessions must proceed while keeping the outstanding payment explicitly traceable as a delayed payment (`DELAYED_ALLOWED`) rather than silently marking it paid.
|
||||
2. **Releasing a slot is always a deliberate human decision**: Automatically expiring a booking after 2 hours conflicts with how Jasmin and her assistant operate. Instead, the dashboard must surface unacknowledged bookings as the session approaches (48 hours prior) so the assistant can manually follow up on WhatsApp and decide whether to acknowledge payment, authorize a delayed-payment exception, or deliberately release the slot (`RELEASED`).
|
||||
3. **Booking status and payment status are distinct facts**: Coupling schedule status (`RESERVED`, `RELEASED`, `COMPLETED`) and financial state (`AWAITING_ACKNOWLEDGMENT`, `ACKNOWLEDGED`) into a single column makes delayed-payment exceptions and post-session receivables impossible to represent cleanly.
|
||||
|
||||
## Decision
|
||||
We implement a **Verification Loop** using unique folios (`ADS-XXXX`) and WhatsApp deep links (`wa.me`):
|
||||
1. Client reservation creates a booking in state `PENDING_PAYMENT` with an automatic 2-hour expiration window.
|
||||
2. The UI immediately renders Jazmín's SPEI coordinates (Bank, CLABE, Beneficiary) and opens a WhatsApp conversation with a pre-filled message including the folio (`ADS-XXXX`).
|
||||
3. Jazmín receives the transfer proof screenshot in WhatsApp, verifies the deposit in her banking app, and confirms the booking with a single tap in `armonia-dashboard`.
|
||||
4. Only upon this acknowledgment does the booking transition to `CONFIRMED` and lock into Google Calendar.
|
||||
We separate booking and payment state into three orthogonal fields on `bookings`, supported by an explicit 48-hour follow-up queue and audit trail:
|
||||
1. **Three Orthogonal State Axes**:
|
||||
- `booking_status`: `RESERVED`, `RELEASED`, `CANCELLED`, `COMPLETED`, `NO_SHOW`
|
||||
- `payment_arrangement`: `PREPAID_DEFAULT`, `DELAYED_ALLOWED`, `PACKAGE_REDEEMED`
|
||||
- `payment_status`: `AWAITING_ACKNOWLEDGMENT`, `ACKNOWLEDGED`, `NOT_APPLICABLE`
|
||||
2. **48-Hour Follow-Up Queue (Derived Query Condition)**:
|
||||
- At 48 hours before `scheduled_at` (configurable via `PAYMENT_FOLLOWUP_THRESHOLD_HOURS`), any `RESERVED` booking with `payment_status = 'AWAITING_ACKNOWLEDGMENT'` surfaces in `GET /bookings/follow-up-queue`.
|
||||
- No background worker mutates or expires the booking; the threshold controls operational visibility.
|
||||
3. **Audited Administrative Actions**:
|
||||
- **Acknowledge Payment**: Verifies SPEI/cash receipt and sets `payment_status = 'ACKNOWLEDGED'`, recording `acknowledged_by` and `acknowledged_at`.
|
||||
- **Authorize Delayed Payment**: Sets `payment_arrangement = 'DELAYED_ALLOWED'` while keeping `payment_status = 'AWAITING_ACKNOWLEDGMENT'`, recording `exception_authorized_by`, `exception_authorized_at`, and `exception_notes`.
|
||||
- **Release Slot**: Sets `booking_status = 'RELEASED'` (and `payment_status = 'NOT_APPLICABLE'` if no session occurred), recording `released_by`, `released_at`, and `release_reason`, immediately freeing the slot for another client.
|
||||
|
||||
## Consequences
|
||||
### Positive
|
||||
- **Zero Payment Default**: Eliminates the "pay after session" trap without charging gateway transaction fees.
|
||||
- **Cultural Alignment**: "Apartar lugar con comprobante" is standard and culturally respected in Mexican wellness communities.
|
||||
- **Low Friction**: Leverages the tool clients already use continuously (WhatsApp).
|
||||
- **Operational Honesty**: Delayed-payment exceptions remain visible as receivables until actually paid and acknowledged.
|
||||
- **Human-in-the-Loop Control**: Neither Jasmin nor her assistant loses a booking to an unexpected timer, while the 48-hour queue ensures no unpaid slot slips through unnoticed.
|
||||
- **Zero Background Infrastructure**: Deriving the 48-hour queue on read requires zero cron jobs or always-on workers, preserving the $0 Cloud Run scale-to-zero profile.
|
||||
|
||||
### Negative / Trade-offs
|
||||
- Requires Jazmín (or her assistant) to manually cross-check deposits in her bank app before clicking "Confirmar".
|
||||
- Requires Jasmin's assistant to review the 48-hour follow-up queue and click "Liberar espacio" (`RELEASED`) when a client declines to complete payment.
|
||||
@@ -1,26 +1,28 @@
|
||||
# ADR 0003: Mandatory Buffer Times and Automated Calendar Synchronization
|
||||
# ADR 0003: Mandatory Buffer Times and Recoverable Google Calendar Synchronization
|
||||
|
||||
## Status
|
||||
Accepted
|
||||
Accepted (Amended 2026-10-18)
|
||||
|
||||
## Context
|
||||
Discovery feedback from long-term clients revealed chronic 10-to-35-minute delays in therapy sessions. The root causes were twofold:
|
||||
1. Therapy sessions frequently overrun their scheduled duration due to emotional crises or deep patient complications.
|
||||
2. Individual sessions were scheduled back-to-back with zero buffer time.
|
||||
Additionally, Jazmín occasionally misremembered appointment hours or forgot to enter bookings into her calendar.
|
||||
Discovery feedback from long-term clients revealed chronic 10-to-35-minute delays in therapy sessions caused by emotional consultation overruns and back-to-back scheduling without buffers. Additionally, Jasmin relies on Google Calendar to view her daily schedule on her phone, while `armonia-api` (backed by Turso) must remain the authoritative record of business state.
|
||||
|
||||
## Decision
|
||||
1. **Mandatory Post-Session Buffers**: Every individual appointment slot enforces an unbookable 15-to-20-minute buffer interval immediately following the session. A 60-minute consultation blocks 75–80 minutes on the scheduling engine.
|
||||
2. **Automated Google Calendar Sync**: All bookings are synced directly via Google Calendar API:
|
||||
- `PENDING_PAYMENT` events are created with `[PENDIENTE]` and highlighted in Yellow.
|
||||
- `CONFIRMED` events transition to `[CONFIRMADO]` and highlighted in Green.
|
||||
- Native calendar push notifications remind Jazmín 24 hours and 1 hour prior to each appointment.
|
||||
1. **Mandatory Post-Session Buffers**: Every individual appointment (`ONE_ON_ONE`) enforces an unbookable 15-to-20-minute buffer interval immediately following the session. A 60-minute consultation blocks 75 minutes on the scheduling engine for any `RESERVED` booking.
|
||||
2. **Backend-Owned Truth with Google Calendar Coordination**:
|
||||
- `armonia-api` owns the authoritative booking and payment decision in Turso; Google Calendar reflects the schedule:
|
||||
- `[PAGO PENDIENTE]` when `booking_status = 'RESERVED'`, `payment_arrangement = 'PREPAID_DEFAULT'`, and `payment_status = 'AWAITING_ACKNOWLEDGMENT'`.
|
||||
- `[PAGO DIFERIDO]` when `booking_status = 'RESERVED'`, `payment_arrangement = 'DELAYED_ALLOWED'`, and `payment_status = 'AWAITING_ACKNOWLEDGMENT'`.
|
||||
- `[CONFIRMADO]` when `payment_status = 'ACKNOWLEDGED'` or `payment_arrangement = 'PACKAGE_REDEEMED'`.
|
||||
- Event deleted/cancelled when `booking_status` transitions to `RELEASED` or `CANCELLED`.
|
||||
3. **Visible & Recoverable Integration State**:
|
||||
- Each booking stores `gcal_event_id`, `gcal_sync_status` (`PENDING`, `SYNCED`, `FAILED`, `NOT_CONFIGURED`), `gcal_sync_error`, and `gcal_synced_at`.
|
||||
- If the Google Calendar API fails transiently, the Turso record is preserved with `gcal_sync_status = 'FAILED'` and administrators can retry synchronization via `POST /bookings/{id}/sync-calendar`.
|
||||
|
||||
## Consequences
|
||||
### Positive
|
||||
- Prevents cascade delays across consultations.
|
||||
- Eliminates forgotten sessions and schedule collisions.
|
||||
- Provides emotional decompression time for the therapist between patients.
|
||||
- Prevents cascade delays across consultations and frees slots immediately when a booking is `RELEASED`.
|
||||
- Prevents silent divergence between Turso and Google Calendar by surfacing `gcal_sync_status` and `gcal_sync_error` directly to the dashboard.
|
||||
- Works cleanly in local development and tests (`NOT_CONFIGURED` fallback when GCP credentials are absent).
|
||||
|
||||
### Negative / Trade-offs
|
||||
- Slightly reduces theoretical maximum daily capacity (e.g., maximum 5 sessions/day instead of 6). However, the trade-off strongly favors punctuality, professional reputation, and therapist well-being.
|
||||
- Slightly reduces theoretical maximum daily capacity (e.g., maximum 5 sessions/day instead of 6) in exchange for punctuality and therapist well-being.
|
||||
@@ -4,18 +4,18 @@
|
||||
Accepted
|
||||
|
||||
## Context
|
||||
Operational interviews revealed that clients frequently purchase therapy as multi-session packages (e.g., 5 or 10 sessions paid upfront). Currently, tracking remaining sessions (e.g. "sesión 8 de 10") is discussed informally at the end of consultations, relying on memory and chat history.
|
||||
Similarly, for recurring low-cost workshops (*Curso de Abundancia*, $50 MXN/session), Jazmín records attendees and payments on a physical sheet of paper and photographs it to share with her assistant.
|
||||
Operational interviews revealed that clients frequently purchase therapy as multi-session packages (e.g., 5 or 10 sessions). Currently, tracking remaining sessions (e.g. "sesión 8 de 10") is discussed informally at the end of consultations, relying on memory and chat history.
|
||||
Similarly, for recurring low-cost workshops (*Curso de Abundancia*, $50 MXN/session), Jasmin records attendees and payments on a physical sheet of paper and photographs it to share with her assistant.
|
||||
|
||||
## Decision
|
||||
1. **Package Domain Model**: We introduce a `packages` entity tracking `client_id`, `service_id`, `total_sessions`, and `completed_sessions`. Booking individual sessions decrements available package credits without triggering payment requests.
|
||||
2. **Digital Workshop Attendance Ledger**: We introduce an `occurrences` and `attendance` model allowing Jazmín or her assistant to record workshop participants and toggle payment status (`attended: true/false`, `payment_method: CASH | SPEI`) with a single mobile tap in `armonia-dashboard`.
|
||||
1. **Package Domain Model**: We introduce a `packages` entity tracking `client_id`, `service_id`, `total_sessions`, and `completed_sessions`. Booking individual sessions under a package sets `payment_arrangement = 'PACKAGE_REDEEMED'` and `payment_status = 'NOT_APPLICABLE'`, decrementing available package credits without entering the unpaid follow-up queue.
|
||||
2. **Digital Workshop Attendance Ledger**: We support workshop roster tracking allowing Jasmin or her assistant to record workshop participants and payment status in `armonia-dashboard`.
|
||||
|
||||
## Consequences
|
||||
### Positive
|
||||
- Completely replaces physical paper sheets and phone photographs.
|
||||
- Eliminates awkward verbal disputes over remaining package sessions.
|
||||
- Enables collaborative coordination between Jazmín and her assistant.
|
||||
- Eliminates verbal confusion over remaining package sessions.
|
||||
- Enables collaborative coordination between Jasmin and her assistant.
|
||||
|
||||
### Negative / Trade-offs
|
||||
- Adds additional entities (`packages`, `attendance`) to the data model and migration pipeline.
|
||||
- Adds `packages` entity management to the data model.
|
||||
@@ -0,0 +1,28 @@
|
||||
# ADR 0005: Backend Google OAuth2 Authentication and Turso Administrator Allowlist
|
||||
|
||||
## Status
|
||||
Accepted (2026-10-18)
|
||||
|
||||
## Context
|
||||
`armonia-dashboard` is an operational control surface used by Jasmin and her assistant to acknowledge SPEI/cash payments, authorize delayed-payment exceptions, and release booking slots. Because `armonia-dashboard` is deployed as a static application on Cloudflare Pages, client-side route guards alone cannot protect administrative operations or keep OAuth secrets safe. Furthermore, if Jasmin rotates her assistant, revoking access must take effect immediately without rebuilding or redeploying containers.
|
||||
|
||||
## Decision
|
||||
1. **Backend-Driven Google OAuth2 Authorization Code Flow**:
|
||||
- `armonia-api` hosts `/auth/google/login` and `/auth/google/callback`, keeping `GOOGLE_OAUTH_CLIENT_ID`, `GOOGLE_OAUTH_CLIENT_SECRET`, and `SESSION_SECRET_KEY` strictly on the backend.
|
||||
- Upon callback, `armonia-api` exchanges the authorization code with Google, verifies `email_verified == true`, and checks the email against Turso's `admin_allowlist` table.
|
||||
- `armonia-api` issues an HMAC-SHA256 signed session token (delivered via `HttpOnly` cookie and usable as a `Bearer` token).
|
||||
2. **Dedicated `admin_allowlist` Table in Turso**:
|
||||
- Stores `email PRIMARY KEY`, `full_name`, `role` (`OWNER`, `ASSISTANT`, `ADMIN`), `is_active`, `created_at`, and `last_login_at`.
|
||||
- Seeded idempotently on startup from `ADMIN_BOOTSTRAP_EMAILS`.
|
||||
- Checked on **every** authenticated administrative request so setting `is_active = 0` revokes access immediately.
|
||||
3. **Mandatory Audit Logging (`admin_audit_log`)**:
|
||||
- Every administrative mutation records the authenticated administrator's email, action type, target entity ID, and timestamp in `admin_audit_log` as well as on the booking/payment record (`acknowledged_by`, `exception_authorized_by`, `released_by`).
|
||||
|
||||
## Consequences
|
||||
### Positive
|
||||
- Zero OAuth client secrets or session signing keys exposed in the frontend bundle.
|
||||
- Instant administrator revocation or addition via Turso without container redeployment.
|
||||
- Complete accountability for who acknowledged a payment, authorized a delayed payment, or released a slot.
|
||||
|
||||
### Negative / Trade-offs
|
||||
- Every protected administrative request performs a fast primary-key lookup against `admin_allowlist` in Turso/SQLite.
|
||||
Reference in new issue
Block a user