From d50d342d2bbb1db0d9348b1e29322b6b1fb9bc0e Mon Sep 17 00:00:00 2001 From: Akshar Prabhudesai <262747075+aksharprabhudesai@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:19:26 -0800 Subject: [PATCH 1/4] fix(rest/python): validate selected_destination_id and refresh empty group options --- rest/python/server/db.py | 6 ++ rest/python/server/integration_test.py | 85 +++++++++++++++++++ .../server/services/checkout_service.py | 32 +++++-- 3 files changed, 115 insertions(+), 8 deletions(-) diff --git a/rest/python/server/db.py b/rest/python/server/db.py index 5f9cbd0..930864d 100644 --- a/rest/python/server/db.py +++ b/rest/python/server/db.py @@ -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. diff --git a/rest/python/server/integration_test.py b/rest/python/server/integration_test.py index 34d5d19..816eb1f 100644 --- a/rest/python/server/integration_test.py +++ b/rest/python/server/integration_test.py @@ -2691,6 +2691,91 @@ 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", + ) + + # 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", + ) + + 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. diff --git a/rest/python/server/services/checkout_service.py b/rest/python/server/services/checkout_service.py index f0ec9f6..0473e39 100644 --- a/rest/python/server/services/checkout_service.py +++ b/rest/python/server/services/checkout_service.py @@ -1331,12 +1331,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: @@ -1395,9 +1400,19 @@ 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: @@ -1405,24 +1420,25 @@ async def _enrich_and_recalculate( 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}" From 0809502cecc850897548403f206a13981f30af60 Mon Sep 17 00:00:00 2001 From: Akshar Prabhudesai <262747075+aksharprabhudesai@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:31:13 -0800 Subject: [PATCH 2/4] fix(rest/python): reset preserved groups when selected destination changes or clears --- rest/python/server/integration_test.py | 136 ++++++++++++++++++ .../server/services/checkout_service.py | 36 ++++- 2 files changed, 166 insertions(+), 6 deletions(-) diff --git a/rest/python/server/integration_test.py b/rest/python/server/integration_test.py index 816eb1f..d7582fc 100644 --- a/rest/python/server/integration_test.py +++ b/rest/python/server/integration_test.py @@ -2731,6 +2731,91 @@ def shipping_method(dest: dict, selected_dest: str, group: dict) -> dict: "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: @@ -2762,6 +2847,57 @@ async def seed_us_only_rate() -> None: "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", {}) ) diff --git a/rest/python/server/services/checkout_service.py b/rest/python/server/services/checkout_service.py index 0473e39..aba5d3a 100644 --- a/rest/python/server/services/checkout_service.py +++ b/rest/python/server/services/checkout_service.py @@ -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: @@ -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( @@ -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) From e40ccb901ed295aa6e14999d4280406cea1e1eeb Mon Sep 17 00:00:00 2001 From: Akshar Prabhudesai <262747075+aksharprabhudesai@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:04:21 -0800 Subject: [PATCH 3/4] fix(rest/python): check g.options is None in _has_fulfillment_selection --- rest/python/server/services/checkout_service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest/python/server/services/checkout_service.py b/rest/python/server/services/checkout_service.py index aba5d3a..24878f8 100644 --- a/rest/python/server/services/checkout_service.py +++ b/rest/python/server/services/checkout_service.py @@ -1301,7 +1301,7 @@ 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 ): From df83ec9eb61ce802610c66ad3749f59c6f43a4ae Mon Sep 17 00:00:00 2001 From: Federico D'Amato Date: Thu, 19 Nov 2026 08:51:41 +0000 Subject: [PATCH 4/4] style(rest/python): wrap line in _has_fulfillment_selection --- rest/python/server/services/checkout_service.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rest/python/server/services/checkout_service.py b/rest/python/server/services/checkout_service.py index 24878f8..24c6ad3 100644 --- a/rest/python/server/services/checkout_service.py +++ b/rest/python/server/services/checkout_service.py @@ -1301,7 +1301,8 @@ def _has_fulfillment_selection(checkout: Checkout) -> bool: if method.groups and any( g.selected_option_id and ( - g.options is None 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 ):