Compare commits
2
Commits
3db817ebf5
...
ad5d4d58c1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad5d4d58c1 | ||
|
|
d3a705c5a3 |
No files matched your search
+12
-1
@@ -7,7 +7,17 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.init_db import init_schema_and_seed
|
||||
from app.routers import auth, availability, bookings, health, packages, payments, rosters, services
|
||||
from app.routers import (
|
||||
auth,
|
||||
availability,
|
||||
bookings,
|
||||
clients,
|
||||
health,
|
||||
packages,
|
||||
payments,
|
||||
rosters,
|
||||
services,
|
||||
)
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
@@ -42,6 +52,7 @@ app.include_router(auth.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(packages.router)
|
||||
app.include_router(payments.router)
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
+295
-87
@@ -8,26 +8,24 @@ import libsql_client
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.core.auth import record_admin_audit, require_admin
|
||||
from app.core.config import settings
|
||||
from app.db.database import get_db, result_to_dicts, row_to_dict
|
||||
from app.schemas.auth import AdminPrincipal
|
||||
from app.schemas.booking import (
|
||||
BookingCompleteRequest,
|
||||
BookingCreate,
|
||||
BookingPaymentStatus,
|
||||
BookingRead,
|
||||
BookingReleaseRequest,
|
||||
BookingRescheduleRequest,
|
||||
BookingStatus,
|
||||
BookingStatusUpdateRequest,
|
||||
DelayedPaymentAuthorizeRequest,
|
||||
PaymentArrangement,
|
||||
)
|
||||
from app.services.bookings import (
|
||||
build_assistant_followup_link,
|
||||
build_whatsapp_link,
|
||||
calculate_hours_until,
|
||||
check_slot_collision,
|
||||
evaluate_payment_followup,
|
||||
generate_booking_code,
|
||||
hydrate_booking_row,
|
||||
)
|
||||
from app.services.calendar import calendar_service
|
||||
from app.services.timestamps import parse_iso_datetime
|
||||
@@ -51,88 +49,6 @@ BOOKING_SELECT_QUERY = """
|
||||
"""
|
||||
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
async def _fetch_hydrated_booking(
|
||||
client: libsql_client.Client,
|
||||
booking_id: str,
|
||||
@@ -678,3 +594,295 @@ async def retry_calendar_sync(
|
||||
details={"sync_status": cal_res.sync_status, "sync_error": cal_res.sync_error},
|
||||
)
|
||||
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,
|
||||
},
|
||||
)
|
||||
@@ -39,6 +39,22 @@ class BookingStatusUpdateRequest(BaseModel):
|
||||
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):
|
||||
id: str
|
||||
booking_code: str
|
||||
|
||||
+72
-3
@@ -1,19 +1,88 @@
|
||||
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):
|
||||
full_name: str = Field(..., min_length=2, max_length=150)
|
||||
phone_whatsapp: str = Field(..., min_length=10, max_length=20)
|
||||
email: str | None = None
|
||||
phone_whatsapp: str = Field(..., 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) -> 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):
|
||||
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):
|
||||
id: 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
|
||||
@@ -6,6 +6,7 @@ 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
|
||||
|
||||
|
||||
@@ -127,3 +128,85 @@ def build_assistant_followup_link(
|
||||
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,
|
||||
)
|
||||
@@ -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
|
||||
Reference in new issue
Block a user