Compare commits
11
Commits
4652a22b0d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2208ed9ac1 | ||
|
|
d9c86e27d9 | ||
|
|
ad5d4d58c1 | ||
|
|
d3a705c5a3 | ||
|
|
3db817ebf5 | ||
|
|
e8aa97080e | ||
|
|
168b835b6b | ||
|
|
4a167ebb48 | ||
|
|
7987fdfa5d | ||
|
|
41e8608315 | ||
|
|
14ef3d1751 |
No files matched your search
@@ -0,0 +1,18 @@
|
|||||||
|
.git/
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
*.pyd
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
.env
|
||||||
|
*.local.env
|
||||||
|
.direnv/
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
@@ -13,6 +13,7 @@ venv/
|
|||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
.coverage
|
.coverage
|
||||||
htmlcov/
|
htmlcov/
|
||||||
|
mutants/
|
||||||
|
|
||||||
# Local databases
|
# Local databases
|
||||||
*.db
|
*.db
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
# Multi-stage production container build for armonia-api
|
||||||
|
|
||||||
|
# Stage 1: Build virtual environment with uv
|
||||||
|
FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim AS builder
|
||||||
|
|
||||||
|
ENV UV_COMPILE_BYTECODE=1 \
|
||||||
|
UV_LINK_MODE=copy
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install dependencies using cache mount
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
|
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||||
|
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||||
|
uv sync --frozen --no-install-project --no-dev
|
||||||
|
|
||||||
|
# Copy application sources and sync project
|
||||||
|
COPY . /app
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||||
|
uv sync --frozen --no-dev
|
||||||
|
|
||||||
|
|
||||||
|
# Stage 2: Minimal runtime image
|
||||||
|
FROM python:3.13-slim-bookworm AS runtime
|
||||||
|
|
||||||
|
ENV PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PATH="/app/.venv/bin:$PATH"
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install curl for container healthcheck
|
||||||
|
RUN apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends curl && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Copy installed virtual environment and application code from builder
|
||||||
|
COPY --from=builder /app /app
|
||||||
|
|
||||||
|
# Non-root unprivileged container user
|
||||||
|
RUN useradd -u 1000 -m -s /bin/bash appuser && \
|
||||||
|
chown -R appuser:appuser /app
|
||||||
|
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
|
CMD curl -f http://localhost:8000/health || exit 1
|
||||||
|
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
+136
-29
@@ -7,13 +7,16 @@ import json
|
|||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any, Protocol
|
||||||
|
|
||||||
import libsql_client
|
import libsql_client
|
||||||
from fastapi import HTTPException, Request, status
|
from fastapi import HTTPException, Request, status
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import AuthProvider, settings
|
||||||
from app.db.database import get_db, row_to_dict
|
from app.db.database import get_db, get_engine, row_to_dict
|
||||||
|
from app.models.admin import RoleEnum
|
||||||
|
from app.repositories.admin import mirror_admin_actor
|
||||||
from app.schemas.auth import AdminPrincipal
|
from app.schemas.auth import AdminPrincipal
|
||||||
|
|
||||||
SESSION_COOKIE_NAME = "armonia_session"
|
SESSION_COOKIE_NAME = "armonia_session"
|
||||||
@@ -123,50 +126,154 @@ async def record_admin_audit(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def require_admin(request: Request) -> AdminPrincipal:
|
# --- Pluggable authentication strategy (ADR-0006) ---------------------------------------
|
||||||
"""
|
#
|
||||||
FastAPI dependency enforcing Google OAuth session token OR dev/service key fallback,
|
# Each adapter inspects only its own credentials and returns:
|
||||||
always verified against an active row in Turso's admin_allowlist table.
|
# * AdminPrincipal -> authenticated and authorized
|
||||||
"""
|
# * None -> its credentials are absent (lets require_admin try a fallback / 401)
|
||||||
candidate_email: str | None = None
|
# and raises HTTPException when credentials are present but invalid or unauthorized.
|
||||||
|
|
||||||
# 1. Check Authorization: Bearer <session_token> or HttpOnly session cookie
|
# Highest privilege first; exact (case-insensitive) LLDAP group names.
|
||||||
|
PROXY_GROUP_ROLES: tuple[tuple[str, RoleEnum], ...] = (
|
||||||
|
("armonia-owner", RoleEnum.OWNER),
|
||||||
|
("armonia-admin", RoleEnum.ADMIN),
|
||||||
|
("armonia-assistant", RoleEnum.ASSISTANT),
|
||||||
|
)
|
||||||
|
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_role_from_groups(raw_groups: str | None) -> RoleEnum | None:
|
||||||
|
"""Map Authelia's comma-separated `Remote-Groups` to the highest-privilege RoleEnum."""
|
||||||
|
if not raw_groups:
|
||||||
|
return None
|
||||||
|
groups = {g.strip().lower() for g in raw_groups.split(",") if g.strip()}
|
||||||
|
for group_name, role in PROXY_GROUP_ROLES:
|
||||||
|
if group_name in groups:
|
||||||
|
return role
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class AuthAdapter(Protocol):
|
||||||
|
async def authenticate(self, request: Request) -> AdminPrincipal | None: ...
|
||||||
|
|
||||||
|
|
||||||
|
async def _require_allowlisted(email: str) -> AdminPrincipal:
|
||||||
|
async with get_db() as client:
|
||||||
|
principal = await get_allowlisted_admin(client, email)
|
||||||
|
if not principal:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"El correo '{email}' no está autorizado en la lista de administradores activos.",
|
||||||
|
)
|
||||||
|
return principal
|
||||||
|
|
||||||
|
|
||||||
|
class ProxyHeaderAdapter:
|
||||||
|
"""
|
||||||
|
Authelia/LLDAP forward-auth. Identity and role come exclusively from Remote-* headers;
|
||||||
|
reads perform zero database queries. On unsafe methods the principal is mirrored into
|
||||||
|
`admin_allowlist` so audited writes keep FK integrity (ADR-0006).
|
||||||
|
|
||||||
|
SECURITY: only enable when the API is reachable exclusively through the proxy, which must
|
||||||
|
strip client-supplied Remote-* headers.
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def authenticate(self, request: Request) -> AdminPrincipal | None:
|
||||||
|
raw_identity = request.headers.get("Remote-Email") or request.headers.get("Remote-User")
|
||||||
|
email = (raw_identity or "").strip().lower()
|
||||||
|
if not email:
|
||||||
|
return None
|
||||||
|
|
||||||
|
role = resolve_role_from_groups(request.headers.get("Remote-Groups"))
|
||||||
|
if role is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"El usuario '{email}' no pertenece a ningún grupo armonia-* autorizado.",
|
||||||
|
)
|
||||||
|
|
||||||
|
full_name = (request.headers.get("Remote-Name") or "").strip() or email
|
||||||
|
principal = AdminPrincipal(email=email, full_name=full_name, role=role.value)
|
||||||
|
|
||||||
|
if request.method.upper() not in SAFE_METHODS:
|
||||||
|
with Session(get_engine()) as session:
|
||||||
|
mirror_admin_actor(session, email=email, full_name=full_name, role=role.value)
|
||||||
|
return principal
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleOAuthAdapter:
|
||||||
|
"""HMAC session token (Bearer header or HttpOnly cookie) verified against the allowlist."""
|
||||||
|
|
||||||
|
async def authenticate(self, request: Request) -> AdminPrincipal | None:
|
||||||
auth_header = request.headers.get("Authorization", "")
|
auth_header = request.headers.get("Authorization", "")
|
||||||
token: str | None = None
|
token: str | None = None
|
||||||
if auth_header.startswith("Bearer "):
|
if auth_header.startswith("Bearer "):
|
||||||
token = auth_header.removeprefix("Bearer ").strip()
|
token = auth_header.removeprefix("Bearer ").strip()
|
||||||
elif SESSION_COOKIE_NAME in request.cookies:
|
elif SESSION_COOKIE_NAME in request.cookies:
|
||||||
token = request.cookies.get(SESSION_COOKIE_NAME)
|
token = request.cookies.get(SESSION_COOKIE_NAME)
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
|
||||||
if token:
|
|
||||||
try:
|
try:
|
||||||
candidate_email = verify_session_token(token)
|
email = verify_session_token(token)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail=f"Sesión inválida o expirada: {exc}",
|
detail=f"Sesión inválida o expirada: {exc}",
|
||||||
) from exc
|
) from exc
|
||||||
else:
|
return await _require_allowlisted(email)
|
||||||
# 2. Check X-Admin-Key + X-Admin-Email fallback for automated tests / CLI
|
|
||||||
admin_key = request.headers.get("X-Admin-Key")
|
|
||||||
admin_email_hdr = request.headers.get("X-Admin-Email")
|
|
||||||
if admin_key and hmac.compare_digest(admin_key, settings.admin_api_key):
|
|
||||||
if admin_email_hdr:
|
|
||||||
candidate_email = admin_email_hdr.strip().lower()
|
|
||||||
elif settings.admin_bootstrap_emails:
|
|
||||||
candidate_email = settings.admin_bootstrap_emails[0].strip().lower()
|
|
||||||
|
|
||||||
if not candidate_email:
|
|
||||||
|
class DevKeyAdapter:
|
||||||
|
"""X-Admin-Key (+ optional X-Admin-Email) for tests, CLI, and local dashboard development."""
|
||||||
|
|
||||||
|
async def authenticate(self, request: Request) -> AdminPrincipal | None:
|
||||||
|
admin_key = request.headers.get("X-Admin-Key")
|
||||||
|
if not admin_key:
|
||||||
|
return None
|
||||||
|
if not hmac.compare_digest(admin_key, settings.admin_api_key):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Autenticación de administrador requerida (Google OAuth).",
|
detail="Clave de administrador inválida.",
|
||||||
)
|
)
|
||||||
|
|
||||||
async with get_db() as client:
|
admin_email_hdr = (request.headers.get("X-Admin-Email") or "").strip().lower()
|
||||||
principal = await get_allowlisted_admin(client, candidate_email)
|
email = admin_email_hdr or (
|
||||||
if not principal:
|
settings.admin_bootstrap_emails[0].strip().lower()
|
||||||
raise HTTPException(
|
if settings.admin_bootstrap_emails
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
else ""
|
||||||
detail=f"El correo '{candidate_email}' no está autorizado en la lista de administradores activos.",
|
|
||||||
)
|
)
|
||||||
|
if not email:
|
||||||
|
return None
|
||||||
|
return await _require_allowlisted(email)
|
||||||
|
|
||||||
|
|
||||||
|
AUTH_ADAPTERS: dict[AuthProvider, AuthAdapter] = {
|
||||||
|
AuthProvider.PROXY_HEADERS: ProxyHeaderAdapter(),
|
||||||
|
AuthProvider.GOOGLE_OAUTH: GoogleOAuthAdapter(),
|
||||||
|
AuthProvider.DEV_KEY: DevKeyAdapter(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_adapter_chain() -> list[AuthAdapter]:
|
||||||
|
"""Configured provider first; dev_key fallback only outside production."""
|
||||||
|
primary = AuthProvider(settings.auth_provider)
|
||||||
|
chain = [AUTH_ADAPTERS[primary]]
|
||||||
|
if primary is not AuthProvider.DEV_KEY and settings.environment != "production":
|
||||||
|
chain.append(AUTH_ADAPTERS[AuthProvider.DEV_KEY])
|
||||||
|
return chain
|
||||||
|
|
||||||
|
|
||||||
|
async def require_admin(request: Request) -> AdminPrincipal:
|
||||||
|
"""
|
||||||
|
FastAPI dependency yielding a uniform AdminPrincipal regardless of identity provider
|
||||||
|
(`settings.auth_provider`). Routers and services never inspect credentials themselves.
|
||||||
|
"""
|
||||||
|
for adapter in resolve_adapter_chain():
|
||||||
|
principal = await adapter.authenticate(request)
|
||||||
|
if principal is not None:
|
||||||
return principal
|
return principal
|
||||||
|
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Autenticación de administrador requerida.",
|
||||||
|
)
|
||||||
+41
-1
@@ -1,12 +1,21 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
from enum import StrEnum
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from pydantic import BeforeValidator
|
from pydantic import BeforeValidator
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class AuthProvider(StrEnum):
|
||||||
|
"""Identity source strategy consumed by `app.core.auth.require_admin`."""
|
||||||
|
|
||||||
|
PROXY_HEADERS = "proxy_headers"
|
||||||
|
GOOGLE_OAUTH = "google_oauth"
|
||||||
|
DEV_KEY = "dev_key"
|
||||||
|
|
||||||
|
|
||||||
def _parse_str_list(v: str | list[str]) -> list[str]:
|
def _parse_str_list(v: str | list[str]) -> list[str]:
|
||||||
if isinstance(v, str):
|
if isinstance(v, str):
|
||||||
try:
|
try:
|
||||||
@@ -19,6 +28,18 @@ def _parse_str_list(v: str | list[str]) -> list[str]:
|
|||||||
return [str(x).strip() for x in v if str(x).strip()]
|
return [str(x).strip() for x in v if str(x).strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_int_list(v: str | list[int]) -> list[int]:
|
||||||
|
if isinstance(v, str):
|
||||||
|
try:
|
||||||
|
parsed = json.loads(v)
|
||||||
|
if isinstance(parsed, list):
|
||||||
|
return [int(x) for x in parsed]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return [int(x.strip()) for x in v.split(",") if x.strip()]
|
||||||
|
return [int(x) for x in v]
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
model_config = SettingsConfigDict(
|
model_config = SettingsConfigDict(
|
||||||
env_file=".env",
|
env_file=".env",
|
||||||
@@ -39,7 +60,12 @@ class Settings(BaseSettings):
|
|||||||
"http://localhost:3000",
|
"http://localhost:3000",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Security & Google OAuth + Turso Allowlist
|
# Security & Pluggable Authentication (ADR-0005, ADR-0006)
|
||||||
|
# proxy_headers: trust Authelia Remote-* headers (API must only be reachable via the proxy)
|
||||||
|
# google_oauth: HMAC session token/cookie verified against Turso admin_allowlist
|
||||||
|
# dev_key: X-Admin-Key (+ X-Admin-Email) verified against admin_allowlist
|
||||||
|
# Outside production, dev_key is also tried as a fallback when the primary finds no credentials.
|
||||||
|
auth_provider: AuthProvider = AuthProvider.GOOGLE_OAUTH
|
||||||
admin_api_key: str = "dev-secret-key-change-in-production"
|
admin_api_key: str = "dev-secret-key-change-in-production"
|
||||||
session_secret_key: str = "dev-session-secret-change-in-production"
|
session_secret_key: str = "dev-session-secret-change-in-production"
|
||||||
session_ttl_seconds: int = 86400 * 7 # 7 days
|
session_ttl_seconds: int = 86400 * 7 # 7 days
|
||||||
@@ -63,6 +89,20 @@ class Settings(BaseSettings):
|
|||||||
spei_bank: str = "BBVA"
|
spei_bank: str = "BBVA"
|
||||||
spei_beneficiary: str = "Jasmin"
|
spei_beneficiary: str = "Jasmin"
|
||||||
|
|
||||||
|
# Business hours & availability engine (ADR-0003)
|
||||||
|
business_timezone: str = "America/Mexico_City"
|
||||||
|
availability_open_time: str = "09:00"
|
||||||
|
availability_close_time: str = "19:00"
|
||||||
|
availability_slot_step_minutes: int = 30
|
||||||
|
availability_working_weekdays: Annotated[list[int], BeforeValidator(_parse_int_list)] = [
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4,
|
||||||
|
] # Mon-Fri
|
||||||
|
availability_max_range_days: int = 60
|
||||||
|
|
||||||
# Google Calendar
|
# Google Calendar
|
||||||
gcal_calendar_id: str = "primary"
|
gcal_calendar_id: str = "primary"
|
||||||
google_service_account_json: str | None = None
|
google_service_account_json: str | None = None
|
||||||
|
|||||||
+14
-1
@@ -7,7 +7,17 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
|
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.db.init_db import init_schema_and_seed
|
from app.db.init_db import init_schema_and_seed
|
||||||
from app.routers import auth, bookings, health, packages, payments, services
|
from app.routers import (
|
||||||
|
auth,
|
||||||
|
availability,
|
||||||
|
bookings,
|
||||||
|
clients,
|
||||||
|
health,
|
||||||
|
packages,
|
||||||
|
payments,
|
||||||
|
rosters,
|
||||||
|
services,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@contextlib.asynccontextmanager
|
@contextlib.asynccontextmanager
|
||||||
@@ -40,6 +50,9 @@ app.add_middleware(
|
|||||||
app.include_router(health.router)
|
app.include_router(health.router)
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(services.router)
|
app.include_router(services.router)
|
||||||
|
app.include_router(availability.router)
|
||||||
|
app.include_router(rosters.router)
|
||||||
|
app.include_router(clients.router)
|
||||||
app.include_router(bookings.router)
|
app.include_router(bookings.router)
|
||||||
app.include_router(packages.router)
|
app.include_router(packages.router)
|
||||||
app.include_router(payments.router)
|
app.include_router(payments.router)
|
||||||
|
|||||||
+6
-1
@@ -3,6 +3,7 @@ from enum import StrEnum
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from pydantic import BeforeValidator, EmailStr
|
from pydantic import BeforeValidator, EmailStr
|
||||||
|
from sqlalchemy import Enum as SAEnum
|
||||||
from sqlmodel import Field, SQLModel
|
from sqlmodel import Field, SQLModel
|
||||||
from sqlmodel._compat import SQLModelConfig
|
from sqlmodel._compat import SQLModelConfig
|
||||||
|
|
||||||
@@ -42,6 +43,8 @@ class ActionTypeEnum(StrEnum):
|
|||||||
UPDATE_BOOKING_STATUS = "UPDATE_BOOKING_STATUS"
|
UPDATE_BOOKING_STATUS = "UPDATE_BOOKING_STATUS"
|
||||||
RELEASE_BOOKING = "RELEASE_BOOKING"
|
RELEASE_BOOKING = "RELEASE_BOOKING"
|
||||||
RETRY_CALENDAR_SYNC = "RETRY_CALENDAR_SYNC"
|
RETRY_CALENDAR_SYNC = "RETRY_CALENDAR_SYNC"
|
||||||
|
ROSTER_CHECKIN = "ROSTER_CHECKIN"
|
||||||
|
ROSTER_WALK_IN = "ROSTER_WALK_IN"
|
||||||
|
|
||||||
|
|
||||||
ActionType = Annotated[
|
ActionType = Annotated[
|
||||||
@@ -66,7 +69,9 @@ class AdminAuditLog(SQLModel, table=True):
|
|||||||
id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
|
id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
|
||||||
admin_email: EmailStr = Field(foreign_key="admin_allowlist.email")
|
admin_email: EmailStr = Field(foreign_key="admin_allowlist.email")
|
||||||
action_type: ActionType
|
action_type: ActionType
|
||||||
entity_type: EntityType
|
entity_type: EntityType = Field(
|
||||||
|
sa_type=SAEnum(EntityTypeEnum, values_callable=lambda x: [e.value for e in x])
|
||||||
|
)
|
||||||
entity_id: str
|
entity_id: str
|
||||||
details_json: str | None = None
|
details_json: str | None = None
|
||||||
created_at: str = Field(default_factory=utc_now_iso)
|
created_at: str = Field(default_factory=utc_now_iso)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Persistence boundary for repositories built on SQLModel sessions."""
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from app.models.admin import AdminAllowlist
|
||||||
|
from app.services.timestamps import utc_now_iso
|
||||||
|
|
||||||
|
|
||||||
|
def mirror_admin_actor(session: Session, *, email: str, full_name: str, role: str) -> None:
|
||||||
|
"""
|
||||||
|
Upsert an externally-authenticated actor (e.g. Authelia proxy user) into `admin_allowlist`
|
||||||
|
so that actor columns (`admin_audit_log.admin_email`, `payments.acknowledged_by`, ...) keep
|
||||||
|
referential integrity (ADR-0006).
|
||||||
|
|
||||||
|
The identity provider is authoritative for name and role, so both are refreshed on every
|
||||||
|
write. `is_active` is deliberately left untouched on conflict: mirroring records who acted,
|
||||||
|
it never re-enables a row an operator disabled.
|
||||||
|
"""
|
||||||
|
now = utc_now_iso()
|
||||||
|
table = AdminAllowlist.__table__ # pyright: ignore[reportAttributeAccessIssue]
|
||||||
|
stmt = sqlite_insert(table).values(
|
||||||
|
email=email,
|
||||||
|
full_name=full_name,
|
||||||
|
role=role,
|
||||||
|
is_active=True,
|
||||||
|
created_at=now,
|
||||||
|
last_login_at=now,
|
||||||
|
)
|
||||||
|
stmt = stmt.on_conflict_do_update(
|
||||||
|
index_elements=[table.c.email],
|
||||||
|
set_={"full_name": full_name, "role": role, "last_login_at": now},
|
||||||
|
)
|
||||||
|
session.exec(stmt) # pyright: ignore[reportCallIssue, reportArgumentType]
|
||||||
|
session.commit()
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import libsql_client
|
||||||
|
|
||||||
|
from app.db.database import result_to_dicts, row_to_dict
|
||||||
|
from app.schemas.client import Client360Read, ClientCreate, ClientRead, ClientUpdate
|
||||||
|
from app.schemas.package import PackageRead
|
||||||
|
from app.services.bookings import hydrate_booking_row
|
||||||
|
from app.services.timestamps import utc_now_iso
|
||||||
|
|
||||||
|
|
||||||
|
def _hydrate_client(row: dict[str, Any]) -> ClientRead:
|
||||||
|
return ClientRead(
|
||||||
|
id=str(row["id"]),
|
||||||
|
full_name=str(row["full_name"]),
|
||||||
|
phone_whatsapp=str(row["phone_whatsapp"]),
|
||||||
|
email=row.get("email"),
|
||||||
|
notes=row.get("notes"),
|
||||||
|
created_at=str(row["created_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _hydrate_package(r: dict[str, Any]) -> PackageRead:
|
||||||
|
total = int(r["total_sessions"])
|
||||||
|
completed = int(r.get("completed_sessions", 0))
|
||||||
|
return PackageRead(
|
||||||
|
id=str(r["id"]),
|
||||||
|
client_id=str(r["client_id"]),
|
||||||
|
client_name=r.get("client_name"),
|
||||||
|
client_phone=r.get("client_phone"),
|
||||||
|
service_id=str(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=str(r["created_at"]),
|
||||||
|
updated_at=str(r["updated_at"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def list_and_search_clients(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
*,
|
||||||
|
search: str | None = None,
|
||||||
|
limit: int = 50,
|
||||||
|
offset: int = 0,
|
||||||
|
) -> list[ClientRead]:
|
||||||
|
"""
|
||||||
|
List and search clients with optional case-insensitive matching on full_name and phone_whatsapp.
|
||||||
|
Supports limit and offset pagination.
|
||||||
|
"""
|
||||||
|
params: list[libsql_client.InValue] = []
|
||||||
|
query = "SELECT id, full_name, phone_whatsapp, email, notes, created_at FROM clients"
|
||||||
|
|
||||||
|
if search and search.strip():
|
||||||
|
term = search.strip()
|
||||||
|
query += " WHERE LOWER(full_name) LIKE ? OR phone_whatsapp LIKE ?"
|
||||||
|
params.extend([f"%{term.lower()}%", f"%{term}%"])
|
||||||
|
|
||||||
|
query += " ORDER BY full_name ASC LIMIT ? OFFSET ?;"
|
||||||
|
params.extend([limit, offset])
|
||||||
|
|
||||||
|
res = await client.execute(query, params)
|
||||||
|
rows = result_to_dicts(res)
|
||||||
|
return [_hydrate_client(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_client_by_id(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
client_id: str,
|
||||||
|
) -> ClientRead | None:
|
||||||
|
"""Retrieve client details by unique ID."""
|
||||||
|
res = await client.execute(
|
||||||
|
"SELECT id, full_name, phone_whatsapp, email, notes, created_at FROM clients WHERE id = ? LIMIT 1;",
|
||||||
|
[client_id],
|
||||||
|
)
|
||||||
|
if not res.rows:
|
||||||
|
return None
|
||||||
|
return _hydrate_client(row_to_dict(res, res.rows[0]))
|
||||||
|
|
||||||
|
|
||||||
|
async def get_client_by_phone(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
phone: str,
|
||||||
|
*,
|
||||||
|
exclude_id: str | None = None,
|
||||||
|
) -> ClientRead | None:
|
||||||
|
"""Find a client matching the given phone number, optionally excluding a specific client ID."""
|
||||||
|
clean_phone = phone.strip()
|
||||||
|
query = "SELECT id, full_name, phone_whatsapp, email, notes, created_at FROM clients WHERE phone_whatsapp = ?"
|
||||||
|
params: list[libsql_client.InValue] = [clean_phone]
|
||||||
|
if exclude_id:
|
||||||
|
query += " AND id != ?"
|
||||||
|
params.append(exclude_id)
|
||||||
|
query += " LIMIT 1;"
|
||||||
|
|
||||||
|
res = await client.execute(query, params)
|
||||||
|
if not res.rows:
|
||||||
|
return None
|
||||||
|
return _hydrate_client(row_to_dict(res, res.rows[0]))
|
||||||
|
|
||||||
|
|
||||||
|
async def create_client(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
payload: ClientCreate,
|
||||||
|
) -> ClientRead:
|
||||||
|
"""Persist a new client record."""
|
||||||
|
client_id = str(uuid.uuid4())
|
||||||
|
now = utc_now_iso()
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO clients (id, full_name, phone_whatsapp, email, notes, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?);
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
client_id,
|
||||||
|
payload.full_name.strip(),
|
||||||
|
payload.phone_whatsapp.strip(),
|
||||||
|
str(payload.email) if payload.email else None,
|
||||||
|
payload.notes,
|
||||||
|
now,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
return ClientRead(
|
||||||
|
id=client_id,
|
||||||
|
full_name=payload.full_name.strip(),
|
||||||
|
phone_whatsapp=payload.phone_whatsapp.strip(),
|
||||||
|
email=payload.email,
|
||||||
|
notes=payload.notes,
|
||||||
|
created_at=now,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def update_client(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
client_id: str,
|
||||||
|
payload: ClientUpdate,
|
||||||
|
) -> ClientRead | None:
|
||||||
|
"""Update mutable client fields."""
|
||||||
|
existing = await get_client_by_id(client, client_id)
|
||||||
|
if not existing:
|
||||||
|
return None
|
||||||
|
|
||||||
|
updates: list[str] = []
|
||||||
|
params: list[libsql_client.InValue] = []
|
||||||
|
|
||||||
|
if payload.full_name is not None:
|
||||||
|
updates.append("full_name = ?")
|
||||||
|
params.append(payload.full_name.strip())
|
||||||
|
if payload.phone_whatsapp is not None:
|
||||||
|
updates.append("phone_whatsapp = ?")
|
||||||
|
params.append(payload.phone_whatsapp.strip())
|
||||||
|
if payload.email is not None:
|
||||||
|
updates.append("email = ?")
|
||||||
|
params.append(str(payload.email))
|
||||||
|
if payload.notes is not None:
|
||||||
|
updates.append("notes = ?")
|
||||||
|
params.append(payload.notes)
|
||||||
|
|
||||||
|
if not updates:
|
||||||
|
return existing
|
||||||
|
|
||||||
|
params.append(client_id)
|
||||||
|
query = f"UPDATE clients SET {', '.join(updates)} WHERE id = ?;"
|
||||||
|
await client.execute(query, params)
|
||||||
|
return await get_client_by_id(client, client_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_client_dependencies(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
client_id: str,
|
||||||
|
) -> dict[str, int]:
|
||||||
|
"""Check how many bookings and packages reference this client."""
|
||||||
|
b_res = await client.execute(
|
||||||
|
"SELECT COUNT(*) FROM bookings WHERE client_id = ?;",
|
||||||
|
[client_id],
|
||||||
|
)
|
||||||
|
bookings_count = int(str(b_res.rows[0][0] or 0)) if b_res.rows else 0
|
||||||
|
|
||||||
|
p_res = await client.execute(
|
||||||
|
"SELECT COUNT(*) FROM packages WHERE client_id = ?;",
|
||||||
|
[client_id],
|
||||||
|
)
|
||||||
|
packages_count = int(str(p_res.rows[0][0] or 0)) if p_res.rows else 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"bookings_count": bookings_count,
|
||||||
|
"packages_count": packages_count,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_client(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
client_id: str,
|
||||||
|
) -> None:
|
||||||
|
"""Delete client row from database."""
|
||||||
|
await client.execute("DELETE FROM clients WHERE id = ?;", [client_id])
|
||||||
|
|
||||||
|
|
||||||
|
async def get_client_360_profile(
|
||||||
|
client: libsql_client.Client,
|
||||||
|
client_id: str,
|
||||||
|
) -> Client360Read | None:
|
||||||
|
"""
|
||||||
|
Retrieve comprehensive 360-degree client profile containing contact info,
|
||||||
|
active multi-session packages, and full booking history.
|
||||||
|
"""
|
||||||
|
c_res = await client.execute(
|
||||||
|
"SELECT id, full_name, phone_whatsapp, email, notes, created_at FROM clients WHERE id = ? LIMIT 1;",
|
||||||
|
[client_id],
|
||||||
|
)
|
||||||
|
if not c_res.rows:
|
||||||
|
return None
|
||||||
|
c_dict = row_to_dict(c_res, c_res.rows[0])
|
||||||
|
|
||||||
|
# Active packages (where completed_sessions < total_sessions)
|
||||||
|
pkg_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.client_id = ? AND p.completed_sessions < p.total_sessions
|
||||||
|
ORDER BY p.created_at DESC;
|
||||||
|
"""
|
||||||
|
pkg_res = await client.execute(pkg_query, [client_id])
|
||||||
|
active_packages = [_hydrate_package(r) for r in result_to_dicts(pkg_res)]
|
||||||
|
|
||||||
|
# Recent booking history
|
||||||
|
booking_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
|
||||||
|
WHERE b.client_id = ?
|
||||||
|
ORDER BY b.scheduled_at DESC;
|
||||||
|
"""
|
||||||
|
b_res = await client.execute(booking_query, [client_id])
|
||||||
|
bookings = [hydrate_booking_row(r) for r in result_to_dicts(b_res)]
|
||||||
|
|
||||||
|
return Client360Read(
|
||||||
|
id=str(c_dict["id"]),
|
||||||
|
full_name=str(c_dict["full_name"]),
|
||||||
|
phone_whatsapp=str(c_dict["phone_whatsapp"]),
|
||||||
|
email=c_dict.get("email"),
|
||||||
|
notes=c_dict.get("notes"),
|
||||||
|
created_at=str(c_dict["created_at"]),
|
||||||
|
active_packages=active_packages,
|
||||||
|
booking_history=bookings,
|
||||||
|
recent_bookings=bookings,
|
||||||
|
)
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import date, time
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
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.routers.bookings import parse_iso_datetime
|
||||||
|
from app.schemas.availability import AvailabilityResponse, DayAvailabilityRead, SlotRead
|
||||||
|
from app.services.availability import (
|
||||||
|
BlockedInterval,
|
||||||
|
BusinessHours,
|
||||||
|
blocked_interval,
|
||||||
|
compute_available_slots,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/availability", tags=["Availability"])
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_time(time_str: str) -> time:
|
||||||
|
parts = [int(p) for p in time_str.split(":")]
|
||||||
|
return time(hour=parts[0], minute=parts[1])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=AvailabilityResponse)
|
||||||
|
async def get_availability(
|
||||||
|
service_id: str = Query(..., description="ID of the service to check availability for"),
|
||||||
|
date_from: date = Query(..., description="Start date (YYYY-MM-DD) inclusive"),
|
||||||
|
date_to: date = Query(..., description="End date (YYYY-MM-DD) inclusive"),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Public-facing endpoint to query available appointment slots for INDIVIDUAL services.
|
||||||
|
Enforces service duration and mandatory 15-minute post-session buffer collision rules.
|
||||||
|
"""
|
||||||
|
if date_to < date_from:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||||
|
detail="date_to cannot be earlier than date_from.",
|
||||||
|
)
|
||||||
|
|
||||||
|
range_days = (date_to - date_from).days + 1
|
||||||
|
if range_days > settings.availability_max_range_days:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||||
|
detail=f"Requested range ({range_days} days) exceeds maximum allowed limit ({settings.availability_max_range_days} days).",
|
||||||
|
)
|
||||||
|
|
||||||
|
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;",
|
||||||
|
[service_id],
|
||||||
|
)
|
||||||
|
if not svc_res.rows:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Service '{service_id}' not found or inactive.",
|
||||||
|
)
|
||||||
|
|
||||||
|
service = row_to_dict(svc_res, svc_res.rows[0])
|
||||||
|
if service["service_type"] != "INDIVIDUAL":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Availability query is only applicable to INDIVIDUAL appointment services.",
|
||||||
|
)
|
||||||
|
|
||||||
|
duration_minutes = int(service.get("duration_minutes", 60))
|
||||||
|
buffer_minutes = int(service.get("buffer_minutes", 15))
|
||||||
|
service_name = str(service["name"])
|
||||||
|
|
||||||
|
# 2. Fetch all existing active reservations that could cause collisions
|
||||||
|
# (bookings where booking_status = 'RESERVED')
|
||||||
|
b_res = await client.execute(
|
||||||
|
"""
|
||||||
|
SELECT scheduled_at, duration_minutes, buffer_minutes
|
||||||
|
FROM bookings
|
||||||
|
WHERE booking_status = 'RESERVED';
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
existing_rows = result_to_dicts(b_res)
|
||||||
|
|
||||||
|
existing_intervals: list[BlockedInterval] = []
|
||||||
|
for r in existing_rows:
|
||||||
|
dt = parse_iso_datetime(str(r["scheduled_at"]))
|
||||||
|
dur = int(r.get("duration_minutes", 60))
|
||||||
|
buf = int(r.get("buffer_minutes", 0))
|
||||||
|
existing_intervals.append(blocked_interval(dt, dur, buf))
|
||||||
|
|
||||||
|
tz = ZoneInfo(settings.business_timezone)
|
||||||
|
hours = BusinessHours(
|
||||||
|
timezone=tz,
|
||||||
|
open_time=_parse_time(settings.availability_open_time),
|
||||||
|
close_time=_parse_time(settings.availability_close_time),
|
||||||
|
working_weekdays=frozenset(settings.availability_working_weekdays),
|
||||||
|
slot_step_minutes=settings.availability_slot_step_minutes,
|
||||||
|
)
|
||||||
|
|
||||||
|
available_slots = compute_available_slots(
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
duration_minutes=duration_minutes,
|
||||||
|
buffer_minutes=buffer_minutes,
|
||||||
|
existing=existing_intervals,
|
||||||
|
hours=hours,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Group available slots by date
|
||||||
|
days_dict: dict[date, list[SlotRead]] = defaultdict(list)
|
||||||
|
for slot in available_slots:
|
||||||
|
slot_date = slot.start.date()
|
||||||
|
days_dict[slot_date].append(
|
||||||
|
SlotRead(start=slot.start.isoformat(), end=slot.end.isoformat())
|
||||||
|
)
|
||||||
|
|
||||||
|
# Maintain sorted dates representation
|
||||||
|
days_list: list[DayAvailabilityRead] = [
|
||||||
|
DayAvailabilityRead(date=d.isoformat(), slots=slots)
|
||||||
|
for d, slots in sorted(days_dict.items(), key=lambda x: x[0])
|
||||||
|
]
|
||||||
|
|
||||||
|
return AvailabilityResponse(
|
||||||
|
service_id=service_id,
|
||||||
|
service_name=service_name,
|
||||||
|
duration_minutes=duration_minutes,
|
||||||
|
buffer_minutes=buffer_minutes,
|
||||||
|
timezone=settings.business_timezone,
|
||||||
|
days=days_list,
|
||||||
|
)
|
||||||
+301
-179
@@ -1,29 +1,34 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import secrets
|
|
||||||
import urllib.parse
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import libsql_client
|
import libsql_client
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
|
|
||||||
from app.core.auth import record_admin_audit, require_admin
|
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.db.database import get_db, result_to_dicts, row_to_dict
|
||||||
from app.schemas.auth import AdminPrincipal
|
from app.schemas.auth import AdminPrincipal
|
||||||
from app.schemas.booking import (
|
from app.schemas.booking import (
|
||||||
|
BookingCompleteRequest,
|
||||||
BookingCreate,
|
BookingCreate,
|
||||||
BookingPaymentStatus,
|
BookingPaymentStatus,
|
||||||
BookingRead,
|
BookingRead,
|
||||||
BookingReleaseRequest,
|
BookingReleaseRequest,
|
||||||
|
BookingRescheduleRequest,
|
||||||
BookingStatus,
|
BookingStatus,
|
||||||
BookingStatusUpdateRequest,
|
BookingStatusUpdateRequest,
|
||||||
DelayedPaymentAuthorizeRequest,
|
DelayedPaymentAuthorizeRequest,
|
||||||
PaymentArrangement,
|
PaymentArrangement,
|
||||||
)
|
)
|
||||||
|
from app.services.bookings import (
|
||||||
|
check_slot_collision,
|
||||||
|
generate_booking_code,
|
||||||
|
hydrate_booking_row,
|
||||||
|
)
|
||||||
from app.services.calendar import calendar_service
|
from app.services.calendar import calendar_service
|
||||||
|
from app.services.timestamps import parse_iso_datetime
|
||||||
|
|
||||||
router = APIRouter(prefix="/bookings", tags=["Bookings"])
|
router = APIRouter(prefix="/bookings", tags=["Bookings"])
|
||||||
|
|
||||||
@@ -44,181 +49,6 @@ BOOKING_SELECT_QUERY = """
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def parse_iso_datetime(dt_str: str) -> datetime:
|
|
||||||
"""Parse an ISO 8601 string, normalizing naive datetimes to UTC."""
|
|
||||||
dt = datetime.fromisoformat(dt_str)
|
|
||||||
if dt.tzinfo is None:
|
|
||||||
dt = dt.replace(tzinfo=UTC)
|
|
||||||
return dt
|
|
||||||
|
|
||||||
|
|
||||||
def check_slot_collision(
|
|
||||||
new_start: datetime,
|
|
||||||
new_duration: int,
|
|
||||||
new_buffer: int,
|
|
||||||
existing_bookings: list[dict[str, Any]],
|
|
||||||
) -> bool:
|
|
||||||
"""
|
|
||||||
Returns True if the requested slot interval (including mandatory 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)
|
|
||||||
for b in existing_bookings:
|
|
||||||
exist_start = parse_iso_datetime(str(b["scheduled_at"]))
|
|
||||||
exist_duration = int(b.get("duration_minutes", 60))
|
|
||||||
exist_buffer = int(b.get("buffer_minutes", 0))
|
|
||||||
exist_blocked_end = exist_start + timedelta(minutes=exist_duration + exist_buffer)
|
|
||||||
|
|
||||||
if new_start < exist_blocked_end and exist_start < new_blocked_end:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
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,
|
|
||||||
package_info: str | None = None,
|
|
||||||
) -> str:
|
|
||||||
"""Generate a pre-filled WhatsApp link for the client to message Armonía del Ser."""
|
|
||||||
if package_info:
|
|
||||||
msg = (
|
|
||||||
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 {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"
|
|
||||||
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}"
|
|
||||||
|
|
||||||
|
|
||||||
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(
|
async def _fetch_hydrated_booking(
|
||||||
client: libsql_client.Client,
|
client: libsql_client.Client,
|
||||||
booking_id: str,
|
booking_id: str,
|
||||||
@@ -764,3 +594,295 @@ async def retry_calendar_sync(
|
|||||||
details={"sync_status": cal_res.sync_status, "sync_error": cal_res.sync_error},
|
details={"sync_status": cal_res.sync_status, "sync_error": cal_res.sync_error},
|
||||||
)
|
)
|
||||||
return await _fetch_hydrated_booking(client, booking_id)
|
return await _fetch_hydrated_booking(client, booking_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{booking_id}/reschedule", response_model=BookingRead)
|
||||||
|
async def reschedule_booking(
|
||||||
|
booking_id: str,
|
||||||
|
payload: BookingRescheduleRequest,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Reschedule an existing RESERVED booking to a new datetime.
|
||||||
|
Validates slot collision factoring in mandatory buffer times, updates Google Calendar,
|
||||||
|
and returns hydrated booking with updated WhatsApp deep link.
|
||||||
|
"""
|
||||||
|
async with get_db() as client:
|
||||||
|
# 1. Fetch current booking
|
||||||
|
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])
|
||||||
|
|
||||||
|
# 2. Validate booking_status is RESERVED
|
||||||
|
if booking["booking_status"] != "RESERVED":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Cannot reschedule booking with status {booking['booking_status']}. Only RESERVED bookings can be rescheduled.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Fetch service to check INDIVIDUAL vs GROUP, buffer, and duration
|
||||||
|
svc_res = await client.execute(
|
||||||
|
"SELECT * FROM services WHERE id = ? LIMIT 1;",
|
||||||
|
[booking["service_id"]],
|
||||||
|
)
|
||||||
|
if not svc_res.rows:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service not found")
|
||||||
|
service = row_to_dict(svc_res, svc_res.rows[0])
|
||||||
|
|
||||||
|
duration_minutes = int(
|
||||||
|
booking.get("duration_minutes") or service.get("duration_minutes", 60)
|
||||||
|
)
|
||||||
|
buffer_minutes = int(booking.get("buffer_minutes") or service.get("buffer_minutes", 0))
|
||||||
|
max_capacity = int(service.get("max_capacity", 1))
|
||||||
|
|
||||||
|
# 4. Collision check factoring in buffer
|
||||||
|
new_start = parse_iso_datetime(payload.new_scheduled_at)
|
||||||
|
if service["service_type"] == "INDIVIDUAL":
|
||||||
|
active_res = await client.execute(
|
||||||
|
"""
|
||||||
|
SELECT b.id, b.scheduled_at, b.duration_minutes, b.buffer_minutes
|
||||||
|
FROM bookings b
|
||||||
|
JOIN services s ON b.service_id = s.id
|
||||||
|
WHERE b.booking_status = 'RESERVED' AND s.service_type = 'INDIVIDUAL' AND b.id != ?;
|
||||||
|
""",
|
||||||
|
[booking_id],
|
||||||
|
)
|
||||||
|
active_bookings = result_to_dicts(active_res)
|
||||||
|
if check_slot_collision(new_start, duration_minutes, buffer_minutes, active_bookings):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=(
|
||||||
|
f"Horario no disponible: Entra en conflicto con otra consulta o con el "
|
||||||
|
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' AND id != ?;
|
||||||
|
""",
|
||||||
|
[service["id"], payload.new_scheduled_at, booking_id],
|
||||||
|
)
|
||||||
|
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.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Sync with Google Calendar
|
||||||
|
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=payload.new_scheduled_at,
|
||||||
|
duration_minutes=duration_minutes,
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_arrangement=str(booking["payment_arrangement"]),
|
||||||
|
payment_status=str(booking["payment_status"]),
|
||||||
|
existing_event_id=booking.get("gcal_event_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 6. Update booking scheduled_at and sync state
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
UPDATE bookings
|
||||||
|
SET scheduled_at = ?,
|
||||||
|
gcal_event_id = ?,
|
||||||
|
gcal_sync_status = ?,
|
||||||
|
gcal_sync_error = ?,
|
||||||
|
gcal_synced_at = ?
|
||||||
|
WHERE id = ?;
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
payload.new_scheduled_at,
|
||||||
|
cal_res.event_id,
|
||||||
|
cal_res.sync_status,
|
||||||
|
cal_res.sync_error,
|
||||||
|
cal_res.synced_at,
|
||||||
|
booking_id,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 7. Record admin audit log
|
||||||
|
await record_admin_audit(
|
||||||
|
client,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="RESCHEDULE_BOOKING",
|
||||||
|
entity_type="booking",
|
||||||
|
entity_id=booking_id,
|
||||||
|
details={
|
||||||
|
"booking_code": booking["booking_code"],
|
||||||
|
"previous_scheduled_at": booking["scheduled_at"],
|
||||||
|
"new_scheduled_at": payload.new_scheduled_at,
|
||||||
|
"notes": payload.notes,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 8. Package info if applicable
|
||||||
|
package_info = None
|
||||||
|
if booking.get("package_id"):
|
||||||
|
pkg_res = await client.execute(
|
||||||
|
"SELECT * FROM packages WHERE id = ? LIMIT 1;",
|
||||||
|
[booking["package_id"]],
|
||||||
|
)
|
||||||
|
if pkg_res.rows:
|
||||||
|
pkg_row = row_to_dict(pkg_res, pkg_res.rows[0])
|
||||||
|
package_info = (
|
||||||
|
f"Sesión {pkg_row['completed_sessions']} de {pkg_row['total_sessions']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return await _fetch_hydrated_booking(client, booking_id, package_info=package_info)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{booking_id}/complete", response_model=BookingRead)
|
||||||
|
async def complete_booking(
|
||||||
|
booking_id: str,
|
||||||
|
payload: BookingCompleteRequest | None = None,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Mark consultation session as COMPLETED.
|
||||||
|
Records package session completion if linked to a multi-session package,
|
||||||
|
updates Google Calendar, and records admin audit log.
|
||||||
|
"""
|
||||||
|
async with get_db() as client:
|
||||||
|
# 1. Fetch current booking
|
||||||
|
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])
|
||||||
|
|
||||||
|
# 2. Validate booking_status is RESERVED
|
||||||
|
if booking["booking_status"] != "RESERVED":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Cannot complete booking with status {booking['booking_status']}. Only RESERVED bookings can be marked as COMPLETED.",
|
||||||
|
)
|
||||||
|
|
||||||
|
now = datetime.now(UTC).isoformat()
|
||||||
|
notes = payload.notes if payload else None
|
||||||
|
target_pkg_id = (
|
||||||
|
payload.package_id if (payload and payload.package_id) else booking.get("package_id")
|
||||||
|
)
|
||||||
|
package_counter_advanced = False
|
||||||
|
|
||||||
|
# If a new package is linked during completion, advance counter and update payment arrangement
|
||||||
|
if payload and payload.package_id and booking.get("package_id") != payload.package_id:
|
||||||
|
pkg_res = await client.execute(
|
||||||
|
"SELECT * FROM packages WHERE id = ? LIMIT 1;",
|
||||||
|
[payload.package_id],
|
||||||
|
)
|
||||||
|
if not pkg_res.rows:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND, detail="Package not found"
|
||||||
|
)
|
||||||
|
pkg_row = row_to_dict(pkg_res, pkg_res.rows[0])
|
||||||
|
completed = int(pkg_row["completed_sessions"])
|
||||||
|
total = int(pkg_row["total_sessions"])
|
||||||
|
if completed >= total:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="El paquete ya no cuenta con sesiones disponibles",
|
||||||
|
)
|
||||||
|
await client.execute(
|
||||||
|
"UPDATE packages SET completed_sessions = completed_sessions + 1, updated_at = ? WHERE id = ?;",
|
||||||
|
[now, payload.package_id],
|
||||||
|
)
|
||||||
|
package_counter_advanced = True
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
UPDATE bookings
|
||||||
|
SET package_id = ?, payment_arrangement = 'PACKAGE_REDEEMED', payment_status = 'NOT_APPLICABLE'
|
||||||
|
WHERE id = ?;
|
||||||
|
""",
|
||||||
|
[payload.package_id, booking_id],
|
||||||
|
)
|
||||||
|
booking["package_id"] = payload.package_id
|
||||||
|
booking["payment_arrangement"] = "PACKAGE_REDEEMED"
|
||||||
|
booking["payment_status"] = "NOT_APPLICABLE"
|
||||||
|
|
||||||
|
# 3. Google Calendar sync
|
||||||
|
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="COMPLETED",
|
||||||
|
payment_arrangement=str(booking["payment_arrangement"]),
|
||||||
|
payment_status=str(booking["payment_status"]),
|
||||||
|
existing_event_id=booking.get("gcal_event_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Update booking_status = COMPLETED
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
UPDATE bookings
|
||||||
|
SET booking_status = 'COMPLETED',
|
||||||
|
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,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Admin audit log
|
||||||
|
audit_details: dict[str, Any] = {
|
||||||
|
"booking_code": booking["booking_code"],
|
||||||
|
"notes": notes,
|
||||||
|
}
|
||||||
|
if target_pkg_id:
|
||||||
|
audit_details["package_id"] = target_pkg_id
|
||||||
|
audit_details["package_session_completed"] = True
|
||||||
|
if package_counter_advanced:
|
||||||
|
audit_details["package_counter_advanced"] = True
|
||||||
|
await record_admin_audit(
|
||||||
|
client,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="COMPLETE_PACKAGE_SESSION",
|
||||||
|
entity_type="package",
|
||||||
|
entity_id=target_pkg_id,
|
||||||
|
details={"booking_id": booking_id, "booking_code": booking["booking_code"]},
|
||||||
|
)
|
||||||
|
|
||||||
|
await record_admin_audit(
|
||||||
|
client,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="COMPLETE_BOOKING",
|
||||||
|
entity_type="booking",
|
||||||
|
entity_id=booking_id,
|
||||||
|
details=audit_details,
|
||||||
|
)
|
||||||
|
|
||||||
|
package_info = None
|
||||||
|
if target_pkg_id:
|
||||||
|
pkg_res = await client.execute(
|
||||||
|
"SELECT * FROM packages WHERE id = ? LIMIT 1;", [target_pkg_id]
|
||||||
|
)
|
||||||
|
if pkg_res.rows:
|
||||||
|
pkg_row = row_to_dict(pkg_res, pkg_res.rows[0])
|
||||||
|
package_info = (
|
||||||
|
f"Sesión {pkg_row['completed_sessions']} de {pkg_row['total_sessions']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return await _fetch_hydrated_booking(client, booking_id, package_info=package_info)
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
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
|
||||||
|
from app.repositories import client as client_repo
|
||||||
|
from app.schemas.auth import AdminPrincipal
|
||||||
|
from app.schemas.client import Client360Read, ClientCreate, ClientRead, ClientUpdate
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/clients", tags=["Clients"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[ClientRead])
|
||||||
|
async def list_clients(
|
||||||
|
search: str | None = Query(
|
||||||
|
default=None, description="Case-insensitive search query matching name or phone"
|
||||||
|
),
|
||||||
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
|
offset: int = Query(default=0, ge=0),
|
||||||
|
_admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Search and list clients with autocomplete support matching full_name or phone_whatsapp.
|
||||||
|
Supports limit and offset pagination.
|
||||||
|
"""
|
||||||
|
async with get_db() as db:
|
||||||
|
return await client_repo.list_and_search_clients(
|
||||||
|
db, search=search, limit=limit, offset=offset
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{client_id}", response_model=Client360Read)
|
||||||
|
async def get_client(
|
||||||
|
client_id: str,
|
||||||
|
_admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Client 360 profile returning contact information, operational notes,
|
||||||
|
active multi-session packages (completed vs total sessions), and recent booking history.
|
||||||
|
"""
|
||||||
|
async with get_db() as db:
|
||||||
|
profile = await client_repo.get_client_360_profile(db, client_id)
|
||||||
|
if not profile:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
return profile
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ClientRead, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_client(
|
||||||
|
payload: ClientCreate,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Explicitly register a new client with phone number validation and duplicate detection.
|
||||||
|
"""
|
||||||
|
async with get_db() as db:
|
||||||
|
existing = await client_repo.get_client_by_phone(db, payload.phone_whatsapp)
|
||||||
|
if existing:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=f"A client with phone {payload.phone_whatsapp} already exists.",
|
||||||
|
)
|
||||||
|
|
||||||
|
new_client = await client_repo.create_client(db, payload)
|
||||||
|
|
||||||
|
await record_admin_audit(
|
||||||
|
db,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="CREATE_CLIENT",
|
||||||
|
entity_type="client",
|
||||||
|
entity_id=new_client.id,
|
||||||
|
details={
|
||||||
|
"full_name": new_client.full_name,
|
||||||
|
"phone_whatsapp": new_client.phone_whatsapp,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return new_client
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{client_id}", response_model=ClientRead)
|
||||||
|
async def update_client(
|
||||||
|
client_id: str,
|
||||||
|
payload: ClientUpdate,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update client contact details, full_name, phone_whatsapp, email, or clinical/operational notes.
|
||||||
|
"""
|
||||||
|
async with get_db() as db:
|
||||||
|
existing = await client_repo.get_client_by_id(db, client_id)
|
||||||
|
if not existing:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if payload.phone_whatsapp:
|
||||||
|
dup = await client_repo.get_client_by_phone(
|
||||||
|
db, payload.phone_whatsapp, exclude_id=client_id
|
||||||
|
)
|
||||||
|
if dup:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=f"Another client with phone {payload.phone_whatsapp} already exists.",
|
||||||
|
)
|
||||||
|
|
||||||
|
updated = await client_repo.update_client(db, client_id, payload)
|
||||||
|
if not updated:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
await record_admin_audit(
|
||||||
|
db,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="UPDATE_CLIENT",
|
||||||
|
entity_type="client",
|
||||||
|
entity_id=client_id,
|
||||||
|
details=payload.model_dump(exclude_none=True),
|
||||||
|
)
|
||||||
|
return updated
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{client_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_client(
|
||||||
|
client_id: str,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Safe client deletion verifying foreign key integrity.
|
||||||
|
Rejects deletion with HTTP 409 Conflict if the client has associated bookings or packages.
|
||||||
|
"""
|
||||||
|
async with get_db() as db:
|
||||||
|
existing = await client_repo.get_client_by_id(db, client_id)
|
||||||
|
if not existing:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Client not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
deps = await client_repo.get_client_dependencies(db, client_id)
|
||||||
|
bookings_count = deps["bookings_count"]
|
||||||
|
packages_count = deps["packages_count"]
|
||||||
|
|
||||||
|
if bookings_count > 0 or packages_count > 0:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=(
|
||||||
|
f"Cannot delete client: client has {bookings_count} associated booking(s) "
|
||||||
|
f"and {packages_count} package(s)."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
await client_repo.delete_client(db, client_id)
|
||||||
|
|
||||||
|
await record_admin_audit(
|
||||||
|
db,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="DELETE_CLIENT",
|
||||||
|
entity_type="client",
|
||||||
|
entity_id=client_id,
|
||||||
|
details={
|
||||||
|
"full_name": existing.full_name,
|
||||||
|
"phone_whatsapp": existing.phone_whatsapp,
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,449 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, date, datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
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.models.payment import PaymentMethodEnum
|
||||||
|
from app.routers.bookings import (
|
||||||
|
BOOKING_SELECT_QUERY,
|
||||||
|
generate_booking_code,
|
||||||
|
parse_iso_datetime,
|
||||||
|
)
|
||||||
|
from app.schemas.auth import AdminPrincipal
|
||||||
|
from app.schemas.roster import (
|
||||||
|
QuickCheckinRequest,
|
||||||
|
QuickCheckinResponse,
|
||||||
|
RosterAttendeeRead,
|
||||||
|
RosterSessionRead,
|
||||||
|
)
|
||||||
|
from app.services.calendar import calendar_service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/rosters", tags=["Group Workshop Rosters"])
|
||||||
|
|
||||||
|
|
||||||
|
def _to_utc_instant_key(dt_str: str) -> str:
|
||||||
|
"""Normalize ISO datetime string to an ISO UTC string so different representations group together."""
|
||||||
|
dt = parse_iso_datetime(dt_str)
|
||||||
|
return dt.astimezone(UTC).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[RosterSessionRead])
|
||||||
|
async def get_rosters(
|
||||||
|
date_from: date = Query(..., description="Start date (YYYY-MM-DD)"),
|
||||||
|
date_to: date = Query(..., description="End date (YYYY-MM-DD)"),
|
||||||
|
service_id: str | None = Query(None, description="Optional service ID filter"),
|
||||||
|
_admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Query workshop roster sessions for GROUP services within [date_from, date_to].
|
||||||
|
Groups bookings by session instant across different ISO timezone representations.
|
||||||
|
Excludes RELEASED and CANCELLED bookings.
|
||||||
|
"""
|
||||||
|
if date_to < date_from:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||||
|
detail="date_to cannot be earlier than date_from.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Convert date range to Mexico City timezone boundaries
|
||||||
|
tz = ZoneInfo(settings.business_timezone)
|
||||||
|
start_dt = datetime(
|
||||||
|
date_from.year, date_from.month, date_from.day, 0, 0, 0, tzinfo=tz
|
||||||
|
).astimezone(UTC)
|
||||||
|
end_dt = datetime(
|
||||||
|
date_to.year, date_to.month, date_to.day, 23, 59, 59, 999999, tzinfo=tz
|
||||||
|
).astimezone(UTC)
|
||||||
|
|
||||||
|
query = (
|
||||||
|
BOOKING_SELECT_QUERY
|
||||||
|
+ """
|
||||||
|
WHERE s.service_type = 'GROUP'
|
||||||
|
AND b.booking_status IN ('RESERVED', 'COMPLETED', 'NO_SHOW')
|
||||||
|
AND s.is_active = 1
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
params = []
|
||||||
|
if service_id:
|
||||||
|
query += " AND s.id = ?"
|
||||||
|
params.append(service_id)
|
||||||
|
|
||||||
|
query += " ORDER BY b.scheduled_at ASC;"
|
||||||
|
|
||||||
|
async with get_db() as client:
|
||||||
|
# Also fetch group service details
|
||||||
|
svc_query = "SELECT id, name, max_capacity FROM services WHERE service_type = 'GROUP';"
|
||||||
|
svc_res = await client.execute(svc_query)
|
||||||
|
services_by_id = {
|
||||||
|
str(r[0]): {"name": str(r[1]), "max_capacity": int(str(r[2] or 1))}
|
||||||
|
for r in svc_res.rows
|
||||||
|
}
|
||||||
|
|
||||||
|
res = await client.execute(query, params)
|
||||||
|
rows = result_to_dicts(res)
|
||||||
|
|
||||||
|
# Group by (service_id, normalized_instant_key)
|
||||||
|
sessions_map: dict[tuple[str, str], dict] = {}
|
||||||
|
|
||||||
|
for r in rows:
|
||||||
|
sched_dt_utc = parse_iso_datetime(str(r["scheduled_at"])).astimezone(UTC)
|
||||||
|
if not (start_dt <= sched_dt_utc <= end_dt):
|
||||||
|
continue
|
||||||
|
|
||||||
|
svc_id = str(r["service_id"])
|
||||||
|
instant_key = sched_dt_utc.isoformat()
|
||||||
|
group_key = (svc_id, instant_key)
|
||||||
|
|
||||||
|
if group_key not in sessions_map:
|
||||||
|
svc_info = services_by_id.get(
|
||||||
|
svc_id, {"name": str(r.get("service_name", "")), "max_capacity": 20}
|
||||||
|
)
|
||||||
|
sessions_map[group_key] = {
|
||||||
|
"service_id": svc_id,
|
||||||
|
"service_name": svc_info["name"],
|
||||||
|
"scheduled_at": str(r["scheduled_at"]), # preserve representative representation
|
||||||
|
"max_capacity": svc_info["max_capacity"],
|
||||||
|
"attendees": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
booking_status = str(r["booking_status"])
|
||||||
|
attended = booking_status == "COMPLETED"
|
||||||
|
|
||||||
|
sessions_map[group_key]["attendees"].append(
|
||||||
|
RosterAttendeeRead(
|
||||||
|
booking_id=str(r["id"]),
|
||||||
|
booking_code=str(r["booking_code"]),
|
||||||
|
client_id=str(r["client_id"]),
|
||||||
|
client_name=str(r.get("client_name") or ""),
|
||||||
|
client_phone=str(r.get("client_phone") or ""),
|
||||||
|
client_email=r.get("client_email"),
|
||||||
|
booking_status=booking_status,
|
||||||
|
payment_arrangement=str(r["payment_arrangement"]),
|
||||||
|
payment_status=str(r["payment_status"]),
|
||||||
|
amount_mxn=int(r["amount_mxn"]),
|
||||||
|
attended=attended,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
roster_sessions: list[RosterSessionRead] = []
|
||||||
|
for s_data in sessions_map.values():
|
||||||
|
attendees = s_data["attendees"]
|
||||||
|
occupied_count = len(attendees)
|
||||||
|
attended_count = sum(1 for a in attendees if a.attended)
|
||||||
|
roster_sessions.append(
|
||||||
|
RosterSessionRead(
|
||||||
|
service_id=s_data["service_id"],
|
||||||
|
service_name=s_data["service_name"],
|
||||||
|
scheduled_at=s_data["scheduled_at"],
|
||||||
|
max_capacity=s_data["max_capacity"],
|
||||||
|
occupied_count=occupied_count,
|
||||||
|
attended_count=attended_count,
|
||||||
|
attendees=attendees,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return roster_sessions
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/quick-checkin", response_model=QuickCheckinResponse)
|
||||||
|
async def quick_checkin(
|
||||||
|
payload: QuickCheckinRequest,
|
||||||
|
admin: AdminPrincipal = Depends(require_admin),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Perform a quick check-in for group workshops:
|
||||||
|
- Mode 1: Check in an existing booking (marking COMPLETED, optionally recording CASH payment).
|
||||||
|
- Mode 2: Register a walk-in attendee directly into COMPLETED status.
|
||||||
|
"""
|
||||||
|
now = datetime.now(UTC).isoformat()
|
||||||
|
|
||||||
|
async with get_db() as client:
|
||||||
|
# MODE 1: Existing booking check-in
|
||||||
|
if payload.booking_id:
|
||||||
|
b_res = await client.execute(
|
||||||
|
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])
|
||||||
|
svc_res = await client.execute(
|
||||||
|
"SELECT service_type FROM services WHERE id = ?;", [booking["service_id"]]
|
||||||
|
)
|
||||||
|
if not svc_res.rows or str(svc_res.rows[0][0]) != "GROUP":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Quick check-in is only available for GROUP workshops.",
|
||||||
|
)
|
||||||
|
|
||||||
|
current_status = str(booking["booking_status"])
|
||||||
|
if current_status in ("RELEASED", "CANCELLED"):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Cannot check in a {current_status.lower()} booking.",
|
||||||
|
)
|
||||||
|
if current_status == "COMPLETED":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="This attendee has already checked in.",
|
||||||
|
)
|
||||||
|
|
||||||
|
new_booking_status = "COMPLETED"
|
||||||
|
payment_id: str | None = None
|
||||||
|
current_p_status = str(booking["payment_status"])
|
||||||
|
current_p_arr = str(booking["payment_arrangement"])
|
||||||
|
|
||||||
|
if payload.paid_cash:
|
||||||
|
new_p_status = "ACKNOWLEDGED"
|
||||||
|
new_p_arr = current_p_arr
|
||||||
|
payment_id = str(uuid.uuid4())
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO payments (
|
||||||
|
id, booking_id, amount_mxn, payment_method, status,
|
||||||
|
acknowledged_by, acknowledged_at, notes, created_at
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, 'ACKNOWLEDGED', ?, ?, ?, ?);
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
payment_id,
|
||||||
|
booking["id"],
|
||||||
|
booking["amount_mxn"],
|
||||||
|
PaymentMethodEnum.CASH.value,
|
||||||
|
admin.email,
|
||||||
|
now,
|
||||||
|
payload.notes or "Quick check-in cash payment",
|
||||||
|
now,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if current_p_status == "ACKNOWLEDGED":
|
||||||
|
new_p_status = "ACKNOWLEDGED"
|
||||||
|
new_p_arr = current_p_arr
|
||||||
|
else:
|
||||||
|
new_p_status = "AWAITING_ACKNOWLEDGMENT"
|
||||||
|
new_p_arr = "DELAYED_ALLOWED"
|
||||||
|
|
||||||
|
cal_res = await calendar_service.sync_booking_event(
|
||||||
|
booking_id=str(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=new_booking_status,
|
||||||
|
payment_arrangement=new_p_arr,
|
||||||
|
payment_status=new_p_status,
|
||||||
|
existing_event_id=booking.get("gcal_event_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
UPDATE bookings
|
||||||
|
SET booking_status = ?,
|
||||||
|
payment_arrangement = ?,
|
||||||
|
payment_status = ?,
|
||||||
|
gcal_event_id = ?,
|
||||||
|
gcal_sync_status = ?,
|
||||||
|
gcal_sync_error = ?,
|
||||||
|
gcal_synced_at = ?
|
||||||
|
WHERE id = ?;
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
new_booking_status,
|
||||||
|
new_p_arr,
|
||||||
|
new_p_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="ROSTER_CHECKIN",
|
||||||
|
entity_type="booking",
|
||||||
|
entity_id=str(booking["id"]),
|
||||||
|
details={"paid_cash": payload.paid_cash, "payment_id": payment_id},
|
||||||
|
)
|
||||||
|
|
||||||
|
attendee = RosterAttendeeRead(
|
||||||
|
booking_id=str(booking["id"]),
|
||||||
|
booking_code=str(booking["booking_code"]),
|
||||||
|
client_id=str(booking["client_id"]),
|
||||||
|
client_name=str(booking["client_name"]),
|
||||||
|
client_phone=str(booking["client_phone"]),
|
||||||
|
client_email=booking.get("client_email"),
|
||||||
|
booking_status=new_booking_status,
|
||||||
|
payment_arrangement=new_p_arr,
|
||||||
|
payment_status=new_p_status,
|
||||||
|
amount_mxn=int(booking["amount_mxn"]),
|
||||||
|
attended=True,
|
||||||
|
)
|
||||||
|
return QuickCheckinResponse(walk_in=False, attendee=attendee, payment_id=payment_id)
|
||||||
|
|
||||||
|
# MODE 2: Walk-in registration and check-in
|
||||||
|
service_id = str(payload.service_id)
|
||||||
|
scheduled_at = str(payload.scheduled_at)
|
||||||
|
client_name = str(payload.client_name)
|
||||||
|
client_phone = str(payload.client_phone)
|
||||||
|
|
||||||
|
svc_res = await client.execute(
|
||||||
|
"SELECT * FROM services WHERE id = ? AND is_active = 1 LIMIT 1;",
|
||||||
|
[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])
|
||||||
|
if service["service_type"] != "GROUP":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Walk-in check-in is only applicable to GROUP workshops.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Capacity check for this group workshop session
|
||||||
|
cap_res = await client.execute(
|
||||||
|
"""
|
||||||
|
SELECT COUNT(*) AS count
|
||||||
|
FROM bookings
|
||||||
|
WHERE service_id = ? AND scheduled_at = ? AND booking_status IN ('RESERVED', 'COMPLETED');
|
||||||
|
""",
|
||||||
|
[service_id, scheduled_at],
|
||||||
|
)
|
||||||
|
current_count = int(str(cap_res.rows[0][0] or 0))
|
||||||
|
max_cap = int(service.get("max_capacity", 1))
|
||||||
|
if current_count >= max_cap:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail=f"El taller ha alcanzado su cupo máximo ({max_cap}) para esta sesión.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Upsert client by phone
|
||||||
|
c_res = await client.execute(
|
||||||
|
"SELECT id FROM clients WHERE phone_whatsapp = ? LIMIT 1;",
|
||||||
|
[client_phone],
|
||||||
|
)
|
||||||
|
if c_res.rows:
|
||||||
|
client_id = str(c_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, client_name, client_phone, payload.client_email, "Walk-in attendee"],
|
||||||
|
)
|
||||||
|
|
||||||
|
booking_id = str(uuid.uuid4())
|
||||||
|
booking_code = generate_booking_code()
|
||||||
|
duration_minutes = int(service.get("duration_minutes", 60))
|
||||||
|
buffer_minutes = int(service.get("buffer_minutes", 0))
|
||||||
|
amount_mxn = int(service["price_mxn"])
|
||||||
|
|
||||||
|
booking_status = "COMPLETED"
|
||||||
|
if payload.paid_cash:
|
||||||
|
payment_status = "ACKNOWLEDGED"
|
||||||
|
payment_arrangement = "PREPAID_DEFAULT"
|
||||||
|
else:
|
||||||
|
payment_status = "AWAITING_ACKNOWLEDGMENT"
|
||||||
|
payment_arrangement = "DELAYED_ALLOWED"
|
||||||
|
|
||||||
|
cal_res = await calendar_service.sync_booking_event(
|
||||||
|
booking_id=booking_id,
|
||||||
|
booking_code=booking_code,
|
||||||
|
service_name=str(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,
|
||||||
|
)
|
||||||
|
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO bookings (
|
||||||
|
id, booking_code, service_id, client_id, scheduled_at,
|
||||||
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
booking_id,
|
||||||
|
booking_code,
|
||||||
|
service["id"],
|
||||||
|
client_id,
|
||||||
|
scheduled_at,
|
||||||
|
duration_minutes,
|
||||||
|
buffer_minutes,
|
||||||
|
booking_status,
|
||||||
|
payment_arrangement,
|
||||||
|
payment_status,
|
||||||
|
amount_mxn,
|
||||||
|
cal_res.event_id,
|
||||||
|
cal_res.sync_status,
|
||||||
|
cal_res.sync_error,
|
||||||
|
cal_res.synced_at,
|
||||||
|
now,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
payment_id = None
|
||||||
|
if payload.paid_cash:
|
||||||
|
payment_id = str(uuid.uuid4())
|
||||||
|
await client.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO payments (
|
||||||
|
id, booking_id, amount_mxn, payment_method, status,
|
||||||
|
acknowledged_by, acknowledged_at, notes, created_at
|
||||||
|
) VALUES (?, ?, ?, ?, 'ACKNOWLEDGED', ?, ?, ?, ?);
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
payment_id,
|
||||||
|
booking_id,
|
||||||
|
amount_mxn,
|
||||||
|
PaymentMethodEnum.CASH.value,
|
||||||
|
admin.email,
|
||||||
|
now,
|
||||||
|
payload.notes or "Walk-in cash payment",
|
||||||
|
now,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
await record_admin_audit(
|
||||||
|
client,
|
||||||
|
admin_email=admin.email,
|
||||||
|
action_type="ROSTER_WALK_IN",
|
||||||
|
entity_type="booking",
|
||||||
|
entity_id=booking_id,
|
||||||
|
details={"paid_cash": payload.paid_cash, "payment_id": payment_id},
|
||||||
|
)
|
||||||
|
|
||||||
|
attendee = RosterAttendeeRead(
|
||||||
|
booking_id=booking_id,
|
||||||
|
booking_code=booking_code,
|
||||||
|
client_id=client_id,
|
||||||
|
client_name=client_name,
|
||||||
|
client_phone=client_phone,
|
||||||
|
client_email=payload.client_email,
|
||||||
|
booking_status=booking_status,
|
||||||
|
payment_arrangement=payment_arrangement,
|
||||||
|
payment_status=payment_status,
|
||||||
|
amount_mxn=amount_mxn,
|
||||||
|
attended=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return QuickCheckinResponse(walk_in=True, attendee=attendee, payment_id=payment_id)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class SlotRead(BaseModel):
|
||||||
|
start: str
|
||||||
|
end: str
|
||||||
|
|
||||||
|
|
||||||
|
class DayAvailabilityRead(BaseModel):
|
||||||
|
date: str
|
||||||
|
slots: list[SlotRead]
|
||||||
|
|
||||||
|
|
||||||
|
class AvailabilityResponse(BaseModel):
|
||||||
|
service_id: str
|
||||||
|
service_name: str
|
||||||
|
duration_minutes: int
|
||||||
|
buffer_minutes: int
|
||||||
|
timezone: str
|
||||||
|
days: list[DayAvailabilityRead]
|
||||||
@@ -39,6 +39,22 @@ class BookingStatusUpdateRequest(BaseModel):
|
|||||||
notes: str | None = None
|
notes: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class BookingRescheduleRequest(BaseModel):
|
||||||
|
new_scheduled_at: str = Field(
|
||||||
|
..., description="ISO 8601 string for new scheduled date and time"
|
||||||
|
)
|
||||||
|
notes: str | None = Field(default=None, description="Optional notes or reason for rescheduling")
|
||||||
|
|
||||||
|
|
||||||
|
class BookingCompleteRequest(BaseModel):
|
||||||
|
package_id: str | None = Field(
|
||||||
|
default=None, description="Optional package to link or redeem for this booking"
|
||||||
|
)
|
||||||
|
notes: str | None = Field(
|
||||||
|
default=None, description="Optional clinical/consultation completion notes"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class BookingRead(BaseModel):
|
class BookingRead(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
booking_code: str
|
booking_code: str
|
||||||
|
|||||||
+72
-3
@@ -1,19 +1,88 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pydantic import BaseModel, EmailStr, Field, field_validator
|
||||||
|
|
||||||
|
from app.schemas.booking import BookingRead
|
||||||
|
from app.schemas.package import PackageRead
|
||||||
|
|
||||||
|
PHONE_WITH_EXT_REGEX = re.compile(
|
||||||
|
r"^((?:\+?\d{1,3}[-.\s]?)?(?:\(?\d{2,4}\)?[-.\s]?){2,4}\d{3,4})(?:[-.\s]*(?:ext|ext\.|x|#|extension)[-.\s]*(\d+))?$",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_phone_format(v: str) -> str:
|
||||||
|
clean_value = v.strip()
|
||||||
|
if not PHONE_WITH_EXT_REGEX.match(clean_value):
|
||||||
|
raise ValueError(
|
||||||
|
"Invalid phone number format. Examples of valid formats: "
|
||||||
|
"'+1 (555) 019-2834', '555-019-2834 ext 123', or '5550192834x12'"
|
||||||
|
)
|
||||||
|
return clean_value
|
||||||
|
|
||||||
|
|
||||||
class ClientBase(BaseModel):
|
class ClientBase(BaseModel):
|
||||||
full_name: str = Field(..., min_length=2, max_length=150)
|
full_name: str = Field(..., min_length=2, max_length=150)
|
||||||
phone_whatsapp: str = Field(..., min_length=10, max_length=20)
|
phone_whatsapp: str = Field(..., min_length=10, max_length=50)
|
||||||
email: str | None = None
|
email: EmailStr | None = None
|
||||||
notes: str | None = None
|
notes: str | None = None
|
||||||
|
|
||||||
|
@field_validator("phone_whatsapp")
|
||||||
|
@classmethod
|
||||||
|
def validate_phone(cls, v: str) -> str:
|
||||||
|
return validate_phone_format(v)
|
||||||
|
|
||||||
|
@field_validator("email", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def normalize_email(cls, v: Any) -> Any:
|
||||||
|
if isinstance(v, str) and not v.strip():
|
||||||
|
return None
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
class ClientCreate(ClientBase):
|
class ClientCreate(ClientBase):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ClientUpdate(BaseModel):
|
||||||
|
full_name: str | None = Field(default=None, min_length=2, max_length=150)
|
||||||
|
phone_whatsapp: str | None = Field(default=None, min_length=10, max_length=50)
|
||||||
|
email: EmailStr | None = None
|
||||||
|
notes: str | None = None
|
||||||
|
|
||||||
|
@field_validator("phone_whatsapp")
|
||||||
|
@classmethod
|
||||||
|
def validate_phone(cls, v: str | None) -> str | None:
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
return validate_phone_format(v)
|
||||||
|
|
||||||
|
@field_validator("email", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def normalize_email(cls, v: Any) -> Any:
|
||||||
|
if isinstance(v, str) and not v.strip():
|
||||||
|
return None
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
class ClientRead(ClientBase):
|
class ClientRead(ClientBase):
|
||||||
id: str
|
id: str
|
||||||
created_at: str
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
|
class Client360Read(BaseModel):
|
||||||
|
id: str
|
||||||
|
full_name: str
|
||||||
|
phone_whatsapp: str
|
||||||
|
email: EmailStr | None = None
|
||||||
|
notes: str | None = None
|
||||||
|
created_at: str
|
||||||
|
active_packages: list[PackageRead] = Field(default_factory=list)
|
||||||
|
booking_history: list[BookingRead] = Field(default_factory=list)
|
||||||
|
recent_bookings: list[BookingRead] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
ClientDetailRead = Client360Read
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pydantic import BaseModel, model_validator
|
||||||
|
|
||||||
|
|
||||||
|
class RosterAttendeeRead(BaseModel):
|
||||||
|
booking_id: str
|
||||||
|
booking_code: str
|
||||||
|
client_id: str
|
||||||
|
client_name: str
|
||||||
|
client_phone: str
|
||||||
|
client_email: str | None = None
|
||||||
|
booking_status: str
|
||||||
|
payment_arrangement: str
|
||||||
|
payment_status: str
|
||||||
|
amount_mxn: int
|
||||||
|
attended: bool
|
||||||
|
|
||||||
|
|
||||||
|
class RosterSessionRead(BaseModel):
|
||||||
|
service_id: str
|
||||||
|
service_name: str
|
||||||
|
scheduled_at: str
|
||||||
|
max_capacity: int
|
||||||
|
occupied_count: int
|
||||||
|
attended_count: int
|
||||||
|
attendees: list[RosterAttendeeRead]
|
||||||
|
|
||||||
|
|
||||||
|
class QuickCheckinRequest(BaseModel):
|
||||||
|
# Mode 1: existing booking check-in
|
||||||
|
booking_id: str | None = None
|
||||||
|
|
||||||
|
# Mode 2: walk-in check-in
|
||||||
|
service_id: str | None = None
|
||||||
|
scheduled_at: str | None = None
|
||||||
|
client_name: str | None = None
|
||||||
|
client_phone: str | None = None
|
||||||
|
client_email: str | None = None
|
||||||
|
|
||||||
|
paid_cash: bool = False
|
||||||
|
notes: str | None = None
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def validate_exactly_one_mode(self) -> QuickCheckinRequest:
|
||||||
|
has_booking_id = bool(self.booking_id)
|
||||||
|
has_any_walk_in = any(
|
||||||
|
[self.service_id, self.scheduled_at, self.client_name, self.client_phone]
|
||||||
|
)
|
||||||
|
is_complete_walk_in = bool(
|
||||||
|
self.service_id and self.scheduled_at and self.client_name and self.client_phone
|
||||||
|
)
|
||||||
|
|
||||||
|
if has_booking_id:
|
||||||
|
if has_any_walk_in:
|
||||||
|
raise ValueError("Cannot combine 'booking_id' with walk-in fields.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
if is_complete_walk_in:
|
||||||
|
return self
|
||||||
|
|
||||||
|
raise ValueError(
|
||||||
|
"Must provide either 'booking_id' for an existing booking, "
|
||||||
|
"or ('service_id', 'scheduled_at', 'client_name', 'client_phone') for a walk-in."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class QuickCheckinResponse(BaseModel):
|
||||||
|
walk_in: bool
|
||||||
|
attendee: RosterAttendeeRead
|
||||||
|
payment_id: str | None = None
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, date, datetime, time, timedelta
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BlockedInterval:
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AvailableSlot:
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BusinessHours:
|
||||||
|
timezone: ZoneInfo
|
||||||
|
open_time: time
|
||||||
|
close_time: time
|
||||||
|
working_weekdays: frozenset[int] # 0=Monday .. 6=Sunday
|
||||||
|
slot_step_minutes: int
|
||||||
|
|
||||||
|
|
||||||
|
def blocked_interval(
|
||||||
|
start: datetime, duration_minutes: int, buffer_minutes: int
|
||||||
|
) -> BlockedInterval:
|
||||||
|
"""Build a blocked interval including mandatory post-session buffer."""
|
||||||
|
return BlockedInterval(start, start + timedelta(minutes=duration_minutes + buffer_minutes))
|
||||||
|
|
||||||
|
|
||||||
|
def intervals_overlap(a: BlockedInterval, b: BlockedInterval) -> bool:
|
||||||
|
"""
|
||||||
|
Two half-open intervals [a.start, a.end) and [b.start, b.end) overlap
|
||||||
|
if max(a.start, b.start) < min(a.end, b.end).
|
||||||
|
Touching at the exact boundary (a.end == b.start) is NOT an overlap.
|
||||||
|
"""
|
||||||
|
return max(a.start, b.start) < min(a.end, b.end)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_available_slots(
|
||||||
|
*,
|
||||||
|
date_from: date,
|
||||||
|
date_to: date,
|
||||||
|
duration_minutes: int,
|
||||||
|
buffer_minutes: int,
|
||||||
|
existing: list[BlockedInterval],
|
||||||
|
hours: BusinessHours,
|
||||||
|
now: datetime | None = None,
|
||||||
|
) -> list[AvailableSlot]:
|
||||||
|
"""
|
||||||
|
Compute collision-free individual appointment slots across [date_from, date_to] (inclusive).
|
||||||
|
Candidate slots are generated in the business timezone from open_time to close_time.
|
||||||
|
A candidate slot is rejected if:
|
||||||
|
1. Its actual session end (start + duration) exceeds close_time.
|
||||||
|
2. Its start is at or before `now` (UTC).
|
||||||
|
3. Its blocked interval (start + duration + buffer) overlaps with any existing blocked interval.
|
||||||
|
"""
|
||||||
|
if date_to < date_from:
|
||||||
|
raise ValueError("date_to cannot precede date_from")
|
||||||
|
|
||||||
|
ref_now = now or datetime.now(UTC)
|
||||||
|
slots: list[AvailableSlot] = []
|
||||||
|
step = timedelta(minutes=hours.slot_step_minutes)
|
||||||
|
session_delta = timedelta(minutes=duration_minutes)
|
||||||
|
|
||||||
|
current_date = date_from
|
||||||
|
while current_date <= date_to:
|
||||||
|
if current_date.weekday() in hours.working_weekdays:
|
||||||
|
day_open = datetime.combine(current_date, hours.open_time, tzinfo=hours.timezone)
|
||||||
|
day_close = datetime.combine(current_date, hours.close_time, tzinfo=hours.timezone)
|
||||||
|
|
||||||
|
candidate_start = day_open
|
||||||
|
while candidate_start < day_close:
|
||||||
|
session_end = candidate_start + session_delta
|
||||||
|
if session_end > day_close:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Verify candidate is strictly in the future compared to ref_now
|
||||||
|
candidate_start_utc = candidate_start.astimezone(UTC)
|
||||||
|
if candidate_start_utc > ref_now:
|
||||||
|
candidate_blocked = blocked_interval(
|
||||||
|
candidate_start, duration_minutes, buffer_minutes
|
||||||
|
)
|
||||||
|
# Check collision against existing blocked intervals
|
||||||
|
has_collision = False
|
||||||
|
for b in existing:
|
||||||
|
# Normalize timezones for safety when comparing
|
||||||
|
b_start_norm = b.start.astimezone(hours.timezone)
|
||||||
|
b_end_norm = b.end.astimezone(hours.timezone)
|
||||||
|
if intervals_overlap(
|
||||||
|
candidate_blocked, BlockedInterval(b_start_norm, b_end_norm)
|
||||||
|
):
|
||||||
|
has_collision = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not has_collision:
|
||||||
|
slots.append(AvailableSlot(start=candidate_start, end=session_end))
|
||||||
|
|
||||||
|
candidate_start += step
|
||||||
|
|
||||||
|
current_date += timedelta(days=1)
|
||||||
|
|
||||||
|
return slots
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
import urllib.parse
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.schemas.booking import BookingRead
|
||||||
|
from app.services.timestamps import parse_iso_datetime
|
||||||
|
|
||||||
|
|
||||||
|
def check_slot_collision(
|
||||||
|
new_start: datetime,
|
||||||
|
new_duration: int,
|
||||||
|
new_buffer: int,
|
||||||
|
existing_bookings: list[dict[str, Any]],
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Returns True if the requested slot interval (including mandatory 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)
|
||||||
|
for b in existing_bookings:
|
||||||
|
exist_start = parse_iso_datetime(str(b["scheduled_at"]))
|
||||||
|
exist_duration = int(b.get("duration_minutes", 60))
|
||||||
|
exist_buffer = int(b.get("buffer_minutes", 0))
|
||||||
|
exist_blocked_end = exist_start + timedelta(minutes=exist_duration + exist_buffer)
|
||||||
|
|
||||||
|
if new_start < exist_blocked_end and exist_start < new_blocked_end:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_hours_until(scheduled_at: datetime | str, now: datetime | None = None) -> float:
|
||||||
|
"""Calculate hours remaining until scheduled_at from now (UTC)."""
|
||||||
|
ref_now = now or datetime.now(UTC)
|
||||||
|
if isinstance(scheduled_at, str):
|
||||||
|
sched_dt = parse_iso_datetime(scheduled_at)
|
||||||
|
else:
|
||||||
|
sched_dt = (
|
||||||
|
scheduled_at if scheduled_at.tzinfo is not None else scheduled_at.replace(tzinfo=UTC)
|
||||||
|
)
|
||||||
|
return round((sched_dt - ref_now).total_seconds() / 3600.0, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_payment_followup(
|
||||||
|
*,
|
||||||
|
booking_status: str,
|
||||||
|
payment_status: str,
|
||||||
|
payment_arrangement: str,
|
||||||
|
hours_until: float,
|
||||||
|
threshold_hours: int = 48,
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Evaluate if an appointment requires payment follow-up:
|
||||||
|
1. payment_status must be 'AWAITING_ACKNOWLEDGMENT'
|
||||||
|
2. AND either:
|
||||||
|
a) booking_status is 'RESERVED' and hours_until <= threshold_hours (default 48h)
|
||||||
|
b) payment_arrangement is 'DELAYED_ALLOWED' and booking_status is 'RESERVED' or 'COMPLETED'
|
||||||
|
"""
|
||||||
|
if payment_status != "AWAITING_ACKNOWLEDGMENT":
|
||||||
|
return False
|
||||||
|
|
||||||
|
is_imminent_reserved = (booking_status == "RESERVED") and (hours_until <= threshold_hours)
|
||||||
|
is_delayed_allowed_active = (payment_arrangement == "DELAYED_ALLOWED") and (
|
||||||
|
booking_status in ("RESERVED", "COMPLETED")
|
||||||
|
)
|
||||||
|
|
||||||
|
return is_imminent_reserved or is_delayed_allowed_active
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
package_info: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Generate a pre-filled WhatsApp link for the client to message Armonía del Ser."""
|
||||||
|
if package_info:
|
||||||
|
msg = (
|
||||||
|
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 {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"
|
||||||
|
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}"
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
)
|
||||||
|
hours_until = calculate_hours_until(str(row["scheduled_at"]), ref_now)
|
||||||
|
needs_followup = evaluate_payment_followup(
|
||||||
|
booking_status=str(row["booking_status"]),
|
||||||
|
payment_status=str(row["payment_status"]),
|
||||||
|
payment_arrangement=str(row["payment_arrangement"]),
|
||||||
|
hours_until=hours_until,
|
||||||
|
threshold_hours=threshold,
|
||||||
|
)
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
@@ -3,3 +3,11 @@ from datetime import UTC, datetime
|
|||||||
|
|
||||||
def utc_now_iso() -> str:
|
def utc_now_iso() -> str:
|
||||||
return datetime.now(UTC).isoformat()
|
return datetime.now(UTC).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_iso_datetime(dt_str: str) -> datetime:
|
||||||
|
"""Parse an ISO 8601 string, normalizing naive datetimes to UTC."""
|
||||||
|
dt = datetime.fromisoformat(dt_str)
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=UTC)
|
||||||
|
return dt
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# ADR 0006: Mutation Testing & Boundary Hardening for Core Business Logic
|
||||||
|
|
||||||
|
## Status
|
||||||
|
Accepted (2026-10-19)
|
||||||
|
|
||||||
|
## Context
|
||||||
|
Standard line and branch coverage metrics only verify that code was executed during a test run; they do not verify that the test assertions are strict enough to detect subtle defects.
|
||||||
|
|
||||||
|
In `armonia-api`, two domain invariants carry direct business risks if mutated:
|
||||||
|
1. **Mandatory Post-Session Buffer Overlap Math**:
|
||||||
|
- An off-by-one operator error ($<$ vs $\le$) or sign change (`duration - buffer` instead of `duration + buffer`) could either allow double-booking a slot during Jasmin's decompression window or falsely reject a legitimate back-to-back appointment.
|
||||||
|
2. **48-Hour Payment Follow-Up Cutoff**:
|
||||||
|
- A boundary condition mutation ($<$ vs $\le$) on `hours_until <= threshold` could exclude consultantes scheduled at the exact threshold boundary, preventing Jasmin's assistant from sending timely WhatsApp follow-ups and allowing ghosted reservations to block inventory.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
1. **Decouple Pure Domain Logic into `app/services/`**:
|
||||||
|
- Business arithmetic (buffer collision detection, 48-hour follow-up evaluation, and folio generation) is decoupled from FastAPI route handlers into `app/services/bookings.py` and `app/services/timestamps.py`.
|
||||||
|
2. **Adopt `mutmut` as Quality Audit Gate**:
|
||||||
|
- Mutation testing is configured in `pyproject.toml` (`[tool.mutmut]`), targeting `app/services/`.
|
||||||
|
- The test selection for mutation workers is restricted to isolated unit tests (`pytest_add_cli_args_test_selection = ["tests/unit/services/"]`) to avoid SQLite database lock contention (`SQLITE_BUSY`) during parallel test execution.
|
||||||
|
- All surviving mutants on boundary arithmetic ($<$, $\le$, `+`, `-`, and threshold fallbacks) must be eliminated prior to merging PRs altering `app/services/`.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
### Positive
|
||||||
|
- **Guaranteed Boundary Invariants**: 100% kill rate achieved on domain functions (`check_slot_collision`, `evaluate_payment_followup`, `calculate_hours_until`, `parse_iso_datetime`, `compute_calendar_prefix`).
|
||||||
|
- **Zero Tautological Tests**: Unit tests assert exact boundary values (`48.0h`, `48.01h`, adjacent buffer ends) rather than loose status checks.
|
||||||
|
- **Fast Execution**: Pure unit tests execute in under 0.1 seconds, enabling `mutmut` to evaluate 250+ mutants in seconds.
|
||||||
|
|
||||||
|
### Negative / Trade-offs
|
||||||
|
- Developers modifying domain logic in `app/services/` must run `mutmut` alongside standard `pytest` to prevent mutation leaks.
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
# Raw Discovery Interview: Jazmín's Assistant & Client Feedback
|
|
||||||
|
|
||||||
**Date Recorded:** 2026-10-18
|
|
||||||
**Source:** Direct interview feedback from Jazmín's assistant and long-term client (2 years of consultation history)
|
|
||||||
**Business:** Armonía del Ser (Mexico)
|
|
||||||
**Purpose:** Unvarnished primary operational data capturing how bookings, payments, schedules, and group courses actually operate in daily practice.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Verbatim Interview Transcripts
|
|
||||||
|
|
||||||
### 1. Inbound Channels & Community Presence
|
|
||||||
> *"Llegan a Whatssap. Mensaje directo aunque no se si haya gente que intente llamarla directamente, como todo imagino que si. También ella lleva 20 años en la ciudad pequeña donde vive así que allá la recomiendan voz a voz. Se planea que lo q llegue por redes se redireccione a Whatssap."*
|
|
||||||
|
|
||||||
**Key Takeaways:**
|
|
||||||
- Primary conversational funnel is WhatsApp (direct messages and voice calls).
|
|
||||||
- Strong local word-of-mouth reputation (20 years operating in the local community).
|
|
||||||
- Social media strategy relies on redirecting external traffic directly into WhatsApp.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 2. Group vs. 1-on-1 Registration Operations
|
|
||||||
> *"¿Cómo así que como manejas la diferencia? ¿A q hace referencia? ¿Al calendario de ella? Se que la gente se inscribe directamente en persona o por Whatssap así que eso sería algo q yo tambn entraría a hacer."*
|
|
||||||
|
|
||||||
**Key Takeaways:**
|
|
||||||
- In-person and WhatsApp registrations are the primary entry points.
|
|
||||||
- Collaborative management: The assistant also needs access to register participants on Jazmín's behalf.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 3. Payment Models, Packages, & Balances
|
|
||||||
> *"En mi experiencia como cliente, antes de la sesión. Y como yo estoy afuera de México por paquete pagaba por adelantado. A veces al finalizar la sesión nos poníamos al día de en q #de sesión íbamos. Ejemplo 8 de 10.*
|
|
||||||
>
|
|
||||||
> *Lo del saldo es complejo porque hay cosas q se dicen en persona entonces ahí es donde ella sesión está haciendo bola. Y si básicamente memoria, Whatssap, o incluso charlarlo con el cliente que pues ya lot depende de la sinceridad del cliente. Ella ha sido algo desordenada con eso.*
|
|
||||||
>
|
|
||||||
> *Por ej empezamos un curso de abundancia y prosperidad (que eres bienvenido haha es de aporte simbólico de $50 Méx por sesión) y anotó el listado de participantes y quienes la pagaron en una hoja y me envió la foto."*
|
|
||||||
|
|
||||||
**Key Takeaways:**
|
|
||||||
- **Package model**: Consultations are frequently bought as multi-session packages (e.g. 10 sessions) paid upfront.
|
|
||||||
- **Session counter ambiguity**: Tracking session numbers (e.g. "sesión 8 de 10") is currently manual, discussed verbally at the end of sessions.
|
|
||||||
- **Unsettled balances & social friction**: In-person agreements cause confusion ("hacerse bolas"). Relies on memory, WhatsApp chat history, and the client's honesty.
|
|
||||||
- **Group workshop lists**: For low-cost workshops (*Curso de Abundancia y Prosperidad*, $50 MXN/session), Jazmín writes attendee and payment lists by hand on a paper sheet and photographs it. Needs a digital 1-tap equivalent.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 4. Group Session Capacities
|
|
||||||
> *"A las grupales aprox 10. Aún el dato no lo tengo pero si quiero preguntarles de hecho está re bueno para mi saber q preguntas exactas formularle."*
|
|
||||||
|
|
||||||
**Key Takeaways:**
|
|
||||||
- Typical group session attendance is approximately 10 people.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 5. Scheduling Friction, Delays, & Calendar Confusion
|
|
||||||
> *"Yo diría q pagos olvidados y lo de la agenda full, casi siempre llegaba tarde a mis consultas, así fuese 10 min a 30-35min porque estaba finalizando otra consulta o porque otro paciente se complicaba en la consulta anterior, eso nunca me gustó, ahora al menos en la noche que solo estoy en constaleciones habmejorado su puntualidad… o me pasó mientras fue mi consultante dos años que un par de veces de repente ella creía q la cita era a otra hr y yo ahí esperando o se le había olvidado agendarla."*
|
|
||||||
|
|
||||||
**Key Takeaways:**
|
|
||||||
- **Tardiness Root Cause**: Chronic 10-35 minute delays caused by consultations running overtime with emotional/complex patients, compounded by back-to-back scheduling with **zero buffer time**.
|
|
||||||
- **Forgotten & Colliding Appointments**: Jazmín sometimes misremembers appointment times or forgets to add them to her calendar altogether, leaving clients waiting.
|
|
||||||
- **Urgent Need**: Mandatory automated buffer times between sessions and automated Google Calendar two-way synchronization with push reminders.
|
|
||||||
@@ -17,6 +17,7 @@ dependencies = [
|
|||||||
"time-machine>=3.5.1",
|
"time-machine>=3.5.1",
|
||||||
"uvicorn[standard]>=0.30.0",
|
"uvicorn[standard]>=0.30.0",
|
||||||
"httpx2>=2.14.0",
|
"httpx2>=2.14.0",
|
||||||
|
"tzdata>=2026.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
@@ -45,3 +46,8 @@ asyncio_mode = "auto"
|
|||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
pythonpath = ["."]
|
pythonpath = ["."]
|
||||||
|
|
||||||
|
[tool.mutmut]
|
||||||
|
source_paths = ["app/services/"]
|
||||||
|
also_copy = ["app"]
|
||||||
|
pytest_add_cli_args_test_selection = ["tests/unit/services/"]
|
||||||
|
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
# Test Suite Architecture & Mutation Testing Guide (`armonia-api`)
|
||||||
|
|
||||||
|
This directory contains the automated test suite for `armonia-api`, structured into isolated unit tests and end-to-end integration workflows.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Test Suite Taxonomy
|
||||||
|
|
||||||
|
```
|
||||||
|
tests/
|
||||||
|
├── conftest.py # Session fixtures, SQLite lifecycle, TestClient
|
||||||
|
├── test_auth_and_workflows.py # Integration: OAuth allowlist, 48h queue, delayed pay
|
||||||
|
├── test_bookings.py # Integration: Booking creation, payment ack, buffers
|
||||||
|
├── test_health.py # Integration: Health check probe
|
||||||
|
├── test_services.py # Integration: Seeded service catalog endpoints
|
||||||
|
└── unit/ # Fast, isolated unit tests (< 0.5s total)
|
||||||
|
├── models/ # SQLModel schema validation and defaults
|
||||||
|
│ ├── test_admin_model.py
|
||||||
|
│ ├── test_booking_model.py
|
||||||
|
│ ├── test_client_model.py
|
||||||
|
│ ├── test_package_model.py
|
||||||
|
│ ├── test_payment_model.py
|
||||||
|
│ └── test_service_model.py
|
||||||
|
├── services/ # Consumer-agnostic domain logic invariants
|
||||||
|
│ ├── test_booking_service.py # Buffer collision arithmetic & 48h follow-up rules
|
||||||
|
│ ├── test_calendar.py # Calendar prefix computation & unconfigured fallback
|
||||||
|
│ └── test_timestamps.py # UTC ISO serialization & timezone normalization
|
||||||
|
└── test_database.py # SQLite table reflection & schema parity
|
||||||
|
```
|
||||||
|
|
||||||
|
### Unit Tests (`tests/unit/`)
|
||||||
|
- **Execution Speed:** In-memory, zero network I/O, zero database concurrency contention.
|
||||||
|
- **Coverage:** Pure business invariants—buffer overlap math, 48-hour follow-up state machines, folio generation, timestamp parsing, and model field validations.
|
||||||
|
|
||||||
|
### Integration Tests (`tests/test_*.py`)
|
||||||
|
- **Execution:** Exercises FastAPI routes against an isolated local SQLite file (`test_armonia.db`).
|
||||||
|
- **External I/O:** Google Calendar and OAuth network side-effects are mocked via `pytest-mock` (`mocker`) and monkeypatched configuration.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Running Verification Gates
|
||||||
|
|
||||||
|
Ensure you are inside the Nix `devShell` (`direnv` or `nix develop`).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Format check
|
||||||
|
uv run ruff format --check .
|
||||||
|
|
||||||
|
# 2. Lint check
|
||||||
|
uv run ruff check .
|
||||||
|
|
||||||
|
# 3. Static type analysis
|
||||||
|
uv run pyright
|
||||||
|
|
||||||
|
# 4. Pytest test suite
|
||||||
|
uv run pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Mutation Testing with `mutmut`
|
||||||
|
|
||||||
|
Mutation testing systematically inserts synthetic syntactic faults (e.g., swapping `<` for `<=`, flipping boolean conditions, changing buffer addition `+` to `-`, or altering numeric constants) to verify that unit tests fail when code semantics change.
|
||||||
|
|
||||||
|
### Configuration (`pyproject.toml`)
|
||||||
|
Mutmut is configured under `[tool.mutmut]`:
|
||||||
|
```toml
|
||||||
|
[tool.mutmut]
|
||||||
|
source_paths = ["app/services/"]
|
||||||
|
also_copy = ["app"]
|
||||||
|
pytest_add_cli_args_test_selection = ["tests/unit/services/"]
|
||||||
|
```
|
||||||
|
- **`source_paths`**: Targets extracted domain services (`app/services/`).
|
||||||
|
- **`also_copy = ["app"]`**: Ensures `app.core`, `app.models`, and schema modules are copied into the mutant runtime workspace to prevent `ModuleNotFoundError`.
|
||||||
|
- **`pytest_add_cli_args_test_selection`**: Executes lightning-fast unit tests (`tests/unit/services/`) for each mutant, preventing SQLite file lock contention (`SQLITE_BUSY`) during parallel worker execution.
|
||||||
|
|
||||||
|
### Mutation Execution Workflow
|
||||||
|
```bash
|
||||||
|
# Clean previous mutant artifacts and run mutation audit
|
||||||
|
rm -rf mutants && uv run mutmut run
|
||||||
|
|
||||||
|
# Check surviving mutants (should output nothing when 100% killed)
|
||||||
|
uv run mutmut results
|
||||||
|
|
||||||
|
# Inspect a specific mutant diff
|
||||||
|
uv run mutmut show <mutant_id>
|
||||||
|
|
||||||
|
# Export CI/CD machine-readable statistics
|
||||||
|
uv run mutmut export-cicd-stats
|
||||||
|
```
|
||||||
|
|
||||||
|
### Hardened Domain Invariants
|
||||||
|
The unit tests in `tests/unit/services/test_booking_service.py` specifically enforce:
|
||||||
|
1. **Buffer Collision Boundaries ($<$ vs $\le$):**
|
||||||
|
- Adjacent slots (`new_start == exist_blocked_end` or `new_blocked_end == exist_start`) return `False` (no collision). Mutants replacing `<` with `<=` are caught and killed.
|
||||||
|
- Buffer encroachment: If the session ended but its post-session buffer overlaps another reservation, `check_slot_collision` returns `True`. Mutants altering `duration + buffer` to `duration - buffer` are killed.
|
||||||
|
2. **48-Hour Follow-Up Cutoff:**
|
||||||
|
- Exact boundary: A reservation scheduled at exactly `48.0` hours from `now` with `AWAITING_ACKNOWLEDGMENT` evaluates to `True` (`needs_followup`). Mutants replacing `<=` with `<` fail this assertion and are killed.
|
||||||
|
- Non-eligible appointments (already `ACKNOWLEDGED`, `CANCELLED`, or beyond 48 hours) evaluate to `False`.
|
||||||
|
3. **Delayed Payment Exceptions (`DELAYED_ALLOWED`):**
|
||||||
|
- Active or completed sessions with delayed payment authorization remain flagged for follow-up regardless of elapsed time (`hours_until`).
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
from app.core.config import AuthProvider, settings
|
||||||
|
from app.db.database import get_engine
|
||||||
|
from app.models.admin import AdminAllowlist
|
||||||
|
|
||||||
|
OWNER_EMAIL = "jasmin@armoniadelser.mx"
|
||||||
|
|
||||||
|
|
||||||
|
def _proxy_headers(
|
||||||
|
email: str | None = "operadora@homelab.lan",
|
||||||
|
groups: str | None = "users,armonia-assistant",
|
||||||
|
name: str | None = "Operadora Homelab",
|
||||||
|
*,
|
||||||
|
user: str | None = None,
|
||||||
|
) -> dict[str, str]:
|
||||||
|
headers: dict[str, str] = {}
|
||||||
|
if email is not None:
|
||||||
|
headers["Remote-Email"] = email
|
||||||
|
if user is not None:
|
||||||
|
headers["Remote-User"] = user
|
||||||
|
if groups is not None:
|
||||||
|
headers["Remote-Groups"] = groups
|
||||||
|
if name is not None:
|
||||||
|
headers["Remote-Name"] = name
|
||||||
|
return headers
|
||||||
|
|
||||||
|
|
||||||
|
def _bearer(email: str = OWNER_EMAIL) -> dict[str, str]:
|
||||||
|
return {"Authorization": f"Bearer {create_session_token(email)}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _dev_key(email: str | None = OWNER_EMAIL, key: str | None = None) -> dict[str, str]:
|
||||||
|
headers = {"X-Admin-Key": key if key is not None else settings.admin_api_key}
|
||||||
|
if email is not None:
|
||||||
|
headers["X-Admin-Email"] = email
|
||||||
|
return headers
|
||||||
|
|
||||||
|
|
||||||
|
def _allowlist_row(email: str) -> AdminAllowlist | None:
|
||||||
|
with Session(get_engine()) as session:
|
||||||
|
return session.exec(select(AdminAllowlist).where(AdminAllowlist.email == email)).first()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def proxy_mode(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "auth_provider", AuthProvider.PROXY_HEADERS)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def production(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "environment", "production")
|
||||||
|
|
||||||
|
|
||||||
|
# --- proxy_headers (Authelia + LLDAP) -------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_build_principal_from_authelia_headers(client, proxy_mode):
|
||||||
|
res = client.get("/auth/me", headers=_proxy_headers())
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["email"] == "operadora@homelab.lan"
|
||||||
|
assert body["full_name"] == "Operadora Homelab"
|
||||||
|
assert body["role"] == "ASSISTANT"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_normalize_email_and_fall_back_to_remote_user(client, proxy_mode):
|
||||||
|
res = client.get(
|
||||||
|
"/auth/me",
|
||||||
|
headers=_proxy_headers(email=None, user=" Owner@Homelab.LAN ", groups="armonia-owner"),
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["email"] == "owner@homelab.lan"
|
||||||
|
assert res.json()["role"] == "OWNER"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_fall_back_to_email_when_remote_name_missing(client, proxy_mode):
|
||||||
|
res = client.get("/auth/me", headers=_proxy_headers(name=None))
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["full_name"] == "operadora@homelab.lan"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_without_identity_are_unauthenticated(client, proxy_mode):
|
||||||
|
res = client.get("/auth/me", headers=_proxy_headers(email=None, user=None))
|
||||||
|
assert res.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_without_armonia_group_are_forbidden(client, proxy_mode):
|
||||||
|
res = client.get("/auth/me", headers=_proxy_headers(groups="users,family"))
|
||||||
|
assert res.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_reads_never_touch_the_allowlist(client, proxy_mode):
|
||||||
|
email = "lector.solo@homelab.lan"
|
||||||
|
res = client.get("/bookings/follow-up-queue", headers=_proxy_headers(email=email))
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert _allowlist_row(email) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_headers_mirror_principal_into_allowlist_on_first_write(client, proxy_mode):
|
||||||
|
email = "escritora@homelab.lan"
|
||||||
|
assert _allowlist_row(email) is None
|
||||||
|
|
||||||
|
res = client.post(
|
||||||
|
"/auth/allowlist",
|
||||||
|
headers=_proxy_headers(email=email, groups="armonia-owner", name="Escritora"),
|
||||||
|
json={"email": "nueva.asistente@armoniadelser.mx", "full_name": "Nueva Asistente"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201
|
||||||
|
|
||||||
|
mirrored = _allowlist_row(email)
|
||||||
|
assert mirrored is not None
|
||||||
|
assert mirrored.role == "OWNER"
|
||||||
|
assert mirrored.full_name == "Escritora"
|
||||||
|
assert mirrored.last_login_at is not None
|
||||||
|
|
||||||
|
# Audit trail references the mirrored actor (FK target exists)
|
||||||
|
audit = client.get(
|
||||||
|
"/auth/audit-log?entity_id=nueva.asistente@armoniadelser.mx",
|
||||||
|
headers=_proxy_headers(email=email, groups="armonia-owner"),
|
||||||
|
).json()
|
||||||
|
assert audit[0]["admin_email"] == email
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_mirror_tracks_role_changes_from_lldap(client, proxy_mode):
|
||||||
|
email = "promovida@homelab.lan"
|
||||||
|
for groups in ("armonia-assistant", "armonia-admin"):
|
||||||
|
res = client.patch(
|
||||||
|
f"/auth/allowlist/{OWNER_EMAIL}",
|
||||||
|
headers=_proxy_headers(email=email, groups=groups),
|
||||||
|
json={},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
mirrored = _allowlist_row(email)
|
||||||
|
assert mirrored is not None
|
||||||
|
assert mirrored.role == "ADMIN"
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_mode_ignores_bearer_tokens_in_production(client, proxy_mode, production):
|
||||||
|
assert client.get("/auth/me", headers=_bearer()).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_mode_rejects_dev_key_in_production(client, proxy_mode, production):
|
||||||
|
assert client.get("/auth/me", headers=_dev_key()).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_mode_allows_dev_key_fallback_outside_production(client, proxy_mode):
|
||||||
|
res = client.get("/auth/me", headers=_dev_key())
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["email"] == OWNER_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
# --- google_oauth -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_google_oauth_ignores_spoofed_proxy_headers(client):
|
||||||
|
assert settings.auth_provider == AuthProvider.GOOGLE_OAUTH
|
||||||
|
res = client.get("/auth/me", headers=_proxy_headers(groups="armonia-owner"))
|
||||||
|
assert res.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_google_oauth_rejects_invalid_session_token(client):
|
||||||
|
res = client.get("/auth/me", headers={"Authorization": "Bearer not.a-valid-token"})
|
||||||
|
assert res.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_google_oauth_accepts_session_cookie(client):
|
||||||
|
client.cookies.set("armonia_session", create_session_token(OWNER_EMAIL))
|
||||||
|
try:
|
||||||
|
res = client.get("/auth/me")
|
||||||
|
finally:
|
||||||
|
client.cookies.clear()
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["role"] == "OWNER"
|
||||||
|
|
||||||
|
|
||||||
|
def test_google_oauth_rejects_dev_key_in_production(client, production):
|
||||||
|
assert client.get("/auth/me", headers=_dev_key()).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_google_oauth_session_still_works_in_production(client, production):
|
||||||
|
assert client.get("/auth/me", headers=_bearer()).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
# --- dev_key ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def dev_key_mode(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "auth_provider", AuthProvider.DEV_KEY)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_key_resolves_allowlisted_email(client, dev_key_mode):
|
||||||
|
res = client.get("/auth/me", headers=_dev_key("asistente@armoniadelser.mx"))
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["role"] == "ASSISTANT"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_key_without_email_uses_first_bootstrap_admin(client, dev_key_mode):
|
||||||
|
res = client.get("/auth/me", headers=_dev_key(email=None))
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["email"] == settings.admin_bootstrap_emails[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_key_with_wrong_key_is_unauthenticated(client, dev_key_mode):
|
||||||
|
assert client.get("/auth/me", headers=_dev_key(key="wrong-key")).status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_key_with_non_allowlisted_email_is_forbidden(client, dev_key_mode):
|
||||||
|
assert client.get("/auth/me", headers=_dev_key("intruder@example.com")).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_key_mode_ignores_bearer_tokens(client, dev_key_mode):
|
||||||
|
assert client.get("/auth/me", headers=_bearer()).status_code == 401
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
DAY = "2027-03-01" # Monday, America/Mexico_City (UTC-6)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def short_business_day(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "business_timezone", "America/Mexico_City")
|
||||||
|
monkeypatch.setattr(settings, "availability_open_time", "09:00")
|
||||||
|
monkeypatch.setattr(settings, "availability_close_time", "13:00")
|
||||||
|
monkeypatch.setattr(settings, "availability_slot_step_minutes", 30)
|
||||||
|
monkeypatch.setattr(settings, "availability_working_weekdays", [0, 1, 2, 3, 4])
|
||||||
|
|
||||||
|
|
||||||
|
def _individual_service(client) -> dict:
|
||||||
|
return client.get("/services/atencion-psicologica-individual").json()
|
||||||
|
|
||||||
|
|
||||||
|
def _book(client, service_id: str, scheduled_at: str, phone: str):
|
||||||
|
return client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": service_id,
|
||||||
|
"client_name": "Cliente Disponibilidad",
|
||||||
|
"client_phone": phone,
|
||||||
|
"scheduled_at": scheduled_at,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_starts(body: dict) -> list[str]:
|
||||||
|
return [slot["start"] for day in body["days"] for slot in day["slots"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_excludes_slots_colliding_with_reserved_buffer(client, short_business_day):
|
||||||
|
svc = _individual_service(client)
|
||||||
|
assert _book(client, svc["id"], f"{DAY}T10:00:00-06:00", "7750001001").status_code == 201
|
||||||
|
|
||||||
|
res = client.get(
|
||||||
|
"/availability", params={"service_id": svc["id"], "date_from": DAY, "date_to": DAY}
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["service_id"] == svc["id"]
|
||||||
|
assert body["duration_minutes"] == 60
|
||||||
|
assert body["buffer_minutes"] == 15
|
||||||
|
assert body["timezone"] == "America/Mexico_City"
|
||||||
|
assert _slot_starts(body) == [f"{DAY}T11:30:00-06:00", f"{DAY}T12:00:00-06:00"]
|
||||||
|
assert body["days"][0]["slots"][0]["end"] == f"{DAY}T12:30:00-06:00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_released_bookings_free_their_slots(client, short_business_day):
|
||||||
|
day = "2027-03-02"
|
||||||
|
svc = _individual_service(client)
|
||||||
|
booking = _book(client, svc["id"], f"{day}T09:00:00-06:00", "7750001002").json()
|
||||||
|
params = {"service_id": svc["id"], "date_from": day, "date_to": day}
|
||||||
|
assert f"{day}T09:00:00-06:00" not in _slot_starts(
|
||||||
|
client.get("/availability", params=params).json()
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = {"Authorization": f"Bearer {create_session_token('jasmin@armoniadelser.mx')}"}
|
||||||
|
rel = client.post(f"/bookings/{booking['id']}/release", headers=headers, json={})
|
||||||
|
assert rel.status_code == 200
|
||||||
|
assert f"{day}T09:00:00-06:00" in _slot_starts(
|
||||||
|
client.get("/availability", params=params).json()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_offered_slot_is_accepted_by_booking_engine(client, short_business_day):
|
||||||
|
day = "2027-03-03"
|
||||||
|
svc = _individual_service(client)
|
||||||
|
params = {"service_id": svc["id"], "date_from": day, "date_to": day}
|
||||||
|
first = _slot_starts(client.get("/availability", params=params).json())[0]
|
||||||
|
assert _book(client, svc["id"], first, "7750001003").status_code == 201
|
||||||
|
|
||||||
|
# Next 30-minute step now collides (60 + 15 buffer) and must disappear
|
||||||
|
after = _slot_starts(client.get("/availability", params=params).json())
|
||||||
|
assert first not in after
|
||||||
|
assert f"{day}T09:30:00-06:00" not in after
|
||||||
|
assert f"{day}T10:00:00-06:00" not in after
|
||||||
|
assert after[0] == f"{day}T10:30:00-06:00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_groups_slots_by_local_day(client, short_business_day):
|
||||||
|
svc = _individual_service(client)
|
||||||
|
res = client.get(
|
||||||
|
"/availability",
|
||||||
|
params={"service_id": svc["id"], "date_from": "2027-03-05", "date_to": "2027-03-08"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
# Fri 5 and Mon 8 are working days; the weekend is omitted
|
||||||
|
assert [d["date"] for d in res.json()["days"]] == ["2027-03-05", "2027-03-08"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_rejects_group_services(client):
|
||||||
|
svc = client.get("/services/circulo-cacao-presencial").json()
|
||||||
|
res = client.get(
|
||||||
|
"/availability", params={"service_id": svc["id"], "date_from": DAY, "date_to": DAY}
|
||||||
|
)
|
||||||
|
assert res.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_unknown_service_is_404(client):
|
||||||
|
res = client.get(
|
||||||
|
"/availability", params={"service_id": "nope", "date_from": DAY, "date_to": DAY}
|
||||||
|
)
|
||||||
|
assert res.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_rejects_inverted_range(client):
|
||||||
|
svc = _individual_service(client)
|
||||||
|
res = client.get(
|
||||||
|
"/availability",
|
||||||
|
params={"service_id": svc["id"], "date_from": "2027-03-02", "date_to": "2027-03-01"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_rejects_range_over_limit(client, monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "availability_max_range_days", 7)
|
||||||
|
svc = _individual_service(client)
|
||||||
|
res = client.get(
|
||||||
|
"/availability",
|
||||||
|
params={"service_id": svc["id"], "date_from": "2027-03-01", "date_to": "2027-03-08"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 422
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_headers(email: str = "jasmin@armoniadelser.mx") -> dict[str, str]:
|
||||||
|
token = create_session_token(email)
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_reschedule_reserved_booking_success(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# 1. Create booking
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Gabriel Sosa",
|
||||||
|
"client_phone": "+52 55 1234 9999",
|
||||||
|
"scheduled_at": "2026-11-10T10:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b_res.status_code == 201
|
||||||
|
booking = b_res.json()
|
||||||
|
booking_id = booking["id"]
|
||||||
|
|
||||||
|
# 2. Reschedule to new slot
|
||||||
|
new_time = "2026-11-12T16:00:00Z"
|
||||||
|
resched_res = client.post(
|
||||||
|
f"/bookings/{booking_id}/reschedule",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"new_scheduled_at": new_time,
|
||||||
|
"notes": "Cliente solicitó cambio de fecha por viaje laboral.",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert resched_res.status_code == 200
|
||||||
|
resched_data = resched_res.json()
|
||||||
|
assert resched_data["scheduled_at"] == new_time
|
||||||
|
assert resched_data["booking_status"] == "RESERVED"
|
||||||
|
assert "2026-11-12" in resched_data["whatsapp_redirect_url"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reschedule_collision_with_buffer_conflict(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# Booking 1 at 10:00 (1h duration + 15m buffer -> blocked until 11:15)
|
||||||
|
b1_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Hugo Luna",
|
||||||
|
"client_phone": "+52 55 8899 0011",
|
||||||
|
"scheduled_at": "2026-11-15T10:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b1_res.status_code == 201
|
||||||
|
|
||||||
|
# Booking 2 at 14:00
|
||||||
|
b2_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Ignacio Vega",
|
||||||
|
"client_phone": "+52 55 8899 0022",
|
||||||
|
"scheduled_at": "2026-11-15T14:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b2_res.status_code == 201
|
||||||
|
b2_id = b2_res.json()["id"]
|
||||||
|
|
||||||
|
# Attempt rescheduling B2 into B1's buffer (11:05) -> 409 Conflict
|
||||||
|
collision_res = client.post(
|
||||||
|
f"/bookings/{b2_id}/reschedule",
|
||||||
|
headers=headers,
|
||||||
|
json={"new_scheduled_at": "2026-11-15T11:05:00Z"},
|
||||||
|
)
|
||||||
|
assert collision_res.status_code == 409
|
||||||
|
assert "colchón" in collision_res.json()["detail"].lower()
|
||||||
|
|
||||||
|
# Reschedule B2 to exact end of buffer (11:15) -> 200 Success
|
||||||
|
valid_res = client.post(
|
||||||
|
f"/bookings/{b2_id}/reschedule",
|
||||||
|
headers=headers,
|
||||||
|
json={"new_scheduled_at": "2026-11-15T11:15:00Z"},
|
||||||
|
)
|
||||||
|
assert valid_res.status_code == 200
|
||||||
|
assert valid_res.json()["scheduled_at"] == "2026-11-15T11:15:00Z"
|
||||||
|
|
||||||
|
|
||||||
|
def test_reschedule_non_reserved_booking_fails(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Julio Cortázar",
|
||||||
|
"client_phone": "+52 55 4444 5555",
|
||||||
|
"scheduled_at": "2026-11-18T10:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
booking_id = b_res.json()["id"]
|
||||||
|
|
||||||
|
# Release booking slot
|
||||||
|
client.post(
|
||||||
|
f"/bookings/{booking_id}/release",
|
||||||
|
headers=headers,
|
||||||
|
json={"reason": "Cliente canceló"},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Attempt to reschedule released booking -> 400 Bad Request
|
||||||
|
resched_res = client.post(
|
||||||
|
f"/bookings/{booking_id}/reschedule",
|
||||||
|
headers=headers,
|
||||||
|
json={"new_scheduled_at": "2026-11-19T10:00:00Z"},
|
||||||
|
)
|
||||||
|
assert resched_res.status_code == 400
|
||||||
|
assert "only reserved" in resched_res.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_reschedule_not_found(client):
|
||||||
|
res = client.post(
|
||||||
|
"/bookings/non-existent-id/reschedule",
|
||||||
|
headers=_admin_headers(),
|
||||||
|
json={"new_scheduled_at": "2026-11-19T10:00:00Z"},
|
||||||
|
)
|
||||||
|
assert res.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_reserved_booking_success(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/circulo-cacao-presencial")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# 1. Create booking
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Karla Morales",
|
||||||
|
"client_phone": "+52 55 9988 1122",
|
||||||
|
"scheduled_at": "2026-11-22T17:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b_res.status_code == 201
|
||||||
|
booking_id = b_res.json()["id"]
|
||||||
|
|
||||||
|
# 2. Mark complete
|
||||||
|
complete_res = client.post(
|
||||||
|
f"/bookings/{booking_id}/complete",
|
||||||
|
headers=headers,
|
||||||
|
json={"notes": "Sesión completada exitosamente."},
|
||||||
|
)
|
||||||
|
assert complete_res.status_code == 200
|
||||||
|
complete_data = complete_res.json()
|
||||||
|
assert complete_data["booking_status"] == "COMPLETED"
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_non_reserved_booking_fails(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/circulo-cacao-presencial")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Lorena Gil",
|
||||||
|
"client_phone": "+52 55 1199 8877",
|
||||||
|
"scheduled_at": "2026-11-23T17:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
booking_id = b_res.json()["id"]
|
||||||
|
|
||||||
|
# Cancel booking
|
||||||
|
client.post(
|
||||||
|
f"/bookings/{booking_id}/status",
|
||||||
|
headers=headers,
|
||||||
|
json={"booking_status": "CANCELLED"},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Attempt to complete cancelled booking -> 400 Bad Request
|
||||||
|
complete_res = client.post(f"/bookings/{booking_id}/complete", headers=headers)
|
||||||
|
assert complete_res.status_code == 400
|
||||||
|
assert "only reserved" in complete_res.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_booking_with_package_records_completion(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# 1. Create client
|
||||||
|
c_res = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Mariana Garza", "phone_whatsapp": "+52 55 3322 1100"},
|
||||||
|
)
|
||||||
|
client_id = c_res.json()["id"]
|
||||||
|
|
||||||
|
# 2. Create package (5 sessions, 0 completed)
|
||||||
|
pkg_res = client.post(
|
||||||
|
"/packages",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"client_id": client_id,
|
||||||
|
"service_id": svc_id,
|
||||||
|
"total_sessions": 5,
|
||||||
|
"completed_sessions": 0,
|
||||||
|
"financial_status": "PAID",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
pkg_id = pkg_res.json()["id"]
|
||||||
|
|
||||||
|
# 3. Create booking redeemed under package (counter becomes 1)
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Mariana Garza",
|
||||||
|
"client_phone": "+52 55 3322 1100",
|
||||||
|
"scheduled_at": "2026-11-28T10:00:00Z",
|
||||||
|
"package_id": pkg_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b_res.status_code == 201
|
||||||
|
booking_id = b_res.json()["id"]
|
||||||
|
|
||||||
|
# Verify package has 1 completed session
|
||||||
|
pkg_check = client.get(f"/packages/{pkg_id}", headers=headers).json()
|
||||||
|
assert pkg_check["completed_sessions"] == 1
|
||||||
|
assert pkg_check["remaining_sessions"] == 4
|
||||||
|
|
||||||
|
# 4. Complete consultation
|
||||||
|
comp_res = client.post(
|
||||||
|
f"/bookings/{booking_id}/complete",
|
||||||
|
headers=headers,
|
||||||
|
json={"notes": "Primera sesión del paquete completada."},
|
||||||
|
)
|
||||||
|
assert comp_res.status_code == 200
|
||||||
|
assert comp_res.json()["booking_status"] == "COMPLETED"
|
||||||
|
assert comp_res.json()["package_id"] == pkg_id
|
||||||
|
|
||||||
|
# Package counter remains 1 (not double-counted)
|
||||||
|
pkg_after = client.get(f"/packages/{pkg_id}", headers=headers).json()
|
||||||
|
assert pkg_after["completed_sessions"] == 1
|
||||||
|
assert pkg_after["remaining_sessions"] == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_booking_links_package_and_advances_counter(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# 1. Create client
|
||||||
|
c_res = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Nicolás Bravo", "phone_whatsapp": "+52 55 6677 8899"},
|
||||||
|
)
|
||||||
|
client_id = c_res.json()["id"]
|
||||||
|
|
||||||
|
# 2. Create package (5 sessions, 0 completed)
|
||||||
|
pkg_res = client.post(
|
||||||
|
"/packages",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"client_id": client_id,
|
||||||
|
"service_id": svc_id,
|
||||||
|
"total_sessions": 5,
|
||||||
|
"completed_sessions": 0,
|
||||||
|
"financial_status": "PAID",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
pkg_id = pkg_res.json()["id"]
|
||||||
|
|
||||||
|
# 3. Create regular booking without package (PREPAID_DEFAULT)
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Nicolás Bravo",
|
||||||
|
"client_phone": "+52 55 6677 8899",
|
||||||
|
"scheduled_at": "2026-11-29T10:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b_res.status_code == 201
|
||||||
|
booking = b_res.json()
|
||||||
|
assert booking["payment_arrangement"] == "PREPAID_DEFAULT"
|
||||||
|
assert booking["package_id"] is None
|
||||||
|
|
||||||
|
# 4. At consultation end, client redeems package session
|
||||||
|
comp_res = client.post(
|
||||||
|
f"/bookings/{booking['id']}/complete",
|
||||||
|
headers=headers,
|
||||||
|
json={"package_id": pkg_id, "notes": "Pago aplicado a paquete."},
|
||||||
|
)
|
||||||
|
assert comp_res.status_code == 200
|
||||||
|
comp_data = comp_res.json()
|
||||||
|
assert comp_data["booking_status"] == "COMPLETED"
|
||||||
|
assert comp_data["package_id"] == pkg_id
|
||||||
|
assert comp_data["payment_arrangement"] == "PACKAGE_REDEEMED"
|
||||||
|
|
||||||
|
# Package counter was advanced from 0 to 1
|
||||||
|
pkg_after = client.get(f"/packages/{pkg_id}", headers=headers).json()
|
||||||
|
assert pkg_after["completed_sessions"] == 1
|
||||||
|
assert pkg_after["remaining_sessions"] == 4
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_headers(email: str = "jasmin@armoniadelser.mx") -> dict[str, str]:
|
||||||
|
token = create_session_token(email)
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_client_success(client):
|
||||||
|
payload = {
|
||||||
|
"full_name": "Valeria Domínguez",
|
||||||
|
"phone_whatsapp": "+52 55 9876 5432",
|
||||||
|
"email": "valeria@example.com",
|
||||||
|
"notes": "Prefiere citas por la tarde.",
|
||||||
|
}
|
||||||
|
res = client.post("/clients", json=payload, headers=_admin_headers())
|
||||||
|
assert res.status_code == 201
|
||||||
|
data = res.json()
|
||||||
|
assert data["full_name"] == "Valeria Domínguez"
|
||||||
|
assert data["phone_whatsapp"] == "+52 55 9876 5432"
|
||||||
|
assert data["email"] == "valeria@example.com"
|
||||||
|
assert data["notes"] == "Prefiere citas por la tarde."
|
||||||
|
assert "id" in data
|
||||||
|
assert "created_at" in data
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_client_phone_validation(client):
|
||||||
|
payload = {
|
||||||
|
"full_name": "Invalid Phone User",
|
||||||
|
"phone_whatsapp": "invalid-number",
|
||||||
|
}
|
||||||
|
res = client.post("/clients", json=payload, headers=_admin_headers())
|
||||||
|
assert res.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_client_duplicate_detection(client):
|
||||||
|
payload = {
|
||||||
|
"full_name": "Roberto Gómez",
|
||||||
|
"phone_whatsapp": "+52 55 4433 2211",
|
||||||
|
"email": "roberto@example.com",
|
||||||
|
}
|
||||||
|
first_res = client.post("/clients", json=payload, headers=_admin_headers())
|
||||||
|
assert first_res.status_code == 201
|
||||||
|
|
||||||
|
# Attempt registering same phone
|
||||||
|
dup_res = client.post("/clients", json=payload, headers=_admin_headers())
|
||||||
|
assert dup_res.status_code == 409
|
||||||
|
assert "already exists" in dup_res.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_client_requires_admin(client):
|
||||||
|
payload = {
|
||||||
|
"full_name": "Unauthenticated Client",
|
||||||
|
"phone_whatsapp": "+52 55 1122 3344",
|
||||||
|
}
|
||||||
|
res = client.post("/clients", json=payload)
|
||||||
|
assert res.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_and_search_clients(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
|
||||||
|
# Seed 3 distinct clients
|
||||||
|
client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Adriana Morales", "phone_whatsapp": "+52 55 7777 0001"},
|
||||||
|
)
|
||||||
|
client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Adrián Castillo", "phone_whatsapp": "+52 55 7777 0002"},
|
||||||
|
)
|
||||||
|
client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Beatriz Solís", "phone_whatsapp": "+52 55 8888 0003"},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Search by partial name (case-insensitive)
|
||||||
|
search_res = client.get("/clients?search=adri", headers=headers)
|
||||||
|
assert search_res.status_code == 200
|
||||||
|
results = search_res.json()
|
||||||
|
names = [c["full_name"] for c in results]
|
||||||
|
assert "Adriana Morales" in names
|
||||||
|
assert "Adrián Castillo" in names
|
||||||
|
assert "Beatriz Solís" not in names
|
||||||
|
|
||||||
|
# Search by partial phone
|
||||||
|
phone_res = client.get("/clients?search=8888 0003", headers=headers)
|
||||||
|
assert phone_res.status_code == 200
|
||||||
|
phone_results = phone_res.json()
|
||||||
|
assert len(phone_results) == 1
|
||||||
|
assert phone_results[0]["full_name"] == "Beatriz Solís"
|
||||||
|
|
||||||
|
# Pagination: limit and offset
|
||||||
|
page_res = client.get("/clients?limit=2&offset=0", headers=headers)
|
||||||
|
assert page_res.status_code == 200
|
||||||
|
assert len(page_res.json()) <= 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_client_360_profile(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
|
||||||
|
# 1. Create client
|
||||||
|
c_res = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"full_name": "Camila Ochoa",
|
||||||
|
"phone_whatsapp": "+52 55 6655 4433",
|
||||||
|
"notes": "Seguimiento quincenal",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert c_res.status_code == 201
|
||||||
|
c_data = c_res.json()
|
||||||
|
client_id = c_data["id"]
|
||||||
|
|
||||||
|
# 2. Fetch service
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
# 3. Create active package (5 total, 1 completed -> active)
|
||||||
|
active_pkg = client.post(
|
||||||
|
"/packages",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"client_id": client_id,
|
||||||
|
"service_id": svc_id,
|
||||||
|
"total_sessions": 5,
|
||||||
|
"completed_sessions": 1,
|
||||||
|
"financial_status": "PAID",
|
||||||
|
},
|
||||||
|
).json()
|
||||||
|
|
||||||
|
# 4. Create exhausted package (3 total, 3 completed -> inactive)
|
||||||
|
client.post(
|
||||||
|
"/packages",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"client_id": client_id,
|
||||||
|
"service_id": svc_id,
|
||||||
|
"total_sessions": 3,
|
||||||
|
"completed_sessions": 3,
|
||||||
|
"financial_status": "PAID",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Create a booking for this client
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Camila Ochoa",
|
||||||
|
"client_phone": "+52 55 6655 4433",
|
||||||
|
"scheduled_at": "2026-11-20T10:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert b_res.status_code == 201
|
||||||
|
|
||||||
|
# 6. Fetch Client 360 profile
|
||||||
|
profile_res = client.get(f"/clients/{client_id}", headers=headers)
|
||||||
|
assert profile_res.status_code == 200
|
||||||
|
profile = profile_res.json()
|
||||||
|
|
||||||
|
assert profile["id"] == client_id
|
||||||
|
assert profile["full_name"] == "Camila Ochoa"
|
||||||
|
assert profile["notes"] == "Seguimiento quincenal"
|
||||||
|
|
||||||
|
# Active packages should only include package with remaining sessions
|
||||||
|
assert len(profile["active_packages"]) == 1
|
||||||
|
assert profile["active_packages"][0]["id"] == active_pkg["id"]
|
||||||
|
assert profile["active_packages"][0]["remaining_sessions"] == 4
|
||||||
|
|
||||||
|
# Booking history should contain the booking
|
||||||
|
assert len(profile["booking_history"]) >= 1
|
||||||
|
assert profile["booking_history"][0]["client_id"] == client_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_client_not_found(client):
|
||||||
|
res = client.get("/clients/non-existent-id", headers=_admin_headers())
|
||||||
|
assert res.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_client_success(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
created = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Daniela Ruiz", "phone_whatsapp": "+52 55 9900 1122"},
|
||||||
|
).json()
|
||||||
|
|
||||||
|
patch_payload = {
|
||||||
|
"full_name": "Daniela Ruiz de Chávez",
|
||||||
|
"notes": "Cambio de apellido civil.",
|
||||||
|
"email": "daniela@example.com",
|
||||||
|
}
|
||||||
|
patch_res = client.patch(f"/clients/{created['id']}", headers=headers, json=patch_payload)
|
||||||
|
assert patch_res.status_code == 200
|
||||||
|
updated = patch_res.json()
|
||||||
|
assert updated["full_name"] == "Daniela Ruiz de Chávez"
|
||||||
|
assert updated["notes"] == "Cambio de apellido civil."
|
||||||
|
assert updated["email"] == "daniela@example.com"
|
||||||
|
assert updated["phone_whatsapp"] == "+52 55 9900 1122"
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_client_duplicate_phone(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Usuario Uno", "phone_whatsapp": "+52 55 1212 1212"},
|
||||||
|
)
|
||||||
|
c2 = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Usuario Dos", "phone_whatsapp": "+52 55 3434 3434"},
|
||||||
|
).json()
|
||||||
|
|
||||||
|
# Attempt to change c2 phone to c1 phone -> 409 Conflict
|
||||||
|
patch_res = client.patch(
|
||||||
|
f"/clients/{c2['id']}",
|
||||||
|
headers=headers,
|
||||||
|
json={"phone_whatsapp": "+52 55 1212 1212"},
|
||||||
|
)
|
||||||
|
assert patch_res.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_client_safe_integrity_check(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
|
||||||
|
# Create client with booking
|
||||||
|
svc_res = client.get("/services/atencion-psicologica-individual")
|
||||||
|
svc_id = svc_res.json()["id"]
|
||||||
|
|
||||||
|
b_res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": svc_id,
|
||||||
|
"client_name": "Enrique Peña",
|
||||||
|
"client_phone": "+52 55 7766 5544",
|
||||||
|
"scheduled_at": "2026-11-25T12:00:00Z",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
client_id = b_res.json()["client_id"]
|
||||||
|
|
||||||
|
# Attempt to delete client with active booking -> 409 Conflict
|
||||||
|
del_res = client.delete(f"/clients/{client_id}", headers=headers)
|
||||||
|
assert del_res.status_code == 409
|
||||||
|
assert "associated" in del_res.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_client_without_dependencies(client):
|
||||||
|
headers = _admin_headers()
|
||||||
|
c = client.post(
|
||||||
|
"/clients",
|
||||||
|
headers=headers,
|
||||||
|
json={"full_name": "Fernando Morales", "phone_whatsapp": "+52 55 9988 7766"},
|
||||||
|
).json()
|
||||||
|
client_id = c["id"]
|
||||||
|
|
||||||
|
del_res = client.delete(f"/clients/{client_id}", headers=headers)
|
||||||
|
assert del_res.status_code == 204
|
||||||
|
|
||||||
|
# Confirm it cannot be found
|
||||||
|
get_res = client.get(f"/clients/{client_id}", headers=headers)
|
||||||
|
assert get_res.status_code == 404
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
from app.core.auth import create_session_token
|
||||||
|
from app.core.config import AuthProvider, settings
|
||||||
|
from app.db.database import get_engine
|
||||||
|
from app.models.admin import AdminAuditLog
|
||||||
|
from app.models.payment import Payment
|
||||||
|
from app.models.service import Service, ServiceModalityEnum, ServiceTypeEnum
|
||||||
|
|
||||||
|
|
||||||
|
def _admin(email: str = "asistente@armoniadelser.mx") -> dict[str, str]:
|
||||||
|
return {"Authorization": f"Bearer {create_session_token(email)}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _book(client, service_id: str, scheduled_at: str, phone: str, name: str = "Asistente Cacao"):
|
||||||
|
res = client.post(
|
||||||
|
"/bookings",
|
||||||
|
json={
|
||||||
|
"service_id": service_id,
|
||||||
|
"client_name": name,
|
||||||
|
"client_phone": phone,
|
||||||
|
"scheduled_at": scheduled_at,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
return res.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _roster(client, day: str, service_id: str | None = None) -> list[dict]:
|
||||||
|
params = {"date_from": day, "date_to": day}
|
||||||
|
if service_id:
|
||||||
|
params["service_id"] = service_id
|
||||||
|
res = client.get("/rosters", params=params, headers=_admin())
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return res.json()
|
||||||
|
|
||||||
|
|
||||||
|
def _queue_ids(client) -> list[str]:
|
||||||
|
return [b["id"] for b in client.get("/bookings/follow-up-queue", headers=_admin()).json()]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def cacao(client) -> dict:
|
||||||
|
return client.get("/services/circulo-cacao-presencial").json()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tiny_workshop() -> dict:
|
||||||
|
"""A GROUP service with capacity 1, inserted through the real SQLModel engine."""
|
||||||
|
service_id = str(uuid.uuid4())
|
||||||
|
with Session(get_engine()) as session:
|
||||||
|
session.add(
|
||||||
|
Service(
|
||||||
|
id=service_id,
|
||||||
|
slug=f"taller-mini-{service_id[:8]}",
|
||||||
|
name="Taller Mini",
|
||||||
|
service_type=ServiceTypeEnum.GROUP,
|
||||||
|
modality=ServiceModalityEnum.PRESENCIAL,
|
||||||
|
price_mxn=50,
|
||||||
|
max_capacity=1,
|
||||||
|
duration_minutes=60,
|
||||||
|
buffer_minutes=0,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
session.commit()
|
||||||
|
return {"id": service_id, "price_mxn": 50}
|
||||||
|
|
||||||
|
|
||||||
|
# --- GET /rosters ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_rosters_require_admin(client):
|
||||||
|
assert client.get("/rosters").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_roster_groups_attendees_by_session_instant_across_iso_formats(client, cacao):
|
||||||
|
# Same instant written two ways must land in ONE session
|
||||||
|
a = _book(client, cacao["id"], "2027-04-06T18:00:00Z", "5510000001", "Ana")
|
||||||
|
b = _book(client, cacao["id"], "2027-04-06T12:00:00-06:00", "5510000002", "Beto")
|
||||||
|
released = _book(client, cacao["id"], "2027-04-06T18:00:00+00:00", "5510000003", "Ceci")
|
||||||
|
client.post(f"/bookings/{released['id']}/release", headers=_admin(), json={})
|
||||||
|
|
||||||
|
sessions = _roster(client, "2027-04-06", cacao["id"])
|
||||||
|
assert len(sessions) == 1
|
||||||
|
session = sessions[0]
|
||||||
|
assert session["service_name"] == cacao["name"]
|
||||||
|
assert session["max_capacity"] == cacao["max_capacity"]
|
||||||
|
assert session["occupied_count"] == 2
|
||||||
|
assert session["attended_count"] == 0
|
||||||
|
ids = {att["booking_id"] for att in session["attendees"]}
|
||||||
|
assert ids == {a["id"], b["id"]} # released booking is not on the roster
|
||||||
|
assert all(att["attended"] is False for att in session["attendees"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_roster_excludes_individual_services(client):
|
||||||
|
svc = client.get("/services/atencion-psicologica-individual").json()
|
||||||
|
_book(client, svc["id"], "2027-04-07T16:00:00Z", "5510000004")
|
||||||
|
assert _roster(client, "2027-04-07") == []
|
||||||
|
|
||||||
|
|
||||||
|
# --- POST /rosters/quick-checkin: existing bookings ------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_checkin_with_cash_marks_attended_and_acknowledges_payment(client, cacao):
|
||||||
|
booking = _book(client, cacao["id"], "2027-04-13T18:00:00Z", "5510000010")
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json={"booking_id": booking["id"], "paid_cash": True},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
body = res.json()
|
||||||
|
assert body["walk_in"] is False
|
||||||
|
assert body["attendee"]["attended"] is True
|
||||||
|
assert body["attendee"]["booking_status"] == "COMPLETED"
|
||||||
|
assert body["attendee"]["payment_status"] == "ACKNOWLEDGED"
|
||||||
|
assert body["payment_id"] is not None
|
||||||
|
|
||||||
|
with Session(get_engine()) as s:
|
||||||
|
payment = s.get(Payment, body["payment_id"])
|
||||||
|
assert payment is not None
|
||||||
|
assert payment.payment_method == "CASH"
|
||||||
|
assert payment.amount_mxn == cacao["price_mxn"]
|
||||||
|
assert payment.acknowledged_by == "asistente@armoniadelser.mx"
|
||||||
|
audit = s.exec(select(AdminAuditLog).where(AdminAuditLog.entity_id == booking["id"])).all()
|
||||||
|
assert [a.action_type for a in audit] == ["ROSTER_CHECKIN"]
|
||||||
|
|
||||||
|
assert booking["id"] not in _queue_ids(client)
|
||||||
|
assert _roster(client, "2027-04-13", cacao["id"])[0]["attended_count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_checkin_twice_is_conflict(client, cacao):
|
||||||
|
booking = _book(client, cacao["id"], "2027-04-14T18:00:00Z", "5510000011")
|
||||||
|
payload = {"booking_id": booking["id"]}
|
||||||
|
assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 200
|
||||||
|
assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_unpaid_checkin_becomes_traceable_delayed_payment(client, cacao):
|
||||||
|
booking = _book(client, cacao["id"], "2027-04-15T18:00:00Z", "5510000012")
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]}
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
attendee = res.json()["attendee"]
|
||||||
|
assert attendee["booking_status"] == "COMPLETED"
|
||||||
|
assert attendee["payment_arrangement"] == "DELAYED_ALLOWED"
|
||||||
|
assert attendee["payment_status"] == "AWAITING_ACKNOWLEDGMENT"
|
||||||
|
assert res.json()["payment_id"] is None
|
||||||
|
# Attending without paying must never silently disappear from the receivables queue
|
||||||
|
assert booking["id"] in _queue_ids(client)
|
||||||
|
|
||||||
|
|
||||||
|
def test_checkin_corrects_a_mistaken_no_show(client, cacao):
|
||||||
|
booking = _book(client, cacao["id"], "2027-04-16T18:00:00Z", "5510000013")
|
||||||
|
client.post(
|
||||||
|
f"/bookings/{booking['id']}/status",
|
||||||
|
headers=_admin(),
|
||||||
|
json={"booking_status": "NO_SHOW"},
|
||||||
|
)
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json={"booking_id": booking["id"], "paid_cash": True},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["attendee"]["attended"] is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("status_path", ["release", "status"])
|
||||||
|
def test_checkin_rejects_released_or_cancelled_bookings(client, cacao, status_path):
|
||||||
|
booking = _book(client, cacao["id"], "2027-04-17T18:00:00Z", f"55100000{20 + len(status_path)}")
|
||||||
|
if status_path == "release":
|
||||||
|
client.post(f"/bookings/{booking['id']}/release", headers=_admin(), json={})
|
||||||
|
else:
|
||||||
|
client.post(
|
||||||
|
f"/bookings/{booking['id']}/status",
|
||||||
|
headers=_admin(),
|
||||||
|
json={"booking_status": "CANCELLED"},
|
||||||
|
)
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]}
|
||||||
|
)
|
||||||
|
assert res.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_checkin_rejects_individual_bookings(client):
|
||||||
|
svc = client.get("/services/atencion-psicologica-individual").json()
|
||||||
|
booking = _book(client, svc["id"], "2027-04-19T16:00:00Z", "5510000030")
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]}
|
||||||
|
)
|
||||||
|
assert res.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_checkin_unknown_booking_is_404(client):
|
||||||
|
res = client.post("/rosters/quick-checkin", headers=_admin(), json={"booking_id": "nope"})
|
||||||
|
assert res.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
# --- POST /rosters/quick-checkin: walk-ins ---------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _walk_in(service_id: str, scheduled_at: str, phone: str, **extra) -> dict:
|
||||||
|
return {
|
||||||
|
"service_id": service_id,
|
||||||
|
"scheduled_at": scheduled_at,
|
||||||
|
"client_name": "Llegó sin reservar",
|
||||||
|
"client_phone": phone,
|
||||||
|
**extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_paid_walk_in_creates_attended_acknowledged_booking(client, cacao):
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(cacao["id"], "2027-04-20T18:00:00Z", "5510000040", paid_cash=True),
|
||||||
|
)
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
body = res.json()
|
||||||
|
assert body["walk_in"] is True
|
||||||
|
assert body["attendee"]["booking_status"] == "COMPLETED"
|
||||||
|
assert body["attendee"]["payment_status"] == "ACKNOWLEDGED"
|
||||||
|
assert body["attendee"]["booking_code"].startswith("ADS-")
|
||||||
|
assert body["payment_id"] is not None
|
||||||
|
|
||||||
|
session = _roster(client, "2027-04-20", cacao["id"])[0]
|
||||||
|
assert [a["booking_id"] for a in session["attendees"]] == [body["attendee"]["booking_id"]]
|
||||||
|
assert session["attended_count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_unpaid_walk_in_is_visible_in_followup_queue(client, cacao):
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(cacao["id"], "2027-04-21T18:00:00Z", "5510000041"),
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
attendee = res.json()["attendee"]
|
||||||
|
assert attendee["payment_arrangement"] == "DELAYED_ALLOWED"
|
||||||
|
assert attendee["booking_id"] in _queue_ids(client)
|
||||||
|
|
||||||
|
|
||||||
|
def test_walk_in_reuses_existing_client_by_phone(client, cacao):
|
||||||
|
existing = _book(client, cacao["id"], "2027-04-22T18:00:00Z", "5510000042")
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(cacao["id"], "2027-04-29T18:00:00Z", "5510000042"),
|
||||||
|
)
|
||||||
|
assert res.json()["attendee"]["client_id"] == existing["client_id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_walk_in_respects_capacity(client, tiny_workshop):
|
||||||
|
when = "2027-04-23T18:00:00Z"
|
||||||
|
first = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(tiny_workshop["id"], when, "5510000050"),
|
||||||
|
)
|
||||||
|
assert first.status_code == 200
|
||||||
|
second = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(tiny_workshop["id"], when, "5510000051"),
|
||||||
|
)
|
||||||
|
assert second.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
def test_walk_in_rejects_individual_service(client):
|
||||||
|
svc = client.get("/services/atencion-psicologica-individual").json()
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=_admin(),
|
||||||
|
json=_walk_in(svc["id"], "2027-04-26T16:00:00Z", "5510000060"),
|
||||||
|
)
|
||||||
|
assert res.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"payload",
|
||||||
|
[
|
||||||
|
{},
|
||||||
|
{"paid_cash": True},
|
||||||
|
{"booking_id": "x", "service_id": "y", "scheduled_at": "2027-04-26T16:00:00Z"},
|
||||||
|
{"service_id": "y", "scheduled_at": "2027-04-26T16:00:00Z"}, # walk-in without client
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_checkin_requires_exactly_one_mode(client, payload):
|
||||||
|
assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
# --- ADR-0006: proxy users keep FK integrity on roster writes --------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_proxy_user_walk_in_checkin_preserves_foreign_keys(client, cacao, monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "auth_provider", AuthProvider.PROXY_HEADERS)
|
||||||
|
proxy = {
|
||||||
|
"Remote-Email": "puerta@homelab.lan",
|
||||||
|
"Remote-Name": "Recepcion",
|
||||||
|
"Remote-Groups": "armonia-assistant",
|
||||||
|
}
|
||||||
|
res = client.post(
|
||||||
|
"/rosters/quick-checkin",
|
||||||
|
headers=proxy,
|
||||||
|
json=_walk_in(cacao["id"], "2027-04-27T18:00:00Z", "5510000070", paid_cash=True),
|
||||||
|
)
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
with Session(get_engine()) as s:
|
||||||
|
payment = s.get(Payment, res.json()["payment_id"])
|
||||||
|
assert payment is not None
|
||||||
|
assert payment.acknowledged_by == "puerta@homelab.lan"
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.auth import resolve_role_from_groups
|
||||||
|
from app.models.admin import RoleEnum
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("raw_groups", "expected"),
|
||||||
|
[
|
||||||
|
("armonia-owner", RoleEnum.OWNER),
|
||||||
|
("armonia-assistant", RoleEnum.ASSISTANT),
|
||||||
|
("armonia-admin", RoleEnum.ADMIN),
|
||||||
|
# Authelia emits comma-separated groups; unrelated LLDAP groups are ignored
|
||||||
|
("users,armonia-assistant,family", RoleEnum.ASSISTANT),
|
||||||
|
# Whitespace and case from the proxy must not break matching
|
||||||
|
(" Users , ARMONIA-Owner ", RoleEnum.OWNER),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_resolve_role_maps_lldap_groups_to_roles(raw_groups: str, expected: RoleEnum):
|
||||||
|
assert resolve_role_from_groups(raw_groups) is expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"raw_groups",
|
||||||
|
[
|
||||||
|
"armonia-owner,armonia-assistant",
|
||||||
|
"armonia-assistant,armonia-owner",
|
||||||
|
"armonia-admin,armonia-owner,armonia-assistant",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_resolve_role_picks_highest_privilege_regardless_of_order(raw_groups: str):
|
||||||
|
assert resolve_role_from_groups(raw_groups) is RoleEnum.OWNER
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_role_prefers_admin_over_assistant():
|
||||||
|
assert resolve_role_from_groups("armonia-assistant,armonia-admin") is RoleEnum.ADMIN
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"raw_groups",
|
||||||
|
[None, "", " ", "users,admins", "armonia", "armonia-owners", "not-armonia-owner"],
|
||||||
|
)
|
||||||
|
def test_resolve_role_returns_none_without_an_exact_armonia_group(raw_groups: str | None):
|
||||||
|
assert resolve_role_from_groups(raw_groups) is None
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, date, datetime, time, timedelta
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.availability import (
|
||||||
|
BlockedInterval,
|
||||||
|
BusinessHours,
|
||||||
|
blocked_interval,
|
||||||
|
compute_available_slots,
|
||||||
|
intervals_overlap,
|
||||||
|
)
|
||||||
|
|
||||||
|
MX = ZoneInfo("America/Mexico_City") # UTC-6, no DST since 2022
|
||||||
|
MONDAY = date(2027, 3, 1)
|
||||||
|
LONG_AGO = datetime(2020, 1, 1, tzinfo=UTC)
|
||||||
|
|
||||||
|
HOURS = BusinessHours(
|
||||||
|
timezone=MX,
|
||||||
|
open_time=time(9, 0),
|
||||||
|
close_time=time(13, 0),
|
||||||
|
working_weekdays=frozenset({0, 1, 2, 3, 4}),
|
||||||
|
slot_step_minutes=30,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _local(day: date, hh: int, mm: int = 0) -> datetime:
|
||||||
|
return datetime(day.year, day.month, day.day, hh, mm, tzinfo=MX)
|
||||||
|
|
||||||
|
|
||||||
|
def _starts(slots) -> list[str]:
|
||||||
|
return [s.start.strftime("%H:%M") for s in slots]
|
||||||
|
|
||||||
|
|
||||||
|
# --- blocked_interval / intervals_overlap -------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_blocked_interval_adds_duration_and_post_session_buffer():
|
||||||
|
start = _local(MONDAY, 10)
|
||||||
|
interval = blocked_interval(start, duration_minutes=60, buffer_minutes=15)
|
||||||
|
assert interval.start == start
|
||||||
|
assert interval.end == start + timedelta(minutes=75)
|
||||||
|
|
||||||
|
|
||||||
|
def test_intervals_touching_at_boundary_do_not_overlap():
|
||||||
|
a = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 10))
|
||||||
|
b = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11))
|
||||||
|
assert intervals_overlap(a, b) is False
|
||||||
|
assert intervals_overlap(b, a) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_intervals_sharing_one_minute_overlap():
|
||||||
|
a = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 10, 1))
|
||||||
|
b = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11))
|
||||||
|
assert intervals_overlap(a, b) is True
|
||||||
|
assert intervals_overlap(b, a) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_contained_interval_overlaps():
|
||||||
|
outer = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 12))
|
||||||
|
inner = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11))
|
||||||
|
assert intervals_overlap(outer, inner) is True
|
||||||
|
assert intervals_overlap(inner, outer) is True
|
||||||
|
|
||||||
|
|
||||||
|
# --- compute_available_slots --------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _compute(existing=(), *, duration=60, buffer=15, now=LONG_AGO, day_to=None, hours=HOURS):
|
||||||
|
return compute_available_slots(
|
||||||
|
date_from=MONDAY,
|
||||||
|
date_to=day_to or MONDAY,
|
||||||
|
duration_minutes=duration,
|
||||||
|
buffer_minutes=buffer,
|
||||||
|
existing=list(existing),
|
||||||
|
hours=hours,
|
||||||
|
now=now,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_day_offers_every_step_whose_session_ends_by_close():
|
||||||
|
# 60-minute session must END by 13:00 -> last start 12:00
|
||||||
|
assert _starts(_compute()) == ["09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_buffer_may_spill_past_closing_time():
|
||||||
|
# 12:00 + 60 = 13:00 session end (allowed) even though buffer runs to 13:15
|
||||||
|
assert "12:00" in _starts(_compute())
|
||||||
|
|
||||||
|
|
||||||
|
def test_slot_end_is_session_end_without_buffer():
|
||||||
|
first = _compute()[0]
|
||||||
|
assert first.end - first.start == timedelta(minutes=60)
|
||||||
|
|
||||||
|
|
||||||
|
def test_slots_are_returned_in_business_timezone():
|
||||||
|
first = _compute()[0]
|
||||||
|
assert first.start.utcoffset() == timedelta(hours=-6)
|
||||||
|
assert first.start.astimezone(UTC).hour == 15
|
||||||
|
|
||||||
|
|
||||||
|
def test_existing_booking_blocks_its_buffer_and_new_sessions_buffer():
|
||||||
|
# Existing 10:00 session blocks [10:00, 11:15)
|
||||||
|
existing = [blocked_interval(_local(MONDAY, 10), 60, 15)]
|
||||||
|
# 09:00 slot would block [09:00, 10:15) -> overlaps because of the NEW buffer
|
||||||
|
# 11:00 slot starts before 11:15 -> overlaps because of the EXISTING buffer
|
||||||
|
assert _starts(_compute(existing)) == ["11:30", "12:00"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_slot_whose_buffer_ends_exactly_at_existing_start_is_available():
|
||||||
|
# 15-min step so 08:45-style edges are representable; 09:45 + 60 + 15 = 11:00
|
||||||
|
hours = BusinessHours(MX, time(9, 0), time(13, 0), frozenset({0}), 15)
|
||||||
|
existing = [blocked_interval(_local(MONDAY, 11), 60, 15)]
|
||||||
|
starts = _starts(_compute(existing, hours=hours))
|
||||||
|
assert "09:45" in starts
|
||||||
|
assert "10:00" not in starts # 10:00 + 75 = 11:15 > 11:00
|
||||||
|
|
||||||
|
|
||||||
|
def test_slot_starting_exactly_at_existing_buffer_end_is_available():
|
||||||
|
hours = BusinessHours(MX, time(9, 0), time(13, 0), frozenset({0}), 15)
|
||||||
|
existing = [blocked_interval(_local(MONDAY, 9), 60, 15)] # blocks until 10:15
|
||||||
|
starts = _starts(_compute(existing, hours=hours))
|
||||||
|
assert starts[0] == "10:15"
|
||||||
|
assert "10:00" not in starts
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_buffer_service_still_respects_existing_buffer():
|
||||||
|
existing = [blocked_interval(_local(MONDAY, 9), 60, 15)] # blocks until 10:15
|
||||||
|
starts = _starts(_compute(existing, buffer=0))
|
||||||
|
assert "10:00" not in starts
|
||||||
|
assert starts[0] == "10:30"
|
||||||
|
|
||||||
|
|
||||||
|
def test_bookings_on_other_days_do_not_block():
|
||||||
|
existing = [blocked_interval(_local(MONDAY + timedelta(days=1), 10), 60, 15)]
|
||||||
|
assert len(_compute(existing)) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_past_and_current_slots_are_excluded():
|
||||||
|
now = _local(MONDAY, 10).astimezone(UTC)
|
||||||
|
starts = _starts(_compute(now=now))
|
||||||
|
assert "10:00" not in starts
|
||||||
|
assert starts[0] == "10:30"
|
||||||
|
|
||||||
|
|
||||||
|
def test_non_working_days_offer_no_slots():
|
||||||
|
saturday, sunday = MONDAY + timedelta(days=5), MONDAY + timedelta(days=6)
|
||||||
|
slots = compute_available_slots(
|
||||||
|
date_from=saturday,
|
||||||
|
date_to=sunday,
|
||||||
|
duration_minutes=60,
|
||||||
|
buffer_minutes=15,
|
||||||
|
existing=[],
|
||||||
|
hours=HOURS,
|
||||||
|
now=LONG_AGO,
|
||||||
|
)
|
||||||
|
assert slots == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_range_is_inclusive_of_both_endpoints():
|
||||||
|
slots = _compute(day_to=MONDAY + timedelta(days=1))
|
||||||
|
assert {s.start.date() for s in slots} == {MONDAY, MONDAY + timedelta(days=1)}
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_longer_than_opening_hours_yields_nothing():
|
||||||
|
assert _compute(duration=300) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_range_is_rejected():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
compute_available_slots(
|
||||||
|
date_from=MONDAY,
|
||||||
|
date_to=MONDAY - timedelta(days=1),
|
||||||
|
duration_minutes=60,
|
||||||
|
buffer_minutes=15,
|
||||||
|
existing=[],
|
||||||
|
hours=HOURS,
|
||||||
|
now=LONG_AGO,
|
||||||
|
)
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
import time_machine
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.services.bookings import (
|
||||||
|
build_assistant_followup_link,
|
||||||
|
build_whatsapp_link,
|
||||||
|
calculate_hours_until,
|
||||||
|
check_slot_collision,
|
||||||
|
evaluate_payment_followup,
|
||||||
|
generate_booking_code,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# Buffer Collision Arithmetic (check_slot_collision)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_when_slots_overlap_in_middle():
|
||||||
|
# Existing booking: 10:00 - 11:00 (+15m buffer = 11:15)
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
# New slot starts inside existing slot: 10:30 - 11:30
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 30, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_when_exact_same_start_and_duration():
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_when_new_slot_starts_during_existing_buffer():
|
||||||
|
# Existing booking: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15)
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
# New slot: 11:05 - 12:05 (starts within existing buffer)
|
||||||
|
new_start = datetime(2026, 10, 27, 11, 5, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_collision_when_new_slot_starts_exactly_at_buffer_end_boundary():
|
||||||
|
# Existing booking: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15)
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
# New slot: 11:15 - 12:15 (exact boundary: new_start == exist_blocked_end)
|
||||||
|
new_start = datetime(2026, 10, 27, 11, 15, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_collision_when_new_slot_blocked_end_exactly_matches_existing_start():
|
||||||
|
# Existing booking: 11:15 - 12:15 (+ 15m buffer)
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T11:15:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
# New slot: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15)
|
||||||
|
# Exact boundary: new_blocked_end == exist_start
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_when_new_slot_buffer_encroaches_on_existing_start():
|
||||||
|
# Existing booking: 11:10 - 12:10 (+ 15m buffer)
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T11:10:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
# New slot: 10:00 - 11:00 (+ 15m buffer = blocked until 11:15 > 11:10)
|
||||||
|
# The session itself ended at 11:00, but its mandatory buffer collides with 11:10!
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_collision_when_completely_disjoint_after():
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T10:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
new_start = datetime(2026, 10, 27, 12, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_collision_when_completely_disjoint_before():
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T14:00:00Z", "duration_minutes": 60, "buffer_minutes": 15}
|
||||||
|
]
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_defaults_for_missing_duration_and_buffer_keys():
|
||||||
|
# Missing duration_minutes defaults to 60, missing buffer_minutes defaults to 0
|
||||||
|
existing = [{"scheduled_at": "2026-10-27T10:00:00Z"}]
|
||||||
|
# New slot at 10:45 collides with default 60-min slot (10:00-11:00)
|
||||||
|
new_start = datetime(2026, 10, 27, 10, 45, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 30, 0, existing) is True
|
||||||
|
|
||||||
|
# New slot at 11:00 does not collide because default buffer is 0
|
||||||
|
new_start_boundary = datetime(2026, 10, 27, 11, 0, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start_boundary, 30, 0, existing) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_collision_with_multiple_existing_bookings_second_matches():
|
||||||
|
existing = [
|
||||||
|
{"scheduled_at": "2026-10-27T08:00:00Z", "duration_minutes": 60, "buffer_minutes": 15},
|
||||||
|
{"scheduled_at": "2026-10-27T14:00:00Z", "duration_minutes": 90, "buffer_minutes": 15},
|
||||||
|
]
|
||||||
|
# Collides with the 14:00-15:45 slot
|
||||||
|
new_start = datetime(2026, 10, 27, 14, 30, tzinfo=UTC)
|
||||||
|
assert check_slot_collision(new_start, 60, 15, existing) is True
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# Hours Until Calculation (calculate_hours_until)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_exact_hours_and_fractional():
|
||||||
|
ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
target = datetime(2026, 10, 27, 12, 0, 0, tzinfo=UTC)
|
||||||
|
assert calculate_hours_until(target, now=ref) == 48.0
|
||||||
|
|
||||||
|
target_half = datetime(2026, 10, 27, 12, 30, 0, tzinfo=UTC)
|
||||||
|
assert calculate_hours_until(target_half, now=ref) == 48.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_past_session_returns_negative():
|
||||||
|
ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
past = datetime(2026, 10, 25, 10, 0, 0, tzinfo=UTC)
|
||||||
|
assert calculate_hours_until(past, now=ref) == -2.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_from_iso_string():
|
||||||
|
ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
assert calculate_hours_until("2026-10-27T12:00:00Z", now=ref) == 48.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_from_naive_datetime():
|
||||||
|
ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
naive_target = datetime(2026, 10, 27, 12, 0, 0)
|
||||||
|
assert calculate_hours_until(naive_target, now=ref) == 48.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_uses_datetime_now_when_now_is_none():
|
||||||
|
frozen_ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
with time_machine.travel(frozen_ref, tick=False):
|
||||||
|
target = "2026-10-27T12:00:00Z"
|
||||||
|
assert calculate_hours_until(target) == 48.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_calculate_hours_until_rounding_to_two_decimals():
|
||||||
|
ref = datetime(2026, 10, 25, 12, 0, 0, tzinfo=UTC)
|
||||||
|
# 1 hour and 20 seconds = 3620s -> 3620 / 3600 = 1.00555... -> 1.01
|
||||||
|
target = ref + timedelta(seconds=3620)
|
||||||
|
assert calculate_hours_until(target, now=ref) == 1.01
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# Payment Follow-Up Evaluation (evaluate_payment_followup)
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def test_payment_followup_false_when_payment_not_awaiting_acknowledgment():
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="ACKNOWLEDGED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=10.0,
|
||||||
|
threshold_hours=48,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="NOT_APPLICABLE",
|
||||||
|
payment_arrangement="PACKAGE_REDEEMED",
|
||||||
|
hours_until=10.0,
|
||||||
|
threshold_hours=48,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_payment_followup_at_exact_48h_boundary_is_true():
|
||||||
|
# Exactly at threshold 48.0 hours -> must trigger follow-up
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=48.0,
|
||||||
|
threshold_hours=48,
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_payment_followup_uses_48h_as_default_threshold():
|
||||||
|
# Verify default parameter threshold_hours=48
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=48.0,
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
# At 48.01 or 49.0 hours, with default threshold=48, it must return False
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=48.01,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=49.0,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_payment_followup_custom_threshold_window():
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=72.0,
|
||||||
|
threshold_hours=72,
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
hours_until=72.01,
|
||||||
|
threshold_hours=72,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_payment_followup_delayed_allowed_for_reserved_and_completed_beyond_threshold():
|
||||||
|
# DELAYED_ALLOWED triggers even when session is far in future
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="DELAYED_ALLOWED",
|
||||||
|
hours_until=120.0,
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
# DELAYED_ALLOWED triggers for COMPLETED sessions (post-session payment)
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="COMPLETED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="DELAYED_ALLOWED",
|
||||||
|
hours_until=-5.0,
|
||||||
|
)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
# Does NOT trigger for RELEASED or CANCELLED
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="RELEASED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="DELAYED_ALLOWED",
|
||||||
|
hours_until=-5.0,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
evaluate_payment_followup(
|
||||||
|
booking_status="CANCELLED",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
payment_arrangement="DELAYED_ALLOWED",
|
||||||
|
hours_until=10.0,
|
||||||
|
)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ==============================================================================
|
||||||
|
# Folio Code & WhatsApp Generation
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_booking_code_format():
|
||||||
|
code = generate_booking_code()
|
||||||
|
assert code.startswith("ADS-")
|
||||||
|
assert len(code) == 8
|
||||||
|
suffix = code[4:]
|
||||||
|
assert suffix == suffix.upper()
|
||||||
|
assert all(c in "0123456789ABCDEF" for c in suffix)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_whatsapp_link_standalone_and_package():
|
||||||
|
# Standalone booking link includes SPEI details
|
||||||
|
link = build_whatsapp_link(
|
||||||
|
service_name="Terapia Holística",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
folio="ADS-1A2B",
|
||||||
|
amount_mxn=700,
|
||||||
|
)
|
||||||
|
assert "https://wa.me/" in link
|
||||||
|
assert "ADS-1A2B" in link
|
||||||
|
assert "700" in link
|
||||||
|
assert settings.spei_bank in link
|
||||||
|
|
||||||
|
# Package booking excludes bank details
|
||||||
|
pkg_link = build_whatsapp_link(
|
||||||
|
service_name="Terapia Holística",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
folio="ADS-1A2B",
|
||||||
|
amount_mxn=700,
|
||||||
|
package_info="Sesión 2/5",
|
||||||
|
)
|
||||||
|
assert "https://wa.me/" in pkg_link
|
||||||
|
assert "Sesi%C3%B3n%202/5" in pkg_link or "Sesión 2/5" in pkg_link
|
||||||
|
assert "CLABE" not in pkg_link
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_assistant_followup_link_phone_normalization():
|
||||||
|
# 10-digit number gets Mexican 52 prefix
|
||||||
|
link_10 = build_assistant_followup_link(
|
||||||
|
client_name="María Pérez",
|
||||||
|
client_phone="5512345678",
|
||||||
|
service_name="Cacao",
|
||||||
|
scheduled_at="2026-10-27",
|
||||||
|
folio="ADS-9999",
|
||||||
|
amount_mxn=350,
|
||||||
|
)
|
||||||
|
assert "https://wa.me/525512345678" in link_10
|
||||||
|
assert "Mar%C3%ADa%20P%C3%A9rez" in link_10 or "María Pérez" in link_10
|
||||||
|
|
||||||
|
# Formatted with +, -, spaces
|
||||||
|
link_formatted = build_assistant_followup_link(
|
||||||
|
client_name="María",
|
||||||
|
client_phone="+52 55-1234-5678",
|
||||||
|
service_name="Cacao",
|
||||||
|
scheduled_at="2026-10-27",
|
||||||
|
folio="ADS-9999",
|
||||||
|
amount_mxn=350,
|
||||||
|
)
|
||||||
|
assert "https://wa.me/525512345678" in link_formatted
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.calendar import (
|
||||||
|
CalendarService,
|
||||||
|
compute_calendar_prefix,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("booking_status", "payment_arrangement", "payment_status", "expected_prefix"),
|
||||||
|
[
|
||||||
|
("RELEASED", "PREPAID_DEFAULT", "AWAITING_ACKNOWLEDGMENT", "[LIBERADO]"),
|
||||||
|
("CANCELLED", "PREPAID_DEFAULT", "ACKNOWLEDGED", "[LIBERADO]"),
|
||||||
|
("RESERVED", "PREPAID_DEFAULT", "ACKNOWLEDGED", "[CONFIRMADO]"),
|
||||||
|
("RESERVED", "PACKAGE_REDEEMED", "NOT_APPLICABLE", "[CONFIRMADO]"),
|
||||||
|
("RESERVED", "DELAYED_ALLOWED", "AWAITING_ACKNOWLEDGMENT", "[PAGO DIFERIDO]"),
|
||||||
|
("RESERVED", "PREPAID_DEFAULT", "AWAITING_ACKNOWLEDGMENT", "[PAGO PENDIENTE]"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_compute_calendar_prefix_states(
|
||||||
|
booking_status: str,
|
||||||
|
payment_arrangement: str,
|
||||||
|
payment_status: str,
|
||||||
|
expected_prefix: str,
|
||||||
|
):
|
||||||
|
assert (
|
||||||
|
compute_calendar_prefix(
|
||||||
|
booking_status=booking_status,
|
||||||
|
payment_arrangement=payment_arrangement,
|
||||||
|
payment_status=payment_status,
|
||||||
|
)
|
||||||
|
== expected_prefix
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_calendar_service_not_configured_when_no_credentials(monkeypatch):
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, "google_service_account_json", None)
|
||||||
|
service = CalendarService()
|
||||||
|
result = await service.sync_booking_event(
|
||||||
|
booking_id="b-1",
|
||||||
|
booking_code="ADS-1234",
|
||||||
|
service_name="Terapia",
|
||||||
|
client_name="Juan",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
duration_minutes=60,
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
existing_event_id="evt-old",
|
||||||
|
)
|
||||||
|
assert result.sync_status == "NOT_CONFIGURED"
|
||||||
|
assert result.event_id == "evt-old"
|
||||||
|
assert result.sync_error is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_calendar_service_mock_gcal_sync_success(monkeypatch):
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, "google_service_account_json", "mock-gcal")
|
||||||
|
service = CalendarService()
|
||||||
|
|
||||||
|
# New event generation
|
||||||
|
res = await service.sync_booking_event(
|
||||||
|
booking_id="12345678-abcd-1111-2222-333333333333",
|
||||||
|
booking_code="ADS-1234",
|
||||||
|
service_name="Cacao",
|
||||||
|
client_name="Lucia",
|
||||||
|
scheduled_at="2026-10-27T10:00:00",
|
||||||
|
duration_minutes=60,
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
payment_status="ACKNOWLEDGED",
|
||||||
|
)
|
||||||
|
assert res.sync_status == "SYNCED"
|
||||||
|
assert res.event_id == "gcal-12345678"
|
||||||
|
assert res.sync_error is None
|
||||||
|
assert res.synced_at is not None
|
||||||
|
|
||||||
|
# Preserves existing event_id
|
||||||
|
res_existing = await service.sync_booking_event(
|
||||||
|
booking_id="12345678-abcd-1111-2222-333333333333",
|
||||||
|
booking_code="ADS-1234",
|
||||||
|
service_name="Cacao",
|
||||||
|
client_name="Lucia",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
duration_minutes=60,
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
payment_status="ACKNOWLEDGED",
|
||||||
|
existing_event_id="gcal-existing-99",
|
||||||
|
)
|
||||||
|
assert res_existing.event_id == "gcal-existing-99"
|
||||||
|
|
||||||
|
# Released/Cancelled booking clears event_id
|
||||||
|
res_released = await service.sync_booking_event(
|
||||||
|
booking_id="12345678-abcd-1111-2222-333333333333",
|
||||||
|
booking_code="ADS-1234",
|
||||||
|
service_name="Cacao",
|
||||||
|
client_name="Lucia",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
duration_minutes=60,
|
||||||
|
booking_status="RELEASED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
existing_event_id="gcal-existing-99",
|
||||||
|
)
|
||||||
|
assert res_released.event_id is None
|
||||||
|
assert res_released.sync_status == "SYNCED"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_calendar_service_fail_gcal_captures_error(monkeypatch):
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
monkeypatch.setattr(settings, "google_service_account_json", "fail-gcal")
|
||||||
|
service = CalendarService()
|
||||||
|
res = await service.sync_booking_event(
|
||||||
|
booking_id="12345678-abcd-1111-2222-333333333333",
|
||||||
|
booking_code="ADS-1234",
|
||||||
|
service_name="Cacao",
|
||||||
|
client_name="Lucia",
|
||||||
|
scheduled_at="2026-10-27T10:00:00Z",
|
||||||
|
duration_minutes=60,
|
||||||
|
booking_status="RESERVED",
|
||||||
|
payment_arrangement="PREPAID_DEFAULT",
|
||||||
|
payment_status="AWAITING_ACKNOWLEDGMENT",
|
||||||
|
existing_event_id="gcal-keep-id",
|
||||||
|
)
|
||||||
|
assert res.sync_status == "FAILED"
|
||||||
|
assert res.event_id == "gcal-keep-id"
|
||||||
|
assert "503" in (res.sync_error or "")
|
||||||
|
assert res.synced_at is not None
|
||||||
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
|
|||||||
|
|
||||||
import time_machine
|
import time_machine
|
||||||
|
|
||||||
from app.services.timestamps import utc_now_iso
|
from app.services.timestamps import parse_iso_datetime, utc_now_iso
|
||||||
|
|
||||||
|
|
||||||
def test_utc_now_iso_returns_exact_timestamp():
|
def test_utc_now_iso_returns_exact_timestamp():
|
||||||
@@ -16,3 +16,20 @@ def test_utc_now_iso_returns_exact_timestamp():
|
|||||||
|
|
||||||
with time_machine.travel(frozen_time, tick=False):
|
with time_machine.travel(frozen_time, tick=False):
|
||||||
assert utc_now_iso() == "2026-09-26T16:00:00.500000+00:00"
|
assert utc_now_iso() == "2026-09-26T16:00:00.500000+00:00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_iso_datetime_naive_string_normalizes_to_utc():
|
||||||
|
parsed = parse_iso_datetime("2026-10-27T10:00:00")
|
||||||
|
assert parsed.tzinfo == UTC
|
||||||
|
assert parsed.year == 2026
|
||||||
|
assert parsed.month == 10
|
||||||
|
assert parsed.day == 27
|
||||||
|
assert parsed.hour == 10
|
||||||
|
assert parsed.minute == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_iso_datetime_aware_string_retains_utc():
|
||||||
|
parsed = parse_iso_datetime("2026-10-27T10:00:00+00:00")
|
||||||
|
assert parsed.tzinfo is not None
|
||||||
|
assert parsed.tzinfo == UTC
|
||||||
|
assert parsed.hour == 10
|
||||||
@@ -206,6 +206,7 @@ dependencies = [
|
|||||||
{ name = "sqlalchemy-libsql" },
|
{ name = "sqlalchemy-libsql" },
|
||||||
{ name = "sqlmodel" },
|
{ name = "sqlmodel" },
|
||||||
{ name = "time-machine" },
|
{ name = "time-machine" },
|
||||||
|
{ name = "tzdata" },
|
||||||
{ name = "uvicorn", extra = ["standard"] },
|
{ name = "uvicorn", extra = ["standard"] },
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -232,6 +233,7 @@ requires-dist = [
|
|||||||
{ name = "sqlalchemy-libsql", specifier = ">=0.2.0" },
|
{ name = "sqlalchemy-libsql", specifier = ">=0.2.0" },
|
||||||
{ name = "sqlmodel", specifier = ">=0.0.48" },
|
{ name = "sqlmodel", specifier = ">=0.0.48" },
|
||||||
{ name = "time-machine", specifier = ">=3.5.1" },
|
{ name = "time-machine", specifier = ">=3.5.1" },
|
||||||
|
{ name = "tzdata", specifier = ">=2026.5" },
|
||||||
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" },
|
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" },
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -265,11 +267,11 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "certifi"
|
name = "certifi"
|
||||||
version = "2026.7.22"
|
version = "2026.10.23"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
|
sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" }
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
{ url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2044,6 +2046,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
|
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tzdata"
|
||||||
|
version = "2026.5"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/d9/68/f1b440335057bfce71b6e50a9d09445aa2ecbd08359a337976627b8409e7/tzdata-2026.5.tar.gz", hash = "sha256:8cc73c0a0bfca7dbfa59235d60b2eff82231dee33f53d206db1acd9173cfc0a7", size = 200404, upload-time = "2026-10-03T09:23:14.143Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "urllib3"
|
name = "urllib3"
|
||||||
version = "2.8.0"
|
version = "2.8.0"
|
||||||
|
|||||||
Reference in new issue
Block a user