feat(admin): add UPDATE and DELETE endpoints for RSVP management
This commit is contained in:
1 parent
c44ecfc14b
commit
6880b74b60
4 files changed
+288
-22
No files matched your search
@@ -13,11 +13,13 @@ from ..schemas import (
|
|||||||
GenerateMapPreviewResponse,
|
GenerateMapPreviewResponse,
|
||||||
InvitationConfigResponse,
|
InvitationConfigResponse,
|
||||||
InvitationConfigUpdate,
|
InvitationConfigUpdate,
|
||||||
|
RSVPAdminItem,
|
||||||
RSVPListResponse,
|
RSVPListResponse,
|
||||||
|
RSVPUpdate,
|
||||||
)
|
)
|
||||||
from ..services.config import get_config, seed_default_config, update_config
|
from ..services.config import get_config, seed_default_config, update_config
|
||||||
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
|
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
|
||||||
from ..services.rsvp import get_rsvps
|
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
|
||||||
|
|
||||||
router = APIRouter(tags=["Admin"])
|
router = APIRouter(tags=["Admin"])
|
||||||
|
|
||||||
@@ -82,6 +84,67 @@ def list_rsvps(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete(
|
||||||
|
"/rsvps/{rsvp_id}",
|
||||||
|
status_code=status.HTTP_204_NO_CONTENT,
|
||||||
|
summary="Eliminar confirmación de asistencia",
|
||||||
|
description="Elimina permanentemente un registro de RSVP por su identificador.",
|
||||||
|
responses={
|
||||||
|
204: {"description": "Registro eliminado con éxito."},
|
||||||
|
404: {"description": "Registro no encontrado."},
|
||||||
|
**ADMIN_401,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
def delete_rsvp_endpoint(
|
||||||
|
rsvp_id: int,
|
||||||
|
admin: AdminDep,
|
||||||
|
db: DbDep,
|
||||||
|
):
|
||||||
|
deleted = delete_rsvp(db, rsvp_id)
|
||||||
|
if not deleted:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"No se encontró el registro con ID {rsvp_id}",
|
||||||
|
)
|
||||||
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch(
|
||||||
|
"/rsvps/{rsvp_id}",
|
||||||
|
response_model=RSVPAdminItem,
|
||||||
|
summary="Editar una confirmación de asistencia",
|
||||||
|
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
|
||||||
|
responses={
|
||||||
|
200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."},
|
||||||
|
400: {"description": "Error de validación en los campos proporcionados."},
|
||||||
|
404: {"description": "Registro no encontrado."},
|
||||||
|
409: {"description": "El número de teléfono ya está registrado por otro asistente."},
|
||||||
|
**ADMIN_401,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
def update_rsvp_endpoint(
|
||||||
|
rsvp_id: int,
|
||||||
|
payload: RSVPUpdate,
|
||||||
|
admin: AdminDep,
|
||||||
|
db: DbDep,
|
||||||
|
):
|
||||||
|
status_res, updated = update_rsvp(db, rsvp_id, payload)
|
||||||
|
|
||||||
|
if status_res == "NOT_FOUND":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"No se encontró el registro con ID {rsvp_id}",
|
||||||
|
)
|
||||||
|
if status_res == "DUPLICATE":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="El número de teléfono ya está registrado para otro asistente.",
|
||||||
|
)
|
||||||
|
assert updated is not None
|
||||||
|
return updated
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/export",
|
"/export",
|
||||||
summary="Exportar confirmaciones en formato CSV",
|
summary="Exportar confirmaciones en formato CSV",
|
||||||
|
|||||||
@@ -6,6 +6,24 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_phone(raw: str) -> str:
|
||||||
|
"""Normalize Colombian mobile numbers.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
1. Strip all non-digit characters.
|
||||||
|
2. If starts with '57' and has 12 digits, strip '57'.
|
||||||
|
3. Must be exactly 10 digits and start with '3'.
|
||||||
|
"""
|
||||||
|
digits = re.sub(r"\D", "", raw)
|
||||||
|
if digits.startswith("57") and len(digits) == 12:
|
||||||
|
digits = digits[2:]
|
||||||
|
|
||||||
|
if len(digits) != 10 or not digits.startswith("3"):
|
||||||
|
raise ValueError("Formato de teléfono inválido")
|
||||||
|
|
||||||
|
return digits
|
||||||
|
|
||||||
|
|
||||||
class RSVPCreate(BaseModel):
|
class RSVPCreate(BaseModel):
|
||||||
name: str = Field(
|
name: str = Field(
|
||||||
...,
|
...,
|
||||||
@@ -36,6 +54,11 @@ class RSVPCreate(BaseModel):
|
|||||||
raise ValueError("El nombre no puede estar vacío.")
|
raise ValueError("El nombre no puede estar vacío.")
|
||||||
return cleaned
|
return cleaned
|
||||||
|
|
||||||
|
@field_validator("phone")
|
||||||
|
@classmethod
|
||||||
|
def validate_phone(cls, v: str) -> str:
|
||||||
|
return normalize_phone(v)
|
||||||
|
|
||||||
@field_validator("email")
|
@field_validator("email")
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_email(cls, v: str | None) -> str | None:
|
def validate_email(cls, v: str | None) -> str | None:
|
||||||
@@ -50,6 +73,61 @@ class RSVPCreate(BaseModel):
|
|||||||
return cleaned.lower()
|
return cleaned.lower()
|
||||||
|
|
||||||
|
|
||||||
|
class RSVPUpdate(BaseModel):
|
||||||
|
name: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
min_length=1,
|
||||||
|
max_length=100,
|
||||||
|
description="Nombre completo del invitado",
|
||||||
|
examples=["Andrés García"],
|
||||||
|
)
|
||||||
|
phone: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
min_length=1,
|
||||||
|
max_length=50,
|
||||||
|
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
|
||||||
|
examples=["+57 300 123 4567"],
|
||||||
|
)
|
||||||
|
email: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
max_length=255,
|
||||||
|
description="Correo electrónico opcional para confirmación y recordatorios",
|
||||||
|
examples=["andres@example.com"],
|
||||||
|
)
|
||||||
|
|
||||||
|
@field_validator("name")
|
||||||
|
@classmethod
|
||||||
|
def normalize_name(cls, v: str | None) -> str | None:
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
cleaned = " ".join(v.strip().split())
|
||||||
|
if not cleaned:
|
||||||
|
raise ValueError("El nombre no puede estar vacío.")
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
@field_validator("phone")
|
||||||
|
@classmethod
|
||||||
|
def validate_phone(cls, v: str | None) -> str | None:
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
return normalize_phone(v)
|
||||||
|
|
||||||
|
@field_validator("email")
|
||||||
|
@classmethod
|
||||||
|
def validate_email(cls, v: str | None) -> str | None:
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
cleaned = v.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
|
||||||
|
if not re.match(email_regex, cleaned):
|
||||||
|
raise ValueError("Formato de correo electrónico inválido")
|
||||||
|
return cleaned.lower()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class RSVPSuccessResponse(BaseModel):
|
class RSVPSuccessResponse(BaseModel):
|
||||||
result: Literal["SUCCESS"] = Field(
|
result: Literal["SUCCESS"] = Field(
|
||||||
default="SUCCESS",
|
default="SUCCESS",
|
||||||
|
|||||||
@@ -1,29 +1,9 @@
|
|||||||
import re
|
|
||||||
|
|
||||||
from sqlalchemy import or_, select
|
from sqlalchemy import or_, select
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from ..models import RSVP
|
from ..models import RSVP
|
||||||
from ..schemas import RSVPCreate
|
from ..schemas import RSVPCreate, RSVPUpdate, normalize_phone
|
||||||
|
|
||||||
|
|
||||||
def normalize_phone(raw: str) -> str:
|
|
||||||
"""Normalize Colombian mobile numbers.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
1. Strip all non-digit characters.
|
|
||||||
2. If starts with '57' and has 12 digits, strip '57'.
|
|
||||||
3. Must be exactly 10 digits and start with '3'.
|
|
||||||
"""
|
|
||||||
digits = re.sub(r"\D", "", raw)
|
|
||||||
if digits.startswith("57") and len(digits) == 12:
|
|
||||||
digits = digits[2:]
|
|
||||||
|
|
||||||
if len(digits) != 10 or not digits.startswith("3"):
|
|
||||||
raise ValueError("Formato de teléfono inválido")
|
|
||||||
|
|
||||||
return digits
|
|
||||||
|
|
||||||
|
|
||||||
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
|
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
|
||||||
@@ -81,3 +61,57 @@ def get_rsvp_count(db: Session) -> int:
|
|||||||
"""Get total count of RSVPs."""
|
"""Get total count of RSVPs."""
|
||||||
query = select(RSVP)
|
query = select(RSVP)
|
||||||
return len(list(db.execute(query).scalars().all()))
|
return len(list(db.execute(query).scalars().all()))
|
||||||
|
|
||||||
|
|
||||||
|
def delete_rsvp(db: Session, rsvp_id: int) -> bool:
|
||||||
|
"""Delete an RSVP record by its ID. Returns True if deleted, False if not found."""
|
||||||
|
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
|
||||||
|
if not rsvp:
|
||||||
|
return False
|
||||||
|
db.delete(rsvp)
|
||||||
|
db.commit()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def update_rsvp(
|
||||||
|
db: Session,
|
||||||
|
rsvp_id: int,
|
||||||
|
update_in: RSVPUpdate,
|
||||||
|
) -> tuple[str, RSVP | None]:
|
||||||
|
"""Update an RSVP record using validated RSVPUpdate schema.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
("SUCCESS", rsvp)
|
||||||
|
("NOT_FOUND", None)
|
||||||
|
("DUPLICATE", None)
|
||||||
|
"""
|
||||||
|
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
|
||||||
|
if not rsvp:
|
||||||
|
return "NOT_FOUND", None
|
||||||
|
|
||||||
|
if update_in.phone is not None:
|
||||||
|
existing = db.execute(
|
||||||
|
select(RSVP).where(RSVP.phone == update_in.phone, RSVP.id != rsvp_id)
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if existing:
|
||||||
|
return "DUPLICATE", None
|
||||||
|
rsvp.phone = update_in.phone
|
||||||
|
|
||||||
|
if update_in.name is not None:
|
||||||
|
rsvp.name = update_in.name
|
||||||
|
|
||||||
|
if update_in.email is not None:
|
||||||
|
rsvp.email = update_in.email
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
db.refresh(rsvp)
|
||||||
|
return "SUCCESS", rsvp
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
return "DUPLICATE", None
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
@@ -68,3 +68,94 @@ def test_admin_export_csv(client):
|
|||||||
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
|
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
|
||||||
assert lines[0] == "name,phone,email,created_at"
|
assert lines[0] == "name,phone,email,created_at"
|
||||||
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_delete_rsvp(client):
|
||||||
|
headers = {"Remote-User": "kiskaadee"}
|
||||||
|
|
||||||
|
# Unauthorized without header
|
||||||
|
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
|
||||||
|
assert res_unauth.status_code == 401
|
||||||
|
|
||||||
|
# 404 for non-existent RSVP
|
||||||
|
res_404 = client.delete("/birthday/api/admin/rsvps/9999", headers=headers)
|
||||||
|
assert res_404.status_code == 404
|
||||||
|
|
||||||
|
# Create an RSVP
|
||||||
|
client.post(
|
||||||
|
"/birthday/api/rsvp",
|
||||||
|
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"},
|
||||||
|
)
|
||||||
|
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
rsvps = list_res.json()["rsvps"]
|
||||||
|
assert len(rsvps) == 1
|
||||||
|
rsvp_id = rsvps[0]["id"]
|
||||||
|
|
||||||
|
# Delete successfully
|
||||||
|
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}", headers=headers)
|
||||||
|
assert del_res.status_code == 204
|
||||||
|
|
||||||
|
# Confirm deletion
|
||||||
|
list_after = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||||
|
assert list_after.json()["count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_update_rsvp(client):
|
||||||
|
headers = {"Remote-User": "kiskaadee"}
|
||||||
|
|
||||||
|
# Unauthorized without header
|
||||||
|
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
|
||||||
|
assert res_unauth.status_code == 401
|
||||||
|
|
||||||
|
# 404 for non-existent RSVP
|
||||||
|
res_404 = client.patch(
|
||||||
|
"/birthday/api/admin/rsvps/9999",
|
||||||
|
json={"name": "New Name"},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_404.status_code == 404
|
||||||
|
|
||||||
|
# Create two RSVPs
|
||||||
|
client.post(
|
||||||
|
"/birthday/api/rsvp",
|
||||||
|
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
|
||||||
|
)
|
||||||
|
client.post(
|
||||||
|
"/birthday/api/rsvp",
|
||||||
|
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
|
||||||
|
)
|
||||||
|
|
||||||
|
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||||
|
rsvps = list_res.json()["rsvps"]
|
||||||
|
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
|
||||||
|
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
|
||||||
|
|
||||||
|
# Update Person One with valid new name and phone
|
||||||
|
patch_res = client.patch(
|
||||||
|
f"/birthday/api/admin/rsvps/{id_one}",
|
||||||
|
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert patch_res.status_code == 200
|
||||||
|
updated_data = patch_res.json()
|
||||||
|
assert updated_data["name"] == "Person One Updated"
|
||||||
|
assert updated_data["phone"] == "3009998888"
|
||||||
|
assert updated_data["email"] == "newone@test.com"
|
||||||
|
|
||||||
|
# Attempt to update Person One's phone to Person Two's phone -> 409
|
||||||
|
dup_res = client.patch(
|
||||||
|
f"/birthday/api/admin/rsvps/{id_one}",
|
||||||
|
json={"phone": "300 333 4444"},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert dup_res.status_code == 409
|
||||||
|
|
||||||
|
# Validation error for invalid phone
|
||||||
|
val_res = client.patch(
|
||||||
|
f"/birthday/api/admin/rsvps/{id_one}",
|
||||||
|
json={"phone": "12345"},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert val_res.status_code in (400, 422)
|
||||||
|
|
||||||
Reference in new issue
Block a user