Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/django_program/registration/services/checkout.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def checkout(
if not items:
raise ValidationError("Cannot check out an empty cart.")

_revalidate_stock(items)
voucher = cart.voucher
_revalidate_stock(items, voucher=voucher)

summary = CartService.get_summary_from_items(cart, items)

voucher = cart.voucher
_validate_voucher_for_checkout(voucher)
voucher_code = voucher.code if voucher else ""
voucher_details = _snapshot_voucher(voucher) if voucher else ""
Expand Down Expand Up @@ -339,7 +339,7 @@ def _increment_voucher_usage(*, voucher: Voucher | None, now: object) -> None:
raise ValidationError(f"Voucher code '{voucher.code}' is no longer valid.")


def _revalidate_stock(items: list[object]) -> None:
def _revalidate_stock(items: list[object], *, voucher: Voucher | None) -> None:
"""Re-validate stock availability for all cart items at checkout time.

Raises:
Expand All @@ -349,16 +349,24 @@ def _revalidate_stock(items: list[object]) -> None:
ticket_type_ids = {item.ticket_type_id for item in items if item.ticket_type_id is not None}
for item in items:
if item.ticket_type is not None:
_revalidate_ticket_stock(item)
_revalidate_ticket_stock(item, voucher=voucher)
elif item.addon is not None:
_revalidate_addon_stock(item, now, ticket_type_ids)


def _revalidate_ticket_stock(item: object) -> None:
def _revalidate_ticket_stock(item: object, *, voucher: Voucher | None) -> None:
"""Validate a ticket type is still available with sufficient stock."""
tt = item.ticket_type
if not tt.is_available:
raise ValidationError(f"Ticket type '{tt.name}' is no longer available.")
if tt.requires_voucher:
if voucher is None or not voucher.unlocks_hidden_tickets:
raise ValidationError(
f"Ticket type '{tt.name}' requires a voucher that unlocks hidden tickets."
)
applicable_ids = set(voucher.applicable_ticket_types.values_list("pk", flat=True))
if applicable_ids and tt.pk not in applicable_ids:
raise ValidationError(f"The applied voucher does not cover ticket type '{tt.name}'.")
remaining = tt.remaining_quantity
if remaining is not None and remaining < item.quantity:
raise ValidationError(f"Only {remaining} tickets of type '{tt.name}' remaining, but {item.quantity} requested.")
Expand Down
31 changes: 31 additions & 0 deletions tests/test_registration/test_checkout_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,37 @@ def test_rejects_checkout_when_voucher_usage_limit_reached(self, cart, ticket_ty
with pytest.raises(ValidationError, match="no longer valid"):
CheckoutService.checkout(cart)

def test_rejects_checkout_for_voucher_required_ticket_when_voucher_removed(self, cart, conference):
hidden_ticket = TicketType.objects.create(
conference=conference,
name="Hidden",
slug="hidden",
price=Decimal("100.00"),
total_quantity=0,
limit_per_user=10,
is_active=True,
requires_voucher=True,
)
voucher = Voucher.objects.create(
conference=conference,
code="HIDDEN",
voucher_type=Voucher.VoucherType.COMP,
max_uses=5,
is_active=True,
unlocks_hidden_tickets=True,
)
voucher.applicable_ticket_types.add(hidden_ticket)

CartService.apply_voucher(cart, "HIDDEN")
CartService.add_ticket(cart, hidden_ticket, qty=1)
CartService.remove_voucher(cart)
Copy link

Copilot AI Feb 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method CartService.remove_voucher does not exist in the codebase. The CartService class only has the following methods: get_or_create_cart, add_ticket, add_addon, remove_item, update_quantity, apply_voucher, get_summary, and get_summary_from_items. This test will fail when executed. To remove a voucher from a cart, you should directly set cart.voucher = None and save the cart.

Suggested change
CartService.remove_voucher(cart)
cart.voucher = None
cart.save(update_fields=["voucher", "updated_at"])

Copilot uses AI. Check for mistakes.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@codex why did you recommend this patch

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question — that recommendation was to fix a test bug, not to change product behavior.

Why I recommended that patch

At line 362, the test calls CartService.remove_voucher(cart), but CartService does not define a remove_voucher method, so the test would fail with an attribute error before reaching the checkout assertion. CartService includes methods like get_or_create_cart, add_ticket, add_addon, remove_item, update_quantity, apply_voucher, get_summary, and get_summary_from_items, but no remove_voucher. tests/test_registration/test_checkout_service.pyL360-L365 src/django_program/registration/services/cart.pyL59-L60 src/django_program/registration/services/cart.pyL103-L104 src/django_program/registration/services/cart.pyL166-L167 src/django_program/registration/services/cart.pyL219-L220 src/django_program/registration/services/cart.pyL248-L249 src/django_program/registration/services/cart.pyL288-L289 src/django_program/registration/services/cart.pyL317-L318 src/django_program/registration/services/cart.pyL333-L334

The suggested replacement (cart.voucher = None + save(update_fields=["voucher", "updated_at"])) was the minimal way to simulate “voucher removed after adding ticket,” which is exactly what that test is trying to validate at checkout time. This also mirrors how voucher assignment is persisted in apply_voucher (same fields saved), just in reverse direction. tests/test_registration/test_checkout_service.pyL340-L368 src/django_program/registration/services/cart.pyL312-L314

Commands I used to verify

  • sed -n '320,390p' tests/test_registration/test_checkout_service.py
  • rg -n "class CartService|def remove_voucher|def get_or_create_cart|def apply_voucher|def get_summary_from_items" src tests
  • sed -n '50,360p' src/django_program/registration/services/cart.py
  • nl -ba tests/test_registration/test_checkout_service.py | sed -n '346,374p'
  • nl -ba src/django_program/registration/services/cart.py | sed -n '50,360p'
  • python - <<'PY' ... duckduckgo query ... PY (web search attempt failed due proxy/tunnel 403)

If you want, I can also propose a cleaner API-level follow-up (adding CartService.remove_voucher) so tests and application code avoid direct model mutation.

View task →

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its wild to me you'd introduce a method that doesn't even exist


with pytest.raises(ValidationError, match="requires a voucher"):
CheckoutService.checkout(cart)

voucher.refresh_from_db()
assert voucher.times_used == 0

def test_retries_on_reference_collision(self, cart_with_ticket):
"""IntegrityError on duplicate reference triggers retry with new reference."""
real_create = Order.objects.create
Expand Down
Loading