diff --git a/rest/python/server/cart_test.py b/rest/python/server/cart_test.py index 63c20e3..24e14b2 100644 --- a/rest/python/server/cart_test.py +++ b/rest/python/server/cart_test.py @@ -602,6 +602,234 @@ def test_idempotency_key_does_not_replay_across_cart_updates(self) -> None: Cart.model_validate(response.json()).line_items[0].quantity, 1 ) + def _seed_discounts(self, *discounts: db.Discount) -> None: + async def seed() -> None: + async with self.transactions_session_factory() as session: + await session.execute(delete(db.Discount)) + session.add_all(list(discounts)) + await session.commit() + + asyncio.run(seed()) + + def _put_cart_codes(self, cart_id: str, codes: list[str], key: str) -> Cart: + response = self.client.put( + f"/carts/{cart_id}", + headers=self._get_headers(idempotency_key=key, request_id=f"r_{key}"), + json={ + "id": cart_id, + "line_items": [{"item": {"id": "rose"}, "quantity": 2}], + "discounts": {"codes": codes}, + }, + ) + self.assertEqual(response.status_code, 200, response.text) + return Cart.model_validate(response.json()) + + @staticmethod + def _amounts(totals, kind: str) -> list[int]: + return [t.amount for t in totals if t.type == kind] + + @staticmethod + def _already_applied(messages) -> list[Any]: + return [ + m + for m in (messages or []) + if getattr(m, "code", None) == "discount_code_already_applied" + ] + + def test_cart_repeated_discount_code_applied_once(self) -> None: + """A repeated code is applied once and the repeats are reported.""" + self._seed_discounts( + db.Discount( + code="FIXED500", type="fixed_amount", value=500, description="$5 Off" + ) + ) + + with self.client: + payload = self._create_cart_payload([("rose", 2)]) + response = self.client.post( + "/carts", + headers=self._get_headers( + idempotency_key="cart_dup_1", request_id="rdup1" + ), + json=payload.model_dump(mode="json", exclude_none=True), + ) + self.assertEqual(response.status_code, 201) + cart_id = Cart.model_validate(response.json()).id + + # Same code three times, including a different case. + cart = self._put_cart_codes( + cart_id, ["FIXED500", "fixed500", "FIXED500"], "cart_dup_2" + ) + + self.assertEqual(len(cart.discounts.applied), 1) + self.assertEqual(self._amounts(cart.totals, "discount"), [-500]) + self.assertEqual(self._amounts(cart.totals, "total"), [1500]) + + warnings = self._already_applied(cart.messages) + self.assertEqual( + [w.path for w in warnings], + ["$.discounts.codes[1]", "$.discounts.codes[2]"], + ) + for warning in warnings: + self.assertEqual(warning.type, "warning") + + # Dropping the repeats clears the warnings on the next recalculation. + cart = self._put_cart_codes(cart_id, ["FIXED500"], "cart_dup_3") + self.assertEqual(self._already_applied(cart.messages), []) + self.assertEqual(self._amounts(cart.totals, "total"), [1500]) + + def test_cart_fixed_discount_never_goes_below_zero(self) -> None: + """A fixed-amount discount is capped at what is left of the total.""" + self._seed_discounts( + db.Discount( + code="BIG", type="fixed_amount", value=5000, description="$50 Off" + ) + ) + + with self.client: + payload = self._create_cart_payload([("rose", 2)]) + response = self.client.post( + "/carts", + headers=self._get_headers( + idempotency_key="cart_cap_1", request_id="rcap1" + ), + json=payload.model_dump(mode="json", exclude_none=True), + ) + self.assertEqual(response.status_code, 201) + cart_id = Cart.model_validate(response.json()).id + + cart = self._put_cart_codes(cart_id, ["BIG"], "cart_cap_2") + + self.assertEqual(self._amounts(cart.totals, "subtotal"), [2000]) + self.assertEqual(self._amounts(cart.totals, "discount"), [-2000]) + self.assertEqual(self._amounts(cart.totals, "total"), [0]) + self.assertEqual(cart.discounts.applied[0].amount, 2000) + + def test_checkout_from_cart_with_repeated_codes_stays_non_negative( + self, + ) -> None: + """Repeated codes carried into checkout are not stacked there either.""" + self._seed_discounts( + db.Discount( + code="FIXED500", type="fixed_amount", value=500, description="$5 Off" + ) + ) + + with self.client: + payload = self._create_cart_payload( + [("rose", 2)], discounts={"codes": ["FIXED500"] * 10} + ) + response = self.client.post( + "/carts", + headers=self._get_headers( + idempotency_key="cart_dup_co_1", request_id="rdupco1" + ), + json=payload.model_dump(mode="json", exclude_none=True), + ) + self.assertEqual(response.status_code, 201, response.text) + cart = Cart.model_validate(response.json()) + self.assertEqual(self._amounts(cart.totals, "total"), [1500]) + self.assertEqual(len(self._already_applied(cart.messages)), 9) + + response = self.client.post( + "/checkout-sessions", + headers=self._get_headers( + idempotency_key="cart_dup_co_2", request_id="rdupco2" + ), + json={"cart_id": cart.id}, + ) + self.assertEqual(response.status_code, 201, response.text) + checkout = TestCheckout.model_validate(response.json()) + self.assertEqual(len(checkout.discounts.applied), 1) + self.assertEqual(self._amounts(checkout.totals, "discount"), [-500]) + self.assertEqual(self._amounts(checkout.totals, "total"), [1500]) + self.assertEqual(len(self._already_applied(checkout.messages)), 9) + + def test_checkout_update_repeated_codes_zero_total_completes(self) -> None: + """Repeats on a direct checkout create/update warn once and still complete. + + The warning is rebuilt on every recalculation, so an update that omits + discounts must neither lose nor duplicate it, and a checkout discounted + to a zero total can be completed. + """ + self._seed_discounts( + db.Discount( + code="BIG", type="fixed_amount", value=500000, description="Big Off" + ) + ) + + with self.client: + payload = self._create_checkout_payload( + "test_checkout_dup_update", [("rose", "Red Rose", 1000, 1)] + ) + body = payload.model_dump(mode="json", exclude_none=True) + body["discounts"] = {"codes": ["BIG", "big"]} + response = self.client.post( + "/checkout-sessions", + headers=self._get_headers(idempotency_key="cdu_1", request_id="cdu1"), + json=body, + ) + self.assertEqual(response.status_code, 201, response.text) + checkout = TestCheckout.model_validate(response.json()) + checkout_id = self.get_resource_id(checkout.id) + self.assertEqual(len(checkout.discounts.applied), 1) + self.assertEqual(self._amounts(checkout.totals, "total"), [0]) + warnings = self._already_applied(checkout.messages) + self.assertEqual([w.path for w in warnings], ["$.discounts.codes[1]"]) + + # An update that omits discounts keeps the single warning and applied + # entry rather than accumulating more. + update_body = payload.model_dump(mode="json", exclude_none=True) + response = self.client.put( + f"/checkout-sessions/{checkout_id}", + headers=self._get_headers(idempotency_key="cdu_2", request_id="cdu2"), + json=update_body, + ) + self.assertEqual(response.status_code, 200, response.text) + checkout = TestCheckout.model_validate(response.json()) + self.assertEqual(len(checkout.discounts.applied), 1) + self.assertEqual(len(self._already_applied(checkout.messages)), 1) + self.assertEqual(self._amounts(checkout.totals, "total"), [0]) + + response = self.client.post( + f"/checkout-sessions/{checkout_id}/complete", + headers=self._get_headers(idempotency_key="cdu_3", request_id="cdu3"), + json=self._create_payment_payload(), + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual( + TestCheckout.model_validate(response.json()).status, "completed" + ) + + def test_repeated_code_after_zero_effect_is_not_reported(self) -> None: + """A code that took no effect (total already 0) is not 'already applied'.""" + self._seed_discounts( + db.Discount( + code="BIG", type="fixed_amount", value=500000, description="Big Off" + ), + db.Discount( + code="EXTRA100", type="fixed_amount", value=100, description="$1 Off" + ), + ) + + with self.client: + payload = self._create_cart_payload([("rose", 2)]) + response = self.client.post( + "/carts", + headers=self._get_headers(idempotency_key="cz_1", request_id="rcz1"), + json=payload.model_dump(mode="json", exclude_none=True), + ) + self.assertEqual(response.status_code, 201, response.text) + cart_id = Cart.model_validate(response.json()).id + + cart = self._put_cart_codes( + cart_id, ["BIG", "EXTRA100", "EXTRA100"], "cz_2" + ) + + self.assertEqual([a.code for a in cart.discounts.applied], ["BIG"]) + self.assertEqual(self._amounts(cart.totals, "total"), [0]) + self.assertEqual(self._already_applied(cart.messages), []) + if __name__ == "__main__": absltest.main() diff --git a/rest/python/server/services/cart_service.py b/rest/python/server/services/cart_service.py index ecca1ee..90336c0 100644 --- a/rest/python/server/services/cart_service.py +++ b/rest/python/server/services/cart_service.py @@ -27,6 +27,7 @@ InvalidRequestError, ) from sqlalchemy.ext.asyncio import AsyncSession +from services import discount_rules from models import UnifiedCart as Cart from models import UnifiedCartCreateRequest as CartCreateRequest from models import UnifiedCartUpdateRequest as CartUpdateRequest @@ -362,23 +363,38 @@ async def _enrich_and_recalculate(self, cart: Cart) -> None: cart.discounts = DiscountsObject() cart.discounts.applied = None + discount_warnings = [] if cart.discounts.codes: discounts = await db.get_discounts_by_codes( self.transactions_session, cart.discounts.codes ) discount_map = {d.code.upper(): d for d in discounts} + # A code is applied at most once per cart; repeats are reported with + # discount_code_already_applied (discount.md). + seen_codes = set() - for code in cart.discounts.codes: + for index, code in enumerate(cart.discounts.codes): discount_obj = discount_map.get(code.upper()) if discount_obj: + if code.upper() in seen_codes: + discount_warnings.append( + discount_rules.already_applied_warning(code, index) + ) + continue + discount_amount = 0 if discount_obj.type == "percentage": discount_amount = int(grand_total * (discount_obj.value / 100)) elif discount_obj.type == "fixed_amount": - discount_amount = discount_obj.value + # Never discount past zero: the total stays non-negative. + discount_amount = discount_rules.fixed_amount_discount( + discount_obj.value, grand_total + ) if discount_amount > 0: + # Only a code that took effect counts as applied. + seen_codes.add(code.upper()) grand_total -= discount_amount if cart.discounts.applied is None: cart.discounts.applied = [] @@ -399,4 +415,7 @@ async def _enrich_and_recalculate(self, cart: Cart) -> None: TotalResponse(type="discount", amount=-discount_amount) ) + cart.messages = discount_rules.replace_discount_warnings( + cart.messages, discount_warnings + ) cart.totals.append(TotalResponse(type="total", amount=grand_total)) diff --git a/rest/python/server/services/checkout_service.py b/rest/python/server/services/checkout_service.py index e9cacf4..8f04505 100644 --- a/rest/python/server/services/checkout_service.py +++ b/rest/python/server/services/checkout_service.py @@ -53,6 +53,7 @@ from models import UnifiedCheckoutUpdateRequest from pydantic import AnyUrl from pydantic import BaseModel +from services import discount_rules from services.fulfillment_service import FulfillmentService from sqlalchemy.ext.asyncio import AsyncSession import ucp_signing @@ -1439,6 +1440,7 @@ async def _enrich_and_recalculate( # mirroring how `totals` is rebuilt above, so entries do not accumulate # on every recalculation (e.g. an update that omits the discounts field). checkout.discounts.applied = None + discount_warnings = [] if checkout.discounts.codes: # Batch fetch discounts to avoid N+1 queries @@ -1450,17 +1452,32 @@ async def _enrich_and_recalculate( # Codes are matched case-insensitively by business (discount.md); # the applied entry echoes the canonical stored code. discount_map = {d.code.upper(): d for d in discounts} + # A code is applied at most once per checkout; repeats are reported + # with discount_code_already_applied (discount.md) instead of + # stacking the same discount again. + seen_codes = set() - for code in checkout.discounts.codes: + for index, code in enumerate(checkout.discounts.codes): discount_obj = discount_map.get(code.upper()) if discount_obj: + if code.upper() in seen_codes: + discount_warnings.append( + discount_rules.already_applied_warning(code, index) + ) + continue + discount_amount = 0 if discount_obj.type == "percentage": discount_amount = int(grand_total * (discount_obj.value / 100)) elif discount_obj.type == "fixed_amount": - discount_amount = discount_obj.value + # Never discount past zero: the total stays non-negative. + discount_amount = discount_rules.fixed_amount_discount( + discount_obj.value, grand_total + ) if discount_amount > 0: + # Only a code that took effect counts as applied. + seen_codes.add(code.upper()) grand_total -= discount_amount if checkout.discounts.applied is None: checkout.discounts.applied = [] @@ -1484,6 +1501,9 @@ async def _enrich_and_recalculate( TotalResponse(type="discount", amount=-discount_amount) ) + checkout.messages = discount_rules.replace_discount_warnings( + checkout.messages, discount_warnings + ) checkout.totals.append(TotalResponse(type="total", amount=grand_total)) async def _process_payment(self, payment: PaymentCreateRequest) -> None: diff --git a/rest/python/server/services/discount_rules.py b/rest/python/server/services/discount_rules.py new file mode 100644 index 0000000..301e4a6 --- /dev/null +++ b/rest/python/server/services/discount_rules.py @@ -0,0 +1,64 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared discount rules for the cart and checkout totals recalculation. + +The discount extension (discount.md) lets the business reject a submitted code +via messages[] with `discount_code_already_applied`, and totals[] carries the +signed effect of each discount. These helpers keep a repeated code from being +applied more than once and keep a fixed-amount discount from pushing the +running total below zero. +""" + +from typing import Any + +from ucp_sdk.models.schemas.shopping.types.message_warning import ( + MessageWarning, +) + +ALREADY_APPLIED = "discount_code_already_applied" + + +def fixed_amount_discount(value: int, remaining_total: int) -> int: + """Cap a fixed-amount discount at what is left of the running total.""" + return max(0, min(value, remaining_total)) + + +def already_applied_warning(code: str, index: int) -> MessageWarning: + """Build the warning returned for a repeated discount code.""" + return MessageWarning( + type="warning", + code=ALREADY_APPLIED, + path=f"$.discounts.codes[{index}]", + content=f"Code '{code}' is already applied", + ) + + +def _message_code(message: Any) -> str | None: + if isinstance(message, dict): + return message.get("code") + return getattr(message, "code", None) + + +def replace_discount_warnings( + messages: list[Any] | None, warnings: list[MessageWarning] +) -> list[Any] | None: + """Swap out the warnings this module owns, leaving any other message alone. + + Totals are rebuilt on every create and update, so warnings from an earlier + recalculation are dropped before the current ones are added. + """ + kept = [m for m in (messages or []) if _message_code(m) != ALREADY_APPLIED] + kept.extend(warnings) + return kept or None