diff --git a/app/db/init_db.py b/app/db/init_db.py index ec86c1c..a3066d9 100644 --- a/app/db/init_db.py +++ b/app/db/init_db.py @@ -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] diff --git a/app/db/schema.sql b/app/db/schema.sql index 89045d2..58e5ba6 100644 --- a/app/db/schema.sql +++ b/app/db/schema.sql @@ -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); diff --git a/app/main.py b/app/main.py index 42489c2..54d7e5c 100644 --- a/app/main.py +++ b/app/main.py @@ -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) diff --git a/app/routers/bookings.py b/app/routers/bookings.py index cf63d8c..a9150f3 100644 --- a/app/routers/bookings.py +++ b/app/routers/bookings.py @@ -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) diff --git a/app/routers/packages.py b/app/routers/packages.py index da9ff56..6c55041 100644 --- a/app/routers/packages.py +++ b/app/routers/packages.py @@ -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 diff --git a/app/routers/payments.py b/app/routers/payments.py index 1c38454..c357caa 100644 --- a/app/routers/payments.py +++ b/app/routers/payments.py @@ -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 ?;", diff --git a/app/routers/services.py b/app/routers/services.py index 4244248..5a1d043 100644 --- a/app/routers/services.py +++ b/app/routers/services.py @@ -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) diff --git a/app/schemas/booking.py b/app/schemas/booking.py index 133aca7..c8036ff 100644 --- a/app/schemas/booking.py +++ b/app/schemas/booking.py @@ -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 diff --git a/app/schemas/payment.py b/app/schemas/payment.py index 93c6a82..56d8142 100644 --- a/app/schemas/payment.py +++ b/app/schemas/payment.py @@ -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 diff --git a/app/services/calendar.py b/app/services/calendar.py new file mode 100644 index 0000000..91e22f7 --- /dev/null +++ b/app/services/calendar.py @@ -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() diff --git a/tests/test_auth_and_workflows.py b/tests/test_auth_and_workflows.py new file mode 100644 index 0000000..a84f933 --- /dev/null +++ b/tests/test_auth_and_workflows.py @@ -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 diff --git a/tests/test_bookings.py b/tests/test_bookings.py index 9a677c5..acf032d 100644 --- a/tests/test_bookings.py +++ b/tests/test_bookings.py @@ -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