feat: scaffold FastAPI backend with Turso and anti-ghosting booking state machine

- Initialize project with uv, FastAPI, and libsql-client for Turso persistence
- Implement local SQLite fallback (`file:local.db`) for zero-friction development and testing
- Create schema and seeder with 9 therapy services from Armonía del Ser flyer
- Implement POST /bookings with automatic WhatsApp deep-link generation and SPEI instructions
- Implement POST /payments/verify 1-tap admin acknowledgment flow
- Add automated test suite with 5 passing tests and verification gates (ruff, pyright, pytest)
This commit is contained in:
kiskaadee committed 2026-10-18 09:01:34 -05:00
1 parent 26899c3337
commit effa1ee86c
24 files changed
+2907 -2

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Database Configuration
# Local SQLite fallback:
DATABASE_URL=file:local.db
DATABASE_AUTH_TOKEN=
# Remote Turso production:
# DATABASE_URL=libsql://armonia-db-yourorg.turso.io
# DATABASE_AUTH_TOKEN=your_turso_token_here
# App settings
ENVIRONMENT=development
PORT=8000
HOST=0.0.0.0
CORS_ORIGINS=["http://localhost:5173","http://localhost:3000","https://armonia-dashboard.pages.dev","https://armonia-landing.pages.dev"]
# Admin Security (for armonia-dashboard)
ADMIN_API_KEY=dev-secret-key-change-in-production
# Jazmin Business Settings
THERAPIST_NAME="Jazmín"
BUSINESS_NAME="Armonía del Ser"
WHATSAPP_PHONE="521XXXXXXXXXX"
SPEI_CLABE="012345678901234567"
SPEI_BANK="BBVA"
SPEI_BENEFICIARY="Jazmín"
# Google Calendar Integration (Optional in local dev)
GCAL_CALENDAR_ID=primary
GOOGLE_SERVICE_ACCOUNT_JSON=
+25
View File
@@ -0,0 +1,25 @@
# Python & Virtual Environments
__pycache__/
*.py[cod]
*$py.class
.venv/
env/
venv/
.env
*.local.env
# Testing & Linting
.pytest_cache/
.ruff_cache/
.coverage
htmlcov/
# Local databases
*.db
*.sqlite
*.sqlite3
# IDE / Editor
.vscode/
.idea/
*.swp
+1
View File
@@ -0,0 +1 @@
3.13
+52
View File
@@ -0,0 +1,52 @@
# Armonía del Ser: API - Agent Guidelines & Workflow Rules
This document specifies mandatory workflows, constraints, and verification gates for AI agents operating in `armonia-api`.
---
## 1. Core Operating Constraints
- **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**:
```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.
---
## 3. Architecture & Domain Directives
- **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.
+94 -2
View File
@@ -1,3 +1,95 @@
# armonia-api
# Armonía del Ser: Core API (`armonia-api`)
FastAPI backend & Turso database integration for Armonía del Ser
Backend API service for **Armonía del Ser**—a holistic therapy, meditation, and personal growth center in Mexico.
Built with **FastAPI** and **Turso (libSQL)** to manage services, appointments, client records, and payment acknowledgments at zero infrastructure cost.
---
## Architecture & Design
```
[Clients / Landing UI] [Admin Dashboard (Jazmín)]
│ │
▼ ▼
┌──────────────────────────────────────────────────────────┐
│ FastAPI Core Service │
│ - Services Catalog (Group & 1-on-1) │
│ - Booking State Machine (Pending -> Confirmed) │
│ - Payment Verification & Acknowledgment │
│ - Dynamic WhatsApp Deep-Link Generator │
└──────────────┬─────────────────────────────┬─────────────┘
│ │
▼ ▼
[Turso Database] [Google Calendar API]
(SQLite / libSQL at edge) (Tentative [PENDIENTE] hold
-> Locked [CONFIRMADO])
```
### 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**:
- 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 Model Overview
| 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. |
| `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. |
---
## Local Development Quickstart
### Prerequisites
- Python 3.13+
- [`uv`](https://github.com/astral-sh/uv)
### 1. Setup Environment
```bash
cp .env.example .env
```
By default, `.env` uses `DATABASE_URL=file:local.db` for zero-configuration local SQLite testing.
### 2. Install Dependencies
```bash
uv sync
```
### 3. Initialize Database & Seed Services
```bash
uv run python -m app.db.init_db
```
### 4. Run Development Server
```bash
uv run uvicorn app.main:app --reload --port 8000
```
Interactive API docs are available at `http://localhost:8000/docs`.
---
## Verification Gates
All changes must pass local verification before proposing commits:
```bash
uv run ruff format --check .
uv run ruff check .
uv run pyright
uv run pytest
```
+58
View File
@@ -0,0 +1,58 @@
from __future__ import annotations
import json
from typing import Annotated
from pydantic import BeforeValidator
from pydantic_settings import BaseSettings, SettingsConfigDict
def _parse_origins(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]
except Exception:
pass
return [x.strip() for x in v.split(",") if x.strip()]
return list(v)
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
# Database
database_url: str = "file:local.db"
database_auth_token: str | None = None
# Application
environment: str = "development"
port: int = 8000
host: str = "0.0.0.0"
cors_origins: Annotated[list[str], BeforeValidator(_parse_origins)] = [
"http://localhost:5173",
"http://localhost:3000",
]
# Security
admin_api_key: str = "dev-secret-key-change-in-production"
# Business profile (Armonía del Ser)
therapist_name: str = "Jazmín"
business_name: str = "Armonía del Ser"
whatsapp_phone: str = "521XXXXXXXXXX"
spei_clabe: str = "012345678901234567"
spei_bank: str = "BBVA"
spei_beneficiary: str = "Jazmín"
# Google Calendar
gcal_calendar_id: str = "primary"
google_service_account_json: str | None = None
settings = Settings()
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
import contextlib
from collections.abc import AsyncIterator
from typing import Any
import libsql_client
from app.core.config import settings
def get_client() -> libsql_client.Client:
"""Create a new async Turso/libSQL client based on current settings."""
if settings.database_url.startswith("file:"):
return libsql_client.create_client(settings.database_url)
return libsql_client.create_client(
url=settings.database_url,
auth_token=settings.database_auth_token or "",
)
@contextlib.asynccontextmanager
async def get_db() -> AsyncIterator[libsql_client.Client]:
"""Dependency / context manager for acquiring a database client."""
client = get_client()
try:
yield client
finally:
await client.close()
def row_to_dict(result_set: libsql_client.ResultSet, row: libsql_client.Row) -> dict[str, Any]:
"""Helper to convert a libsql Row into a Python dictionary."""
return {col: val for col, val in zip(result_set.columns, row, strict=False)}
def result_to_dicts(result_set: libsql_client.ResultSet) -> list[dict[str, Any]]:
"""Helper to convert all rows of a ResultSet into dictionaries."""
return [row_to_dict(result_set, row) for row in result_set.rows]
+166
View File
@@ -0,0 +1,166 @@
from __future__ import annotations
import asyncio
import uuid
from pathlib import Path
from app.db.database import get_db
SCHEMA_FILE = Path(__file__).parent / "schema.sql"
INITIAL_SERVICES = [
{
"id": str(uuid.uuid4()),
"slug": "circulo-cacao-presencial",
"name": "Círculo de Cacao (Presencial)",
"description": "Espacio de reconexión con medicina de cacao, meditación y trabajo interior.",
"service_type": "GROUP",
"modality": "PRESENCIAL",
"default_schedule": "Lunes 6:00 p. m.",
"price_mxn": 350,
"max_capacity": 15,
"duration_minutes": 120,
},
{
"id": str(uuid.uuid4()),
"slug": "meditacion-cuencos-martes",
"name": "Meditación con cuencos (Martes)",
"description": "Sesión de armonización sonora con cuencos tibetanos.",
"service_type": "GROUP",
"modality": "PRESENCIAL",
"default_schedule": "Martes 7:00 a. m.",
"price_mxn": 200,
"max_capacity": 12,
"duration_minutes": 60,
},
{
"id": str(uuid.uuid4()),
"slug": "meditacion-ejercicios-conscientes",
"name": "Meditación con ejercicios conscientes",
"description": "Movimiento consciente y respiración para calmar la mente y armonizar tu energía.",
"service_type": "GROUP",
"modality": "PRESENCIAL",
"default_schedule": "Martes 8:00 a. m.",
"price_mxn": 200,
"max_capacity": 12,
"duration_minutes": 60,
},
{
"id": str(uuid.uuid4()),
"slug": "circulo-cacao-online",
"name": "Círculo de Cacao (Online)",
"description": "Conexión a distancia con la energía del cacao y círculo de sanación.",
"service_type": "GROUP",
"modality": "ONLINE",
"default_schedule": "Martes 7:00 p. m.",
"price_mxn": 300,
"max_capacity": 25,
"duration_minutes": 120,
},
{
"id": str(uuid.uuid4()),
"slug": "constelaciones-familiares-online",
"name": "Constelaciones Familiares (Online)",
"description": "Terapia sistémica grupal virtual para sanar dinámicas inconscientes familiares.",
"service_type": "GROUP",
"modality": "ONLINE",
"default_schedule": "Jueves 7:00 p. m.",
"price_mxn": 450,
"max_capacity": 20,
"duration_minutes": 120,
},
{
"id": str(uuid.uuid4()),
"slug": "clase-4-elementos-tarot",
"name": "Clase de los 4 Elementos y Tarot",
"description": "Exploración de la cosmovisión de los cuatro elementos integrada a la sabiduría del tarot.",
"service_type": "GROUP",
"modality": "ONLINE",
"default_schedule": "Viernes 9:00 a. m.",
"price_mxn": 300,
"max_capacity": 15,
"duration_minutes": 90,
},
{
"id": str(uuid.uuid4()),
"slug": "meditacion-guiada-sabado",
"name": "Meditación guiada (Sábado)",
"description": "Meditación guiada matutina para iniciar el fin de semana en paz y presencia.",
"service_type": "GROUP",
"modality": "PRESENCIAL",
"default_schedule": "Sábados 7:00 a. m.",
"price_mxn": 200,
"max_capacity": 15,
"duration_minutes": 60,
},
{
"id": str(uuid.uuid4()),
"slug": "meditacion-cuencos-sabado",
"name": "Meditación con cuencos (Sábado)",
"description": "Vibración y baño de sonido con cuencos tibetanos.",
"service_type": "GROUP",
"modality": "PRESENCIAL",
"default_schedule": "Sábados 8:00 a. m.",
"price_mxn": 200,
"max_capacity": 15,
"duration_minutes": 60,
},
{
"id": str(uuid.uuid4()),
"slug": "atencion-psicologica-individual",
"name": "Atención Psicológica Individual",
"description": "Sesión individual de psicoterapia personalizada (presencial u online).",
"service_type": "ONE_ON_ONE",
"modality": "PRESENCIAL",
"default_schedule": "Con cita previa",
"price_mxn": 600,
"max_capacity": 1,
"duration_minutes": 60,
},
]
async def init_schema_and_seed():
"""Execute DDL statements and seed initial flyer services."""
async with get_db() as client:
with open(SCHEMA_FILE, encoding="utf-8") as f:
ddl = f.read()
statements = [stmt.strip() for stmt in ddl.split(";") if stmt.strip()]
for stmt in statements:
await client.execute(stmt)
# Check if services already seeded
res = await client.execute("SELECT COUNT(*) AS count FROM services;")
count = res.rows[0][0]
if count == 0:
print("🌱 Seeding initial services from Armonía del Ser flyer...")
insert_query = """
INSERT INTO services (
id, slug, name, description, service_type, modality,
default_schedule, price_mxn, max_capacity, duration_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1);
"""
for s in INITIAL_SERVICES:
await client.execute(
insert_query,
[
s["id"],
s["slug"],
s["name"],
s["description"],
s["service_type"],
s["modality"],
s["default_schedule"],
s["price_mxn"],
s["max_capacity"],
s["duration_minutes"],
],
)
print(f"✅ Successfully seeded {len(INITIAL_SERVICES)} services!")
else:
print(f"ℹ️ Services table already has {count} entries, skipping seed.")
if __name__ == "__main__":
asyncio.run(init_schema_and_seed())
+56
View File
@@ -0,0 +1,56 @@
-- Armonía del Ser Database Schema (Turso / SQLite3)
CREATE TABLE IF NOT EXISTS services (
id TEXT PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT,
service_type TEXT NOT NULL CHECK (service_type IN ('GROUP', 'ONE_ON_ONE')),
modality TEXT NOT NULL CHECK (modality IN ('PRESENCIAL', 'ONLINE')),
default_schedule TEXT,
price_mxn INTEGER NOT NULL DEFAULT 0,
max_capacity INTEGER NOT NULL DEFAULT 1,
duration_minutes INTEGER NOT NULL DEFAULT 60,
is_active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS clients (
id TEXT PRIMARY KEY,
full_name TEXT NOT NULL,
phone_whatsapp TEXT NOT NULL,
email TEXT,
notes TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS bookings (
id TEXT PRIMARY KEY,
booking_code TEXT UNIQUE NOT NULL,
service_id TEXT NOT NULL REFERENCES services(id),
client_id TEXT NOT NULL REFERENCES clients(id),
scheduled_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING_PAYMENT' CHECK (status IN ('PENDING_PAYMENT', 'CONFIRMED', 'CANCELLED', 'EXPIRED', 'NO_SHOW')),
amount_mxn INTEGER NOT NULL,
gcal_event_id TEXT,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
confirmed_at TEXT
);
CREATE TABLE IF NOT EXISTS payments (
id TEXT PRIMARY KEY,
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,
notes 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_scheduled ON bookings(scheduled_at);
CREATE INDEX IF NOT EXISTS idx_clients_phone ON clients(phone_whatsapp);
+49
View File
@@ -0,0 +1,49 @@
from __future__ import annotations
import contextlib
from fastapi import FastAPI
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, payments, services
@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
# Ensure tables 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",
lifespan=lifespan,
)
# CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include Routers
app.include_router(health.router)
app.include_router(services.router)
app.include_router(bookings.router)
app.include_router(payments.router)
@app.get("/")
def root():
return {
"service": settings.business_name,
"tagline": "Cada día, un espacio para volver a ti",
"docs_url": "/docs",
}
+156
View File
@@ -0,0 +1,156 @@
from __future__ import annotations
import secrets
import urllib.parse
import uuid
from datetime import UTC, datetime, timedelta
import libsql_client
from fastapi import APIRouter, HTTPException, Query, status
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
router = APIRouter(prefix="/bookings", tags=["Bookings"])
def generate_booking_code() -> str:
"""Generate a clean human-readable folio code, e.g. ADS-7F2A."""
token = secrets.token_hex(2).upper()
return f"ADS-{token}"
def build_whatsapp_link(service_name: str, scheduled_at: str, folio: str, amount_mxn: int) -> str:
"""Generate a pre-filled WhatsApp link instructing the client to send SPEI proof."""
msg = (
f"Hola Jazmín! ✨ 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"
f"🏦 *Banco:* {settings.spei_bank}\n"
f"💳 *CLABE:* {settings.spei_clabe}\n"
f"👤 *Beneficiario:* {settings.spei_beneficiary}\n\n"
f"Te adjunto mi comprobante de pago en este chat para confirmar mi lugar. ¡Muchas gracias!"
)
encoded = urllib.parse.quote(msg)
clean_phone = settings.whatsapp_phone.replace("+", "").replace(" ", "").replace("-", "")
return f"https://wa.me/{clean_phone}?text={encoded}"
@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 and yields a pre-filled WhatsApp transfer message.
"""
async with get_db() as client:
# 1. Fetch service details
svc_res = await client.execute(
"SELECT * FROM services WHERE id = ? AND is_active = 1 LIMIT 1;",
[payload.service_id],
)
if not svc_res.rows:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Service not found or inactive",
)
service = row_to_dict(svc_res, svc_res.rows[0])
# 2. Upsert client
client_res = await client.execute(
"SELECT id FROM clients WHERE phone_whatsapp = ? LIMIT 1;",
[payload.client_phone],
)
if client_res.rows:
client_id = client_res.rows[0][0]
else:
client_id = str(uuid.uuid4())
await client.execute(
"INSERT INTO clients (id, full_name, phone_whatsapp, email, notes) VALUES (?, ?, ?, ?, ?);",
[
client_id,
payload.client_name,
payload.client_phone,
payload.client_email,
payload.notes,
],
)
# 3. Create booking
booking_id = str(uuid.uuid4())
booking_code = generate_booking_code()
now = datetime.now(UTC)
expires_at = (now + timedelta(hours=2)).isoformat()
amount_mxn = int(service["price_mxn"])
insert_booking_query = """
INSERT INTO bookings (
id, booking_code, service_id, client_id, scheduled_at,
status, amount_mxn, expires_at
) VALUES (?, ?, ?, ?, ?, 'PENDING_PAYMENT', ?, ?);
"""
await client.execute(
insert_booking_query,
[
booking_id,
booking_code,
service["id"],
client_id,
payload.scheduled_at,
amount_mxn,
expires_at,
],
)
wa_link = build_whatsapp_link(
service_name=service["name"],
scheduled_at=payload.scheduled_at,
folio=booking_code,
amount_mxn=amount_mxn,
)
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,
scheduled_at=payload.scheduled_at,
status="PENDING_PAYMENT",
amount_mxn=amount_mxn,
expires_at=expires_at,
created_at=now.isoformat(),
whatsapp_redirect_url=wa_link,
)
@router.get("", response_model=list[BookingRead])
async def list_bookings(
status_filter: BookingStatus | None = Query(None, alias="status"),
limit: int = 50,
):
"""Admin-facing endpoint to list bookings, filtered by status."""
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.scheduled_at, 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
"""
params: list[libsql_client.InValue] = []
if status_filter:
query += " WHERE b.status = ?"
params.append(status_filter)
query += " ORDER BY b.scheduled_at DESC 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]
+24
View File
@@ -0,0 +1,24 @@
from __future__ import annotations
from fastapi import APIRouter, status
from app.db.database import get_db
router = APIRouter(prefix="/health", tags=["Health"])
@router.get("", status_code=status.HTTP_200_OK)
async def health_check():
"""Health check endpoint confirming service and database connectivity."""
db_status = "ok"
try:
async with get_db() as client:
await client.execute("SELECT 1;")
except Exception as e:
db_status = f"unhealthy: {e}"
return {
"status": "ok" if db_status == "ok" else "degraded",
"database": db_status,
"service": "armonia-api",
}
+83
View File
@@ -0,0 +1,83 @@
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from fastapi import APIRouter, HTTPException, status
from app.db.database import get_db, result_to_dicts, row_to_dict
from app.schemas.payment import PaymentRead, PaymentVerificationRequest
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 with get_db() as client:
# 1. Fetch booking
b_res = await client.execute(
"SELECT * FROM bookings WHERE 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":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Booking is already confirmed",
)
now = datetime.now(UTC).isoformat()
payment_id = str(uuid.uuid4())
# 2. Record payment
await client.execute(
"""
INSERT INTO payments (id, booking_id, amount_mxn, payment_method, status, verified_at, notes, created_at)
VALUES (?, ?, ?, ?, 'VERIFIED', ?, ?, ?);
""",
[
payment_id,
payload.booking_id,
payload.amount_mxn,
payload.payment_method,
now,
payload.notes,
now,
],
)
# 3. Transition booking to CONFIRMED
await client.execute(
"UPDATE bookings SET status = 'CONFIRMED', confirmed_at = ? WHERE id = ?;",
[now, payload.booking_id],
)
return PaymentRead(
id=payment_id,
booking_id=payload.booking_id,
amount_mxn=payload.amount_mxn,
payment_method=payload.payment_method,
status="VERIFIED",
verified_at=now,
notes=payload.notes,
created_at=now,
)
@router.get("/history", response_model=list[PaymentRead])
async def list_payments(limit: int = 50):
"""List recent verified payment records."""
async with get_db() as client:
res = await client.execute(
"SELECT * FROM payments ORDER BY created_at DESC LIMIT ?;",
[limit],
)
rows = result_to_dicts(res)
return [PaymentRead(**r) for r in rows]
+81
View File
@@ -0,0 +1,81 @@
from __future__ import annotations
import uuid
from fastapi import APIRouter, HTTPException, status
from app.db.database import get_db, result_to_dicts, row_to_dict
from app.schemas.service import ServiceCreate, ServiceRead
router = APIRouter(prefix="/services", tags=["Services"])
@router.get("", response_model=list[ServiceRead])
async def list_services(active_only: bool = True):
"""Retrieve catalog of services offered by Armonía del Ser."""
query = "SELECT * FROM services"
if active_only:
query += " WHERE is_active = 1"
query += " ORDER BY service_type ASC, name ASC;"
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
@router.get("/{service_id_or_slug}", response_model=ServiceRead)
async def get_service(service_id_or_slug: str):
"""Retrieve details for a specific service by ID or slug."""
query = "SELECT * FROM services WHERE id = ? OR slug = ? LIMIT 1;"
async with get_db() as client:
res = await client.execute(query, [service_id_or_slug, service_id_or_slug])
if not res.rows:
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
@router.post("", response_model=ServiceRead, status_code=status.HTTP_201_CREATED)
async def create_service(payload: ServiceCreate):
"""Add a new service to the catalog (Admin action)."""
service_id = str(uuid.uuid4())
insert_query = """
INSERT INTO services (
id, slug, name, description, service_type, modality,
default_schedule, price_mxn, max_capacity, duration_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
"""
async with get_db() as client:
try:
await client.execute(
insert_query,
[
service_id,
payload.slug,
payload.name,
payload.description,
payload.service_type,
payload.modality,
payload.default_schedule,
payload.price_mxn,
payload.max_capacity,
payload.duration_minutes,
1 if payload.is_active else 0,
],
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Failed to create service: {e}",
) from e
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
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
BookingStatus = Literal["PENDING_PAYMENT", "CONFIRMED", "CANCELLED", "EXPIRED", "NO_SHOW"]
class BookingCreate(BaseModel):
service_id: str
client_name: str = Field(..., min_length=2)
client_phone: str = Field(..., min_length=10)
client_email: str | None = None
scheduled_at: str = Field(..., description="ISO 8601 string for scheduled date and time")
notes: str | None = None
class BookingRead(BaseModel):
id: str
booking_code: str
service_id: str
service_name: str | None = None
client_id: str
client_name: str | None = None
client_phone: str | None = None
scheduled_at: str
status: BookingStatus
amount_mxn: int
gcal_event_id: str | None = None
expires_at: str
created_at: str
confirmed_at: str | None = None
whatsapp_redirect_url: str | None = None
+19
View File
@@ -0,0 +1,19 @@
from __future__ import annotations
from pydantic import BaseModel, Field
class ClientBase(BaseModel):
full_name: str = Field(..., min_length=2, max_length=150)
phone_whatsapp: str = Field(..., min_length=10, max_length=20)
email: str | None = None
notes: str | None = None
class ClientCreate(ClientBase):
pass
class ClientRead(ClientBase):
id: str
created_at: str
+26
View File
@@ -0,0 +1,26 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
PaymentMethod = Literal["SPEI", "OXXO", "CASH"]
PaymentStatus = Literal["PENDING", "VERIFIED", "REJECTED"]
class PaymentVerificationRequest(BaseModel):
booking_id: str
amount_mxn: int = Field(..., ge=0)
payment_method: PaymentMethod = "SPEI"
notes: str | None = None
class PaymentRead(BaseModel):
id: str
booking_id: str
amount_mxn: int
payment_method: PaymentMethod
status: PaymentStatus
verified_at: str | None = None
notes: str | None = None
created_at: str
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
class ServiceBase(BaseModel):
name: str = Field(..., min_length=2, max_length=150)
description: str | None = None
service_type: Literal["GROUP", "ONE_ON_ONE"]
modality: Literal["PRESENCIAL", "ONLINE"]
default_schedule: str | None = None
price_mxn: int = Field(..., ge=0)
max_capacity: int = Field(default=1, ge=1)
duration_minutes: int = Field(default=60, ge=15)
is_active: bool = True
class ServiceCreate(ServiceBase):
slug: str = Field(..., min_length=2, max_length=100)
class ServiceUpdate(BaseModel):
name: str | None = None
description: str | None = None
service_type: Literal["GROUP", "ONE_ON_ONE"] | None = None
modality: Literal["PRESENCIAL", "ONLINE"] | None = None
default_schedule: str | None = None
price_mxn: int | None = Field(default=None, ge=0)
max_capacity: int | None = Field(default=None, ge=1)
duration_minutes: int | None = Field(default=None, ge=15)
is_active: bool | None = None
class ServiceRead(ServiceBase):
id: str
slug: str
created_at: str
+39
View File
@@ -0,0 +1,39 @@
[project]
name = "armonia-api"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
"fastapi>=0.115.0",
"httpx>=0.27.0",
"libsql-client>=0.3.1",
"pydantic>=2.8.0",
"pydantic-settings>=2.4.0",
"uvicorn[standard]>=0.30.0",
]
[dependency-groups]
dev = [
"pyright>=1.1.414",
"pytest>=9.1.1",
"pytest-asyncio>=1.4.0",
"ruff>=0.17.1",
]
[tool.ruff]
line-length = 100
target-version = "py313"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
ignore = ["B008", "E501"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["E402"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
pythonpath = ["."]
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
import os
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
# Ensure test DB is used
TEST_DB = "test_armonia.db"
os.environ["DATABASE_URL"] = f"file:{TEST_DB}"
from app.core.config import settings
settings.database_url = f"file:{TEST_DB}"
import asyncio
from app.db.init_db import init_schema_and_seed
from app.main import app
@pytest.fixture(scope="session", autouse=True)
def setup_test_db():
# Remove existing test DB if any
if Path(TEST_DB).exists():
Path(TEST_DB).unlink()
asyncio.run(init_schema_and_seed())
yield
if Path(TEST_DB).exists():
Path(TEST_DB).unlink()
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
+48
View File
@@ -0,0 +1,48 @@
from __future__ import annotations
def test_booking_and_payment_flow(client):
# 1. Fetch a service
svc_res = client.get("/services/circulo-cacao-presencial")
assert svc_res.status_code == 200
svc = svc_res.json()
# 2. Create reservation
booking_payload = {
"service_id": svc["id"],
"client_name": "Carlos Méndez",
"client_phone": "5512345678",
"client_email": "carlos@example.com",
"scheduled_at": "2026-10-26T18:00:00Z",
"notes": "Primera vez en círculo de cacao",
}
b_res = client.post("/bookings", json=booking_payload)
assert b_res.status_code == 201
booking = b_res.json()
assert booking["status"] == "PENDING_PAYMENT"
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"]
# 3. Verify 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)
assert p_res.status_code == 201
payment = p_res.json()
assert payment["status"] == "VERIFIED"
assert payment["booking_id"] == booking["id"]
# 4. Confirm booking status updated
list_res = client.get("/bookings?status=CONFIRMED")
assert list_res.status_code == 200
confirmed_bookings = list_res.json()
matching = [b for b in confirmed_bookings if b["id"] == booking["id"]]
assert len(matching) == 1
assert matching[0]["status"] == "CONFIRMED"
+17
View File
@@ -0,0 +1,17 @@
from __future__ import annotations
def test_root_endpoint(client):
response = client.get("/")
assert response.status_code == 200
data = response.json()
assert data["service"] == "Armonía del Ser"
assert "/docs" in data["docs_url"]
def test_health_check(client):
response = client.get("/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "ok"
assert data["database"] == "ok"
+22
View File
@@ -0,0 +1,22 @@
from __future__ import annotations
def test_list_seeded_services(client):
response = client.get("/services")
assert response.status_code == 200
services = response.json()
assert len(services) >= 9
slugs = [s["slug"] for s in services]
assert "circulo-cacao-presencial" in slugs
assert "atencion-psicologica-individual" in slugs
assert "constelaciones-familiares-online" in slugs
def test_get_service_by_slug(client):
response = client.get("/services/circulo-cacao-presencial")
assert response.status_code == 200
data = response.json()
assert data["name"] == "Círculo de Cacao (Presencial)"
assert data["price_mxn"] == 350
assert data["service_type"] == "GROUP"
Generated
+1711
View File
File diff suppressed because it is too large. Load diff