diff --git a/app/__init__.py b/app/__init__.py index cd64a97..a40322f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -133,22 +133,34 @@ def create_app(test_config: dict | None = None) -> Flask: # Idempotent: return existing confirmed session without creating a duplicate meeting if row["status"] == "confirmed": return jsonify(AppointmentResponse.model_validate(row).model_dump()), 200 + if row["status"] == "payment_processing": + return jsonify({"error": "El pago ya está siendo procesado."}), 409 - token = zoom.get_access_token(body.credentials) - meeting = zoom.create_meeting( - access_token=token, - topic=f"Sesión con {row['client_name']}", - start_time_local=row["start_time_local"], - tz_name=row["timezone"], - duration_minutes=row["duration_minutes"], - ) - updated = db.mark_appointment_confirmed( - session_id=row["session_id"], - zoom_meeting_id=str(meeting["id"]), - zoom_join_url=meeting["join_url"], - zoom_start_url=meeting["start_url"], - db_path=db_path, - ) + if not db.claim_appointment_for_payment(row["session_id"], db_path=db_path): + latest = db.get_appointment_by_lookup(row["session_id"], db_path=db_path) + if latest and latest["status"] == "confirmed": + return jsonify(AppointmentResponse.model_validate(latest).model_dump()), 200 + return jsonify({"error": "El pago ya está siendo procesado."}), 409 + + try: + token = zoom.get_access_token(body.credentials) + meeting = zoom.create_meeting( + access_token=token, + topic=f"Sesión con {row['client_name']}", + start_time_local=row["start_time_local"], + tz_name=row["timezone"], + duration_minutes=row["duration_minutes"], + ) + updated = db.mark_appointment_confirmed( + session_id=row["session_id"], + zoom_meeting_id=str(meeting["id"]), + zoom_join_url=meeting["join_url"], + zoom_start_url=meeting["start_url"], + db_path=db_path, + ) + except Exception: + db.release_payment_claim(row["session_id"], db_path=db_path) + raise return jsonify(AppointmentResponse.model_validate(updated).model_dump()), 200 @app.delete("/api/appointments/") diff --git a/app/db.py b/app/db.py index 41f3c93..9db4695 100644 --- a/app/db.py +++ b/app/db.py @@ -41,7 +41,7 @@ def init_db(db_path: Path | None = None) -> None: timezone TEXT NOT NULL, duration_minutes INTEGER NOT NULL DEFAULT 60, amount_usd REAL NOT NULL, - status TEXT NOT NULL CHECK (status IN ('payment_pending', 'confirmed')), + status TEXT NOT NULL CHECK (status IN ('payment_pending', 'payment_processing', 'confirmed')), zoom_meeting_id TEXT, zoom_join_url TEXT, zoom_start_url TEXT, @@ -110,6 +110,33 @@ def get_appointment_by_lookup(lookup_id: str, db_path: Path | None = None) -> di return _row_to_dict(row) +def claim_appointment_for_payment(session_id: str, db_path: Path | None = None) -> bool: + """Atomically claim a payment_pending appointment for Zoom meeting provisioning.""" + with get_connection(db_path) as conn: + cursor = conn.execute( + """ + UPDATE appointments + SET status = 'payment_processing' + WHERE session_id = ? AND status = 'payment_pending' + """, + (session_id,), + ) + return cursor.rowcount == 1 + + +def release_payment_claim(session_id: str, db_path: Path | None = None) -> None: + """Revert an in-flight payment_processing claim back to payment_pending.""" + with get_connection(db_path) as conn: + conn.execute( + """ + UPDATE appointments + SET status = 'payment_pending' + WHERE session_id = ? AND status = 'payment_processing' + """, + (session_id,), + ) + + def mark_appointment_confirmed( session_id: str, zoom_meeting_id: str, diff --git a/app/schemas.py b/app/schemas.py index 22f4c6d..c9e30bb 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -59,7 +59,7 @@ class AppointmentResponse(BaseModel): timezone: str duration_minutes: int = 60 amount_usd: float - status: Literal["payment_pending", "confirmed"] + status: Literal["payment_pending", "payment_processing", "confirmed"] zoom_meeting_id: str | None = None zoom_join_url: str | None = None zoom_start_url: str | None = None diff --git a/tests/test_app.py b/tests/test_app.py index 169e005..02d6514 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -1,4 +1,5 @@ import sqlite3 +import threading from pathlib import Path import pytest @@ -484,3 +485,72 @@ def test_duration_minutes_persisted_and_forwarded_to_zoom(client, monkeypatch): assert p_resp.get_json()["duration_minutes"] == 45 assert len(captured_payloads) == 1 assert captured_payloads[0]["duration"] == 45 + + +def test_concurrent_pay_creates_only_one_zoom_meeting(tmp_path: Path, monkeypatch): + db_file = tmp_path / "concurrent_pay.db" + app = create_app({"TESTING": True, "DB_PATH": str(db_file), "RATELIMIT_ENABLED": False}) + + create_calls = [] + in_create = threading.Event() + allow_create_finish = threading.Event() + + def fake_post(url, **kwargs): + if url == "https://zoom.us/oauth/token": + return FakeResponse(200, {"access_token": "mock_token"}) + if url == "https://api.zoom.us/v2/users/me/meetings": + create_calls.append(kwargs.get("json")) + in_create.set() + assert allow_create_finish.wait(timeout=2.0) + return FakeResponse( + 201, + { + "id": 555666777, + "join_url": "https://zoom.us/j/555666777", + "start_url": "https://zoom.us/s/555666777?zak=abc", + }, + ) + raise AssertionError(f"Unexpected POST URL: {url}") + + monkeypatch.setattr(zoom.requests, "post", fake_post) + monkeypatch.setattr( + zoom.requests, + "get", + lambda url, **kwargs: FakeResponse(200, {"meetings": []}), + ) + + with app.test_client() as tc: + c_resp = tc.post( + "/api/appointments", + json={ + "credentials": SAMPLE_CREDS, + "client_name": "María Perez", + "start_time_local": "2026-11-25T15:00", + }, + ) + assert c_resp.status_code == 201 + sid = c_resp.get_json()["session_id"] + + statuses = [] + + def worker_1(): + with app.test_client() as tc1: + r = tc1.post(f"/api/appointments/{sid}/pay", json={"credentials": SAMPLE_CREDS}) + statuses.append(r.status_code) + + def worker_2(): + assert in_create.wait(timeout=2.0) + with app.test_client() as tc2: + r = tc2.post(f"/api/appointments/{sid}/pay", json={"credentials": SAMPLE_CREDS}) + statuses.append(r.status_code) + allow_create_finish.set() + + t1 = threading.Thread(target=worker_1) + t2 = threading.Thread(target=worker_2) + t1.start() + t2.start() + t1.join(timeout=3.0) + t2.join(timeout=3.0) + + assert len(create_calls) == 1 + assert sorted(statuses) == [200, 409]