use serde::{Deserialize, Serialize};
use tracing::instrument;
use crate::core::client::UspsClient;
use crate::core::error::{Result, UspsError};
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressStandardizationRequest {
pub street_address: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub secondary_address: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(rename = "ZIPCode", skip_serializing_if = "Option::is_none")]
pub zip_code: Option<String>,
#[serde(rename = "ZIPPlus4", skip_serializing_if = "Option::is_none")]
pub zip_plus4: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub urbanization: Option<String>,
}
impl AddressStandardizationRequest {
#[must_use]
pub fn new(street_address: impl Into<String>) -> Self {
Self {
street_address: street_address.into(),
..Default::default()
}
}
#[must_use]
pub fn secondary_address(mut self, secondary: impl Into<String>) -> Self {
self.secondary_address = Some(secondary.into());
self
}
#[must_use]
pub fn city_state(mut self, city: impl Into<String>, state: impl Into<String>) -> Self {
self.city = Some(city.into());
self.state = Some(state.into());
self
}
#[must_use]
pub fn zip_code(mut self, zip: impl Into<String>) -> Self {
self.zip_code = Some(zip.into());
self
}
#[must_use]
pub fn zip_plus4(mut self, plus4: impl Into<String>) -> Self {
self.zip_plus4 = Some(plus4.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StandardizedAddress {
#[serde(default)]
pub street_address: Option<String>,
#[serde(default)]
pub street_address_abbreviation: Option<String>,
#[serde(default)]
pub secondary_address: Option<String>,
#[serde(default)]
pub city: Option<String>,
#[serde(default)]
pub city_abbreviation: Option<String>,
#[serde(default)]
pub state: Option<String>,
#[serde(rename = "ZIPCode", default)]
pub zip_code: Option<String>,
#[serde(rename = "ZIPPlus4", default)]
pub zip_plus4: Option<String>,
#[serde(default)]
pub urbanization: Option<String>,
#[serde(default)]
pub delivery_point: Option<String>,
#[serde(default)]
pub carrier_route: Option<String>,
#[serde(rename = "DPVConfirmation", default)]
pub dpv_confirmation: Option<String>,
#[serde(rename = "DPVCMRA", default)]
pub dpv_cmra: Option<String>,
#[serde(default)]
pub business: Option<String>,
#[serde(default)]
pub vacant: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct AddressResponse {
#[serde(default)]
pub address: Option<StandardizedAddress>,
#[serde(default)]
pub warnings: Vec<String>,
#[serde(default)]
pub correction: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZipCodeLookupRequest {
pub street_address: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub secondary_address: Option<String>,
pub city: String,
pub state: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub urbanization: Option<String>,
}
impl ZipCodeLookupRequest {
#[must_use]
pub fn new(
street_address: impl Into<String>,
city: impl Into<String>,
state: impl Into<String>,
) -> Self {
Self {
street_address: street_address.into(),
secondary_address: None,
city: city.into(),
state: state.into(),
urbanization: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CityStateResponse {
#[serde(rename = "ZIPCode")]
pub zip_code: String,
pub city: String,
pub state: String,
}
#[derive(Debug, Clone)]
pub struct AddressesService {
client: UspsClient,
}
impl AddressesService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "standardize_address")]
pub async fn standardize(
&self,
req: &AddressStandardizationRequest,
) -> Result<AddressResponse> {
if req.street_address.trim().is_empty() {
return Err(UspsError::InvalidInput(
"La dirección principal 'street_address' es obligatoria".to_string(),
));
}
let endpoint = "/addresses/v3/address";
self.client.get_with_query(endpoint, req).await
}
#[instrument(skip(self), name = "lookup_zip_code")]
pub async fn lookup_zip_code(&self, req: &ZipCodeLookupRequest) -> Result<AddressResponse> {
if req.street_address.trim().is_empty() {
return Err(UspsError::InvalidInput(
"La dirección principal 'street_address' es requerida".to_string(),
));
}
if req.city.trim().is_empty() || req.state.trim().is_empty() {
return Err(UspsError::InvalidInput(
"La ciudad y el estado son requeridos para consultar el código postal".to_string(),
));
}
let endpoint = "/addresses/v3/zipcode";
self.client.get_with_query(endpoint, req).await
}
#[instrument(skip(self), name = "lookup_city_state")]
pub async fn lookup_city_state(&self, zip_code: &str) -> Result<CityStateResponse> {
let trimmed = zip_code.trim();
if trimmed.len() != 5 || !trimmed.chars().all(|c| c.is_ascii_digit()) {
return Err(UspsError::InvalidInput(
"El código postal debe contener exactamente 5 dígitos numéricos".to_string(),
));
}
let endpoint = "/addresses/v3/city-state";
let query = [("ZIPCode", trimmed)];
self.client.get_with_query(endpoint, &query).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_standardization_request_builder() {
let req = AddressStandardizationRequest::new("475 L'Enfant Plaza SW")
.secondary_address("Room 100")
.city_state("Washington", "DC")
.zip_code("20260");
assert_eq!(req.street_address, "475 L'Enfant Plaza SW");
assert_eq!(req.secondary_address.as_deref(), Some("Room 100"));
assert_eq!(req.city.as_deref(), Some("Washington"));
assert_eq!(req.state.as_deref(), Some("DC"));
assert_eq!(req.zip_code.as_deref(), Some("20260"));
}
#[test]
fn address_response_deserialization() {
let json = r#"{
"address": {
"streetAddress": "475 LENFANT PLZ SW",
"city": "WASHINGTON",
"state": "DC",
"ZIPCode": "20260",
"ZIPPlus4": "0004",
"DPVConfirmation": "Y"
},
"warnings": []
}"#;
let res: AddressResponse = serde_json::from_str(json).unwrap();
let addr = res.address.unwrap();
assert_eq!(addr.street_address.as_deref(), Some("475 LENFANT PLZ SW"));
assert_eq!(addr.city.as_deref(), Some("WASHINGTON"));
assert_eq!(addr.state.as_deref(), Some("DC"));
assert_eq!(addr.zip_code.as_deref(), Some("20260"));
assert_eq!(addr.zip_plus4.as_deref(), Some("0004"));
assert_eq!(addr.dpv_confirmation.as_deref(), Some("Y"));
}
#[test]
fn city_state_response_deserialization() {
let json = r#"{
"ZIPCode": "90210",
"city": "BEVERLY HILLS",
"state": "CA"
}"#;
let res: CityStateResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.zip_code, "90210");
assert_eq!(res.city, "BEVERLY HILLS");
assert_eq!(res.state, "CA");
}
}