-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathcheckout_service.py
More file actions
1268 lines (1123 loc) · 43.3 KB
/
checkout_service.py
File metadata and controls
1268 lines (1123 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
"""Checkout service for managing the lifecycle of checkout sessions.
This module provides the `CheckoutService` class, which encapsulates the
business logic
for creating, retrieving, updating, and completing checkout sessions. It handles
integration with the persistence layer, fulfillment calculation, payment
processing,
and inventory validation.
Key responsibilities include:
- Creating and managing checkout sessions with idempotency support.
- Calculating checkout totals, including line items, shipping, and discounts.
- Validating inventory availability.
- Processing payments via various handlers (e.g., Google Pay, Shop Pay, Mock).
- Transforming checkout sessions into completed orders.
- Supporting hierarchical fulfillment configuration.
"""
import datetime
import hashlib
import json
import logging
from typing import Any
import uuid
import config
import db
from enums import CheckoutStatus
from exceptions import Ap2VerificationError
from exceptions import CheckoutNotModifiableError
from exceptions import IdempotencyConflictError
from exceptions import InvalidRequestError
from exceptions import OutOfStockError
from exceptions import PaymentFailedError
from exceptions import ResourceNotFoundError
import httpx
from models import UnifiedCheckout as Checkout
from models import UnifiedCheckoutCreateRequest
from models import UnifiedCheckoutUpdateRequest
from pydantic import AnyUrl
from pydantic import BaseModel
from services.fulfillment_service import FulfillmentService
from sqlalchemy.ext.asyncio import AsyncSession
from ucp_sdk.models._internal import Response
from ucp_sdk.models._internal import ResponseCheckout
from ucp_sdk.models._internal import ResponseOrder
from ucp_sdk.models._internal import Version
from ucp_sdk.models.schemas.shopping.ap2_mandate import Ap2CompleteRequest
from ucp_sdk.models.schemas.shopping.discount_resp import Allocation
from ucp_sdk.models.schemas.shopping.discount_resp import AppliedDiscount
from ucp_sdk.models.schemas.shopping.discount_resp import DiscountsObject
from ucp_sdk.models.schemas.shopping.fulfillment_resp import (
Fulfillment as FulfillmentResp,
)
from ucp_sdk.models.schemas.shopping.order import (
Fulfillment as OrderFulfillment,
)
from ucp_sdk.models.schemas.shopping.order import Order
from ucp_sdk.models.schemas.shopping.order import PlatformConfig
from ucp_sdk.models.schemas.shopping.payment_create_req import (
PaymentCreateRequest,
)
from ucp_sdk.models.schemas.shopping.payment_resp import PaymentResponse
from ucp_sdk.models.schemas.shopping.types import order_line_item
from ucp_sdk.models.schemas.shopping.types import total_resp
from ucp_sdk.models.schemas.shopping.types.card_credential import CardCredential
from ucp_sdk.models.schemas.shopping.types.expectation import Expectation
from ucp_sdk.models.schemas.shopping.types.expectation import (
LineItem as ExpectationLineItem,
)
from ucp_sdk.models.schemas.shopping.types.fulfillment_destination_resp import (
FulfillmentDestinationResponse,
)
from ucp_sdk.models.schemas.shopping.types.fulfillment_group_resp import (
FulfillmentGroupResponse,
)
from ucp_sdk.models.schemas.shopping.types.fulfillment_method_resp import (
FulfillmentMethodResponse,
)
from ucp_sdk.models.schemas.shopping.types.fulfillment_resp import (
FulfillmentResponse,
)
from ucp_sdk.models.schemas.shopping.types.item_resp import ItemResponse
from ucp_sdk.models.schemas.shopping.types.line_item_resp import (
LineItemResponse,
)
from ucp_sdk.models.schemas.shopping.types.order_confirmation import (
OrderConfirmation,
)
from ucp_sdk.models.schemas.shopping.types.order_line_item import OrderLineItem
from ucp_sdk.models.schemas.shopping.types.postal_address import PostalAddress
from ucp_sdk.models.schemas.shopping.types.shipping_destination_resp import (
ShippingDestinationResponse,
)
from ucp_sdk.models.schemas.shopping.types.token_credential_resp import (
TokenCredentialResponse,
)
from ucp_sdk.models.schemas.shopping.types.total_resp import (
TotalResponse as Total,
)
logger = logging.getLogger(__name__)
class CheckoutService:
"""Service for managing checkout sessions and orders."""
def __init__(
self,
fulfillment_service: FulfillmentService,
products_session: AsyncSession,
transactions_session: AsyncSession,
base_url: str,
):
"""Initialize CheckoutService."""
self.fulfillment_service = fulfillment_service
self.products_session = products_session
self.transactions_session = transactions_session
self.base_url = base_url.rstrip("/")
def _compute_hash(self, data: Any) -> str:
"""Compute SHA256 hash of the JSON-serialized data."""
if isinstance(data, BaseModel):
# Pydantic's optimized JSON dump
# sort_keys is not supported in model_dump_json in Pydantic V2.
# We dump to dict and use standard json.dumps for deterministic sorting.
json_str = json.dumps(data.model_dump(mode="json"), sort_keys=True)
else:
# sort_keys=True ensures deterministic hashing for dicts
json_str = json.dumps(data, sort_keys=True)
return hashlib.sha256(json_str.encode("utf-8")).hexdigest()
async def create_checkout(
self,
checkout_req: UnifiedCheckoutCreateRequest,
idempotency_key: str,
platform_config: PlatformConfig | None = None,
) -> Checkout:
"""Create a new checkout session."""
logger.info("Creating checkout session")
# Idempotency Check
request_hash = self._compute_hash(checkout_req)
existing_record = await db.get_idempotency_record(
self.transactions_session, idempotency_key
)
if existing_record:
if existing_record.request_hash != request_hash:
raise IdempotencyConflictError(
"Idempotency key reused with different parameters"
)
# Return cached response
return Checkout(**existing_record.response_body)
# Initialize full model from request
checkout_id = getattr(checkout_req, "id", None) or str(uuid.uuid4())
# Map line items
line_items = []
for li_req in checkout_req.line_items:
line_items.append(
LineItemResponse(
id=str(uuid.uuid4()),
item=ItemResponse(
id=li_req.item.id,
title=li_req.item.title,
price=0, # Will be set by recalculate_totals
),
quantity=li_req.quantity,
totals=[],
)
)
# We exclude fields that the service explicitly manages or overrides to
# avoid keyword argument conflicts when constructing the response model.
# By excluding only these 'base' fields, we allow extension fields (like
# 'buyer' or 'discounts') to pass through dynamically via **checkout_data.
#
# * Conflict Prevention: If we didn't exclude currency, id, or payment,
# passing them via **checkout_data while also specifying them as keyword
# arguments (e.g., currency=checkout_req.currency) would raise a
# TypeError: multiple values for keyword argument.
# * Server Authority: Fields like status, totals, and links might be
# present in a client request (even if they shouldn't be), but the server
# is the source of truth. We exclude them from the dumped data to ensure
# we start with a "clean" calculated state (e.g.,
# status=CheckoutStatus.IN_PROGRESS, totals=[]).
# * Model Transformation: ucp in the request is usually just version
# negotiation info, but in the response, it's a complex ResponseCheckout
# object with capability metadata. We exclude the request version to
# inject the full response object.
checkout_data = checkout_req.model_dump(
exclude={
"line_items",
"payment",
"ucp",
"currency",
"id",
"status",
"totals",
"links",
"fulfillment",
}
)
# Initialize fulfillment response
fulfillment_resp = None
if checkout_req.fulfillment:
req_fulfillment = checkout_req.fulfillment.root
resp_methods = []
all_li_ids = [li.id for li in line_items]
if req_fulfillment.methods:
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
)
method_type = getattr(method_req, "type", "shipping")
resp_groups = []
if method_req.groups:
for group_req in method_req.groups:
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
)
resp_groups.append(
FulfillmentGroupResponse(
id=group_id,
line_item_ids=group_li_ids,
selected_option_id=getattr(
group_req, "selected_option_id", None
),
)
)
# Convert destinations if present (usually empty on create, but
# handled for completeness)
resp_destinations = []
if method_req.destinations:
for dest_req in method_req.destinations:
# Assuming ShippingDestinationRequest can map to Response
# structure or needs conversion. For create, we typically accept
# ShippingDestinationRequest inside
# FulfillmentMethodCreateRequest. We need to convert it to
# FulfillmentDestinationResponse.
# The request model structure is complex
# (FulfillmentDestinationRequest -> ShippingDestinationRequest)
# The response model is FulfillmentDestinationResponse ->
# ShippingDestinationResponse
# Extract the inner ShippingDestinationRequest
inner_dest = dest_req.root
resp_destinations.append(
FulfillmentDestinationResponse(
root=ShippingDestinationResponse(
id=getattr(inner_dest, "id", None) or str(uuid.uuid4()),
address_country=inner_dest.address_country,
postal_code=inner_dest.postal_code,
address_region=inner_dest.address_region,
address_locality=inner_dest.address_locality,
street_address=inner_dest.street_address,
)
)
)
resp_methods.append(
FulfillmentMethodResponse(
id=method_id,
type=method_type,
line_item_ids=method_li_ids,
groups=resp_groups or None,
destinations=resp_destinations or None,
selected_destination_id=getattr(
method_req, "selected_destination_id", None
),
)
)
fulfillment_resp = FulfillmentResp(
root=FulfillmentResponse(methods=resp_methods)
)
checkout = Checkout(
ucp=ResponseCheckout(
version=Version(config.get_server_version()),
capabilities=[
Response(
name="dev.ucp.shopping.checkout",
version=Version(config.get_server_version()),
)
],
),
id=checkout_id,
status=CheckoutStatus.IN_PROGRESS,
currency=checkout_req.currency,
line_items=line_items,
totals=[],
links=[],
payment=PaymentResponse(
handlers=[],
selected_instrument_id=checkout_req.payment.selected_instrument_id,
instruments=checkout_req.payment.instruments,
),
platform=platform_config,
fulfillment=fulfillment_resp,
**checkout_data,
)
# Validate inventory and recalculate totals (Server is authority)
await self._recalculate_totals(checkout)
await self._validate_inventory(checkout)
checkout.status = CheckoutStatus.READY_FOR_COMPLETE
response_body = checkout.model_dump(mode="json", by_alias=True)
# Persist checkout to Transactions DB
await db.save_checkout(
self.transactions_session,
checkout.id,
checkout.status,
response_body,
)
# Save Idempotency Record
await db.save_idempotency_record(
self.transactions_session,
idempotency_key,
request_hash,
201, # Created
response_body,
)
await self.transactions_session.commit()
return checkout
async def get_checkout(
self,
checkout_id: str,
) -> Checkout:
"""Retrieve a checkout session."""
# Log the request
await db.log_request(
self.transactions_session,
method="GET",
url=f"/checkout-sessions/{checkout_id}",
checkout_id=checkout_id,
)
await self.transactions_session.commit()
return await self._get_and_validate_checkout(checkout_id)
async def update_checkout(
self,
checkout_id: str,
checkout_req: UnifiedCheckoutUpdateRequest,
idempotency_key: str,
platform_config: PlatformConfig | None = None,
) -> Checkout:
"""Update a checkout session."""
logger.info("Updating checkout session %s", checkout_id)
# Idempotency Check
request_hash = self._compute_hash(checkout_req)
existing_record = await db.get_idempotency_record(
self.transactions_session, idempotency_key
)
if existing_record:
if existing_record.request_hash != request_hash:
raise IdempotencyConflictError(
"Idempotency key reused with different parameters"
)
return Checkout(**existing_record.response_body)
# Log the request
payload_dict = checkout_req.model_dump(mode="json")
await db.log_request(
self.transactions_session,
method="PUT",
url=f"/checkout-sessions/{checkout_id}",
checkout_id=checkout_id,
payload=payload_dict,
)
existing = await self._get_and_validate_checkout(checkout_id)
self._ensure_modifiable(existing, "update")
# Update existing with request data
# This is a partial update logic
if checkout_req.line_items:
line_items = []
for li_req in checkout_req.line_items:
line_items.append(
LineItemResponse(
id=li_req.id or str(uuid.uuid4()),
item=ItemResponse(
id=li_req.item.id,
title=li_req.item.title,
price=0,
),
quantity=li_req.quantity,
totals=[],
parent_id=li_req.parent_id,
)
)
existing.line_items = line_items
if checkout_req.currency:
existing.currency = checkout_req.currency
if checkout_req.payment:
existing.payment = PaymentResponse(
handlers=existing.payment.handlers,
selected_instrument_id=checkout_req.payment.selected_instrument_id,
instruments=checkout_req.payment.instruments,
)
if checkout_req.buyer:
existing.buyer = checkout_req.buyer
if hasattr(checkout_req, "fulfillment") and checkout_req.fulfillment:
# Hierarchical fulfillment update
logging.info(
"Processing hierarchical fulfillment update for %s", checkout_id
)
# Fetch customer addresses if buyer is known
customer_addresses = []
if existing.buyer and existing.buyer.email:
customer_addresses = await db.get_customer_addresses(
self.transactions_session, existing.buyer.email
)
req_fulfillment = checkout_req.fulfillment
resp_methods = []
if req_fulfillment.root.methods:
logging.info(
"Request has %d methods", len(req_fulfillment.root.methods)
)
for m_req in req_fulfillment.root.methods:
# Find matching existing method to preserve state
existing_method = None
if existing.fulfillment and existing.fulfillment.root.methods:
existing_method = next(
(
m
for m in existing.fulfillment.root.methods
if m.id == getattr(m_req, "id", None)
),
None,
)
# Fallback: If no ID in request, and only 1 existing method, match
# it
if (
not existing_method
and not getattr(m_req, "id", None)
and len(existing.fulfillment.root.methods) == 1
):
existing_method = existing.fulfillment.root.methods[0]
# Resolve ID
method_id = getattr(m_req, "id", None)
if existing_method and not method_id:
method_id = existing_method.id
if not method_id:
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
]
resp_destinations = []
# Handle destinations
if method_type == "shipping":
if m_req.destinations:
# Use provided destinations
for dest_req in m_req.destinations:
# Extract inner dest
inner_dest = dest_req.root
dest_data = inner_dest.model_dump(exclude_none=True)
# Persist addresses for known customers
if existing.buyer and existing.buyer.email:
# Save and update ID
saved_id = await db.save_customer_address(
self.transactions_session,
existing.buyer.email,
dest_data,
)
dest_data["id"] = saved_id
resp_destinations.append(
FulfillmentDestinationResponse(
root=ShippingDestinationResponse(**dest_data)
)
)
elif existing_method and existing_method.destinations:
# Preserve existing destinations
resp_destinations = existing_method.destinations
elif customer_addresses:
for addr in customer_addresses:
resp_destinations.append(
FulfillmentDestinationResponse(
root=ShippingDestinationResponse(
id=addr.id,
street_address=addr.street_address,
city=addr.city,
region=addr.state, # Map state to region
postal_code=addr.postal_code,
address_country=addr.country,
)
)
)
# Handle groups
resp_groups = []
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
]
resp_groups.append(
FulfillmentGroupResponse(
id=g_id,
line_item_ids=g_li_ids,
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
# Construct the method response
method_resp = FulfillmentMethodResponse(
id=method_id,
type=method_type,
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
),
)
resp_methods.append(method_resp)
existing.fulfillment = FulfillmentResp(
root=FulfillmentResponse(
methods=resp_methods,
)
)
if checkout_req.discounts:
existing.discounts = checkout_req.discounts
if platform_config:
existing.platform = platform_config
# Validate inventory and recalculate totals (Server is authority)
await self._recalculate_totals(existing)
await self._validate_inventory(existing)
response_body = existing.model_dump(mode="json", by_alias=True)
await db.save_checkout(
self.transactions_session,
checkout_id,
existing.status,
response_body,
)
# Save Idempotency Record
await db.save_idempotency_record(
self.transactions_session,
idempotency_key,
request_hash,
200,
response_body,
)
await self.transactions_session.commit()
return existing
async def complete_checkout(
self,
checkout_id: str,
payment: PaymentCreateRequest,
risk_signals: dict[str, Any],
idempotency_key: str,
ap2: Ap2CompleteRequest | None = None,
) -> Checkout:
"""Complete a checkout session."""
logger.info("Completing checkout session %s", checkout_id)
# Idempotency Check
# Include risk_signals and ap2 in the hash
combined_data = {
"payment": payment.model_dump(mode="json"),
"risk_signals": risk_signals,
"ap2": ap2.model_dump(mode="json") if ap2 else None,
}
request_hash = self._compute_hash(combined_data)
existing_record = await db.get_idempotency_record(
self.transactions_session, idempotency_key
)
if existing_record:
if existing_record.request_hash != request_hash:
raise IdempotencyConflictError(
"Idempotency key reused with different parameters"
)
return Checkout(**existing_record.response_body)
# Log the request
await db.log_request(
self.transactions_session,
method="POST",
url=f"/checkout-sessions/{checkout_id}/complete",
checkout_id=checkout_id,
payload=combined_data,
)
checkout = await self._get_and_validate_checkout(checkout_id)
self._ensure_modifiable(checkout, "complete")
# Verify AP2 Mandate if present
if ap2:
self._verify_ap2_mandate(ap2)
# Process Payment
await self._process_payment(payment)
# Validate Fulfillment (Required for completion in this implementation)
fulfillment_valid = False
if checkout.fulfillment and checkout.fulfillment.root.methods:
for method in checkout.fulfillment.root.methods:
if method.type == "shipping" and not method.selected_destination_id:
continue
if method.groups:
for group in method.groups:
if group.selected_option_id:
fulfillment_valid = True
break
if fulfillment_valid:
break
if not fulfillment_valid:
raise InvalidRequestError(
"Fulfillment address and option must be selected before completion."
)
# Atomic Inventory Reservation + Order Completion
try:
for line in checkout.line_items:
product_id = line.item.id
# We verify product existence again (optional but good practice)
if await db.get_product(self.products_session, product_id):
success = await db.reserve_stock(
self.transactions_session, product_id, line.quantity
)
if not success:
# This rollback applies to the transaction_session
await self.transactions_session.rollback()
raise OutOfStockError(
f"Item {product_id} is out of stock", status_code=409
)
checkout.status = CheckoutStatus.COMPLETED
order_id = f"{uuid.uuid4()}"
order_permalink_url = AnyUrl(f"{self.base_url}/orders/{order_id}")
checkout.order = OrderConfirmation(
id=order_id, permalink_url=order_permalink_url
)
response_body = checkout.model_dump(mode="json", by_alias=True)
# Create and persist Order
expectations = []
if checkout.fulfillment and checkout.fulfillment.root.methods:
for method in checkout.fulfillment.root.methods:
selected_dest = None
if method.selected_destination_id and method.destinations:
for dest in method.destinations:
if dest.root.id == method.selected_destination_id:
# Convert ShippingDestination to PostalAddress for expectation
# Assuming simple mapping for now
dest_root = dest.root
selected_dest = PostalAddress(
street_address=dest_root.street_address,
address_locality=dest_root.address_locality,
address_region=dest_root.address_region,
postal_code=dest_root.postal_code,
address_country=dest_root.address_country,
)
break
if method.groups:
for group in method.groups:
if group.selected_option_id and group.options:
selected_opt = next(
(
o for o in group.options if o.id == group.selected_option_id
),
None,
)
if selected_opt:
expectation_id = f"exp_{uuid.uuid4()}"
# Filter line items for this group
# group.line_item_ids is list[str]
# We need to find quantity for each id
exp_line_items = []
for li in checkout.line_items:
if li.id in group.line_item_ids:
exp_line_items.append(
ExpectationLineItem(id=li.id, quantity=li.quantity)
)
expectations.append(
Expectation(
id=expectation_id,
line_items=exp_line_items,
method_type=method.type,
destination=selected_dest,
description=selected_opt.title,
)
)
order_line_items = []
for li in checkout.line_items:
# Create Quantity object for OrderLineItem
qty = order_line_item.Quantity(total=li.quantity, fulfilled=0)
oli = OrderLineItem(
id=li.id,
item=li.item,
quantity=qty,
totals=li.totals,
status="processing",
parent_id=li.parent_id,
)
order_line_items.append(oli)
order = Order(
ucp=ResponseOrder(**checkout.ucp.model_dump()),
id=checkout.order.id,
checkout_id=checkout.id,
permalink_url=checkout.order.permalink_url,
line_items=order_line_items,
totals=[
total_resp.TotalResponse(**t.model_dump()) for t in checkout.totals
],
fulfillment=OrderFulfillment(expectations=expectations, events=[]),
)
await db.save_order(
self.transactions_session,
order.id,
order.model_dump(mode="json", by_alias=True),
)
await db.save_checkout(
self.transactions_session,
checkout_id,
checkout.status,
response_body,
)
# Save Idempotency Record
await db.save_idempotency_record(
self.transactions_session,
idempotency_key,
request_hash,
200,
response_body,
)
# Commit both inventory updates and checkout status update atomically
await self.transactions_session.commit()
# Notify webhook of order placement
await self._notify_webhook(checkout, "order_placed")
except Exception as e:
await self.transactions_session.rollback()
raise e
return checkout
async def _notify_webhook(self, checkout: Checkout, event_type: str) -> None:
"""Notifies the configured webhook of an event."""
if not checkout.platform or not checkout.platform.webhook_url:
return
webhook_url = str(checkout.platform.webhook_url)
order_data = None
if checkout.order and checkout.order.id:
order_data = await db.get_order(
self.transactions_session, checkout.order.id
)
payload = {
"event_type": event_type,
"checkout_id": checkout.id,
"order": order_data,
}
try:
async with httpx.AsyncClient() as client:
await client.post(webhook_url, json=payload, timeout=5.0)
except Exception as e: # pylint: disable=broad-exception-caught
logger.error("Failed to notify webhook at %s: %s", webhook_url, e)
async def ship_order(self, order_id: str) -> None:
"""Simulate shipping an order and notifies the webhook."""
order_data = await db.get_order(self.transactions_session, order_id)
if not order_data:
raise ResourceNotFoundError("Order not found")
# Add shipping event to order
if "fulfillment" not in order_data:
order_data["fulfillment"] = {"events": []}
if (
"events" not in order_data["fulfillment"]
or order_data["fulfillment"]["events"] is None
):
order_data["fulfillment"]["events"] = []
event_id = f"evt_{uuid.uuid4()}"
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
order_data["fulfillment"]["events"].append(
{
"id": event_id,
"type": "shipped",
"timestamp": timestamp,
}
)
await db.save_order(self.transactions_session, order_id, order_data)
await self.transactions_session.commit()
# Get checkout to find webhook_url
checkout_id = order_data.get("checkout_id")
if checkout_id:
checkout = await self._get_and_validate_checkout(checkout_id)
await self._notify_webhook(checkout, "order_shipped")
async def cancel_checkout(
self,
checkout_id: str,
idempotency_key: str,
) -> Checkout:
"""Cancel a checkout session."""
logger.info("Canceling checkout session %s", checkout_id)
# Idempotency Check
# Payload is empty for cancel usually.
request_hash = self._compute_hash({})
existing_record = await db.get_idempotency_record(
self.transactions_session, idempotency_key
)
if existing_record:
if existing_record.request_hash != request_hash:
raise IdempotencyConflictError(
"Idempotency key reused with different parameters"
)
return Checkout(**existing_record.response_body)
# Log the request
await db.log_request(
self.transactions_session,
method="POST",
url=f"/checkout-sessions/{checkout_id}/cancel",
checkout_id=checkout_id,
)
checkout = await self._get_and_validate_checkout(checkout_id)
self._ensure_modifiable(checkout, "cancel")
checkout.status = CheckoutStatus.CANCELED
response_body = checkout.model_dump(mode="json", by_alias=True)
await db.save_checkout(
self.transactions_session,
checkout_id,
checkout.status,
response_body,
)
# Save Idempotency Record
await db.save_idempotency_record(
self.transactions_session,
idempotency_key,
request_hash,
200,
response_body,
)
await self.transactions_session.commit()
return checkout
async def get_order(
self,
order_id: str,
) -> dict[str, Any]:
"""Retrieve an order."""
data = await db.get_order(self.transactions_session, order_id)
if not data:
raise ResourceNotFoundError("Order not found")
return data
async def update_order(
self,
order_id: str,
order: dict[str, Any],
) -> dict[str, Any]:
"""Update an order."""
# Verify existence
await self.get_order(order_id)
# Persist
await db.save_order(
self.transactions_session,
order_id,
order,
)
await self.transactions_session.commit()
return order
async def _get_and_validate_checkout(self, checkout_id: str) -> Checkout:
"""Retrieve a checkout session and validates its existence."""
data = await db.get_checkout_session(self.transactions_session, checkout_id)
if not data:
raise ResourceNotFoundError("Checkout session not found")
return Checkout(**data)
def _ensure_modifiable(self, checkout: Checkout, action: str) -> None:
"""Ensure that the checkout is in a state that allows modification."""
if checkout.status in [CheckoutStatus.COMPLETED, CheckoutStatus.CANCELED]:
raise CheckoutNotModifiableError(
f"Cannot {action} checkout in state '{checkout.status}'"
)
async def _validate_inventory(
self,
checkout: Checkout,
) -> None:
"""Validate that all items in the checkout have sufficient stock."""
for line in checkout.line_items:
product_id = line.item.id
qty_avail = await db.get_inventory(self.transactions_session, product_id)
if qty_avail is None or qty_avail < line.quantity:
raise OutOfStockError(f"Insufficient stock for item {product_id}")
async def _recalculate_totals(
self,
checkout: Checkout,
) -> None:
"""Recalculate line item subtotals and checkout totals."""
grand_total = 0
for line in checkout.line_items:
product_id = line.item.id
product = await db.get_product(self.products_session, product_id)
if not product:
raise InvalidRequestError(f"Product {product_id} not found")
# Use authoritative price and title from DB