diff -ruN /mnt/data/vase_work_before/app/Http/Controllers/SiiSetPruebaBoletaController.php /mnt/data/vase_work/app/Http/Controllers/SiiSetPruebaBoletaController.php --- /mnt/data/vase_work_before/app/Http/Controllers/SiiSetPruebaBoletaController.php 2026-07-20 20:50:28.000000000 +0000 +++ /mnt/data/vase_work/app/Http/Controllers/SiiSetPruebaBoletaController.php 2026-08-04 21:06:29.464445694 +0000 @@ -92,7 +92,7 @@ return response()->json([ 'ok' => true, - 'message' => 'Los ocho documentos del Set Básico 4933514 fueron generados, firmados y enviados juntos al SII.', + 'message' => 'Los ocho documentos del Set Básico 4994954 fueron generados, firmados y enviados juntos al SII.', 'data' => $resultado, ], 201); } catch (Throwable $e) { diff -ruN /mnt/data/vase_work_before/app/Services/SiiSetPruebaFacturaService.php /mnt/data/vase_work/app/Services/SiiSetPruebaFacturaService.php --- /mnt/data/vase_work_before/app/Services/SiiSetPruebaFacturaService.php 2026-07-20 21:07:35.000000000 +0000 +++ /mnt/data/vase_work/app/Services/SiiSetPruebaFacturaService.php 2026-08-04 21:14:51.872445694 +0000 @@ -4,18 +4,20 @@ use App\Models\DteEmisorConfiguracion; use App\Models\DteFolio; +use App\Models\SiiCertificacionProceso; use DOMDocument; use DOMElement; use DOMXPath; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use RuntimeException; use Throwable; class SiiSetPruebaFacturaService extends SiiSetPruebaBoletaService { - private const ATENCION_SET_BASICO = '4933514'; - private const ATENCION_LIBRO_VENTAS = '4933515'; - private const ATENCION_LIBRO_COMPRAS = '4933516'; + private const ATENCION_SET_BASICO = '4994954'; + private const ATENCION_LIBRO_VENTAS = '4994955'; + private const ATENCION_LIBRO_COMPRAS = '4994956'; private const RUT_EMISOR_ASIGNADO = '77925354-6'; private const RUT_FIRMANTE_ASIGNADO = '19512040-4'; @@ -27,6 +29,12 @@ private const ACTIVIDADES_ASIGNADAS = ['472101', '478100', '561000']; private const FECHA_RESOLUCION_ASIGNADA = '2026-07-02'; private const NUMERO_RESOLUCION_ASIGNADO = '0'; + private const SET_OFICIAL_ARCHIVO = 'SIISetDePruebas779253546_4994954.txt'; + private const SET_OFICIAL_RUTA_RELATIVA = 'app/private/sii/certificacion/sets/'.self::SET_OFICIAL_ARCHIVO; + private const SET_OFICIAL_SHA256 = '6ddd988da17a7ef887168b1d8f220eb1252074e171728fd4a9fb5faab8994daf'; + private const XSD_DTE_RUTA_RELATIVA = 'app/private/sii/xsd/dte'; + private const XSD_DTE_PRINCIPAL = 'EnvioDTE_v10.xsd'; + private const XSD_DTE_ARCHIVOS = ['EnvioDTE_v10.xsd', 'DTE_v10.xsd', 'SiiTypes_v10.xsd', 'xmldsignature_v10.xsd']; private const REQUERIDOS = [33 => 4, 61 => 3, 56 => 1]; @@ -98,12 +106,14 @@ $fechaResolucionCorrecta = (bool) $emisor && $emisor->resolucion_fecha && $emisor->resolucion_fecha->format('Y-m-d') === self::FECHA_RESOLUCION_ASIGNADA; + $setOficial = $this->estadoSetOficial(); $baseLista = (bool) $emisor && strtoupper((string) $emisor->ambiente) === 'CERTIFICACION' && (bool) ($emisor->certificado_path && $emisor->certificado_password) && $rutCorrecto && $numeroResolucionCorrecto - && $fechaResolucionCorrecta; + && $fechaResolucionCorrecta + && ($setOficial['verificado_con_codigo'] ?? false); $foliosListos = collect($folios)->every(fn (array $item) => $item['listo']); return [ @@ -139,6 +149,8 @@ 'libro_ventas' => self::ATENCION_LIBRO_VENTAS, 'libro_compras' => self::ATENCION_LIBRO_COMPRAS, ], + 'set_oficial' => $setOficial, + 'xsd_oficial' => $this->estadoXsdOficial(), 'folios' => $folios, 'receptores_tecnicos_automaticos' => true, 'puede_enviar' => $baseLista && $foliosListos, @@ -167,8 +179,8 @@ 'titulo' => 'Factura afecta simple', 'receptor_indice' => 0, 'items' => [ - ['nombre' => 'Cajón AFECTO', 'cantidad' => 158, 'precio' => 2922, 'exento' => false], - ['nombre' => 'Relleno AFECTO', 'cantidad' => 67, 'precio' => 4853, 'exento' => false], + ['nombre' => 'Cajón AFECTO', 'cantidad' => 189, 'precio' => 4666, 'exento' => false], + ['nombre' => 'Relleno AFECTO', 'cantidad' => 79, 'precio' => 7801, 'exento' => false], ], ], [ @@ -178,8 +190,8 @@ 'titulo' => 'Factura con descuentos por línea', 'receptor_indice' => 1, 'items' => [ - ['nombre' => 'Pañuelo AFECTO', 'cantidad' => 643, 'precio' => 5000, 'descuento_pct' => 8, 'exento' => false], - ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 583, 'precio' => 4054, 'descuento_pct' => 19, 'exento' => false], + ['nombre' => 'Pañuelo AFECTO', 'cantidad' => 999, 'precio' => 7683, 'descuento_pct' => 12, 'exento' => false], + ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 951, 'precio' => 6728, 'descuento_pct' => 31, 'exento' => false], ], ], [ @@ -189,9 +201,9 @@ 'titulo' => 'Factura afecta y exenta', 'receptor_indice' => 2, 'items' => [ - ['nombre' => 'Pintura B&W AFECTO', 'cantidad' => 50, 'precio' => 5866, 'exento' => false], - ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 217, 'precio' => 3734, 'exento' => false], - ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 1, 'precio' => 35162, 'exento' => true], + ['nombre' => 'Pintura B&W AFECTO', 'cantidad' => 99, 'precio' => 8803, 'exento' => false], + ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 276, 'precio' => 4668, 'exento' => false], + ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 1, 'precio' => 35561, 'exento' => true], ], ], [ @@ -200,11 +212,11 @@ 'documento' => 'FACTURA ELECTRONICA', 'titulo' => 'Factura con descuento global afecto', 'receptor_indice' => 3, - 'descuento_global_pct' => 19, + 'descuento_global_pct' => 30, 'items' => [ - ['nombre' => 'ITEM 1 AFECTO', 'cantidad' => 340, 'precio' => 4979, 'exento' => false], - ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 144, 'precio' => 5920, 'exento' => false], - ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 2, 'precio' => 6818, 'exento' => true], + ['nombre' => 'ITEM 1 AFECTO', 'cantidad' => 567, 'precio' => 7864, 'exento' => false], + ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 240, 'precio' => 9860, 'exento' => false], + ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 2, 'precio' => 6863, 'exento' => true], ], ], [ @@ -232,8 +244,8 @@ 'codigo_referencia' => 3, 'razon_referencia' => 'DEVOLUCION DE MERCADERIAS', 'items' => [ - ['nombre' => 'Pañuelo AFECTO', 'cantidad' => 236, 'precio' => 5000, 'descuento_pct' => 8, 'exento' => false], - ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 395, 'precio' => 4054, 'descuento_pct' => 19, 'exento' => false], + ['nombre' => 'Pañuelo AFECTO', 'cantidad' => 367, 'precio' => 7683, 'descuento_pct' => 12, 'exento' => false], + ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 645, 'precio' => 6728, 'descuento_pct' => 31, 'exento' => false], ], ], [ @@ -247,9 +259,9 @@ 'codigo_referencia' => 1, 'razon_referencia' => 'ANULA FACTURA', 'items' => [ - ['nombre' => 'Pintura B&W AFECTO', 'cantidad' => 50, 'precio' => 5866, 'exento' => false], - ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 217, 'precio' => 3734, 'exento' => false], - ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 1, 'precio' => 35162, 'exento' => true], + ['nombre' => 'Pintura B&W AFECTO', 'cantidad' => 99, 'precio' => 8803, 'exento' => false], + ['nombre' => 'ITEM 2 AFECTO', 'cantidad' => 276, 'precio' => 4668, 'exento' => false], + ['nombre' => 'ITEM 3 SERVICIO EXENTO', 'cantidad' => 1, 'precio' => 35561, 'exento' => true], ], ], [ @@ -280,6 +292,7 @@ public function enviarSetBasico(): array { $emisor = $this->obtenerEmisorCertificacion(); + $this->validarSetOficialLocal(); $this->validarConfiguracionAsignada($emisor); $certificado = $this->cargarCertificado($emisor); if ($this->limpiarRut($certificado['rut_firmante'] ?? null) !== self::RUT_FIRMANTE_ASIGNADO) { @@ -325,21 +338,30 @@ $estado = ['ok' => false, 'pendiente' => true, 'mensaje' => $e->getMessage()]; } + $xmlExacto = (string) ($upload['xml_upload'] ?? $preparado['xml']); + $uploadPublico = collect($upload)->except('xml_upload')->all(); + $auditoria = $this->auditarXmlExacto($xmlExacto, $uploadPublico, $estado); + $this->guardarProcesoAuditoria($trackId, $xmlExacto, $uploadPublico, $estado, $auditoria); + return [ 'tipo' => 'SET_BASICO_FACTURAS', 'numero_atencion' => self::ATENCION_SET_BASICO, 'track_id' => $trackId, 'archivo' => $archivo, 'folios_por_caso' => $preparado['folios_por_caso'], - 'xml_base64' => base64_encode((string) ($upload['xml_upload'] ?? $preparado['xml'])), - 'upload' => collect($upload)->except('xml_upload')->all(), + 'xml_base64' => base64_encode($xmlExacto), + 'upload' => $uploadPublico, 'estado' => $estado, + 'auditoria' => $auditoria, ]; } public function consultarEstado(string $trackId): array { - return $this->motor->consultarTrackTecnicoCertificacion($trackId); + $estado = $this->motor->consultarTrackTecnicoCertificacion($trackId); + $this->actualizarProcesoEstado($trackId, $estado); + + return $estado; } private function construirSetBasico(DteEmisorConfiguracion $emisor, array $certificado, array $receptores, array $reservas): string @@ -579,6 +601,7 @@ if (!$dom->loadXML($xml, LIBXML_NONET)) { throw new RuntimeException('El XML del Set Básico no se pudo releer.'); } + $this->validarXsdOficialSiDisponible($xml); $xpath = new DOMXPath($dom); $xpath->registerNamespace('ds', 'http://www.w3.org/2000/09/xmldsig#'); $documentos = $xpath->query('//*[local-name()="Documento" and @ID]'); @@ -852,7 +875,7 @@ private function codigosActividad(DteEmisorConfiguracion $emisor): array { - // Este servicio corresponde exclusivamente al Set 4933514 asignado a + // Este servicio corresponde exclusivamente al Set 4994954 asignado a // EL PAPAS SPA; se informan las tres actividades registradas por el SII. return self::ACTIVIDADES_ASIGNADAS; } @@ -946,6 +969,10 @@ if (!$emisor->certificado_path || !$emisor->certificado_password) { return 'Falta cargar el certificado digital y su clave.'; } + $setOficial = $this->estadoSetOficial(); + if (!($setOficial['verificado_con_codigo'] ?? false)) { + return (string) ($setOficial['mensaje'] ?? 'Falta verificar el TXT oficial del Set Básico.'); + } $faltantes = []; foreach ($folios as $item) { if (!$item['listo']) { @@ -958,6 +985,291 @@ return 'Listo para generar los 8 DTE del Set Básico '.self::ATENCION_SET_BASICO.' en un único EnvioDTE.'; } + private function estadoXsdOficial(): array + { + $directorio = storage_path(self::XSD_DTE_RUTA_RELATIVA); + $faltantes = array_values(array_filter( + self::XSD_DTE_ARCHIVOS, + fn (string $archivo) => !is_file($directorio.DIRECTORY_SEPARATOR.$archivo) + )); + + return [ + 'ruta_relativa' => self::XSD_DTE_RUTA_RELATIVA, + 'principal' => self::XSD_DTE_PRINCIPAL, + 'archivos_requeridos' => self::XSD_DTE_ARCHIVOS, + 'faltantes' => $faltantes, + 'instalado' => $faltantes === [], + 'estado' => $faltantes === [] ? 'INSTALADO_VALIDACION_PREVIA_ACTIVA' : 'PENDIENTE_INSTALAR_4_XSD_SII', + ]; + } + + private function validarXsdOficialSiDisponible(string $xml): void + { + $estado = $this->estadoXsdOficial(); + if (!($estado['instalado'] ?? false)) { + return; + } + + $rutaPrincipal = storage_path(self::XSD_DTE_RUTA_RELATIVA.'/'.self::XSD_DTE_PRINCIPAL); + $anterior = libxml_use_internal_errors(true); + libxml_clear_errors(); + try { + $dom = new DOMDocument(); + $dom->preserveWhiteSpace = true; + if (!$dom->loadXML($xml, LIBXML_NONET)) { + throw new RuntimeException('El XML no se pudo cargar para validarlo contra el XSD oficial.'); + } + if (!$dom->schemaValidate($rutaPrincipal)) { + $errores = array_map( + static fn (\LibXMLError $error) => trim($error->message).' (línea '.$error->line.', columna '.$error->column.')', + libxml_get_errors() + ); + throw new RuntimeException('El Set Básico no cumple el XSD oficial del SII: '.implode(' | ', array_slice($errores, 0, 12))); + } + } finally { + libxml_clear_errors(); + libxml_use_internal_errors($anterior); + } + } + + private function estadoSetOficial(): array + { + $ruta = storage_path(self::SET_OFICIAL_RUTA_RELATIVA); + $estado = [ + 'archivo' => self::SET_OFICIAL_ARCHIVO, + 'ruta_relativa' => self::SET_OFICIAL_RUTA_RELATIVA, + 'sha256_esperado' => self::SET_OFICIAL_SHA256, + 'sha256' => null, + 'numero_atencion' => self::ATENCION_SET_BASICO, + 'libro_ventas' => self::ATENCION_LIBRO_VENTAS, + 'libro_compras' => self::ATENCION_LIBRO_COMPRAS, + 'casos' => 0, + 'existe' => is_file($ruta), + 'verificado_con_codigo' => false, + 'verificado_at' => null, + 'mensaje' => '', + ]; + + if (!is_file($ruta)) { + $estado['mensaje'] = 'Falta copiar el TXT oficial en storage/'.self::SET_OFICIAL_RUTA_RELATIVA.'.'; + return $estado; + } + + $contenido = file_get_contents($ruta); + if (!is_string($contenido) || trim($contenido) === '') { + $estado['mensaje'] = 'El TXT oficial está vacío o no se pudo leer.'; + return $estado; + } + + $sha = hash('sha256', $contenido); + preg_match_all('/^CASO\s+'.preg_quote(self::ATENCION_SET_BASICO, '/').'-(\d+)\s*$/mi', $contenido, $coincidencias); + $casos = array_values(array_unique(array_map('intval', $coincidencias[1] ?? []))); + sort($casos); + + $numerosCorrectos = str_contains($contenido, 'SET BASICO - NUMERO DE ATENCION: '.self::ATENCION_SET_BASICO) + && str_contains($contenido, 'SET LIBRO DE VENTAS - NUMERO DE ATENCION: '.self::ATENCION_LIBRO_VENTAS) + && str_contains($contenido, 'SET LIBRO DE COMPRAS - NUMERO DE ATENCION: '.self::ATENCION_LIBRO_COMPRAS); + $casosCorrectos = $casos === range(1, 8); + $hashCorrecto = hash_equals(self::SET_OFICIAL_SHA256, $sha); + $verificado = $numerosCorrectos && $casosCorrectos && $hashCorrecto; + + $estado['sha256'] = $sha; + $estado['casos'] = count($casos); + $estado['verificado_con_codigo'] = $verificado; + $estado['verificado_at'] = $verificado ? now()->toIso8601String() : null; + $estado['mensaje'] = $verificado + ? 'TXT oficial verificado por número de atención, ocho casos y SHA-256.' + : 'El TXT no coincide exactamente con el set oficial esperado; el envío está bloqueado.'; + + return $estado; + } + + private function validarSetOficialLocal(): void + { + $estado = $this->estadoSetOficial(); + if (!($estado['verificado_con_codigo'] ?? false)) { + throw new RuntimeException((string) ($estado['mensaje'] ?? 'No se pudo verificar el TXT oficial del Set Básico.')); + } + } + + private function auditarXmlExacto(string $xml, array $upload, ?array $estado): array + { + $dom = new DOMDocument(); + $dom->preserveWhiteSpace = true; + if (!$dom->loadXML($xml, LIBXML_NONET) || !$dom->documentElement) { + throw new RuntimeException('No se pudo auditar el XML exacto enviado al SII.'); + } + + $xpath = new DOMXPath($dom); + $documentos = []; + foreach ($xpath->query('//*[local-name()="Documento" and @ID]') ?: [] as $documento) { + if (!$documento instanceof DOMElement) { + continue; + } + $leer = static function (DOMXPath $xp, DOMElement $ctx, string $nombre): string { + return trim((string) ($xp->query('.//*[local-name()="'.$nombre.'"][1]', $ctx)?->item(0)?->textContent ?? '')); + }; + $referenciaSet = ''; + foreach ($xpath->query('./*[local-name()="Referencia"]', $documento) ?: [] as $ref) { + if (!$ref instanceof DOMElement) { + continue; + } + $tipoRef = trim((string) ($xpath->query('./*[local-name()="TpoDocRef"]', $ref)?->item(0)?->textContent ?? '')); + if ($tipoRef === 'SET') { + $referenciaSet = trim((string) ($xpath->query('./*[local-name()="RazonRef"]', $ref)?->item(0)?->textContent ?? '')); + break; + } + } + $documentos[] = [ + 'id' => $documento->getAttribute('ID'), + 'tipo_dte' => (int) $leer($xpath, $documento, 'TipoDTE'), + 'folio' => (int) $leer($xpath, $documento, 'Folio'), + 'rut_receptor' => $leer($xpath, $documento, 'RUTRecep'), + 'razon_social_receptor' => $leer($xpath, $documento, 'RznSocRecep'), + 'neto' => (int) ($leer($xpath, $documento, 'MntNeto') ?: 0), + 'exento' => (int) ($leer($xpath, $documento, 'MntExe') ?: 0), + 'iva' => (int) ($leer($xpath, $documento, 'IVA') ?: 0), + 'total' => (int) ($leer($xpath, $documento, 'MntTotal') ?: 0), + 'referencia_set' => $referenciaSet, + ]; + } + + $caratula = $xpath->query('//*[local-name()="SetDTE"]/*[local-name()="Caratula"]')?->item(0); + $leerCaratula = static function (?DOMElement $ctx, DOMXPath $xp, string $nombre): string { + if (!$ctx) { + return ''; + } + return trim((string) ($xp->query('./*[local-name()="'.$nombre.'"]', $ctx)?->item(0)?->textContent ?? '')); + }; + + $set = $xpath->query('//*[local-name()="SetDTE" and @ID]')?->item(0); + $schemaLocation = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation'); + + return [ + 'sha256' => hash('sha256', $xml), + 'bytes' => strlen($xml), + 'encoding_declarado' => preg_match('/<\?xml[^>]*encoding=["\']([^"\']+)/i', $xml, $m) ? strtoupper($m[1]) : null, + 'raiz' => $dom->documentElement->localName, + 'namespace' => $dom->documentElement->namespaceURI, + 'schema_location' => $schemaLocation, + 'set_id' => $set instanceof DOMElement ? $set->getAttribute('ID') : null, + 'set_oficial' => array_merge($this->estadoSetOficial(), ['coincidencia_codigo' => true]), + 'caratula' => [ + 'rut_emisor' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'RutEmisor'), + 'rut_envia' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'RutEnvia'), + 'rut_receptor' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'RutReceptor'), + 'fecha_resolucion' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'FchResol'), + 'numero_resolucion' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'NroResol'), + 'timestamp_firma' => $leerCaratula($caratula instanceof DOMElement ? $caratula : null, $xpath, 'TmstFirmaEnv'), + ], + 'conteos' => [ + 'documentos' => count($documentos), + 'firmas_xmldsig' => (int) ($xpath->query('//*[local-name()="Signature" and namespace-uri()="http://www.w3.org/2000/09/xmldsig#"]')?->length ?? 0), + 'ted' => (int) ($xpath->query('//*[local-name()="TED"]')?->length ?? 0), + 'frmt' => (int) ($xpath->query('//*[local-name()="FRMT"]')?->length ?? 0), + ], + 'documentos' => $documentos, + 'validaciones' => [ + 'estructura_interna' => 'OK', + 'firmas_xmldsig' => 'OK', + 'ted_frmt' => 'OK', + 'coincidencia_set_oficial' => 'OK_CODIGO_ACTUALIZADO_CON_TXT_4994954', + 'xsd_oficial' => $this->estadoXsdOficial()['estado'], + ], + 'upload' => $upload, + 'estado_inicial' => $estado, + ]; + } + + private function guardarProcesoAuditoria(string $trackId, string $xml, array $upload, ?array $estado, array $auditoria): void + { + if (!Schema::hasTable('sii_certificacion_procesos')) { + return; + } + + try { + SiiCertificacionProceso::query()->create([ + 'tipo' => 'SET_BASICO', + 'ambiente' => 'CERTIFICACION', + 'estado' => $this->estadoProceso($estado), + 'descripcion' => 'Set Básico '.self::ATENCION_SET_BASICO.' · SHA-256 '.($auditoria['sha256'] ?? '-'), + // La columna es UTF-8. Se guarda una copia legible; los bytes exactos + // del upload quedan preservados en Base64 dentro de sii_respuesta. + 'xml_generado' => $this->xmlLegibleUtf8($xml), + 'track_id' => $trackId, + 'sii_respuesta' => json_encode([ + 'xml_exacto_base64' => base64_encode($xml), + 'xml_sha256' => hash('sha256', $xml), + 'upload' => $upload, + 'estado' => $estado, + 'auditoria' => $auditoria, + ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE), + 'generado_at' => now(), + 'enviado_at' => now(), + 'user_id' => auth()->id(), + ]); + } catch (Throwable $e) { + // El SII ya entregó Track ID. Una falla de auditoría local nunca debe + // convertir el envío exitoso en un falso error que provoque reenvíos. + report($e); + } + } + + private function xmlLegibleUtf8(string $xml): string + { + $utf8 = mb_convert_encoding($xml, 'UTF-8', 'ISO-8859-1'); + return preg_replace( + '/^<\?xml\s+[^?]*\?>/i', + '', + $utf8, + 1 + ) ?? $utf8; + } + + private function actualizarProcesoEstado(string $trackId, array $estado): void + { + if (!Schema::hasTable('sii_certificacion_procesos')) { + return; + } + + $proceso = SiiCertificacionProceso::query() + ->where('track_id', $trackId) + ->latest('id') + ->first(); + if (!$proceso) { + return; + } + + $respuestaAnterior = json_decode((string) $proceso->sii_respuesta, true); + if (!is_array($respuestaAnterior)) { + $respuestaAnterior = []; + } + $respuestaAnterior['estado'] = $estado; + $respuestaAnterior['consultado_at'] = now()->toIso8601String(); + + $proceso->update([ + 'estado' => $this->estadoProceso($estado), + 'sii_respuesta' => json_encode($respuestaAnterior, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE), + ]); + } + + private function estadoProceso(?array $estado): string + { + if (!$estado || ($estado['pendiente'] ?? false)) { + return 'ENVIADO'; + } + if (($estado['sobre_rechazado'] ?? false) || (int) ($estado['rechazados'] ?? 0) > 0) { + return 'RECHAZADO'; + } + if ((int) ($estado['reparos'] ?? 0) > 0) { + return 'REPARO'; + } + if ((int) ($estado['aceptados'] ?? 0) === 8) { + return 'ACEPTADO'; + } + return 'ENVIADO'; + } + private function nombreTipo(int $tipo): string { return match ($tipo) { @@ -971,13 +1283,13 @@ private function registrosLibroCompras(): array { return [ - ['tipo_dte' => 30, 'documento' => 'FACTURA', 'folio' => 234, 'observacion' => 'FACTURA DEL GIRO CON DERECHO A CREDITO', 'monto_exento' => 0, 'monto_afecto' => 6284], - ['tipo_dte' => 33, 'documento' => 'FACTURA ELECTRONICA', 'folio' => 32, 'observacion' => 'FACTURA DEL GIRO CON DERECHO A CREDITO', 'monto_exento' => 8003, 'monto_afecto' => 4204], - ['tipo_dte' => 30, 'documento' => 'FACTURA', 'folio' => 781, 'observacion' => 'FACTURA CON IVA USO COMUN', 'monto_exento' => 0, 'monto_afecto' => 29604, 'factor_proporcionalidad' => 0.60], - ['tipo_dte' => 60, 'documento' => 'NOTA DE CREDITO', 'folio' => 451, 'observacion' => 'NOTA DE CREDITO POR DESCUENTO A FACTURA 234', 'monto_exento' => 0, 'monto_afecto' => 2620], - ['tipo_dte' => 33, 'documento' => 'FACTURA ELECTRONICA', 'folio' => 67, 'observacion' => 'ENTREGA GRATUITA DEL PROVEEDOR', 'monto_exento' => 0, 'monto_afecto' => 9035], - ['tipo_dte' => 46, 'documento' => 'FACTURA DE COMPRA ELECTRONICA', 'folio' => 9, 'observacion' => 'COMPRA CON RETENCION TOTAL DEL IVA', 'monto_exento' => 0, 'monto_afecto' => 9078], - ['tipo_dte' => 60, 'documento' => 'NOTA DE CREDITO', 'folio' => 211, 'observacion' => 'NOTA DE CREDITO POR DESCUENTO FACTURA ELECTRONICA 32', 'monto_exento' => 0, 'monto_afecto' => 2310], + ['tipo_dte' => 30, 'documento' => 'FACTURA', 'folio' => 234, 'observacion' => 'FACTURA DEL GIRO CON DERECHO A CREDITO', 'monto_exento' => 0, 'monto_afecto' => 11530], + ['tipo_dte' => 33, 'documento' => 'FACTURA ELECTRONICA', 'folio' => 32, 'observacion' => 'FACTURA DEL GIRO CON DERECHO A CREDITO', 'monto_exento' => 8297, 'monto_afecto' => 5016], + ['tipo_dte' => 30, 'documento' => 'FACTURA', 'folio' => 781, 'observacion' => 'FACTURA CON IVA USO COMUN', 'monto_exento' => 0, 'monto_afecto' => 29668, 'factor_proporcionalidad' => 0.60], + ['tipo_dte' => 60, 'documento' => 'NOTA DE CREDITO', 'folio' => 451, 'observacion' => 'NOTA DE CREDITO POR DESCUENTO A FACTURA 234', 'monto_exento' => 0, 'monto_afecto' => 2655], + ['tipo_dte' => 33, 'documento' => 'FACTURA ELECTRONICA', 'folio' => 67, 'observacion' => 'ENTREGA GRATUITA DEL PROVEEDOR', 'monto_exento' => 0, 'monto_afecto' => 9381], + ['tipo_dte' => 46, 'documento' => 'FACTURA DE COMPRA ELECTRONICA', 'folio' => 9, 'observacion' => 'COMPRA CON RETENCION TOTAL DEL IVA', 'monto_exento' => 0, 'monto_afecto' => 9252], + ['tipo_dte' => 60, 'documento' => 'NOTA DE CREDITO', 'folio' => 211, 'observacion' => 'NOTA DE CREDITO POR DESCUENTO FACTURA ELECTRONICA 32', 'monto_exento' => 0, 'monto_afecto' => 3063], ]; } } diff -ruN /mnt/data/vase_work_before/public/css/set-pruebas-boletas-sii.css /mnt/data/vase_work/public/css/set-pruebas-boletas-sii.css --- /mnt/data/vase_work_before/public/css/set-pruebas-boletas-sii.css 2026-07-20 20:53:19.000000000 +0000 +++ /mnt/data/vase_work/public/css/set-pruebas-boletas-sii.css 2026-08-04 21:07:35.268445694 +0000 @@ -33,3 +33,4 @@ .is-pulsing{animation:sbsPulse 1.2s ease-in-out infinite} @keyframes sbsPulse{0%,100%{opacity:1}50%{opacity:.55}} @media(max-width:680px){.sbs-wizard--three{grid-template-columns:1fr}} +.sbs-info-box.is-verified{border-color:#75e0a7;background:#f3fff7}.sbs-info-box.is-verified p{color:#05603a}.sbs-info-box.is-warning{border-color:#fedf89;background:#fffaeb}.sbs-info-box.is-warning p{color:#7a2e0e}.sbs-audit-block{margin-top:18px;padding:18px;border:1px solid #b2ccff;border-radius:14px;background:#f8fbff}.sbs-audit-block .sbs-section-head{align-items:flex-start}.sbs-audit-block h3{margin:0 0 4px}.sbs-audit-block p{margin:0;color:var(--muted)}.sbs-data-table--audit{min-width:980px}.sbs-data-table--audit td:first-child{min-width:170px}.sbs-audit-block pre{max-height:520px} diff -ruN /mnt/data/vase_work_before/public/js/set-pruebas-boletas-sii.js /mnt/data/vase_work/public/js/set-pruebas-boletas-sii.js --- /mnt/data/vase_work_before/public/js/set-pruebas-boletas-sii.js 2026-07-20 20:53:45.000000000 +0000 +++ /mnt/data/vase_work/public/js/set-pruebas-boletas-sii.js 2026-08-04 21:07:28.512445694 +0000 @@ -18,6 +18,7 @@ panels: [...document.querySelectorAll('[data-panel]')], datosEmisor: $('facturaDatosEmisor'), + setOfficialSummary: $('setOficialResumen'), facturaFolios: $('facturaFolios'), datosNext: $('datosSiguientePaso'), datosNextIcon: $('datosSiguienteIcono'), @@ -68,6 +69,11 @@ facturaDownload: $('btnDescargarXmlFacturas'), facturaAutoBadge: $('facturaAutoConsultaBadge'), facturaGoBooks: $('btnIrLibros'), + facturaAuditSummary: $('facturaAuditoriaResumen'), + facturaAuditDocuments: $('facturaAuditoriaDocumentos'), + facturaXmlExact: $('facturaXmlExacto'), + facturaUploadRaw: $('facturaUploadRaw'), + facturaStatusRaw: $('facturaEstadoSiiRaw'), libroCompras: $('libroComprasFilas'), }; @@ -87,11 +93,14 @@ cases: [], trackId: '', xmlBase64: '', - filename: 'EnvioDTE_SET_BASICO_4933514.xml', + filename: 'EnvioDTE_SET_BASICO_4994954.xml', currentStep: 1, accepted: false, autoConsulting: false, autoToken: 0, + audit: null, + uploadResponse: null, + statusResponse: null, }, }; @@ -158,6 +167,18 @@ ]); } + function renderOfficialSet() { + const set = state.facturas.config?.set_oficial || {}; + if (!els.setOfficialSummary) return; + const ok = set.verificado_con_codigo === true + && String(set.numero_atencion || '') === '4994954' + && Boolean(set.sha256); + els.setOfficialSummary.className = `sbs-info-box ${ok ? 'is-verified' : 'is-warning'}`; + els.setOfficialSummary.innerHTML = ok + ? `Set oficial 4994954 incorporado y verificado

Archivo ${escapeHtml(set.archivo || '-')} · SHA-256 ${escapeHtml(set.sha256 || '-')} · 8 casos trasladados al generador.

` + : 'Set oficial pendiente de verificar

No se habilitará el envío hasta que el código confirme el nuevo set 4994954.

'; + } + function foliosReady() { const folios = state.facturas.config?.folios || {}; return ['33', '61', '56'].every((tipo) => Boolean(folios[tipo]?.listo)); @@ -172,6 +193,7 @@ && config.resolucion_numero_correcto && config.resolucion_fecha_correcta && config.certificado_cargado + && config.set_oficial?.verificado_con_codigo === true && foliosReady() ); } @@ -209,7 +231,7 @@ els.datosNext.className = `sbs-next-step ${ready ? 'is-ready' : 'is-pending'}`; els.datosNextIcon.textContent = ready ? '✓' : '!'; els.datosNextLabel.textContent = ready ? 'TODO LISTO' : 'FALTA COMPLETAR'; - els.datosNextTitle.textContent = ready ? 'Ya puedes enviar el Set Básico 4933514' : 'Todavía falta completar la configuración'; + els.datosNextTitle.textContent = ready ? 'Ya puedes enviar el Set Básico 4994954' : 'Todavía falta completar la configuración'; els.datosNextDetail.textContent = ready ? 'No cargues más CAF. Presiona el botón para revisar y enviar los ocho DTE.' : (state.facturas.config?.mensaje || 'Revisa las tarjetas marcadas en rojo.'); @@ -331,6 +353,7 @@ checklistItem('Ambiente de certificación', config.ambiente || 'Sin configurar', String(config.ambiente || '').toUpperCase() === 'CERTIFICACION'), checklistItem('Resolución SII', `${config.resolucion_numero ?? '-'} · ${config.resolucion_fecha || '-'}`, Boolean(config.resolucion_numero_correcto && config.resolucion_fecha_correcta)), checklistItem('Certificado digital', config.certificado_cargado ? 'Certificado y contraseña cargados' : 'Falta certificado o contraseña', Boolean(config.certificado_cargado)), + checklistItem('Nuevo set oficial SII', `${config.set_oficial?.numero_atencion || '-'} · ${config.set_oficial?.archivo || 'sin archivo'}`, config.set_oficial?.verificado_con_codigo === true), checklistItem('Factura electrónica tipo 33', `${folios['33']?.disponibles ?? 0}/${folios['33']?.requeridos ?? 4} folios`, Boolean(folios['33']?.listo)), checklistItem('Nota de crédito tipo 61', `${folios['61']?.disponibles ?? 0}/${folios['61']?.requeridos ?? 3} folios`, Boolean(folios['61']?.listo)), checklistItem('Nota de débito tipo 56', `${folios['56']?.disponibles ?? 0}/${folios['56']?.requeridos ?? 1} folios`, Boolean(folios['56']?.listo)), @@ -342,7 +365,7 @@ const config = state.facturas.config || {}; const folios = config.folios || {}; els.facturaSummary.innerHTML = summaryBoxes([ - ['N° atención', config.numero_atencion?.set_basico || '4933514'], + ['N° atención', config.numero_atencion?.set_basico || '4994954'], ['Ambiente', config.ambiente || '-'], ['Resolución', `${config.resolucion_numero ?? '-'} · ${config.resolucion_fecha || '-'}`], ['Factura 33', `${folios['33']?.disponibles ?? 0}/${folios['33']?.requeridos ?? 4}`], @@ -453,6 +476,7 @@ state.facturas.cases = data.facturas?.casos || []; renderEmisor(); + renderOfficialSet(); renderFolios(); renderDatosNextStep(); renderBoletaCases(); @@ -495,6 +519,69 @@ return ['RSC', 'RCH', 'DOK', 'EPR', 'ACEPTADO', 'RECHAZADO'].some((item) => code.includes(item)); } + function decodeXmlBase64(base64Value) { + if (!base64Value) return ''; + try { + const binary = atob(base64Value); + const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0)); + if (typeof TextDecoder !== 'undefined') { + return new TextDecoder('iso-8859-1').decode(bytes); + } + return Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''); + } catch (error) { + return `No se pudo decodificar el XML: ${error.message}`; + } + } + + function renderFacturaAudit(payload, status) { + if (payload.auditoria) state.facturas.audit = payload.auditoria; + if (payload.upload) state.facturas.uploadResponse = payload.upload; + state.facturas.statusResponse = status || state.facturas.statusResponse; + + const audit = state.facturas.audit || {}; + const counts = audit.conteos || {}; + const official = audit.set_oficial || state.facturas.config?.set_oficial || {}; + const validations = audit.validaciones || {}; + if (els.facturaAuditSummary) { + els.facturaAuditSummary.innerHTML = summaryBoxes([ + ['SHA-256 XML', audit.sha256 || '-'], + ['Bytes enviados', audit.bytes ?? '-'], + ['Encoding', audit.encoding_declarado || '-'], + ['Raíz / Set ID', `${audit.raiz || '-'} · ${audit.set_id || '-'}`], + ['Documentos', counts.documentos ?? '-'], + ['Firmas XMLDSig', counts.firmas_xmldsig ?? '-'], + ['TED / FRMT', `${counts.ted ?? '-'} / ${counts.frmt ?? '-'}`], + ['Set oficial', `${official.numero_atencion || '4994954'} · ${validations.coincidencia_set_oficial || '-'}`], + ['Validación XSD', validations.xsd_oficial || 'PENDIENTE'], + ]); + } + + const docs = Array.isArray(audit.documentos) ? audit.documentos : []; + if (els.facturaAuditDocuments) { + els.facturaAuditDocuments.innerHTML = docs.length ? docs.map((doc) => ` + + ${escapeHtml(doc.referencia_set || doc.id || '-')} + T${escapeHtml(doc.tipo_dte)} / F${escapeHtml(doc.folio)} + ${escapeHtml(doc.razon_social_receptor || '-')}${escapeHtml(doc.rut_receptor || '-')} + ${money(doc.neto)} + ${money(doc.exento)} + ${money(doc.iva)} + ${money(doc.total)} + + `).join('') : 'La auditoría detallada se mostrará después del envío.'; + } + + if (els.facturaXmlExact) { + els.facturaXmlExact.textContent = decodeXmlBase64(state.facturas.xmlBase64) || 'Esperando XML...'; + } + if (els.facturaUploadRaw) { + els.facturaUploadRaw.textContent = JSON.stringify(state.facturas.uploadResponse || {}, null, 2); + } + if (els.facturaStatusRaw) { + els.facturaStatusRaw.textContent = status?.raw || JSON.stringify(status || {}, null, 2); + } + } + function renderResult(kind, payload, expected) { const target = kind === 'boletas' ? { state: state.boletas, @@ -518,6 +605,7 @@ target.state.trackId = String(payload.track_id || target.state.trackId || ''); target.state.xmlBase64 = String(payload.xml_base64 || target.state.xmlBase64 || ''); target.state.filename = String(payload.archivo || target.state.filename); + if (kind === 'facturas') renderFacturaAudit(payload, status); let folios = '-'; if (Array.isArray(payload.folios)) folios = payload.folios.join(', '); @@ -550,7 +638,7 @@ target.diagnostic.className = `sbs-diagnostic ${resultStatusClass(status, expected)}`; target.diagnostic.textContent = diagnostic; - target.raw.textContent = status.raw || JSON.stringify(status.respuesta || payload.upload || payload, null, 2); + target.raw.textContent = status.raw || JSON.stringify(kind === 'facturas' ? { upload: state.facturas.uploadResponse, estado: status, auditoria: state.facturas.audit } : (status.respuesta || payload.upload || payload), null, 2); target.consult.disabled = !canConsult || !target.state.trackId || (kind === 'facturas' && state.facturas.autoConsulting); target.download.disabled = !target.state.xmlBase64; target.section.hidden = false; @@ -674,7 +762,7 @@ showMessage('danger', 'Sin permiso para enviar', 'Tu usuario no tiene el permiso facturacion.set_boletas.enviar.'); return; } - if (!window.confirm('Se enviarán ahora los 8 DTE del Set Básico 4933514. Presiona Aceptar una sola vez.')) return; + if (!window.confirm('Se enviarán ahora los 8 DTE del Set Básico 4994954. Presiona Aceptar una sola vez.')) return; const original = els.facturaSend.textContent; state.facturas.autoConsulting = true; @@ -710,7 +798,7 @@ state.facturas.autoConsulting = false; els.facturaAutoBadge.textContent = 'ENVÍO FALLIDO'; els.facturaAutoBadge.className = 'sbs-status sbs-status--danger'; - showMessage('danger', 'No se pudo enviar el Set Básico 4933514', error.message); + showMessage('danger', 'No se pudo enviar el Set Básico 4994954', error.message); switchTab('facturas', false); goFacturaStep(2, false); } finally { diff -ruN /mnt/data/vase_work_before/resources/views/facturacion/set-pruebas-boletas.blade.php /mnt/data/vase_work/resources/views/facturacion/set-pruebas-boletas.blade.php --- /mnt/data/vase_work_before/resources/views/facturacion/set-pruebas-boletas.blade.php 2026-07-20 20:53:45.000000000 +0000 +++ /mnt/data/vase_work/resources/views/facturacion/set-pruebas-boletas.blade.php 2026-08-04 21:06:58.924445694 +0000 @@ -8,7 +8,7 @@ - + @endsection @section('content') @@ -38,7 +38,7 @@ - +
@@ -53,10 +53,14 @@
Cargando datos del emisor...
+
+ Verificando el nuevo set oficial del SII... +

Se comprobará el número de atención, archivo fuente y huella SHA-256 usada por el generador.

+
-

Folios CAF requeridos para el Set Básico 4933514

+

Folios CAF requeridos para el Set Básico 4994954

Se necesitan 4 folios tipo 33, 3 folios tipo 61 y 1 folio tipo 56.

@@ -139,7 +143,7 @@
- SET 4933514 + SET 4994954

Emitir Set Básico de Facturas

Primero se valida. Después presionas un solo botón y el sistema muestra automáticamente la respuesta del SII.

@@ -184,7 +188,7 @@
PASO 2 DE 3 -

Enviar el Set Básico 4933514

+

Enviar el Set Básico 4994954

Se generarán y enviarán juntos: 4 facturas tipo 33, 3 notas de crédito tipo 61 y 1 nota de débito tipo 56.

8 DTE LISTOS @@ -239,8 +243,37 @@ Descargar XML enviado
+
+
+
+

Auditoría exacta del envío

+

Estos datos corresponden al mismo XML serializado que fue adjuntado al upload del SII.

+
+
+
+
+ + + + + +
CasoDTE/FolioReceptorNetoExentoIVATotal
Esperando envío...
+
+
+ XML exacto enviado al SII +

+                        
+
+ Respuesta inmediata del upload +

+                        
+
+ Respuesta de consulta del Track ID +

+                        
+
- Respuesta técnica completa + Respuesta técnica consolidada

                     
@@ -248,7 +281,7 @@
@@ -258,13 +291,13 @@
- 4933515 + 4994955

Libro de Ventas

-

Debe construirse con los ocho documentos del Set Básico 4933514, una vez que el envío quede aceptado sin rechazos ni reparos.

+

Debe construirse con los ocho documentos del Set Básico 4994954, una vez que el envío quede aceptado sin rechazos ni reparos.

DESPUÉS DEL SET BÁSICO
- 4933516 + 4994956

Libro de Compras

Este es el número de atención que se debe informar para el set de compras asignado a EL PAPAS SPA.

NÚMERO CONFIRMADO @@ -273,7 +306,7 @@
-

Datos exactos del Libro de Compras 4933516

+

Datos exactos del Libro de Compras 4994956

La factura con IVA de uso común debe considerar factor de proporcionalidad 0,60.

@@ -287,12 +320,12 @@
Orden correcto del proceso -

Primero envía y aprueba el Set Básico 4933514. Después genera el Libro de Ventas 4933515 y el Libro de Compras 4933516. No se mezclan con el set de boletas.

+

Primero envía y aprueba el Set Básico 4994954. Después genera el Libro de Ventas 4994955 y el Libro de Compras 4994956. No se mezclan con el set de boletas.

@endsection @section('javascript') - + @endsection diff -ruN /mnt/data/vase_work_before/storage/app/private/sii/certificacion/sets/SIISetDePruebas779253546_4994954.txt /mnt/data/vase_work/storage/app/private/sii/certificacion/sets/SIISetDePruebas779253546_4994954.txt --- /mnt/data/vase_work_before/storage/app/private/sii/certificacion/sets/SIISetDePruebas779253546_4994954.txt 1970-01-01 00:00:00.000000000 +0000 +++ /mnt/data/vase_work/storage/app/private/sii/certificacion/sets/SIISetDePruebas779253546_4994954.txt 2026-08-04 21:13:09.344445694 +0000 @@ -0,0 +1,132 @@ +INDICACIONES GENERALES: + +Se debe adjuntar ejemplar tributario y cedible de los documentos: Factura Electrónica, Factura No Afecta o Exenta Electrónica, Guía de Despacho Electrónica y Factura de Compra Electrónica. + +Para consultar los datos del contribuyente, como el giro, razón social, direcciones y sucursales, Dirección Regional o Unidad debe ingresar en la opción "Mi SII" de la página del SII. + +Además se les recomienda no utilizar abreviaciones en los giros y no agregar textos que informen arreglos de contrato con los clientes. + + +SET BASICO - NUMERO DE ATENCION: 4994954 + +IMPORTANTE: Considerar que los descuentos por línea o globales deben ser indicados en las representaciones impresas. Además, señalar las cifras con separador de miles con ".". + + +CASO 4994954-1 +============== +DOCUMENTO FACTURA ELECTRONICA + +ITEM CANTIDAD PRECIO UNITARIO +Cajón AFECTO 189 4666 +Relleno AFECTO 79 7801 + + +CASO 4994954-2 +============== +DOCUMENTO FACTURA ELECTRONICA + +ITEM CANTIDAD PRECIO UNITARIO DESCUENTO ITEM +Pañuelo AFECTO 999 7683 12% +ITEM 2 AFECTO 951 6728 31% + + +CASO 4994954-3 +============== +DOCUMENTO FACTURA ELECTRONICA + +ITEM CANTIDAD PRECIO UNITARIO +Pintura B&W AFECTO 99 8803 +ITEM 2 AFECTO 276 4668 +ITEM 3 SERVICIO EXENTO 1 35561 + + +CASO 4994954-4 +============== +DOCUMENTO FACTURA ELECTRONICA + +ITEM CANTIDAD PRECIO UNITARIO +ITEM 1 AFECTO 567 7864 +ITEM 2 AFECTO 240 9860 +ITEM 3 SERVICIO EXENTO 2 6863 + +DESCUENTO GLOBAL ITEMES AFECTOS 30% + + +CASO 4994954-5 +============== +DOCUMENTO NOTA DE CREDITO ELECTRONICA +REFERENCIA FACTURA ELECTRONICA CORRESPONDIENTE A CASO 4994954-1 +RAZON REFERENCIA CORRIGE GIRO DEL RECEPTOR + + +CASO 4994954-6 +============== +DOCUMENTO NOTA DE CREDITO ELECTRONICA +REFERENCIA FACTURA ELECTRONICA CORRESPONDIENTE A CASO 4994954-2 +RAZON REFERENCIA DEVOLUCION DE MERCADERIAS + +ITEM CANTIDAD +Pañuelo AFECTO 367 +ITEM 2 AFECTO 645 + + +CASO 4994954-7 +============== +DOCUMENTO NOTA DE CREDITO ELECTRONICA +REFERENCIA FACTURA ELECTRONICA CORRESPONDIENTE A CASO 4994954-3 +RAZON REFERENCIA ANULA FACTURA + + +CASO 4994954-8 +============== +DOCUMENTO NOTA DE DEBITO ELECTRONICA +REFERENCIA NOTA DE CREDITO ELECTRONICA CORRESPONDIENTE A CASO 4994954-5 +RAZON REFERENCIA ANULA NOTA DE CREDITO ELECTRONICA +-------------------------------------------------------------------------------- +SET LIBRO DE VENTAS - NUMERO DE ATENCION: 4994955 + +CONSTRUYA EL LIBRO DE VENTAS CON LOS DOCUMENTOS CON QUE GENERO +EL SET BASICO O EL SET DE FACTURA EXENTA, SEGUN CORRESPONDA. +SI OBTUVO AMBOS SET, UTILICE LOS DOCUMENTOS DEL SET BASICO PARA +CONSTRUIR EL LIBRO DE VENTAS. +-------------------------------------------------------------------------------- +SET LIBRO DE COMPRAS - NUMERO DE ATENCION: 4994956 + +========================================================================== +TIPO DOCUMENTO FOLIO +OBSERVACIONES +MONTO EXENTO MONTO AFECTO +========================================================================== +FACTURA 234 +FACTURA DEL GIRO CON DERECHO A CREDITO + 11530 + +FACTURA ELECTRONICA 32 +FACTURA DEL GIRO CON DERECHO A CREDITO + 8297 5016 + +FACTURA 781 +FACTURA CON IVA USO COMUN + 29668 + +NOTA DE CREDITO 451 +NOTA DE CREDITO POR DESCUENTO A FACTURA 234 + 2655 + +FACTURA ELECTRONICA 67 +ENTREGA GRATUITA DEL PROVEEDOR + 9381 + +FACTURA DE COMPRA ELECTRONICA 9 +COMPRA CON RETENCION TOTAL DEL IVA + 9252 + +NOTA DE CREDITO 211 +NOTA DE CREDITO POR DESCUENTO FACTURA ELECTRONICA 32 + 3063 +========================================================================== + +OBSERVACIONES GENERALES +----------------------- +EN FACTURA CON IVA USO COMUN CONSIDERE QUE EL FACTOR DE PROPORCIONALIDAD +DEL IVA ES DE 0.60 diff -ruN /mnt/data/vase_work_before/storage/app/private/sii/certificacion/sets/comparacion_4994954.json /mnt/data/vase_work/storage/app/private/sii/certificacion/sets/comparacion_4994954.json --- /mnt/data/vase_work_before/storage/app/private/sii/certificacion/sets/comparacion_4994954.json 1970-01-01 00:00:00.000000000 +0000 +++ /mnt/data/vase_work/storage/app/private/sii/certificacion/sets/comparacion_4994954.json 2026-08-04 21:15:57.132445694 +0000 @@ -0,0 +1,13 @@ +{ + "rut_emisor": "77925354-6", + "razon_social": "EL PAPAS SPA", + "set_basico": "4994954", + "libro_ventas": "4994955", + "libro_compras": "4994956", + "archivo_oficial": "SIISetDePruebas779253546_4994954.txt", + "sha256": "6ddd988da17a7ef887168b1d8f220eb1252074e171728fd4a9fb5faab8994daf", + "casos": 8, + "distribucion_dte": {"33": 4, "61": 3, "56": 1}, + "verificado": true, + "fecha_verificacion": "2026-08-04" +} diff -ruN /mnt/data/vase_work_before/storage/app/private/sii/xsd/dte/LEEME.txt /mnt/data/vase_work/storage/app/private/sii/xsd/dte/LEEME.txt --- /mnt/data/vase_work_before/storage/app/private/sii/xsd/dte/LEEME.txt 1970-01-01 00:00:00.000000000 +0000 +++ /mnt/data/vase_work/storage/app/private/sii/xsd/dte/LEEME.txt 2026-08-04 21:14:08.824445694 +0000 @@ -0,0 +1,11 @@ +VALIDACIÓN XSD OFICIAL SII + +Copiar en esta misma carpeta los cuatro archivos del paquete oficial schema_dte.zip: +- EnvioDTE_v10.xsd +- DTE_v10.xsd +- SiiTypes_v10.xsd +- xmldsignature_v10.xsd + +Cuando estén los cuatro, VASE ejecutará schemaValidate() automáticamente antes de subir el Set Básico. +Fuente oficial: SII > Factura electrónica > Formato XML de documentos electrónicos. +No renombrar los archivos ni cambiar sus includes/imports relativos.