Skip to main content

storekit/
advanced_commerce.rs

1use core::ffi::c_void;
2use core::ptr;
3
4use serde::{Deserialize, Serialize};
5
6use crate::app_store::AppStore;
7use crate::error::StoreKitError;
8use crate::ffi;
9use crate::private::{
10    cstring_from_str, error_from_status, json_cstring, json_error, parse_json_ptr,
11};
12use crate::product::ProductType;
13use crate::purchase_option::{PurchaseResult, PurchaseResultPayload};
14use crate::renewal_info::RenewalInfo;
15use crate::subscription::{SubscriptionPeriod, SubscriptionPeriodPayload};
16use crate::transaction::{Transaction, TransactionHandle, TransactionStream};
17use crate::verification_result::VerificationResult;
18use crate::window::NSWindowHandle;
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21#[serde(tag = "kind", rename_all = "camelCase")]
22/// Represents the merchandising kind requested from `StoreKit.AppStore`.
23pub enum AppStoreMerchandisingKind {
24    /// Represents the `SubscriptionBundle` `StoreKit` case.
25    SubscriptionBundle {
26        #[serde(rename = "groupID")]
27        /// Subscription group identifier reported by `StoreKit`.
28        group_id: String,
29    },
30}
31
32impl AppStoreMerchandisingKind {
33    /// Builds the `StoreKit` merchandising request for a subscription bundle.
34    pub fn subscription_bundle(group_id: impl Into<String>) -> Self {
35        Self::SubscriptionBundle {
36            group_id: group_id.into(),
37        }
38    }
39}
40
41#[derive(Debug)]
42#[allow(clippy::large_enum_variant)]
43/// Represents the result returned by `StoreKit` merchandising presentation APIs.
44pub enum AppStoreMerchandisingPresentationResult {
45    /// Represents the `Dismissed` `StoreKit` case.
46    Dismissed,
47    /// The merchandising flow completed with a purchase result.
48    PurchaseCompleted(PurchaseResult),
49}
50
51impl AppStore {
52    /// Fetches the age rating code reported by `StoreKit`.
53    pub fn age_rating_code() -> Result<Option<i64>, StoreKitError> {
54        let mut raw_value = 0_i64;
55        let mut has_value = 0;
56        let mut error_message = ptr::null_mut();
57        let status = unsafe {
58            ffi::sk_app_store_age_rating_code(
59                &raw mut raw_value,
60                &raw mut has_value,
61                &raw mut error_message,
62            )
63        };
64        if status == ffi::status::OK {
65            Ok((has_value != 0).then_some(raw_value))
66        } else {
67            Err(unsafe { error_from_status(status, error_message) })
68        }
69    }
70
71    /// Presents `StoreKit` merchandising UI in the supplied window.
72    pub fn present_merchandising(
73        kind: &AppStoreMerchandisingKind,
74        window: &NSWindowHandle,
75    ) -> Result<AppStoreMerchandisingPresentationResult, StoreKitError> {
76        let kind_json = json_cstring(kind, "App Store merchandising kind")?;
77        let mut transaction_handle: *mut c_void = ptr::null_mut();
78        let mut result_json = ptr::null_mut();
79        let mut error_message = ptr::null_mut();
80        let status = unsafe {
81            ffi::sk_app_store_present_merchandising(
82                kind_json.as_ptr(),
83                window.as_raw(),
84                &raw mut transaction_handle,
85                &raw mut result_json,
86                &raw mut error_message,
87            )
88        };
89        if status != ffi::status::OK {
90            return Err(unsafe { error_from_status(status, error_message) });
91        }
92        let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
93        let payload = unsafe {
94            parse_json_ptr::<AppStoreMerchandisingPresentationResultPayload>(
95                result_json,
96                "App Store merchandising presentation result",
97            )
98        }?;
99        payload.into_result(transaction_handle)
100    }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
104#[serde(tag = "kind", rename_all = "camelCase")]
105/// Represents advanced-commerce options forwarded to `StoreKit` purchase APIs.
106pub enum AdvancedCommercePurchaseOption {
107    /// Represents the `OnStorefrontChange` `StoreKit` case.
108    OnStorefrontChange {
109        #[serde(rename = "shouldContinuePurchase")]
110        /// Value forwarded to `StoreKit` for `should_continue_purchase`.
111        should_continue_purchase: bool,
112    },
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
116/// Wraps a `StoreKit` advanced-commerce product.
117pub struct AdvancedCommerceProduct {
118    /// `StoreKit` identifier for this value.
119    pub id: String,
120    /// Product type reported by `StoreKit`.
121    pub product_type: ProductType,
122}
123
124impl AdvancedCommerceProduct {
125    /// Fetches the `StoreKit` advanced-commerce product for the supplied identifier.
126    pub fn new(id: &str) -> Result<Self, StoreKitError> {
127        let product_id = cstring_from_str(id, "advanced commerce product id")?;
128        let mut product_json = ptr::null_mut();
129        let mut error_message = ptr::null_mut();
130        let status = unsafe {
131            ffi::sk_advanced_commerce_product_json(
132                product_id.as_ptr(),
133                &raw mut product_json,
134                &raw mut error_message,
135            )
136        };
137        if status != ffi::status::OK {
138            return Err(unsafe { error_from_status(status, error_message) });
139        }
140        let payload = unsafe {
141            parse_json_ptr::<AdvancedCommerceProductPayload>(
142                product_json,
143                "advanced commerce product",
144            )
145        }?;
146        Ok(payload.into_product())
147    }
148
149    /// Calls the `StoreKit` advanced-commerce purchase API while presenting UI in the supplied `NSWindow`.
150    pub fn purchase_in_window(
151        &self,
152        compact_jws: &str,
153        window: &NSWindowHandle,
154        options: &[AdvancedCommercePurchaseOption],
155    ) -> Result<PurchaseResult, StoreKitError> {
156        let product_id = cstring_from_str(&self.id, "advanced commerce product id")?;
157        let compact_jws = cstring_from_str(compact_jws, "advanced commerce compact JWS")?;
158        let options_json = json_cstring(options, "advanced commerce purchase options")?;
159        let mut transaction_handle: *mut c_void = ptr::null_mut();
160        let mut result_json = ptr::null_mut();
161        let mut error_message = ptr::null_mut();
162        let status = unsafe {
163            ffi::sk_advanced_commerce_product_purchase(
164                product_id.as_ptr(),
165                compact_jws.as_ptr(),
166                window.as_raw(),
167                options_json.as_ptr(),
168                &raw mut transaction_handle,
169                &raw mut result_json,
170                &raw mut error_message,
171            )
172        };
173        if status != ffi::status::OK {
174            return Err(unsafe { error_from_status(status, error_message) });
175        }
176        let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
177
178        unsafe {
179            parse_json_ptr::<PurchaseResultPayload>(
180                result_json,
181                "advanced commerce purchase result",
182            )
183        }?
184        .into_purchase_result(transaction_handle)
185    }
186
187    /// Fetches the latest `StoreKit` transaction for this advanced-commerce product.
188    pub fn latest_transaction(
189        &self,
190    ) -> Result<Option<VerificationResult<Transaction>>, StoreKitError> {
191        Transaction::latest_for(&self.id)
192    }
193
194    /// Creates a stream of all `StoreKit` transactions for this advanced-commerce product.
195    pub fn all_transactions(&self) -> Result<TransactionStream, StoreKitError> {
196        Transaction::all_for(&self.id)
197    }
198
199    /// Creates a stream of current `StoreKit` entitlements for this advanced-commerce product.
200    pub fn current_entitlements(&self) -> Result<TransactionStream, StoreKitError> {
201        Transaction::current_entitlements_for(&self.id)
202    }
203}
204
205#[derive(Debug, Clone, PartialEq, Eq)]
206/// Carries advanced-commerce metadata attached to `StoreKit.Transaction`.
207pub struct TransactionAdvancedCommerceInfo {
208    /// Request reference identifier reported by `StoreKit`.
209    pub request_reference_id: String,
210    /// Estimated tax reported by `StoreKit`.
211    pub estimated_tax: String,
212    /// Tax rate reported by `StoreKit`.
213    pub tax_rate: String,
214    /// Tax code reported by `StoreKit`.
215    pub tax_code: String,
216    /// Tax-exclusive price reported by `StoreKit`.
217    pub tax_exclusive_price: String,
218    /// Description reported by `StoreKit`.
219    pub description: Option<String>,
220    /// Display name reported by `StoreKit`.
221    pub display_name: Option<String>,
222    /// Subscription period reported by `StoreKit`.
223    pub period: Option<SubscriptionPeriod>,
224    /// Nested items reported by `StoreKit`.
225    pub items: Vec<TransactionAdvancedCommerceItem>,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
229/// Carries an advanced-commerce item attached to `StoreKit.Transaction`.
230pub struct TransactionAdvancedCommerceItem {
231    /// Detailed item payload reported by `StoreKit`.
232    pub details: TransactionAdvancedCommerceItemDetails,
233    /// Refund details reported by `StoreKit`.
234    pub refunds: Option<Vec<TransactionAdvancedCommerceRefund>>,
235    /// Revocation date reported by `StoreKit`.
236    pub revocation_date: Option<String>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq)]
240/// Carries detail fields for an advanced-commerce item returned by `StoreKit`.
241pub struct TransactionAdvancedCommerceItemDetails {
242    /// SKU reported by `StoreKit`.
243    pub sku: String,
244    /// Display name reported by `StoreKit`.
245    pub display_name: String,
246    /// Description reported by `StoreKit`.
247    pub description: String,
248    /// Offer metadata reported by `StoreKit`.
249    pub offer: Option<TransactionAdvancedCommerceOffer>,
250    /// Price reported by `StoreKit`.
251    pub price: String,
252}
253
254#[derive(Debug, Clone, PartialEq, Eq)]
255/// Carries advanced-commerce offer data attached to `StoreKit.Transaction`.
256pub struct TransactionAdvancedCommerceOffer {
257    /// Price reported by `StoreKit`.
258    pub price: String,
259    /// Subscription period reported by `StoreKit`.
260    pub period: SubscriptionPeriod,
261    /// Number of periods reported by `StoreKit`.
262    pub period_count: i64,
263    /// Reason reported by `StoreKit`.
264    pub reason: TransactionAdvancedCommerceOfferReason,
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268/// Wraps advanced-commerce offer reasons returned by `StoreKit`.
269pub enum TransactionAdvancedCommerceOfferReason {
270    /// Represents the `Acquisition` `StoreKit` case.
271    Acquisition,
272    /// Represents the `Retention` `StoreKit` case.
273    Retention,
274    /// Represents the `WinBack` `StoreKit` case.
275    WinBack,
276    /// Preserves an unrecognized `StoreKit` case.
277    Unknown(String),
278}
279
280impl TransactionAdvancedCommerceOfferReason {
281    /// Returns the raw `StoreKit` string for this advanced-commerce offer reason.
282    pub fn as_str(&self) -> &str {
283        match self {
284            Self::Acquisition => "acquisition",
285            Self::Retention => "retention",
286            Self::WinBack => "winBack",
287            Self::Unknown(value) => value.as_str(),
288        }
289    }
290
291    fn from_raw(raw: String) -> Self {
292        match raw.as_str() {
293            "acquisition" => Self::Acquisition,
294            "retention" => Self::Retention,
295            "winBack" => Self::WinBack,
296            _ => Self::Unknown(raw),
297        }
298    }
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
302/// Carries advanced-commerce refund details returned by `StoreKit`.
303pub struct TransactionAdvancedCommerceRefund {
304    /// Reason reported by `StoreKit`.
305    pub reason: TransactionAdvancedCommerceRefundReason,
306    /// Refund type reported by `StoreKit`.
307    pub refund_type: TransactionAdvancedCommerceRefundType,
308    /// Date reported by `StoreKit`.
309    pub date: String,
310    /// Amount reported by `StoreKit`.
311    pub amount: String,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
315/// Wraps advanced-commerce refund reasons returned by `StoreKit`.
316pub enum TransactionAdvancedCommerceRefundReason {
317    /// Represents the `Legal` `StoreKit` case.
318    Legal,
319    /// Represents the `ModifyItems` `StoreKit` case.
320    ModifyItems,
321    /// Represents the `Unintended` `StoreKit` case.
322    Unintended,
323    /// Represents the `Unfulfilled` `StoreKit` case.
324    Unfulfilled,
325    /// Represents the `Unsatisfied` `StoreKit` case.
326    Unsatisfied,
327    /// Represents the `other` `StoreKit` case.
328    Other,
329    /// Preserves an unrecognized `StoreKit` case.
330    Unknown(String),
331}
332
333impl TransactionAdvancedCommerceRefundReason {
334    /// Returns the raw `StoreKit` string for this advanced-commerce refund reason.
335    pub fn as_str(&self) -> &str {
336        match self {
337            Self::Legal => "legal",
338            Self::ModifyItems => "modifyItems",
339            Self::Unintended => "unintended",
340            Self::Unfulfilled => "unfulfilled",
341            Self::Unsatisfied => "unsatisfied",
342            Self::Other => "other",
343            Self::Unknown(value) => value.as_str(),
344        }
345    }
346
347    fn from_raw(raw: String) -> Self {
348        match raw.as_str() {
349            "legal" => Self::Legal,
350            "modifyItems" => Self::ModifyItems,
351            "unintended" => Self::Unintended,
352            "unfulfilled" => Self::Unfulfilled,
353            "unsatisfied" => Self::Unsatisfied,
354            "other" => Self::Other,
355            _ => Self::Unknown(raw),
356        }
357    }
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
361/// Wraps advanced-commerce refund types returned by `StoreKit`.
362pub enum TransactionAdvancedCommerceRefundType {
363    /// Represents the `Custom` `StoreKit` case.
364    Custom,
365    /// Represents the `ProRated` `StoreKit` case.
366    ProRated,
367    /// Represents the `Full` `StoreKit` case.
368    Full,
369    /// Preserves an unrecognized `StoreKit` case.
370    Unknown(String),
371}
372
373impl TransactionAdvancedCommerceRefundType {
374    /// Returns the raw `StoreKit` string for this advanced-commerce refund type.
375    pub fn as_str(&self) -> &str {
376        match self {
377            Self::Custom => "custom",
378            Self::ProRated => "proRated",
379            Self::Full => "full",
380            Self::Unknown(value) => value.as_str(),
381        }
382    }
383
384    fn from_raw(raw: String) -> Self {
385        match raw.as_str() {
386            "custom" => Self::Custom,
387            "proRated" => Self::ProRated,
388            "full" => Self::Full,
389            _ => Self::Unknown(raw),
390        }
391    }
392}
393
394#[derive(Debug, Clone, PartialEq, Eq)]
395/// Carries advanced-commerce metadata attached to `StoreKit.RenewalInfo`.
396pub struct RenewalInfoAdvancedCommerceInfo {
397    /// Consistency token reported by `StoreKit`.
398    pub consistency_token: String,
399    /// Request reference identifier reported by `StoreKit`.
400    pub request_reference_id: String,
401    /// Tax code reported by `StoreKit`.
402    pub tax_code: String,
403    /// Description reported by `StoreKit`.
404    pub description: String,
405    /// Display name reported by `StoreKit`.
406    pub display_name: String,
407    /// Subscription period reported by `StoreKit`.
408    pub period: SubscriptionPeriod,
409    /// Nested items reported by `StoreKit`.
410    pub items: Vec<RenewalInfoAdvancedCommerceItem>,
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
414/// Carries an advanced-commerce renewal item returned by `StoreKit`.
415pub struct RenewalInfoAdvancedCommerceItem {
416    /// Detailed item payload reported by `StoreKit`.
417    pub details: TransactionAdvancedCommerceItemDetails,
418    /// Price increase details reported by `StoreKit`.
419    pub price_increase_info: Option<RenewalInfoAdvancedCommercePriceIncreaseInfo>,
420}
421
422#[derive(Debug, Clone, PartialEq, Eq)]
423/// Carries advanced-commerce price increase details returned by `StoreKit`.
424pub struct RenewalInfoAdvancedCommercePriceIncreaseInfo {
425    /// Status reported by `StoreKit`.
426    pub status: RenewalInfoAdvancedCommercePriceIncreaseStatus,
427    /// Price reported by `StoreKit`.
428    pub price: String,
429    /// Dependent SKUs reported by `StoreKit`.
430    pub dependent_skus: Vec<String>,
431}
432
433#[derive(Debug, Clone, PartialEq, Eq)]
434/// Wraps advanced-commerce price increase states returned by `StoreKit`.
435pub enum RenewalInfoAdvancedCommercePriceIncreaseStatus {
436    /// The `StoreKit` flow is pending further action.
437    Pending,
438    /// Represents the `Accepted` `StoreKit` case.
439    Accepted,
440    /// Represents the `Scheduled` `StoreKit` case.
441    Scheduled,
442    /// Preserves an unrecognized `StoreKit` case.
443    Unknown(String),
444}
445
446impl RenewalInfoAdvancedCommercePriceIncreaseStatus {
447    /// Returns the raw `StoreKit` string for this advanced-commerce price increase status.
448    pub fn as_str(&self) -> &str {
449        match self {
450            Self::Pending => "pending",
451            Self::Accepted => "accepted",
452            Self::Scheduled => "scheduled",
453            Self::Unknown(value) => value.as_str(),
454        }
455    }
456
457    fn from_raw(raw: String) -> Self {
458        match raw.as_str() {
459            "pending" => Self::Pending,
460            "accepted" => Self::Accepted,
461            "scheduled" => Self::Scheduled,
462            _ => Self::Unknown(raw),
463        }
464    }
465}
466
467impl VerificationResult<Transaction> {
468    /// Returns advanced-commerce metadata decoded from the `StoreKit.Transaction` payload.
469    pub fn advanced_commerce_info(
470        &self,
471    ) -> Result<Option<TransactionAdvancedCommerceInfo>, StoreKitError> {
472        self.payload_value()?;
473        parse_transaction_advanced_commerce_info_payload(&self.metadata().payload_data)
474    }
475}
476
477impl VerificationResult<RenewalInfo> {
478    /// Returns advanced-commerce metadata decoded from the `StoreKit.RenewalInfo` payload.
479    pub fn advanced_commerce_info(
480        &self,
481    ) -> Result<Option<RenewalInfoAdvancedCommerceInfo>, StoreKitError> {
482        self.payload_value()?;
483        parse_renewal_advanced_commerce_info_payload(&self.metadata().payload_data)
484    }
485}
486
487#[derive(Debug, Deserialize)]
488pub(crate) struct TransactionAdvancedCommerceInfoPayload {
489    #[serde(rename = "requestReferenceID")]
490    request_reference_id: String,
491    #[serde(rename = "estimatedTax")]
492    estimated_tax: String,
493    #[serde(rename = "taxRate")]
494    tax_rate: String,
495    #[serde(rename = "taxCode")]
496    tax_code: String,
497    #[serde(rename = "taxExclusivePrice")]
498    tax_exclusive_price: String,
499    description: Option<String>,
500    #[serde(rename = "displayName")]
501    display_name: Option<String>,
502    period: Option<SubscriptionPeriodPayload>,
503    items: Vec<TransactionAdvancedCommerceItemPayload>,
504}
505
506impl TransactionAdvancedCommerceInfoPayload {
507    pub(crate) fn into_transaction_advanced_commerce_info(self) -> TransactionAdvancedCommerceInfo {
508        TransactionAdvancedCommerceInfo {
509            request_reference_id: self.request_reference_id,
510            estimated_tax: self.estimated_tax,
511            tax_rate: self.tax_rate,
512            tax_code: self.tax_code,
513            tax_exclusive_price: self.tax_exclusive_price,
514            description: self.description,
515            display_name: self.display_name,
516            period: self
517                .period
518                .map(SubscriptionPeriodPayload::into_subscription_period),
519            items: self
520                .items
521                .into_iter()
522                .map(
523                    TransactionAdvancedCommerceItemPayload::into_transaction_advanced_commerce_item,
524                )
525                .collect(),
526        }
527    }
528}
529
530#[derive(Debug, Deserialize)]
531struct TransactionAdvancedCommerceItemPayload {
532    details: TransactionAdvancedCommerceItemDetailsPayload,
533    refunds: Option<Vec<TransactionAdvancedCommerceRefundPayload>>,
534    #[serde(rename = "revocationDate")]
535    revocation_date: Option<String>,
536}
537
538impl TransactionAdvancedCommerceItemPayload {
539    fn into_transaction_advanced_commerce_item(self) -> TransactionAdvancedCommerceItem {
540        TransactionAdvancedCommerceItem {
541            details: self.details.into_transaction_advanced_commerce_item_details(),
542            refunds: self.refunds.map(|refunds| {
543                refunds
544                    .into_iter()
545                    .map(TransactionAdvancedCommerceRefundPayload::into_transaction_advanced_commerce_refund)
546                    .collect()
547            }),
548            revocation_date: self.revocation_date,
549        }
550    }
551}
552
553#[derive(Debug, Deserialize)]
554struct TransactionAdvancedCommerceItemDetailsPayload {
555    sku: String,
556    #[serde(rename = "displayName")]
557    display_name: String,
558    description: String,
559    offer: Option<TransactionAdvancedCommerceOfferPayload>,
560    price: String,
561}
562
563impl TransactionAdvancedCommerceItemDetailsPayload {
564    fn into_transaction_advanced_commerce_item_details(
565        self,
566    ) -> TransactionAdvancedCommerceItemDetails {
567        TransactionAdvancedCommerceItemDetails {
568            sku: self.sku,
569            display_name: self.display_name,
570            description: self.description,
571            offer: self.offer.map(
572                TransactionAdvancedCommerceOfferPayload::into_transaction_advanced_commerce_offer,
573            ),
574            price: self.price,
575        }
576    }
577}
578
579#[derive(Debug, Deserialize)]
580struct TransactionAdvancedCommerceOfferPayload {
581    price: String,
582    period: SubscriptionPeriodPayload,
583    #[serde(rename = "periodCount")]
584    period_count: i64,
585    reason: String,
586}
587
588impl TransactionAdvancedCommerceOfferPayload {
589    fn into_transaction_advanced_commerce_offer(self) -> TransactionAdvancedCommerceOffer {
590        TransactionAdvancedCommerceOffer {
591            price: self.price,
592            period: self.period.into_subscription_period(),
593            period_count: self.period_count,
594            reason: TransactionAdvancedCommerceOfferReason::from_raw(self.reason),
595        }
596    }
597}
598
599#[derive(Debug, Deserialize)]
600struct TransactionAdvancedCommerceRefundPayload {
601    reason: String,
602    #[serde(rename = "type")]
603    refund_type: String,
604    date: String,
605    amount: String,
606}
607
608impl TransactionAdvancedCommerceRefundPayload {
609    fn into_transaction_advanced_commerce_refund(self) -> TransactionAdvancedCommerceRefund {
610        TransactionAdvancedCommerceRefund {
611            reason: TransactionAdvancedCommerceRefundReason::from_raw(self.reason),
612            refund_type: TransactionAdvancedCommerceRefundType::from_raw(self.refund_type),
613            date: self.date,
614            amount: self.amount,
615        }
616    }
617}
618
619#[derive(Debug, Deserialize)]
620struct RenewalSignedPayload {
621    #[serde(rename = "advancedCommerceInfo")]
622    advanced_commerce_info: Option<RenewalInfoAdvancedCommerceInfoPayload>,
623}
624
625#[derive(Debug, Deserialize)]
626struct RenewalInfoAdvancedCommerceInfoPayload {
627    #[serde(rename = "consistencyToken")]
628    consistency_token: String,
629    #[serde(rename = "requestReferenceID")]
630    request_reference_id: String,
631    #[serde(rename = "taxCode")]
632    tax_code: String,
633    description: String,
634    #[serde(rename = "displayName")]
635    display_name: String,
636    period: SubscriptionPeriodPayload,
637    items: Vec<RenewalInfoAdvancedCommerceItemPayload>,
638}
639
640impl RenewalInfoAdvancedCommerceInfoPayload {
641    fn into_renewal_info_advanced_commerce_info(self) -> RenewalInfoAdvancedCommerceInfo {
642        RenewalInfoAdvancedCommerceInfo {
643            consistency_token: self.consistency_token,
644            request_reference_id: self.request_reference_id,
645            tax_code: self.tax_code,
646            description: self.description,
647            display_name: self.display_name,
648            period: self.period.into_subscription_period(),
649            items: self
650                .items
651                .into_iter()
652                .map(RenewalInfoAdvancedCommerceItemPayload::into_renewal_info_advanced_commerce_item)
653                .collect(),
654        }
655    }
656}
657
658#[derive(Debug, Deserialize)]
659struct RenewalInfoAdvancedCommerceItemPayload {
660    details: TransactionAdvancedCommerceItemDetailsPayload,
661    #[serde(rename = "priceIncreaseInfo")]
662    price_increase_info: Option<RenewalInfoAdvancedCommercePriceIncreaseInfoPayload>,
663}
664
665impl RenewalInfoAdvancedCommerceItemPayload {
666    fn into_renewal_info_advanced_commerce_item(self) -> RenewalInfoAdvancedCommerceItem {
667        RenewalInfoAdvancedCommerceItem {
668            details: self.details.into_transaction_advanced_commerce_item_details(),
669            price_increase_info: self.price_increase_info.map(
670                RenewalInfoAdvancedCommercePriceIncreaseInfoPayload::into_renewal_info_advanced_commerce_price_increase_info,
671            ),
672        }
673    }
674}
675
676#[derive(Debug, Deserialize)]
677struct RenewalInfoAdvancedCommercePriceIncreaseInfoPayload {
678    status: String,
679    price: String,
680    #[serde(rename = "dependentSKUs")]
681    dependent_skus: Vec<String>,
682}
683
684impl RenewalInfoAdvancedCommercePriceIncreaseInfoPayload {
685    fn into_renewal_info_advanced_commerce_price_increase_info(
686        self,
687    ) -> RenewalInfoAdvancedCommercePriceIncreaseInfo {
688        RenewalInfoAdvancedCommercePriceIncreaseInfo {
689            status: RenewalInfoAdvancedCommercePriceIncreaseStatus::from_raw(self.status),
690            price: self.price,
691            dependent_skus: self.dependent_skus,
692        }
693    }
694}
695
696#[derive(Debug, Deserialize)]
697struct AdvancedCommerceProductPayload {
698    id: String,
699    #[serde(rename = "type")]
700    product_type: String,
701}
702
703impl AdvancedCommerceProductPayload {
704    fn into_product(self) -> AdvancedCommerceProduct {
705        AdvancedCommerceProduct {
706            id: self.id,
707            product_type: ProductType::from_raw(self.product_type),
708        }
709    }
710}
711
712#[derive(Debug, Deserialize)]
713#[allow(clippy::unsafe_derive_deserialize)]
714pub(crate) struct AppStoreMerchandisingPresentationResultPayload {
715    kind: String,
716    #[serde(rename = "purchaseResult")]
717    purchase_result: Option<PurchaseResultPayload>,
718}
719
720impl AppStoreMerchandisingPresentationResultPayload {
721    pub(crate) fn into_result(
722        self,
723        transaction_handle: Option<TransactionHandle>,
724    ) -> Result<AppStoreMerchandisingPresentationResult, StoreKitError> {
725        match self.kind.as_str() {
726            "dismissed" => Ok(AppStoreMerchandisingPresentationResult::Dismissed),
727            "purchaseCompleted" => {
728                let purchase_result = self.purchase_result.ok_or_else(|| {
729                    StoreKitError::Unknown(
730                        "App Store merchandising reported a purchase completion without a purchase result"
731                            .to_owned(),
732                    )
733                })?;
734                Ok(AppStoreMerchandisingPresentationResult::PurchaseCompleted(
735                    purchase_result.into_purchase_result(transaction_handle)?,
736                ))
737            }
738            other => Err(StoreKitError::Unknown(format!(
739                "unknown App Store merchandising presentation result kind '{other}'"
740            ))),
741        }
742    }
743}
744
745#[derive(Debug, Deserialize)]
746struct TransactionSignedPayload {
747    #[serde(rename = "advancedCommerceInfo")]
748    advanced_commerce_info: Option<TransactionAdvancedCommerceInfoPayload>,
749}
750
751fn parse_transaction_advanced_commerce_info_payload(
752    payload_data: &[u8],
753) -> Result<Option<TransactionAdvancedCommerceInfo>, StoreKitError> {
754    let payload = serde_json::from_slice::<TransactionSignedPayload>(payload_data)
755        .map_err(|error| json_error(&error, "signed transaction payload"))?;
756    Ok(payload
757        .advanced_commerce_info
758        .map(TransactionAdvancedCommerceInfoPayload::into_transaction_advanced_commerce_info))
759}
760
761fn parse_renewal_advanced_commerce_info_payload(
762    payload_data: &[u8],
763) -> Result<Option<RenewalInfoAdvancedCommerceInfo>, StoreKitError> {
764    let payload = serde_json::from_slice::<RenewalSignedPayload>(payload_data)
765        .map_err(|error| json_error(&error, "signed renewal payload"))?;
766    Ok(payload
767        .advanced_commerce_info
768        .map(RenewalInfoAdvancedCommerceInfoPayload::into_renewal_info_advanced_commerce_info))
769}