-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModels.swift
More file actions
5154 lines (4451 loc) · 183 KB
/
Copy pathModels.swift
File metadata and controls
5154 lines (4451 loc) · 183 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
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let checkout = try Checkout(json)
// let order = try Order(json)
// let errorResponse = try ErrorResponse(json)
// let instrumentsChangeResult = try InstrumentsChangeResult(json)
// let credentialResult = try CredentialResult(json)
// let addressChangeResult = try AddressChangeResult(json)
// let readyRequest = try ReadyRequest(json)
// let readyResult = try ReadyResult(json)
// let authRequest = try AuthRequest(json)
// let authResult = try AuthResult(json)
// let windowOpenRequest = try WindowOpenRequest(json)
// let windowOpenResult = try WindowOpenResult(json)
import Foundation
/// Base checkout schema. Extensions compose onto this using allOf.
// MARK: - Checkout
public struct Checkout: Codable, Sendable {
public let attribution: [String: String]?
/// Representation of the buyer.
public let buyer: Buyer?
public let context: Context?
/// URL for checkout handoff and session recovery. MUST be provided when status is
/// requires_escalation. See specification for format and availability requirements.
public let continueURL: String?
/// ISO 4217 currency code reflecting the merchant's market determination. Derived from
/// address, context, and geo IP—buyers provide signals, merchants determine currency.
public let currency: String
public let discounts: CheckoutDiscounts?
/// RFC 3339 expiry timestamp. Default TTL is 6 hours from creation if not sent.
public let expiresAt: Date?
/// Fulfillment details.
public let fulfillment: CheckoutFulfillment?
/// Unique identifier of the checkout session.
public let id: String
/// List of line items being checked out.
public let lineItems: [LineItem]
/// Links to be displayed by the platform (Privacy Policy, TOS). Mandatory for legal
/// compliance.
public let links: [Link]
/// List of messages with error and info about the checkout session state.
public let messages: [Message]?
/// Details about an order created for this checkout session.
public let order: OrderConfirmation?
public let payment: Payment?
public let signals: [String: JSONAny]?
/// Checkout state indicating the current phase and required action. See Checkout Status
/// lifecycle documentation for state transition details.
public let status: CheckoutStatus
/// Different cart totals.
public let totals: [CheckoutTotal]
public let ucp: UCPCheckoutResponseSchema
public enum CodingKeys: String, CodingKey {
case attribution, buyer, context
case continueURL = "continue_url"
case currency, discounts
case expiresAt = "expires_at"
case fulfillment, id
case lineItems = "line_items"
case links, messages, order, payment, signals, status, totals, ucp
}
public init(attribution: [String: String]?, buyer: Buyer?, context: Context?, continueURL: String?, currency: String, discounts: CheckoutDiscounts?, expiresAt: Date?, fulfillment: CheckoutFulfillment?, id: String, lineItems: [LineItem], links: [Link], messages: [Message]?, order: OrderConfirmation?, payment: Payment?, signals: [String: JSONAny]?, status: CheckoutStatus, totals: [CheckoutTotal], ucp: UCPCheckoutResponseSchema) {
self.attribution = attribution
self.buyer = buyer
self.context = context
self.continueURL = continueURL
self.currency = currency
self.discounts = discounts
self.expiresAt = expiresAt
self.fulfillment = fulfillment
self.id = id
self.lineItems = lineItems
self.links = links
self.messages = messages
self.order = order
self.payment = payment
self.signals = signals
self.status = status
self.totals = totals
self.ucp = ucp
}
public var additionalProperties: [String: JSONAny] = [:]
private static let knownAdditionalPropertyKeys: Set<String> = ["attribution", "buyer", "context", "continue_url", "currency", "discounts", "expires_at", "fulfillment", "id", "line_items", "links", "messages", "order", "payment", "signals", "status", "totals", "ucp"]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.attribution = try container.decodeIfPresent([String: String].self, forKey: .attribution)
self.buyer = try container.decodeIfPresent(Buyer.self, forKey: .buyer)
self.context = try container.decodeIfPresent(Context.self, forKey: .context)
self.continueURL = try container.decodeIfPresent(String.self, forKey: .continueURL)
self.currency = try container.decode(String.self, forKey: .currency)
self.discounts = try container.decodeIfPresent(CheckoutDiscounts.self, forKey: .discounts)
self.expiresAt = try container.decodeIfPresent(Date.self, forKey: .expiresAt)
self.fulfillment = try container.decodeIfPresent(CheckoutFulfillment.self, forKey: .fulfillment)
self.id = try container.decode(String.self, forKey: .id)
self.lineItems = try container.decode([LineItem].self, forKey: .lineItems)
self.links = try container.decode([Link].self, forKey: .links)
self.messages = try container.decodeIfPresent([Message].self, forKey: .messages)
self.order = try container.decodeIfPresent(OrderConfirmation.self, forKey: .order)
self.payment = try container.decodeIfPresent(Payment.self, forKey: .payment)
self.signals = try container.decodeIfPresent([String: JSONAny].self, forKey: .signals)
self.status = try container.decode(CheckoutStatus.self, forKey: .status)
self.totals = try container.decode([CheckoutTotal].self, forKey: .totals)
self.ucp = try container.decode(UCPCheckoutResponseSchema.self, forKey: .ucp)
let additionalContainer = try decoder.container(keyedBy: JSONCodingKey.self)
var extras: [String: JSONAny] = [:]
for key in additionalContainer.allKeys where !Self.knownAdditionalPropertyKeys.contains(key.stringValue) {
extras[key.stringValue] = try additionalContainer.decode(JSONAny.self, forKey: key)
}
self.additionalProperties = extras
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(attribution, forKey: .attribution)
try container.encodeIfPresent(buyer, forKey: .buyer)
try container.encodeIfPresent(context, forKey: .context)
try container.encodeIfPresent(continueURL, forKey: .continueURL)
try container.encode(currency, forKey: .currency)
try container.encodeIfPresent(discounts, forKey: .discounts)
try container.encodeIfPresent(expiresAt, forKey: .expiresAt)
try container.encodeIfPresent(fulfillment, forKey: .fulfillment)
try container.encode(id, forKey: .id)
try container.encode(lineItems, forKey: .lineItems)
try container.encode(links, forKey: .links)
try container.encodeIfPresent(messages, forKey: .messages)
try container.encodeIfPresent(order, forKey: .order)
try container.encodeIfPresent(payment, forKey: .payment)
try container.encodeIfPresent(signals, forKey: .signals)
try container.encode(status, forKey: .status)
try container.encode(totals, forKey: .totals)
try container.encode(ucp, forKey: .ucp)
var additionalContainer = encoder.container(keyedBy: JSONCodingKey.self)
for key in additionalProperties.keys.sorted() where !Self.knownAdditionalPropertyKeys.contains(key) {
try additionalContainer.encode(additionalProperties[key]!, forKey: JSONCodingKey(stringValue: key)!)
}
}
}
// MARK: Checkout convenience initializers and mutators
public extension Checkout {
init(data: Data) throws {
self = try newJSONDecoder().decode(Checkout.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
attribution: [String: String]?? = nil,
buyer: Buyer?? = nil,
context: Context?? = nil,
continueURL: String?? = nil,
currency: String? = nil,
discounts: CheckoutDiscounts?? = nil,
expiresAt: Date?? = nil,
fulfillment: CheckoutFulfillment?? = nil,
id: String? = nil,
lineItems: [LineItem]? = nil,
links: [Link]? = nil,
messages: [Message]?? = nil,
order: OrderConfirmation?? = nil,
payment: Payment?? = nil,
signals: [String: JSONAny]?? = nil,
status: CheckoutStatus? = nil,
totals: [CheckoutTotal]? = nil,
ucp: UCPCheckoutResponseSchema? = nil
) -> Checkout {
return Checkout(
attribution: attribution ?? self.attribution,
buyer: buyer ?? self.buyer,
context: context ?? self.context,
continueURL: continueURL ?? self.continueURL,
currency: currency ?? self.currency,
discounts: discounts ?? self.discounts,
expiresAt: expiresAt ?? self.expiresAt,
fulfillment: fulfillment ?? self.fulfillment,
id: id ?? self.id,
lineItems: lineItems ?? self.lineItems,
links: links ?? self.links,
messages: messages ?? self.messages,
order: order ?? self.order,
payment: payment ?? self.payment,
signals: signals ?? self.signals,
status: status ?? self.status,
totals: totals ?? self.totals,
ucp: ucp ?? self.ucp
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Representation of the buyer.
// MARK: - Buyer
public struct Buyer: Codable, Sendable {
/// Email of the buyer.
public let email: String?
/// First name of the buyer.
public let firstName: String?
/// Last name of the buyer.
public let lastName: String?
/// E.164 standard.
public let phoneNumber: String?
public enum CodingKeys: String, CodingKey {
case email
case firstName = "first_name"
case lastName = "last_name"
case phoneNumber = "phone_number"
}
public init(email: String?, firstName: String?, lastName: String?, phoneNumber: String?) {
self.email = email
self.firstName = firstName
self.lastName = lastName
self.phoneNumber = phoneNumber
}
public var additionalProperties: [String: JSONAny] = [:]
private static let knownAdditionalPropertyKeys: Set<String> = ["email", "first_name", "last_name", "phone_number"]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.email = try container.decodeIfPresent(String.self, forKey: .email)
self.firstName = try container.decodeIfPresent(String.self, forKey: .firstName)
self.lastName = try container.decodeIfPresent(String.self, forKey: .lastName)
self.phoneNumber = try container.decodeIfPresent(String.self, forKey: .phoneNumber)
let additionalContainer = try decoder.container(keyedBy: JSONCodingKey.self)
var extras: [String: JSONAny] = [:]
for key in additionalContainer.allKeys where !Self.knownAdditionalPropertyKeys.contains(key.stringValue) {
extras[key.stringValue] = try additionalContainer.decode(JSONAny.self, forKey: key)
}
self.additionalProperties = extras
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(email, forKey: .email)
try container.encodeIfPresent(firstName, forKey: .firstName)
try container.encodeIfPresent(lastName, forKey: .lastName)
try container.encodeIfPresent(phoneNumber, forKey: .phoneNumber)
var additionalContainer = encoder.container(keyedBy: JSONCodingKey.self)
for key in additionalProperties.keys.sorted() where !Self.knownAdditionalPropertyKeys.contains(key) {
try additionalContainer.encode(additionalProperties[key]!, forKey: JSONCodingKey(stringValue: key)!)
}
}
}
// MARK: Buyer convenience initializers and mutators
public extension Buyer {
init(data: Data) throws {
self = try newJSONDecoder().decode(Buyer.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
email: String?? = nil,
firstName: String?? = nil,
lastName: String?? = nil,
phoneNumber: String?? = nil
) -> Buyer {
return Buyer(
email: email ?? self.email,
firstName: firstName ?? self.firstName,
lastName: lastName ?? self.lastName,
phoneNumber: phoneNumber ?? self.phoneNumber
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Provisional buyer signals for relevance and localization—not authoritative data.
/// Businesses SHOULD use these values when verified inputs (e.g., shipping address) are
/// absent, and MAY ignore or down-rank them if inconsistent with higher-confidence signals
/// (authenticated account, risk detection) or regulatory constraints (export controls).
/// Eligibility and policy enforcement MUST occur at checkout time using binding transaction
/// data. Context SHOULD be non-identifying and can be disclosed progressively—coarse signals
/// early, finer resolution as the session progresses. Higher-resolution data (shipping
/// address, billing address) supersedes context.
// MARK: - Context
public struct Context: Codable, Sendable {
/// The country. Recommended to be in 2-letter ISO 3166-1 alpha-2 format, for example "US".
/// For backward compatibility, a 3-letter ISO 3166-1 alpha-3 country code such as "SGP" or a
/// full country name such as "Singapore" can also be used. Optional hint for market context
/// (currency, availability, pricing)—higher-resolution data (e.g., shipping address)
/// supersedes this value.
public let addressCountry: String?
/// The region in which the locality is, and which is in the country. For example, California
/// or another appropriate first-level Administrative division. Optional hint for progressive
/// localization—higher-resolution data (e.g., shipping address) supersedes this value.
public let addressRegion: String?
/// Preferred currency (ISO 4217, e.g., 'EUR', 'USD'). Businesses determine presentment
/// currency from context and authoritative signals; this hint MAY inform selection in
/// multi-currency markets. Also serves as the denomination for price filter values —
/// platforms SHOULD include this field when sending price filters. Response prices include
/// explicit currency confirming the resolution.
public let currency: String?
/// Buyer claims about eligible benefits such as loyalty membership, payment instrument
/// perks, and similar. Recognized claims MAY inform the Business response (e.g., member-only
/// product availability, adjusted pricing in catalog, provisional discounts at cart or
/// checkout). Businesses MUST ignore unrecognized values without error. Values MUST use
/// reverse-domain naming (e.g., 'com.example.loyalty_gold', 'org.school.student') and MUST
/// be non-identifying.
public let eligibility: [String]?
/// Background context describing buyer's intent (e.g., 'looking for a gift under $50', 'need
/// something durable for outdoor use'). Informs relevance, recommendations, and
/// personalization.
public let intent: String?
/// Preferred language for content. Use IETF BCP 47 language tags (e.g., 'en', 'fr-CA',
/// 'zh-Hans'). For REST, equivalent to Accept-Language header—platforms SHOULD fall back to
/// Accept-Language when this field is absent; when provided, overrides Accept-Language.
/// Businesses MAY return content in a different language if unavailable.
public let language: String?
/// The postal code. For example, 94043. Optional hint for regional
/// refinement—higher-resolution data (e.g., shipping address) supersedes this value.
public let postalCode: String?
public enum CodingKeys: String, CodingKey {
case addressCountry = "address_country"
case addressRegion = "address_region"
case currency, eligibility, intent, language
case postalCode = "postal_code"
}
public init(addressCountry: String?, addressRegion: String?, currency: String?, eligibility: [String]?, intent: String?, language: String?, postalCode: String?) {
self.addressCountry = addressCountry
self.addressRegion = addressRegion
self.currency = currency
self.eligibility = eligibility
self.intent = intent
self.language = language
self.postalCode = postalCode
}
public var additionalProperties: [String: JSONAny] = [:]
private static let knownAdditionalPropertyKeys: Set<String> = ["address_country", "address_region", "currency", "eligibility", "intent", "language", "postal_code"]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.addressCountry = try container.decodeIfPresent(String.self, forKey: .addressCountry)
self.addressRegion = try container.decodeIfPresent(String.self, forKey: .addressRegion)
self.currency = try container.decodeIfPresent(String.self, forKey: .currency)
self.eligibility = try container.decodeIfPresent([String].self, forKey: .eligibility)
self.intent = try container.decodeIfPresent(String.self, forKey: .intent)
self.language = try container.decodeIfPresent(String.self, forKey: .language)
self.postalCode = try container.decodeIfPresent(String.self, forKey: .postalCode)
let additionalContainer = try decoder.container(keyedBy: JSONCodingKey.self)
var extras: [String: JSONAny] = [:]
for key in additionalContainer.allKeys where !Self.knownAdditionalPropertyKeys.contains(key.stringValue) {
extras[key.stringValue] = try additionalContainer.decode(JSONAny.self, forKey: key)
}
self.additionalProperties = extras
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(addressCountry, forKey: .addressCountry)
try container.encodeIfPresent(addressRegion, forKey: .addressRegion)
try container.encodeIfPresent(currency, forKey: .currency)
try container.encodeIfPresent(eligibility, forKey: .eligibility)
try container.encodeIfPresent(intent, forKey: .intent)
try container.encodeIfPresent(language, forKey: .language)
try container.encodeIfPresent(postalCode, forKey: .postalCode)
var additionalContainer = encoder.container(keyedBy: JSONCodingKey.self)
for key in additionalProperties.keys.sorted() where !Self.knownAdditionalPropertyKeys.contains(key) {
try additionalContainer.encode(additionalProperties[key]!, forKey: JSONCodingKey(stringValue: key)!)
}
}
}
// MARK: Context convenience initializers and mutators
public extension Context {
init(data: Data) throws {
self = try newJSONDecoder().decode(Context.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
addressCountry: String?? = nil,
addressRegion: String?? = nil,
currency: String?? = nil,
eligibility: [String]?? = nil,
intent: String?? = nil,
language: String?? = nil,
postalCode: String?? = nil
) -> Context {
return Context(
addressCountry: addressCountry ?? self.addressCountry,
addressRegion: addressRegion ?? self.addressRegion,
currency: currency ?? self.currency,
eligibility: eligibility ?? self.eligibility,
intent: intent ?? self.intent,
language: language ?? self.language,
postalCode: postalCode ?? self.postalCode
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Discount codes input and applied discounts output.
// MARK: - CheckoutDiscounts
public struct CheckoutDiscounts: Codable, Sendable {
/// Discounts successfully applied (code-based and automatic).
public let applied: [AppliedDiscount]?
/// Discount codes to apply. Case-insensitive. Replaces previously submitted codes. Send
/// empty array to clear.
public let codes: [String]?
public init(applied: [AppliedDiscount]?, codes: [String]?) {
self.applied = applied
self.codes = codes
}
}
// MARK: CheckoutDiscounts convenience initializers and mutators
public extension CheckoutDiscounts {
init(data: Data) throws {
self = try newJSONDecoder().decode(CheckoutDiscounts.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
applied: [AppliedDiscount]?? = nil,
codes: [String]?? = nil
) -> CheckoutDiscounts {
return CheckoutDiscounts(
applied: applied ?? self.applied,
codes: codes ?? self.codes
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// A discount that was successfully applied.
// MARK: - AppliedDiscount
public struct AppliedDiscount: Codable, Sendable {
/// Breakdown of where this discount was allocated. Sum of allocation amounts equals total
/// amount.
public let allocations: [DiscountAllocation]?
/// Total discount amount in ISO 4217 minor units.
public let amount: Int
/// True if applied automatically by merchant rules (no code required).
public let automatic: Bool?
/// The discount code. Omitted for automatic discounts.
public let code: String?
/// The eligibility claim accepted by the Business for this discount. Corresponds to a value
/// from context.eligibility. Omitted for code-based and non-eligibility automatic discounts.
public let eligibility: String?
/// Allocation method. 'each' = applied independently per item. 'across' = split
/// proportionally by value.
public let method: DiscountMethod?
/// Stacking order for discount calculation. Lower numbers applied first (1 = first).
public let priority: Int?
/// True if this discount requires additional verification.
public let provisional: Bool?
/// Human-readable discount name (e.g., 'Summer Sale 20% Off').
public let title: String
public init(allocations: [DiscountAllocation]?, amount: Int, automatic: Bool?, code: String?, eligibility: String?, method: DiscountMethod?, priority: Int?, provisional: Bool?, title: String) {
self.allocations = allocations
self.amount = amount
self.automatic = automatic
self.code = code
self.eligibility = eligibility
self.method = method
self.priority = priority
self.provisional = provisional
self.title = title
}
}
// MARK: AppliedDiscount convenience initializers and mutators
public extension AppliedDiscount {
init(data: Data) throws {
self = try newJSONDecoder().decode(AppliedDiscount.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
allocations: [DiscountAllocation]?? = nil,
amount: Int? = nil,
automatic: Bool?? = nil,
code: String?? = nil,
eligibility: String?? = nil,
method: DiscountMethod?? = nil,
priority: Int?? = nil,
provisional: Bool?? = nil,
title: String? = nil
) -> AppliedDiscount {
return AppliedDiscount(
allocations: allocations ?? self.allocations,
amount: amount ?? self.amount,
automatic: automatic ?? self.automatic,
code: code ?? self.code,
eligibility: eligibility ?? self.eligibility,
method: method ?? self.method,
priority: priority ?? self.priority,
provisional: provisional ?? self.provisional,
title: title ?? self.title
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Breakdown of how a discount amount was allocated to a specific target.
// MARK: - DiscountAllocation
public struct DiscountAllocation: Codable, Sendable {
/// Amount allocated to this target in ISO 4217 minor units.
public let amount: Int
/// JSONPath to the allocation target (e.g., '$.line_items[0]', '$.totals.shipping').
public let path: String
public init(amount: Int, path: String) {
self.amount = amount
self.path = path
}
}
// MARK: DiscountAllocation convenience initializers and mutators
public extension DiscountAllocation {
init(data: Data) throws {
self = try newJSONDecoder().decode(DiscountAllocation.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
amount: Int? = nil,
path: String? = nil
) -> DiscountAllocation {
return DiscountAllocation(
amount: amount ?? self.amount,
path: path ?? self.path
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Allocation method. 'each' = applied independently per item. 'across' = split
/// proportionally by value.
public enum DiscountMethod: String, Codable, Sendable {
case across = "across"
case each = "each"
}
/// Fulfillment details.
///
/// Container for fulfillment methods and availability.
// MARK: - CheckoutFulfillment
public struct CheckoutFulfillment: Codable, Sendable {
/// Inventory availability hints.
public let availableMethods: [FulfillmentAvailableMethod]?
/// Fulfillment methods for cart items.
public let methods: [FulfillmentMethod]?
public enum CodingKeys: String, CodingKey {
case availableMethods = "available_methods"
case methods
}
public init(availableMethods: [FulfillmentAvailableMethod]?, methods: [FulfillmentMethod]?) {
self.availableMethods = availableMethods
self.methods = methods
}
}
// MARK: CheckoutFulfillment convenience initializers and mutators
public extension CheckoutFulfillment {
init(data: Data) throws {
self = try newJSONDecoder().decode(CheckoutFulfillment.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
availableMethods: [FulfillmentAvailableMethod]?? = nil,
methods: [FulfillmentMethod]?? = nil
) -> CheckoutFulfillment {
return CheckoutFulfillment(
availableMethods: availableMethods ?? self.availableMethods,
methods: methods ?? self.methods
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Inventory availability hint for a fulfillment method type.
// MARK: - FulfillmentAvailableMethod
public struct FulfillmentAvailableMethod: Codable, Sendable {
/// Human-readable availability info (e.g., 'Available for pickup at Downtown Store today').
public let description: String?
/// 'now' for immediate availability, or ISO 8601 date for future (preorders, transfers).
public let fulfillableOn: String?
/// Line items available for this fulfillment method.
public let lineItemIDS: [String]
/// Fulfillment method type this availability applies to.
public let type: FulfillmentMethodType
public enum CodingKeys: String, CodingKey {
case description
case fulfillableOn = "fulfillable_on"
case lineItemIDS = "line_item_ids"
case type
}
public init(description: String?, fulfillableOn: String?, lineItemIDS: [String], type: FulfillmentMethodType) {
self.description = description
self.fulfillableOn = fulfillableOn
self.lineItemIDS = lineItemIDS
self.type = type
}
public var additionalProperties: [String: JSONAny] = [:]
private static let knownAdditionalPropertyKeys: Set<String> = ["description", "fulfillable_on", "line_item_ids", "type"]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.description = try container.decodeIfPresent(String.self, forKey: .description)
self.fulfillableOn = try container.decodeIfPresent(String.self, forKey: .fulfillableOn)
self.lineItemIDS = try container.decode([String].self, forKey: .lineItemIDS)
self.type = try container.decode(FulfillmentMethodType.self, forKey: .type)
let additionalContainer = try decoder.container(keyedBy: JSONCodingKey.self)
var extras: [String: JSONAny] = [:]
for key in additionalContainer.allKeys where !Self.knownAdditionalPropertyKeys.contains(key.stringValue) {
extras[key.stringValue] = try additionalContainer.decode(JSONAny.self, forKey: key)
}
self.additionalProperties = extras
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(description, forKey: .description)
try container.encodeIfPresent(fulfillableOn, forKey: .fulfillableOn)
try container.encode(lineItemIDS, forKey: .lineItemIDS)
try container.encode(type, forKey: .type)
var additionalContainer = encoder.container(keyedBy: JSONCodingKey.self)
for key in additionalProperties.keys.sorted() where !Self.knownAdditionalPropertyKeys.contains(key) {
try additionalContainer.encode(additionalProperties[key]!, forKey: JSONCodingKey(stringValue: key)!)
}
}
}
// MARK: FulfillmentAvailableMethod convenience initializers and mutators
public extension FulfillmentAvailableMethod {
init(data: Data) throws {
self = try newJSONDecoder().decode(FulfillmentAvailableMethod.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
description: String?? = nil,
fulfillableOn: String?? = nil,
lineItemIDS: [String]? = nil,
type: FulfillmentMethodType? = nil
) -> FulfillmentAvailableMethod {
return FulfillmentAvailableMethod(
description: description ?? self.description,
fulfillableOn: fulfillableOn ?? self.fulfillableOn,
lineItemIDS: lineItemIDS ?? self.lineItemIDS,
type: type ?? self.type
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// Fulfillment method type this availability applies to.
///
/// Fulfillment method type.
public enum FulfillmentMethodType: String, Codable, Sendable {
case pickup = "pickup"
case shipping = "shipping"
}
/// A fulfillment method (shipping or pickup) with destinations and groups.
// MARK: - FulfillmentMethod
public struct FulfillmentMethod: Codable, Sendable {
/// Available destinations. For shipping: addresses. For pickup: retail locations.
public let destinations: [FulfillmentDestination]?
/// Fulfillment groups for selecting options. Agent sets selected_option_id on groups to
/// choose shipping method.
public let groups: [FulfillmentGroup]?
/// Unique fulfillment method identifier.
public let id: String
/// Line item IDs fulfilled via this method.
public let lineItemIDS: [String]
/// ID of the selected destination.
public let selectedDestinationID: String?
/// Fulfillment method type.
public let type: FulfillmentMethodType
public enum CodingKeys: String, CodingKey {
case destinations, groups, id
case lineItemIDS = "line_item_ids"
case selectedDestinationID = "selected_destination_id"
case type
}
public init(destinations: [FulfillmentDestination]?, groups: [FulfillmentGroup]?, id: String, lineItemIDS: [String], selectedDestinationID: String?, type: FulfillmentMethodType) {
self.destinations = destinations
self.groups = groups
self.id = id
self.lineItemIDS = lineItemIDS
self.selectedDestinationID = selectedDestinationID
self.type = type
}
public var additionalProperties: [String: JSONAny] = [:]
private static let knownAdditionalPropertyKeys: Set<String> = ["destinations", "groups", "id", "line_item_ids", "selected_destination_id", "type"]
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.destinations = try container.decodeIfPresent([FulfillmentDestination].self, forKey: .destinations)
self.groups = try container.decodeIfPresent([FulfillmentGroup].self, forKey: .groups)
self.id = try container.decode(String.self, forKey: .id)
self.lineItemIDS = try container.decode([String].self, forKey: .lineItemIDS)
self.selectedDestinationID = try container.decodeIfPresent(String.self, forKey: .selectedDestinationID)
self.type = try container.decode(FulfillmentMethodType.self, forKey: .type)
let additionalContainer = try decoder.container(keyedBy: JSONCodingKey.self)
var extras: [String: JSONAny] = [:]
for key in additionalContainer.allKeys where !Self.knownAdditionalPropertyKeys.contains(key.stringValue) {
extras[key.stringValue] = try additionalContainer.decode(JSONAny.self, forKey: key)
}
self.additionalProperties = extras
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(destinations, forKey: .destinations)
try container.encodeIfPresent(groups, forKey: .groups)
try container.encode(id, forKey: .id)
try container.encode(lineItemIDS, forKey: .lineItemIDS)
try container.encodeIfPresent(selectedDestinationID, forKey: .selectedDestinationID)
try container.encode(type, forKey: .type)
var additionalContainer = encoder.container(keyedBy: JSONCodingKey.self)
for key in additionalProperties.keys.sorted() where !Self.knownAdditionalPropertyKeys.contains(key) {
try additionalContainer.encode(additionalProperties[key]!, forKey: JSONCodingKey(stringValue: key)!)
}
}
}
// MARK: FulfillmentMethod convenience initializers and mutators
public extension FulfillmentMethod {
init(data: Data) throws {
self = try newJSONDecoder().decode(FulfillmentMethod.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
destinations: [FulfillmentDestination]?? = nil,
groups: [FulfillmentGroup]?? = nil,
id: String? = nil,
lineItemIDS: [String]? = nil,
selectedDestinationID: String?? = nil,
type: FulfillmentMethodType? = nil
) -> FulfillmentMethod {
return FulfillmentMethod(
destinations: destinations ?? self.destinations,
groups: groups ?? self.groups,
id: id ?? self.id,
lineItemIDS: lineItemIDS ?? self.lineItemIDS,
selectedDestinationID: selectedDestinationID ?? self.selectedDestinationID,
type: type ?? self.type
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
/// A destination for fulfillment.
///
/// Shipping destination.
///
/// Physical address of the location.
///
/// The billing address associated with this payment method.
///
/// Delivery destination address.
///
/// A pickup location (retail store, locker, etc.).
// MARK: - FulfillmentDestination
public struct FulfillmentDestination: Codable, Sendable {
/// The country. Recommended to be in 2-letter ISO 3166-1 alpha-2 format, for example "US".
/// For backward compatibility, a 3-letter ISO 3166-1 alpha-3 country code such as "SGP" or a
/// full country name such as "Singapore" can also be used.
public let addressCountry: String?
/// The locality in which the street address is, and which is in the region. For example,
/// Mountain View.
public let addressLocality: String?
/// The region in which the locality is, and which is in the country. Required for applicable
/// countries (i.e. state in US, province in CA). For example, California or another
/// appropriate first-level Administrative division.
public let addressRegion: String?
/// An address extension such as an apartment number, C/O or alternative name.
public let extendedAddress: String?
/// Optional. First name of the contact associated with the address.
public let firstName: String?
/// Optional. Last name of the contact associated with the address.
public let lastName: String?
/// Optional. Phone number of the contact associated with the address.
public let phoneNumber: String?
/// The postal code. For example, 94043.
public let postalCode: String?
/// The street address.
public let streetAddress: String?
/// ID specific to this shipping destination.
///
/// Unique location identifier.
public let id: String
/// Physical address of the location.
public let address: PostalAddress?
/// Location name (e.g., store name).
public let name: String?
public enum CodingKeys: String, CodingKey {
case addressCountry = "address_country"
case addressLocality = "address_locality"
case addressRegion = "address_region"
case extendedAddress = "extended_address"
case firstName = "first_name"
case lastName = "last_name"
case phoneNumber = "phone_number"
case postalCode = "postal_code"
case streetAddress = "street_address"
case id, address, name
}
public init(addressCountry: String?, addressLocality: String?, addressRegion: String?, extendedAddress: String?, firstName: String?, lastName: String?, phoneNumber: String?, postalCode: String?, streetAddress: String?, id: String, address: PostalAddress?, name: String?) {
self.addressCountry = addressCountry
self.addressLocality = addressLocality
self.addressRegion = addressRegion
self.extendedAddress = extendedAddress
self.firstName = firstName