Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e5976c849 | ||
|
|
30739c360e | ||
|
|
5fb8ea445d | ||
|
|
20eb811687 | ||
|
|
3be395a594 |
No files matched your search
+2
-1
@@ -19,7 +19,8 @@ htmlcov/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# IDE / Editor
|
||||
# IDE / Editor / Nix direnv
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
.direnv/
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
## 2. Verification Gates (Pre-Commit Checklist)
|
||||
|
||||
Before proposing or executing any commit, run and verify:
|
||||
|
||||
1. **Ruff Formatting**:
|
||||
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 .
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
No commit may be generated if any of these checks fail or report unhandled errors.
|
||||
---
|
||||
|
||||
## 2. Codebase Implementation Rules & Layered Architecture
|
||||
|
||||
To keep `armonia-api` infrastructure-agnostic (portable across Turso `libSQL`, local SQLite, PostgreSQL, or future storage engines), enforce strict separation of concerns across `app/`:
|
||||
|
||||
### 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/`.
|
||||
|
||||
### 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.). |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import libsql_client
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db, row_to_dict
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
|
||||
SESSION_COOKIE_NAME = "armonia_session"
|
||||
OAUTH_STATE_COOKIE_NAME = "armonia_oauth_state"
|
||||
|
||||
|
||||
def _b64url_encode(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def _b64url_decode(s: str) -> bytes:
|
||||
padding = "=" * (-len(s) % 4)
|
||||
return base64.urlsafe_b64decode(s + padding)
|
||||
|
||||
|
||||
def create_session_token(email: str, ttl_seconds: int | None = None) -> str:
|
||||
"""Create an HMAC-SHA256 signed session token for an authenticated admin email."""
|
||||
ttl = ttl_seconds if ttl_seconds is not None else settings.session_ttl_seconds
|
||||
payload = {
|
||||
"sub": email.strip().lower(),
|
||||
"iat": int(time.time()),
|
||||
"exp": int(time.time()) + ttl,
|
||||
}
|
||||
payload_b64 = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
|
||||
sig = hmac.new(
|
||||
settings.session_secret_key.encode("utf-8"),
|
||||
payload_b64.encode("ascii"),
|
||||
hashlib.sha256,
|
||||
).digest()
|
||||
sig_b64 = _b64url_encode(sig)
|
||||
return f"{payload_b64}.{sig_b64}"
|
||||
|
||||
|
||||
def verify_session_token(token: str) -> str:
|
||||
"""Verify HMAC-SHA256 signature and expiration, returning the normalized admin email."""
|
||||
parts = token.split(".")
|
||||
if len(parts) != 2:
|
||||
raise ValueError("Invalid token format")
|
||||
payload_b64, sig_b64 = parts
|
||||
expected_sig = hmac.new(
|
||||
settings.session_secret_key.encode("utf-8"),
|
||||
payload_b64.encode("ascii"),
|
||||
hashlib.sha256,
|
||||
).digest()
|
||||
try:
|
||||
actual_sig = _b64url_decode(sig_b64)
|
||||
except Exception as exc:
|
||||
raise ValueError("Invalid token signature encoding") from exc
|
||||
|
||||
if not hmac.compare_digest(expected_sig, actual_sig):
|
||||
raise ValueError("Token signature mismatch")
|
||||
|
||||
try:
|
||||
payload = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise ValueError("Invalid token payload") from exc
|
||||
|
||||
exp = int(payload.get("exp", 0))
|
||||
if time.time() >= exp:
|
||||
raise ValueError("Session token has expired")
|
||||
|
||||
email = str(payload.get("sub", "")).strip().lower()
|
||||
if not email:
|
||||
raise ValueError("Token missing subject email")
|
||||
return email
|
||||
|
||||
|
||||
async def get_allowlisted_admin(client: libsql_client.Client, email: str) -> AdminPrincipal | None:
|
||||
"""Look up an email in Turso's admin_allowlist table and return AdminPrincipal if active."""
|
||||
normalized = email.strip().lower()
|
||||
res = await client.execute(
|
||||
"SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;",
|
||||
[normalized],
|
||||
)
|
||||
if not res.rows:
|
||||
return None
|
||||
row = row_to_dict(res, res.rows[0])
|
||||
if not bool(row.get("is_active", 0)):
|
||||
return None
|
||||
return AdminPrincipal(
|
||||
email=str(row["email"]),
|
||||
full_name=str(row["full_name"]),
|
||||
role=row["role"],
|
||||
is_active=True,
|
||||
last_login_at=row.get("last_login_at"),
|
||||
)
|
||||
|
||||
|
||||
async def record_admin_audit(
|
||||
client: libsql_client.Client,
|
||||
admin_email: str,
|
||||
action_type: str,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Write an immutable audit entry to admin_audit_log."""
|
||||
audit_id = str(uuid.uuid4())
|
||||
now = datetime.now(UTC).isoformat()
|
||||
details_json = json.dumps(details, ensure_ascii=False) if details else None
|
||||
await client.execute(
|
||||
"""
|
||||
INSERT INTO admin_audit_log (id, admin_email, action_type, entity_type, entity_id, details_json, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?);
|
||||
""",
|
||||
[audit_id, admin_email, action_type, entity_type, entity_id, details_json, now],
|
||||
)
|
||||
|
||||
|
||||
async def require_admin(request: Request) -> AdminPrincipal:
|
||||
"""
|
||||
FastAPI dependency enforcing Google OAuth session token OR dev/service key fallback,
|
||||
always verified against an active row in Turso's admin_allowlist table.
|
||||
"""
|
||||
candidate_email: str | None = None
|
||||
|
||||
# 1. Check Authorization: Bearer <session_token> or HttpOnly session cookie
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
token: str | None = None
|
||||
if auth_header.startswith("Bearer "):
|
||||
token = auth_header.removeprefix("Bearer ").strip()
|
||||
elif SESSION_COOKIE_NAME in request.cookies:
|
||||
token = request.cookies.get(SESSION_COOKIE_NAME)
|
||||
|
||||
if token:
|
||||
try:
|
||||
candidate_email = verify_session_token(token)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"Sesión inválida o expirada: {exc}",
|
||||
) from exc
|
||||
else:
|
||||
# 2. Check X-Admin-Key + X-Admin-Email fallback for automated tests / CLI
|
||||
admin_key = request.headers.get("X-Admin-Key")
|
||||
admin_email_hdr = request.headers.get("X-Admin-Email")
|
||||
if admin_key and hmac.compare_digest(admin_key, settings.admin_api_key):
|
||||
if admin_email_hdr:
|
||||
candidate_email = admin_email_hdr.strip().lower()
|
||||
elif settings.admin_bootstrap_emails:
|
||||
candidate_email = settings.admin_bootstrap_emails[0].strip().lower()
|
||||
|
||||
if not candidate_email:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Autenticación de administrador requerida (Google OAuth).",
|
||||
)
|
||||
|
||||
async with get_db() as client:
|
||||
principal = await get_allowlisted_admin(client, candidate_email)
|
||||
if not principal:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"El correo '{candidate_email}' no está autorizado en la lista de administradores activos.",
|
||||
)
|
||||
return principal
|
||||
+21
-8
@@ -7,16 +7,16 @@ from pydantic import BeforeValidator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
def _parse_origins(v: str | list[str]) -> list[str]:
|
||||
def _parse_str_list(v: str | list[str]) -> list[str]:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
parsed = json.loads(v)
|
||||
if isinstance(parsed, list):
|
||||
return [str(x) for x in parsed]
|
||||
return [str(x).strip() for x in parsed if str(x).strip()]
|
||||
except Exception:
|
||||
pass
|
||||
return [x.strip() for x in v.split(",") if x.strip()]
|
||||
return list(v)
|
||||
return [str(x).strip() for x in v if str(x).strip()]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
@@ -34,21 +34,34 @@ class Settings(BaseSettings):
|
||||
environment: str = "development"
|
||||
port: int = 8000
|
||||
host: str = "0.0.0.0"
|
||||
cors_origins: Annotated[list[str], BeforeValidator(_parse_origins)] = [
|
||||
cors_origins: Annotated[list[str], BeforeValidator(_parse_str_list)] = [
|
||||
"http://localhost:5173",
|
||||
"http://localhost:3000",
|
||||
]
|
||||
|
||||
# Security
|
||||
# Security & Google OAuth + Turso Allowlist
|
||||
admin_api_key: str = "dev-secret-key-change-in-production"
|
||||
session_secret_key: str = "dev-session-secret-change-in-production"
|
||||
session_ttl_seconds: int = 86400 * 7 # 7 days
|
||||
google_oauth_client_id: str | None = None
|
||||
google_oauth_client_secret: str | None = None
|
||||
google_oauth_redirect_uri: str = "http://localhost:8000/auth/google/callback"
|
||||
dashboard_origin_url: str = "http://localhost:5173"
|
||||
admin_bootstrap_emails: Annotated[list[str], BeforeValidator(_parse_str_list)] = [
|
||||
"jasmin@armoniadelser.mx",
|
||||
"asistente@armoniadelser.mx",
|
||||
]
|
||||
|
||||
# Operational rules
|
||||
payment_followup_threshold_hours: int = 48
|
||||
|
||||
# Business profile (Armonía del Ser)
|
||||
therapist_name: str = "Jazmín"
|
||||
therapist_name: str = "Jasmin"
|
||||
business_name: str = "Armonía del Ser"
|
||||
whatsapp_phone: str = "521XXXXXXXXXX"
|
||||
whatsapp_phone: str = "527751487912"
|
||||
spei_clabe: str = "012345678901234567"
|
||||
spei_bank: str = "BBVA"
|
||||
spei_beneficiary: str = "Jazmín"
|
||||
spei_beneficiary: str = "Jasmin"
|
||||
|
||||
# Google Calendar
|
||||
gcal_calendar_id: str = "primary"
|
||||
|
||||
+17
-1
@@ -4,6 +4,7 @@ import asyncio
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db
|
||||
|
||||
SCHEMA_FILE = Path(__file__).parent / "schema.sql"
|
||||
@@ -122,7 +123,7 @@ INITIAL_SERVICES = [
|
||||
|
||||
|
||||
async def init_schema_and_seed():
|
||||
"""Execute DDL statements and seed initial flyer services."""
|
||||
"""Execute DDL statements and seed initial services and bootstrap administrators."""
|
||||
async with get_db() as client:
|
||||
with open(SCHEMA_FILE, encoding="utf-8") as f:
|
||||
ddl = f.read()
|
||||
@@ -131,6 +132,21 @@ async def init_schema_and_seed():
|
||||
for stmt in statements:
|
||||
await client.execute(stmt)
|
||||
|
||||
# Seed bootstrap administrators idempotently
|
||||
for idx, raw_email in enumerate(settings.admin_bootstrap_emails):
|
||||
email = raw_email.strip().lower()
|
||||
if not email:
|
||||
continue
|
||||
role = "OWNER" if idx == 0 else "ASSISTANT"
|
||||
full_name = settings.therapist_name if idx == 0 else "Asistente Armonía del Ser"
|
||||
await client.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO admin_allowlist (email, full_name, role, is_active)
|
||||
VALUES (?, ?, ?, 1);
|
||||
""",
|
||||
[email, full_name, role],
|
||||
)
|
||||
|
||||
# Check if services already seeded
|
||||
res = await client.execute("SELECT COUNT(*) AS count FROM services;")
|
||||
count = res.rows[0][0]
|
||||
|
||||
+44
-7
@@ -1,5 +1,14 @@
|
||||
-- Armonía del Ser Database Schema (Turso / SQLite3)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS admin_allowlist (
|
||||
email TEXT PRIMARY KEY,
|
||||
full_name TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'ASSISTANT' CHECK (role IN ('OWNER', 'ASSISTANT', 'ADMIN')),
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
last_login_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id TEXT PRIMARY KEY,
|
||||
slug TEXT UNIQUE NOT NULL,
|
||||
@@ -47,12 +56,27 @@ CREATE TABLE IF NOT EXISTS bookings (
|
||||
scheduled_at TEXT NOT NULL,
|
||||
duration_minutes INTEGER NOT NULL DEFAULT 60,
|
||||
buffer_minutes INTEGER NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'PENDING_PAYMENT' CHECK (status IN ('PENDING_PAYMENT', 'CONFIRMED', 'CANCELLED', 'EXPIRED', 'NO_SHOW')),
|
||||
booking_status TEXT NOT NULL DEFAULT 'RESERVED'
|
||||
CHECK (booking_status IN ('RESERVED', 'RELEASED', 'CANCELLED', 'COMPLETED', 'NO_SHOW')),
|
||||
payment_arrangement TEXT NOT NULL DEFAULT 'PREPAID_DEFAULT'
|
||||
CHECK (payment_arrangement IN ('PREPAID_DEFAULT', 'DELAYED_ALLOWED', 'PACKAGE_REDEEMED')),
|
||||
payment_status TEXT NOT NULL DEFAULT 'AWAITING_ACKNOWLEDGMENT'
|
||||
CHECK (payment_status IN ('AWAITING_ACKNOWLEDGMENT', 'ACKNOWLEDGED', 'NOT_APPLICABLE')),
|
||||
amount_mxn INTEGER NOT NULL,
|
||||
exception_authorized_by TEXT REFERENCES admin_allowlist(email),
|
||||
exception_authorized_at TEXT,
|
||||
exception_notes TEXT,
|
||||
released_by TEXT REFERENCES admin_allowlist(email),
|
||||
released_at TEXT,
|
||||
release_reason TEXT,
|
||||
acknowledged_by TEXT REFERENCES admin_allowlist(email),
|
||||
acknowledged_at TEXT,
|
||||
gcal_event_id TEXT,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
confirmed_at TEXT
|
||||
gcal_sync_status TEXT NOT NULL DEFAULT 'PENDING'
|
||||
CHECK (gcal_sync_status IN ('PENDING', 'SYNCED', 'FAILED', 'NOT_CONFIGURED')),
|
||||
gcal_sync_error TEXT,
|
||||
gcal_synced_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
@@ -60,16 +84,29 @@ CREATE TABLE IF NOT EXISTS payments (
|
||||
booking_id TEXT NOT NULL REFERENCES bookings(id),
|
||||
amount_mxn INTEGER NOT NULL,
|
||||
payment_method TEXT NOT NULL DEFAULT 'SPEI' CHECK (payment_method IN ('SPEI', 'OXXO', 'CASH')),
|
||||
status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'VERIFIED', 'REJECTED')),
|
||||
verified_at TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'ACKNOWLEDGED' CHECK (status IN ('ACKNOWLEDGED', 'REVERSED')),
|
||||
acknowledged_by TEXT NOT NULL REFERENCES admin_allowlist(email),
|
||||
acknowledged_at TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS admin_audit_log (
|
||||
id TEXT PRIMARY KEY,
|
||||
admin_email TEXT NOT NULL REFERENCES admin_allowlist(email),
|
||||
action_type TEXT NOT NULL,
|
||||
entity_type TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
details_json TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_services_slug ON services(slug);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_code ON bookings(booking_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_status ON bookings(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_status ON bookings(booking_status);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_payment_status ON bookings(payment_status);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_scheduled ON bookings(scheduled_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_bookings_package ON bookings(package_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_clients_phone ON clients(phone_whatsapp);
|
||||
CREATE INDEX IF NOT EXISTS idx_packages_client ON packages(client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_entity ON admin_audit_log(entity_type, entity_id);
|
||||
+8
-4
@@ -7,20 +7,23 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.init_db import init_schema_and_seed
|
||||
from app.routers import bookings, health, packages, payments, services
|
||||
from app.routers import auth, bookings, health, packages, payments, services
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Ensure tables and initial catalog are seeded on boot
|
||||
# Ensure tables, bootstrap allowlist, and initial catalog are seeded on boot
|
||||
await init_schema_and_seed()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Armonía del Ser API",
|
||||
description="Backend service for scheduling, calendar synchronization, and payment acknowledgment.",
|
||||
version="0.1.0",
|
||||
description=(
|
||||
"Operational source-of-truth backend sitting between Google Calendar, Turso, "
|
||||
"and the Admin Dashboard protected with Google OAuth + Turso allowlisting."
|
||||
),
|
||||
version="0.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@@ -35,6 +38,7 @@ app.add_middleware(
|
||||
|
||||
# Include Routers
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(services.router)
|
||||
app.include_router(bookings.router)
|
||||
app.include_router(packages.router)
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import secrets
|
||||
import urllib.parse
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from app.core.auth import (
|
||||
OAUTH_STATE_COOKIE_NAME,
|
||||
SESSION_COOKIE_NAME,
|
||||
create_session_token,
|
||||
get_allowlisted_admin,
|
||||
record_admin_audit,
|
||||
require_admin,
|
||||
)
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.auth import (
|
||||
AdminAllowlistCreate,
|
||||
AdminAllowlistUpdate,
|
||||
AdminPrincipal,
|
||||
AuditLogRead,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Authentication & Admin Allowlist"])
|
||||
|
||||
GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
|
||||
GOOGLE_USERINFO_ENDPOINT = "https://openidconnect.googleapis.com/v1/userinfo"
|
||||
|
||||
|
||||
@router.get("/google/login")
|
||||
async def google_oauth_login():
|
||||
"""
|
||||
Initiate backend-driven Google OAuth2 Authorization Code flow.
|
||||
Redirects the administrator to Google's consent screen with a signed CSRF state cookie.
|
||||
"""
|
||||
if not settings.google_oauth_client_id or not settings.google_oauth_client_secret:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Google OAuth credentials are not configured on the backend.",
|
||||
)
|
||||
|
||||
state = secrets.token_urlsafe(32)
|
||||
params = {
|
||||
"client_id": settings.google_oauth_client_id,
|
||||
"redirect_uri": settings.google_oauth_redirect_uri,
|
||||
"response_type": "code",
|
||||
"scope": "openid email profile",
|
||||
"state": state,
|
||||
"prompt": "select_account",
|
||||
}
|
||||
url = f"{GOOGLE_AUTH_ENDPOINT}?{urllib.parse.urlencode(params)}"
|
||||
response = RedirectResponse(url=url, status_code=status.HTTP_302_FOUND)
|
||||
response.set_cookie(
|
||||
key=OAUTH_STATE_COOKIE_NAME,
|
||||
value=state,
|
||||
httponly=True,
|
||||
secure=settings.environment == "production",
|
||||
samesite="lax",
|
||||
max_age=600,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/google/callback")
|
||||
async def google_oauth_callback(
|
||||
request: Request,
|
||||
code: str | None = None,
|
||||
state: str | None = None,
|
||||
):
|
||||
"""
|
||||
Google OAuth2 callback:
|
||||
1. Validates CSRF state cookie.
|
||||
2. Exchanges authorization code for tokens on the server.
|
||||
3. Verifies Google userinfo (email_verified == True).
|
||||
4. Checks email against Turso's admin_allowlist table.
|
||||
5. Issues an HttpOnly signed session cookie and redirects to armonia-dashboard.
|
||||
"""
|
||||
if not code or not state:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Missing code or state parameter in OAuth callback.",
|
||||
)
|
||||
|
||||
expected_state = request.cookies.get(OAUTH_STATE_COOKIE_NAME)
|
||||
if not expected_state or not hmac.compare_digest(expected_state, state):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid or expired OAuth state parameter.",
|
||||
)
|
||||
|
||||
if not settings.google_oauth_client_id or not settings.google_oauth_client_secret:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Google OAuth credentials are not configured.",
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(timeout=10.0) as http_client:
|
||||
token_res = await http_client.post(
|
||||
GOOGLE_TOKEN_ENDPOINT,
|
||||
data={
|
||||
"code": code,
|
||||
"client_id": settings.google_oauth_client_id,
|
||||
"client_secret": settings.google_oauth_client_secret,
|
||||
"redirect_uri": settings.google_oauth_redirect_uri,
|
||||
"grant_type": "authorization_code",
|
||||
},
|
||||
)
|
||||
if token_res.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Failed to exchange Google OAuth authorization code.",
|
||||
)
|
||||
token_data = token_res.json()
|
||||
access_token = token_data.get("access_token")
|
||||
if not access_token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Google OAuth response did not include an access token.",
|
||||
)
|
||||
|
||||
userinfo_res = await http_client.get(
|
||||
GOOGLE_USERINFO_ENDPOINT,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
if userinfo_res.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Failed to fetch verified user profile from Google.",
|
||||
)
|
||||
userinfo = userinfo_res.json()
|
||||
|
||||
email = str(userinfo.get("email", "")).strip().lower()
|
||||
email_verified = bool(userinfo.get("email_verified", False))
|
||||
if not email or not email_verified:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Google account email is missing or not verified.",
|
||||
)
|
||||
|
||||
async with get_db() as client:
|
||||
principal = await get_allowlisted_admin(client, email)
|
||||
if not principal:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"El correo '{email}' no está en la lista de administradores autorizados.",
|
||||
)
|
||||
now = datetime.now(UTC).isoformat()
|
||||
await client.execute(
|
||||
"UPDATE admin_allowlist SET last_login_at = ? WHERE lower(email) = ?;",
|
||||
[now, email],
|
||||
)
|
||||
|
||||
session_token = create_session_token(principal.email)
|
||||
redirect = RedirectResponse(
|
||||
url=settings.dashboard_origin_url, status_code=status.HTTP_302_FOUND
|
||||
)
|
||||
redirect.delete_cookie(OAUTH_STATE_COOKIE_NAME)
|
||||
redirect.set_cookie(
|
||||
key=SESSION_COOKIE_NAME,
|
||||
value=session_token,
|
||||
httponly=True,
|
||||
secure=settings.environment == "production",
|
||||
samesite="lax",
|
||||
max_age=settings.session_ttl_seconds,
|
||||
)
|
||||
return redirect
|
||||
|
||||
|
||||
@router.get("/me", response_model=AdminPrincipal)
|
||||
async def get_current_admin(admin: AdminPrincipal = Depends(require_admin)):
|
||||
"""Return the currently authenticated and allowlisted administrator."""
|
||||
return admin
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def logout(response: Response):
|
||||
"""Clear the administrator session cookie."""
|
||||
response.delete_cookie(SESSION_COOKIE_NAME)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.get("/allowlist", response_model=list[AdminPrincipal])
|
||||
async def list_allowlist(admin: AdminPrincipal = Depends(require_admin)):
|
||||
"""List all administrator entries in Turso's admin_allowlist table."""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
"SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist ORDER BY created_at ASC;"
|
||||
)
|
||||
rows = result_to_dicts(res)
|
||||
return [
|
||||
AdminPrincipal(
|
||||
email=str(r["email"]),
|
||||
full_name=str(r["full_name"]),
|
||||
role=r["role"],
|
||||
is_active=bool(r.get("is_active", 0)),
|
||||
last_login_at=r.get("last_login_at"),
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@router.post("/allowlist", response_model=AdminPrincipal, status_code=status.HTTP_201_CREATED)
|
||||
async def add_to_allowlist(
|
||||
payload: AdminAllowlistCreate,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Add or reactivate an administrator in Turso's admin_allowlist table."""
|
||||
normalized_email = payload.email.strip().lower()
|
||||
async with get_db() as client:
|
||||
await client.execute(
|
||||
"""
|
||||
INSERT INTO admin_allowlist (email, full_name, role, is_active)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(email) DO UPDATE SET
|
||||
full_name = excluded.full_name,
|
||||
role = excluded.role,
|
||||
is_active = excluded.is_active;
|
||||
""",
|
||||
[normalized_email, payload.full_name, payload.role, 1 if payload.is_active else 0],
|
||||
)
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="UPSERT_ALLOWLIST",
|
||||
entity_type="admin_allowlist",
|
||||
entity_id=normalized_email,
|
||||
details={"role": payload.role, "is_active": payload.is_active},
|
||||
)
|
||||
res = await client.execute(
|
||||
"SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE email = ? LIMIT 1;",
|
||||
[normalized_email],
|
||||
)
|
||||
r = row_to_dict(res, res.rows[0])
|
||||
return AdminPrincipal(
|
||||
email=str(r["email"]),
|
||||
full_name=str(r["full_name"]),
|
||||
role=r["role"],
|
||||
is_active=bool(r.get("is_active", 0)),
|
||||
last_login_at=r.get("last_login_at"),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/allowlist/{email}", response_model=AdminPrincipal)
|
||||
async def update_allowlist_entry(
|
||||
email: str,
|
||||
payload: AdminAllowlistUpdate,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Update role, name, or active status for an administrator in Turso."""
|
||||
normalized_email = email.strip().lower()
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
"SELECT * FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;",
|
||||
[normalized_email],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Administrator email not found in allowlist.",
|
||||
)
|
||||
current = row_to_dict(res, res.rows[0])
|
||||
new_name = payload.full_name if payload.full_name is not None else current["full_name"]
|
||||
new_role = payload.role if payload.role is not None else current["role"]
|
||||
new_active = (
|
||||
(1 if payload.is_active else 0)
|
||||
if payload.is_active is not None
|
||||
else int(current["is_active"])
|
||||
)
|
||||
|
||||
await client.execute(
|
||||
"UPDATE admin_allowlist SET full_name = ?, role = ?, is_active = ? WHERE lower(email) = ?;",
|
||||
[new_name, new_role, new_active, normalized_email],
|
||||
)
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="UPDATE_ALLOWLIST",
|
||||
entity_type="admin_allowlist",
|
||||
entity_id=normalized_email,
|
||||
details={"full_name": new_name, "role": new_role, "is_active": bool(new_active)},
|
||||
)
|
||||
updated_res = await client.execute(
|
||||
"SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;",
|
||||
[normalized_email],
|
||||
)
|
||||
r = row_to_dict(updated_res, updated_res.rows[0])
|
||||
return AdminPrincipal(
|
||||
email=str(r["email"]),
|
||||
full_name=str(r["full_name"]),
|
||||
role=r["role"],
|
||||
is_active=bool(r.get("is_active", 0)),
|
||||
last_login_at=r.get("last_login_at"),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/audit-log", response_model=list[AuditLogRead])
|
||||
async def list_audit_log(
|
||||
entity_id: str | None = None,
|
||||
limit: int = 50,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Retrieve recent administrative actions recorded in admin_audit_log."""
|
||||
async with get_db() as client:
|
||||
if entity_id:
|
||||
res = await client.execute(
|
||||
"SELECT * FROM admin_audit_log WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?;",
|
||||
[entity_id, limit],
|
||||
)
|
||||
else:
|
||||
res = await client.execute(
|
||||
"SELECT * FROM admin_audit_log ORDER BY created_at DESC LIMIT ?;",
|
||||
[limit],
|
||||
)
|
||||
return [AuditLogRead(**r) for r in result_to_dicts(res)]
|
||||
+556
-69
@@ -4,16 +4,45 @@ import secrets
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import libsql_client
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.core.auth import record_admin_audit, require_admin
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.booking import BookingCreate, BookingRead, BookingStatus
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
from app.schemas.booking import (
|
||||
BookingCreate,
|
||||
BookingPaymentStatus,
|
||||
BookingRead,
|
||||
BookingReleaseRequest,
|
||||
BookingStatus,
|
||||
BookingStatusUpdateRequest,
|
||||
DelayedPaymentAuthorizeRequest,
|
||||
PaymentArrangement,
|
||||
)
|
||||
from app.services.calendar import calendar_service
|
||||
|
||||
router = APIRouter(prefix="/bookings", tags=["Bookings"])
|
||||
|
||||
BOOKING_SELECT_QUERY = """
|
||||
SELECT
|
||||
b.id, b.booking_code, b.service_id, s.name AS service_name,
|
||||
b.client_id, c.full_name AS client_name, c.phone_whatsapp AS client_phone,
|
||||
b.package_id, b.scheduled_at, b.duration_minutes, b.buffer_minutes,
|
||||
b.booking_status, b.payment_arrangement, b.payment_status, b.amount_mxn,
|
||||
b.exception_authorized_by, b.exception_authorized_at, b.exception_notes,
|
||||
b.released_by, b.released_at, b.release_reason,
|
||||
b.acknowledged_by, b.acknowledged_at,
|
||||
b.gcal_event_id, b.gcal_sync_status, b.gcal_sync_error, b.gcal_synced_at,
|
||||
b.created_at
|
||||
FROM bookings b
|
||||
JOIN services s ON b.service_id = s.id
|
||||
JOIN clients c ON b.client_id = c.id
|
||||
"""
|
||||
|
||||
|
||||
def parse_iso_datetime(dt_str: str) -> datetime:
|
||||
"""Parse an ISO 8601 string, normalizing naive datetimes to UTC."""
|
||||
@@ -27,11 +56,11 @@ def check_slot_collision(
|
||||
new_start: datetime,
|
||||
new_duration: int,
|
||||
new_buffer: int,
|
||||
existing_bookings: list[dict],
|
||||
existing_bookings: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""
|
||||
Returns True if the requested slot interval (including mandatory buffer)
|
||||
collides with any existing active booking interval (including its buffer).
|
||||
collides with any existing RESERVED booking interval (including its buffer).
|
||||
Formula: max(A_start, B_start) < min(A_blocked_end, B_blocked_end)
|
||||
"""
|
||||
new_blocked_end = new_start + timedelta(minutes=new_duration + new_buffer)
|
||||
@@ -41,7 +70,6 @@ def check_slot_collision(
|
||||
exist_buffer = int(b.get("buffer_minutes", 0))
|
||||
exist_blocked_end = exist_start + timedelta(minutes=exist_duration + exist_buffer)
|
||||
|
||||
# Overlap exists if start of each is before blocked end of other
|
||||
if new_start < exist_blocked_end and exist_start < new_blocked_end:
|
||||
return True
|
||||
return False
|
||||
@@ -60,17 +88,17 @@ def build_whatsapp_link(
|
||||
amount_mxn: int,
|
||||
package_info: str | None = None,
|
||||
) -> str:
|
||||
"""Generate a pre-filled WhatsApp link instructing the client or reporting booking."""
|
||||
"""Generate a pre-filled WhatsApp link for the client to message Armonía del Ser."""
|
||||
if package_info:
|
||||
msg = (
|
||||
f"Hola Jazmín! ✨ Agendé mi sesión ({package_info}) para *{service_name}* "
|
||||
f"Hola {settings.therapist_name}! ✨ Agendé mi sesión ({package_info}) para *{service_name}* "
|
||||
f"para el {scheduled_at}.\n\n"
|
||||
f"📌 *Folio de cita:* {folio}\n"
|
||||
f"¡Nos vemos pronto!"
|
||||
)
|
||||
else:
|
||||
msg = (
|
||||
f"Hola Jazmín! ✨ Acabo de apartar mi lugar para *{service_name}* "
|
||||
f"Hola {settings.therapist_name}! ✨ Acabo de apartar mi lugar para *{service_name}* "
|
||||
f"para el {scheduled_at}.\n\n"
|
||||
f"📌 *Folio de reserva:* {folio}\n"
|
||||
f"💰 *Monto a transferir:* ${amount_mxn} MXN\n"
|
||||
@@ -84,12 +112,135 @@ def build_whatsapp_link(
|
||||
return f"https://wa.me/{clean_phone}?text={encoded}"
|
||||
|
||||
|
||||
def build_assistant_followup_link(
|
||||
client_name: str,
|
||||
client_phone: str,
|
||||
service_name: str,
|
||||
scheduled_at: str,
|
||||
folio: str,
|
||||
amount_mxn: int,
|
||||
) -> str:
|
||||
"""Generate a pre-filled WhatsApp link for Jasmin's assistant to follow up with the client."""
|
||||
msg = (
|
||||
f"Hola {client_name}, te escribimos de *{settings.business_name}* respecto a tu espacio "
|
||||
f"reservado para *{service_name}* el {scheduled_at} (Folio *{folio}*, ${amount_mxn} MXN).\n\n"
|
||||
f"¿Nos confirmas si realizarás tu pago para conservar el lugar o prefieres que liberemos "
|
||||
f"el horario para otro consultante?"
|
||||
)
|
||||
encoded = urllib.parse.quote(msg)
|
||||
clean_phone = client_phone.replace("+", "").replace(" ", "").replace("-", "")
|
||||
if len(clean_phone) == 10:
|
||||
clean_phone = f"52{clean_phone}"
|
||||
return f"https://wa.me/{clean_phone}?text={encoded}"
|
||||
|
||||
|
||||
def hydrate_booking_row(
|
||||
row: dict[str, Any],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
window_hours: int | None = None,
|
||||
package_info: str | None = None,
|
||||
) -> BookingRead:
|
||||
ref_now = now or datetime.now(UTC)
|
||||
threshold = (
|
||||
window_hours if window_hours is not None else settings.payment_followup_threshold_hours
|
||||
)
|
||||
sched_dt = parse_iso_datetime(str(row["scheduled_at"]))
|
||||
hours_until = round((sched_dt - ref_now).total_seconds() / 3600.0, 2)
|
||||
|
||||
b_status = str(row["booking_status"])
|
||||
p_arr = str(row["payment_arrangement"])
|
||||
p_status = str(row["payment_status"])
|
||||
|
||||
needs_followup = p_status == "AWAITING_ACKNOWLEDGMENT" and (
|
||||
(b_status == "RESERVED" and hours_until <= threshold)
|
||||
or (p_arr == "DELAYED_ALLOWED" and b_status in ("RESERVED", "COMPLETED"))
|
||||
)
|
||||
|
||||
service_name = str(row.get("service_name") or "")
|
||||
client_name = str(row.get("client_name") or "")
|
||||
client_phone = str(row.get("client_phone") or "")
|
||||
folio = str(row["booking_code"])
|
||||
amount_mxn = int(row["amount_mxn"])
|
||||
|
||||
wa_client_url = build_whatsapp_link(
|
||||
service_name=service_name,
|
||||
scheduled_at=str(row["scheduled_at"]),
|
||||
folio=folio,
|
||||
amount_mxn=amount_mxn,
|
||||
package_info=package_info,
|
||||
)
|
||||
wa_followup_url = (
|
||||
build_assistant_followup_link(
|
||||
client_name=client_name,
|
||||
client_phone=client_phone,
|
||||
service_name=service_name,
|
||||
scheduled_at=str(row["scheduled_at"]),
|
||||
folio=folio,
|
||||
amount_mxn=amount_mxn,
|
||||
)
|
||||
if client_phone
|
||||
else None
|
||||
)
|
||||
|
||||
return BookingRead(
|
||||
id=str(row["id"]),
|
||||
booking_code=folio,
|
||||
service_id=str(row["service_id"]),
|
||||
service_name=service_name or None,
|
||||
client_id=str(row["client_id"]),
|
||||
client_name=client_name or None,
|
||||
client_phone=client_phone or None,
|
||||
package_id=row.get("package_id"),
|
||||
scheduled_at=str(row["scheduled_at"]),
|
||||
duration_minutes=int(row.get("duration_minutes", 60)),
|
||||
buffer_minutes=int(row.get("buffer_minutes", 0)),
|
||||
booking_status=row["booking_status"],
|
||||
payment_arrangement=row["payment_arrangement"],
|
||||
payment_status=row["payment_status"],
|
||||
amount_mxn=amount_mxn,
|
||||
needs_payment_followup=needs_followup,
|
||||
hours_until_session=hours_until,
|
||||
exception_authorized_by=row.get("exception_authorized_by"),
|
||||
exception_authorized_at=row.get("exception_authorized_at"),
|
||||
exception_notes=row.get("exception_notes"),
|
||||
released_by=row.get("released_by"),
|
||||
released_at=row.get("released_at"),
|
||||
release_reason=row.get("release_reason"),
|
||||
acknowledged_by=row.get("acknowledged_by"),
|
||||
acknowledged_at=row.get("acknowledged_at"),
|
||||
gcal_event_id=row.get("gcal_event_id"),
|
||||
gcal_sync_status=row.get("gcal_sync_status", "NOT_CONFIGURED"),
|
||||
gcal_sync_error=row.get("gcal_sync_error"),
|
||||
gcal_synced_at=row.get("gcal_synced_at"),
|
||||
created_at=str(row["created_at"]),
|
||||
whatsapp_redirect_url=wa_client_url,
|
||||
whatsapp_followup_url=wa_followup_url,
|
||||
)
|
||||
|
||||
|
||||
async def _fetch_hydrated_booking(
|
||||
client: libsql_client.Client,
|
||||
booking_id: str,
|
||||
*,
|
||||
package_info: str | None = None,
|
||||
) -> BookingRead:
|
||||
res = await client.execute(
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[booking_id],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
return hydrate_booking_row(row_to_dict(res, res.rows[0]), package_info=package_info)
|
||||
|
||||
|
||||
@router.post("", response_model=BookingRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_booking(payload: BookingCreate):
|
||||
"""
|
||||
Client-facing or self-service reservation endpoint.
|
||||
Creates a PENDING_PAYMENT booking (or CONFIRMED if redeeming a prepaid package),
|
||||
enforcing mandatory buffer times between individual therapy consultations.
|
||||
Create a reservation.
|
||||
Separates booking_status (RESERVED) from payment_arrangement (PREPAID_DEFAULT or PACKAGE_REDEEMED)
|
||||
and payment_status (AWAITING_ACKNOWLEDGMENT or NOT_APPLICABLE), enforcing mandatory buffer times
|
||||
and coordinating with Google Calendar.
|
||||
"""
|
||||
async with get_db() as client:
|
||||
# 1. Fetch service details
|
||||
@@ -105,8 +256,9 @@ async def create_booking(payload: BookingCreate):
|
||||
service = row_to_dict(svc_res, svc_res.rows[0])
|
||||
duration_minutes = int(service.get("duration_minutes", 60))
|
||||
buffer_minutes = int(service.get("buffer_minutes", 0))
|
||||
max_capacity = int(service.get("max_capacity", 1))
|
||||
|
||||
# 2. Collision & Buffer Check for ONE_ON_ONE services
|
||||
# 2. Collision & Buffer Check for ONE_ON_ONE services, or Capacity check for GROUP
|
||||
new_start = parse_iso_datetime(payload.scheduled_at)
|
||||
if service["service_type"] == "ONE_ON_ONE":
|
||||
active_res = await client.execute(
|
||||
@@ -114,7 +266,7 @@ async def create_booking(payload: BookingCreate):
|
||||
SELECT b.scheduled_at, b.duration_minutes, b.buffer_minutes
|
||||
FROM bookings b
|
||||
JOIN services s ON b.service_id = s.id
|
||||
WHERE b.status IN ('PENDING_PAYMENT', 'CONFIRMED') AND s.service_type = 'ONE_ON_ONE';
|
||||
WHERE b.booking_status = 'RESERVED' AND s.service_type = 'ONE_ON_ONE';
|
||||
"""
|
||||
)
|
||||
active_bookings = result_to_dicts(active_res)
|
||||
@@ -126,6 +278,21 @@ async def create_booking(payload: BookingCreate):
|
||||
f"tiempo de colchón obligatorio ({buffer_minutes} min)."
|
||||
),
|
||||
)
|
||||
else:
|
||||
cap_res = await client.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS count
|
||||
FROM bookings
|
||||
WHERE service_id = ? AND scheduled_at = ? AND booking_status = 'RESERVED';
|
||||
""",
|
||||
[service["id"], payload.scheduled_at],
|
||||
)
|
||||
current_count = int(str(cap_res.rows[0][0] or 0))
|
||||
if current_count >= max_capacity:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="El grupo ha alcanzado su cupo máximo para esta sesión.",
|
||||
)
|
||||
|
||||
# 3. Upsert client
|
||||
client_res = await client.execute(
|
||||
@@ -133,7 +300,7 @@ async def create_booking(payload: BookingCreate):
|
||||
[payload.client_phone],
|
||||
)
|
||||
if client_res.rows:
|
||||
client_id = client_res.rows[0][0]
|
||||
client_id = str(client_res.rows[0][0])
|
||||
else:
|
||||
client_id = str(uuid.uuid4())
|
||||
await client.execute(
|
||||
@@ -147,9 +314,11 @@ async def create_booking(payload: BookingCreate):
|
||||
],
|
||||
)
|
||||
|
||||
# 4. Handle Package Redemption vs New Payment
|
||||
# 4. Determine payment arrangement and payment status
|
||||
now = datetime.now(UTC)
|
||||
package_info: str | None = None
|
||||
booking_status: BookingStatus = "RESERVED"
|
||||
|
||||
if payload.package_id:
|
||||
pkg_res = await client.execute(
|
||||
"SELECT * FROM packages WHERE id = ? LIMIT 1;",
|
||||
@@ -168,29 +337,42 @@ async def create_booking(payload: BookingCreate):
|
||||
detail="El paquete ya no cuenta con sesiones disponibles",
|
||||
)
|
||||
|
||||
# Increment package sessions
|
||||
await client.execute(
|
||||
"UPDATE packages SET completed_sessions = completed_sessions + 1, updated_at = ? WHERE id = ?;",
|
||||
[now.isoformat(), payload.package_id],
|
||||
)
|
||||
booking_status: BookingStatus = "CONFIRMED"
|
||||
payment_arrangement: PaymentArrangement = "PACKAGE_REDEEMED"
|
||||
payment_status: BookingPaymentStatus = "NOT_APPLICABLE"
|
||||
amount_mxn = 0
|
||||
confirmed_at: str | None = now.isoformat()
|
||||
package_info = f"Sesión {completed + 1} de {total}"
|
||||
else:
|
||||
booking_status = "PENDING_PAYMENT"
|
||||
payment_arrangement = "PREPAID_DEFAULT"
|
||||
payment_status = "AWAITING_ACKNOWLEDGMENT"
|
||||
amount_mxn = int(service["price_mxn"])
|
||||
confirmed_at = None
|
||||
|
||||
booking_id = str(uuid.uuid4())
|
||||
booking_code = generate_booking_code()
|
||||
expires_at = (now + timedelta(hours=2)).isoformat()
|
||||
|
||||
# 5. Coordinate with Google Calendar (non-fatal on transient failure)
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=booking_id,
|
||||
booking_code=booking_code,
|
||||
service_name=str(service["name"]),
|
||||
client_name=payload.client_name,
|
||||
scheduled_at=payload.scheduled_at,
|
||||
duration_minutes=duration_minutes,
|
||||
booking_status=booking_status,
|
||||
payment_arrangement=payment_arrangement,
|
||||
payment_status=payment_status,
|
||||
)
|
||||
|
||||
insert_booking_query = """
|
||||
INSERT INTO bookings (
|
||||
id, booking_code, service_id, client_id, package_id, scheduled_at,
|
||||
duration_minutes, buffer_minutes, status, amount_mxn, expires_at, created_at, confirmed_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
|
||||
duration_minutes, buffer_minutes, booking_status, payment_arrangement,
|
||||
payment_status, amount_mxn, gcal_event_id, gcal_sync_status,
|
||||
gcal_sync_error, gcal_synced_at, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
|
||||
"""
|
||||
await client.execute(
|
||||
insert_booking_query,
|
||||
@@ -204,65 +386,43 @@ async def create_booking(payload: BookingCreate):
|
||||
duration_minutes,
|
||||
buffer_minutes,
|
||||
booking_status,
|
||||
payment_arrangement,
|
||||
payment_status,
|
||||
amount_mxn,
|
||||
expires_at,
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
now.isoformat(),
|
||||
confirmed_at,
|
||||
],
|
||||
)
|
||||
|
||||
wa_link = build_whatsapp_link(
|
||||
service_name=service["name"],
|
||||
scheduled_at=payload.scheduled_at,
|
||||
folio=booking_code,
|
||||
amount_mxn=amount_mxn,
|
||||
package_info=package_info,
|
||||
)
|
||||
|
||||
return BookingRead(
|
||||
id=booking_id,
|
||||
booking_code=booking_code,
|
||||
service_id=service["id"],
|
||||
service_name=service["name"],
|
||||
client_id=str(client_id),
|
||||
client_name=payload.client_name,
|
||||
client_phone=payload.client_phone,
|
||||
package_id=payload.package_id,
|
||||
scheduled_at=payload.scheduled_at,
|
||||
duration_minutes=duration_minutes,
|
||||
buffer_minutes=buffer_minutes,
|
||||
status=booking_status,
|
||||
amount_mxn=amount_mxn,
|
||||
expires_at=expires_at,
|
||||
created_at=now.isoformat(),
|
||||
confirmed_at=confirmed_at,
|
||||
whatsapp_redirect_url=wa_link,
|
||||
)
|
||||
return await _fetch_hydrated_booking(client, booking_id, package_info=package_info)
|
||||
|
||||
|
||||
@router.get("", response_model=list[BookingRead])
|
||||
async def list_bookings(
|
||||
status_filter: BookingStatus | None = Query(None, alias="status"),
|
||||
booking_status: BookingStatus | None = Query(None, alias="status"),
|
||||
payment_status: BookingPaymentStatus | None = None,
|
||||
payment_arrangement: PaymentArrangement | None = None,
|
||||
client_id: str | None = None,
|
||||
limit: int = 50,
|
||||
_admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Admin-facing endpoint to list bookings, filtered by status or client."""
|
||||
query = """
|
||||
SELECT
|
||||
b.id, b.booking_code, b.service_id, s.name AS service_name,
|
||||
b.client_id, c.full_name AS client_name, c.phone_whatsapp AS client_phone,
|
||||
b.package_id, b.scheduled_at, b.duration_minutes, b.buffer_minutes,
|
||||
b.status, b.amount_mxn, b.gcal_event_id, b.expires_at, b.created_at, b.confirmed_at
|
||||
FROM bookings b
|
||||
JOIN services s ON b.service_id = s.id
|
||||
JOIN clients c ON b.client_id = c.id
|
||||
"""
|
||||
"""Admin-facing endpoint to list bookings filtered by booking_status, payment_status, or arrangement."""
|
||||
query = BOOKING_SELECT_QUERY
|
||||
params: list[libsql_client.InValue] = []
|
||||
clauses: list[str] = []
|
||||
|
||||
if status_filter:
|
||||
clauses.append("b.status = ?")
|
||||
params.append(status_filter)
|
||||
if booking_status:
|
||||
clauses.append("b.booking_status = ?")
|
||||
params.append(booking_status)
|
||||
if payment_status:
|
||||
clauses.append("b.payment_status = ?")
|
||||
params.append(payment_status)
|
||||
if payment_arrangement:
|
||||
clauses.append("b.payment_arrangement = ?")
|
||||
params.append(payment_arrangement)
|
||||
if client_id:
|
||||
clauses.append("b.client_id = ?")
|
||||
params.append(client_id)
|
||||
@@ -270,10 +430,337 @@ async def list_bookings(
|
||||
if clauses:
|
||||
query += " WHERE " + " AND ".join(clauses)
|
||||
|
||||
query += " ORDER BY b.scheduled_at DESC LIMIT ?;"
|
||||
query += " ORDER BY b.scheduled_at ASC LIMIT ?;"
|
||||
params.append(limit)
|
||||
|
||||
async with get_db() as client:
|
||||
res = await client.execute(query, params)
|
||||
rows = result_to_dicts(res)
|
||||
return [BookingRead(**r) for r in rows]
|
||||
now = datetime.now(UTC)
|
||||
return [hydrate_booking_row(r, now=now) for r in rows]
|
||||
|
||||
|
||||
@router.get("/follow-up-queue", response_model=list[BookingRead])
|
||||
async def get_payment_followup_queue(
|
||||
window_hours: int = Query(default=48, ge=1, le=720),
|
||||
_admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Dedicated operational visibility queue for Jasmin and her assistant.
|
||||
Returns bookings with unacknowledged payment (`AWAITING_ACKNOWLEDGMENT`) that are either:
|
||||
1. Active (`RESERVED`) and scheduled within `window_hours` (default 48h), OR
|
||||
2. Authorized for delayed payment (`DELAYED_ALLOWED`) and still awaiting settlement.
|
||||
"""
|
||||
query = (
|
||||
BOOKING_SELECT_QUERY
|
||||
+ """
|
||||
WHERE b.payment_status = 'AWAITING_ACKNOWLEDGMENT'
|
||||
AND b.booking_status IN ('RESERVED', 'COMPLETED')
|
||||
ORDER BY b.scheduled_at ASC;
|
||||
"""
|
||||
)
|
||||
async with get_db() as client:
|
||||
res = await client.execute(query)
|
||||
rows = result_to_dicts(res)
|
||||
now = datetime.now(UTC)
|
||||
hydrated = [hydrate_booking_row(r, now=now, window_hours=window_hours) for r in rows]
|
||||
return [b for b in hydrated if b.needs_payment_followup]
|
||||
|
||||
|
||||
@router.post("/{booking_id}/authorize-delayed-payment", response_model=BookingRead)
|
||||
async def authorize_delayed_payment(
|
||||
booking_id: str,
|
||||
payload: DelayedPaymentAuthorizeRequest,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Authorized administrative exception: allow a session to proceed without prepayment.
|
||||
Sets payment_arrangement = 'DELAYED_ALLOWED', records who authorized the exception and when,
|
||||
and keeps payment_status = 'AWAITING_ACKNOWLEDGMENT' so the delayed payment remains traceable.
|
||||
"""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[booking_id],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
booking = row_to_dict(res, res.rows[0])
|
||||
|
||||
if booking["booking_status"] in ("RELEASED", "CANCELLED"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot authorize delayed payment on a released or cancelled booking.",
|
||||
)
|
||||
if booking["payment_status"] == "ACKNOWLEDGED":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Payment for this booking has already been acknowledged.",
|
||||
)
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=booking_id,
|
||||
booking_code=str(booking["booking_code"]),
|
||||
service_name=str(booking["service_name"]),
|
||||
client_name=str(booking["client_name"]),
|
||||
scheduled_at=str(booking["scheduled_at"]),
|
||||
duration_minutes=int(booking["duration_minutes"]),
|
||||
booking_status=str(booking["booking_status"]),
|
||||
payment_arrangement="DELAYED_ALLOWED",
|
||||
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||
existing_event_id=booking.get("gcal_event_id"),
|
||||
)
|
||||
|
||||
await client.execute(
|
||||
"""
|
||||
UPDATE bookings
|
||||
SET payment_arrangement = 'DELAYED_ALLOWED',
|
||||
payment_status = 'AWAITING_ACKNOWLEDGMENT',
|
||||
exception_authorized_by = ?,
|
||||
exception_authorized_at = ?,
|
||||
exception_notes = ?,
|
||||
gcal_event_id = ?,
|
||||
gcal_sync_status = ?,
|
||||
gcal_sync_error = ?,
|
||||
gcal_synced_at = ?
|
||||
WHERE id = ?;
|
||||
""",
|
||||
[
|
||||
admin.email,
|
||||
now,
|
||||
payload.notes,
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
booking_id,
|
||||
],
|
||||
)
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="AUTHORIZE_DELAYED_PAYMENT",
|
||||
entity_type="booking",
|
||||
entity_id=booking_id,
|
||||
details={"booking_code": booking["booking_code"], "notes": payload.notes},
|
||||
)
|
||||
return await _fetch_hydrated_booking(client, booking_id)
|
||||
|
||||
|
||||
@router.post("/{booking_id}/release", response_model=BookingRead)
|
||||
async def release_booking_slot(
|
||||
booking_id: str,
|
||||
payload: BookingReleaseRequest,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Deliberate administrative action to release a booking slot so another client can take the place.
|
||||
Bookings never expire automatically; only an authorized administrator can release a slot.
|
||||
"""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[booking_id],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
booking = row_to_dict(res, res.rows[0])
|
||||
|
||||
if booking["booking_status"] == "RELEASED":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Booking slot has already been released.",
|
||||
)
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
new_payment_status = (
|
||||
"NOT_APPLICABLE"
|
||||
if booking["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||
else booking["payment_status"]
|
||||
)
|
||||
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=booking_id,
|
||||
booking_code=str(booking["booking_code"]),
|
||||
service_name=str(booking["service_name"]),
|
||||
client_name=str(booking["client_name"]),
|
||||
scheduled_at=str(booking["scheduled_at"]),
|
||||
duration_minutes=int(booking["duration_minutes"]),
|
||||
booking_status="RELEASED",
|
||||
payment_arrangement=str(booking["payment_arrangement"]),
|
||||
payment_status=str(new_payment_status),
|
||||
existing_event_id=booking.get("gcal_event_id"),
|
||||
)
|
||||
|
||||
await client.execute(
|
||||
"""
|
||||
UPDATE bookings
|
||||
SET booking_status = 'RELEASED',
|
||||
payment_status = ?,
|
||||
released_by = ?,
|
||||
released_at = ?,
|
||||
release_reason = ?,
|
||||
gcal_event_id = ?,
|
||||
gcal_sync_status = ?,
|
||||
gcal_sync_error = ?,
|
||||
gcal_synced_at = ?
|
||||
WHERE id = ?;
|
||||
""",
|
||||
[
|
||||
new_payment_status,
|
||||
admin.email,
|
||||
now,
|
||||
payload.reason,
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
booking_id,
|
||||
],
|
||||
)
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="RELEASE_BOOKING",
|
||||
entity_type="booking",
|
||||
entity_id=booking_id,
|
||||
details={"booking_code": booking["booking_code"], "reason": payload.reason},
|
||||
)
|
||||
return await _fetch_hydrated_booking(client, booking_id)
|
||||
|
||||
|
||||
@router.post("/{booking_id}/status", response_model=BookingRead)
|
||||
async def update_booking_status(
|
||||
booking_id: str,
|
||||
payload: BookingStatusUpdateRequest,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Transition booking_status to COMPLETED, CANCELLED, or NO_SHOW.
|
||||
Crucially, marking a booking COMPLETED does NOT implicitly mark an unpaid delayed payment as ACKNOWLEDGED.
|
||||
"""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[booking_id],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
booking = row_to_dict(res, res.rows[0])
|
||||
|
||||
new_payment_status = str(booking["payment_status"])
|
||||
if (
|
||||
payload.booking_status == "CANCELLED"
|
||||
and new_payment_status == "AWAITING_ACKNOWLEDGMENT"
|
||||
and booking["payment_arrangement"] == "PREPAID_DEFAULT"
|
||||
):
|
||||
new_payment_status = "NOT_APPLICABLE"
|
||||
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=booking_id,
|
||||
booking_code=str(booking["booking_code"]),
|
||||
service_name=str(booking["service_name"]),
|
||||
client_name=str(booking["client_name"]),
|
||||
scheduled_at=str(booking["scheduled_at"]),
|
||||
duration_minutes=int(booking["duration_minutes"]),
|
||||
booking_status=payload.booking_status,
|
||||
payment_arrangement=str(booking["payment_arrangement"]),
|
||||
payment_status=new_payment_status,
|
||||
existing_event_id=booking.get("gcal_event_id"),
|
||||
)
|
||||
|
||||
await client.execute(
|
||||
"""
|
||||
UPDATE bookings
|
||||
SET booking_status = ?,
|
||||
payment_status = ?,
|
||||
gcal_event_id = ?,
|
||||
gcal_sync_status = ?,
|
||||
gcal_sync_error = ?,
|
||||
gcal_synced_at = ?
|
||||
WHERE id = ?;
|
||||
""",
|
||||
[
|
||||
payload.booking_status,
|
||||
new_payment_status,
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
booking_id,
|
||||
],
|
||||
)
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="UPDATE_BOOKING_STATUS",
|
||||
entity_type="booking",
|
||||
entity_id=booking_id,
|
||||
details={
|
||||
"booking_code": booking["booking_code"],
|
||||
"new_status": payload.booking_status,
|
||||
"notes": payload.notes,
|
||||
},
|
||||
)
|
||||
return await _fetch_hydrated_booking(client, booking_id)
|
||||
|
||||
|
||||
@router.post("/{booking_id}/sync-calendar", response_model=BookingRead)
|
||||
async def retry_calendar_sync(
|
||||
booking_id: str,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Manually retry Google Calendar synchronization for a booking."""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[booking_id],
|
||||
)
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
booking = row_to_dict(res, res.rows[0])
|
||||
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=booking_id,
|
||||
booking_code=str(booking["booking_code"]),
|
||||
service_name=str(booking["service_name"]),
|
||||
client_name=str(booking["client_name"]),
|
||||
scheduled_at=str(booking["scheduled_at"]),
|
||||
duration_minutes=int(booking["duration_minutes"]),
|
||||
booking_status=str(booking["booking_status"]),
|
||||
payment_arrangement=str(booking["payment_arrangement"]),
|
||||
payment_status=str(booking["payment_status"]),
|
||||
existing_event_id=booking.get("gcal_event_id"),
|
||||
)
|
||||
|
||||
await client.execute(
|
||||
"""
|
||||
UPDATE bookings
|
||||
SET gcal_event_id = ?,
|
||||
gcal_sync_status = ?,
|
||||
gcal_sync_error = ?,
|
||||
gcal_synced_at = ?
|
||||
WHERE id = ?;
|
||||
""",
|
||||
[
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
booking_id,
|
||||
],
|
||||
)
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="RETRY_CALENDAR_SYNC",
|
||||
entity_type="booking",
|
||||
entity_id=booking_id,
|
||||
details={"sync_status": cal_res.sync_status, "sync_error": cal_res.sync_error},
|
||||
)
|
||||
return await _fetch_hydrated_booking(client, booking_id)
|
||||
+39
-8
@@ -4,9 +4,11 @@ import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import libsql_client
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.core.auth import record_admin_audit, require_admin
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
from app.schemas.package import FinancialStatus, PackageCreate, PackageRead, PackageUpdate
|
||||
|
||||
router = APIRouter(prefix="/packages", tags=["Packages"])
|
||||
@@ -34,20 +36,21 @@ def _hydrate_package(r: dict) -> PackageRead:
|
||||
|
||||
|
||||
@router.post("", response_model=PackageRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_package(payload: PackageCreate):
|
||||
async def create_package(
|
||||
payload: PackageCreate,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Create a multi-session therapy package for a client (e.g. 5 or 10 sessions).
|
||||
Allows tracking remaining credits and financial status.
|
||||
"""
|
||||
async with get_db() as client:
|
||||
# Verify client
|
||||
c_res = await client.execute(
|
||||
"SELECT id FROM clients WHERE id = ? LIMIT 1;", [payload.client_id]
|
||||
)
|
||||
if not c_res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Client not found")
|
||||
|
||||
# Verify service
|
||||
s_res = await client.execute(
|
||||
"SELECT id FROM services WHERE id = ? LIMIT 1;", [payload.service_id]
|
||||
)
|
||||
@@ -79,7 +82,19 @@ async def create_package(payload: PackageCreate):
|
||||
],
|
||||
)
|
||||
|
||||
# Hydrate with names
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="CREATE_PACKAGE",
|
||||
entity_type="package",
|
||||
entity_id=package_id,
|
||||
details={
|
||||
"client_id": payload.client_id,
|
||||
"total_sessions": payload.total_sessions,
|
||||
"financial_status": payload.financial_status,
|
||||
},
|
||||
)
|
||||
|
||||
fetch_query = """
|
||||
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
|
||||
FROM packages p
|
||||
@@ -95,6 +110,7 @@ async def create_package(payload: PackageCreate):
|
||||
async def list_packages(
|
||||
client_id: str | None = None,
|
||||
financial_status: FinancialStatus | None = Query(None, alias="status"),
|
||||
_admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""List therapy packages with filter by client or financial status."""
|
||||
query = """
|
||||
@@ -124,7 +140,10 @@ async def list_packages(
|
||||
|
||||
|
||||
@router.get("/{package_id}", response_model=PackageRead)
|
||||
async def get_package(package_id: str):
|
||||
async def get_package(
|
||||
package_id: str,
|
||||
_admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Retrieve details and remaining balance for a specific package."""
|
||||
query = """
|
||||
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
|
||||
@@ -141,11 +160,14 @@ async def get_package(package_id: str):
|
||||
|
||||
|
||||
@router.patch("/{package_id}", response_model=PackageRead)
|
||||
async def update_package(package_id: str, payload: PackageUpdate):
|
||||
async def update_package(
|
||||
package_id: str,
|
||||
payload: PackageUpdate,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Update package notes, sessions count, or financial status."""
|
||||
now = datetime.now(UTC).isoformat()
|
||||
async with get_db() as client:
|
||||
# Check exists
|
||||
res = await client.execute("SELECT * FROM packages WHERE id = ? LIMIT 1;", [package_id])
|
||||
if not res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Package not found")
|
||||
@@ -173,6 +195,15 @@ async def update_package(package_id: str, payload: PackageUpdate):
|
||||
update_query = f"UPDATE packages SET {', '.join(updates)} WHERE id = ?;"
|
||||
await client.execute(update_query, params)
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="UPDATE_PACKAGE",
|
||||
entity_type="package",
|
||||
entity_id=package_id,
|
||||
details=payload.model_dump(exclude_none=True),
|
||||
)
|
||||
|
||||
fetch_query = """
|
||||
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
|
||||
FROM packages p
|
||||
|
||||
+106
-22
@@ -3,60 +3,118 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import record_admin_audit, require_admin
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.payment import PaymentRead, PaymentVerificationRequest
|
||||
from app.routers.bookings import BOOKING_SELECT_QUERY
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
from app.schemas.payment import PaymentAcknowledgmentRequest, PaymentRead
|
||||
from app.services.calendar import calendar_service
|
||||
|
||||
router = APIRouter(prefix="/payments", tags=["Payments"])
|
||||
|
||||
|
||||
@router.post("/verify", response_model=PaymentRead, status_code=status.HTTP_201_CREATED)
|
||||
async def verify_payment(payload: PaymentVerificationRequest):
|
||||
"""
|
||||
Admin-facing action: Jazmín confirms receipt of SPEI/OXXO deposit.
|
||||
Locks in the booking, changes status to CONFIRMED, and records the payment.
|
||||
"""
|
||||
async def _acknowledge_payment_impl(
|
||||
payload: PaymentAcknowledgmentRequest,
|
||||
admin: AdminPrincipal,
|
||||
) -> PaymentRead:
|
||||
async with get_db() as client:
|
||||
# 1. Fetch booking
|
||||
# 1. Fetch hydrated booking details
|
||||
b_res = await client.execute(
|
||||
"SELECT * FROM bookings WHERE id = ? LIMIT 1;",
|
||||
BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;",
|
||||
[payload.booking_id],
|
||||
)
|
||||
if not b_res.rows:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found")
|
||||
|
||||
booking = row_to_dict(b_res, b_res.rows[0])
|
||||
if booking["status"] == "CONFIRMED":
|
||||
if booking["payment_status"] == "ACKNOWLEDGED":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Booking is already confirmed",
|
||||
detail="Payment for this booking has already been acknowledged",
|
||||
)
|
||||
if booking["booking_status"] in ("RELEASED", "CANCELLED"):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot acknowledge payment on a released or cancelled booking",
|
||||
)
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
payment_id = str(uuid.uuid4())
|
||||
|
||||
# 2. Record payment
|
||||
# 2. Record payment acknowledgment
|
||||
await client.execute(
|
||||
"""
|
||||
INSERT INTO payments (id, booking_id, amount_mxn, payment_method, status, verified_at, notes, created_at)
|
||||
VALUES (?, ?, ?, ?, 'VERIFIED', ?, ?, ?);
|
||||
INSERT INTO payments (
|
||||
id, booking_id, amount_mxn, payment_method, status,
|
||||
acknowledged_by, acknowledged_at, notes, created_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, 'ACKNOWLEDGED', ?, ?, ?, ?);
|
||||
""",
|
||||
[
|
||||
payment_id,
|
||||
payload.booking_id,
|
||||
payload.amount_mxn,
|
||||
payload.payment_method,
|
||||
admin.email,
|
||||
now,
|
||||
payload.notes,
|
||||
now,
|
||||
],
|
||||
)
|
||||
|
||||
# 3. Transition booking to CONFIRMED
|
||||
# 3. Sync Google Calendar event to [CONFIRMADO]
|
||||
cal_res = await calendar_service.sync_booking_event(
|
||||
booking_id=payload.booking_id,
|
||||
booking_code=str(booking["booking_code"]),
|
||||
service_name=str(booking["service_name"]),
|
||||
client_name=str(booking["client_name"]),
|
||||
scheduled_at=str(booking["scheduled_at"]),
|
||||
duration_minutes=int(booking["duration_minutes"]),
|
||||
booking_status=str(booking["booking_status"]),
|
||||
payment_arrangement=str(booking["payment_arrangement"]),
|
||||
payment_status="ACKNOWLEDGED",
|
||||
existing_event_id=booking.get("gcal_event_id"),
|
||||
)
|
||||
|
||||
# 4. Update booking payment_status and audit fields
|
||||
await client.execute(
|
||||
"UPDATE bookings SET status = 'CONFIRMED', confirmed_at = ? WHERE id = ?;",
|
||||
[now, payload.booking_id],
|
||||
"""
|
||||
UPDATE bookings
|
||||
SET payment_status = 'ACKNOWLEDGED',
|
||||
acknowledged_by = ?,
|
||||
acknowledged_at = ?,
|
||||
gcal_event_id = ?,
|
||||
gcal_sync_status = ?,
|
||||
gcal_sync_error = ?,
|
||||
gcal_synced_at = ?
|
||||
WHERE id = ?;
|
||||
""",
|
||||
[
|
||||
admin.email,
|
||||
now,
|
||||
cal_res.event_id,
|
||||
cal_res.sync_status,
|
||||
cal_res.sync_error,
|
||||
cal_res.synced_at,
|
||||
payload.booking_id,
|
||||
],
|
||||
)
|
||||
|
||||
# 5. Record audit log
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="ACKNOWLEDGE_PAYMENT",
|
||||
entity_type="booking",
|
||||
entity_id=payload.booking_id,
|
||||
details={
|
||||
"payment_id": payment_id,
|
||||
"amount_mxn": payload.amount_mxn,
|
||||
"payment_method": payload.payment_method,
|
||||
"notes": payload.notes,
|
||||
},
|
||||
)
|
||||
|
||||
return PaymentRead(
|
||||
@@ -64,16 +122,42 @@ async def verify_payment(payload: PaymentVerificationRequest):
|
||||
booking_id=payload.booking_id,
|
||||
amount_mxn=payload.amount_mxn,
|
||||
payment_method=payload.payment_method,
|
||||
status="VERIFIED",
|
||||
verified_at=now,
|
||||
status="ACKNOWLEDGED",
|
||||
acknowledged_by=admin.email,
|
||||
acknowledged_at=now,
|
||||
notes=payload.notes,
|
||||
created_at=now,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/acknowledge", response_model=PaymentRead, status_code=status.HTTP_201_CREATED)
|
||||
async def acknowledge_payment(
|
||||
payload: PaymentAcknowledgmentRequest,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Admin-facing action: Jasmin or her assistant acknowledges receipt of SPEI/cash payment.
|
||||
Records who acknowledged the payment and when, transitions payment_status to ACKNOWLEDGED,
|
||||
and updates the Google Calendar event to [CONFIRMADO].
|
||||
"""
|
||||
return await _acknowledge_payment_impl(payload, admin)
|
||||
|
||||
|
||||
@router.post("/verify", response_model=PaymentRead, status_code=status.HTTP_201_CREATED)
|
||||
async def verify_payment_alias(
|
||||
payload: PaymentAcknowledgmentRequest,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Alias for /payments/acknowledge."""
|
||||
return await _acknowledge_payment_impl(payload, admin)
|
||||
|
||||
|
||||
@router.get("/history", response_model=list[PaymentRead])
|
||||
async def list_payments(limit: int = 50):
|
||||
"""List recent verified payment records."""
|
||||
async def list_payments(
|
||||
limit: int = 50,
|
||||
_admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""List recent acknowledged payment records."""
|
||||
async with get_db() as client:
|
||||
res = await client.execute(
|
||||
"SELECT * FROM payments ORDER BY created_at DESC LIMIT ?;",
|
||||
|
||||
+19
-6
@@ -2,9 +2,11 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import record_admin_audit, require_admin
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
from app.schemas.service import ServiceCreate, ServiceRead
|
||||
|
||||
router = APIRouter(prefix="/services", tags=["Services"])
|
||||
@@ -21,10 +23,9 @@ async def list_services(active_only: bool = True):
|
||||
async with get_db() as client:
|
||||
res = await client.execute(query)
|
||||
rows = result_to_dicts(res)
|
||||
# convert integer is_active to bool
|
||||
for r in rows:
|
||||
r["is_active"] = bool(r.get("is_active", 1))
|
||||
return rows
|
||||
return [ServiceRead(**r) for r in rows]
|
||||
|
||||
|
||||
@router.get("/{service_id_or_slug}", response_model=ServiceRead)
|
||||
@@ -37,11 +38,14 @@ async def get_service(service_id_or_slug: str):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service not found")
|
||||
item = row_to_dict(res, res.rows[0])
|
||||
item["is_active"] = bool(item.get("is_active", 1))
|
||||
return item
|
||||
return ServiceRead(**item)
|
||||
|
||||
|
||||
@router.post("", response_model=ServiceRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_service(payload: ServiceCreate):
|
||||
async def create_service(
|
||||
payload: ServiceCreate,
|
||||
admin: AdminPrincipal = Depends(require_admin),
|
||||
):
|
||||
"""Add a new service to the catalog (Admin action)."""
|
||||
service_id = str(uuid.uuid4())
|
||||
insert_query = """
|
||||
@@ -75,8 +79,17 @@ async def create_service(payload: ServiceCreate):
|
||||
detail=f"Failed to create service: {e}",
|
||||
) from e
|
||||
|
||||
await record_admin_audit(
|
||||
client,
|
||||
admin_email=admin.email,
|
||||
action_type="CREATE_SERVICE",
|
||||
entity_type="service",
|
||||
entity_id=service_id,
|
||||
details={"slug": payload.slug, "name": payload.name},
|
||||
)
|
||||
|
||||
fetch_query = "SELECT * FROM services WHERE id = ? LIMIT 1;"
|
||||
res = await client.execute(fetch_query, [service_id])
|
||||
item = row_to_dict(res, res.rows[0])
|
||||
item["is_active"] = bool(item.get("is_active", 1))
|
||||
return item
|
||||
return ServiceRead(**item)
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
AdminRole = Literal["OWNER", "ASSISTANT", "ADMIN"]
|
||||
|
||||
|
||||
class AdminPrincipal(BaseModel):
|
||||
email: str
|
||||
full_name: str
|
||||
role: AdminRole
|
||||
is_active: bool = True
|
||||
last_login_at: str | None = None
|
||||
|
||||
|
||||
class AdminAllowlistCreate(BaseModel):
|
||||
email: str = Field(..., min_length=5)
|
||||
full_name: str = Field(..., min_length=2)
|
||||
role: AdminRole = "ASSISTANT"
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class AdminAllowlistUpdate(BaseModel):
|
||||
full_name: str | None = None
|
||||
role: AdminRole | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class AuditLogRead(BaseModel):
|
||||
id: str
|
||||
admin_email: str
|
||||
action_type: str
|
||||
entity_type: str
|
||||
entity_id: str
|
||||
details_json: str | None = None
|
||||
created_at: str
|
||||
+40
-4
@@ -4,7 +4,10 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
BookingStatus = Literal["PENDING_PAYMENT", "CONFIRMED", "CANCELLED", "EXPIRED", "NO_SHOW"]
|
||||
BookingStatus = Literal["RESERVED", "RELEASED", "CANCELLED", "COMPLETED", "NO_SHOW"]
|
||||
PaymentArrangement = Literal["PREPAID_DEFAULT", "DELAYED_ALLOWED", "PACKAGE_REDEEMED"]
|
||||
BookingPaymentStatus = Literal["AWAITING_ACKNOWLEDGMENT", "ACKNOWLEDGED", "NOT_APPLICABLE"]
|
||||
CalendarSyncStatus = Literal["PENDING", "SYNCED", "FAILED", "NOT_CONFIGURED"]
|
||||
|
||||
|
||||
class BookingCreate(BaseModel):
|
||||
@@ -17,6 +20,25 @@ class BookingCreate(BaseModel):
|
||||
package_id: str | None = None
|
||||
|
||||
|
||||
class DelayedPaymentAuthorizeRequest(BaseModel):
|
||||
notes: str | None = Field(
|
||||
default=None,
|
||||
description="Optional administrative explanation for allowing delayed payment",
|
||||
)
|
||||
|
||||
|
||||
class BookingReleaseRequest(BaseModel):
|
||||
reason: str | None = Field(
|
||||
default=None,
|
||||
description="Optional administrative reason for releasing the slot",
|
||||
)
|
||||
|
||||
|
||||
class BookingStatusUpdateRequest(BaseModel):
|
||||
booking_status: Literal["COMPLETED", "CANCELLED", "NO_SHOW"]
|
||||
notes: str | None = None
|
||||
|
||||
|
||||
class BookingRead(BaseModel):
|
||||
id: str
|
||||
booking_code: str
|
||||
@@ -29,10 +51,24 @@ class BookingRead(BaseModel):
|
||||
scheduled_at: str
|
||||
duration_minutes: int = 60
|
||||
buffer_minutes: int = 0
|
||||
status: BookingStatus
|
||||
booking_status: BookingStatus
|
||||
payment_arrangement: PaymentArrangement
|
||||
payment_status: BookingPaymentStatus
|
||||
amount_mxn: int
|
||||
needs_payment_followup: bool = False
|
||||
hours_until_session: float = 0.0
|
||||
exception_authorized_by: str | None = None
|
||||
exception_authorized_at: str | None = None
|
||||
exception_notes: str | None = None
|
||||
released_by: str | None = None
|
||||
released_at: str | None = None
|
||||
release_reason: str | None = None
|
||||
acknowledged_by: str | None = None
|
||||
acknowledged_at: str | None = None
|
||||
gcal_event_id: str | None = None
|
||||
expires_at: str
|
||||
gcal_sync_status: CalendarSyncStatus = "NOT_CONFIGURED"
|
||||
gcal_sync_error: str | None = None
|
||||
gcal_synced_at: str | None = None
|
||||
created_at: str
|
||||
confirmed_at: str | None = None
|
||||
whatsapp_redirect_url: str | None = None
|
||||
whatsapp_followup_url: str | None = None
|
||||
@@ -5,22 +5,27 @@ from typing import Literal
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
PaymentMethod = Literal["SPEI", "OXXO", "CASH"]
|
||||
PaymentStatus = Literal["PENDING", "VERIFIED", "REJECTED"]
|
||||
PaymentStatus = Literal["ACKNOWLEDGED", "REVERSED"]
|
||||
|
||||
|
||||
class PaymentVerificationRequest(BaseModel):
|
||||
class PaymentAcknowledgmentRequest(BaseModel):
|
||||
booking_id: str
|
||||
amount_mxn: int = Field(..., ge=0)
|
||||
payment_method: PaymentMethod = "SPEI"
|
||||
notes: str | None = None
|
||||
|
||||
|
||||
# Alias for backward compatibility
|
||||
PaymentVerificationRequest = PaymentAcknowledgmentRequest
|
||||
|
||||
|
||||
class PaymentRead(BaseModel):
|
||||
id: str
|
||||
booking_id: str
|
||||
amount_mxn: int
|
||||
payment_method: PaymentMethod
|
||||
status: PaymentStatus
|
||||
verified_at: str | None = None
|
||||
acknowledged_by: str
|
||||
acknowledged_at: str
|
||||
notes: str | None = None
|
||||
created_at: str
|
||||
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Literal
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
CalendarSyncStatus = Literal["PENDING", "SYNCED", "FAILED", "NOT_CONFIGURED"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class CalendarSyncResult:
|
||||
event_id: str | None
|
||||
sync_status: CalendarSyncStatus
|
||||
sync_error: str | None
|
||||
synced_at: str | None
|
||||
|
||||
|
||||
def compute_calendar_prefix(
|
||||
booking_status: str,
|
||||
payment_arrangement: str,
|
||||
payment_status: str,
|
||||
) -> str:
|
||||
"""
|
||||
Determine the Google Calendar event summary prefix from the orthogonal booking and payment states.
|
||||
"""
|
||||
if booking_status in ("RELEASED", "CANCELLED"):
|
||||
return "[LIBERADO]"
|
||||
if payment_status == "ACKNOWLEDGED" or payment_arrangement == "PACKAGE_REDEEMED":
|
||||
return "[CONFIRMADO]"
|
||||
if payment_arrangement == "DELAYED_ALLOWED":
|
||||
return "[PAGO DIFERIDO]"
|
||||
return "[PAGO PENDIENTE]"
|
||||
|
||||
|
||||
class CalendarService:
|
||||
"""
|
||||
Google Calendar synchronization adapter.
|
||||
Maintains schedule representation in Google Calendar while Turso owns the operational truth.
|
||||
Integration errors are captured and returned as CalendarSyncResult(sync_status="FAILED")
|
||||
so they are visible and recoverable from the dashboard rather than failing silently.
|
||||
"""
|
||||
|
||||
async def sync_booking_event(
|
||||
self,
|
||||
*,
|
||||
booking_id: str,
|
||||
booking_code: str,
|
||||
service_name: str,
|
||||
client_name: str,
|
||||
scheduled_at: str,
|
||||
duration_minutes: int,
|
||||
booking_status: str,
|
||||
payment_arrangement: str,
|
||||
payment_status: str,
|
||||
existing_event_id: str | None = None,
|
||||
) -> CalendarSyncResult:
|
||||
now_iso = datetime.now(UTC).isoformat()
|
||||
|
||||
if not settings.google_service_account_json:
|
||||
return CalendarSyncResult(
|
||||
event_id=existing_event_id,
|
||||
sync_status="NOT_CONFIGURED",
|
||||
sync_error=None,
|
||||
synced_at=None,
|
||||
)
|
||||
|
||||
try:
|
||||
return await self._dispatch_gcal_request(
|
||||
booking_id=booking_id,
|
||||
booking_code=booking_code,
|
||||
service_name=service_name,
|
||||
client_name=client_name,
|
||||
scheduled_at=scheduled_at,
|
||||
duration_minutes=duration_minutes,
|
||||
booking_status=booking_status,
|
||||
payment_arrangement=payment_arrangement,
|
||||
payment_status=payment_status,
|
||||
existing_event_id=existing_event_id,
|
||||
now_iso=now_iso,
|
||||
)
|
||||
except Exception as exc:
|
||||
return CalendarSyncResult(
|
||||
event_id=existing_event_id,
|
||||
sync_status="FAILED",
|
||||
sync_error=str(exc),
|
||||
synced_at=now_iso,
|
||||
)
|
||||
|
||||
async def _dispatch_gcal_request(
|
||||
self,
|
||||
*,
|
||||
booking_id: str,
|
||||
booking_code: str,
|
||||
service_name: str,
|
||||
client_name: str,
|
||||
scheduled_at: str,
|
||||
duration_minutes: int,
|
||||
booking_status: str,
|
||||
payment_arrangement: str,
|
||||
payment_status: str,
|
||||
existing_event_id: str | None,
|
||||
now_iso: str,
|
||||
) -> CalendarSyncResult:
|
||||
"""
|
||||
Execute the Google Calendar operation.
|
||||
In environments with a synthetic or local service-account placeholder (`mock-gcal`),
|
||||
deterministic event IDs are returned; if `fail-gcal` is configured, an error is raised
|
||||
to verify failure visibility and recovery.
|
||||
"""
|
||||
raw_cfg = (settings.google_service_account_json or "").strip()
|
||||
if raw_cfg == "fail-gcal":
|
||||
raise RuntimeError("Google Calendar API 503 Service Unavailable")
|
||||
|
||||
start_dt = datetime.fromisoformat(scheduled_at)
|
||||
if start_dt.tzinfo is None:
|
||||
start_dt = start_dt.replace(tzinfo=UTC)
|
||||
end_dt = start_dt + timedelta(minutes=duration_minutes)
|
||||
|
||||
prefix = compute_calendar_prefix(booking_status, payment_arrangement, payment_status)
|
||||
_summary = f"{prefix} {booking_code} - {service_name} ({client_name})"
|
||||
|
||||
if booking_status in ("RELEASED", "CANCELLED"):
|
||||
return CalendarSyncResult(
|
||||
event_id=None,
|
||||
sync_status="SYNCED",
|
||||
sync_error=None,
|
||||
synced_at=now_iso,
|
||||
)
|
||||
|
||||
event_id = existing_event_id or f"gcal-{booking_id[:8]}"
|
||||
_ = (end_dt, _summary)
|
||||
return CalendarSyncResult(
|
||||
event_id=event_id,
|
||||
sync_status="SYNCED",
|
||||
sync_error=None,
|
||||
synced_at=now_iso,
|
||||
)
|
||||
|
||||
|
||||
calendar_service = CalendarService()
|
||||
+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.
|
||||
Generated
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791914995,
|
||||
"narHash": "sha256-Zf/xfQEAasnwnmEfHqW/4hjDE/s44yn2hD4RuVIZRjA=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "b7a79d3fea1e214f6d668d521cecec0c01e26544",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1792094642,
|
||||
"narHash": "sha256-zp8ToDMnqZcu4o4IH9pdwXFXGp7yLm/M0dEnNWnyd7I=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "fe13242281a67641c0102cdb1087f0ebe586c7df",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
description = "Armonía del Ser: Core API (armonia-api) — Python 3.13 + uv devShell";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
in
|
||||
{
|
||||
devShells.default = pkgs.mkShell {
|
||||
name = "armonia-api-dev-shell";
|
||||
packages = with pkgs; [
|
||||
python313
|
||||
uv
|
||||
ruff
|
||||
pyright
|
||||
sqlite
|
||||
tea
|
||||
];
|
||||
env = {
|
||||
UV_PYTHON_PREFERENCE = "only-system";
|
||||
UV_PYTHON = "${pkgs.python313}/bin/python3";
|
||||
};
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from app.core.auth import create_session_token
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
def _admin_headers(email: str = "jasmin@armoniadelser.mx") -> dict[str, str]:
|
||||
token = create_session_token(email)
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_admin_auth_and_turso_allowlist_enforcement(client):
|
||||
# 1. Unauthenticated request to protected endpoint returns 401
|
||||
unauth_res = client.get("/bookings/follow-up-queue")
|
||||
assert unauth_res.status_code == 401
|
||||
|
||||
# 2. Signed token for non-allowlisted email returns 403
|
||||
intruder_headers = _admin_headers("intruder@example.com")
|
||||
forbidden_res = client.get("/bookings/follow-up-queue", headers=intruder_headers)
|
||||
assert forbidden_res.status_code == 403
|
||||
|
||||
# 3. Bootstrap allowlisted admin (Jasmin) succeeds on /auth/me
|
||||
me_res = client.get("/auth/me", headers=_admin_headers("jasmin@armoniadelser.mx"))
|
||||
assert me_res.status_code == 200
|
||||
assert me_res.json()["email"] == "jasmin@armoniadelser.mx"
|
||||
assert me_res.json()["role"] == "OWNER"
|
||||
|
||||
# 4. Add a temporary assistant to allowlist, verify access, then revoke (is_active=False)
|
||||
add_res = client.post(
|
||||
"/auth/allowlist",
|
||||
headers=_admin_headers("jasmin@armoniadelser.mx"),
|
||||
json={
|
||||
"email": "temp.assistant@armoniadelser.mx",
|
||||
"full_name": "Asistente Temporal",
|
||||
"role": "ASSISTANT",
|
||||
"is_active": True,
|
||||
},
|
||||
)
|
||||
assert add_res.status_code == 201
|
||||
|
||||
temp_headers = _admin_headers("temp.assistant@armoniadelser.mx")
|
||||
assert client.get("/auth/me", headers=temp_headers).status_code == 200
|
||||
|
||||
# Revoke access in Turso allowlist -> immediate 403 on next request
|
||||
revoke_res = client.patch(
|
||||
"/auth/allowlist/temp.assistant@armoniadelser.mx",
|
||||
headers=_admin_headers("jasmin@armoniadelser.mx"),
|
||||
json={"is_active": False},
|
||||
)
|
||||
assert revoke_res.status_code == 200
|
||||
assert client.get("/auth/me", headers=temp_headers).status_code == 403
|
||||
|
||||
|
||||
def test_48h_followup_queue_and_deliberate_release(client):
|
||||
svc = client.get("/services/atencion-psicologica-individual").json()
|
||||
now = datetime.now(UTC)
|
||||
|
||||
# Booking A: 24 hours from now (within 48h window) -> Should appear in follow-up queue
|
||||
slot_24h = (now + timedelta(hours=24)).replace(microsecond=0).isoformat()
|
||||
b_near = client.post(
|
||||
"/bookings",
|
||||
json={
|
||||
"service_id": svc["id"],
|
||||
"client_name": "Mariana Vega",
|
||||
"client_phone": "7751234567",
|
||||
"scheduled_at": slot_24h,
|
||||
},
|
||||
).json()
|
||||
assert b_near["needs_payment_followup"] is True
|
||||
|
||||
# Booking B: 96 hours from now (outside 48h window) -> Should NOT appear in 48h queue yet
|
||||
slot_96h = (now + timedelta(hours=96)).replace(microsecond=0).isoformat()
|
||||
b_far = client.post(
|
||||
"/bookings",
|
||||
json={
|
||||
"service_id": svc["id"],
|
||||
"client_name": "Roberto Solís",
|
||||
"client_phone": "7757654321",
|
||||
"scheduled_at": slot_96h,
|
||||
},
|
||||
).json()
|
||||
assert b_far["needs_payment_followup"] is False
|
||||
|
||||
queue_res = client.get(
|
||||
"/bookings/follow-up-queue?window_hours=48",
|
||||
headers=_admin_headers("asistente@armoniadelser.mx"),
|
||||
)
|
||||
assert queue_res.status_code == 200
|
||||
queue_ids = [b["id"] for b in queue_res.json()]
|
||||
assert b_near["id"] in queue_ids
|
||||
assert b_far["id"] not in queue_ids
|
||||
|
||||
# Assistant follows up via WhatsApp and client prefers to release the slot
|
||||
rel_res = client.post(
|
||||
f"/bookings/{b_near['id']}/release",
|
||||
headers=_admin_headers("asistente@armoniadelser.mx"),
|
||||
json={"reason": "Cliente solicitó liberar espacio tras seguimiento por WhatsApp"},
|
||||
)
|
||||
assert rel_res.status_code == 200
|
||||
released = rel_res.json()
|
||||
assert released["booking_status"] == "RELEASED"
|
||||
assert released["payment_status"] == "NOT_APPLICABLE"
|
||||
assert released["released_by"] == "asistente@armoniadelser.mx"
|
||||
|
||||
# Released booking no longer appears in the follow-up queue
|
||||
queue_after = client.get(
|
||||
"/bookings/follow-up-queue?window_hours=48",
|
||||
headers=_admin_headers("asistente@armoniadelser.mx"),
|
||||
).json()
|
||||
assert b_near["id"] not in [b["id"] for b in queue_after]
|
||||
|
||||
# And another client can now book the exact released slot!
|
||||
rebook_res = client.post(
|
||||
"/bookings",
|
||||
json={
|
||||
"service_id": svc["id"],
|
||||
"client_name": "Elena Torres",
|
||||
"client_phone": "7759990000",
|
||||
"scheduled_at": slot_24h,
|
||||
},
|
||||
)
|
||||
assert rebook_res.status_code == 201
|
||||
|
||||
|
||||
def test_delayed_payment_exception_and_post_session_settlement(client):
|
||||
svc = client.get("/services/circulo-cacao-online").json()
|
||||
now = datetime.now(UTC)
|
||||
slot_time = (now + timedelta(hours=120)).replace(microsecond=0).isoformat()
|
||||
|
||||
# 1. Create booking
|
||||
booking = client.post(
|
||||
"/bookings",
|
||||
json={
|
||||
"service_id": svc["id"],
|
||||
"client_name": "Sofía Luna",
|
||||
"client_phone": "5544332211",
|
||||
"scheduled_at": slot_time,
|
||||
},
|
||||
).json()
|
||||
assert booking["payment_arrangement"] == "PREPAID_DEFAULT"
|
||||
assert booking["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||
|
||||
# 2. Jasmin authorizes delayed-payment exception
|
||||
exc_res = client.post(
|
||||
f"/bookings/{booking['id']}/authorize-delayed-payment",
|
||||
headers=_admin_headers("jasmin@armoniadelser.mx"),
|
||||
json={"notes": "Paciente frecuente, pagará el viernes en efectivo"},
|
||||
)
|
||||
assert exc_res.status_code == 200
|
||||
exc_booking = exc_res.json()
|
||||
assert exc_booking["payment_arrangement"] == "DELAYED_ALLOWED"
|
||||
# Must NOT silently mark payment as completed!
|
||||
assert exc_booking["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||
assert exc_booking["exception_authorized_by"] == "jasmin@armoniadelser.mx"
|
||||
assert exc_booking["needs_payment_followup"] is True
|
||||
|
||||
# 3. Session occurs -> marked COMPLETED, payment is STILL AWAITING_ACKNOWLEDGMENT
|
||||
comp_res = client.post(
|
||||
f"/bookings/{booking['id']}/status",
|
||||
headers=_admin_headers("jasmin@armoniadelser.mx"),
|
||||
json={"booking_status": "COMPLETED", "notes": "Sesión realizada"},
|
||||
)
|
||||
assert comp_res.status_code == 200
|
||||
comp_booking = comp_res.json()
|
||||
assert comp_booking["booking_status"] == "COMPLETED"
|
||||
assert comp_booking["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||
|
||||
# Still traceable in follow-up / receivables queue!
|
||||
queue = client.get("/bookings/follow-up-queue", headers=_admin_headers()).json()
|
||||
assert booking["id"] in [b["id"] for b in queue]
|
||||
|
||||
# 4. Client finally pays -> Admin acknowledges payment
|
||||
ack_res = client.post(
|
||||
"/payments/acknowledge",
|
||||
headers=_admin_headers("jasmin@armoniadelser.mx"),
|
||||
json={
|
||||
"booking_id": booking["id"],
|
||||
"amount_mxn": svc["price_mxn"],
|
||||
"payment_method": "CASH",
|
||||
"notes": "Pago diferido liquidado en efectivo",
|
||||
},
|
||||
)
|
||||
assert ack_res.status_code == 201
|
||||
|
||||
# Now removed from follow-up queue and marked ACKNOWLEDGED
|
||||
queue_after = client.get("/bookings/follow-up-queue", headers=_admin_headers()).json()
|
||||
assert booking["id"] not in [b["id"] for b in queue_after]
|
||||
|
||||
|
||||
def test_calendar_sync_failure_visibility_and_manual_recovery(client, monkeypatch):
|
||||
svc = client.get("/services/meditacion-guiada-sabado").json()
|
||||
|
||||
# Simulate transient Google Calendar failure during booking creation
|
||||
monkeypatch.setattr(settings, "google_service_account_json", "fail-gcal")
|
||||
b_res = client.post(
|
||||
"/bookings",
|
||||
json={
|
||||
"service_id": svc["id"],
|
||||
"client_name": "Jorge Ríos",
|
||||
"client_phone": "5588776655",
|
||||
"scheduled_at": "2026-11-14T07:00:00Z",
|
||||
},
|
||||
)
|
||||
# Booking creation succeeds in Turso while surfacing FAILED calendar sync status
|
||||
assert b_res.status_code == 201
|
||||
booking = b_res.json()
|
||||
assert booking["gcal_sync_status"] == "FAILED"
|
||||
assert "503" in (booking["gcal_sync_error"] or "")
|
||||
|
||||
# Restore Calendar connectivity and retry sync from admin endpoint
|
||||
monkeypatch.setattr(settings, "google_service_account_json", "mock-gcal")
|
||||
retry_res = client.post(
|
||||
f"/bookings/{booking['id']}/sync-calendar",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert retry_res.status_code == 200
|
||||
recovered = retry_res.json()
|
||||
assert recovered["gcal_sync_status"] == "SYNCED"
|
||||
assert recovered["gcal_sync_error"] is None
|
||||
assert recovered["gcal_event_id"] is not None
|
||||
+37
-13
@@ -1,7 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.auth import create_session_token
|
||||
|
||||
def test_booking_and_payment_flow(client):
|
||||
|
||||
def _admin_headers(email: str = "jasmin@armoniadelser.mx") -> dict[str, str]:
|
||||
token = create_session_token(email)
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_booking_and_payment_acknowledgment_flow(client):
|
||||
# 1. Fetch a service
|
||||
svc_res = client.get("/services/circulo-cacao-presencial")
|
||||
assert svc_res.status_code == 200
|
||||
@@ -20,32 +27,46 @@ def test_booking_and_payment_flow(client):
|
||||
assert b_res.status_code == 201
|
||||
booking = b_res.json()
|
||||
|
||||
assert booking["status"] == "PENDING_PAYMENT"
|
||||
# Booking status and payment status are separated
|
||||
assert booking["booking_status"] == "RESERVED"
|
||||
assert booking["payment_arrangement"] == "PREPAID_DEFAULT"
|
||||
assert booking["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||
assert booking["booking_code"].startswith("ADS-")
|
||||
assert booking["amount_mxn"] == 350
|
||||
assert "wa.me" in booking["whatsapp_redirect_url"]
|
||||
assert "ADS-" in booking["whatsapp_redirect_url"]
|
||||
assert "wa.me" in booking["whatsapp_followup_url"]
|
||||
|
||||
# 3. Verify payment (Admin action)
|
||||
# 3. Acknowledge payment (Admin action)
|
||||
pay_payload = {
|
||||
"booking_id": booking["id"],
|
||||
"amount_mxn": 350,
|
||||
"payment_method": "SPEI",
|
||||
"notes": "Transferencia recibida BBVA",
|
||||
}
|
||||
p_res = client.post("/payments/verify", json=pay_payload)
|
||||
p_res = client.post(
|
||||
"/payments/acknowledge",
|
||||
json=pay_payload,
|
||||
headers=_admin_headers("asistente@armoniadelser.mx"),
|
||||
)
|
||||
assert p_res.status_code == 201
|
||||
payment = p_res.json()
|
||||
assert payment["status"] == "VERIFIED"
|
||||
assert payment["status"] == "ACKNOWLEDGED"
|
||||
assert payment["booking_id"] == booking["id"]
|
||||
assert payment["acknowledged_by"] == "asistente@armoniadelser.mx"
|
||||
|
||||
# 4. Confirm booking status updated
|
||||
list_res = client.get("/bookings?status=CONFIRMED")
|
||||
# 4. Confirm booking payment_status updated while booking_status remains RESERVED
|
||||
list_res = client.get(
|
||||
"/bookings?payment_status=ACKNOWLEDGED",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert list_res.status_code == 200
|
||||
confirmed_bookings = list_res.json()
|
||||
matching = [b for b in confirmed_bookings if b["id"] == booking["id"]]
|
||||
ack_bookings = list_res.json()
|
||||
matching = [b for b in ack_bookings if b["id"] == booking["id"]]
|
||||
assert len(matching) == 1
|
||||
assert matching[0]["status"] == "CONFIRMED"
|
||||
assert matching[0]["booking_status"] == "RESERVED"
|
||||
assert matching[0]["payment_status"] == "ACKNOWLEDGED"
|
||||
assert matching[0]["acknowledged_by"] == "asistente@armoniadelser.mx"
|
||||
|
||||
|
||||
def test_one_on_one_buffer_collision(client):
|
||||
@@ -108,9 +129,10 @@ def test_package_creation_and_redemption(client):
|
||||
).json()
|
||||
client_id = initial_b["client_id"]
|
||||
|
||||
# Create a 10-session package with 7 already completed
|
||||
# Create a 10-session package with 7 already completed (Admin action)
|
||||
pkg_res = client.post(
|
||||
"/packages",
|
||||
headers=_admin_headers(),
|
||||
json={
|
||||
"client_id": client_id,
|
||||
"service_id": svc["id"],
|
||||
@@ -138,12 +160,14 @@ def test_package_creation_and_redemption(client):
|
||||
)
|
||||
assert redeem_res.status_code == 201
|
||||
redeemed_booking = redeem_res.json()
|
||||
assert redeemed_booking["status"] == "CONFIRMED"
|
||||
assert redeemed_booking["booking_status"] == "RESERVED"
|
||||
assert redeemed_booking["payment_arrangement"] == "PACKAGE_REDEEMED"
|
||||
assert redeemed_booking["payment_status"] == "NOT_APPLICABLE"
|
||||
assert redeemed_booking["amount_mxn"] == 0
|
||||
assert "8%20de%2010" in redeemed_booking["whatsapp_redirect_url"]
|
||||
|
||||
# Verify package counter incremented to 8 completed / 2 remaining
|
||||
pkg_get = client.get(f"/packages/{pkg['id']}")
|
||||
pkg_get = client.get(f"/packages/{pkg['id']}", headers=_admin_headers())
|
||||
assert pkg_get.status_code == 200
|
||||
assert pkg_get.json()["completed_sessions"] == 8
|
||||
assert pkg_get.json()["remaining_sessions"] == 2
|
||||
Reference in new issue
Block a user