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::invoice::InvoiceNoTaxReason;
use crate::core::models::invoice_settings::{
EffectiveInvoiceSettings, InvoiceSettingsResponse, InvoiceTaxRule, InvoiceTaxRuleEvaluation,
InvoiceTaxRules,
};
use crate::http::client::{Inner, KeyPolicy};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
const LOGO_ACCEPT: &str = "image/png, image/jpeg";
#[derive(Debug, Clone)]
pub struct InvoiceSettings {
inner: Arc<Inner>,
}
impl InvoiceSettings {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn retrieve(&self) -> Result<InvoiceSettingsResponse> {
self.inner
.request(HttpMethod::Get, "/invoice-settings", None, &[], None)
.await
}
pub async fn update(&self, params: &InvoiceSettingsRequest) -> Result<InvoiceSettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
"/invoice-settings",
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve_for_shop(&self, profile_id: &str) -> Result<InvoiceSettingsResponse> {
self.inner
.request(HttpMethod::Get, &shop_path(profile_id), None, &[], None)
.await
}
pub async fn update_for_shop(
&self,
profile_id: &str,
params: &InvoiceSettingsRequest,
) -> Result<InvoiceSettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
&shop_path(profile_id),
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve_effective(&self, profile_id: &str) -> Result<EffectiveInvoiceSettings> {
let path = format!("{}/effective", shop_path(profile_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn preview(&self, params: &InvoicePreviewRequest) -> Result<Vec<u8>> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.send_raw_keyed(
HttpMethod::Post,
"/invoice-settings/preview",
Some(&body),
&[],
None,
KeyPolicy::BodyKeyOnly,
&[("accept", "application/pdf")],
None,
)
.await
}
pub async fn retrieve_logo(&self) -> Result<Vec<u8>> {
self.inner
.request_bytes(HttpMethod::Get, "/invoice-settings/logo", &[], LOGO_ACCEPT)
.await
}
pub async fn update_logo(
&self,
params: &InvoiceLogoRequest,
) -> Result<InvoiceSettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
"/invoice-settings/logo",
Some(&body),
&[],
None,
)
.await
}
pub async fn delete_logo(&self) -> Result<InvoiceSettingsResponse> {
self.inner
.request_body_keyed_with_query(
HttpMethod::Delete,
"/invoice-settings/logo",
None,
&[],
None,
)
.await
}
pub async fn retrieve_logo_for_shop(&self, profile_id: &str) -> Result<Vec<u8>> {
let path = format!("{}/logo", shop_path(profile_id));
self.inner
.request_bytes(HttpMethod::Get, &path, &[], LOGO_ACCEPT)
.await
}
pub async fn update_logo_for_shop(
&self,
profile_id: &str,
params: &InvoiceLogoRequest,
) -> Result<InvoiceSettingsResponse> {
params.validate()?;
let path = format!("{}/logo", shop_path(profile_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn delete_logo_for_shop(&self, profile_id: &str) -> Result<InvoiceSettingsResponse> {
let path = format!("{}/logo", shop_path(profile_id));
self.inner
.request_body_keyed_with_query(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn retrieve_tax_rules(&self) -> Result<InvoiceTaxRules> {
self.inner
.request(
HttpMethod::Get,
"/invoice-settings/tax-rules",
None,
&[],
None,
)
.await
}
pub async fn update_tax_rules(
&self,
params: &InvoiceTaxRulesRequest,
) -> Result<InvoiceTaxRules> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Put,
"/invoice-settings/tax-rules",
Some(&body),
&[],
None,
)
.await
}
pub async fn retrieve_tax_rules_for_shop(&self, profile_id: &str) -> Result<InvoiceTaxRules> {
let path = format!("{}/tax-rules", shop_path(profile_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update_tax_rules_for_shop(
&self,
profile_id: &str,
params: &InvoiceTaxRulesRequest,
) -> Result<InvoiceTaxRules> {
params.validate()?;
let path = format!("{}/tax-rules", shop_path(profile_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn delete_tax_rules_for_shop(&self, profile_id: &str) -> Result<InvoiceTaxRules> {
let path = format!("{}/tax-rules", shop_path(profile_id));
self.inner
.request_body_keyed_with_query(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn evaluate_tax_rules(
&self,
params: &InvoiceTaxRuleEvaluateRequest,
) -> Result<InvoiceTaxRuleEvaluation> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Post,
"/invoice-settings/tax-rules/evaluate",
Some(&body),
&[],
None,
)
.await
}
}
fn shop_path(profile_id: &str) -> String {
format!("/invoice-settings/profiles/{}", encode_segment(profile_id))
}
fn reject_collisions(
extra: &serde_json::Map<String, Value>,
named: &[&str],
type_name: &str,
) -> Result<()> {
for key in extra.keys() {
if named.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on {type_name}"
)));
}
}
Ok(())
}
macro_rules! setters {
($($(#[$doc:meta])* $name:ident: $ty:ty;)*) => {
$(
$(#[$doc])*
#[must_use]
pub fn $name(mut self, value: impl Into<$ty>) -> Self {
self.$name = Some(value.into());
self
}
)*
};
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceSettingsRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_address: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_tax_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_vat_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_registration: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_phone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_website: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bank_details: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub accent_color: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub footer_text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_notes: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_terms_days: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub number_prefix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub own_number_sequence: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub time_zone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub show_platform_branding: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_tax_rate_bp: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub no_tax_reason: Option<InvoiceNoTaxReason>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale_mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub document_title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seller_tax_id_label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_label_default: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_reporting_currency: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processor_tax_mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_issue: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl InvoiceSettingsRequest {
pub fn new() -> Self {
Self::default()
}
setters! {
seller_name: String;
seller_address: String;
seller_tax_id: String;
seller_vat_id: String;
seller_registration: String;
seller_email: String;
seller_phone: String;
seller_website: String;
bank_details: String;
accent_color: String;
footer_text: String;
default_notes: String;
payment_terms_days: i32;
number_prefix: String;
own_number_sequence: bool;
locale: String;
time_zone: String;
show_platform_branding: bool;
tax_mode: String;
default_tax_rate_bp: i32;
no_tax_reason: InvoiceNoTaxReason;
locale_mode: String;
document_title: String;
seller_tax_id_label: String;
tax_label_default: String;
tax_reporting_currency: String;
processor_tax_mode: String;
auto_issue: String;
}
}
impl From<&InvoiceSettingsResponse> for InvoiceSettingsRequest {
fn from(settings: &InvoiceSettingsResponse) -> Self {
Self {
seller_name: settings.seller_name.clone(),
seller_address: settings.seller_address.clone(),
seller_tax_id: settings.seller_tax_id.clone(),
seller_vat_id: settings.seller_vat_id.clone(),
seller_registration: settings.seller_registration.clone(),
seller_email: settings.seller_email.clone(),
seller_phone: settings.seller_phone.clone(),
seller_website: settings.seller_website.clone(),
bank_details: settings.bank_details.clone(),
accent_color: settings.accent_color.clone(),
footer_text: settings.footer_text.clone(),
default_notes: settings.default_notes.clone(),
payment_terms_days: settings.payment_terms_days,
number_prefix: settings.number_prefix.clone(),
own_number_sequence: settings.own_number_sequence,
locale: settings.locale.clone(),
time_zone: settings.time_zone.clone(),
show_platform_branding: settings.show_platform_branding,
tax_mode: settings.tax_mode.clone(),
default_tax_rate_bp: settings.default_tax_rate_bp,
no_tax_reason: settings.no_tax_reason.clone(),
locale_mode: settings.locale_mode.clone(),
document_title: settings.document_title.clone(),
seller_tax_id_label: settings.seller_tax_id_label.clone(),
tax_label_default: settings.tax_label_default.clone(),
tax_reporting_currency: settings.tax_reporting_currency.clone(),
processor_tax_mode: settings.processor_tax_mode.clone(),
auto_issue: settings.auto_issue.clone(),
extra: settings.extra.clone(),
}
}
}
const INVOICE_SETTINGS_REQUEST_NAMED: &[&str] = &[
"seller_name",
"seller_address",
"seller_tax_id",
"seller_vat_id",
"seller_registration",
"seller_email",
"seller_phone",
"seller_website",
"bank_details",
"accent_color",
"footer_text",
"default_notes",
"payment_terms_days",
"number_prefix",
"own_number_sequence",
"locale",
"time_zone",
"show_platform_branding",
"tax_mode",
"default_tax_rate_bp",
"no_tax_reason",
"locale_mode",
"document_title",
"seller_tax_id_label",
"tax_label_default",
"tax_reporting_currency",
"processor_tax_mode",
"auto_issue",
];
impl ValidateRequest for InvoiceSettingsRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
INVOICE_SETTINGS_REQUEST_NAMED,
"InvoiceSettingsRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceLogoRequest {
pub content_type: String,
pub data_base64: String,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl InvoiceLogoRequest {
pub fn new(content_type: impl Into<String>, data_base64: impl Into<String>) -> Self {
Self {
content_type: content_type.into(),
data_base64: data_base64.into(),
..Default::default()
}
}
}
const INVOICE_LOGO_REQUEST_NAMED: &[&str] = &["content_type", "data_base64"];
impl ValidateRequest for InvoiceLogoRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
INVOICE_LOGO_REQUEST_NAMED,
"InvoiceLogoRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoicePreviewRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub settings: Option<InvoiceSettingsRequest>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub clear: Vec<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl InvoicePreviewRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn settings(mut self, settings: InvoiceSettingsRequest) -> Self {
self.settings = Some(settings);
self
}
#[must_use]
pub fn clear(mut self, fields: Vec<String>) -> Self {
self.clear = fields;
self
}
}
const INVOICE_PREVIEW_REQUEST_NAMED: &[&str] = &["profile_id", "settings", "clear"];
impl ValidateRequest for InvoicePreviewRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
INVOICE_PREVIEW_REQUEST_NAMED,
"InvoicePreviewRequest",
)?;
if let Some(settings) = &self.settings {
settings.validate()?;
}
Ok(())
}
}
const INVOICE_TAX_RULE_NAMED: &[&str] = &[
"id",
"name",
"enabled",
"buyer_countries",
"buyer_regions",
"buyer_type",
"tax_categories",
"kind",
"rate_bp",
"tax_label",
"no_tax_reason",
"note",
];
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceTaxRulesRequest {
pub rules: Vec<InvoiceTaxRule>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl InvoiceTaxRulesRequest {
pub fn new(rules: Vec<InvoiceTaxRule>) -> Self {
Self {
rules,
..Default::default()
}
}
}
const INVOICE_TAX_RULES_REQUEST_NAMED: &[&str] = &["rules"];
impl ValidateRequest for InvoiceTaxRulesRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
INVOICE_TAX_RULES_REQUEST_NAMED,
"InvoiceTaxRulesRequest",
)?;
for rule in &self.rules {
reject_collisions(&rule.extra, INVOICE_TAX_RULE_NAMED, "InvoiceTaxRule")?;
}
Ok(())
}
}
#[derive(Clone, Default, Serialize)]
pub struct InvoiceTaxRuleBuyer {
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub vat_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_id: Option<String>,
}
impl std::fmt::Debug for InvoiceTaxRuleBuyer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InvoiceTaxRuleBuyer")
.field("country", &self.country)
.field("region", &self.region)
.field("vat_id", &self.vat_id.as_ref().map(|_| "<redacted>"))
.field("tax_id", &self.tax_id.as_ref().map(|_| "<redacted>"))
.finish()
}
}
impl InvoiceTaxRuleBuyer {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn country(mut self, country: impl Into<String>) -> Self {
self.country = Some(country.into());
self
}
#[must_use]
pub fn region(mut self, region: impl Into<String>) -> Self {
self.region = Some(region.into());
self
}
#[must_use]
pub fn vat_id(mut self, vat_id: impl Into<String>) -> Self {
self.vat_id = Some(vat_id.into());
self
}
#[must_use]
pub fn tax_id(mut self, tax_id: impl Into<String>) -> Self {
self.tax_id = Some(tax_id.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceTaxRuleEvaluateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub buyer: Option<InvoiceTaxRuleBuyer>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_category: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl InvoiceTaxRuleEvaluateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn buyer(mut self, buyer: InvoiceTaxRuleBuyer) -> Self {
self.buyer = Some(buyer);
self
}
#[must_use]
pub fn tax_category(mut self, tax_category: impl Into<String>) -> Self {
self.tax_category = Some(tax_category.into());
self
}
}
const INVOICE_TAX_RULE_EVALUATE_REQUEST_NAMED: &[&str] = &["profile_id", "buyer", "tax_category"];
impl ValidateRequest for InvoiceTaxRuleEvaluateRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
INVOICE_TAX_RULE_EVALUATE_REQUEST_NAMED,
"InvoiceTaxRuleEvaluateRequest",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const SETTINGS_JSON: &str = r#"{
"seller_name": "Shop GmbH",
"seller_address": "Berlin",
"payment_terms_days": 14,
"locale": "de",
"tax_mode": "no_vat",
"no_tax_reason": {"kind": "small_business"},
"default_tax_rate_bp": 1900,
"logo_url": "https://api.test/logo.png",
"logo_sha256": "abc",
"modified_at": "2026-01-01T00:00:00Z",
"surprise_field": 1
}"#;
const TAX_RULES_JSON: &str = r#"{
"profile_id": "pro_1",
"own_rules": true,
"rules": [{
"id": "itr_1", "name": "FR standard", "enabled": true,
"buyer_countries": ["FR"], "buyer_regions": [], "buyer_type": "any",
"tax_categories": [], "kind": "rate", "rate_bp": 2000, "tax_label": "TVA"
}],
"surprise_field": 2
}"#;
#[tokio::test]
async fn retrieve_gets_the_merchant_default() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client.invoice_settings().retrieve().await.unwrap();
assert_eq!(out.seller_name.as_deref(), Some("Shop GmbH"));
assert_eq!(out.payment_terms_days, Some(14));
assert_eq!(
out.no_tax_reason.as_ref().map(|r| r.kind.as_str()),
Some("small_business")
);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoice-settings");
}
#[tokio::test]
async fn update_puts_the_whole_object_built_from_a_read() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let read: InvoiceSettingsResponse = serde_json::from_str(SETTINGS_JSON).unwrap();
let params = InvoiceSettingsRequest::from(&read).seller_name("Shop AG");
let out = client.invoice_settings().update(¶ms).await.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/invoice-settings");
assert_eq!(
seen[0].body_json(),
json!({
"seller_name": "Shop AG",
"seller_address": "Berlin",
"payment_terms_days": 14,
"locale": "de",
"tax_mode": "no_vat",
"no_tax_reason": {"kind": "small_business"},
"default_tax_rate_bp": 1900,
"surprise_field": 1
})
);
}
#[tokio::test]
async fn retrieve_for_shop_encodes_the_profile_id() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client
.invoice_settings()
.retrieve_for_shop("pro/1")
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro%2F1"
);
}
#[tokio::test]
async fn update_for_shop_puts_the_shop_override() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let params = InvoiceSettingsRequest::new()
.number_prefix("BER")
.own_number_sequence(true);
let out = client
.invoice_settings()
.update_for_shop("pro_1", ¶ms)
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1"
);
assert_eq!(
seen[0].body_json(),
json!({"number_prefix": "BER", "own_number_sequence": true})
);
}
#[tokio::test]
async fn retrieve_effective_decodes_the_sources() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"profile_id":"pro_1","settings":{SETTINGS_JSON},
"sources":{{"seller_name":"merchant","locale":"shop"}},"surprise_field":3}}"#
))]);
let out = client
.invoice_settings()
.retrieve_effective("pro_1")
.await
.unwrap();
assert_eq!(out.profile_id, "pro_1");
assert_eq!(out.sources["seller_name"], "merchant");
assert_eq!(out.settings.extra["surprise_field"], 1);
assert_eq!(out.extra["surprise_field"], 3);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1/effective"
);
}
#[tokio::test]
async fn update_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(SETTINGS_JSON),
],
2,
);
let params = InvoiceSettingsRequest::new().seller_name("Shop AG");
assert!(
client
.with_idempotency_key("client-key")
.invoice_settings()
.update(¶ms)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn preview_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("%PDF-1.7\nnot json"),
],
2,
);
let params = InvoicePreviewRequest::new().profile_id("pro_1");
assert!(
client
.with_idempotency_key("client-key")
.invoice_settings()
.preview(¶ms)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn preview_posts_the_body_and_returns_the_pdf() {
let (client, mock) = client_with(vec![Step::ok("%PDF-1.7\nnot json")]);
let params = InvoicePreviewRequest::new()
.profile_id("pro_1")
.settings(InvoiceSettingsRequest::new().accent_color("#112233"))
.clear(vec!["seller_phone".to_string()]);
let pdf = client.invoice_settings().preview(¶ms).await.unwrap();
assert!(pdf.starts_with(b"%PDF-1.7"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/preview");
assert_eq!(seen[0].header("accept"), Some("application/pdf"));
assert_eq!(
seen[0].body_json(),
json!({
"profile_id": "pro_1",
"settings": {"accent_color": "#112233"},
"clear": ["seller_phone"]
})
);
}
#[tokio::test]
async fn retrieve_logo_returns_the_image_bytes() {
let (client, mock) = client_with(vec![Step::ok("\u{89}PNG not json")]);
let bytes = client.invoice_settings().retrieve_logo().await.unwrap();
assert!(bytes.ends_with(b"PNG not json"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/logo");
assert_eq!(seen[0].header("accept"), Some(LOGO_ACCEPT));
}
#[tokio::test]
async fn update_logo_puts_the_base64_image() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client
.invoice_settings()
.update_logo(&InvoiceLogoRequest::new("image/png", "iVBORw0KGgo="))
.await
.unwrap();
assert_eq!(out.logo_sha256.as_deref(), Some("abc"));
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/logo");
assert_eq!(
seen[0].body_json(),
json!({"content_type": "image/png", "data_base64": "iVBORw0KGgo="})
);
}
#[tokio::test]
async fn delete_logo_deletes_the_merchant_logo() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client.invoice_settings().delete_logo().await.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/logo");
}
#[tokio::test]
async fn retrieve_logo_for_shop_gets_the_shop_logo() {
let (client, mock) = client_with(vec![Step::ok("\u{ff}\u{d8}jpeg")]);
let bytes = client
.invoice_settings()
.retrieve_logo_for_shop("pro/1")
.await
.unwrap();
assert!(bytes.ends_with(b"jpeg"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro%2F1/logo"
);
assert_eq!(seen[0].header("accept"), Some(LOGO_ACCEPT));
}
#[tokio::test]
async fn update_logo_for_shop_puts_the_shop_logo() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client
.invoice_settings()
.update_logo_for_shop("pro_1", &InvoiceLogoRequest::new("image/jpeg", "/9j/"))
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1/logo"
);
assert_eq!(
seen[0].body_json(),
json!({"content_type": "image/jpeg", "data_base64": "/9j/"})
);
}
#[tokio::test]
async fn delete_logo_for_shop_deletes_the_shop_logo() {
let (client, mock) = client_with(vec![Step::ok(SETTINGS_JSON)]);
let out = client
.invoice_settings()
.delete_logo_for_shop("pro_1")
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1/logo"
);
}
#[tokio::test]
async fn retrieve_tax_rules_gets_the_merchant_list() {
let (client, mock) = client_with(vec![Step::ok(TAX_RULES_JSON)]);
let out = client
.invoice_settings()
.retrieve_tax_rules()
.await
.unwrap();
assert!(out.own_rules);
assert_eq!(out.rules[0].rate_bp, Some(2000));
assert_eq!(out.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/tax-rules");
}
#[tokio::test]
async fn update_tax_rules_puts_the_whole_list() {
let (client, mock) = client_with(vec![Step::ok(TAX_RULES_JSON)]);
let params = InvoiceTaxRulesRequest::new(vec![
InvoiceTaxRule::no_tax("EU B2B", "reverse_charge", "Reverse charge")
.buyer_type("vat_registered"),
]);
let out = client
.invoice_settings()
.update_tax_rules(¶ms)
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/invoice-settings/tax-rules");
assert_eq!(
seen[0].body_json(),
json!({"rules": [{
"name": "EU B2B",
"enabled": true,
"buyer_countries": [],
"buyer_regions": [],
"buyer_type": "vat_registered",
"tax_categories": [],
"kind": "no_tax",
"no_tax_reason": "reverse_charge",
"note": "Reverse charge"
}]})
);
}
#[tokio::test]
async fn retrieve_tax_rules_for_shop_encodes_the_profile_id() {
let (client, mock) = client_with(vec![Step::ok(TAX_RULES_JSON)]);
let out = client
.invoice_settings()
.retrieve_tax_rules_for_shop("pro/1")
.await
.unwrap();
assert_eq!(out.profile_id.as_deref(), Some("pro_1"));
assert_eq!(out.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro%2F1/tax-rules"
);
}
#[tokio::test]
async fn update_tax_rules_for_shop_puts_an_empty_list() {
let (client, mock) = client_with(vec![Step::ok(TAX_RULES_JSON)]);
let out = client
.invoice_settings()
.update_tax_rules_for_shop("pro_1", &InvoiceTaxRulesRequest::new(Vec::new()))
.await
.unwrap();
assert_eq!(out.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1/tax-rules"
);
assert_eq!(seen[0].body_json(), json!({"rules": []}));
}
#[tokio::test]
async fn delete_tax_rules_for_shop_returns_the_inherited_list() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","own_rules":false,"rules":[],"surprise_field":4}"#,
)]);
let out = client
.invoice_settings()
.delete_tax_rules_for_shop("pro_1")
.await
.unwrap();
assert!(!out.own_rules);
assert_eq!(out.extra["surprise_field"], 4);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/profiles/pro_1/tax-rules"
);
}
#[tokio::test]
async fn evaluate_tax_rules_posts_the_buyer_and_category() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","rules_source":"merchant","buyer_type":"business",
"vat_registered":true,"tax_category":"books","source":"rule",
"matched_rule":{"id":"itr_1","name":"EU B2B","kind":"no_tax",
"no_tax_reason":"reverse_charge","note":"Reverse charge"},
"matched_position":0,
"outcome":{"kind":"no_tax","no_tax_reason":"reverse_charge","note":"Reverse charge"},
"surprise_field":5}"#,
)]);
let params = InvoiceTaxRuleEvaluateRequest::new()
.profile_id("pro_1")
.buyer(InvoiceTaxRuleBuyer::new().country("FR").vat_id("FR123"))
.tax_category("books");
let out = client
.invoice_settings()
.evaluate_tax_rules(¶ms)
.await
.unwrap();
assert!(out.vat_registered);
assert_eq!(out.matched_position, Some(0));
assert_eq!(out.outcome.kind, "no_tax");
assert_eq!(out.extra["surprise_field"], 5);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/invoice-settings/tax-rules/evaluate"
);
assert_eq!(
seen[0].body_json(),
json!({
"profile_id": "pro_1",
"buyer": {"country": "FR", "vat_id": "FR123"},
"tax_category": "books"
})
);
}
#[test]
fn tax_rule_buyer_debug_redacts_the_tax_ids() {
let buyer = InvoiceTaxRuleBuyer::new().country("FR").vat_id("FR123456");
let out = format!("{buyer:?}");
assert!(out.contains("FR"));
assert!(!out.contains("FR123456"), "Debug leaked the VAT id: {out}");
}
fn assert_named_complete(value: Value, named: &[&str], name: &str) {
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
named.contains(&key.as_str()),
"{name} is missing wire key `{key}`"
);
}
}
#[test]
fn invoice_settings_request_named_fields_are_complete() {
let req = InvoiceSettingsRequest::new()
.seller_name("a")
.seller_address("a")
.seller_tax_id("a")
.seller_vat_id("a")
.seller_registration("a")
.seller_email("a")
.seller_phone("a")
.seller_website("a")
.bank_details("a")
.accent_color("a")
.footer_text("a")
.default_notes("a")
.payment_terms_days(1)
.number_prefix("a")
.own_number_sequence(true)
.locale("a")
.time_zone("a")
.show_platform_branding(true)
.tax_mode("a")
.default_tax_rate_bp(1)
.no_tax_reason(InvoiceNoTaxReason::reverse_charge())
.locale_mode("a")
.document_title("a")
.seller_tax_id_label("a")
.tax_label_default("a")
.tax_reporting_currency("a")
.processor_tax_mode("a")
.auto_issue("a");
let value = serde_json::to_value(req).unwrap();
assert_eq!(
value.as_object().unwrap().len(),
INVOICE_SETTINGS_REQUEST_NAMED.len()
);
assert_named_complete(
value,
INVOICE_SETTINGS_REQUEST_NAMED,
"INVOICE_SETTINGS_REQUEST_NAMED",
);
}
#[test]
fn invoice_logo_request_named_fields_are_complete() {
assert_named_complete(
serde_json::to_value(InvoiceLogoRequest::new("image/png", "x")).unwrap(),
INVOICE_LOGO_REQUEST_NAMED,
"INVOICE_LOGO_REQUEST_NAMED",
);
}
#[test]
fn invoice_preview_request_named_fields_are_complete() {
let req = InvoicePreviewRequest::new()
.profile_id("p")
.settings(InvoiceSettingsRequest::new())
.clear(vec!["x".to_string()]);
assert_named_complete(
serde_json::to_value(req).unwrap(),
INVOICE_PREVIEW_REQUEST_NAMED,
"INVOICE_PREVIEW_REQUEST_NAMED",
);
}
#[test]
fn invoice_tax_rule_named_fields_are_complete() {
let mut rule = InvoiceTaxRule::rate("r", 1)
.id("i")
.buyer_type("any")
.tax_label("l")
.note("n");
rule.no_tax_reason = Some("exempt".to_string());
assert_named_complete(
serde_json::to_value(rule).unwrap(),
INVOICE_TAX_RULE_NAMED,
"INVOICE_TAX_RULE_NAMED",
);
}
#[test]
fn invoice_tax_rules_request_named_fields_are_complete() {
assert_named_complete(
serde_json::to_value(InvoiceTaxRulesRequest::new(Vec::new())).unwrap(),
INVOICE_TAX_RULES_REQUEST_NAMED,
"INVOICE_TAX_RULES_REQUEST_NAMED",
);
}
#[test]
fn invoice_tax_rule_evaluate_request_named_fields_are_complete() {
let req = InvoiceTaxRuleEvaluateRequest::new()
.profile_id("p")
.buyer(InvoiceTaxRuleBuyer::new())
.tax_category("c");
assert_named_complete(
serde_json::to_value(req).unwrap(),
INVOICE_TAX_RULE_EVALUATE_REQUEST_NAMED,
"INVOICE_TAX_RULE_EVALUATE_REQUEST_NAMED",
);
}
#[test]
fn validate_rejects_colliding_extra_keys() {
let mut settings = InvoiceSettingsRequest::new();
settings.extra.insert("locale".to_string(), json!("en"));
let mut logo = InvoiceLogoRequest::new("image/png", "x");
logo.extra.insert("data_base64".to_string(), json!("y"));
let mut nested = InvoiceSettingsRequest::new();
nested.extra.insert("tax_mode".to_string(), json!("vat"));
let preview = InvoicePreviewRequest::new().settings(nested);
let mut rule = InvoiceTaxRule::rate("r", 1);
rule.extra.insert("kind".to_string(), json!("no_tax"));
let rules = InvoiceTaxRulesRequest::new(vec![rule]);
let mut evaluate = InvoiceTaxRuleEvaluateRequest::new();
evaluate.extra.insert("buyer".to_string(), json!({}));
for (err, key) in [
(settings.validate().unwrap_err(), "locale"),
(logo.validate().unwrap_err(), "data_base64"),
(preview.validate().unwrap_err(), "tax_mode"),
(rules.validate().unwrap_err(), "kind"),
(evaluate.validate().unwrap_err(), "buyer"),
] {
match err {
DelopayError::InvalidRequest(msg) => assert!(msg.contains(key), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}
}