use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::common::{PaymentMethod, PaymentMethodType};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct AvailabilityOverrides {
inner: Arc<Inner>,
}
impl AvailabilityOverrides {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(&self, params: &AvailabilityOverrideCreateRequest) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/availability-overrides",
Some(&body),
&[],
None,
)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<Value>> {
let query = [("merchant_id", merchant_id.to_string())];
self.inner
.request(
HttpMethod::Get,
"/availability-overrides",
None,
&query,
None,
)
.await
}
pub async fn delete(&self, id: &str) -> Result<bool> {
let path = format!("/availability-overrides/{}", encode_segment(id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn preview(&self, params: &AvailabilityPreviewParams) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/availability-overrides/preview",
None,
¶ms.to_query(),
None,
)
.await
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverrideScope {
Global,
Project,
Shop,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverrideAction {
ForceShow,
ForceHide,
}
#[derive(Debug, Clone, Serialize)]
pub struct AvailabilityOverrideCreateRequest {
pub merchant_id: String,
pub scope: OverrideScope,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope_id: Option<String>,
pub payment_method: PaymentMethod,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<PaymentMethodType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region_code: Option<String>,
pub action: OverrideAction,
}
impl AvailabilityOverrideCreateRequest {
pub fn new(
merchant_id: impl Into<String>,
scope: OverrideScope,
payment_method: impl Into<PaymentMethod>,
action: OverrideAction,
) -> Self {
Self {
merchant_id: merchant_id.into(),
scope,
scope_id: None,
payment_method: payment_method.into(),
payment_method_type: None,
country: None,
region_code: None,
action,
}
}
#[must_use]
pub fn scope_id_value(mut self, scope_id: impl Into<String>) -> Self {
self.scope_id = Some(scope_id.into());
self
}
#[must_use]
pub fn payment_method_type_value(
mut self,
payment_method_type: impl Into<PaymentMethodType>,
) -> Self {
self.payment_method_type = Some(payment_method_type.into());
self
}
#[must_use]
pub fn country_code(mut self, country: impl Into<String>) -> Self {
self.country = Some(country.into());
self
}
#[must_use]
pub fn region(mut self, region_code: impl Into<String>) -> Self {
self.region_code = Some(region_code.into());
self
}
}
#[derive(Debug, Clone, Default)]
pub struct AvailabilityPreviewParams {
pub merchant_id: String,
pub profile_id: String,
pub country: Option<String>,
}
impl AvailabilityPreviewParams {
pub fn new(merchant_id: impl Into<String>, profile_id: impl Into<String>) -> Self {
Self {
merchant_id: merchant_id.into(),
profile_id: profile_id.into(),
country: None,
}
}
#[must_use]
pub fn country(mut self, country: impl Into<String>) -> Self {
self.country = Some(country.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![
("merchant_id", self.merchant_id.clone()),
("profile_id", self.profile_id.clone()),
];
if let Some(v) = &self.country {
q.push(("country", v.clone()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
const OVERRIDE_JSON: &str = r#"{
"id": "avo_1",
"merchant_id": "mer_1",
"scope": "shop",
"payment_method": "wallet",
"action": "force_hide"
}"#;
#[tokio::test]
async fn create_posts_the_override() {
let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
let req = AvailabilityOverrideCreateRequest::new(
"mer_1",
OverrideScope::Shop,
"wallet",
OverrideAction::ForceHide,
)
.scope_id_value("pro_1")
.payment_method_type_value("apple_pay")
.country_code("DE");
client.availability_overrides().create(&req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/availability-overrides");
let body = seen[0].body_json();
assert_eq!(body["scope"], "shop");
assert_eq!(body["scope_id"], "pro_1");
assert_eq!(body["payment_method"], "wallet");
assert_eq!(body["payment_method_type"], "apple_pay");
assert_eq!(body["country"], "DE");
assert_eq!(body["action"], "force_hide");
assert!(
body.get("region_code").is_none(),
"an unset region_code must be omitted, not null"
);
}
#[tokio::test]
async fn list_sends_the_merchant_id_query() {
let (client, mock) = client_with(vec![Step::ok("[]")]);
client.availability_overrides().list("mer_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/availability-overrides?merchant_id=mer_1"
);
}
#[tokio::test]
async fn delete_encodes_the_id_and_returns_the_bare_boolean() {
let (client, mock) = client_with(vec![Step::ok("true")]);
let out = client
.availability_overrides()
.delete("avo/1")
.await
.unwrap();
assert!(out);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/availability-overrides/avo%2F1"
);
}
#[tokio::test]
async fn preview_serializes_its_query_in_order() {
let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
client
.availability_overrides()
.preview(&AvailabilityPreviewParams::new("mer_1", "pro_1").country("FR"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/availability-overrides/preview?merchant_id=mer_1&profile_id=pro_1&country=FR"
);
}
#[tokio::test]
async fn preview_omits_country_when_unset() {
let (client, mock) = client_with(vec![Step::ok(r#"{"payment_methods":[]}"#)]);
client
.availability_overrides()
.preview(&AvailabilityPreviewParams::new("mer_1", "pro_1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/availability-overrides/preview?merchant_id=mer_1&profile_id=pro_1"
);
}
}