@ramiidv/arca-mtxca 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ramiidv
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,387 @@
1
+ # @ramiidv/arca-mtxca
2
+
3
+ SDK de TypeScript para el web service WSMTXCA de ARCA (ex AFIP). Facturacion electronica con detalle de articulos (item-level detail: codigos de barras, cantidades, precios unitarios, descripciones por linea).
4
+
5
+ ## Caracteristicas
6
+
7
+ - Zero dependencias SOAP: construye los envelopes SOAP manualmente
8
+ - Zero dependencias HTTP: usa `fetch` nativo (Node 18+)
9
+ - Firma CMS/PKCS#7 con node-forge (via arca-common)
10
+ - ESM only
11
+ - TypeScript estricto con tipos completos
12
+ - Cache automatico de tokens WSAA
13
+ - Reintentos con backoff exponencial
14
+ - Sistema de eventos para monitoreo
15
+
16
+ ## Instalacion
17
+
18
+ ```bash
19
+ npm install @ramiidv/arca-mtxca
20
+ ```
21
+
22
+ ## WSMTXCA vs WSFEv1
23
+
24
+ | Caracteristica | WSFEv1 (`arca-facturacion`) | WSMTXCA (`arca-mtxca`) |
25
+ |---|---|---|
26
+ | Detalle de items | No | Si (codigo, descripcion, cantidad, precio unitario por linea) |
27
+ | Protocolo | SOAP (.NET) | SOAP (Java) |
28
+ | Formato fechas | YYYYMMDD | YYYY-MM-DD |
29
+ | IVA por item | No (subtotales globales) | Si (codigoCondicionIVA + importeIVA por item) |
30
+ | Tipos cbte | A, B, C, E, M, FCE | A, B, M |
31
+ | Uso tipico | Facturas sin detalle de productos | Facturas con detalle de productos (ej: retail, e-commerce) |
32
+
33
+ ## Inicio rapido
34
+
35
+ ```typescript
36
+ import { readFileSync } from 'fs';
37
+ import { ArcaMtxca, CbteTipo, CodigoCondicionIVA } from '@ramiidv/arca-mtxca';
38
+
39
+ const mtxca = new ArcaMtxca({
40
+ cert: readFileSync('./cert.pem', 'utf-8'),
41
+ key: readFileSync('./key.pem', 'utf-8'),
42
+ cuit: 20123456789,
43
+ production: false, // false = homologacion
44
+ });
45
+
46
+ // Autorizar factura B con detalle de articulos
47
+ const result = await mtxca.autorizar({
48
+ ptoVta: 1,
49
+ cbteTipo: CbteTipo.FACTURA_B,
50
+ invoice: {
51
+ concepto: 1, // Productos
52
+ docTipo: 99, // Consumidor Final
53
+ docNro: 0,
54
+ cbteFch: '2026-03-31',
55
+ importeTotal: 121,
56
+ importeGravado: 100,
57
+ importeNoGravado: 0,
58
+ importeExento: 0,
59
+ subtotalesIVA: [
60
+ { codigo: CodigoCondicionIVA.IVA_21, baseImponible: 100, importe: 21 },
61
+ ],
62
+ items: [
63
+ {
64
+ codigo: '7790001000012',
65
+ descripcion: 'Producto de ejemplo',
66
+ cantidad: 2,
67
+ unidadMedida: 7, // unidades
68
+ precioUnitario: 50,
69
+ importeItem: 100,
70
+ codigoCondicionIVA: CodigoCondicionIVA.IVA_21,
71
+ importeIVA: 21,
72
+ },
73
+ ],
74
+ },
75
+ });
76
+
77
+ if (result.resultado === 'A') {
78
+ console.log('CAE:', result.cae);
79
+ console.log('Vencimiento:', result.caeFchVto);
80
+ console.log('Cbte Nro:', result.cbteNro);
81
+ }
82
+ ```
83
+
84
+ ## Configuracion
85
+
86
+ ```typescript
87
+ interface ArcaMtxcaConfig {
88
+ /** Certificado X.509 en formato PEM */
89
+ cert: string;
90
+ /** Clave privada RSA en formato PEM */
91
+ key: string;
92
+ /** CUIT del contribuyente (sin guiones) */
93
+ cuit: number;
94
+ /** Usar endpoints de produccion (default: false) */
95
+ production?: boolean;
96
+ /** Timeout en ms (default: 30000) */
97
+ timeout?: number;
98
+ /** Cantidad de reintentos en errores 5xx/red (default: 1) */
99
+ retries?: number;
100
+ /** Delay base en ms para backoff exponencial (default: 1000) */
101
+ retryDelayMs?: number;
102
+ /** Callback de eventos para monitoreo */
103
+ onEvent?: (event: ArcaEvent) => void;
104
+ }
105
+ ```
106
+
107
+ ## API
108
+
109
+ ### Metodos principales
110
+
111
+ #### `autorizar(request: AutorizarRequest): Promise<MtxcaInvoiceResult>`
112
+
113
+ Autoriza un comprobante con detalle de articulos. Retorna CAE si fue aprobado.
114
+
115
+ ```typescript
116
+ const result = await mtxca.autorizar({
117
+ ptoVta: 1,
118
+ cbteTipo: CbteTipo.FACTURA_A,
119
+ invoice: {
120
+ concepto: 1,
121
+ docTipo: 80, // CUIT
122
+ docNro: 30123456789,
123
+ cbteFch: '2026-03-31',
124
+ importeTotal: 242,
125
+ importeGravado: 200,
126
+ subtotalesIVA: [
127
+ { codigo: CodigoCondicionIVA.IVA_21, baseImponible: 200, importe: 42 },
128
+ ],
129
+ items: [
130
+ {
131
+ codigo: '001',
132
+ descripcion: 'Servicio de consultoria',
133
+ cantidad: 1,
134
+ unidadMedida: 7,
135
+ precioUnitario: 200,
136
+ importeItem: 200,
137
+ codigoCondicionIVA: CodigoCondicionIVA.IVA_21,
138
+ importeIVA: 42,
139
+ },
140
+ ],
141
+ },
142
+ });
143
+ ```
144
+
145
+ #### `ultimoComprobante(ptoVta, cbteTipo): Promise<number>`
146
+
147
+ Ultimo numero de comprobante autorizado.
148
+
149
+ ```typescript
150
+ const ultimo = await mtxca.ultimoComprobante(1, CbteTipo.FACTURA_B);
151
+ ```
152
+
153
+ #### `siguienteComprobante(ptoVta, cbteTipo): Promise<number>`
154
+
155
+ Siguiente numero de comprobante (ultimo + 1).
156
+
157
+ ```typescript
158
+ const siguiente = await mtxca.siguienteComprobante(1, CbteTipo.FACTURA_B);
159
+ ```
160
+
161
+ #### `consultarComprobante(cbteTipo, ptoVta, cbteNro): Promise<MtxcaComprobante>`
162
+
163
+ Consulta un comprobante previamente autorizado, incluyendo el detalle de items.
164
+
165
+ ```typescript
166
+ const comprobante = await mtxca.consultarComprobante(CbteTipo.FACTURA_B, 1, 150);
167
+ console.log(comprobante.items); // Detalle de articulos
168
+ ```
169
+
170
+ #### `status(): Promise<ServerStatus>`
171
+
172
+ Health check del servicio. No requiere autenticacion.
173
+
174
+ ```typescript
175
+ const estado = await mtxca.status();
176
+ console.log(estado.appserver); // "OK"
177
+ ```
178
+
179
+ ### Consulta de parametros
180
+
181
+ ```typescript
182
+ const tiposCbte = await mtxca.getTiposComprobante();
183
+ const tiposDoc = await mtxca.getTiposDocumento();
184
+ const alicuotas = await mtxca.getAlicuotasIVA();
185
+ const condiciones = await mtxca.getCondicionesIVA();
186
+ const monedas = await mtxca.getMonedas();
187
+ const unidades = await mtxca.getUnidadesMedida();
188
+ const ptosVenta = await mtxca.getPuntosVenta();
189
+ const ptosVentaCAE = await mtxca.getPuntosVentaCAE();
190
+ const ptosVentaCAEA = await mtxca.getPuntosVentaCAEA();
191
+ const cotizacion = await mtxca.getCotizacionMoneda('DOL');
192
+ ```
193
+
194
+ ### Acceso a clientes de bajo nivel
195
+
196
+ Para casos avanzados, se pueden usar los clientes individuales directamente:
197
+
198
+ ```typescript
199
+ const mtxca = new ArcaMtxca({ /* ... */ });
200
+
201
+ // Obtener ticket de acceso manualmente
202
+ const ticket = await mtxca.wsaa.getAccessTicket('wsmtxca');
203
+
204
+ const auth = {
205
+ Token: ticket.token,
206
+ Sign: ticket.sign,
207
+ Cuit: 20123456789,
208
+ };
209
+
210
+ // Llamar directamente al servicio
211
+ const result = await mtxca.client.autorizarComprobante(auth, request);
212
+ ```
213
+
214
+ ## Tipos principales
215
+
216
+ ### MtxcaItem
217
+
218
+ ```typescript
219
+ interface MtxcaItem {
220
+ codigo?: string; // Codigo/barcode del producto
221
+ descripcion: string; // Descripcion del producto/servicio
222
+ cantidad: number; // Cantidad
223
+ unidadMedida: number; // Codigo unidad de medida
224
+ precioUnitario: number; // Precio unitario
225
+ importeItem: number; // Importe total del item
226
+ codigoCondicionIVA: number; // Condicion de IVA del item
227
+ importeIVA: number; // Importe de IVA del item
228
+ importeBonificacion?: number; // Descuento
229
+ }
230
+ ```
231
+
232
+ ### MtxcaInvoiceResult
233
+
234
+ ```typescript
235
+ interface MtxcaInvoiceResult {
236
+ resultado: string; // "A" = Aprobado, "R" = Rechazado
237
+ cae?: string; // CAE otorgado
238
+ caeFchVto?: string; // Vencimiento del CAE (YYYY-MM-DD)
239
+ cbteNro: number; // Numero de comprobante
240
+ observaciones: MtxcaObservacion[];
241
+ errores: MtxcaObservacion[];
242
+ }
243
+ ```
244
+
245
+ ### MtxcaComprobante
246
+
247
+ ```typescript
248
+ interface MtxcaComprobante {
249
+ codigoTipoComprobante: number;
250
+ numeroPuntoVenta: number;
251
+ numeroComprobante: number;
252
+ fechaEmision: string;
253
+ codigoTipoDocumento: number;
254
+ numeroDocumento: number;
255
+ importeTotal: number;
256
+ importeNoGravado: number;
257
+ importeGravado: number;
258
+ importeExento: number;
259
+ importeOtrosTributos: number;
260
+ importeSubtotal: number;
261
+ codigoMoneda: string;
262
+ cotizacionMoneda: number;
263
+ resultado: string;
264
+ codigoAutorizacion?: string;
265
+ fechaVencimiento?: string;
266
+ observaciones: MtxcaObservacion[];
267
+ items: MtxcaItem[];
268
+ }
269
+ ```
270
+
271
+ ## Manejo de errores
272
+
273
+ El SDK usa la jerarquia de errores de `@ramiidv/arca-common`:
274
+
275
+ ```
276
+ Error
277
+ └── ArcaError (base)
278
+ ├── ArcaAuthError (errores de WSAA)
279
+ ├── ArcaServiceError (errores de negocio)
280
+ └── ArcaSoapError (errores HTTP/transporte)
281
+ ```
282
+
283
+ ```typescript
284
+ import { ArcaAuthError, ArcaServiceError, ArcaSoapError } from '@ramiidv/arca-mtxca';
285
+
286
+ try {
287
+ await mtxca.autorizar(request);
288
+ } catch (error) {
289
+ if (error instanceof ArcaAuthError) {
290
+ // Certificado vencido, servicio no autorizado, WSAA caido
291
+ console.error('Error de autenticacion:', error.message);
292
+ } else if (error instanceof ArcaServiceError) {
293
+ // Errores de negocio (comprobante rechazado, etc.)
294
+ for (const detalle of error.errors) {
295
+ console.error(`[${detalle.code}] ${detalle.msg}`);
296
+ }
297
+ } else if (error instanceof ArcaSoapError) {
298
+ // Errores HTTP/red
299
+ console.error('Error HTTP:', error.statusCode, error.message);
300
+ }
301
+ }
302
+ ```
303
+
304
+ Ademas, las respuestas de `autorizar()` pueden tener `resultado === 'R'` con observaciones/errores sin lanzar excepcion. Siempre verificar `result.resultado`:
305
+
306
+ ```typescript
307
+ const result = await mtxca.autorizar(request);
308
+ if (result.resultado !== 'A') {
309
+ console.error('Rechazado:', result.errores);
310
+ console.warn('Observaciones:', result.observaciones);
311
+ }
312
+ ```
313
+
314
+ ## Eventos
315
+
316
+ ```typescript
317
+ const mtxca = new ArcaMtxca({
318
+ // ...
319
+ onEvent: (evento) => {
320
+ switch (evento.type) {
321
+ case 'auth:login':
322
+ console.log(`Login para ${evento.service}`);
323
+ break;
324
+ case 'auth:cache-hit':
325
+ console.log(`Token cacheado para ${evento.service}`);
326
+ break;
327
+ case 'request:start':
328
+ console.log(`Inicio ${evento.method}`);
329
+ break;
330
+ case 'request:end':
331
+ console.log(`Fin ${evento.method} (${evento.durationMs}ms)`);
332
+ break;
333
+ case 'request:retry':
334
+ console.log(`Reintento #${evento.attempt}`);
335
+ break;
336
+ case 'request:error':
337
+ console.error(`Error: ${evento.error}`);
338
+ break;
339
+ }
340
+ },
341
+ });
342
+ ```
343
+
344
+ ## Enums utiles
345
+
346
+ ```typescript
347
+ import { CbteTipo, Concepto, CodigoCondicionIVA, Moneda } from '@ramiidv/arca-mtxca';
348
+
349
+ // Tipos de comprobante
350
+ CbteTipo.FACTURA_A // 1
351
+ CbteTipo.NOTA_DEBITO_A // 2
352
+ CbteTipo.NOTA_CREDITO_A // 3
353
+ CbteTipo.FACTURA_B // 6
354
+ CbteTipo.NOTA_DEBITO_B // 7
355
+ CbteTipo.NOTA_CREDITO_B // 8
356
+
357
+ // Concepto
358
+ Concepto.PRODUCTOS // 1
359
+ Concepto.SERVICIOS // 2
360
+ Concepto.PRODUCTOS_Y_SERVICIOS // 3
361
+
362
+ // Condicion IVA del item
363
+ CodigoCondicionIVA.NO_GRAVADO // 1
364
+ CodigoCondicionIVA.EXENTO // 2
365
+ CodigoCondicionIVA.IVA_0 // 3
366
+ CodigoCondicionIVA.IVA_10_5 // 4
367
+ CodigoCondicionIVA.IVA_21 // 5
368
+ CodigoCondicionIVA.IVA_27 // 6
369
+ CodigoCondicionIVA.GRAVADO // 7
370
+ CodigoCondicionIVA.IVA_5 // 8
371
+ CodigoCondicionIVA.IVA_2_5 // 9
372
+
373
+ // Monedas
374
+ Moneda.PESOS // "PES"
375
+ Moneda.DOLARES // "DOL"
376
+ Moneda.EUROS // "060"
377
+ ```
378
+
379
+ ## Requisitos
380
+
381
+ - Node.js >= 18 (soporte nativo de `fetch`)
382
+ - Certificado digital emitido por ARCA/AFIP
383
+ - Autorizacion para el servicio `wsmtxca`
384
+
385
+ ## Licencia
386
+
387
+ MIT
@@ -0,0 +1,99 @@
1
+ import { WsaaClient } from '@ramiidv/arca-common';
2
+ import type { ServerStatus } from '@ramiidv/arca-common';
3
+ import { MtxcaClient } from './mtxca-client.js';
4
+ import type { ArcaMtxcaConfig, AutorizarRequest, MtxcaInvoiceResult, MtxcaComprobante, ParamItem, MonedaItem, UnidadMedidaItem, PtoVentaItem, CotizacionResult } from './types.js';
5
+ /**
6
+ * Main orchestrator class for the WSMTXCA web service.
7
+ *
8
+ * Provides high-level methods that handle WSAA authentication automatically.
9
+ * WSMTXCA is used for electronic invoicing WITH item-level detail (barcodes,
10
+ * quantities, unit prices, product descriptions per line).
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { ArcaMtxca, CbteTipo, CodigoCondicionIVA } from '@ramiidv/arca-mtxca';
15
+ * import { readFileSync } from 'fs';
16
+ *
17
+ * const mtxca = new ArcaMtxca({
18
+ * cert: readFileSync('cert.pem', 'utf-8'),
19
+ * key: readFileSync('key.pem', 'utf-8'),
20
+ * cuit: 20123456789,
21
+ * production: false,
22
+ * });
23
+ *
24
+ * const result = await mtxca.autorizar({
25
+ * ptoVta: 1,
26
+ * cbteTipo: CbteTipo.FACTURA_B,
27
+ * invoice: {
28
+ * concepto: 1,
29
+ * docTipo: 99,
30
+ * docNro: 0,
31
+ * cbteFch: '2026-03-31',
32
+ * importeTotal: 121,
33
+ * items: [{
34
+ * descripcion: 'Producto de ejemplo',
35
+ * cantidad: 1,
36
+ * unidadMedida: 7,
37
+ * precioUnitario: 100,
38
+ * importeItem: 100,
39
+ * codigoCondicionIVA: CodigoCondicionIVA.IVA_21,
40
+ * importeIVA: 21,
41
+ * }],
42
+ * },
43
+ * });
44
+ * ```
45
+ */
46
+ export declare class ArcaMtxca {
47
+ /** Low-level WSAA client for direct access */
48
+ readonly wsaa: WsaaClient;
49
+ /** Low-level MTXCA SOAP client for direct access */
50
+ readonly client: MtxcaClient;
51
+ private readonly cuit;
52
+ private readonly onEvent?;
53
+ constructor(config: ArcaMtxcaConfig);
54
+ private getAuth;
55
+ /**
56
+ * Autoriza un comprobante con detalle de articulos.
57
+ * Obtiene automaticamente el numero de comprobante siguiente.
58
+ */
59
+ autorizar(request: AutorizarRequest): Promise<MtxcaInvoiceResult>;
60
+ /**
61
+ * Ultimo numero de comprobante autorizado para un punto de venta y tipo.
62
+ */
63
+ ultimoComprobante(ptoVta: number, cbteTipo: number): Promise<number>;
64
+ /**
65
+ * Siguiente numero de comprobante (ultimo + 1).
66
+ */
67
+ siguienteComprobante(ptoVta: number, cbteTipo: number): Promise<number>;
68
+ /**
69
+ * Consulta un comprobante previamente autorizado.
70
+ */
71
+ consultarComprobante(cbteTipo: number, ptoVta: number, cbteNro: number): Promise<MtxcaComprobante>;
72
+ /**
73
+ * Health check del servicio WSMTXCA. No requiere autenticacion.
74
+ */
75
+ status(): Promise<ServerStatus>;
76
+ /** Tipos de comprobante disponibles. */
77
+ getTiposComprobante(): Promise<ParamItem[]>;
78
+ /** Tipos de documento disponibles. */
79
+ getTiposDocumento(): Promise<ParamItem[]>;
80
+ /** Alicuotas de IVA disponibles. */
81
+ getAlicuotasIVA(): Promise<ParamItem[]>;
82
+ /** Condiciones de IVA disponibles. */
83
+ getCondicionesIVA(): Promise<ParamItem[]>;
84
+ /** Monedas disponibles. */
85
+ getMonedas(): Promise<MonedaItem[]>;
86
+ /** Unidades de medida disponibles. */
87
+ getUnidadesMedida(): Promise<UnidadMedidaItem[]>;
88
+ /** Puntos de venta habilitados. */
89
+ getPuntosVenta(): Promise<PtoVentaItem[]>;
90
+ /** Puntos de venta habilitados para CAE. */
91
+ getPuntosVentaCAE(): Promise<PtoVentaItem[]>;
92
+ /** Puntos de venta habilitados para CAEA. */
93
+ getPuntosVentaCAEA(): Promise<PtoVentaItem[]>;
94
+ /** Cotizacion de una moneda. */
95
+ getCotizacionMoneda(monedaId: string): Promise<CotizacionResult>;
96
+ /** Invalida el ticket de acceso cacheado. */
97
+ clearAuthCache(): void;
98
+ }
99
+ //# sourceMappingURL=arca-mtxca.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arca-mtxca.d.ts","sourceRoot":"","sources":["../src/arca-mtxca.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,KAAK,EAAa,YAAY,EAAmB,MAAM,sBAAsB,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EACV,eAAe,EAEf,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,qBAAa,SAAS;IACpB,8CAA8C;IAC9C,SAAgB,IAAI,EAAE,UAAU,CAAC;IACjC,oDAAoD;IACpD,SAAgB,MAAM,EAAE,WAAW,CAAC;IAEpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAA6B;gBAE1C,MAAM,EAAE,eAAe;YAgCrB,OAAO;IAarB;;;OAGG;IACG,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAMvE;;OAEG;IACG,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAK1E;;OAEG;IACG,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAK7E;;OAEG;IACG,oBAAoB,CACxB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,gBAAgB,CAAC;IAS5B;;OAEG;IACG,MAAM,IAAI,OAAO,CAAC,YAAY,CAAC;IAQrC,wCAAwC;IAClC,mBAAmB,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAKjD,sCAAsC;IAChC,iBAAiB,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAK/C,oCAAoC;IAC9B,eAAe,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAK7C,sCAAsC;IAChC,iBAAiB,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAK/C,2BAA2B;IACrB,UAAU,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;IAKzC,sCAAsC;IAChC,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAKtD,mCAAmC;IAC7B,cAAc,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAK/C,4CAA4C;IACtC,iBAAiB,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAKlD,6CAA6C;IACvC,kBAAkB,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAKnD,gCAAgC;IAC1B,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAStE,6CAA6C;IAC7C,cAAc,IAAI,IAAI;CAGvB"}
@@ -0,0 +1,191 @@
1
+ import { WsaaClient } from '@ramiidv/arca-common';
2
+ import { MTXCA_SERVICE_ID } from './constants.js';
3
+ import { MtxcaClient } from './mtxca-client.js';
4
+ import { validateAutorizarRequest } from './validation.js';
5
+ /**
6
+ * Main orchestrator class for the WSMTXCA web service.
7
+ *
8
+ * Provides high-level methods that handle WSAA authentication automatically.
9
+ * WSMTXCA is used for electronic invoicing WITH item-level detail (barcodes,
10
+ * quantities, unit prices, product descriptions per line).
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { ArcaMtxca, CbteTipo, CodigoCondicionIVA } from '@ramiidv/arca-mtxca';
15
+ * import { readFileSync } from 'fs';
16
+ *
17
+ * const mtxca = new ArcaMtxca({
18
+ * cert: readFileSync('cert.pem', 'utf-8'),
19
+ * key: readFileSync('key.pem', 'utf-8'),
20
+ * cuit: 20123456789,
21
+ * production: false,
22
+ * });
23
+ *
24
+ * const result = await mtxca.autorizar({
25
+ * ptoVta: 1,
26
+ * cbteTipo: CbteTipo.FACTURA_B,
27
+ * invoice: {
28
+ * concepto: 1,
29
+ * docTipo: 99,
30
+ * docNro: 0,
31
+ * cbteFch: '2026-03-31',
32
+ * importeTotal: 121,
33
+ * items: [{
34
+ * descripcion: 'Producto de ejemplo',
35
+ * cantidad: 1,
36
+ * unidadMedida: 7,
37
+ * precioUnitario: 100,
38
+ * importeItem: 100,
39
+ * codigoCondicionIVA: CodigoCondicionIVA.IVA_21,
40
+ * importeIVA: 21,
41
+ * }],
42
+ * },
43
+ * });
44
+ * ```
45
+ */
46
+ export class ArcaMtxca {
47
+ /** Low-level WSAA client for direct access */
48
+ wsaa;
49
+ /** Low-level MTXCA SOAP client for direct access */
50
+ client;
51
+ cuit;
52
+ onEvent;
53
+ constructor(config) {
54
+ const isProduction = config.production ?? false;
55
+ this.cuit = config.cuit;
56
+ this.onEvent = config.onEvent;
57
+ const soapOptions = {
58
+ timeout: config.timeout,
59
+ retries: config.retries,
60
+ retryDelayMs: config.retryDelayMs,
61
+ };
62
+ this.wsaa = new WsaaClient({
63
+ cert: config.cert,
64
+ key: config.key,
65
+ production: isProduction,
66
+ timeout: config.timeout,
67
+ retries: config.retries,
68
+ retryDelayMs: config.retryDelayMs,
69
+ onEvent: config.onEvent,
70
+ });
71
+ this.client = new MtxcaClient({
72
+ production: isProduction,
73
+ soapOptions,
74
+ onEvent: config.onEvent,
75
+ });
76
+ }
77
+ // =========================================================================
78
+ // Auth helper
79
+ // =========================================================================
80
+ async getAuth() {
81
+ const ticket = await this.wsaa.getAccessTicket(MTXCA_SERVICE_ID);
82
+ return {
83
+ Token: ticket.token,
84
+ Sign: ticket.sign,
85
+ Cuit: this.cuit,
86
+ };
87
+ }
88
+ // =========================================================================
89
+ // Facturacion
90
+ // =========================================================================
91
+ /**
92
+ * Autoriza un comprobante con detalle de articulos.
93
+ * Obtiene automaticamente el numero de comprobante siguiente.
94
+ */
95
+ async autorizar(request) {
96
+ validateAutorizarRequest(request);
97
+ const auth = await this.getAuth();
98
+ return this.client.autorizarComprobante(auth, request);
99
+ }
100
+ /**
101
+ * Ultimo numero de comprobante autorizado para un punto de venta y tipo.
102
+ */
103
+ async ultimoComprobante(ptoVta, cbteTipo) {
104
+ const auth = await this.getAuth();
105
+ return this.client.consultarUltimoComprobanteAutorizado(auth, ptoVta, cbteTipo);
106
+ }
107
+ /**
108
+ * Siguiente numero de comprobante (ultimo + 1).
109
+ */
110
+ async siguienteComprobante(ptoVta, cbteTipo) {
111
+ const ultimo = await this.ultimoComprobante(ptoVta, cbteTipo);
112
+ return ultimo + 1;
113
+ }
114
+ /**
115
+ * Consulta un comprobante previamente autorizado.
116
+ */
117
+ async consultarComprobante(cbteTipo, ptoVta, cbteNro) {
118
+ const auth = await this.getAuth();
119
+ return this.client.consultarComprobante(auth, cbteTipo, ptoVta, cbteNro);
120
+ }
121
+ // =========================================================================
122
+ // Estado del servicio
123
+ // =========================================================================
124
+ /**
125
+ * Health check del servicio WSMTXCA. No requiere autenticacion.
126
+ */
127
+ async status() {
128
+ return this.client.dummy();
129
+ }
130
+ // =========================================================================
131
+ // Parametros
132
+ // =========================================================================
133
+ /** Tipos de comprobante disponibles. */
134
+ async getTiposComprobante() {
135
+ const auth = await this.getAuth();
136
+ return this.client.consultarTiposComprobante(auth);
137
+ }
138
+ /** Tipos de documento disponibles. */
139
+ async getTiposDocumento() {
140
+ const auth = await this.getAuth();
141
+ return this.client.consultarTiposDocumento(auth);
142
+ }
143
+ /** Alicuotas de IVA disponibles. */
144
+ async getAlicuotasIVA() {
145
+ const auth = await this.getAuth();
146
+ return this.client.consultarAlicuotasIVA(auth);
147
+ }
148
+ /** Condiciones de IVA disponibles. */
149
+ async getCondicionesIVA() {
150
+ const auth = await this.getAuth();
151
+ return this.client.consultarCondicionesIVA(auth);
152
+ }
153
+ /** Monedas disponibles. */
154
+ async getMonedas() {
155
+ const auth = await this.getAuth();
156
+ return this.client.consultarMonedas(auth);
157
+ }
158
+ /** Unidades de medida disponibles. */
159
+ async getUnidadesMedida() {
160
+ const auth = await this.getAuth();
161
+ return this.client.consultarUnidadesMedida(auth);
162
+ }
163
+ /** Puntos de venta habilitados. */
164
+ async getPuntosVenta() {
165
+ const auth = await this.getAuth();
166
+ return this.client.consultarPuntosVenta(auth);
167
+ }
168
+ /** Puntos de venta habilitados para CAE. */
169
+ async getPuntosVentaCAE() {
170
+ const auth = await this.getAuth();
171
+ return this.client.consultarPuntosVentaCAE(auth);
172
+ }
173
+ /** Puntos de venta habilitados para CAEA. */
174
+ async getPuntosVentaCAEA() {
175
+ const auth = await this.getAuth();
176
+ return this.client.consultarPuntosVentaCAEA(auth);
177
+ }
178
+ /** Cotizacion de una moneda. */
179
+ async getCotizacionMoneda(monedaId) {
180
+ const auth = await this.getAuth();
181
+ return this.client.consultarCotizacionMoneda(auth, monedaId);
182
+ }
183
+ // =========================================================================
184
+ // Cache management
185
+ // =========================================================================
186
+ /** Invalida el ticket de acceso cacheado. */
187
+ clearAuthCache() {
188
+ this.wsaa.clearTicket(MTXCA_SERVICE_ID);
189
+ }
190
+ }
191
+ //# sourceMappingURL=arca-mtxca.js.map