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, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PackageLocation {
#[default]
FrontDoor,
BackDoor,
SideDoor,
InMailbox,
OfficeReception,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PickupPackageCount {
#[serde(default)]
pub priority_mail_express: u32,
#[serde(default)]
pub priority_mail: u32,
#[serde(default)]
pub ground_advantage: u32,
#[serde(default)]
pub international: u32,
#[serde(default)]
pub other: u32,
}
impl PickupPackageCount {
#[must_use]
pub fn total(&self) -> u32 {
self.priority_mail_express
+ self.priority_mail
+ self.ground_advantage
+ self.international
+ self.other
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PickupContactAddress {
pub first_name: String,
pub last_name: 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,
pub phone: String,
pub email: String,
}
impl PickupContactAddress {
#[must_use]
pub fn new(
first_name: impl Into<String>,
last_name: impl Into<String>,
street_address: impl Into<String>,
city: impl Into<String>,
state: impl Into<String>,
zip_code: impl Into<String>,
) -> Self {
Self {
first_name: first_name.into(),
last_name: last_name.into(),
firm_name: None,
street_address: street_address.into(),
secondary_address: None,
city: city.into(),
state: state.into(),
zip_code: zip_code.into(),
phone: String::new(),
email: String::new(),
}
}
#[must_use]
pub fn contact_info(mut self, phone: impl Into<String>, email: impl Into<String>) -> Self {
self.phone = phone.into();
self.email = email.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, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SchedulePickupRequest {
#[serde(flatten)]
pub contact: PickupContactAddress,
pub pickup_date: String,
pub package_location: PackageLocation,
#[serde(skip_serializing_if = "Option::is_none")]
pub special_instructions: Option<String>,
pub package_count: PickupPackageCount,
}
impl SchedulePickupRequest {
#[must_use]
pub fn new(contact: PickupContactAddress, pickup_date: impl Into<String>) -> Self {
Self {
contact,
pickup_date: pickup_date.into(),
package_location: PackageLocation::FrontDoor,
special_instructions: None,
package_count: PickupPackageCount::default(),
}
}
#[must_use]
pub fn location(mut self, location: PackageLocation) -> Self {
self.package_location = location;
self
}
#[must_use]
pub fn special_instructions(mut self, notes: impl Into<String>) -> Self {
self.special_instructions = Some(notes.into());
self
}
#[must_use]
pub fn packages(mut self, count: PickupPackageCount) -> Self {
self.package_count = count;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SchedulePickupResponse {
pub confirmation_number: String,
pub pickup_date: String,
pub status: String,
#[serde(default)]
pub total_packages: Option<u32>,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PickupAvailabilityResponse {
pub available: bool,
#[serde(rename = "ZIPCode")]
pub zip_code: String,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelPickupResponse {
pub status: String,
pub confirmation_number: String,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PickupService {
client: UspsClient,
}
impl PickupService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "check_pickup_availability")]
pub async fn check_availability(&self, zip_code: &str) -> Result<PickupAvailabilityResponse> {
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".to_string(),
));
}
let endpoint = "/pickup/v3/carrier-pickup/availability";
let query = [("ZIPCode", trimmed)];
self.client.get_with_query(endpoint, &query).await
}
#[instrument(skip(self), name = "schedule_pickup")]
pub async fn schedule(&self, req: &SchedulePickupRequest) -> Result<SchedulePickupResponse> {
if req.contact.first_name.trim().is_empty() || req.contact.last_name.trim().is_empty() {
return Err(UspsError::InvalidInput(
"El nombre y apellido del contacto son obligatorios".to_string(),
));
}
if req.contact.street_address.trim().is_empty()
|| req.contact.city.trim().is_empty()
|| req.contact.state.trim().is_empty()
{
return Err(UspsError::InvalidInput(
"La dirección física de recolección está incompleta".to_string(),
));
}
if req.package_count.total() == 0 {
return Err(UspsError::InvalidInput(
"Debe indicarse al menos 1 paquete a recolectar".to_string(),
));
}
let endpoint = "/pickup/v3/carrier-pickup";
self.client.post_json(endpoint, req).await
}
#[instrument(skip(self), name = "cancel_pickup")]
pub async fn cancel(&self, confirmation_number: &str) -> Result<CancelPickupResponse> {
let clean_num = confirmation_number.trim();
if clean_num.is_empty() {
return Err(UspsError::InvalidInput(
"El número de confirmación no puede estar vacío".to_string(),
));
}
let endpoint = format!("/pickup/v3/carrier-pickup/{clean_num}");
let body = self.client.delete(&endpoint).await?;
if body.trim().is_empty() {
Ok(CancelPickupResponse {
status: "CANCELLED".to_string(),
confirmation_number: clean_num.to_string(),
message: Some("Recolección cancelada satisfactoriamente".to_string()),
})
} else {
serde_json::from_str::<CancelPickupResponse>(&body).map_err(UspsError::Serialization)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schedule_pickup_request_builder() {
let count = PickupPackageCount {
priority_mail: 2,
ground_advantage: 3,
..Default::default()
};
let contact =
PickupContactAddress::new("John", "Doe", "123 Maple St", "Chicago", "IL", "60601")
.contact_info("555-123-4567", "john@example.com");
let req = SchedulePickupRequest::new(contact, "2026-09-20")
.location(PackageLocation::FrontDoor)
.special_instructions("Beware of dog")
.packages(count);
assert_eq!(req.contact.first_name, "John");
assert_eq!(req.package_count.total(), 5);
assert_eq!(req.package_location, PackageLocation::FrontDoor);
assert_eq!(req.special_instructions.as_deref(), Some("Beware of dog"));
}
#[test]
fn schedule_pickup_response_deserialization() {
let json = r#"{
"confirmationNumber": "WEC123456789",
"pickupDate": "2026-09-20",
"status": "Scheduled",
"totalPackages": 5,
"message": "Pickup scheduled successfully"
}"#;
let res: SchedulePickupResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.confirmation_number, "WEC123456789");
assert_eq!(res.pickup_date, "2026-09-20");
assert_eq!(res.status, "Scheduled");
assert_eq!(res.total_packages, Some(5));
}
}