use serde::{Deserialize, Serialize};
use tracing::instrument;
use crate::core::client::UspsClient;
use crate::core::error::{Result, UspsError};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentAccountType {
Eps,
PermitImprint,
PostageMeter,
Omas,
}
impl std::fmt::Display for PaymentAccountType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Eps => write!(f, "EPS"),
Self::PermitImprint => write!(f, "PERMIT_IMPRINT"),
Self::PostageMeter => write!(f, "POSTAGE_METER"),
Self::Omas => write!(f, "OMAS"),
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountBalanceResponse {
pub account_id: String,
#[serde(default)]
pub account_type: Option<String>,
pub available_balance: f64,
#[serde(default)]
pub pending_balance: Option<f64>,
#[serde(default)]
pub currency: Option<String>,
pub status: String,
#[serde(default)]
pub account_holder_name: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAuthorizationRequest {
pub account_id: String,
pub amount: f64,
pub account_type: PaymentAccountType,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_reference_id: Option<String>,
}
impl PaymentAuthorizationRequest {
#[must_use]
pub fn new(
account_id: impl Into<String>,
amount: f64,
account_type: PaymentAccountType,
) -> Self {
Self {
account_id: account_id.into(),
amount,
account_type,
client_reference_id: None,
}
}
#[must_use]
pub fn client_reference_id(mut self, ref_id: impl Into<String>) -> Self {
self.client_reference_id = Some(ref_id.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentAuthorizationResponse {
pub authorization_id: String,
pub account_id: String,
pub authorized_amount: f64,
pub status: String,
#[serde(default)]
pub expiration_timestamp: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PaymentsService {
client: UspsClient,
}
impl PaymentsService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "get_account_balance")]
pub async fn get_account_balance(&self, account_id: &str) -> Result<AccountBalanceResponse> {
let clean_id = account_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El identificador de cuenta (account_id) no puede estar vacío".to_string(),
));
}
let endpoint = format!("/payments/v3/payment-accounts/{clean_id}/balance");
let empty_query: [(&str, &str); 0] = [];
self.client.get_with_query(&endpoint, &empty_query).await
}
#[instrument(skip(self), name = "authorize_payment")]
pub async fn authorize_payment(
&self,
req: &PaymentAuthorizationRequest,
) -> Result<PaymentAuthorizationResponse> {
if req.account_id.trim().is_empty() {
return Err(UspsError::InvalidInput(
"El account_id no puede estar vacío".to_string(),
));
}
if req.amount <= 0.0 {
return Err(UspsError::InvalidInput(
"El monto de autorización debe ser estrictamente mayor a 0.00 USD".to_string(),
));
}
let endpoint = "/payments/v3/payment-authorization";
self.client.post_json(endpoint, req).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn payment_authorization_request_builder() {
let req = PaymentAuthorizationRequest::new("EPS-123456", 150.75, PaymentAccountType::Eps)
.client_reference_id("ORDER-99001");
assert_eq!(req.account_id, "EPS-123456");
assert_eq!(req.amount, 150.75);
assert_eq!(req.account_type, PaymentAccountType::Eps);
assert_eq!(req.client_reference_id.as_deref(), Some("ORDER-99001"));
}
#[test]
fn account_balance_response_deserialization() {
let json = r#"{
"accountId": "EPS-123456",
"accountType": "EPS",
"availableBalance": 4520.50,
"pendingBalance": 120.00,
"currency": "USD",
"status": "ACTIVE",
"accountHolderName": "Acme Logistics Corp"
}"#;
let res: AccountBalanceResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.account_id, "EPS-123456");
assert_eq!(res.available_balance, 4520.50);
assert_eq!(res.pending_balance, Some(120.00));
assert_eq!(res.status, "ACTIVE");
assert_eq!(
res.account_holder_name.as_deref(),
Some("Acme Logistics Corp")
);
}
#[test]
fn payment_account_type_display() {
assert_eq!(PaymentAccountType::Eps.to_string(), "EPS");
assert_eq!(
PaymentAccountType::PermitImprint.to_string(),
"PERMIT_IMPRINT"
);
assert_eq!(
PaymentAccountType::PostageMeter.to_string(),
"POSTAGE_METER"
);
assert_eq!(PaymentAccountType::Omas.to_string(), "OMAS");
}
}