use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::shop_label::{
ShopLabelDeleteResponse, ShopLabelResponse, ShopLabelsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct ShopLabels {
inner: Arc<Inner>,
}
impl ShopLabels {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<ShopLabelResponse>> {
self.inner
.request(HttpMethod::Get, &labels_path(merchant_id), None, &[], None)
.await
}
pub async fn create(
&self,
merchant_id: &str,
params: &ShopLabelCreateRequest,
) -> Result<ShopLabelResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
&labels_path(merchant_id),
Some(&body),
None,
)
.await
}
pub async fn update(
&self,
merchant_id: &str,
label_id: &str,
params: &ShopLabelUpdateRequest,
) -> Result<ShopLabelResponse> {
params.validate()?;
let path = label_path(merchant_id, label_id);
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Patch, &path, Some(&body), None)
.await
}
pub async fn delete(
&self,
merchant_id: &str,
label_id: &str,
) -> Result<ShopLabelDeleteResponse> {
let path = label_path(merchant_id, label_id);
self.inner
.request_body_keyed(HttpMethod::Delete, &path, None, None)
.await
}
pub async fn set_for_shop(
&self,
merchant_id: &str,
profile_id: &str,
params: &ShopLabelsSetRequest,
) -> Result<ShopLabelsResponse> {
params.validate()?;
let path = format!(
"/account/{}/business-profile/{}/labels",
encode_segment(merchant_id),
encode_segment(profile_id)
);
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Put, &path, Some(&body), None)
.await
}
}
fn labels_path(merchant_id: &str) -> String {
format!(
"/account/{}/business-profile/labels",
encode_segment(merchant_id)
)
}
fn label_path(merchant_id: &str, label_id: &str) -> String {
format!("{}/{}", labels_path(merchant_id), encode_segment(label_id))
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelUpdateRequest {
pub name: String,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ShopLabelUpdateRequest {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
}
const SHOP_LABEL_UPDATE_REQUEST_NAMED: &[&str] = &["name"];
impl ValidateRequest for ShopLabelUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SHOP_LABEL_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ShopLabelUpdateRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelCreateRequest {
pub name: String,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ShopLabelCreateRequest {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
}
const SHOP_LABEL_CREATE_REQUEST_NAMED: &[&str] = &["name"];
impl ValidateRequest for ShopLabelCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SHOP_LABEL_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ShopLabelCreateRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopLabelsSetRequest {
pub label_ids: Vec<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ShopLabelsSetRequest {
pub fn new(label_ids: Vec<String>) -> Self {
Self {
label_ids,
..Default::default()
}
}
}
const SHOP_LABELS_SET_REQUEST_NAMED: &[&str] = &["label_ids"];
impl ValidateRequest for ShopLabelsSetRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SHOP_LABELS_SET_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ShopLabelsSetRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const LABEL_JSON: &str = r#"{
"label_id": "lbl_1",
"name": "Gaming",
"profile_ids": ["pro_1", "pro_2"],
"surprise_field": 1
}"#;
#[tokio::test]
async fn list_gets_the_labels_path() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{LABEL_JSON}]"))]);
let labels = client.shop_labels().list("mer/1").await.unwrap();
assert_eq!(labels[0].label_id, "lbl_1");
assert_eq!(labels[0].profile_ids, ["pro_1", "pro_2"]);
assert_eq!(labels[0].extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/account/mer%2F1/business-profile/labels"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn create_posts_the_name_to_the_labels_path() {
let (client, mock) = client_with(vec![Step::ok(LABEL_JSON)]);
let label = client
.shop_labels()
.create("mer_1", &ShopLabelCreateRequest::new("Gaming"))
.await
.unwrap();
assert_eq!(label.name, "Gaming");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/business-profile/labels"
);
assert_eq!(seen[0].body_json(), json!({"name": "Gaming"}));
}
#[tokio::test]
async fn set_for_shop_puts_the_complete_set_even_when_empty() {
let (client, mock) = client_with(vec![
Step::ok(
r#"{"profile_id":"pro_1","labels":[{"label_id":"lbl_1","name":"Gaming"}],"surprise_field":1}"#,
),
Step::ok(r#"{"profile_id":"pro_1","labels":[]}"#),
]);
let labels = client.shop_labels();
let out = labels
.set_for_shop(
"mer_1",
"pro/1",
&ShopLabelsSetRequest::new(vec!["lbl_1".to_string()]),
)
.await
.unwrap();
assert_eq!(out.profile_id, "pro_1");
assert_eq!(out.labels[0].name, "Gaming");
assert_eq!(out.extra["surprise_field"], 1);
let cleared = labels
.set_for_shop("mer_1", "pro/1", &ShopLabelsSetRequest::new(Vec::new()))
.await
.unwrap();
assert!(cleared.labels.is_empty());
let seen = mock.seen.lock().unwrap();
for step in seen.iter() {
assert_eq!(step.method, "PUT");
assert_eq!(
step.url,
"https://api.test/account/mer_1/business-profile/pro%2F1/labels"
);
}
assert_eq!(seen[0].body_json(), json!({"label_ids": ["lbl_1"]}));
assert_eq!(seen[1].body_json(), json!({"label_ids": []}));
}
#[tokio::test]
async fn update_patches_and_delete_deletes_the_label_path() {
let (client, mock) = client_with(vec![
Step::ok(LABEL_JSON),
Step::ok(r#"{"label_id":"lbl_1","deleted":true,"surprise_field":1}"#),
]);
let labels = client.shop_labels();
let renamed = labels
.update("mer_1", "lbl/1", &ShopLabelUpdateRequest::new("Games"))
.await
.unwrap();
assert_eq!(renamed.label_id, "lbl_1");
let deleted = labels.delete("mer_1", "lbl/1").await.unwrap();
assert!(deleted.deleted);
assert_eq!(deleted.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
for step in seen.iter() {
assert_eq!(
step.url,
"https://api.test/account/mer_1/business-profile/labels/lbl%2F1"
);
}
assert_eq!(seen[0].method, "PATCH");
assert_eq!(seen[0].body_json(), json!({"name": "Games"}));
assert_eq!(seen[1].method, "DELETE");
assert!(seen[1].body.is_none());
}
#[test]
fn shop_label_update_request_named_fields_are_complete() {
let value = serde_json::to_value(ShopLabelUpdateRequest::new("Games")).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SHOP_LABEL_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"SHOP_LABEL_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
let mut colliding = ShopLabelUpdateRequest::new("Games");
colliding.extra.insert("name".to_string(), json!("x"));
assert!(colliding.validate().is_err());
}
#[test]
fn shop_label_create_request_named_fields_are_complete() {
let value = serde_json::to_value(ShopLabelCreateRequest::new("Gaming")).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SHOP_LABEL_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"SHOP_LABEL_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn shop_labels_set_request_named_fields_are_complete() {
let value =
serde_json::to_value(ShopLabelsSetRequest::new(vec!["lbl_1".to_string()])).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SHOP_LABELS_SET_REQUEST_NAMED.contains(&key.as_str()),
"SHOP_LABELS_SET_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_extra_keys_colliding_with_named_fields() {
let mut create = ShopLabelCreateRequest::new("Gaming");
create.extra.insert("name".to_string(), json!("Other"));
match create.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut set = ShopLabelsSetRequest::new(Vec::new());
set.extra.insert("label_ids".to_string(), json!([]));
match set.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("label_ids")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn label_writes_ignore_the_client_wide_idempotency_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::ok("{}"),
],
2,
);
let labels = client.with_idempotency_key("client-key").shop_labels();
assert!(
labels
.create("mer_1", &ShopLabelCreateRequest::new("Gaming"))
.await
.is_err()
);
assert!(
labels
.update("mer_1", "lbl_1", &ShopLabelUpdateRequest::new("Games"))
.await
.is_err()
);
assert!(labels.delete("mer_1", "lbl_1").await.is_err());
assert!(
labels
.set_for_shop("mer_1", "pro_1", &ShopLabelsSetRequest::new(Vec::new()))
.await
.is_err()
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 4);
assert!(seen.iter().all(|step| !step.had_idempotency_key()));
}
}