use std::fmt;
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::{
InvoiceEmailDelivery, InvoiceEmailDeliveryList, InvoiceList, InvoiceNoTaxReason,
InvoiceShareLink, MerchantInvoiceDocument,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Invoices {
inner: Arc<Inner>,
}
impl Invoices {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(&self, params: &CreateInvoiceRequest) -> Result<MerchantInvoiceDocument> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/invoices", Some(&body), &[], None)
.await
}
pub async fn create_idempotent(
&self,
params: &CreateInvoiceRequest,
idempotency_key: &str,
) -> Result<MerchantInvoiceDocument> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/invoices",
Some(&body),
&[],
Some(idempotency_key),
)
.await
}
pub async fn list(&self, params: &InvoiceListParams) -> Result<InvoiceList> {
self.inner
.request(
HttpMethod::Get,
"/invoices",
None,
¶ms.to_query(true),
None,
)
.await
}
pub async fn list_for_payment(
&self,
payment_id: &str,
params: &InvoicePageParams,
) -> Result<InvoiceList> {
let path = format!("/payments/{}/invoices", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, ¶ms.to_query(), None)
.await
}
pub async fn list_for_product(
&self,
product_id: &str,
params: &InvoiceListParams,
) -> Result<InvoiceList> {
let path = format!("/products/{}/invoices", encode_segment(product_id));
self.inner
.request(HttpMethod::Get, &path, None, ¶ms.to_query(false), None)
.await
}
pub async fn export(&self, params: &InvoiceExportParams) -> Result<Vec<u8>> {
self.inner
.request_bytes(
HttpMethod::Get,
"/invoices/export",
¶ms.to_query(),
params.format.accept(),
)
.await
}
pub async fn retrieve(&self, invoice_id: &str) -> Result<MerchantInvoiceDocument> {
self.inner
.request(HttpMethod::Get, &invoice_path(invoice_id), None, &[], None)
.await
}
pub async fn update(
&self,
invoice_id: &str,
params: &UpdateInvoiceRequest,
) -> Result<MerchantInvoiceDocument> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(
HttpMethod::Patch,
&invoice_path(invoice_id),
Some(&body),
&[],
None,
)
.await
}
pub async fn delete(&self, invoice_id: &str) -> Result<()> {
self.inner
.request_body_keyed_with_query::<serde::de::IgnoredAny>(
HttpMethod::Delete,
&invoice_path(invoice_id),
None,
&[],
None,
)
.await
.map(|_| ())
}
pub async fn finalize(&self, invoice_id: &str) -> Result<MerchantInvoiceDocument> {
let path = format!("{}/finalize", invoice_path(invoice_id));
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn void(
&self,
invoice_id: &str,
params: &VoidInvoiceRequest,
) -> Result<MerchantInvoiceDocument> {
params.validate()?;
let path = format!("{}/void", invoice_path(invoice_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn create_credit_note(
&self,
invoice_id: &str,
params: &CreateCreditNoteRequest,
) -> Result<MerchantInvoiceDocument> {
params.validate()?;
let path = format!("{}/credit-note", invoice_path(invoice_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn download_pdf(&self, invoice_id: &str) -> Result<Vec<u8>> {
let path = format!("{}/pdf", invoice_path(invoice_id));
self.inner
.request_bytes(HttpMethod::Get, &path, &[], "application/pdf")
.await
}
pub async fn create_share_link(&self, invoice_id: &str) -> Result<InvoiceShareLink> {
let path = format!("{}/share-link", invoice_path(invoice_id));
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn send_email(&self, invoice_id: &str) -> Result<InvoiceEmailDelivery> {
let path = format!("{}/email", invoice_path(invoice_id));
self.inner
.request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn list_emails(&self, invoice_id: &str) -> Result<InvoiceEmailDeliveryList> {
let path = format!("{}/emails", invoice_path(invoice_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
}
fn invoice_path(invoice_id: &str) -> String {
format!("/invoices/{}", encode_segment(invoice_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(())
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct InvoiceSourceRef {
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub subscription_invoice_id: Option<String>,
}
impl InvoiceSourceRef {
pub fn payment(payment_id: impl Into<String>) -> Self {
Self {
payment_id: Some(payment_id.into()),
subscription_invoice_id: None,
}
}
pub fn subscription_cycle(subscription_invoice_id: impl Into<String>) -> Self {
Self {
payment_id: None,
subscription_invoice_id: Some(subscription_invoice_id.into()),
}
}
}
#[derive(Clone, Default, Serialize)]
pub struct InvoiceBuyer {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: 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>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
}
impl fmt::Debug for InvoiceBuyer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InvoiceBuyer")
.field("country", &self.country)
.field("region", &self.region)
.field("name", &"<redacted>")
.field("address", &"<redacted>")
.field("email", &"<redacted>")
.field("vat_id", &"<redacted>")
.field("tax_id", &"<redacted>")
.finish()
}
}
impl InvoiceBuyer {
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 address(mut self, address: impl Into<String>) -> Self {
self.address = Some(address.into());
self
}
#[must_use]
pub fn email(mut self, email: impl Into<String>) -> Self {
self.email = Some(email.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
}
#[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
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateInvoiceRequest {
pub source: InvoiceSourceRef,
#[serde(skip_serializing_if = "Option::is_none")]
pub finalize: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub buyer: Option<InvoiceBuyer>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notes: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub due_date: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl CreateInvoiceRequest {
pub fn new(source: InvoiceSourceRef) -> Self {
Self {
source,
..Default::default()
}
}
#[must_use]
pub fn finalize(mut self, finalize: bool) -> Self {
self.finalize = Some(finalize);
self
}
#[must_use]
pub fn buyer(mut self, buyer: InvoiceBuyer) -> Self {
self.buyer = Some(buyer);
self
}
#[must_use]
pub fn notes(mut self, notes: impl Into<String>) -> Self {
self.notes = Some(notes.into());
self
}
#[must_use]
pub fn due_date(mut self, due_date: impl Into<String>) -> Self {
self.due_date = Some(due_date.into());
self
}
}
const CREATE_INVOICE_REQUEST_NAMED: &[&str] = &["source", "finalize", "buyer", "notes", "due_date"];
impl ValidateRequest for CreateInvoiceRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
CREATE_INVOICE_REQUEST_NAMED,
"CreateInvoiceRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateInvoiceLine {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_rate_bp: Option<Option<i32>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_exemption_note: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reset_to_rule: Option<bool>,
}
impl UpdateInvoiceLine {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
..Default::default()
}
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn tax_rate_bp(mut self, tax_rate_bp: i32) -> Self {
self.tax_rate_bp = Some(Some(tax_rate_bp));
self
}
#[must_use]
pub fn no_tax_rate(mut self) -> Self {
self.tax_rate_bp = Some(None);
self
}
#[must_use]
pub fn tax_exemption_note(mut self, note: impl Into<String>) -> Self {
self.tax_exemption_note = Some(Some(note.into()));
self
}
#[must_use]
pub fn clear_tax_exemption_note(mut self) -> Self {
self.tax_exemption_note = Some(None);
self
}
#[must_use]
pub fn reset_to_rule(mut self) -> Self {
self.reset_to_rule = Some(true);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateInvoiceRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub buyer: Option<InvoiceBuyer>,
#[serde(skip_serializing_if = "Option::is_none")]
pub supply_date: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub period_start: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub period_end: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub due_date: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub notes: Option<Option<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub no_tax_reason: Option<Option<InvoiceNoTaxReason>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lines: Option<Vec<UpdateInvoiceLine>>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl UpdateInvoiceRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn buyer(mut self, buyer: InvoiceBuyer) -> Self {
self.buyer = Some(buyer);
self
}
#[must_use]
pub fn supply_date(mut self, supply_date: impl Into<String>) -> Self {
self.supply_date = Some(supply_date.into());
self
}
#[must_use]
pub fn period_start(mut self, period_start: impl Into<String>) -> Self {
self.period_start = Some(Some(period_start.into()));
self
}
#[must_use]
pub fn clear_period_start(mut self) -> Self {
self.period_start = Some(None);
self
}
#[must_use]
pub fn period_end(mut self, period_end: impl Into<String>) -> Self {
self.period_end = Some(Some(period_end.into()));
self
}
#[must_use]
pub fn clear_period_end(mut self) -> Self {
self.period_end = Some(None);
self
}
#[must_use]
pub fn due_date(mut self, due_date: impl Into<String>) -> Self {
self.due_date = Some(Some(due_date.into()));
self
}
#[must_use]
pub fn clear_due_date(mut self) -> Self {
self.due_date = Some(None);
self
}
#[must_use]
pub fn notes(mut self, notes: impl Into<String>) -> Self {
self.notes = Some(Some(notes.into()));
self
}
#[must_use]
pub fn clear_notes(mut self) -> Self {
self.notes = Some(None);
self
}
#[must_use]
pub fn no_tax_reason(mut self, reason: InvoiceNoTaxReason) -> Self {
self.no_tax_reason = Some(Some(reason));
self
}
#[must_use]
pub fn clear_no_tax_reason(mut self) -> Self {
self.no_tax_reason = Some(None);
self
}
#[must_use]
pub fn lines(mut self, lines: Vec<UpdateInvoiceLine>) -> Self {
self.lines = Some(lines);
self
}
}
const UPDATE_INVOICE_REQUEST_NAMED: &[&str] = &[
"buyer",
"supply_date",
"period_start",
"period_end",
"due_date",
"notes",
"no_tax_reason",
"lines",
];
impl ValidateRequest for UpdateInvoiceRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
UPDATE_INVOICE_REQUEST_NAMED,
"UpdateInvoiceRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct VoidInvoiceRequest {
pub reason: String,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl VoidInvoiceRequest {
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
..Default::default()
}
}
}
const VOID_INVOICE_REQUEST_NAMED: &[&str] = &["reason"];
impl ValidateRequest for VoidInvoiceRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
VOID_INVOICE_REQUEST_NAMED,
"VoidInvoiceRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreditNoteLine {
pub invoice_line_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
}
impl CreditNoteLine {
pub fn new(invoice_line_id: impl Into<String>) -> Self {
Self {
invoice_line_id: invoice_line_id.into(),
..Default::default()
}
}
#[must_use]
pub fn quantity(mut self, quantity: i64) -> Self {
self.quantity = Some(quantity);
self
}
#[must_use]
pub fn amount(mut self, amount: i64) -> Self {
self.amount = Some(amount);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateCreditNoteRequest {
pub reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub lines: Option<Vec<CreditNoteLine>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub finalize: Option<bool>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl CreateCreditNoteRequest {
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
..Default::default()
}
}
#[must_use]
pub fn lines(mut self, lines: Vec<CreditNoteLine>) -> Self {
self.lines = Some(lines);
self
}
#[must_use]
pub fn finalize(mut self, finalize: bool) -> Self {
self.finalize = Some(finalize);
self
}
}
const CREATE_CREDIT_NOTE_REQUEST_NAMED: &[&str] = &["reason", "lines", "finalize"];
impl ValidateRequest for CreateCreditNoteRequest {
fn validate(&self) -> Result<()> {
reject_collisions(
&self.extra,
CREATE_CREDIT_NOTE_REQUEST_NAMED,
"CreateCreditNoteRequest",
)
}
}
#[derive(Debug, Clone, Default)]
pub struct InvoiceListParams {
pub profile_id: Option<String>,
pub status: Option<String>,
pub kind: Option<String>,
pub test_mode: Option<bool>,
pub payment_id: Option<String>,
pub subscription_id: Option<String>,
pub subscription_invoice_id: Option<String>,
pub product_id: Option<String>,
pub from: Option<String>,
pub to: Option<String>,
pub q: Option<String>,
pub limit: Option<i64>,
pub offset: Option<i64>,
pub include_lines: Option<bool>,
}
impl InvoiceListParams {
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 status(mut self, status: impl Into<String>) -> Self {
self.status = Some(status.into());
self
}
#[must_use]
pub fn kind(mut self, kind: impl Into<String>) -> Self {
self.kind = Some(kind.into());
self
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
#[must_use]
pub fn payment_id(mut self, payment_id: impl Into<String>) -> Self {
self.payment_id = Some(payment_id.into());
self
}
#[must_use]
pub fn subscription_id(mut self, subscription_id: impl Into<String>) -> Self {
self.subscription_id = Some(subscription_id.into());
self
}
#[must_use]
pub fn subscription_invoice_id(mut self, subscription_invoice_id: impl Into<String>) -> Self {
self.subscription_invoice_id = Some(subscription_invoice_id.into());
self
}
#[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 from(mut self, from: impl Into<String>) -> Self {
self.from = Some(from.into());
self
}
#[must_use]
pub fn to(mut self, to: impl Into<String>) -> Self {
self.to = Some(to.into());
self
}
#[must_use]
pub fn q(mut self, q: impl Into<String>) -> Self {
self.q = Some(q.into());
self
}
#[must_use]
pub fn limit(mut self, limit: i64) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn include_lines(mut self, include_lines: bool) -> Self {
self.include_lines = Some(include_lines);
self
}
fn to_query(&self, with_product: bool) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
push_filters(
&mut q,
&self.profile_id,
&self.status,
&self.kind,
self.test_mode,
&self.payment_id,
&self.subscription_id,
&self.subscription_invoice_id,
);
if with_product {
push_opt(&mut q, "product_id", &self.product_id);
}
push_opt(&mut q, "from", &self.from);
push_opt(&mut q, "to", &self.to);
push_opt(&mut q, "q", &self.q);
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = self.include_lines {
q.push(("include_lines", v.to_string()));
}
q
}
}
fn push_opt(q: &mut Vec<(&'static str, String)>, key: &'static str, value: &Option<String>) {
if let Some(v) = value {
q.push((key, v.clone()));
}
}
#[allow(clippy::too_many_arguments)]
fn push_filters(
q: &mut Vec<(&'static str, String)>,
profile_id: &Option<String>,
status: &Option<String>,
kind: &Option<String>,
test_mode: Option<bool>,
payment_id: &Option<String>,
subscription_id: &Option<String>,
subscription_invoice_id: &Option<String>,
) {
push_opt(q, "profile_id", profile_id);
push_opt(q, "status", status);
push_opt(q, "kind", kind);
if let Some(v) = test_mode {
q.push(("test_mode", v.to_string()));
}
push_opt(q, "payment_id", payment_id);
push_opt(q, "subscription_id", subscription_id);
push_opt(q, "subscription_invoice_id", subscription_invoice_id);
}
#[derive(Debug, Clone, Default)]
pub struct InvoicePageParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl InvoicePageParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn limit(mut self, limit: i64) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
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, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvoiceExportFormat {
#[default]
Csv,
Json,
Xlsx,
Zip,
}
impl InvoiceExportFormat {
pub fn accept(self) -> &'static str {
match self {
Self::Csv => "text/csv",
Self::Json => "application/json",
Self::Xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
Self::Zip => "application/zip",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct InvoiceExportParams {
pub from: String,
pub to: String,
pub profile_id: Option<String>,
pub status: Option<String>,
pub kind: Option<String>,
pub test_mode: Option<bool>,
pub payment_id: Option<String>,
pub subscription_id: Option<String>,
pub subscription_invoice_id: Option<String>,
pub product_id: Option<String>,
pub q: Option<String>,
pub format: InvoiceExportFormat,
}
impl InvoiceExportParams {
pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
Self {
from: from.into(),
to: to.into(),
..Default::default()
}
}
#[must_use]
pub fn format(mut self, format: InvoiceExportFormat) -> Self {
self.format = format;
self
}
#[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 status(mut self, status: impl Into<String>) -> Self {
self.status = Some(status.into());
self
}
#[must_use]
pub fn kind(mut self, kind: impl Into<String>) -> Self {
self.kind = Some(kind.into());
self
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
#[must_use]
pub fn payment_id(mut self, payment_id: impl Into<String>) -> Self {
self.payment_id = Some(payment_id.into());
self
}
#[must_use]
pub fn subscription_id(mut self, subscription_id: impl Into<String>) -> Self {
self.subscription_id = Some(subscription_id.into());
self
}
#[must_use]
pub fn subscription_invoice_id(mut self, subscription_invoice_id: impl Into<String>) -> Self {
self.subscription_invoice_id = Some(subscription_invoice_id.into());
self
}
#[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 q(mut self, q: impl Into<String>) -> Self {
self.q = Some(q.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
push_filters(
&mut q,
&self.profile_id,
&self.status,
&self.kind,
self.test_mode,
&self.payment_id,
&self.subscription_id,
&self.subscription_invoice_id,
);
push_opt(&mut q, "product_id", &self.product_id);
q.push(("from", self.from.clone()));
q.push(("to", self.to.clone()));
push_opt(&mut q, "q", &self.q);
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const DOCUMENT_JSON: &str = r#"{
"id": "inv_1",
"merchant_id": "mer_1",
"profile_id": "pro_1",
"kind": "invoice",
"status": "draft",
"source": "payment",
"payment_id": "pay_1",
"test_mode": true,
"supply_date": "2026-01-02",
"seller": {"name": "Shop GmbH", "address": "Berlin", "country": "DE"},
"buyer": {"name": "Erika", "address": "Hamburg", "country": "DE"},
"currency": "EUR",
"net_amount": 1000,
"tax_amount": 190,
"gross_amount": 1190,
"locale": "de",
"tax_warnings": [],
"lines": [{
"id": "line_1", "position": 1, "description": "Mug", "quantity": 2,
"unit_net_amount": 500, "line_net_amount": 1000, "tax_rate_bp": 1900,
"tax_amount": 190, "gross_amount": 1190, "included": false,
"tax_source": "rule"
}],
"credit_notes": [],
"created_at": "2026-01-02T10:00:00Z",
"modified_at": "2026-01-02T10:00:00Z",
"surprise_field": 1
}"#;
fn list_json() -> String {
format!(
r#"{{"data":[{DOCUMENT_JSON}],"total_count":1,"limit":25,"offset":0,"surprise_field":2}}"#
)
}
const DELIVERY_JSON: &str = r#"{
"id": "ied_1", "invoice_id": "inv_1", "template_id": "invoice_issued",
"revision": 2, "origin": "manual", "status": "failed",
"recipient": "e***@example.com", "test_mode": false, "attempts": 1,
"error_code": "merchant_limit_reached",
"created_at": "2026-01-02T10:00:00Z", "modified_at": "2026-01-02T10:00:01Z",
"surprise_field": 3
}"#;
#[tokio::test]
async fn create_posts_the_source_and_decodes_the_document() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"))
.finalize(true)
.buyer(InvoiceBuyer::new().name("Erika").country("DE"))
.due_date("2026-02-01");
let doc = client.invoices().create(¶ms).await.unwrap();
assert_eq!(doc.id, "inv_1");
assert_eq!(doc.gross_amount, 1190);
assert_eq!(doc.lines[0].tax_rate_bp, Some(1900));
assert_eq!(doc.buyer.country.as_deref(), Some("DE"));
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices");
assert!(!seen[0].had_idempotency_key());
assert_eq!(
seen[0].body_json(),
json!({
"source": {"payment_id": "pay_1"},
"finalize": true,
"buyer": {"name": "Erika", "country": "DE"},
"due_date": "2026-02-01"
})
);
}
#[tokio::test]
async fn an_unkeyed_create_is_not_replayed_after_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(DOCUMENT_JSON),
],
2,
);
let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
assert!(client.invoices().create(¶ms).await.is_err());
assert_eq!(mock.seen.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn finalize_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(DOCUMENT_JSON),
],
2,
);
assert!(
client
.with_idempotency_key("client-key")
.invoices()
.finalize("inv_1")
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn create_sends_a_client_wide_key_and_is_replayed_after_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(DOCUMENT_JSON),
],
2,
);
let params = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
client
.with_idempotency_key("client-key")
.invoices()
.create(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen[0].header("idempotency-key"), Some("client-key"));
assert_eq!(seen[1].header("idempotency-key"), Some("client-key"));
}
#[tokio::test]
async fn create_idempotent_sends_the_key_and_is_replayed_after_a_5xx() {
let (client, mock) = client_with_retries(
vec![
Step::status(500, r#"{"error":{"message":"boom"}}"#),
Step::ok(DOCUMENT_JSON),
],
2,
);
let params = CreateInvoiceRequest::new(InvoiceSourceRef::subscription_cycle("sub_inv_1"));
client
.invoices()
.create_idempotent(¶ms, "inv-key-1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert_eq!(seen[1].header("idempotency-key"), Some("inv-key-1"));
assert_eq!(
seen[1].body_json(),
json!({"source": {"subscription_invoice_id": "sub_inv_1"}})
);
}
#[tokio::test]
async fn list_sends_every_filter() {
let (client, mock) = client_with(vec![Step::ok(&list_json())]);
let params = InvoiceListParams::new()
.profile_id("pro_1")
.status("issued")
.kind("invoice")
.test_mode(false)
.payment_id("pay_1")
.subscription_id("sub_1")
.subscription_invoice_id("si_1")
.product_id("prod_1")
.from("2026-01-01T00:00:00Z")
.to("2026-02-01T00:00:00Z")
.q("INV-")
.limit(10)
.offset(20)
.include_lines(true);
let page = client.invoices().list(¶ms).await.unwrap();
assert_eq!(page.total_count, 1);
assert_eq!(page.data[0].id, "inv_1");
assert_eq!(page.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoices?profile_id=pro_1&status=issued&kind=invoice\
&test_mode=false&payment_id=pay_1&subscription_id=sub_1\
&subscription_invoice_id=si_1&product_id=prod_1\
&from=2026-01-01T00:00:00Z&to=2026-02-01T00:00:00Z&q=INV-\
&limit=10&offset=20&include_lines=true"
);
}
#[tokio::test]
async fn list_for_payment_encodes_the_payment_and_pages() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"data":[],"total_count":0,"limit":5,"offset":0,
"merchant_of_record":"creem","refunded_amount":300,"surprise_field":4}"#,
)]);
let page = client
.invoices()
.list_for_payment("pay/1", &InvoicePageParams::new().limit(5).offset(0))
.await
.unwrap();
assert_eq!(page.merchant_of_record.as_deref(), Some("creem"));
assert_eq!(page.refunded_amount, Some(300));
assert_eq!(page.extra["surprise_field"], 4);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay%2F1/invoices?limit=5&offset=0"
);
}
#[tokio::test]
async fn list_for_product_takes_the_product_from_the_path() {
let (client, mock) = client_with(vec![Step::ok(&list_json())]);
let params = InvoiceListParams::new()
.product_id("other")
.status("issued");
let page = client
.invoices()
.list_for_product("prod/1", ¶ms)
.await
.unwrap();
assert_eq!(page.data[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/products/prod%2F1/invoices?status=issued"
);
}
#[tokio::test]
async fn export_returns_bytes_and_asks_for_the_chosen_format() {
let (client, mock) = client_with(vec![Step::ok("PK\u{3}\u{4}not json")]);
let params = InvoiceExportParams::new("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z")
.format(InvoiceExportFormat::Zip)
.status("issued");
let bytes = client.invoices().export(¶ms).await.unwrap();
assert!(bytes.starts_with(b"PK"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/invoices/export?status=issued\
&from=2026-01-01T00:00:00Z&to=2026-02-01T00:00:00Z"
);
assert_eq!(seen[0].header("accept"), Some("application/zip"));
}
#[tokio::test]
async fn export_defaults_to_csv() {
let (client, mock) = client_with(vec![Step::ok("number,buyer\n")]);
let params = InvoiceExportParams::new("a", "b");
client.invoices().export(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("accept"), Some("text/csv"));
}
#[tokio::test]
async fn retrieve_encodes_the_invoice_id() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let doc = client.invoices().retrieve("inv/1").await.unwrap();
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1");
}
#[tokio::test]
async fn update_patches_with_set_and_cleared_fields() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let params = UpdateInvoiceRequest::new()
.supply_date("2026-01-03")
.clear_due_date()
.notes("Thanks")
.no_tax_reason(InvoiceNoTaxReason::reverse_charge())
.lines(vec![
UpdateInvoiceLine::new("line_1")
.no_tax_rate()
.tax_exemption_note("Art. 196"),
UpdateInvoiceLine::new("line_2").reset_to_rule(),
]);
let doc = client.invoices().update("inv_1", ¶ms).await.unwrap();
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PATCH");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1");
assert_eq!(
seen[0].body_json(),
json!({
"supply_date": "2026-01-03",
"due_date": null,
"notes": "Thanks",
"no_tax_reason": {"kind": "reverse_charge"},
"lines": [
{"id": "line_1", "tax_rate_bp": null, "tax_exemption_note": "Art. 196"},
{"id": "line_2", "reset_to_rule": true}
]
})
);
}
#[tokio::test]
async fn delete_deletes_the_draft() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"deleted":true,"id":"inv_1","surprise_field":1}"#,
)]);
client.invoices().delete("inv_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1");
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn delete_accepts_an_empty_body() {
let (client, _mock) = client_with(vec![Step::ok("")]);
client.invoices().delete("inv_1").await.unwrap();
}
#[tokio::test]
async fn finalize_posts_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let doc = client.invoices().finalize("inv/1").await.unwrap();
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/finalize");
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn void_posts_the_reason() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let doc = client
.invoices()
.void("inv_1", &VoidInvoiceRequest::new("Sent to the wrong buyer"))
.await
.unwrap();
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/void");
assert_eq!(
seen[0].body_json(),
json!({"reason": "Sent to the wrong buyer"})
);
}
#[tokio::test]
async fn create_credit_note_posts_the_lines() {
let (client, mock) = client_with(vec![Step::ok(DOCUMENT_JSON)]);
let params = CreateCreditNoteRequest::new("Returned one mug")
.lines(vec![CreditNoteLine::new("line_1").quantity(1).amount(595)])
.finalize(true);
let doc = client
.invoices()
.create_credit_note("inv_1", ¶ms)
.await
.unwrap();
assert_eq!(doc.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/credit-note");
assert_eq!(
seen[0].body_json(),
json!({
"reason": "Returned one mug",
"lines": [{"invoice_line_id": "line_1", "quantity": 1, "amount": 595}],
"finalize": true
})
);
}
#[tokio::test]
async fn download_pdf_returns_bytes_and_asks_for_pdf() {
let (client, mock) = client_with(vec![Step::ok("%PDF-1.7\nnot json")]);
let bytes = client.invoices().download_pdf("inv/1").await.unwrap();
assert!(bytes.starts_with(b"%PDF-1.7"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/pdf");
assert_eq!(seen[0].header("accept"), Some("application/pdf"));
}
#[tokio::test]
async fn create_share_link_posts_and_decodes_the_link() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"url":"https://api.test/x?token=t","expires_at":"2026-01-09T00:00:00Z","surprise_field":5}"#,
)]);
let link = client.invoices().create_share_link("inv_1").await.unwrap();
assert_eq!(link.url, "https://api.test/x?token=t");
assert_eq!(link.extra["surprise_field"], 5);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/share-link");
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn send_email_posts_and_decodes_a_failed_delivery() {
let (client, mock) = client_with(vec![Step::ok(DELIVERY_JSON)]);
let out = client.invoices().send_email("inv_1").await.unwrap();
assert_eq!(out.status, "failed");
assert_eq!(out.error_code.as_deref(), Some("merchant_limit_reached"));
assert_eq!(out.revision, 2);
assert_eq!(out.extra["surprise_field"], 3);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/invoices/inv_1/email");
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn list_emails_gets_the_emails_path() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"data":[{DELIVERY_JSON}],"surprise_field":6}}"#
))]);
let out = client.invoices().list_emails("inv/1").await.unwrap();
assert_eq!(out.data[0].id, "ied_1");
assert_eq!(out.extra["surprise_field"], 6);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/invoices/inv%2F1/emails");
}
#[test]
fn buyer_debug_prints_no_personal_data() {
let buyer = InvoiceBuyer::new()
.name("Erika Muster")
.email("erika@example.com")
.vat_id("DE123456789")
.country("DE");
let out = format!("{buyer:?}");
assert!(out.contains("DE"));
for secret in ["Erika", "erika@example.com", "DE123456789"] {
assert!(!out.contains(secret), "Debug leaked `{secret}`: {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 create_invoice_request_named_fields_are_complete() {
let req = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"))
.finalize(true)
.buyer(InvoiceBuyer::new().name("x"))
.notes("n")
.due_date("2026-01-01");
assert_named_complete(
serde_json::to_value(req).unwrap(),
CREATE_INVOICE_REQUEST_NAMED,
"CREATE_INVOICE_REQUEST_NAMED",
);
}
#[test]
fn update_invoice_request_named_fields_are_complete() {
let req = UpdateInvoiceRequest::new()
.buyer(InvoiceBuyer::new().name("x"))
.supply_date("2026-01-01")
.period_start("2026-01-01")
.period_end("2026-01-31")
.due_date("2026-02-01")
.notes("n")
.no_tax_reason(InvoiceNoTaxReason::small_business())
.lines(vec![UpdateInvoiceLine::new("l")]);
assert_named_complete(
serde_json::to_value(req).unwrap(),
UPDATE_INVOICE_REQUEST_NAMED,
"UPDATE_INVOICE_REQUEST_NAMED",
);
}
#[test]
fn void_invoice_request_named_fields_are_complete() {
assert_named_complete(
serde_json::to_value(VoidInvoiceRequest::new("r")).unwrap(),
VOID_INVOICE_REQUEST_NAMED,
"VOID_INVOICE_REQUEST_NAMED",
);
}
#[test]
fn create_credit_note_request_named_fields_are_complete() {
let req = CreateCreditNoteRequest::new("r")
.lines(vec![CreditNoteLine::new("l")])
.finalize(false);
assert_named_complete(
serde_json::to_value(req).unwrap(),
CREATE_CREDIT_NOTE_REQUEST_NAMED,
"CREATE_CREDIT_NOTE_REQUEST_NAMED",
);
}
#[test]
fn validate_rejects_colliding_extra_keys() {
let mut create = CreateInvoiceRequest::new(InvoiceSourceRef::payment("pay_1"));
create.extra.insert("source".to_string(), json!({}));
let mut update = UpdateInvoiceRequest::new();
update.extra.insert("notes".to_string(), json!("x"));
let mut void = VoidInvoiceRequest::new("r");
void.extra.insert("reason".to_string(), json!("x"));
let mut credit = CreateCreditNoteRequest::new("r");
credit.extra.insert("lines".to_string(), json!([]));
for (err, key) in [
(create.validate().unwrap_err(), "source"),
(update.validate().unwrap_err(), "notes"),
(void.validate().unwrap_err(), "reason"),
(credit.validate().unwrap_err(), "lines"),
] {
match err {
DelopayError::InvalidRequest(msg) => assert!(msg.contains(key), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}
}