use std::collections::BTreeMap;
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::common::Currency;
use crate::core::models::product::{
BillingReadinessResponse, BundlePricing, ProductCategoryListResponse, ProductCategoryResponse,
ProductDeleteResponse, ProductImageUploadResponse, ProductImportPreviewResponse,
ProductImportRunListResponse, ProductImportRunResponse, ProductKind, ProductListResponse,
ProductPriceInterval, ProductPriceTaxBehavior, ProductProviderCreateResponse,
ProductProviderPushResponse, ProductProviderSyncBatchResponse, ProductProviderSyncResponse,
ProductResolveResponse, ProductResponse, ProductSalesResponse, ProductStatus,
ProviderAccountListResponse, ProviderArchiveAction, ProviderArchiveOutcome,
ProviderCleanupListResponse,
};
use crate::core::models::subscription::SubscriptionItem;
use crate::http::client::{Inner, KeyPolicy};
use crate::http::multipart::{FilePart, encode_file};
use crate::http::transport::HttpMethod;
const PROFILE_HEADER: &str = "x-profile-id";
#[derive(Debug, Clone)]
pub struct Products {
inner: Arc<Inner>,
}
impl Products {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
async fn send<T: DeserializeOwned>(
&self,
method: HttpMethod,
path: &str,
profile_id: &str,
body: Option<&[u8]>,
query: &[(&str, String)],
) -> Result<T> {
self.inner
.request_body_keyed_with_query_and_headers(
method,
path,
body,
query,
&[(PROFILE_HEADER, profile_id)],
None,
)
.await
}
async fn send_json<T: DeserializeOwned, B: Serialize>(
&self,
method: HttpMethod,
path: &str,
profile_id: &str,
params: &B,
) -> Result<T> {
let body = to_json_vec(params)?;
self.send(method, path, profile_id, Some(&body), &[]).await
}
pub async fn upload_image(
&self,
profile_id: &str,
file_name: &str,
content_type: &str,
bytes: &[u8],
) -> Result<ProductImageUploadResponse> {
let form = encode_file(&FilePart {
field: "file",
file_name,
content_type,
bytes,
});
let raw = self
.inner
.send_raw_keyed(
HttpMethod::Post,
"/products/images",
Some(&form.body),
&[],
None,
KeyPolicy::BodyKeyOnly,
&[(PROFILE_HEADER, profile_id)],
Some(&form.content_type),
)
.await?;
serde_json::from_slice(&raw).map_err(|e| DelopayError::Decode(e.to_string()))
}
pub async fn create(
&self,
profile_id: &str,
params: &ProductCreateRequest,
) -> Result<ProductResponse> {
self.send_json(HttpMethod::Post, "/products", profile_id, params)
.await
}
pub async fn list(
&self,
profile_id: &str,
params: &ProductListParams,
) -> Result<ProductListResponse> {
if params.category_id.is_some() && params.uncategorized == Some(true) {
return Err(DelopayError::InvalidRequest(
"`category_id` and `uncategorized: true` ask for different products; set one"
.to_owned(),
));
}
self.send(
HttpMethod::Get,
"/products/list",
profile_id,
None,
¶ms.to_query(),
)
.await
}
pub async fn resolve(
&self,
profile_id: &str,
query: &ProductResolveQuery,
) -> Result<ProductResolveResponse> {
self.send(
HttpMethod::Get,
"/products/resolve",
profile_id,
None,
&query.to_query(),
)
.await
}
pub async fn retrieve(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
self.send(
HttpMethod::Get,
&product_path(product_id),
profile_id,
None,
&[],
)
.await
}
pub async fn sales(
&self,
product_id: &str,
profile_id: &str,
params: &ProductSalesParams,
) -> Result<ProductSalesResponse> {
let path = format!("{}/sales", product_path(product_id));
self.send(HttpMethod::Get, &path, profile_id, None, ¶ms.to_query())
.await
}
pub async fn billing_readiness(
&self,
profile_id: &str,
product_ids: &[&str],
) -> Result<BillingReadinessResponse> {
self.send(
HttpMethod::Get,
"/products/billing-readiness",
profile_id,
None,
&[("product_ids", product_ids.join(","))],
)
.await
}
pub async fn update(
&self,
product_id: &str,
profile_id: &str,
params: &ProductUpdateRequest,
) -> Result<ProductResponse> {
self.send_json(
HttpMethod::Post,
&product_path(product_id),
profile_id,
params,
)
.await
}
pub async fn archive(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
let path = format!("{}/archive", product_path(product_id));
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn restore(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
let path = format!("{}/restore", product_path(product_id));
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn delete(&self, product_id: &str, profile_id: &str) -> Result<()> {
self.send::<serde::de::IgnoredAny>(
HttpMethod::Delete,
&product_path(product_id),
profile_id,
None,
&[],
)
.await
.map(|_| ())
}
pub async fn delete_with_providers(
&self,
product_id: &str,
profile_id: &str,
params: &ProductDeleteRequest,
) -> Result<ProductDeleteResponse> {
let path = format!("{}/delete", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn add_price(
&self,
product_id: &str,
profile_id: &str,
params: &ProductPriceCreateRequest,
) -> Result<ProductResponse> {
let path = format!("{}/prices", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn update_price(
&self,
product_id: &str,
price_id: &str,
profile_id: &str,
params: &ProductPriceUpdateRequest,
) -> Result<ProductResponse> {
self.send_json(
HttpMethod::Post,
&price_path(product_id, price_id),
profile_id,
params,
)
.await
}
pub async fn archive_price(
&self,
product_id: &str,
price_id: &str,
profile_id: &str,
) -> Result<ProductResponse> {
let path = format!("{}/archive", price_path(product_id, price_id));
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn create_addon_group(
&self,
product_id: &str,
profile_id: &str,
params: &AddonGroupCreateRequest,
) -> Result<ProductResponse> {
let path = format!("{}/addon-groups", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn update_addon_group(
&self,
product_id: &str,
group_id: &str,
profile_id: &str,
params: &AddonGroupUpdateRequest,
) -> Result<ProductResponse> {
self.send_json(
HttpMethod::Post,
&addon_group_path(product_id, group_id),
profile_id,
params,
)
.await
}
pub async fn delete_addon_group(
&self,
product_id: &str,
group_id: &str,
profile_id: &str,
) -> Result<ProductResponse> {
self.send(
HttpMethod::Delete,
&addon_group_path(product_id, group_id),
profile_id,
None,
&[],
)
.await
}
pub async fn replace_bundle(
&self,
product_id: &str,
profile_id: &str,
params: &BundleDefinition,
) -> Result<ProductResponse> {
let path = format!("{}/bundle", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn add_alias(
&self,
product_id: &str,
profile_id: &str,
params: &ProductAliasCreateRequest,
) -> Result<ProductResponse> {
let path = format!("{}/aliases", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn remove_alias(
&self,
product_id: &str,
alias_id: &str,
profile_id: &str,
) -> Result<ProductResponse> {
let path = format!(
"{}/aliases/{}/remove",
product_path(product_id),
encode_segment(alias_id)
);
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn add_connector_reference(
&self,
product_id: &str,
profile_id: &str,
params: &ProductConnectorReferenceCreateRequest,
) -> Result<ProductResponse> {
let path = format!("{}/connector-references", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn remove_connector_reference(
&self,
product_id: &str,
reference_id: &str,
profile_id: &str,
) -> Result<ProductResponse> {
let path = format!(
"{}/connector-references/{}/remove",
product_path(product_id),
encode_segment(reference_id)
);
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn import_suggestions(
&self,
profile_id: &str,
params: &ProductImportSuggestionsParams,
) -> Result<Vec<SubscriptionItem>> {
self.send(
HttpMethod::Get,
"/products/import-suggestions",
profile_id,
None,
¶ms.to_query(),
)
.await
}
pub async fn accept_import(
&self,
product_id: &str,
profile_id: &str,
params: &ProductImportAcceptRequest,
) -> Result<ProductResponse> {
let path = format!("{}/connector-references/import", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn create_category(
&self,
profile_id: &str,
params: &ProductCategoryCreateRequest,
) -> Result<ProductCategoryResponse> {
self.send_json(HttpMethod::Post, "/products/categories", profile_id, params)
.await
}
pub async fn list_categories(
&self,
profile_id: &str,
params: &ProductCategoryListParams,
) -> Result<ProductCategoryListResponse> {
self.send(
HttpMethod::Get,
"/products/categories/list",
profile_id,
None,
¶ms.to_query(),
)
.await
}
pub async fn reorder_categories(
&self,
profile_id: &str,
params: &ProductCategoryReorderRequest,
) -> Result<ProductCategoryListResponse> {
self.send_json(
HttpMethod::Post,
"/products/categories/reorder",
profile_id,
params,
)
.await
}
pub async fn update_category(
&self,
category_id: &str,
profile_id: &str,
params: &ProductCategoryUpdateRequest,
) -> Result<ProductCategoryResponse> {
self.send_json(
HttpMethod::Post,
&category_path(category_id),
profile_id,
params,
)
.await
}
pub async fn delete_category(
&self,
category_id: &str,
profile_id: &str,
) -> Result<ProductCategoryResponse> {
self.send(
HttpMethod::Delete,
&category_path(category_id),
profile_id,
None,
&[],
)
.await
}
pub async fn archive_category(
&self,
category_id: &str,
profile_id: &str,
) -> Result<ProductCategoryResponse> {
let path = format!("{}/archive", category_path(category_id));
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn restore_category(
&self,
category_id: &str,
profile_id: &str,
) -> Result<ProductCategoryResponse> {
let path = format!("{}/restore", category_path(category_id));
self.send(HttpMethod::Post, &path, profile_id, None, &[])
.await
}
pub async fn import_preview(
&self,
profile_id: &str,
params: &ProductImportPreviewRequest,
) -> Result<ProductImportPreviewResponse> {
self.send_json(
HttpMethod::Post,
"/products/import/preview",
profile_id,
params,
)
.await
}
pub async fn import_apply(
&self,
profile_id: &str,
params: &ProductImportApplyRequest,
) -> Result<ProductImportRunResponse> {
self.send_json(
HttpMethod::Post,
"/products/import/apply",
profile_id,
params,
)
.await
}
pub async fn list_import_runs(
&self,
profile_id: &str,
merchant_connector_id: &str,
) -> Result<ProductImportRunListResponse> {
self.send(
HttpMethod::Get,
"/products/import/runs",
profile_id,
None,
&[("merchant_connector_id", merchant_connector_id.to_string())],
)
.await
}
pub async fn provider_sync(
&self,
product_id: &str,
profile_id: &str,
) -> Result<ProductProviderSyncResponse> {
let path = format!("{}/provider-sync", product_path(product_id));
self.send(HttpMethod::Get, &path, profile_id, None, &[])
.await
}
pub async fn provider_sync_batch(
&self,
profile_id: &str,
params: &ProductProviderSyncBatchRequest,
) -> Result<ProductProviderSyncBatchResponse> {
self.send_json(
HttpMethod::Post,
"/products/provider-sync",
profile_id,
params,
)
.await
}
pub async fn provider_push(
&self,
product_id: &str,
profile_id: &str,
params: &ProductProviderPushRequest,
) -> Result<ProductProviderPushResponse> {
let path = format!("{}/provider-sync/push", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn provider_accounts(&self, profile_id: &str) -> Result<ProviderAccountListResponse> {
self.send(
HttpMethod::Get,
"/products/provider-accounts",
profile_id,
None,
&[],
)
.await
}
pub async fn provider_cleanups(&self, profile_id: &str) -> Result<ProviderCleanupListResponse> {
self.send(
HttpMethod::Get,
"/products/provider-cleanups",
profile_id,
None,
&[],
)
.await
}
pub async fn provider_create(
&self,
product_id: &str,
profile_id: &str,
params: &ProductProviderCreateRequest,
) -> Result<ProductProviderCreateResponse> {
let path = format!("{}/provider-sync/create", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
pub async fn provider_archive(
&self,
product_id: &str,
profile_id: &str,
params: &ProviderArchiveRequest,
) -> Result<ProviderArchiveOutcome> {
let path = format!("{}/provider-archive", product_path(product_id));
self.send_json(HttpMethod::Post, &path, profile_id, params)
.await
}
}
fn product_path(product_id: &str) -> String {
format!("/products/{}", encode_segment(product_id))
}
fn price_path(product_id: &str, price_id: &str) -> String {
format!(
"{}/prices/{}",
product_path(product_id),
encode_segment(price_id)
)
}
fn addon_group_path(product_id: &str, group_id: &str) -> String {
format!(
"{}/addon-groups/{}",
product_path(product_id),
encode_segment(group_id)
)
}
fn category_path(category_id: &str) -> String {
format!("/products/categories/{}", encode_segment(category_id))
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductPriceCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub nickname: Option<String>,
pub amount: i64,
pub currency: Currency,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_interval: Option<ProductPriceInterval>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_interval_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trial_period: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trial_period_unit: Option<ProductPriceInterval>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_default: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_behavior: Option<ProductPriceTaxBehavior>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
impl ProductPriceCreateRequest {
pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
Self {
nickname: None,
amount,
currency: currency.into(),
billing_interval: None,
billing_interval_count: None,
trial_period: None,
trial_period_unit: None,
is_default: None,
tax_behavior: None,
metadata: None,
}
}
#[must_use]
pub fn recurring(mut self, interval: ProductPriceInterval, count: i32) -> Self {
self.billing_interval = Some(interval);
self.billing_interval_count = Some(count);
self
}
#[must_use]
pub fn trial(mut self, period: i32, unit: ProductPriceInterval) -> Self {
self.trial_period = Some(period);
self.trial_period_unit = Some(unit);
self
}
#[must_use]
pub fn nickname(mut self, nickname: impl Into<String>) -> Self {
self.nickname = Some(nickname.into());
self
}
#[must_use]
pub fn is_default(mut self, is_default: bool) -> Self {
self.is_default = Some(is_default);
self
}
#[must_use]
pub fn tax_behavior(mut self, tax_behavior: ProductPriceTaxBehavior) -> Self {
self.tax_behavior = Some(tax_behavior);
self
}
#[must_use]
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub aliases: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_url: Option<String>,
pub kind: ProductKind,
pub prices: Vec<ProductPriceCreateRequest>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bundle: Option<BundleDefinition>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub category_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub buyer_chooses_addons: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_category: Option<String>,
}
impl ProductCreateRequest {
pub fn new(
name: impl Into<String>,
kind: ProductKind,
prices: Vec<ProductPriceCreateRequest>,
) -> Self {
Self {
product_id: None,
name: name.into(),
aliases: None,
description: None,
image_url: None,
kind,
prices,
bundle: None,
metadata: None,
category_id: None,
buyer_chooses_addons: None,
tax_category: None,
}
}
#[must_use]
pub fn product_id(mut self, product_id: impl Into<String>) -> Self {
self.product_id = Some(product_id.into());
self
}
#[must_use]
pub fn aliases(mut self, aliases: Vec<String>) -> Self {
self.aliases = Some(aliases);
self
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn image_url(mut self, image_url: impl Into<String>) -> Self {
self.image_url = Some(image_url.into());
self
}
#[must_use]
pub fn bundle(mut self, bundle: BundleDefinition) -> Self {
self.bundle = Some(bundle);
self
}
#[must_use]
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
#[must_use]
pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
self.category_id = Some(category_id.into());
self
}
#[must_use]
pub fn buyer_chooses_addons(mut self, buyer_chooses_addons: bool) -> Self {
self.buyer_chooses_addons = Some(buyer_chooses_addons);
self
}
#[must_use]
pub fn tax_category(mut self, tax_category: impl Into<String>) -> Self {
self.tax_category = Some(tax_category.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub category_id: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub buyer_chooses_addons: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_category: Option<Option<String>>,
}
impl ProductUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn image_url(mut self, image_url: impl Into<String>) -> Self {
self.image_url = Some(image_url.into());
self
}
#[must_use]
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
#[must_use]
pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
self.category_id = Some(Some(category_id.into()));
self
}
#[must_use]
pub fn uncategorized(mut self) -> Self {
self.category_id = Some(None);
self
}
#[must_use]
pub fn buyer_chooses_addons(mut self, buyer_chooses_addons: bool) -> Self {
self.buyer_chooses_addons = Some(buyer_chooses_addons);
self
}
#[must_use]
pub fn tax_category(mut self, tax_category: impl Into<String>) -> Self {
self.tax_category = Some(Some(tax_category.into()));
self
}
#[must_use]
pub fn standard_tax_category(mut self) -> Self {
self.tax_category = Some(None);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductPriceUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub nickname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_default: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
impl ProductPriceUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn nickname(mut self, nickname: impl Into<String>) -> Self {
self.nickname = Some(nickname.into());
self
}
#[must_use]
pub fn is_default(mut self, is_default: bool) -> Self {
self.is_default = Some(is_default);
self
}
#[must_use]
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AddonGroupCreateRequest {
pub name: String,
pub min_choices: i32,
pub max_choices: i32,
pub addon_product_ids: Vec<String>,
}
impl AddonGroupCreateRequest {
pub fn new(
name: impl Into<String>,
min_choices: i32,
max_choices: i32,
addon_product_ids: Vec<String>,
) -> Self {
Self {
name: name.into(),
min_choices,
max_choices,
addon_product_ids,
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AddonGroupUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_choices: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_choices: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub addon_product_ids: Option<Vec<String>>,
}
impl AddonGroupUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn choices(mut self, min_choices: i32, max_choices: i32) -> Self {
self.min_choices = Some(min_choices);
self.max_choices = Some(max_choices);
self
}
#[must_use]
pub fn addon_product_ids(mut self, addon_product_ids: Vec<String>) -> Self {
self.addon_product_ids = Some(addon_product_ids);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct BundleItemRequest {
pub product_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<i32>,
}
impl BundleItemRequest {
pub fn new(product_id: impl Into<String>) -> Self {
Self {
product_id: product_id.into(),
quantity: None,
}
}
#[must_use]
pub fn quantity(mut self, quantity: i32) -> Self {
self.quantity = Some(quantity);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct BundleDefinition {
pub pricing: BundlePricing,
pub items: Vec<BundleItemRequest>,
}
impl BundleDefinition {
pub fn new(pricing: BundlePricing, items: Vec<BundleItemRequest>) -> Self {
Self { pricing, items }
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductAliasCreateRequest {
pub alias: String,
}
impl ProductAliasCreateRequest {
pub fn new(alias: impl Into<String>) -> Self {
Self {
alias: alias.into(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductConnectorReferenceCreateRequest {
pub merchant_connector_id: String,
pub connector_product_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
impl ProductConnectorReferenceCreateRequest {
pub fn new(
merchant_connector_id: impl Into<String>,
connector_product_id: impl Into<String>,
) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
connector_product_id: connector_product_id.into(),
connector_price_id: None,
price_id: None,
display_name: None,
}
}
#[must_use]
pub fn price(
mut self,
connector_price_id: impl Into<String>,
price_id: impl Into<String>,
) -> Self {
self.connector_price_id = Some(connector_price_id.into());
self.price_id = Some(price_id.into());
self
}
#[must_use]
pub fn connector_price_id(mut self, connector_price_id: impl Into<String>) -> Self {
self.connector_price_id = Some(connector_price_id.into());
self
}
#[must_use]
pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
self.display_name = Some(display_name.into());
self
}
}
#[derive(Debug, Clone)]
pub struct ProductImportSuggestionsParams {
pub merchant_connector_id: String,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl ProductImportSuggestionsParams {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
limit: None,
offset: None,
}
}
#[must_use]
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![("merchant_connector_id", self.merchant_connector_id.clone())];
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportAcceptRequest {
pub merchant_connector_id: String,
pub connector_product_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offset: Option<u32>,
}
impl ProductImportAcceptRequest {
pub fn new(
merchant_connector_id: impl Into<String>,
connector_product_id: impl Into<String>,
) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
connector_product_id: connector_product_id.into(),
connector_price_id: None,
price_id: None,
limit: None,
offset: None,
}
}
#[must_use]
pub fn price(
mut self,
connector_price_id: impl Into<String>,
price_id: impl Into<String>,
) -> Self {
self.connector_price_id = Some(connector_price_id.into());
self.price_id = Some(price_id.into());
self
}
#[must_use]
pub fn page(mut self, limit: u32, offset: u32) -> Self {
self.limit = Some(limit);
self.offset = Some(offset);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductCategoryCreateRequest {
pub name: String,
}
impl ProductCategoryCreateRequest {
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into() }
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductCategoryUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl ProductCategoryUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductCategoryReorderRequest {
pub category_ids: Vec<String>,
}
impl ProductCategoryReorderRequest {
pub fn new(category_ids: Vec<String>) -> Self {
Self { category_ids }
}
}
#[derive(Debug, Clone, Default)]
pub struct ProductCategoryListParams {
pub include_archived: Option<bool>,
}
impl ProductCategoryListParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn include_archived(mut self, include_archived: bool) -> Self {
self.include_archived = Some(include_archived);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.include_archived {
q.push(("include_archived", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct ProductListParams {
pub status: Option<ProductStatus>,
pub category_id: Option<String>,
pub uncategorized: Option<bool>,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl ProductListParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn status(mut self, status: ProductStatus) -> Self {
self.status = Some(status);
self
}
#[must_use]
pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
self.category_id = Some(category_id.into());
self
}
#[must_use]
pub fn uncategorized(mut self) -> Self {
self.uncategorized = Some(true);
self
}
#[must_use]
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.status {
q.push(("status", v.as_str().to_string()));
}
if let Some(v) = &self.category_id {
q.push(("category_id", v.clone()));
}
if let Some(v) = self.uncategorized {
q.push(("uncategorized", v.to_string()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ProductResolveQuery {
Alias(String),
ConnectorProduct {
connector: String,
connector_product_id: String,
},
ConnectorPrice {
connector: String,
connector_price_id: String,
},
}
impl ProductResolveQuery {
pub fn alias(alias: impl Into<String>) -> Self {
Self::Alias(alias.into())
}
pub fn connector_product(
connector: impl Into<String>,
connector_product_id: impl Into<String>,
) -> Self {
Self::ConnectorProduct {
connector: connector.into(),
connector_product_id: connector_product_id.into(),
}
}
pub fn connector_price(
connector: impl Into<String>,
connector_price_id: impl Into<String>,
) -> Self {
Self::ConnectorPrice {
connector: connector.into(),
connector_price_id: connector_price_id.into(),
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
match self {
Self::Alias(alias) => vec![("alias", alias.clone())],
Self::ConnectorProduct {
connector,
connector_product_id,
} => vec![
("connector", connector.clone()),
("connector_product_id", connector_product_id.clone()),
],
Self::ConnectorPrice {
connector,
connector_price_id,
} => vec![
("connector", connector.clone()),
("connector_price_id", connector_price_id.clone()),
],
}
}
}
#[derive(Debug, Clone)]
pub struct ProductSalesParams {
pub start_time: String,
pub end_time: Option<String>,
pub test_mode: bool,
}
impl ProductSalesParams {
pub fn new(start_time: impl Into<String>, test_mode: bool) -> Self {
Self {
start_time: start_time.into(),
end_time: None,
test_mode,
}
}
#[must_use]
pub fn end_time(mut self, end_time: impl Into<String>) -> Self {
self.end_time = Some(end_time.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![("start_time", self.start_time.clone())];
if let Some(v) = &self.end_time {
q.push(("end_time", v.clone()));
}
q.push(("test_mode", self.test_mode.to_string()));
q
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportScope {
ProductsRecurring,
ProductsOneTime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportMixedDecision {
Split,
RecurringOnly,
Skip,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportArchivedAtProvider {
Skip,
Archive,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductImportOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub mixed: Option<ProductImportMixedDecision>,
#[serde(skip_serializing_if = "Option::is_none")]
pub archived: Option<ProductImportArchivedAtProvider>,
}
impl ProductImportOptions {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn mixed(mut self, mixed: ProductImportMixedDecision) -> Self {
self.mixed = Some(mixed);
self
}
#[must_use]
pub fn archived(mut self, archived: ProductImportArchivedAtProvider) -> Self {
self.archived = Some(archived);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportPreviewRequest {
pub merchant_connector_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub scopes: Option<Vec<ProductImportScope>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<ProductImportOptions>,
}
impl ProductImportPreviewRequest {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
scopes: None,
options: None,
}
}
#[must_use]
pub fn scopes(mut self, scopes: Vec<ProductImportScope>) -> Self {
self.scopes = Some(scopes);
self
}
#[must_use]
pub fn options(mut self, options: ProductImportOptions) -> Self {
self.options = Some(options);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportApplyRequest {
pub merchant_connector_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_product_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub confirmation: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub decisions: Option<BTreeMap<String, ProductImportMixedDecision>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scopes: Option<Vec<ProductImportScope>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<ProductImportOptions>,
}
impl ProductImportApplyRequest {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
connector_product_ids: None,
confirmation: None,
decisions: None,
scopes: None,
options: None,
}
}
#[must_use]
pub fn connector_product_ids(mut self, connector_product_ids: Vec<String>) -> Self {
self.connector_product_ids = Some(connector_product_ids);
self
}
#[must_use]
pub fn confirmation(mut self, confirmation: impl Into<String>) -> Self {
self.confirmation = Some(confirmation.into());
self
}
#[must_use]
pub fn decision(
mut self,
connector_product_id: impl Into<String>,
decision: ProductImportMixedDecision,
) -> Self {
self.decisions
.get_or_insert_with(BTreeMap::new)
.insert(connector_product_id.into(), decision);
self
}
#[must_use]
pub fn scopes(mut self, scopes: Vec<ProductImportScope>) -> Self {
self.scopes = Some(scopes);
self
}
#[must_use]
pub fn options(mut self, options: ProductImportOptions) -> Self {
self.options = Some(options);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderSyncBatchRequest {
pub product_ids: Vec<String>,
}
impl ProductProviderSyncBatchRequest {
pub fn new(product_ids: Vec<String>) -> Self {
Self { product_ids }
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderPushRequest {
pub merchant_connector_id: String,
pub confirmed: Vec<String>,
}
impl ProductProviderPushRequest {
pub fn new(merchant_connector_id: impl Into<String>, confirmed: Vec<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
confirmed,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderCreateRequest {
pub merchant_connector_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_ids: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub confirmed: Option<String>,
}
impl ProductProviderCreateRequest {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
price_ids: None,
confirmed: None,
}
}
#[must_use]
pub fn price_ids(mut self, price_ids: Vec<String>) -> Self {
self.price_ids = Some(price_ids);
self
}
#[must_use]
pub fn confirmed(mut self, fingerprint: impl Into<String>) -> Self {
self.confirmed = Some(fingerprint.into());
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProviderArchiveRequest {
pub merchant_connector_id: String,
pub action: ProviderArchiveAction,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_product_id: Option<String>,
}
impl ProviderArchiveRequest {
pub fn new(merchant_connector_id: impl Into<String>, action: ProviderArchiveAction) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
action,
connector_product_id: None,
}
}
#[must_use]
pub fn connector_product_id(mut self, connector_product_id: impl Into<String>) -> Self {
self.connector_product_id = Some(connector_product_id.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductDeleteRequest {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub provider_actions: Vec<ProviderArchiveRequest>,
}
impl ProductDeleteRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn provider_action(mut self, action: ProviderArchiveRequest) -> Self {
self.provider_actions.push(action);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::models::product::{
PriceBillingState, ProductAliasKind, ProductImportClassification, ProductMappingMode,
ProductMatch, ProductPriceResponse, ProviderArchiveMode, ProviderArchiveStatus,
ProviderPushAction, ProviderSyncField, ProviderSyncStatus,
};
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const PRICE_JSON: &str = r#"{
"id": "price_1",
"product_id": "prd_1",
"nickname": "Monthly",
"amount": 1999,
"currency": "EUR",
"billing_interval": "month",
"billing_interval_count": 1,
"is_default": true,
"status": "active",
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-01T00:00:00Z",
"price_surprise": 7
}"#;
fn product_json() -> String {
format!(
r#"{{
"id": "prd_1",
"profile_id": "pro_1",
"name": "Pro plan",
"kind": "recurring",
"status": "active",
"prices": [{PRICE_JSON}],
"aliases": [{{"id": "al_1", "alias": "PRO", "kind": "alias", "created_at": "2026-01-01T00:00:00Z"}}],
"connector_references": [{{
"id": "ref_1", "connector": "stripe", "merchant_connector_id": "mca_1",
"connector_product_id": "prod_X", "mapping_mode": "manual_id",
"created_at": "2026-01-01T00:00:00Z"
}}],
"addon_groups": [{{
"id": "grp_1", "name": "Extras", "min_choices": 0, "max_choices": 2,
"items": [{{"addon_product_id": "prd_a", "name": "Gift wrap", "status": "active"}}]
}}],
"bundle_items": [],
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-02T00:00:00Z",
"category_id": "cat_1",
"buyer_chooses_addons": false,
"tax_category": "digital_services",
"surprise_field": 1
}}"#
)
}
const CATEGORY_JSON: &str = r#"{
"id": "cat_1",
"profile_id": "pro_1",
"name": "Plans",
"position": 0,
"status": "active",
"created_at": "2026-01-01T00:00:00Z",
"modified_at": "2026-01-01T00:00:00Z",
"surprise_field": 1
}"#;
fn sync_json() -> String {
r#"{
"product_id": "prd_1",
"status": "changed_at_provider",
"links": [{
"merchant_connector_id": "mca_1",
"connector": "stripe",
"connector_product_id": "prod_X",
"test_mode": true,
"status": "changed_at_provider",
"differences": [{
"key": "k1",
"field": "name",
"catalog_value": "Pro plan",
"provider_value": "Pro",
"push_action": "update_product"
}],
"can_push": true,
"compared_fields": ["name", "price_terms"]
}],
"checked_at": "2026-01-03T00:00:00Z",
"surprise_field": 1
}"#
.to_string()
}
const COUNTS_JSON: &str = r#"{
"new": 1, "changed": 0, "unchanged": 2, "unavailable": 0, "conflicting": 0,
"products_created": 1, "prices_added": 1, "failed": 0
}"#;
const OUTCOME_JSON: &str = r#"{
"merchant_connector_id": "mca_1",
"connector": "stripe",
"connector_product_id": "prod_X",
"action": "archive",
"status": "done",
"deactivated_price_ids": ["price_X"],
"kept_price_ids": [],
"surprise_field": 1
}"#;
fn assert_seen(mock: &crate::http::mock::MockTransport, method: &str, url: &str) {
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].method, method);
assert_eq!(seen[0].url, url);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
fn body(mock: &crate::http::mock::MockTransport) -> Value {
mock.seen.lock().unwrap()[0].body_json()
}
fn assert_no_body(mock: &crate::http::mock::MockTransport) {
assert!(mock.seen.lock().unwrap()[0].body.is_none());
}
#[tokio::test]
async fn upload_image_posts_a_multipart_file_with_the_shop_header() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"image_url":"https://cdn.test/p.png","surprise_field":1}"#,
)]);
let out = client
.products()
.upload_image("pro_1", "p.png", "image/png", b"PNGDATA")
.await
.unwrap();
assert_eq!(out.image_url, "https://cdn.test/p.png");
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/images");
let seen = mock.seen.lock().unwrap();
let content_type = seen[0].content_type.as_deref().expect("explicit type");
let boundary = content_type
.strip_prefix("multipart/form-data; boundary=")
.expect("multipart content type");
let raw = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
assert!(raw.starts_with(&format!("--{boundary}\r\n")));
assert!(raw.contains("name=\"file\"; filename=\"p.png\""));
assert!(raw.contains("Content-Type: image/png\r\n\r\nPNGDATA\r\n"));
}
#[tokio::test]
async fn create_posts_the_product_with_its_prices() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductCreateRequest::new(
"Pro plan",
ProductKind::Recurring,
vec![
ProductPriceCreateRequest::new(1999, "EUR")
.recurring(ProductPriceInterval::Month, 1)
.trial(14, ProductPriceInterval::Day)
.is_default(true),
],
)
.product_id("pro-plan")
.category_id("cat_1")
.tax_category("digital_services");
let product = client.products().create("pro_1", ¶ms).await.unwrap();
assert_eq!(product.id, "prd_1");
assert_eq!(product.kind, ProductKind::Recurring);
assert_eq!(product.prices[0].amount, 1999);
assert_eq!(
product.prices[0].billing_interval,
Some(ProductPriceInterval::Month)
);
assert_eq!(product.prices[0].extra["price_surprise"], 7);
assert_eq!(product.aliases[0].kind, ProductAliasKind::Alias);
assert_eq!(
product.connector_references[0].mapping_mode,
ProductMappingMode::ManualId
);
assert_eq!(product.addon_groups[0].items[0].addon_product_id, "prd_a");
assert_eq!(product.tax_category.as_deref(), Some("digital_services"));
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products");
assert_eq!(
body(&mock),
json!({
"product_id": "pro-plan",
"name": "Pro plan",
"kind": "recurring",
"prices": [{
"amount": 1999,
"currency": "EUR",
"billing_interval": "month",
"billing_interval_count": 1,
"trial_period": 14,
"trial_period_unit": "day",
"is_default": true
}],
"category_id": "cat_1",
"tax_category": "digital_services"
})
);
}
#[tokio::test]
async fn create_without_an_idempotency_key_is_not_replayed_on_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(&product_json()),
],
2,
);
let params = ProductCreateRequest::new(
"Pro plan",
ProductKind::OneTime,
vec![ProductPriceCreateRequest::new(500, "EUR")],
);
assert!(client.products().create("pro_1", ¶ms).await.is_err());
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn create_ignores_a_client_wide_key_and_is_not_replayed() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(&product_json()),
],
2,
);
let params = ProductCreateRequest::new(
"Pro plan",
ProductKind::OneTime,
vec![ProductPriceCreateRequest::new(500, "EUR")],
);
assert!(
client
.with_idempotency_key("client-key")
.products()
.create("pro_1", ¶ms)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn upload_image_ignores_a_client_wide_key_and_is_not_replayed() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(r#"{"image_url":"https://cdn.test/p.png"}"#),
],
2,
);
assert!(
client
.with_idempotency_key("client-key")
.products()
.upload_image("pro_1", "p.png", "image/png", b"PNGDATA")
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn list_sends_the_filters_as_query() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{}],"total_count":42,"surprise_field":1}}"#,
product_json()
))]);
let params = ProductListParams::new()
.status(ProductStatus::Archived)
.category_id("cat_1")
.limit(10)
.offset(20);
let page = client.products().list("pro_1", ¶ms).await.unwrap();
assert_eq!(page.total_count, 42);
assert_eq!(page.data[0].id, "prd_1");
assert_eq!(page.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/list?status=archived&category_id=cat_1&limit=10&offset=20",
);
}
#[tokio::test]
async fn list_refuses_a_category_together_with_uncategorized() {
let (client, mock) = client_with(vec![]);
let params = ProductListParams::new()
.category_id("cat_1")
.uncategorized();
match client.products().list("pro_1", ¶ms).await.unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("uncategorized")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn resolve_sends_only_the_chosen_lookup() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"matched_by":"connector_price","price_id":"price_1","product":{},"surprise_field":1}}"#,
product_json()
))]);
let out = client
.products()
.resolve(
"pro_1",
&ProductResolveQuery::connector_price("stripe", "price_X"),
)
.await
.unwrap();
assert_eq!(out.matched_by, ProductMatch::ConnectorPrice);
assert_eq!(out.price_id.as_deref(), Some("price_1"));
assert_eq!(out.product.id, "prd_1");
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/resolve?connector=stripe&connector_price_id=price_X",
);
}
#[tokio::test]
async fn retrieve_encodes_the_product_id() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client.products().retrieve("prd/1", "pro_1").await.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "GET", "https://api.test/products/prd%2F1");
assert_no_body(&mock);
}
#[tokio::test]
async fn sales_sends_the_window_as_query() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"product_id": "prd_1", "profile_id": "pro_1", "test_mode": false,
"start_time": "2026-01-01T00:00:00Z", "end_time": "2026-02-01T00:00:00Z",
"currencies": [{
"currency": "EUR", "payment_count": 3, "sold_quantity": 4,
"sold_amount": 8000, "refunded_quantity": 1, "refunded_amount": 2000,
"refund_pending_quantity": 0, "refund_pending_amount": 0,
"net_quantity": 3, "net_amount": 6000
}],
"surprise_field": 1
}"#,
)]);
let params =
ProductSalesParams::new("2026-01-01T00:00:00Z", false).end_time("2026-02-01T00:00:00Z");
let out = client
.products()
.sales("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.currencies[0].net_amount, 6000);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/prd_1/sales?start_time=2026-01-01T00:00:00Z&end_time=2026-02-01T00:00:00Z&test_mode=false",
);
}
#[tokio::test]
async fn billing_readiness_joins_the_ids_into_one_value() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"billing_account": {"merchant_connector_id": "mca_1", "connector": "stripe", "test_mode": true},
"prices": [{"product_id": "prd_1", "price_id": "price_1", "state": "other_environment"}],
"surprise_field": 1
}"#,
)]);
let out = client
.products()
.billing_readiness("pro_1", &["prd_1", "prd_2"])
.await
.unwrap();
assert_eq!(out.prices[0].state, PriceBillingState::OtherEnvironment);
assert!(out.billing_account.unwrap().test_mode);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/billing-readiness?product_ids=prd_1,prd_2",
);
}
#[tokio::test]
async fn update_posts_to_the_product_and_can_send_null_category() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductUpdateRequest::new()
.name("Pro")
.uncategorized()
.standard_tax_category();
let product = client
.products()
.update("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1");
assert_eq!(
body(&mock),
json!({"name": "Pro", "category_id": null, "tax_category": null})
);
}
#[tokio::test]
async fn archive_posts_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client.products().archive("prd_1", "pro_1").await.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/archive");
assert_no_body(&mock);
}
#[tokio::test]
async fn restore_posts_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client.products().restore("prd_1", "pro_1").await.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/restore");
assert_no_body(&mock);
}
#[tokio::test]
async fn delete_deletes_the_product_and_accepts_a_json_body() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"deleted":true,"product_id":"prd_1","surprise_field":1}"#,
)]);
client.products().delete("prd_1", "pro_1").await.unwrap();
assert_seen(&mock, "DELETE", "https://api.test/products/prd_1");
assert_no_body(&mock);
}
#[tokio::test]
async fn delete_accepts_an_empty_body() {
let (client, _mock) = client_with(vec![Step::ok("")]);
client.products().delete("prd_1", "pro_1").await.unwrap();
}
#[tokio::test]
async fn delete_with_providers_posts_the_provider_actions() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"product_id":"prd_1","deleted":true,"provider":[{OUTCOME_JSON}],"surprise_field":1}}"#
))]);
let params = ProductDeleteRequest::new().provider_action(ProviderArchiveRequest::new(
"mca_1",
ProviderArchiveAction::Archive,
));
let out = client
.products()
.delete_with_providers("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert!(out.deleted);
assert_eq!(out.provider[0].status, ProviderArchiveStatus::Done);
assert_eq!(out.provider[0].extra["surprise_field"], 1);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/delete");
assert_eq!(
body(&mock),
json!({"provider_actions": [{"merchant_connector_id": "mca_1", "action": "archive"}]})
);
}
#[tokio::test]
async fn add_price_posts_the_price() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductPriceCreateRequest::new(2999, "EUR").nickname("Yearly");
let product = client
.products()
.add_price("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/prices");
assert_eq!(
body(&mock),
json!({"nickname": "Yearly", "amount": 2999, "currency": "EUR"})
);
}
#[tokio::test]
async fn add_price_sends_tax_added_on_top_only_when_asked() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductPriceCreateRequest::new(1000, "EUR")
.recurring(ProductPriceInterval::Month, 1)
.tax_behavior(ProductPriceTaxBehavior::Exclusive);
client
.products()
.add_price("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(
body(&mock),
json!({"amount": 1000, "currency": "EUR", "billing_interval": "month",
"billing_interval_count": 1, "tax_behavior": "exclusive"})
);
}
#[test]
fn a_price_reads_whether_tax_is_added_on_top() {
let with = |value: &str| -> ProductPriceResponse {
let mut json: Value = serde_json::from_str(PRICE_JSON).unwrap();
json["tax_behavior"] = json!(value);
serde_json::from_value(json).unwrap()
};
assert_eq!(
with("exclusive").tax_behavior,
Some(ProductPriceTaxBehavior::Exclusive)
);
assert_eq!(
with("inclusive").tax_behavior,
Some(ProductPriceTaxBehavior::Inclusive)
);
assert_eq!(
with("a_later_mode").tax_behavior,
Some(ProductPriceTaxBehavior::Unknown)
);
let older: ProductPriceResponse = serde_json::from_str(PRICE_JSON).unwrap();
assert_eq!(older.tax_behavior, None);
}
#[tokio::test]
async fn update_price_encodes_both_ids() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductPriceUpdateRequest::new().is_default(false);
let product = client
.products()
.update_price("prd_1", "price/1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/prices/price%2F1",
);
assert_eq!(body(&mock), json!({"is_default": false}));
}
#[tokio::test]
async fn archive_price_posts_the_archive_sub_path() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client
.products()
.archive_price("prd_1", "price_1", "pro_1")
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/prices/price_1/archive",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn create_addon_group_posts_the_group() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = AddonGroupCreateRequest::new("Extras", 0, 2, vec!["prd_a".to_string()]);
let product = client
.products()
.create_addon_group("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.addon_groups[0].max_choices, 2);
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/addon-groups",
);
assert_eq!(
body(&mock),
json!({"name": "Extras", "min_choices": 0, "max_choices": 2, "addon_product_ids": ["prd_a"]})
);
}
#[tokio::test]
async fn update_addon_group_posts_to_the_group() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = AddonGroupUpdateRequest::new()
.choices(1, 1)
.addon_product_ids(vec!["prd_b".to_string()]);
let product = client
.products()
.update_addon_group("prd_1", "grp 1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/addon-groups/grp%201",
);
assert_eq!(
body(&mock),
json!({"min_choices": 1, "max_choices": 1, "addon_product_ids": ["prd_b"]})
);
}
#[tokio::test]
async fn delete_addon_group_deletes_the_group() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client
.products()
.delete_addon_group("prd_1", "grp_1", "pro_1")
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"DELETE",
"https://api.test/products/prd_1/addon-groups/grp_1",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn replace_bundle_posts_the_definition() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = BundleDefinition::new(
BundlePricing::Sum,
vec![
BundleItemRequest::new("prd_a").quantity(2),
BundleItemRequest::new("prd_b"),
],
);
let product = client
.products()
.replace_bundle("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/bundle");
assert_eq!(
body(&mock),
json!({"pricing": "sum", "items": [{"product_id": "prd_a", "quantity": 2}, {"product_id": "prd_b"}]})
);
}
#[tokio::test]
async fn add_alias_posts_the_name() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client
.products()
.add_alias("prd_1", "pro_1", &ProductAliasCreateRequest::new("PRO"))
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/prd_1/aliases");
assert_eq!(body(&mock), json!({"alias": "PRO"}));
}
#[tokio::test]
async fn remove_alias_posts_the_remove_sub_path() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client
.products()
.remove_alias("prd_1", "al/1", "pro_1")
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/aliases/al%2F1/remove",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn add_connector_reference_posts_the_reference() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductConnectorReferenceCreateRequest::new("mca_1", "prod_X")
.price("price_X", "price_1")
.display_name("Pro");
let product = client
.products()
.add_connector_reference("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/connector-references",
);
assert_eq!(
body(&mock),
json!({
"merchant_connector_id": "mca_1",
"connector_product_id": "prod_X",
"connector_price_id": "price_X",
"price_id": "price_1",
"display_name": "Pro"
})
);
}
#[tokio::test]
async fn remove_connector_reference_posts_the_remove_sub_path() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let product = client
.products()
.remove_connector_reference("prd_1", "ref_1", "pro_1")
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/connector-references/ref_1/remove",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn import_suggestions_sends_the_page_as_query() {
let (client, mock) = client_with(vec![Step::ok(
r#"[{
"item_id": "prod_X", "name": "Pro", "available": true,
"price_id": [{"price_id": "price_X", "amount": 1999, "currency": "EUR",
"interval": "Month", "interval_count": 1}],
"surprise_field": 1
}]"#,
)]);
let params = ProductImportSuggestionsParams::new("mca_1")
.limit(5)
.offset(10);
let items = client
.products()
.import_suggestions("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(items[0].item_id, "prod_X");
assert_eq!(items[0].available, Some(true));
assert_eq!(items[0].extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/import-suggestions?merchant_connector_id=mca_1&limit=5&offset=10",
);
}
#[tokio::test]
async fn accept_import_posts_the_item_and_its_page() {
let (client, mock) = client_with(vec![Step::ok(&product_json())]);
let params = ProductImportAcceptRequest::new("mca_1", "prod_X").page(20, 0);
let product = client
.products()
.accept_import("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(product.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/connector-references/import",
);
assert_eq!(
body(&mock),
json!({"merchant_connector_id": "mca_1", "connector_product_id": "prod_X", "limit": 20, "offset": 0})
);
}
#[tokio::test]
async fn create_category_posts_the_name() {
let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
let category = client
.products()
.create_category("pro_1", &ProductCategoryCreateRequest::new("Plans"))
.await
.unwrap();
assert_eq!(category.id, "cat_1");
assert_eq!(category.status, ProductStatus::Active);
assert_eq!(category.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/categories");
assert_eq!(body(&mock), json!({"name": "Plans"}));
}
#[tokio::test]
async fn list_categories_sends_include_archived() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{CATEGORY_JSON}],"surprise_field":1}}"#
))]);
let out = client
.products()
.list_categories(
"pro_1",
&ProductCategoryListParams::new().include_archived(true),
)
.await
.unwrap();
assert_eq!(out.data[0].position, 0);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/categories/list?include_archived=true",
);
}
#[tokio::test]
async fn reorder_categories_posts_the_order() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{CATEGORY_JSON}],"surprise_field":1}}"#
))]);
let params = ProductCategoryReorderRequest::new(vec!["cat_2".into(), "cat_1".into()]);
let out = client
.products()
.reorder_categories("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/categories/reorder",
);
assert_eq!(body(&mock), json!({"category_ids": ["cat_2", "cat_1"]}));
}
#[tokio::test]
async fn update_category_encodes_the_category_id() {
let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
let category = client
.products()
.update_category(
"cat/1",
"pro_1",
&ProductCategoryUpdateRequest::new().name("Bundles"),
)
.await
.unwrap();
assert_eq!(category.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/categories/cat%2F1",
);
assert_eq!(body(&mock), json!({"name": "Bundles"}));
}
#[tokio::test]
async fn delete_category_deletes_and_decodes_the_category() {
let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
let category = client
.products()
.delete_category("cat_1", "pro_1")
.await
.unwrap();
assert_eq!(category.extra["surprise_field"], 1);
assert_seen(
&mock,
"DELETE",
"https://api.test/products/categories/cat_1",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn archive_category_posts_the_archive_sub_path() {
let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
let category = client
.products()
.archive_category("cat_1", "pro_1")
.await
.unwrap();
assert_eq!(category.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/categories/cat_1/archive",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn restore_category_posts_the_restore_sub_path() {
let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
let category = client
.products()
.restore_category("cat_1", "pro_1")
.await
.unwrap();
assert_eq!(category.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/categories/cat_1/restore",
);
assert_no_body(&mock);
}
#[tokio::test]
async fn import_preview_posts_the_scope_and_options() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{
"confirmation": "conf_1",
"capabilities": {{"connector": "stripe", "one_time_products": true,
"recurring_products": true, "availability": true, "trial_periods": false}},
"counts": {COUNTS_JSON},
"items": [{{
"key": "k1", "connector_product_id": "prod_X", "mixed": false,
"name": "Pro", "classification": "new", "kind": "recurring",
"prices": [{{"connector_price_id": "price_X", "amount": 1999,
"currency": "EUR", "interval": "month", "interval_count": 1, "state": "new"}}]
}}],
"surprise_field": 1
}}"#
))]);
let params = ProductImportPreviewRequest::new("mca_1")
.scopes(vec![ProductImportScope::ProductsRecurring])
.options(ProductImportOptions::new().mixed(ProductImportMixedDecision::RecurringOnly));
let out = client
.products()
.import_preview("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.confirmation, "conf_1");
assert_eq!(
out.items[0].classification,
ProductImportClassification::New
);
assert_eq!(out.counts.unchanged, 2);
assert_eq!(out.counts.archived, None);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/import/preview");
assert_eq!(
body(&mock),
json!({
"merchant_connector_id": "mca_1",
"scopes": ["products_recurring"],
"options": {"mixed": "recurring_only"}
})
);
}
fn run_json() -> String {
format!(
r#"{{
"id": "run_1", "merchant_connector_id": "mca_1", "connector": "stripe",
"status": "partial", "confirmation_outdated": false,
"counts": {COUNTS_JSON},
"failures": [{{"connector_product_id": "prod_Y", "kind": "one_time",
"name": "Mug", "reason": "currency not supported"}}],
"created_at": "2026-01-01T00:00:00Z",
"surprise_field": 1
}}"#
)
}
#[tokio::test]
async fn import_apply_posts_the_confirmation_and_decisions() {
let (client, mock) = client_with(vec![Step::ok(&run_json())]);
let params = ProductImportApplyRequest::new("mca_1")
.confirmation("conf_1")
.decision("prod_X", ProductImportMixedDecision::Split)
.options(
ProductImportOptions::new().archived(ProductImportArchivedAtProvider::Archive),
);
let run = client
.products()
.import_apply("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(run.status, "partial");
assert_eq!(run.failures[0].kind, Some(ProductKind::OneTime));
assert_eq!(run.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/import/apply");
assert_eq!(
body(&mock),
json!({
"merchant_connector_id": "mca_1",
"confirmation": "conf_1",
"decisions": {"prod_X": "split"},
"options": {"archived": "archive"}
})
);
}
#[tokio::test]
async fn list_import_runs_sends_the_account_as_query() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{}],"surprise_field":1}}"#,
run_json()
))]);
let out = client
.products()
.list_import_runs("pro_1", "mca_1")
.await
.unwrap();
assert_eq!(out.data[0].id, "run_1");
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/import/runs?merchant_connector_id=mca_1",
);
}
#[tokio::test]
async fn provider_sync_gets_the_comparison() {
let (client, mock) = client_with(vec![Step::ok(&sync_json())]);
let out = client
.products()
.provider_sync("prd_1", "pro_1")
.await
.unwrap();
assert_eq!(out.status, ProviderSyncStatus::ChangedAtProvider);
let link = &out.links[0];
assert_eq!(link.differences[0].field, ProviderSyncField::Name);
assert_eq!(
link.differences[0].push_action,
Some(ProviderPushAction::UpdateProduct)
);
assert_eq!(link.compared_fields[1], ProviderSyncField::PriceTerms);
assert_eq!(link.can_create, None);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"GET",
"https://api.test/products/prd_1/provider-sync",
);
}
#[tokio::test]
async fn provider_sync_reads_the_wire_unknown_status_as_unknown() {
let (client, _mock) = client_with(vec![Step::ok(
r#"{"product_id":"prd_1","status":"unknown","links":[],"checked_at":"t"}"#,
)]);
let out = client
.products()
.provider_sync("prd_1", "pro_1")
.await
.unwrap();
assert_eq!(out.status, ProviderSyncStatus::Unknown);
let (client, _mock) = client_with(vec![Step::ok(
r#"{"product_id":"prd_1","status":"brand_new","links":[],"checked_at":"t"}"#,
)]);
let out = client
.products()
.provider_sync("prd_1", "pro_1")
.await
.unwrap();
assert_eq!(out.status, ProviderSyncStatus::Unrecognized);
}
#[tokio::test]
async fn provider_sync_batch_posts_the_ids() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{}],"surprise_field":1}}"#,
sync_json()
))]);
let params = ProductProviderSyncBatchRequest::new(vec!["prd_1".into(), "prd_2".into()]);
let out = client
.products()
.provider_sync_batch("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.data[0].product_id, "prd_1");
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "POST", "https://api.test/products/provider-sync");
assert_eq!(body(&mock), json!({"product_ids": ["prd_1", "prd_2"]}));
}
#[tokio::test]
async fn provider_push_posts_the_confirmed_keys() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{
"nothing_to_push": false, "confirmation_outdated": false,
"applied": [{{"action": "replace_price", "keys": ["k2"], "price_id": "price_1",
"connector_price_id": "price_Z"}}],
"result": {},
"surprise_field": 1
}}"#,
sync_json()
))]);
let params = ProductProviderPushRequest::new("mca_1", vec!["k2".into()]);
let out = client
.products()
.provider_push("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.applied[0].action, ProviderPushAction::ReplacePrice);
assert_eq!(out.result.product_id, "prd_1");
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/provider-sync/push",
);
assert_eq!(
body(&mock),
json!({"merchant_connector_id": "mca_1", "confirmed": ["k2"]})
);
}
#[tokio::test]
async fn provider_accounts_gets_the_accounts() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"data":[{
"merchant_connector_id": "mca_1", "connector": "paypal", "test_mode": false,
"disabled": false, "billing_processor": true, "serves_subscriptions": true,
"capabilities": {"read_catalog": true, "one_time_products": false,
"recurring_products": true, "push": false, "create": true,
"archive": "none", "split_mixed_imports": false,
"unavailable_reason": "no_credentials_for_environment",
"unavailable_environment": "test"}
}],"surprise_field":1}"#,
)]);
let out = client.products().provider_accounts("pro_1").await.unwrap();
let caps = &out.data[0].capabilities;
assert_eq!(caps.archive, ProviderArchiveMode::NoAction);
assert_eq!(
caps.unavailable_reason,
Some(crate::core::models::product::ProviderUnavailableReason::NoCredentialsForEnvironment)
);
assert!(out.data[0].billing_processor);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "GET", "https://api.test/products/provider-accounts");
assert_no_body(&mock);
}
#[tokio::test]
async fn provider_cleanups_gets_the_pending_cleanups() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"data":[{
"product_id": "prd_1", "product_name": "Pro", "deleted": true,
"merchant_connector_id": "mca_1", "connector": "stripe",
"connector_product_id": "prod_X", "action": "deactivate_plans",
"error": "timeout", "surprise_field": 1
}],"surprise_field":1}"#,
)]);
let out = client.products().provider_cleanups("pro_1").await.unwrap();
assert_eq!(out.data[0].action, ProviderArchiveAction::DeactivatePlans);
assert_eq!(out.data[0].attempted_at, None);
assert_eq!(out.data[0].extra["surprise_field"], 1);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(&mock, "GET", "https://api.test/products/provider-cleanups");
}
#[tokio::test]
async fn provider_create_posts_the_confirmed_plan() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"created": true, "confirmation_outdated": false,
"plan": {"fingerprint": "fp_1", "connector": "stripe",
"merchant_connector_id": "mca_1", "test_mode": true, "name": "Pro",
"prices": [{"price_id": "price_1", "is_default": true,
"terms": {"amount": 1999, "currency": "EUR", "interval": "month",
"interval_count": 1, "active": true}}],
"unsupported_prices": [], "skipped_price_ids": []},
"connector_product_id": "prod_N",
"prices": [{"price_id": "price_1", "connector_price_id": "price_N"}],
"surprise_field": 1
}"#,
)]);
let params = ProductProviderCreateRequest::new("mca_1")
.price_ids(vec!["price_1".into()])
.confirmed("fp_1");
let out = client
.products()
.provider_create("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert!(out.created);
assert_eq!(out.plan.prices[0].terms.amount, 1999);
assert_eq!(out.connector_product_id.as_deref(), Some("prod_N"));
assert!(out.result.is_none());
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/provider-sync/create",
);
assert_eq!(
body(&mock),
json!({"merchant_connector_id": "mca_1", "price_ids": ["price_1"], "confirmed": "fp_1"})
);
}
#[tokio::test]
async fn provider_archive_posts_the_action() {
let (client, mock) = client_with(vec![Step::ok(OUTCOME_JSON)]);
let params = ProviderArchiveRequest::new("mca_1", ProviderArchiveAction::Archive)
.connector_product_id("prod_X");
let out = client
.products()
.provider_archive("prd_1", "pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.action, ProviderArchiveAction::Archive);
assert_eq!(out.deactivated_price_ids, ["price_X"]);
assert_eq!(out.extra["surprise_field"], 1);
assert_seen(
&mock,
"POST",
"https://api.test/products/prd_1/provider-archive",
);
assert_eq!(
body(&mock),
json!({"merchant_connector_id": "mca_1", "action": "archive", "connector_product_id": "prod_X"})
);
}
#[test]
fn product_status_query_values_match_the_wire() {
for status in [ProductStatus::Active, ProductStatus::Archived] {
assert_eq!(
serde_json::to_value(status).unwrap(),
json!(status.as_str())
);
}
}
}