use std::sync::Arc;
use serde::Serialize;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::settlement::{
FeeStatementDetail, SettlementBackfillResponse, SettlementCurrentResponse,
SettlementLineListResponse, SettlementOverviewResponse, SettlementStatementListResponse,
ShopFeeConfigResponse, ShopVisibilityResponse, StatementAdjustment,
StatementAdjustmentListResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct Settlement {
inner: Arc<Inner>,
}
impl Settlement {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn overview(&self, test_mode: bool) -> Result<SettlementOverviewResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/overview",
None,
&[("test_mode", test_mode.to_string())],
None,
)
.await
}
pub async fn current(
&self,
test_mode: bool,
profile_id: Option<&str>,
) -> Result<SettlementCurrentResponse> {
let mut query = vec![("test_mode", test_mode.to_string())];
if let Some(profile_id) = profile_id {
query.push(("profile_id", profile_id.to_string()));
}
self.inner
.request(HttpMethod::Get, "/settlement/current", None, &query, None)
.await
}
pub async fn list_statements(
&self,
params: &StatementListParams,
) -> Result<SettlementStatementListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/statements",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn retrieve_statement(&self, statement_id: &str) -> Result<FeeStatementDetail> {
let path = statement_path(statement_id);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn generate_statement(
&self,
params: &StatementGenerateRequest,
) -> Result<FeeStatementDetail> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/statements/generate",
Some(&body),
&[],
None,
)
.await
}
pub async fn update_statement_payout(
&self,
statement_id: &str,
params: &StatementPayoutUpdateRequest,
) -> Result<FeeStatementDetail> {
let path = format!("{}/payout", statement_path(statement_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn download_statement_pdf(
&self,
statement_id: &str,
params: &StatementPdfParams,
) -> Result<Vec<u8>> {
let path = format!("{}/pdf", statement_path(statement_id));
self.inner
.request_bytes(
HttpMethod::Get,
&path,
¶ms.to_query(),
"application/pdf",
)
.await
}
pub async fn list_lines(
&self,
params: &SettlementLineListParams,
) -> Result<SettlementLineListResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/lines",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn fee_config(&self, profile_id: &str) -> Result<ShopFeeConfigResponse> {
self.inner
.request(
HttpMethod::Get,
"/settlement/fee-config",
None,
&[("profile_id", profile_id.to_string())],
None,
)
.await
}
pub async fn backfill(
&self,
params: &SettlementBackfillRequest,
) -> Result<SettlementBackfillResponse> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/settlement/backfill",
Some(&body),
&[],
None,
)
.await
}
pub async fn set_shop_visibility(
&self,
profile_id: &str,
visible_to_shop: bool,
) -> Result<ShopVisibilityResponse> {
let body = to_json_vec(&ShopVisibilityUpdateRequest {
profile_id: profile_id.to_string(),
visible_to_shop,
})?;
self.inner
.request(
HttpMethod::Post,
"/settlement/shops/visibility",
Some(&body),
&[],
None,
)
.await
}
pub async fn list_statement_adjustments(
&self,
statement_id: &str,
) -> Result<StatementAdjustmentListResponse> {
let path = format!("{}/adjustments", statement_path(statement_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn create_statement_adjustment(
&self,
statement_id: &str,
params: &StatementAdjustmentCreateRequest,
) -> Result<StatementAdjustment> {
let path = format!("{}/adjustments", statement_path(statement_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn delete_statement_adjustment(
&self,
statement_id: &str,
adjustment_id: &str,
) -> Result<()> {
let path = format!(
"{}/adjustments/{}",
statement_path(statement_id),
encode_segment(adjustment_id)
);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
}
fn statement_path(statement_id: &str) -> String {
format!("/settlement/statements/{}", encode_segment(statement_id))
}
#[derive(Debug, Clone)]
pub struct StatementListParams {
pub test_mode: bool,
pub profile_id: Option<String>,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl StatementListParams {
#[must_use]
pub fn new(test_mode: bool) -> Self {
Self {
test_mode,
profile_id: None,
limit: None,
offset: None,
}
}
#[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 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![("test_mode", self.test_mode.to_string())];
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.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)]
pub struct SettlementLineListParams {
pub profile_id: String,
pub year: i32,
pub month: u32,
pub test_mode: bool,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl SettlementLineListParams {
#[must_use]
pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
Self {
profile_id: profile_id.into(),
year,
month,
test_mode,
limit: None,
offset: None,
}
}
#[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![
("profile_id", self.profile_id.clone()),
("year", self.year.to_string()),
("month", self.month.to_string()),
("test_mode", self.test_mode.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, Default)]
pub struct StatementPdfParams {
pub currency: Option<String>,
pub include_transactions: Option<bool>,
}
impl StatementPdfParams {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn currency(mut self, currency: impl Into<String>) -> Self {
self.currency = Some(currency.into());
self
}
#[must_use]
pub fn include_transactions(mut self, include_transactions: bool) -> Self {
self.include_transactions = Some(include_transactions);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = &self.currency {
q.push(("currency", v.clone()));
}
if let Some(v) = self.include_transactions {
q.push(("include_transactions", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Serialize)]
pub struct StatementGenerateRequest {
pub profile_id: String,
pub year: i32,
pub month: u32,
pub test_mode: bool,
}
impl StatementGenerateRequest {
#[must_use]
pub fn new(profile_id: impl Into<String>, year: i32, month: u32, test_mode: bool) -> Self {
Self {
profile_id: profile_id.into(),
year,
month,
test_mode,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct StatementPayoutUpdateRequest {
pub payout_status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub paid_amount_usd: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub paid_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
impl StatementPayoutUpdateRequest {
#[must_use]
pub fn new(payout_status: impl Into<String>) -> Self {
Self {
payout_status: payout_status.into(),
paid_amount_usd: None,
paid_at: None,
note: None,
}
}
#[must_use]
pub fn paid_amount_usd(mut self, paid_amount_usd: i64) -> Self {
self.paid_amount_usd = Some(paid_amount_usd);
self
}
#[must_use]
pub fn paid_at(mut self, paid_at: impl Into<String>) -> Self {
self.paid_at = Some(paid_at.into());
self
}
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SettlementBackfillRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub to: Option<String>,
}
impl SettlementBackfillRequest {
#[must_use]
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 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
}
}
#[derive(Debug, Clone, Serialize)]
struct ShopVisibilityUpdateRequest {
profile_id: String,
visible_to_shop: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct StatementAdjustmentCreateRequest {
pub label: String,
pub amount_usd: i64,
}
impl StatementAdjustmentCreateRequest {
#[must_use]
pub fn charge(label: impl Into<String>, amount_usd: i64) -> Self {
Self {
label: label.into(),
amount_usd: amount_usd.saturating_abs(),
}
}
#[must_use]
pub fn credit(label: impl Into<String>, amount_usd: i64) -> Self {
Self {
label: label.into(),
amount_usd: -amount_usd.saturating_abs(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
const STATEMENT_JSON: &str = r#"{
"id": "stmt_1",
"merchant_id": "mer_1",
"profile_id": "pro_1",
"period_start": "2026-07-01T00:00:00Z",
"period_end": "2026-08-01T00:00:00Z",
"test_mode": false,
"gross_usd": 100000,
"platform_fee_usd": 1000,
"merchant_fee_usd": 15000,
"refund_usd": 0,
"net_to_shop_usd": 85000,
"line_count": 12,
"refund_count": 0,
"payout_status": "unpaid",
"paid_amount_usd": 0,
"generated_at": "2026-08-01T00:20:00Z",
"adjustments_usd": 0,
"net_after_adjustments_usd": 85000,
"breakdown": []
}"#;
#[tokio::test]
async fn overview_transmits_a_false_test_mode() {
let (client, mock) = client_with(vec![Step::ok(r#"{"shops":[]}"#)]);
client.settlement().overview(false).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/overview?test_mode=false"
);
}
#[tokio::test]
async fn current_omits_an_absent_profile_but_keeps_test_mode() {
let (client, mock) = client_with(vec![
Step::ok(
r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
"test_mode":true,"breakdown":[]}"#,
),
Step::ok(
r#"{"period_start":"2026-08-01T00:00:00Z","period_end":"2026-09-01T00:00:00Z",
"test_mode":true,"breakdown":[]}"#,
),
]);
client.settlement().current(true, None).await.unwrap();
client
.settlement()
.current(true, Some("pro/1"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/current?test_mode=true"
);
assert_eq!(
seen[1].url,
"https://api.test/settlement/current?test_mode=true&profile_id=pro/1"
);
}
#[tokio::test]
async fn list_statements_sends_every_set_filter() {
let (client, mock) = client_with(vec![Step::ok(r#"{"statements":[],"total_count":0}"#)]);
let params = StatementListParams::new(false)
.profile_id("pro_1")
.limit(20)
.offset(40);
client.settlement().list_statements(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements?test_mode=false&profile_id=pro_1&limit=20&offset=40"
);
}
#[tokio::test]
async fn retrieve_statement_encodes_the_id_and_decodes_the_breakdown() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let detail = client
.settlement()
.retrieve_statement("stmt/1")
.await
.unwrap();
assert_eq!(detail.summary.id, "stmt_1");
assert_eq!(detail.summary.net_after_adjustments_usd, 85000);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt%2F1"
);
}
#[tokio::test]
async fn generate_statement_posts_the_period() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let params = StatementGenerateRequest::new("pro_1", 2026, 7, false);
client
.settlement()
.generate_statement(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/generate"
);
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["year"], 2026);
assert_eq!(body["month"], 7);
assert_eq!(body["test_mode"], false);
}
#[tokio::test]
async fn update_statement_payout_posts_only_the_set_fields() {
let (client, mock) = client_with(vec![Step::ok(STATEMENT_JSON)]);
let params = StatementPayoutUpdateRequest::new("partial").paid_amount_usd(40000);
client
.settlement()
.update_statement_payout("stmt_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/payout"
);
let body = seen[0].body_json();
assert_eq!(body["payout_status"], "partial");
assert_eq!(body["paid_amount_usd"], 40000);
assert!(body.get("note").is_none());
assert!(body.get("paid_at").is_none());
}
#[tokio::test]
async fn download_statement_pdf_returns_bytes_and_asks_for_pdf() {
let (client, mock) = client_with(vec![Step::ok("%PDF-1.4\nnot json at all")]);
let params = StatementPdfParams::new()
.currency("EUR")
.include_transactions(true);
let bytes = client
.settlement()
.download_statement_pdf("stmt_1", ¶ms)
.await
.unwrap();
assert!(bytes.starts_with(b"%PDF-1.4"));
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/pdf?currency=EUR&include_transactions=true"
);
assert_eq!(seen[0].header("accept"), Some("application/pdf"));
assert_eq!(
seen[0]
.headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("accept"))
.count(),
1
);
}
#[tokio::test]
async fn list_lines_sends_the_full_period_key() {
let (client, mock) = client_with(vec![Step::ok(r#"{"lines":[],"total_count":0}"#)]);
let params = SettlementLineListParams::new("pro_1", 2026, 7, true).limit(50);
client.settlement().list_lines(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/lines?profile_id=pro_1&year=2026&month=7&test_mode=true&limit=50"
);
}
#[tokio::test]
async fn fee_config_scopes_by_profile() {
let (client, mock) =
client_with(vec![Step::ok(r#"{"profile_id":"pro_1","schedules":[]}"#)]);
let out = client.settlement().fee_config("pro_1").await.unwrap();
assert_eq!(out.profile_id, "pro_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/settlement/fee-config?profile_id=pro_1"
);
}
#[tokio::test]
async fn backfill_posts_an_empty_body_when_unrestricted() {
let (client, mock) = client_with(vec![Step::ok(r#"{"enqueued":true,"job_id":"job_1"}"#)]);
let out = client
.settlement()
.backfill(&SettlementBackfillRequest::new())
.await
.unwrap();
assert!(out.enqueued);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/settlement/backfill");
assert_eq!(seen[0].body_json(), serde_json::json!({}));
}
#[tokio::test]
async fn set_shop_visibility_posts_both_fields() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","visible_to_shop":false}"#,
)]);
let out = client
.settlement()
.set_shop_visibility("pro_1", false)
.await
.unwrap();
assert!(!out.visible_to_shop);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/settlement/shops/visibility");
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_1");
assert_eq!(body["visible_to_shop"], false);
}
#[tokio::test]
async fn adjustments_round_trip_on_the_statement_sub_path() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"adjustments":[]}"#),
Step::ok(
r#"{"id":"adj_1","label":"Setup fee","amount_usd":5000,
"created_at":"2026-08-02T00:00:00Z"}"#,
),
Step::ok(""),
]);
let settlement = client.settlement();
settlement
.list_statement_adjustments("stmt_1")
.await
.unwrap();
settlement
.create_statement_adjustment(
"stmt_1",
&StatementAdjustmentCreateRequest::charge("Setup fee", 5000),
)
.await
.unwrap();
settlement
.delete_statement_adjustment("stmt_1", "adj/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/settlement/statements/stmt_1/adjustments"
);
assert_eq!(seen[1].method, "POST");
assert_eq!(seen[2].method, "DELETE");
assert_eq!(
seen[2].url,
"https://api.test/settlement/statements/stmt_1/adjustments/adj%2F1"
);
}
#[test]
fn credit_is_negative_and_charge_is_positive_whatever_the_caller_passes() {
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", 2500).amount_usd,
-2500
);
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", -2500).amount_usd,
-2500
);
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", 2500).amount_usd,
2500
);
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", -2500).amount_usd,
2500
);
}
#[test]
fn the_adjustment_constructors_survive_i64_min() {
assert_eq!(
StatementAdjustmentCreateRequest::charge("Setup", i64::MIN).amount_usd,
i64::MAX
);
assert_eq!(
StatementAdjustmentCreateRequest::credit("Goodwill", i64::MIN).amount_usd,
-i64::MAX
);
}
}