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
148 changes: 148 additions & 0 deletions rest/python/server/integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,14 @@ async def seed_discount() -> None:
# 2. Update without re-submitting discounts (e.g. a quantity/address
# change). applied must remain a single entry, not accumulate.
update_body = payload.model_dump(mode="json", exclude_none=True)
# Update requires line_item_ids; reference the server-assigned ids.
li_ids = [li["id"] for li in create.json()["line_items"]]
for li, li_id in zip(update_body["line_items"], li_ids, strict=True):
li["id"] = li_id
for m in update_body["fulfillment"]["methods"]:
m["line_item_ids"] = li_ids
for g in m.get("groups", []):
g["line_item_ids"] = li_ids
update = self.client.put(
f"/checkout-sessions/{checkout_id}",
headers=self._get_headers(idempotency_key="dup-2", request_id="dup-2"),
Expand Down Expand Up @@ -2359,6 +2367,146 @@ def test_create_checkout_with_fulfillment_create_shape(self) -> None:
self.assertEqual(destinations[0].get("street_address"), "1 Test Way")
self.assertEqual(destinations[0].get("postal_code"), "99999")

def test_fulfillment_rejects_unknown_line_item_ids(self) -> None:
"""Create ignores omit line_item_ids; update rejects unknown ones with 400.

On create, fulfillment method and group `line_item_ids` carry `create: omit`
because line item IDs are assigned by the server; ignoring client-supplied
values prevents dangling references from silently skipping item-based
shipping promotions (#277). On update, unknown `line_item_ids` are rejected
with 400 INVALID_REQUEST, while an explicit empty list `[]` is preserved.
"""

async def seed_shipping_and_promo() -> None:
async with self.products_session_factory() as session:
await session.execute(delete(db.Promotion))
session.add(
db.Promotion(
id="promo_rose",
type="free_shipping",
eligible_item_ids=["rose"],
description="Free Shipping on Roses",
)
)
await session.commit()
async with self.transactions_session_factory() as session:
await session.execute(delete(db.ShippingRate))
session.add(
db.ShippingRate(
id="std-ship",
country_code="US",
service_level="standard",
price=500,
title="Standard Shipping",
)
)
await session.commit()

asyncio.run(seed_shipping_and_promo())

destination = {"id": "dest_1", "address_country": "US"}

def method(
li_ids: list[str] | None,
group_li_ids: list[str] | None = None,
selected_option_id: str | None = None,
):
m = {
"type": "shipping",
"destinations": [destination],
"selected_destination_id": "dest_1",
}
if li_ids is not None:
m["line_item_ids"] = li_ids
if group_li_ids is not None or selected_option_id is not None:
g: dict[str, object] = {"id": "group_1"}
if group_li_ids is not None:
g["line_item_ids"] = group_li_ids
if selected_option_id is not None:
g["selected_option_id"] = selected_option_id
m["groups"] = [g]
return {"methods": [m]}

def assert_unknown(res: httpx.Response, li_id: str) -> None:
self.assertEqual(res.status_code, 400, res.text)
msg = res.json()["messages"][0]
self.assertEqual(msg["code"], "INVALID_REQUEST")
self.assertTrue(
msg["content"].startswith(f"Unknown line item '{li_id}'."),
msg["content"],
)

with self.client:
line_items = [{"item": {"id": "rose"}, "quantity": 1}]

# Create: `create: omit` client-supplied line_item_ids on methods and
# groups are ignored in favor of server-assigned UUIDs, so item-based
# free shipping applies identically whether line_item_ids is omitted or
# carries a product/synthetic id (#277).
for key, ful in [
("unknown_li_1", method(None, None, "std-ship")),
("unknown_li_2", method(["rose"], ["rose"], "std-ship")),
("unknown_li_3", method(None, ["rose"], "std-ship")),
]:
res = self.client.post(
"/checkout-sessions",
headers=self._get_headers(idempotency_key=key, request_id=key),
json={"line_items": line_items, "fulfillment": ful},
)
self.assertEqual(res.status_code, 201, res.text)
body = res.json()
created_li_id = body["line_items"][0]["id"]
created_method = body["fulfillment"]["methods"][0]
self.assertEqual(created_method["line_item_ids"], [created_li_id])
self.assertEqual(
created_method["groups"][0]["line_item_ids"], [created_li_id]
)
totals = {t["type"]: t["amount"] for t in body["totals"]}
self.assertEqual(
totals, {"subtotal": 1000, "fulfillment": 0, "total": 1000}
)

create_res = self.client.post(
"/checkout-sessions",
headers=self._get_headers(
idempotency_key="unknown_li_4", request_id="unknown_li_4"
),
json={"line_items": line_items},
)
self.assertEqual(create_res.status_code, 201, create_res.text)
checkout_id = self.get_resource_id(create_res.json()["id"])
li_id = create_res.json()["line_items"][0]["id"]

def update(key: str, ful: dict) -> httpx.Response:
for idx, m in enumerate(ful["methods"], start=1):
m.setdefault("id", f"method_{idx}")
return self.client.put(
f"/checkout-sessions/{checkout_id}",
headers=self._get_headers(idempotency_key=key, request_id=key),
json={
"line_items": [{"id": li_id, **line_items[0]}],
"fulfillment": ful,
},
)

# Update: an unknown id is rejected, the real line item id is accepted,
# and an explicit empty list `[]` is preserved rather than expanded.
assert_unknown(update("unknown_li_5", method(["rose"])), "rose")
assert_unknown(update("unknown_li_6", method([li_id], ["rose"])), "rose")
ok_res = update(
"unknown_li_7",
{
"methods": [
method([li_id], [li_id], "std-ship")["methods"][0],
{"id": "method_2", "type": "pickup", "line_item_ids": []},
]
},
)
self.assertEqual(ok_res.status_code, 200, ok_res.text)
ok_methods = ok_res.json()["fulfillment"]["methods"]
self.assertEqual(ok_methods[0]["line_item_ids"], [li_id])
self.assertEqual(ok_methods[1]["line_item_ids"], [])

def test_validation_failure_answers_with_ucp_envelope(self) -> None:
"""A validation failure answers with the UCP envelope, not detail."""
with self.client:
Expand Down
53 changes: 41 additions & 12 deletions rest/python/server/services/checkout_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,12 @@ async def create_checkout(
for method_req in req_fulfillment.methods:
# Create Method Response
method_id = getattr(method_req, "id", None) or str(uuid.uuid4())
method_li_ids = (
getattr(method_req, "line_item_ids", None) or all_li_ids
)
# `fulfillment.methods[].line_item_ids` and
# `fulfillment.groups[].line_item_ids` carry `create: omit`
# (fulfillment_method.json, fulfillment_group.json): line item IDs
# are assigned by the server on create, so client-supplied values are
# ignored and all checkout line items are assigned directly.
method_li_ids = list(all_li_ids)
method_type = getattr(method_req, "type", "shipping")

resp_groups = []
Expand All @@ -317,9 +320,7 @@ async def create_checkout(
group_id = (
getattr(group_req, "id", None) or f"group_{uuid.uuid4()}"
)
group_li_ids = (
getattr(group_req, "line_item_ids", None) or all_li_ids
)
group_li_ids = list(all_li_ids)

resp_groups.append(
FulfillmentGroup(
Expand Down Expand Up @@ -608,9 +609,13 @@ async def update_checkout(
method_id = str(uuid.uuid4())

method_type = getattr(m_req, "type", "shipping")
method_li_ids = getattr(m_req, "line_item_ids", None) or [
li.id for li in existing.line_items
]
req_method_li_ids = getattr(m_req, "line_item_ids", None)
self._validate_line_item_ids(req_method_li_ids, existing.line_items)
method_li_ids = (
req_method_li_ids
if req_method_li_ids is not None
else [li.id for li in existing.line_items]
)

resp_destinations = []

Expand Down Expand Up @@ -662,9 +667,15 @@ async def update_checkout(
if m_req.groups:
for g_req in m_req.groups:
g_id = getattr(g_req, "id", None) or f"group_{uuid.uuid4()}"
g_li_ids = getattr(g_req, "line_item_ids", None) or [
li.id for li in existing.line_items
]
req_group_li_ids = getattr(g_req, "line_item_ids", None)
self._validate_line_item_ids(
req_group_li_ids, existing.line_items
)
g_li_ids = (
req_group_li_ids
if req_group_li_ids is not None
else [li.id for li in existing.line_items]
)
resp_groups.append(
FulfillmentGroup(
id=g_id,
Expand Down Expand Up @@ -1266,6 +1277,24 @@ def _ensure_modifiable(self, checkout: Checkout, action: str) -> None:
f"Cannot {action} checkout in state '{checkout.status}'"
)

@staticmethod
def _validate_line_item_ids(
line_item_ids: list[str] | None, line_items: list[LineItemResponse]
) -> None:
"""Reject fulfillment line_item_ids that match no line item.

An unknown id would otherwise be skipped silently when quoting shipping,
so item-based promotions would not apply and the buyer would be charged
a different total with no feedback.
"""
known = {li.id for li in line_items}
for li_id in line_item_ids or []:
if li_id not in known:
listed = ", ".join(f"{li.id} ({li.item.id})" for li in line_items)
raise InvalidRequestError(
f"Unknown line item '{li_id}'. Line items in this checkout: {listed}"
)

@staticmethod
def _has_fulfillment_selection(checkout: Checkout) -> bool:
"""Return True if a fulfillment destination and option are selected."""
Expand Down
Loading