use std::fmt;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use super::prices::MailClass;
use crate::core::client::UspsClient;
use crate::core::error::{Result, UspsError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum LabelImageType {
#[default]
Pdf,
Png,
Tiff,
Svg,
}
impl fmt::Display for LabelImageType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pdf => write!(f, "PDF"),
Self::Png => write!(f, "PNG"),
Self::Tiff => write!(f, "TIFF"),
Self::Svg => write!(f, "SVG"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum LabelSize {
#[default]
#[serde(rename = "4X6")]
Label4x6,
#[serde(rename = "4X4")]
Label4x4,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImageInfo {
pub image_type: LabelImageType,
#[serde(skip_serializing_if = "Option::is_none")]
pub label_type: Option<LabelSize>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LabelPartyAddress {
#[serde(skip_serializing_if = "Option::is_none")]
pub first_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub firm_name: Option<String>,
pub street_address: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub secondary_address: Option<String>,
pub city: String,
pub state: String,
#[serde(rename = "ZIPCode")]
pub zip_code: String,
#[serde(rename = "ZIPPlus4", skip_serializing_if = "Option::is_none")]
pub zip_plus4: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
}
impl LabelPartyAddress {
#[must_use]
pub fn new(
street_address: impl Into<String>,
city: impl Into<String>,
state: impl Into<String>,
zip_code: impl Into<String>,
) -> Self {
Self {
first_name: None,
last_name: None,
firm_name: None,
street_address: street_address.into(),
secondary_address: None,
city: city.into(),
state: state.into(),
zip_code: zip_code.into(),
zip_plus4: None,
phone: None,
email: None,
}
}
#[must_use]
pub fn person(mut self, first_name: impl Into<String>, last_name: impl Into<String>) -> Self {
self.first_name = Some(first_name.into());
self.last_name = Some(last_name.into());
self
}
#[must_use]
pub fn firm_name(mut self, firm: impl Into<String>) -> Self {
self.firm_name = Some(firm.into());
self
}
#[must_use]
pub fn secondary_address(mut self, sec: impl Into<String>) -> Self {
self.secondary_address = Some(sec.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PackageDescription {
pub mail_class: MailClass,
pub weight: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub length: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub width: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub height: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mailing_date: Option<String>,
}
impl PackageDescription {
#[must_use]
pub fn new(mail_class: MailClass, weight_lbs: f64) -> Self {
Self {
mail_class,
weight: weight_lbs,
length: None,
width: None,
height: None,
mailing_date: None,
}
}
#[must_use]
pub fn dimensions(mut self, length: f64, width: f64, height: f64) -> Self {
self.length = Some(length);
self.width = Some(width);
self.height = Some(height);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateLabelRequest {
pub image_info: ImageInfo,
pub from_address: LabelPartyAddress,
pub to_address: LabelPartyAddress,
pub package_description: PackageDescription,
}
impl CreateLabelRequest {
#[must_use]
pub fn new(
from_address: LabelPartyAddress,
to_address: LabelPartyAddress,
package_description: PackageDescription,
) -> Self {
Self {
image_info: ImageInfo {
image_type: LabelImageType::Pdf,
label_type: Some(LabelSize::Label4x6),
},
from_address,
to_address,
package_description,
}
}
#[must_use]
pub fn image_type(mut self, image_type: LabelImageType) -> Self {
self.image_info.image_type = image_type;
self
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateLabelResponse {
pub label_id: String,
pub tracking_number: String,
#[serde(default)]
pub label_broker_id: Option<String>,
#[serde(default)]
pub label_image: Option<String>,
#[serde(default)]
pub label_url: Option<String>,
#[serde(default)]
pub total_price: Option<f64>,
#[serde(default)]
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelLabelResponse {
pub status: String,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LabelBrokerRequest {
pub from_address: LabelPartyAddress,
pub to_address: LabelPartyAddress,
pub package_description: PackageDescription,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_reference_id: Option<String>,
}
impl LabelBrokerRequest {
#[must_use]
pub fn new(
from_address: LabelPartyAddress,
to_address: LabelPartyAddress,
package_description: PackageDescription,
) -> Self {
Self {
from_address,
to_address,
package_description,
customer_reference_id: None,
}
}
#[must_use]
pub fn customer_reference_id(mut self, ref_id: impl Into<String>) -> Self {
self.customer_reference_id = Some(ref_id.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LabelBrokerResponse {
pub label_broker_id: String,
pub tracking_number: String,
#[serde(default)]
pub qr_code: Option<String>,
pub status: String,
#[serde(default)]
pub expiration_date: Option<String>,
}
#[derive(Debug, Clone)]
pub struct LabelsService {
client: UspsClient,
}
impl LabelsService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "create_label")]
pub async fn create_label(&self, req: &CreateLabelRequest) -> Result<CreateLabelResponse> {
if req.from_address.street_address.trim().is_empty()
|| req.from_address.city.trim().is_empty()
|| req.from_address.state.trim().is_empty()
{
return Err(UspsError::InvalidInput(
"La dirección del remitente (from_address) está incompleta".to_string(),
));
}
if req.to_address.street_address.trim().is_empty()
|| req.to_address.city.trim().is_empty()
|| req.to_address.state.trim().is_empty()
{
return Err(UspsError::InvalidInput(
"La dirección del destinatario (to_address) está incompleta".to_string(),
));
}
if req.package_description.weight <= 0.0 {
return Err(UspsError::InvalidInput(
"El peso del paquete debe ser estrictamente mayor a 0 libras".to_string(),
));
}
let endpoint = "/labels/v3/label";
self.client.post_json(endpoint, req).await
}
#[instrument(skip(self), name = "cancel_label")]
pub async fn cancel_label(&self, label_id: &str) -> Result<CancelLabelResponse> {
let clean_id = label_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El label_id no puede estar vacío".to_string(),
));
}
let endpoint = format!("/labels/v3/label/{clean_id}");
let body = self.client.delete(&endpoint).await?;
if body.trim().is_empty() {
Ok(CancelLabelResponse {
status: "CANCELLED".to_string(),
message: Some(format!("Etiqueta {clean_id} anulada satisfactoriamente")),
})
} else {
serde_json::from_str::<CancelLabelResponse>(&body).map_err(UspsError::Serialization)
}
}
#[instrument(skip(self), name = "get_label_data")]
pub async fn get_label_data(&self, label_id: &str) -> Result<CreateLabelResponse> {
let clean_id = label_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El label_id no puede estar vacío".to_string(),
));
}
let endpoint = format!("/labels/v3/label/{clean_id}");
let empty_query: [(&str, &str); 0] = [];
self.client.get_with_query(&endpoint, &empty_query).await
}
#[instrument(skip(self), name = "create_label_broker")]
pub async fn create_label_broker(
&self,
req: &LabelBrokerRequest,
) -> Result<LabelBrokerResponse> {
if req.from_address.street_address.trim().is_empty()
|| req.from_address.city.trim().is_empty()
|| req.from_address.state.trim().is_empty()
{
return Err(UspsError::InvalidInput(
"La dirección del remitente (from_address) está incompleta".to_string(),
));
}
if req.to_address.street_address.trim().is_empty()
|| req.to_address.city.trim().is_empty()
|| req.to_address.state.trim().is_empty()
{
return Err(UspsError::InvalidInput(
"La dirección del destinatario (to_address) está incompleta".to_string(),
));
}
if req.package_description.weight <= 0.0 {
return Err(UspsError::InvalidInput(
"El peso del paquete debe ser estrictamente mayor a 0 libras".to_string(),
));
}
let endpoint = "/labels/v3/label-broker";
self.client.post_json(endpoint, req).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_label_request_builder() {
let from = LabelPartyAddress::new("123 Sender Way", "Austin", "TX", "78701")
.person("Alice", "Smith");
let to = LabelPartyAddress::new("456 Receiver Ave", "New York", "NY", "10001")
.person("Bob", "Jones");
let pkg = PackageDescription::new(MailClass::PriorityMail, 2.0).dimensions(10.0, 5.0, 4.0);
let req = CreateLabelRequest::new(from, to, pkg).image_type(LabelImageType::Pdf);
assert_eq!(req.image_info.image_type, LabelImageType::Pdf);
assert_eq!(req.from_address.city, "Austin");
assert_eq!(req.to_address.city, "New York");
assert_eq!(req.package_description.mail_class, MailClass::PriorityMail);
assert_eq!(req.package_description.weight, 2.0);
}
#[test]
fn create_label_response_deserialization() {
let json = r#"{
"labelId": "LBL-1234567890",
"trackingNumber": "9405500000000000000000",
"labelBrokerId": "LB-999",
"labelImage": "JVBERi0xLjQKJ...",
"totalPrice": 10.50,
"warnings": []
}"#;
let res: CreateLabelResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.label_id, "LBL-1234567890");
assert_eq!(res.tracking_number, "9405500000000000000000");
assert_eq!(res.label_broker_id.as_deref(), Some("LB-999"));
assert_eq!(res.total_price, Some(10.50));
assert!(res.label_image.is_some());
}
#[test]
fn label_image_type_display() {
assert_eq!(LabelImageType::Pdf.to_string(), "PDF");
assert_eq!(LabelImageType::Png.to_string(), "PNG");
assert_eq!(LabelImageType::Tiff.to_string(), "TIFF");
assert_eq!(LabelImageType::Svg.to_string(), "SVG");
}
#[test]
fn label_broker_request_builder() {
let from = LabelPartyAddress::new("123 Sender Way", "Austin", "TX", "78701");
let to = LabelPartyAddress::new("456 Receiver Ave", "New York", "NY", "10001");
let pkg = PackageDescription::new(MailClass::PriorityMail, 1.5);
let req = LabelBrokerRequest::new(from, to, pkg).customer_reference_id("ORDER-5544");
assert_eq!(req.customer_reference_id.as_deref(), Some("ORDER-5544"));
}
#[test]
fn label_broker_response_deserialization() {
let json = r#"{
"labelBrokerId": "LB-887766",
"trackingNumber": "9405500000000000000011",
"qrCode": "iVBORw0KGgoAAA...",
"status": "ACTIVE",
"expirationDate": "2026-10-01"
}"#;
let res: LabelBrokerResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.label_broker_id, "LB-887766");
assert_eq!(res.tracking_number, "9405500000000000000011");
assert_eq!(res.status, "ACTIVE");
assert_eq!(res.expiration_date.as_deref(), Some("2026-10-01"));
}
}