Protected
constructorOptional
_value: RfcPrivate
Optional
Readonly
_valueStatic
checkStatic
createStatic
emptyGenerated using TypeDoc
Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Generated using TypeDoc
Generated using TypeDoc
Private
Readonly
_bodyPrivate
Readonly
_headersPrivate
Readonly
_methodPrivate
Readonly
_uriGenerated using TypeDoc
Private
Readonly
_bodyPrivate
Readonly
_headersPrivate
Readonly
_statusGenerated using TypeDoc
Filter by filename or content contract
-Static
obtainGenerated using TypeDoc
Expected behavior of a PackageReader contract
-Private
Readonly
_packageStatic
createStatic
createGenerated using TypeDoc
if assign by Values.code
-Private
Readonly
valueOptional
code?: numberStatic
Protected
Readonly
VALUESStatic
getGenerated using TypeDoc
Private
Readonly
MapReadonly
_idStatic
createStatic
undefinedGenerated using TypeDoc
Private
Readonly
MapReadonly
_idStatic
createStatic
undefinedGenerated using TypeDoc
Private
Readonly
MapReadonly
_idStatic
createStatic
undefinedGenerated using TypeDoc
Optional
previous: ErrorPrivate
Optional
Readonly
_previousOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureStatic
createOptional
previous: ErrorGenerated using TypeDoc
Helper to iterate inside a CSV file -The file must have on the first line the headers. -The file uses "~" as separator and "|" as text delimiter.
-Private
Readonly
_iteratorStatic
createStatic
createGenerated using TypeDoc
Defines a date and time
-DateTime constructor.
-If value is an integer is used as a timestamp, if is a string is evaluated -as an argument for DateTimeImmutable and if it is DateTimeImmutable is used as is.
-Optional
value: string | number | DateTimeOptional
defaultTimeZone: stringError if unable to create a DateTime
-Private
Readonly
_defaultPrivate
_valuePrivate
castStatic
createCreate a DateTime instance
-If value is an integer is used as a timestamp, if is a string is evaluated -as an argument for DateTimeImmutable and if it is DateTimeImmutable is used as is.
-Optional
value: string | number | DateTimeOptional
defaultTimeZone: stringStatic
nowGenerated using TypeDoc
Defines a period of time by start of period and end of period values
-Private
Readonly
_endPrivate
Readonly
_startStatic
createStatic
createGenerated using TypeDoc
Readonly
_idGenerated using TypeDoc
Readonly
_idGenerated using TypeDoc
Private
Readonly
_packagePrivate
Readonly
_packagePrivate
Readonly
_statusStatus of the download call
-Generated using TypeDoc
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Generated using TypeDoc
Readonly
_idGenerated using TypeDoc
Defines a eFirma/FIEL/FEA -This object is based on nodecfdi/credentials Credential object
-Credential
-Private
Readonly
_credentialStatic
createGenerated using TypeDoc
The implementors must create the request signed ready to send to the SAT Web Service Descarga Masiva -The information about owner like RFC, certificate, private key, etc. are outside the scope of this interface
-Private
Readonly
_fielPrivate
createPrivate
createPrivate
createPrivate
parseCreates a query signed xml message
-RequestBuilderException
-Static
Private
createGenerated using TypeDoc
Expected behavior of a PackageReader contract
-Private
Readonly
_archivePrivate
Readonly
_filenamePrivate
_filterPrivate
_removeOptional
filter: FileFilterInterfaceStatic
createStatic
createGenerated using TypeDoc
Generated using TypeDoc
Optional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
Optional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
Optional
onFireRequest: CallableFunctionOptional
onFireResponse: CallableFunctionPrivate
Optional
Readonly
_firePrivate
Optional
Readonly
_fireMethod called before calling the web service
-Method called after calling the web service
-Generated using TypeDoc
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Generated using TypeDoc
The iterator will be used in a foreach loop to create MetadataItems -The first iteration must contain an array of header names that will be renames to lower case first letter -The next iterations must contain an array with data
-Private
Readonly
_csvPrivate
Readonly
_thirdPrivate
changeStatic
createThis method fix the content and create a SplTempFileObject to store the information
-Optional
thirdParties: ThirdPartiesRecordsGenerated using TypeDoc
Implementation to filter a Metadata Package file contents
-Generated using TypeDoc
Metadata DTO object
-This collection of magic properties is reported as of 2019-08-01, if it changes use all()/get() methods
-Private
Readonly
_dataGenerated using TypeDoc
Expected behavior of a PackageReader contract
-Optional
_thirdParties: ThirdPartiesRecordsPrivate
Readonly
_packagePrivate
Optional
_thirdStatic
createStatic
createGenerated using TypeDoc
This preprocesor fixes metadata issues:
-MetadataContent
-Private
_contentsThe data to process
-Private
CONTROL_Private
CONTROL_Private
CONTROL_Generated using TypeDoc
NullObject patern, it does not filter any file contents
-Generated using TypeDoc
Optional
previous: ErrorPrivate
Readonly
_codePrivate
Readonly
_filenamePrivate
Optional
Readonly
_previousOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureStatic
createOptional
previous: ErrorGenerated using TypeDoc
Abstract
Optional
message: stringOptional
message: stringOptional
options: ErrorOptionsOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
This class contains all the information required to perform a query on the SAT Web Service
-Private
_complementPrivate
_documentPrivate
_documentPrivate
_downloadPrivate
_periodPrivate
_requestPrivate
_rfcPrivate
_rfcPrivate
Optional
_servicePrivate
_uuidStatic
createOptional
period: DateTimePeriodOptional
downloadType: DownloadTypeOptional
requestType: RequestTypeGenerated using TypeDoc
Private
Readonly
_requestPrivate
Readonly
_statusStatus of the verification call
-Generated using TypeDoc
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Generated using TypeDoc
Abstract
Optional
message: stringOptional
message: stringOptional
options: ErrorOptionsOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
Readonly
_idGenerated using TypeDoc
Protected
constructorStatic
checkStatic
createStatic
emptyGenerated using TypeDoc
Rest
...items: RfcMatch[]Private
Readonly
_countPrivate
Readonly
_itemsStatic
createRest
...items: RfcMatch[]Static
createRest
...values: string[]Generated using TypeDoc
Protected
constructorOptional
_value: RfcStatic
checkStatic
createStatic
emptyGenerated using TypeDoc
Client constructor of "servicio de consulta y recuperación de comprobantes"
-Optional
_currentToken: TokenOptional
endpoints: ServiceEndpointsendpoints If undefined uses CFDI endpoints
-Optional
_currentPrivate
Readonly
_endpointsPrivate
Readonly
_requestPrivate
Readonly
_webPrivate
consumeOptional
token: TokenConsume the "SolicitaDescarga" web service
-Consume the "VerificaSolicitudDescarga" web service
-Generated using TypeDoc
Optional
token: TokenOptional
token: TokenStatic
consumeOptional
token: TokenGenerated using TypeDoc
This class contains the end points to consume the service -Use ServiceEndpoints.cfdi() for "CFDI regulares" -Use ServiceEndpoints.retenciones() for "CFDI de retenciones e información de pagos"
-Private
Readonly
_authenticatePrivate
Readonly
_downloadPrivate
Readonly
_queryPrivate
Readonly
_servicePrivate
Readonly
_verifyStatic
cfdiCreate an object with known endpoints for "CFDI regulares"
-Static
retencionesGenerated using TypeDoc
Readonly
_idGenerated using TypeDoc
Optional
previous: ErrorPrivate
Readonly
_faultOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
Private
Readonly
_codePrivate
Readonly
_messageGenerated using TypeDoc
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Static
extractGenerated using TypeDoc
Private
Readonly
_codePrivate
Readonly
_messageGenerated using TypeDoc
if number is send assign value by array index of VALUES, values from 0 to 5 if string is send find value by Values.name
-Private
Readonly
valueOptional
code?: numberStatic
Protected
Readonly
VALUESStatic
getGenerated using TypeDoc
Class to extract the data from a "third parties" file.
-Private
Readonly
_csvStatic
createGenerated using TypeDoc
Implementation to filter a Metadata Package file contents
-Generated using TypeDoc
Private
Readonly
_recordsStatic
createStatic
createStatic
Private
formatGenerated using TypeDoc
Private
Readonly
_createdPrivate
Readonly
_expiresPrivate
Readonly
_valueGenerated using TypeDoc
Generated using TypeDoc
Rest
...packageIds: string[]Private
Readonly
_codePrivate
Readonly
_numberPrivate
Readonly
_packagesPrivate
Readonly
_statusPrivate
Readonly
_statusCode related to the status of the query
-Status of the verification call
-Status of the query
-Generated using TypeDoc
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-Find the element determined by the chain of children and return the attributes as an -array using the attribute name as array key and attribute value as entry value.
-Rest
...search: string[]Generated using TypeDoc
Private
Optional
Readonly
_previousPrivate
Readonly
_requestPrivate
Readonly
_responseOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
-Static
stackStatic
captureGenerated using TypeDoc
Protected
constructorOptional
_value: RfcPrivate
Optional
Readonly
_valueStatic
checkStatic
createStatic
emptyContain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]Private
Readonly
_bodyPrivate
Readonly
_headersPrivate
Readonly
_methodPrivate
Readonly
_uriPrivate
Readonly
_bodyPrivate
Readonly
_headersPrivate
Readonly
_statusStatic
obtainPrivate
Readonly
_packageStatic
createStatic
createif assign by Values.code
+Private
Readonly
valueOptional
code?: numberStatic
Protected
Readonly
VALUESStatic
getPrivate
Readonly
MapReadonly
_idStatic
createStatic
undefinedPrivate
Readonly
MapReadonly
_idStatic
createStatic
undefinedPrivate
Readonly
MapReadonly
_idStatic
createStatic
undefinedOptional
previous: ErrorPrivate
Optional
Readonly
_previousOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureStatic
createOptional
previous: ErrorHelper to iterate inside a CSV file +The file must have on the first line the headers. +The file uses "~" as separator and "|" as text delimiter.
+Private
Readonly
_iteratorStatic
createStatic
createDefines a date and time
+DateTime constructor.
+If value is an integer is used as a timestamp, if is a string is evaluated +as an argument for DateTimeImmutable and if it is DateTimeImmutable is used as is.
+Optional
value: string | number | DateTime<boolean>Optional
defaultTimeZone: stringError if unable to create a DateTime
+Private
Readonly
_defaultPrivate
_valuePrivate
castStatic
createCreate a DateTime instance
+If value is an integer is used as a timestamp, if is a string is evaluated +as an argument for DateTimeImmutable and if it is DateTimeImmutable is used as is.
+Optional
value: string | number | DateTime<boolean>Optional
defaultTimeZone: stringStatic
nowDefines a period of time by start of period and end of period values
+Private
Readonly
_endPrivate
Readonly
_startStatic
createStatic
createReadonly
_idReadonly
_idPrivate
Readonly
_packagePrivate
Readonly
_packagePrivate
Readonly
_statusStatus of the download call
+Contain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]Readonly
_idDefines a eFirma/FIEL/FEA +This object is based on nodecfdi/credentials Credential object
+Credential
+Private
Readonly
_credentialStatic
createPrivate
Readonly
_fielPrivate
createPrivate
createPrivate
createPrivate
parseStatic
Private
createPrivate
Readonly
_archivePrivate
Readonly
_filenamePrivate
_filterPrivate
_removeOptional
filter: FileFilterInterfaceStatic
createStatic
createOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureOptional
onFireRequest: CallableFunctionOptional
onFireResponse: CallableFunctionPrivate
Optional
Readonly
_firePrivate
Optional
Readonly
_fireContain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]The iterator will be used in a foreach loop to create MetadataItems +The first iteration must contain an array of header names that will be renames to lower case first letter +The next iterations must contain an array with data
+Private
Readonly
_csvPrivate
Readonly
_thirdPrivate
changeStatic
createThis method fix the content and create a SplTempFileObject to store the information
+Optional
thirdParties: ThirdPartiesRecordsImplementation to filter a Metadata Package file contents
+Metadata DTO object
+This collection of magic properties is reported as of 2019-08-01, if it changes use all()/get() methods
+Private
Readonly
_dataOptional
_thirdParties: ThirdPartiesRecordsPrivate
Readonly
_packagePrivate
Optional
_thirdStatic
createStatic
createThis preprocesor fixes metadata issues:
+MetadataContent
+Private
Readonly
CONTROL_Private
Readonly
CONTROL_Private
Readonly
CONTROL_Private
_contentsThe data to process
+NullObject patern, it does not filter any file contents
+Optional
previous: ErrorPrivate
Readonly
_codePrivate
Readonly
_filenamePrivate
Optional
Readonly
_previousOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureStatic
createOptional
previous: ErrorAbstract
Optional
message: stringOptional
message: stringOptional
options: ErrorOptionsOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureThis class contains all the information required to perform a query on the SAT Web Service
+Private
_complementPrivate
_documentPrivate
_documentPrivate
_downloadPrivate
_periodPrivate
_requestPrivate
_rfcPrivate
_rfcPrivate
Optional
_servicePrivate
_uuidStatic
createOptional
period: DateTimePeriodOptional
downloadType: DownloadTypeOptional
requestType: RequestTypePrivate
Readonly
_requestPrivate
Readonly
_statusStatus of the verification call
+Contain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]Abstract
Optional
message: stringOptional
message: stringOptional
options: ErrorOptionsOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
captureReadonly
_idProtected
constructorStatic
checkStatic
createStatic
emptyRest
...items: RfcMatch[]Private
Readonly
_countPrivate
Readonly
_itemsStatic
createRest
...items: RfcMatch[]Static
createRest
...values: string[]Protected
constructorOptional
_value: RfcStatic
checkStatic
createStatic
emptyClient constructor of "servicio de consulta y recuperación de comprobantes"
+Optional
_currentToken: TokenOptional
endpoints: ServiceEndpointsendpoints If undefined uses CFDI endpoints
+Optional
_currentPrivate
Readonly
_endpointsPrivate
Readonly
_requestPrivate
Readonly
_webPrivate
consumeOptional
token: TokenConsume the "SolicitaDescarga" web service
+Consume the "VerificaSolicitudDescarga" web service
+Optional
token: TokenOptional
token: TokenStatic
consumeOptional
token: TokenThis class contains the end points to consume the service +Use ServiceEndpoints.cfdi() for "CFDI regulares" +Use ServiceEndpoints.retenciones() for "CFDI de retenciones e información de pagos"
+Private
Readonly
_authenticatePrivate
Readonly
_downloadPrivate
Readonly
_queryPrivate
Readonly
_servicePrivate
Readonly
_verifyStatic
cfdiCreate an object with known endpoints for "CFDI regulares"
+Static
retencionesReadonly
_idOptional
previous: ErrorPrivate
Readonly
_faultOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
capturePrivate
Readonly
_codePrivate
Readonly
_messageContain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]Static
extractPrivate
Readonly
_codePrivate
Readonly
_messageif number is send assign value by array index of VALUES, values from 0 to 5 if string is send find value by Values.name
+Private
Readonly
valueOptional
code?: numberStatic
Protected
Readonly
VALUESStatic
getClass to extract the data from a "third parties" file.
+Private
Readonly
_csvStatic
createImplementation to filter a Metadata Package file contents
+Private
Readonly
_recordsStatic
createStatic
createStatic
Private
formatRest
...packageIds: string[]Private
Readonly
_codePrivate
Readonly
_numberPrivate
Readonly
_packagesPrivate
Readonly
_statusPrivate
Readonly
_statusCode related to the status of the query
+Status of the verification call
+Status of the query
+Contain functions to interact with XML contents and XML DOM
+This class is internal, do not use it outside this project
+Find the element determined by the chain of children and return the attributes as an +array using the attribute name as array key and attribute value as entry value.
+Rest
...search: string[]Private
Optional
Readonly
_previousPrivate
Readonly
_requestPrivate
Readonly
_responseOptional
causeOptional
stackStatic
Optional
prepareOptional override for formatting stack traces
+Static
stackStatic
capture:us: The documentation of this project is in spanish as this is the natural language for intended audience.
:mexico: La documentación del proyecto está en español porque ese es el lenguaje principal de los usuarios.
-npm i @nodecfdi/sat-ws-descarga-masiva --save
+Instalación
npm i @nodecfdi/sat-ws-descarga-masiva --save
o
-yarn add @nodecfdi/sat-ws-descarga-masiva
+yarn add @nodecfdi/sat-ws-descarga-masiva
o
-pnpm add @nodecfdi/sat-ws-descarga-masiva
+pnpm add @nodecfdi/sat-ws-descarga-masiva
Ejemplos de uso
Todos los objetos de entrada y salida se pueden exportar como JSON para su fácil depuración.
-Creación del servicio
import { readFileSync } from 'fs';
import { Fiel, HttpsWebClient, FielRequestBuilder, Service } from '@nodecfdi/sat-ws-descarga-masiva';
import { install } from '@nodecfdi/cfdiutils-common';
import { DOMParser, XMLSerializer, DOMImplementation } from '@xmldom/xmldom';
//instala tu gestor de DOM preferido para este ejemplo se usa @xmldom/xmldom
install(new DOMParser(), new XMLSerializer(), new DOMImplementation());
// Creación de la FIEL, puede leer archivos DER (como los envía el SAT) o PEM (convertidos con openssl)
const fiel = Fiel.create(
readFileSync('fake-fiel/EKU9003173C9.cer', 'binary'),
readFileSync('fake-fiel/EKU9003173C9.key', 'binary'),
'12345678a'
);
// verificar que la FIEL sea válida (no sea CSD y sea vigente acorde a la fecha del sistema)
if (!fiel.isValid()) {
return;
}
// Creación del cliente web se usa el cliente incluido en nodeJS.
const webClient = new HttpsWebClient();
// creación del objeto encargado de crear las solicitudes firmadas usando una FIEL
const requestBuilder = new FielRequestBuilder(fiel);
// Creación del servicio
const service = new Service(requestBuilder, webClient);
+Creación del servicio
import { readFileSync } from 'fs';
import {
Fiel,
HttpsWebClient,
FielRequestBuilder,
Service,
} from '@nodecfdi/sat-ws-descarga-masiva';
// Creación de la FIEL, puede leer archivos DER (como los envía el SAT) o PEM (convertidos con openssl)
const fiel = Fiel.create(
readFileSync('fake-fiel/EKU9003173C9.cer', 'binary'),
readFileSync('fake-fiel/EKU9003173C9.key', 'binary'),
'12345678a',
);
// verificar que la FIEL sea válida (no sea CSD y sea vigente acorde a la fecha del sistema)
if (!fiel.isValid()) {
return;
}
// Creación del cliente web se usa el cliente incluido en nodeJS.
const webClient = new HttpsWebClient();
// creación del objeto encargado de crear las solicitudes firmadas usando una FIEL
const requestBuilder = new FielRequestBuilder(fiel);
// Creación del servicio
const service = new Service(requestBuilder, webClient);
Cliente para consumir los servicios de CFDI de Retenciones
Existen dos tipos de Comprobantes Fiscales Digitales, los regulares (ingresos, egresos, traslados, nóminas y pagos), y los CFDI de retenciones e información de pagos (retenciones).
Puede utilizar esta librería para consumir los CFDI de Retenciones. Para lograrlo construya el servicio con la especificación de ServiceEndpoints.retenciones()
.
Los constructores ServiceEndpoints.cfdi()
y ServiceEndpoints.retenciones()
agregan automáticamente la propiedad ServiceType
al objeto. Esta propiedad será después utilizada el servicio para especificar el valor en la consulta antes de consumirla.
-import { HttpsWebClient, RequestBuilderInterface, ServiceEndpoints, Service } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var webClient: HttpsWebClient
* @var requestBuilder: RequestBuilderInterface
*/
// Creación del servicio
const service = new Service(requestBuilder, webClient, undefined, ServiceEndpoints.retenciones());
+import {
HttpsWebClient,
RequestBuilderInterface,
ServiceEndpoints,
Service,
} from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var webClient: HttpsWebClient
* @var requestBuilder: RequestBuilderInterface
*/
// Creación del servicio
const service = new Service(requestBuilder, webClient, undefined, ServiceEndpoints.cfdi());
Aunque no es recomendado, también puedes construir el objeto ServiceEndpoints con direcciones URL del servicio personalizadas utilizando el constructor del objeto en lugar de los métodos estáticos.
Realiza una consulta
Una vez creado el servicio, se puede presentar la consulta, si se pudo presentar devolverá el identificador de la solicitud, y con este identificador se podrá continuar al servicio de verificación.
@@ -52,7 +196,7 @@ @nodecfdi/sat-ws-descarga-masiva
RequestType.metadata
o de archivos CFDI RequestType.cfdi
.import { QueryParameters, DateTimePeriod } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* El servicio ya existe
* @var service: Service
*/
const request = QueryParameters.create(
DateTimePeriod.createFromValues('2022-01-01 00:00:00', '2022-02-28 23:59:59'));
// presentar la consulta
const query = await service.query(request);
// verificar que el proceso de consulta fue correcto
if (!query.getStatus().isAccepted()) {
console.log(`Fallo al presentar la consulta: ${query.getStatus().getMessage()}`);
return;
}
console.log(`Se generó la solicitud ${query.getRequestId()}`);
+import { QueryParameters, DateTimePeriod } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* El servicio ya existe
* @var service: Service
*/
const request = QueryParameters.create(
DateTimePeriod.createFromValues('2022-01-01 00:00:00', '2022-02-28 23:59:59'),
);
// presentar la consulta
const query = await service.query(request);
// verificar que el proceso de consulta fue correcto
if (!query.getStatus().isAccepted()) {
console.log(`Fallo al presentar la consulta: ${query.getStatus().getMessage()}`);
return;
}
console.log(`Se generó la solicitud ${query.getRequestId()}`);
Parámetros de la consulta
Periodo (DateTimePeriod
)
Fecha y hora de inicio y fin de la consulta. Si no se especifica crea un periodo del segundo exacto de la creación del objeto.
Tipo de descarga (DownloadType
)
Especifica si la solicitud es de documentos emitidos DownloadType::issued() o recibidos DownloadType::received(). Si no se especifica utiliza el valor de emitidos.
@@ -95,7 +239,7 @@ @nodecfdi/sat-ws-descarga-masiva
new RequestType('metadata')
.import { RfcMatch } from '@nodecfdi/sat-ws-descarga-masiva';
const rfcMatch = RfcMatch.create('XXX01010199A');
parameters = parameters->withRfcMatch(rfcMatch);
console.log(rfcMatch === parameters.getRfcMatch()); // bool(true)
+import { RfcMatch } from '@nodecfdi/sat-ws-descarga-masiva';
const rfcMatch = RfcMatch.create('XXX01010199A');
parameters = parameters->withRfcMatch(rfcMatch);
console.log(rfcMatch === parameters.getRfcMatch()); // bool(true)
El servicio del SAT permite especificar hasta 5 RFC Receptores, al menos así lo establecen en su documentación.
Sin embargo, al tratarse de receptores, solo se puede utilizar en una consulta de documentos emitidos.
@@ -103,10 +247,10 @@
@nodecfdi/sat-ws-descarga-masiva
Por lo regular utilizará solamente los métodos QueryParameter.getRfcMatch(): RfcMatch
y QueryParameter.withRfcMatch(rfcMatch: RfcMatch)
.
Sin embargo, si fuera necesario especificar el listado de RFC, se puede realizar de la siguiente manera:
-parameters = parameters.withRfcMatches(
RfcMatches.create(
RfcMatch.create('AAA010101000'),
RfcMatch.create('AAA010101001'),
RfcMatch.create('AAA010101002')
)
);
+parameters = parameters.withRfcMatches(
RfcMatches.create(
RfcMatch.create('AAA010101000'),
RfcMatch.create('AAA010101001'),
RfcMatch.create('AAA010101002'),
),
);
O bien, utilizar una lista de RFC como cadenas de texto:
-parameters = parameters.withRfcMatches(
RfcMatches.createFromValues('AAA010101000', 'AAA010101001', 'AAA010101002')
);
+parameters = parameters.withRfcMatches(
RfcMatches.createFromValues('AAA010101000', 'AAA010101001', 'AAA010101002'),
);
Acerca de RfcMatches
Este objeto mantiene una lista de RfcMatches
, pero con características especiales:
@@ -137,355 +281,41 @@ @nodecfdi/sat-ws-descarga-masiva
MAG041126GT8
. Como se solicitan recibidos, entonces son los emidos por ese RFC.96623061-61fe-49de-b298-c7156476aa8b
.import { QueryParameters, DateTimePeriod, DownloadType, RequestType,
DocumentType, ComplementoCfdi, DocumentStatus, RfcOnBehalf, RfcMatch, Uuid
} from '@nodecfdi/sat-ws-descarga-masiva';
const query = QueryParameters.create()
.withPeriod(DateTimePeriod.createFromValues('2019-01-13 00:00:00', '2019-01-13 23:59:59'))
.withDownloadType(DownloadType.received())
.withRequestType(RequestType.xml())
.withDocumentType(DocumentType.ingreso())
.withComplement(ComplementoCfdi.leyendasFiscales10())
.withDocumentStatus(DocumentStatus.active())
.withRfcOnBehalf(RfcOnBehalf.create('XXX01010199A'))
.withRfcMatch(RfcMatch.create('MAG041126GT8'))
.withUuid(Uuid.create('96623061-61fe-49de-b298-c7156476aa8b'))
;
+import {
QueryParameters,
DateTimePeriod,
DownloadType,
RequestType,
DocumentType,
ComplementoCfdi,
DocumentStatus,
RfcOnBehalf,
RfcMatch,
Uuid,
} from '@nodecfdi/sat-ws-descarga-masiva';
const query = QueryParameters.create()
.withPeriod(DateTimePeriod.createFromValues('2019-01-13 00:00:00', '2019-01-13 23:59:59'))
.withDownloadType(DownloadType.received())
.withRequestType(RequestType.xml())
.withDocumentType(DocumentType.ingreso())
.withComplement(ComplementoCfdi.leyendasFiscales10())
.withDocumentStatus(DocumentStatus.active())
.withRfcOnBehalf(RfcOnBehalf.create('XXX01010199A'))
.withRfcMatch(RfcMatch.create('MAG041126GT8'))
.withUuid(Uuid.create('96623061-61fe-49de-b298-c7156476aa8b'));
Ejemplo de consulta por UUID
En este caso se especifica solamente el UUID a consultar, en el ejemplo es 96623061-61fe-49de-b298-c7156476aa8b
.
Nota: Todos los demás argumentos de la consulta son ignorados.
-import { QueryParameters, Uuid } from '@nodecfdi/sat-ws-descarga-masiva';
$query = QueryParameters.create()
.withUuid(Uuid.create('96623061-61fe-49de-b298-c7156476aa8b'))
;
+import { QueryParameters, Uuid } from '@nodecfdi/sat-ws-descarga-masiva';
$query = QueryParameters.create().withUuid(Uuid.create('96623061-61fe-49de-b298-c7156476aa8b'));
Verificar una consulta
La verificación depende de que la consulta haya sido aceptada.
-import { Service } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var service: Service
* @var requestId: Identificador generado al presentar la consulta, previamente fabricado
*/
// consultar el servicio de verificación
const verify = await service.verify(requestId);
// revisar que el proceso de verificación fue correcto
if (!verify.getStatus().isAccepted()) {
console.log(`Fallo al verificar la consulta ${requestId}: ${verify.getStatus().getMessage()}`);
return;
}
// revisar el progreso de la generación de los paquetes
const statusRequest = verify.getStatusRequest();
if (statusRequest.isTypeOf('Expired') || statusRequest.isTypeOf('Failure') || statusRequest.isTypeOf('Rejected')) {
console.log(`La solicitud ${requestId} no se puede completar`);
return;
}
if (statusRequest.isTypeOf('InProgress') || statusRequest.isTypeOf('Accepted')) {
console.log(`La solicitud ${requestId} se está procesando`);
return;
}
if (statusRequest.isTypeOf('Finished')) {
console.log(`La solicitud ${requestId} está lista`);
}
console.log(`Se encontraron ${verify.countPackages()} paquetes`);
for (const packageId of verify.getPackageIds()) {
console.log(` > ${packageId}`)
}
+import { Service } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var service: Service
* @var requestId: Identificador generado al presentar la consulta, previamente fabricado
*/
// consultar el servicio de verificación
const verify = await service.verify(requestId);
// revisar que el proceso de verificación fue correcto
if (!verify.getStatus().isAccepted()) {
console.log(`Fallo al verificar la consulta ${requestId}: ${verify.getStatus().getMessage()}`);
return;
}
// revisar el progreso de la generación de los paquetes
const statusRequest = verify.getStatusRequest();
if (
statusRequest.isTypeOf('Expired') ||
statusRequest.isTypeOf('Failure') ||
statusRequest.isTypeOf('Rejected')
) {
console.log(`La solicitud ${requestId} no se puede completar`);
return;
}
if (statusRequest.isTypeOf('InProgress') || statusRequest.isTypeOf('Accepted')) {
console.log(`La solicitud ${requestId} se está procesando`);
return;
}
if (statusRequest.isTypeOf('Finished')) {
console.log(`La solicitud ${requestId} está lista`);
}
console.log(`Se encontraron ${verify.countPackages()} paquetes`);
for (const packageId of verify.getPackageIds()) {
console.log(` > ${packageId}`);
}
Descarga los paquetes de la consulta
La descarga de los paquetes depende de que la consulta haya sido correctamente verificada.
Una consulta genera un identificador de la solicitud, la verificación retorna uno o varios identificadores de paquetes. Necesitas descargar todos y cada uno de los paquetes para tener la información completa de la consulta.
-import { Service } from '@nodecfdi/sat-ws-descarga-masiva';
import { writeFileSync } from 'fs';
/**
* @var service: Service
* @var packagesIds: string[] El listado de identificadores de paquetes generado en la (correcta) verificación
*/
for (const packageId of packagesIds) {
const download = await service.download(packageId);
if (!download.getStatus().isAccepted()) {
console.log(`El paquete ${packageId} no se ha podido descargar: ${download.getStatus().getMessage()}`);
continue;
}
writeFileSync(`${packageId}.zip`, Buffer.from(download.getPackageContent(), 'base64'));
console.log(`el paquete ${packageId} se ha almacenado`);
}
+import { Service } from '@nodecfdi/sat-ws-descarga-masiva';
import { writeFileSync } from 'fs';
/**
* @var service: Service
* @var packagesIds: string[] El listado de identificadores de paquetes generado en la (correcta) verificación
*/
for (const packageId of packagesIds) {
const download = await service.download(packageId);
if (!download.getStatus().isAccepted()) {
console.log(
`El paquete ${packageId} no se ha podido descargar: ${download.getStatus().getMessage()}`,
);
continue;
}
writeFileSync(`${packageId}.zip`, Buffer.from(download.getPackageContent(), 'base64'));
console.log(`el paquete ${packageId} se ha almacenado`);
}
Lectura de paquetes
Los paquetes de Metadata y CFDI se pueden leer con las clases MetadataPackageReader y CfdiPackageReader respectivamente. Para fabricar los objetos, se pueden usar sus métodos createFromFile para crearlo a partir de un archivo existente o createFromContents para crearlo a partir del contenido del archivo en memoria.
Cada paquete puede contener uno o más archivos internos. Cada paquete se lee individualmente.
-Lectura de paquetes de tipo Metadata
import { MetadataPackageReader, OpenZipFileException } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var zipfile: string contiene la ruta al archivo de paquete de Metadata
*/
let metadataReader: MetadataPackageReader;
// abrir el archivo de Metadata
try {
metadataReader = await MetadataPackageReader.createFromFile(zipFile);
} catch (error) {
const zipError = error as OpenZipFileException;
console.log(zipError.message);
return;
}
for await (const item of metadataReader.metadata()) {
console.log(`${item.get('uuid')} ${item.get('fechaEmision')}`);
}
+Lectura de paquetes de tipo Metadata
import { MetadataPackageReader, OpenZipFileException } from '@nodecfdi/sat-ws-descarga-masiva';
/**
* @var zipfile: string contiene la ruta al archivo de paquete de Metadata
*/
let metadataReader: MetadataPackageReader;
// abrir el archivo de Metadata
try {
metadataReader = await MetadataPackageReader.createFromFile(zipFile);
} catch (error) {
const zipError = error as OpenZipFileException;
console.log(zipError.message);
return;
}
for await (const item of metadataReader.metadata()) {
console.log(`${item.get('uuid')} ${item.get('fechaEmision')}`);
}
-Lectura de paquetes de tipo CFDI
import { CfdiPackageReader, OpenZipFileException } from '@nodecfdi/sat-ws-descarga-masiva';
import { writeFileSync } from 'fs';
/**
* @var zipfile: string contiene la ruta al archivo de paquete de archivos ZIP
*/
let cfdiReader: CfdiPackageReader;
try {
cfdiReader = await CfdiPackageReader.createFromFile(zipFile);
} catch (error) {
const zipError = error as OpenZipFileException;
console.log(zipError.message);
return;
}
for await (const map of cfdiPackageReader.cfdis()) {
for (const [name, content] of map) {
writeFileSync(`cfdis/${name}.xml`, Buffer.from(download.getPackageContent(), 'base64'));
}
}
+Lectura de paquetes de tipo CFDI
import { CfdiPackageReader, OpenZipFileException } from '@nodecfdi/sat-ws-descarga-masiva';
import { writeFileSync } from 'fs';
/**
* @var zipfile: string contiene la ruta al archivo de paquete de archivos ZIP
*/
let cfdiReader: CfdiPackageReader;
try {
cfdiReader = await CfdiPackageReader.createFromFile(zipFile);
} catch (error) {
const zipError = error as OpenZipFileException;
console.log(zipError.message);
return;
}
for await (const map of cfdiPackageReader.cfdis()) {
for (const [name, content] of map) {
writeFileSync(`cfdis/${name}.xml`, Buffer.from(content, 'utf8'));
}
}
Información técnica
La información técnica puede ser leida del siguiente link: CfdiPackageReader facilitada por la librería que inspiró a ésta.
Copyright and License
The nodecfdi/sat-ws-descarga-masiva
library is copyright © NodeCfdi and OcelotlStudio
and licensed for use under the MIT License (MIT). Please see LICENSE for more information.
-
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
The implementors must create the request signed ready to send to the SAT Web Service Descarga Masiva -The information about owner like RFC, certificate, private key, etc. are outside the scope of this interface
-Creates a query signed xml message
-RequestBuilderException
-Generated using TypeDoc
Generated using TypeDoc
Method called before calling the web service
-Method called after calling the web service
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Filter by filename or content contract
+Expected behavior of a PackageReader contract
+The implementors must create the request signed ready to send to the SAT Web Service Descarga Masiva +The information about owner like RFC, certificate, private key, etc. are outside the scope of this interface
+Creates a query signed xml message
+RequestBuilderException
+
Contain functions to interact with XML contents and XML DOM
-This class is internal, do not use it outside this project
-