feat(packages): add multi-session package endpoints and service buffer schema

- Add `packages` table and indexes in `schema.sql` to track prepaid or
  partially paid multi-session therapy bundles (`total_sessions`,
  `completed_sessions`, `financial_status`).
- Add `buffer_minutes`, `duration_minutes`, and `package_id` columns to
  support mandatory post-consultation buffers and package redemptions.
- Seed 15-minute mandatory buffer on `atencion-psicologica-individual`.
- Implement `/packages` CRUD router (`POST`, `GET`, `PATCH`) and mount it
  in `app/main.py`.

Refs: #1
This commit is contained in:
kiskaadee committed 2026-10-18 12:00:10 -05:00
1 parent effa1ee86c
commit 92edb4ac12
7 files changed
+258 -5

No files matched your search

+4 -2
View File
@@ -116,6 +116,7 @@ INITIAL_SERVICES = [
"price_mxn": 600,
"max_capacity": 1,
"duration_minutes": 60,
"buffer_minutes": 15,
},
]
@@ -138,8 +139,8 @@ async def init_schema_and_seed():
insert_query = """
INSERT INTO services (
id, slug, name, description, service_type, modality,
default_schedule, price_mxn, max_capacity, duration_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1);
default_schedule, price_mxn, max_capacity, duration_minutes, buffer_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1);
"""
for s in INITIAL_SERVICES:
await client.execute(
@@ -155,6 +156,7 @@ async def init_schema_and_seed():
s["price_mxn"],
s["max_capacity"],
s["duration_minutes"],
s.get("buffer_minutes", 0),
],
)
print(f"✅ Successfully seeded {len(INITIAL_SERVICES)} services!")
+19
View File
@@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS services (
price_mxn INTEGER NOT NULL DEFAULT 0,
max_capacity INTEGER NOT NULL DEFAULT 1,
duration_minutes INTEGER NOT NULL DEFAULT 60,
buffer_minutes INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
@@ -24,12 +25,28 @@ CREATE TABLE IF NOT EXISTS clients (
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS packages (
id TEXT PRIMARY KEY,
client_id TEXT NOT NULL REFERENCES clients(id),
service_id TEXT NOT NULL REFERENCES services(id),
total_sessions INTEGER NOT NULL CHECK (total_sessions > 0),
completed_sessions INTEGER NOT NULL DEFAULT 0 CHECK (completed_sessions >= 0),
price_paid_mxn INTEGER NOT NULL DEFAULT 0,
financial_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (financial_status IN ('PAID', 'PARTIAL', 'PENDING')),
notes TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_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),
package_id TEXT REFERENCES packages(id),
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')),
amount_mxn INTEGER NOT NULL,
gcal_event_id TEXT,
@@ -53,4 +70,6 @@ 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_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);
+2 -1
View File
@@ -7,7 +7,7 @@ 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
from app.routers import bookings, health, packages, payments, services
@contextlib.asynccontextmanager
@@ -37,6 +37,7 @@ app.add_middleware(
app.include_router(health.router)
app.include_router(services.router)
app.include_router(bookings.router)
app.include_router(packages.router)
app.include_router(payments.router)
+184
View File
@@ -0,0 +1,184 @@
from __future__ import annotations
import uuid
from datetime import UTC, datetime
import libsql_client
from fastapi import APIRouter, HTTPException, Query, status
from app.db.database import get_db, result_to_dicts, row_to_dict
from app.schemas.package import FinancialStatus, PackageCreate, PackageRead, PackageUpdate
router = APIRouter(prefix="/packages", tags=["Packages"])
def _hydrate_package(r: dict) -> PackageRead:
total = int(r["total_sessions"])
completed = int(r.get("completed_sessions", 0))
return PackageRead(
id=r["id"],
client_id=r["client_id"],
client_name=r.get("client_name"),
client_phone=r.get("client_phone"),
service_id=r["service_id"],
service_name=r.get("service_name"),
total_sessions=total,
completed_sessions=completed,
remaining_sessions=max(0, total - completed),
price_paid_mxn=int(r.get("price_paid_mxn", 0)),
financial_status=r.get("financial_status", "PENDING"),
notes=r.get("notes"),
created_at=r["created_at"],
updated_at=r["updated_at"],
)
@router.post("", response_model=PackageRead, status_code=status.HTTP_201_CREATED)
async def create_package(payload: PackageCreate):
"""
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]
)
if not s_res.rows:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service not found")
package_id = str(uuid.uuid4())
now = datetime.now(UTC).isoformat()
insert_query = """
INSERT INTO packages (
id, client_id, service_id, total_sessions, completed_sessions,
price_paid_mxn, financial_status, notes, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
"""
await client.execute(
insert_query,
[
package_id,
payload.client_id,
payload.service_id,
payload.total_sessions,
payload.completed_sessions,
payload.price_paid_mxn,
payload.financial_status,
payload.notes,
now,
now,
],
)
# Hydrate with names
fetch_query = """
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
FROM packages p
JOIN clients c ON p.client_id = c.id
JOIN services s ON p.service_id = s.id
WHERE p.id = ? LIMIT 1;
"""
res = await client.execute(fetch_query, [package_id])
return _hydrate_package(row_to_dict(res, res.rows[0]))
@router.get("", response_model=list[PackageRead])
async def list_packages(
client_id: str | None = None,
financial_status: FinancialStatus | None = Query(None, alias="status"),
):
"""List therapy packages with filter by client or financial status."""
query = """
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
FROM packages p
JOIN clients c ON p.client_id = c.id
JOIN services s ON p.service_id = s.id
"""
params: list[libsql_client.InValue] = []
clauses: list[str] = []
if client_id:
clauses.append("p.client_id = ?")
params.append(client_id)
if financial_status:
clauses.append("p.financial_status = ?")
params.append(financial_status)
if clauses:
query += " WHERE " + " AND ".join(clauses)
query += " ORDER BY p.created_at DESC;"
async with get_db() as client:
res = await client.execute(query, params)
rows = result_to_dicts(res)
return [_hydrate_package(r) for r in rows]
@router.get("/{package_id}", response_model=PackageRead)
async def get_package(package_id: str):
"""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
FROM packages p
JOIN clients c ON p.client_id = c.id
JOIN services s ON p.service_id = s.id
WHERE p.id = ? LIMIT 1;
"""
async with get_db() as client:
res = await client.execute(query, [package_id])
if not res.rows:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Package not found")
return _hydrate_package(row_to_dict(res, res.rows[0]))
@router.patch("/{package_id}", response_model=PackageRead)
async def update_package(package_id: str, payload: PackageUpdate):
"""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")
updates: list[str] = ["updated_at = ?"]
params: list[libsql_client.InValue] = [now]
if payload.total_sessions is not None:
updates.append("total_sessions = ?")
params.append(payload.total_sessions)
if payload.completed_sessions is not None:
updates.append("completed_sessions = ?")
params.append(payload.completed_sessions)
if payload.price_paid_mxn is not None:
updates.append("price_paid_mxn = ?")
params.append(payload.price_paid_mxn)
if payload.financial_status is not None:
updates.append("financial_status = ?")
params.append(payload.financial_status)
if payload.notes is not None:
updates.append("notes = ?")
params.append(payload.notes)
params.append(package_id)
update_query = f"UPDATE packages SET {', '.join(updates)} WHERE id = ?;"
await client.execute(update_query, params)
fetch_query = """
SELECT p.*, c.full_name AS client_name, c.phone_whatsapp AS client_phone, s.name AS service_name
FROM packages p
JOIN clients c ON p.client_id = c.id
JOIN services s ON p.service_id = s.id
WHERE p.id = ? LIMIT 1;
"""
updated_res = await client.execute(fetch_query, [package_id])
return _hydrate_package(row_to_dict(updated_res, updated_res.rows[0]))
+3 -2
View File
@@ -47,8 +47,8 @@ async def create_service(payload: ServiceCreate):
insert_query = """
INSERT INTO services (
id, slug, name, description, service_type, modality,
default_schedule, price_mxn, max_capacity, duration_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
default_schedule, price_mxn, max_capacity, duration_minutes, buffer_minutes, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
"""
async with get_db() as client:
try:
@@ -65,6 +65,7 @@ async def create_service(payload: ServiceCreate):
payload.price_mxn,
payload.max_capacity,
payload.duration_minutes,
payload.buffer_minutes,
1 if payload.is_active else 0,
],
)
+44
View File
@@ -0,0 +1,44 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
FinancialStatus = Literal["PAID", "PARTIAL", "PENDING"]
class PackageBase(BaseModel):
client_id: str
service_id: str
total_sessions: int = Field(..., ge=1, description="Total sessions in package, e.g. 5 or 10")
price_paid_mxn: int = Field(default=0, ge=0)
financial_status: FinancialStatus = "PENDING"
notes: str | None = None
class PackageCreate(PackageBase):
completed_sessions: int = Field(default=0, ge=0)
class PackageUpdate(BaseModel):
total_sessions: int | None = Field(default=None, ge=1)
completed_sessions: int | None = Field(default=None, ge=0)
price_paid_mxn: int | None = Field(default=None, ge=0)
financial_status: FinancialStatus | None = None
notes: str | None = None
class PackageRedeem(BaseModel):
scheduled_at: str = Field(..., description="ISO 8601 string for the redeemed session date/time")
notes: str | None = None
class PackageRead(PackageBase):
id: str
completed_sessions: int
remaining_sessions: int
client_name: str | None = None
client_phone: str | None = None
service_name: str | None = None
created_at: str
updated_at: str
+2
View File
@@ -14,6 +14,7 @@ class ServiceBase(BaseModel):
price_mxn: int = Field(..., ge=0)
max_capacity: int = Field(default=1, ge=1)
duration_minutes: int = Field(default=60, ge=15)
buffer_minutes: int = Field(default=0, ge=0)
is_active: bool = True
@@ -30,6 +31,7 @@ class ServiceUpdate(BaseModel):
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)
buffer_minutes: int | None = Field(default=None, ge=0)
is_active: bool | None = None