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
6 changes: 6 additions & 0 deletions rest/python/server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,12 @@ async def get_shipping_rates(
return list(result.scalars().all())


async def has_any_shipping_rates(session: AsyncSession) -> bool:
"""Return True if at least one shipping rate is configured in the DB."""
result = await session.execute(select(ShippingRate.id).limit(1))
return result.scalar_one_or_none() is not None


async def get_discount(session: AsyncSession, code: str) -> Discount | None:
"""Retrieve a discount by code.

Expand Down
221 changes: 221 additions & 0 deletions rest/python/server/integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2691,6 +2691,227 @@ def update_with_option(option_id: str, key: str) -> httpx.Response:
self.assertEqual(totals.get("fulfillment"), 500)
self.assertEqual(totals.get("total"), 1500)

def update_fulfillment(key: str, method: dict) -> httpx.Response:
return self.client.put(
f"/checkout-sessions/{checkout_id}",
headers=self._get_headers(idempotency_key=key, request_id=key),
json={
"line_items": [
{"id": line_item_id, "item": {"id": "rose"}, "quantity": 1}
],
"fulfillment": {"methods": [method]},
},
)

def shipping_method(dest: dict, selected_dest: str, group: dict) -> dict:
return {
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"destinations": [dest],
"selected_destination_id": selected_dest,
"groups": [
{"id": "group_1", "line_item_ids": [line_item_id], **group}
],
}

us = {"id": "dest_1", "address_country": "US"}
ca = {"id": "dest_ca", "address_country": "CA"}

# An unknown selected_destination_id is rejected rather than leaving
# the group without options and skipping option validation.
bad_dest = update_fulfillment(
"unoffered_opt_bad_dest",
shipping_method(us, "dest_typo", {"selected_option_id": "standard"}),
)
self.assertEqual(bad_dest.status_code, 400, bad_dest.text)
self.assertEqual(
bad_dest.json()["messages"][0]["content"],
"Unknown shipping destination 'dest_typo'. "
"Available destinations: dest_1",
)

# Select US-only express option, then verify group preservation vs reset
# when a destination-only PUT omits `groups`.
us_exp = update_with_option("exp-ship-us", "unoffered_opt_us_exp")
self.assertEqual(us_exp.status_code, 200, us_exp.text)
self.assertEqual(
{t["type"]: t["amount"] for t in us_exp.json()["totals"]},
{"subtotal": 1000, "fulfillment": 1500, "total": 2500},
)

# Control: keeping the same selected destination while omitting `groups`
# preserves the existing option selection.
same_dest = update_fulfillment(
"unoffered_opt_same_dest",
{
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"selected_destination_id": "dest_1",
},
)
self.assertEqual(same_dest.status_code, 200, same_dest.text)
same_dest_body = same_dest.json()
self.assertEqual(same_dest_body["status"], "ready_for_complete")
self.assertEqual(
same_dest_body["fulfillment"]["methods"][0]["groups"][0][
"selected_option_id"
],
"exp-ship-us",
)
self.assertEqual(
{t["type"]: t["amount"] for t in same_dest_body["totals"]},
{"subtotal": 1000, "fulfillment": 1500, "total": 2500},
)

# Switching selected_destination_id via a destination-only PUT (omitting
# `groups`) clears the stale US option and re-quotes CA options cleanly.
ca_requote = update_fulfillment(
"unoffered_opt_ca_requote",
{
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"destinations": [ca],
"selected_destination_id": "dest_ca",
},
)
self.assertEqual(ca_requote.status_code, 200, ca_requote.text)
ca_requote_body = ca_requote.json()
self.assertEqual(ca_requote_body["status"], "incomplete")
ca_requote_group = ca_requote_body["fulfillment"]["methods"][0]["groups"][
0
]
self.assertIsNone(ca_requote_group.get("selected_option_id"))
self.assertEqual(
[o["id"] for o in ca_requote_group["options"]], ["std-ship"]
)
self.assertEqual(
{t["type"]: t["amount"] for t in ca_requote_body["totals"]},
{"subtotal": 1000, "total": 1000},
)

# Clearing selected_destination_id to null while omitting `groups` drops
# the old option selection and fulfillment cost.
us_exp_2 = update_with_option("exp-ship-us", "unoffered_opt_us_exp_2")
self.assertEqual(us_exp_2.status_code, 200, us_exp_2.text)

cleared_dest = update_fulfillment(
"unoffered_opt_clear_dest",
{
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"destinations": [us],
"selected_destination_id": None,
},
)
self.assertEqual(cleared_dest.status_code, 200, cleared_dest.text)
cleared_body = cleared_dest.json()
self.assertEqual(cleared_body["status"], "incomplete")
self.assertIsNone(cleared_body["fulfillment"]["methods"][0].get("groups"))
self.assertEqual(
{t["type"]: t["amount"] for t in cleared_body["totals"]},
{"subtotal": 1000, "total": 1000},
)

# With rates seeded but none serving CA, options refresh to [] instead
# of keeping the previous destination's options.
async def seed_us_only_rate() -> None:
async with self.transactions_session_factory() as session:
await session.execute(delete(db.ShippingRate))
session.add(
db.ShippingRate(
id="exp-ship-us",
country_code="US",
service_level="express",
price=1500,
title="Express Shipping (US)",
)
)
await session.commit()

asyncio.run(seed_us_only_rate())

us_ok = update_with_option("exp-ship-us", "unoffered_opt_us_only")
self.assertEqual(us_ok.status_code, 200, us_ok.text)

ca_bad = update_fulfillment(
"unoffered_opt_ca_bad",
shipping_method(ca, "dest_ca", {"selected_option_id": "exp-ship-us"}),
)
self.assertEqual(ca_bad.status_code, 400, ca_bad.text)
self.assertEqual(
ca_bad.json()["messages"][0]["content"],
"Unknown shipping option 'exp-ship-us'. Offered options: none",
)

# Destination-only PUT (omitting `groups`) to unserved CA also re-quotes
# cleanly to [] without rejecting the prior US option.
ca_no_groups = update_fulfillment(
"unoffered_opt_ca_no_groups",
{
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"destinations": [ca],
"selected_destination_id": "dest_ca",
},
)
self.assertEqual(ca_no_groups.status_code, 200, ca_no_groups.text)
ca_no_groups_body = ca_no_groups.json()
self.assertEqual(ca_no_groups_body["status"], "incomplete")
ca_no_groups_grp = ca_no_groups_body["fulfillment"]["methods"][0][
"groups"
][0]
self.assertIsNone(ca_no_groups_grp.get("selected_option_id"))
self.assertEqual(ca_no_groups_grp["options"], [])
self.assertEqual(
{t["type"]: t["amount"] for t in ca_no_groups_body["totals"]},
{"subtotal": 1000, "total": 1000},
)

# Reusing the same destination id with updated country while omitting
# `groups` also resets the prior option selection and re-quotes cleanly.
us_ok_2 = update_with_option("exp-ship-us", "unoffered_opt_us_only_2")
self.assertEqual(us_ok_2.status_code, 200, us_ok_2.text)

reused_dest_ca = update_fulfillment(
"unoffered_opt_reused_dest_ca",
{
"id": "method_1",
"type": "shipping",
"line_item_ids": [line_item_id],
"destinations": [{"id": "dest_1", "address_country": "CA"}],
"selected_destination_id": "dest_1",
},
)
self.assertEqual(reused_dest_ca.status_code, 200, reused_dest_ca.text)
reused_body = reused_dest_ca.json()
self.assertEqual(reused_body["status"], "incomplete")
reused_grp = reused_body["fulfillment"]["methods"][0]["groups"][0]
self.assertIsNone(reused_grp.get("selected_option_id"))
self.assertEqual(reused_grp["options"], [])
self.assertEqual(
{t["type"]: t["amount"] for t in reused_body["totals"]},
{"subtotal": 1000, "total": 1000},
)

ca_ok = update_fulfillment(
"unoffered_opt_ca_ok", shipping_method(ca, "dest_ca", {})
)
self.assertEqual(ca_ok.status_code, 200, ca_ok.text)
ca_body = ca_ok.json()
self.assertEqual(ca_body["status"], "incomplete")
self.assertEqual(
ca_body["fulfillment"]["methods"][0]["groups"][0]["options"], []
)
self.assertEqual(
{t["type"]: t["amount"] for t in ca_body["totals"]},
{"subtotal": 1000, "total": 1000},
)

def test_checkout_payment_handler_config_matches_discovery(self) -> None:
"""The checkout envelope and discovery must advertise the same shop id.

Expand Down
71 changes: 56 additions & 15 deletions rest/python/server/services/checkout_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,8 @@ async def update_checkout(
)
)

selected_dest_id = getattr(m_req, "selected_destination_id", None)

# Handle groups
resp_groups = []
if m_req.groups:
Expand All @@ -672,9 +674,33 @@ async def update_checkout(
selected_option_id=getattr(g_req, "selected_option_id", None),
)
)
elif existing_method and existing_method.groups:
# Preserve existing groups if not updating them
resp_groups = existing_method.groups
elif (
existing_method
and existing_method.groups
and selected_dest_id
and selected_dest_id == existing_method.selected_destination_id
):
prev_dest = next(
(
d
for d in (existing_method.destinations or [])
if d.id == existing_method.selected_destination_id
),
None,
)
curr_dest = next(
(d for d in resp_destinations if d.id == selected_dest_id),
None,
)
if method_type != "shipping" or (
prev_dest is not None
and curr_dest is not None
and prev_dest.model_dump(exclude_none=True)
== curr_dest.model_dump(exclude_none=True)
):
# Preserve existing groups only when not updating them and the
# selected destination is non-null and unchanged.
resp_groups = existing_method.groups

# Construct the method response
method_resp = FulfillmentMethod(
Expand All @@ -683,9 +709,7 @@ async def update_checkout(
line_item_ids=method_li_ids,
groups=resp_groups or None,
destinations=resp_destinations or None,
selected_destination_id=getattr(
m_req, "selected_destination_id", None
),
selected_destination_id=selected_dest_id,
)
resp_methods.append(method_resp)

Expand Down Expand Up @@ -1277,7 +1301,8 @@ def _has_fulfillment_selection(checkout: Checkout) -> bool:
if method.groups and any(
g.selected_option_id
and (
not g.options or any(o.id == g.selected_option_id for o in g.options)
g.options is None
or any(o.id == g.selected_option_id for o in g.options)
)
for g in method.groups
):
Expand Down Expand Up @@ -1331,12 +1356,17 @@ async def _enrich_and_recalculate(

# Fulfillment Logic
if checkout.fulfillment and checkout.fulfillment.methods:
# Fetch promotions once for the loop
# Fetch promotions and rate-table state once for the loop
promotions = await db.get_active_promotions(self.products_session)
has_configured_rates = await db.has_any_shipping_rates(
self.transactions_session
)

for method in checkout.fulfillment.methods:
# 1. Identify Destination and Calculate Options
calculated_options = []
# None means "not quoted"; [] means rates exist but none serve the
# selected destination.
calculated_options = None
if method.type == "shipping" and method.selected_destination_id:
selected_dest = None
if method.destinations:
Expand Down Expand Up @@ -1395,34 +1425,45 @@ async def _enrich_and_recalculate(
line_item_ids=target_product_ids,
)
)
calculated_options = calculated_options_resp
if has_configured_rates or calculated_options_resp:
calculated_options = calculated_options_resp
except (ValueError, TypeError) as e:
logging.error("Failed to calculate options: %s", e)
else:
available = ", ".join(
d.id for d in method.destinations or [] if d.id
)
raise InvalidRequestError(
"Unknown shipping destination "
f"'{method.selected_destination_id}'. "
f"Available destinations: {available or 'none'}"
)

# 2. Generate or Update Groups
if method.selected_destination_id and not method.groups:
# Generate new group
group = FulfillmentGroup(
id=f"group_{uuid.uuid4()}",
line_item_ids=method.line_item_ids,
options=calculated_options,
options=calculated_options or [],
)
method.groups = [group]
elif method.groups:
# Update existing groups with fresh options
for group in method.groups:
# Refresh options if they changed due to address/item update
if calculated_options:
# Refresh options if they changed due to address/item update,
# including to [] when the new destination is not served.
if calculated_options is not None:
group.options = calculated_options

# Recalculate Totals based on Group Selection
if group.selected_option_id and group.options:
if group.selected_option_id and group.options is not None:
selected_opt = next(
(o for o in group.options if o.id == group.selected_option_id),
None,
)
if not selected_opt:
offered = ", ".join(o.id for o in group.options)
offered = ", ".join(o.id for o in group.options) or "none"
raise InvalidRequestError(
f"Unknown shipping option '{group.selected_option_id}'. "
f"Offered options: {offered}"
Expand Down
Loading