refactor(services): extract domain booking logic and configure mutmut
- Extract buffer collision arithmetic, 48-hour follow-up evaluation, and folio/link generation from bookings router into app/services/bookings.py - Move parse_iso_datetime to app/services/timestamps.py for shared UTC normalization - Refactor app/routers/bookings.py to consume extracted domain services - Configure mutmut 3.8+ in pyproject.toml targeting app/services/ with also_copy = ["app"] and unit test selection - Add mutants/ to .gitignore to prevent linting pollution Refs: #6
This commit is contained in:
1 parent
4652a22b0d
commit
14ef3d1751
5 files changed
+160
-103
No files matched your search
@@ -13,6 +13,7 @@ venv/
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
mutants/
|
||||
|
||||
# Local databases
|
||||
*.db
|
||||
|
||||
+17
-103
@@ -1,9 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import libsql_client
|
||||
@@ -23,7 +21,16 @@ from app.schemas.booking import (
|
||||
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,
|
||||
)
|
||||
from app.services.calendar import calendar_service
|
||||
from app.services.timestamps import parse_iso_datetime
|
||||
|
||||
router = APIRouter(prefix="/bookings", tags=["Bookings"])
|
||||
|
||||
@@ -44,96 +51,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],
|
||||
*,
|
||||
@@ -145,16 +62,13 @@ def hydrate_booking_row(
|
||||
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"))
|
||||
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 "")
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
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.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}"
|
||||
@@ -3,3 +3,11 @@ from datetime import UTC, datetime
|
||||
|
||||
def utc_now_iso() -> str:
|
||||
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
|
||||
@@ -45,3 +45,8 @@ asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["."]
|
||||
|
||||
[tool.mutmut]
|
||||
source_paths = ["app/services/"]
|
||||
also_copy = ["app"]
|
||||
pytest_add_cli_args_test_selection = ["tests/unit/services/"]
|
||||
|
||||
Reference in new issue
Block a user