use crate::cpe_cdr::CpeCdr;
use crate::cpe_empaquetado::{cpe_codificar_base64, cpe_decodificar_base64};
use crate::cpe_error::{CpeError, CpeResult};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CpeAmbiente {
Beta,
Produccion,
Personalizado(String),
}
impl CpeAmbiente {
#[must_use]
pub fn url_bill_service(&self) -> &str {
match self {
Self::Beta => "https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService",
Self::Produccion => "https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService",
Self::Personalizado(url) => url.as_str(),
}
}
#[must_use]
pub fn url_consult_service(&self) -> &str {
match self {
Self::Beta => {
"https://e-beta.sunat.gob.pe/ol-ti-itwsconsvalidcpe-beta/billConsultService"
}
Self::Produccion => {
"https://e-factura.sunat.gob.pe/ol-it-wsconsvalidcpe/billConsultService"
}
Self::Personalizado(url) => url.as_str(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CpeCredencialesSol {
pub ruc: String,
pub usuario_sol: String,
pub clave_sol: String,
}
impl CpeCredencialesSol {
#[must_use]
pub fn nuevo(ruc: &str, usuario_sol: &str, clave_sol: &str) -> Self {
Self {
ruc: ruc.trim().to_string(),
usuario_sol: usuario_sol.trim().to_string(),
clave_sol: clave_sol.trim().to_string(),
}
}
#[must_use]
pub fn username_token(&self) -> String {
format!("{}{}", self.ruc, self.usuario_sol)
}
}
fn cpe_construir_soap_header_security(credenciales: &CpeCredencialesSol) -> String {
format!(
r#" <soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>{}</wsse:Username>
<wsse:Password>{}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>"#,
credenciales.username_token(),
credenciales.clave_sol
)
}
#[must_use]
pub fn cpe_construir_envelope_send_bill(
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> String {
let base64_zip = cpe_codificar_base64(zip_bytes);
let header = cpe_construir_soap_header_security(credenciales);
format!(
r#"<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.sunat.gob.pe" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
{}
<soapenv:Body>
<ser:sendBill>
<fileName>{}</fileName>
<contentFile>{}</contentFile>
</ser:sendBill>
</soapenv:Body>
</soapenv:Envelope>"#,
header, nombre_archivo_zip, base64_zip
)
}
#[must_use]
pub fn cpe_construir_envelope_send_summary(
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> String {
let base64_zip = cpe_codificar_base64(zip_bytes);
let header = cpe_construir_soap_header_security(credenciales);
format!(
r#"<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.sunat.gob.pe" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
{}
<soapenv:Body>
<ser:sendSummary>
<fileName>{}</fileName>
<contentFile>{}</contentFile>
</ser:sendSummary>
</soapenv:Body>
</soapenv:Envelope>"#,
header, nombre_archivo_zip, base64_zip
)
}
#[must_use]
pub fn cpe_construir_envelope_get_status(
credenciales: &CpeCredencialesSol,
ticket: &str,
) -> String {
let header = cpe_construir_soap_header_security(credenciales);
format!(
r#"<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.sunat.gob.pe" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
{}
<soapenv:Body>
<ser:getStatus>
<ticket>{}</ticket>
</ser:getStatus>
</soapenv:Body>
</soapenv:Envelope>"#,
header, ticket
)
}
pub fn cpe_extraer_cdr_de_respuesta_soap(soap_response: &str) -> CpeResult<CpeCdr> {
if let Some(pos) = soap_response.find("applicationResponse") {
if let Some(pos_cierre) = soap_response[pos..].find('>') {
let inicio = pos + pos_cierre + 1;
if let Some(fin_rel) = soap_response[inicio..].find("</") {
let base64_cdr = soap_response[inicio..inicio + fin_rel].trim();
let zip_bytes = cpe_decodificar_base64(base64_cdr)?;
return CpeCdr::desde_zip(&zip_bytes);
}
}
}
if let Some(fault_pos) = soap_response.find("faultcode") {
if let Some(pos_cierre) = soap_response[fault_pos..].find('>') {
let inicio = fault_pos + pos_cierre + 1;
let fin_rel = soap_response[inicio..].find("</").unwrap_or(0);
let codigo = &soap_response[inicio..inicio + fin_rel];
let mensaje = if let Some(msg_pos) = soap_response.find("faultstring") {
if let Some(mcierre) = soap_response[msg_pos..].find('>') {
let minicio = msg_pos + mcierre + 1;
let mfin_rel = soap_response[minicio..].find("</").unwrap_or(0);
soap_response[minicio..minicio + mfin_rel].trim()
} else {
"Error SOAP sin descripción"
}
} else {
"Error SOAP sin descripción"
};
return Err(CpeError::ErrorSunatWebService {
codigo: codigo.trim().to_string(),
mensaje: mensaje.to_string(),
});
}
}
Err(CpeError::ErrorXml(
"Respuesta SOAP inesperada: no contiene applicationResponse ni SoapFault".to_string(),
))
}
#[cfg(feature = "async")]
pub async fn cpe_enviar_documento_async(
ambiente: &CpeAmbiente,
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> CpeResult<CpeCdr> {
let soap_envelope =
cpe_construir_envelope_send_bill(credenciales, nombre_archivo_zip, zip_bytes);
let client = reqwest::Client::new();
let res = client
.post(ambiente.url_bill_service())
.header("Content-Type", "text/xml; charset=utf-8")
.header("SOAPAction", "urn:sendBill")
.body(soap_envelope)
.send()
.await
.map_err(|e| {
CpeError::ErrorRed(format!("Error HTTP al enviar comprobante a SUNAT: {e}"))
})?;
let cuerpo_respuesta = res
.text()
.await
.map_err(|e| CpeError::ErrorRed(format!("Error al leer respuesta SOAP: {e}")))?;
cpe_extraer_cdr_de_respuesta_soap(&cuerpo_respuesta)
}
#[cfg(feature = "async")]
pub async fn cpe_enviar_resumen_async(
ambiente: &CpeAmbiente,
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> CpeResult<String> {
let soap_envelope =
cpe_construir_envelope_send_summary(credenciales, nombre_archivo_zip, zip_bytes);
let client = reqwest::Client::new();
let res = client
.post(ambiente.url_bill_service())
.header("Content-Type", "text/xml; charset=utf-8")
.header("SOAPAction", "urn:sendSummary")
.body(soap_envelope)
.send()
.await
.map_err(|e| CpeError::ErrorRed(format!("Error HTTP al enviar resumen a SUNAT: {e}")))?;
let cuerpo_respuesta = res
.text()
.await
.map_err(|e| CpeError::ErrorRed(format!("Error al leer respuesta SOAP: {e}")))?;
if let Some(pos) = cuerpo_respuesta.find("<ticket>") {
let inicio = pos + "<ticket>".len();
let fin = cuerpo_respuesta[inicio..]
.find("</ticket>")
.ok_or_else(|| CpeError::ErrorXml("Etiqueta </ticket> no encontrada".to_string()))?
+ inicio;
Ok(cuerpo_respuesta[inicio..fin].trim().to_string())
} else {
cpe_extraer_cdr_de_respuesta_soap(&cuerpo_respuesta)?;
Err(CpeError::ErrorXml(
"Respuesta no contiene número de ticket".to_string(),
))
}
}
#[cfg(feature = "blocking")]
pub fn cpe_enviar_documento_sync(
ambiente: &CpeAmbiente,
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> CpeResult<CpeCdr> {
let soap_envelope =
cpe_construir_envelope_send_bill(credenciales, nombre_archivo_zip, zip_bytes);
let res = ureq::post(ambiente.url_bill_service())
.set("Content-Type", "text/xml; charset=utf-8")
.set("SOAPAction", "urn:sendBill")
.send_string(&soap_envelope)
.map_err(|e| CpeError::ErrorRed(format!("Error HTTP síncrono al contactar SUNAT: {e}")))?;
let cuerpo_respuesta = res
.into_string()
.map_err(|e| CpeError::ErrorRed(format!("Error al leer respuesta SOAP: {e}")))?;
cpe_extraer_cdr_de_respuesta_soap(&cuerpo_respuesta)
}
#[cfg(feature = "blocking")]
pub fn cpe_enviar_resumen_sync(
ambiente: &CpeAmbiente,
credenciales: &CpeCredencialesSol,
nombre_archivo_zip: &str,
zip_bytes: &[u8],
) -> CpeResult<String> {
let soap_envelope =
cpe_construir_envelope_send_summary(credenciales, nombre_archivo_zip, zip_bytes);
let res = ureq::post(ambiente.url_bill_service())
.set("Content-Type", "text/xml; charset=utf-8")
.set("SOAPAction", "urn:sendSummary")
.send_string(&soap_envelope)
.map_err(|e| CpeError::ErrorRed(format!("Error HTTP síncrono al enviar resumen: {e}")))?;
let cuerpo_respuesta = res
.into_string()
.map_err(|e| CpeError::ErrorRed(format!("Error al leer respuesta SOAP: {e}")))?;
if let Some(pos) = cuerpo_respuesta.find("<ticket>") {
let inicio = pos + "<ticket>".len();
let fin = cuerpo_respuesta[inicio..]
.find("</ticket>")
.ok_or_else(|| CpeError::ErrorXml("Etiqueta </ticket> no encontrada".to_string()))?
+ inicio;
Ok(cuerpo_respuesta[inicio..fin].trim().to_string())
} else {
cpe_extraer_cdr_de_respuesta_soap(&cuerpo_respuesta)?;
Err(CpeError::ErrorXml(
"Respuesta no contiene número de ticket".to_string(),
))
}
}