facturas 0.6.1 → 0.7.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/dist/wsfe.mjs CHANGED
@@ -1,1032 +1,14 @@
1
- // src/errors.ts
2
- var ArcaError = class extends Error {
3
- code;
4
- name = "ArcaError";
5
- constructor(message, code = "ARCA_ERROR", options) {
6
- super(message, options);
7
- this.code = code;
8
- }
9
- };
10
- var ArcaInputError = class extends ArcaError {
11
- name = "ArcaInputError";
12
- detail;
13
- constructor(message, options) {
14
- super(message, "ARCA_INPUT_ERROR", options);
15
- this.detail = options?.detail;
16
- }
17
- };
18
- var ArcaTransportError = class extends ArcaError {
19
- name = "ArcaTransportError";
20
- statusCode;
21
- contentType;
22
- responseBody;
23
- constructor(message, options) {
24
- super(message, "ARCA_TRANSPORT_ERROR", options);
25
- this.statusCode = options?.statusCode;
26
- this.contentType = options?.contentType;
27
- this.responseBody = options?.responseBody;
28
- }
29
- };
30
- var ArcaSoapFaultError = class extends ArcaError {
31
- name = "ArcaSoapFaultError";
32
- faultCode;
33
- detail;
34
- constructor(message, options) {
35
- super(message, "ARCA_SOAP_FAULT", options);
36
- this.faultCode = options?.faultCode;
37
- this.detail = options?.detail;
38
- }
39
- };
40
- var ArcaInvalidSoapResponseError = class extends ArcaError {
41
- name = "ArcaInvalidSoapResponseError";
42
- service;
43
- operation;
44
- endpointUrl;
45
- statusCode;
46
- contentType;
47
- responseBodyLength;
48
- responseBodyPreview;
49
- parsedDetail;
50
- constructor(message, options) {
51
- super(message, "ARCA_INVALID_SOAP_RESPONSE", options);
52
- this.service = options?.service;
53
- this.operation = options?.operation;
54
- this.endpointUrl = options?.endpointUrl;
55
- this.statusCode = options?.statusCode;
56
- this.contentType = options?.contentType;
57
- this.responseBodyLength = options?.responseBodyLength;
58
- this.responseBodyPreview = options?.responseBodyPreview;
59
- this.parsedDetail = options?.parsedDetail;
60
- }
61
- };
62
- var ArcaServiceError = class extends ArcaError {
63
- name = "ArcaServiceError";
64
- serviceCode;
65
- service;
66
- operation;
67
- result;
68
- resultLevel;
69
- results;
70
- cae;
71
- issues;
72
- detail;
73
- constructor(message, options) {
74
- super(message, "ARCA_SERVICE_ERROR", options);
75
- this.serviceCode = options?.serviceCode;
76
- this.service = options?.service;
77
- this.operation = options?.operation;
78
- this.result = options?.result;
79
- this.resultLevel = options?.resultLevel;
80
- this.results = options?.results;
81
- this.cae = options?.cae;
82
- this.issues = options?.issues;
83
- this.detail = options?.detail;
84
- }
85
- };
86
-
87
- // src/services/wsfe.ts
88
- function createWsfeService(options) {
89
- async function executeWsfeAuthenticatedRawOperation(operation, input, body = {}, retries) {
90
- const auth = await options.auth.login("wsfe", {
91
- representedTaxId: input.representedTaxId,
92
- forceRefresh: input.forceRefresh
93
- });
94
- const response = await options.soap.execute({
95
- service: "wsfe",
96
- operation,
97
- ...retries === void 0 ? {} : { retries },
98
- body: {
99
- Auth: createWsfeAuth(
100
- input.representedTaxId ?? options.config.taxId,
101
- auth.token,
102
- auth.sign
103
- ),
104
- ...body
105
- }
106
- });
107
- return unwrapWsfeOperationEnvelope(operation, response.result);
108
- }
109
- async function executeWsfeAuthenticatedOperation(operation, input, body = {}) {
110
- const result = await executeWsfeAuthenticatedRawOperation(
111
- operation,
112
- input,
113
- body
114
- );
115
- throwForWsfeOperationErrors(operation, result);
116
- return result;
117
- }
118
- async function executeWsfeOperation(operation, body = {}) {
119
- const response = await options.soap.execute({
120
- service: "wsfe",
121
- operation,
122
- body
123
- });
124
- const result = unwrapWsfeOperationEnvelope(operation, response.result);
125
- throwForWsfeOperationErrors(operation, result);
126
- return result;
127
- }
128
- async function getNextVoucherNumber({
129
- representedTaxId,
130
- salesPoint,
131
- voucherType,
132
- forceRefresh
133
- }) {
134
- const result = await executeWsfeAuthenticatedOperation(
135
- "FECompUltimoAutorizado",
136
- {
137
- representedTaxId,
138
- forceRefresh
139
- },
140
- {
141
- PtoVta: salesPoint,
142
- CbteTipo: voucherType
143
- }
144
- );
145
- return Number(result.CbteNro ?? 0) + 1;
146
- }
147
- async function getWsfeCatalog(operation, resultKey, input) {
148
- const result = await executeWsfeAuthenticatedOperation(operation, {
149
- representedTaxId: input.representedTaxId,
150
- forceRefresh: input.forceRefresh
151
- });
152
- return getWsfeResultEntries(result, resultKey).map(mapWsfeCatalogEntry);
153
- }
154
- function authorizeVoucher({
155
- representedTaxId,
156
- data,
157
- voucherNumber,
158
- forceRefresh
159
- }) {
160
- const normalizedInput = normalizeWsfeVoucherInput(data);
161
- return authorizeNormalizedVoucher({
162
- representedTaxId,
163
- data: normalizedInput,
164
- voucherNumber,
165
- forceRefresh
166
- });
167
- }
168
- function authorizeVoucherOutcome({
169
- representedTaxId,
170
- data,
171
- voucherNumber,
172
- forceRefresh
173
- }) {
174
- const normalizedInput = normalizeWsfeVoucherInput(data);
175
- return executeWsfeAuthorization({
176
- representedTaxId,
177
- data: normalizedInput,
178
- voucherNumber,
179
- forceRefresh
180
- }).then(({ outcome }) => outcome);
181
- }
182
- async function authorizeNormalizedVoucher({
183
- representedTaxId,
184
- data: normalizedInput,
185
- voucherNumber,
186
- forceRefresh
187
- }) {
188
- const execution = await executeWsfeAuthorization({
189
- representedTaxId,
190
- data: normalizedInput,
191
- voucherNumber,
192
- forceRefresh
193
- });
194
- if (execution.error) {
195
- throw execution.error;
196
- }
197
- if (execution.outcome.kind !== "authorized") {
198
- throw createWsfeOutcomeError(execution.outcome);
199
- }
200
- const { cae, caeExpiry, raw } = execution.outcome;
201
- if (!(caeExpiry && raw)) {
202
- throw new ArcaServiceError("WSFE did not return CAE authorization data", {
203
- service: "wsfe",
204
- operation: "FECAESolicitar",
205
- result: execution.outcome.result,
206
- resultLevel: execution.outcome.resultLevel,
207
- results: execution.outcome.results,
208
- cae,
209
- issues: [
210
- ...execution.outcome.errors,
211
- ...execution.outcome.observations
212
- ],
213
- detail: raw
214
- });
215
- }
216
- return {
217
- cae,
218
- caeExpiry,
219
- voucherNumber,
220
- raw
221
- };
222
- }
223
- async function executeWsfeAuthorization({
224
- representedTaxId,
225
- data: normalizedInput,
226
- voucherNumber,
227
- forceRefresh
228
- }) {
229
- const requestData = mapWsfeVoucherInput(normalizedInput, voucherNumber);
230
- try {
231
- const result = await executeWsfeAuthenticatedRawOperation(
232
- "FECAESolicitar",
233
- { representedTaxId, forceRefresh },
234
- {
235
- FeCAEReq: {
236
- FeCabReq: {
237
- CantReg: 1,
238
- PtoVta: normalizedInput.salesPoint,
239
- CbteTipo: normalizedInput.voucherType
240
- },
241
- FeDetReq: {
242
- FECAEDetRequest: requestData
243
- }
244
- }
245
- },
246
- 0
247
- );
248
- return {
249
- outcome: classifyWsfeAuthorization(result, voucherNumber)
250
- };
251
- } catch (error) {
252
- return {
253
- outcome: createWsfeIndeterminateOutcome(error),
254
- error
255
- };
256
- }
257
- }
258
- async function lookupVoucher({
259
- representedTaxId,
260
- number,
261
- salesPoint,
262
- voucherType,
263
- forceRefresh
264
- }) {
265
- const operation = "FECompConsultar";
266
- const result = await executeWsfeAuthenticatedRawOperation(
267
- operation,
268
- { representedTaxId, forceRefresh },
269
- {
270
- FeCompConsReq: {
271
- CbteNro: number,
272
- PtoVta: salesPoint,
273
- CbteTipo: voucherType
274
- }
275
- }
276
- );
277
- const errors = extractWsfeGlobalIssues(result, operation);
278
- if (errors.length > 0 && errors.every((issue) => issue.code === "602")) {
279
- return {
280
- kind: "not_found",
281
- service: "wsfe",
282
- operation,
283
- errors,
284
- observations: [],
285
- raw: result
286
- };
287
- }
288
- if (errors.length > 0) {
289
- throw createWsfeServiceError(operation, result, errors);
290
- }
291
- const raw = toWsfeRecord(result.ResultGet);
292
- if (!raw) {
293
- throw new ArcaServiceError("WSFE did not return the consulted voucher", {
294
- service: "wsfe",
295
- operation,
296
- detail: result
297
- });
298
- }
299
- return {
300
- kind: "found",
301
- service: "wsfe",
302
- operation,
303
- voucher: mapWsfeVoucherInfo(raw),
304
- observations: [],
305
- raw: result
306
- };
307
- }
308
- return {
309
- authorizeVoucherOutcome,
310
- authorizeVoucher,
311
- async createNextVoucher({ representedTaxId, data, forceRefresh }) {
312
- const normalizedInput = normalizeWsfeVoucherInput(data);
313
- const voucherNumber = await getNextVoucherNumber({
314
- representedTaxId,
315
- salesPoint: normalizedInput.salesPoint,
316
- voucherType: normalizedInput.voucherType,
317
- forceRefresh
318
- });
319
- return authorizeNormalizedVoucher({
320
- representedTaxId,
321
- data: normalizedInput,
322
- voucherNumber
323
- });
324
- },
325
- getNextVoucherNumber,
326
- getLastVoucher(input) {
327
- return getNextVoucherNumber(input);
328
- },
329
- async getSalesPoints({ representedTaxId, forceRefresh }) {
330
- const result = await executeWsfeAuthenticatedOperation(
331
- "FEParamGetPtosVenta",
332
- {
333
- representedTaxId,
334
- forceRefresh
335
- }
336
- );
337
- const rawPoints = result.ResultGet?.PtoVenta;
338
- if (!rawPoints) {
339
- return [];
340
- }
341
- const entries = Array.isArray(rawPoints) ? rawPoints : [rawPoints];
342
- return entries.map(mapWsfeSalesPoint);
343
- },
344
- getVoucherTypes(input) {
345
- return getWsfeCatalog("FEParamGetTiposCbte", "CbteTipo", input);
346
- },
347
- getDocumentTypes(input) {
348
- return getWsfeCatalog("FEParamGetTiposDoc", "DocTipo", input);
349
- },
350
- getConceptTypes(input) {
351
- return getWsfeCatalog("FEParamGetTiposConcepto", "ConceptoTipo", input);
352
- },
353
- async getCurrencyTypes({ representedTaxId, forceRefresh }) {
354
- const result = await executeWsfeAuthenticatedOperation(
355
- "FEParamGetTiposMonedas",
356
- {
357
- representedTaxId,
358
- forceRefresh
359
- }
360
- );
361
- return getWsfeResultEntries(result, "Moneda").map(mapWsfeCurrencyType);
362
- },
363
- getVatRates(input) {
364
- return getWsfeCatalog("FEParamGetTiposIva", "IvaTipo", input);
365
- },
366
- getTaxTypes(input) {
367
- return getWsfeCatalog("FEParamGetTiposTributos", "TributoTipo", input);
368
- },
369
- getOptionalTypes(input) {
370
- return getWsfeCatalog("FEParamGetTiposOpcional", "OpcionalTipo", input);
371
- },
372
- async getActivities({ representedTaxId, forceRefresh }) {
373
- const result = await executeWsfeAuthenticatedOperation(
374
- "FEParamGetActividades",
375
- {
376
- representedTaxId,
377
- forceRefresh
378
- }
379
- );
380
- return getWsfeResultEntries(result, "ActividadesTipo").map(
381
- mapWsfeActivityType
382
- );
383
- },
384
- async getReceiverVatConditions({
385
- representedTaxId,
386
- voucherClass,
387
- forceRefresh
388
- }) {
389
- const result = await executeWsfeAuthenticatedOperation(
390
- "FEParamGetCondicionIvaReceptor",
391
- {
392
- representedTaxId,
393
- forceRefresh
394
- },
395
- {
396
- ...voucherClass === void 0 ? {} : { ClaseCmp: voucherClass }
397
- }
398
- );
399
- return getWsfeResultEntries(result, "CondicionIvaReceptor").map(
400
- mapWsfeReceiverVatCondition
401
- );
402
- },
403
- async getServerStatus() {
404
- const result = await executeWsfeOperation("FEDummy");
405
- return mapWsfeServerStatus(result);
406
- },
407
- async getQuotation({ currencyId, representedTaxId, forceRefresh }) {
408
- const result = await executeWsfeAuthenticatedOperation(
409
- "FEParamGetCotizacion",
410
- {
411
- representedTaxId,
412
- forceRefresh
413
- },
414
- {
415
- MonId: currencyId
416
- }
417
- );
418
- const raw = result.ResultGet ?? {};
419
- return mapWsfeQuotation(raw);
420
- },
421
- async getVoucherInfo(input) {
422
- const lookup = await lookupVoucher(input);
423
- return lookup.kind === "found" ? lookup.voucher : null;
424
- },
425
- lookupVoucher
426
- };
427
- }
428
- function mapWsfeVoucherInput(input, voucherNumber) {
429
- const data = {
430
- Concepto: input.concept,
431
- DocTipo: input.documentType,
432
- DocNro: input.documentNumber,
433
- CbteDesde: voucherNumber,
434
- CbteHasta: voucherNumber,
435
- CbteFch: input.voucherDate,
436
- ImpTotal: input.totalAmount,
437
- ImpTotConc: input.nonTaxableAmount,
438
- ImpNeto: input.netAmount,
439
- ImpOpEx: input.exemptAmount,
440
- ImpTrib: input.taxAmount,
441
- ImpIVA: input.vatAmount,
442
- MonId: input.currencyId,
443
- PtoVta: input.salesPoint,
444
- CbteTipo: input.voucherType
445
- };
446
- if (input.exchangeRate !== void 0) {
447
- data.MonCotiz = input.exchangeRate;
448
- }
449
- if (input.receiverVatConditionId !== void 0) {
450
- data.CondicionIVAReceptorId = input.receiverVatConditionId;
451
- }
452
- if (input.currencyId !== "PES" && input.sameCurrencyForeignCancellation !== void 0) {
453
- data.CanMisMonExt = input.sameCurrencyForeignCancellation;
454
- }
455
- if (input.serviceStartDate !== void 0) {
456
- data.FchServDesde = input.serviceStartDate;
457
- }
458
- if (input.serviceEndDate !== void 0) {
459
- data.FchServHasta = input.serviceEndDate;
460
- }
461
- if (input.paymentDueDate !== void 0) {
462
- data.FchVtoPago = input.paymentDueDate;
463
- }
464
- if (input.associatedVouchers) {
465
- data.CbtesAsoc = {
466
- CbteAsoc: input.associatedVouchers.map((v) => ({
467
- Tipo: v.type,
468
- PtoVta: v.salesPoint,
469
- Nro: v.number,
470
- ...v.taxId === void 0 ? {} : { Cuit: v.taxId },
471
- ...v.voucherDate === void 0 ? {} : { CbteFch: v.voucherDate }
472
- }))
473
- };
474
- }
475
- if (input.associatedPeriod) {
476
- data.PeriodoAsoc = {
477
- FchDesde: input.associatedPeriod.startDate,
478
- FchHasta: input.associatedPeriod.endDate
479
- };
480
- }
481
- if (input.taxes) {
482
- data.Tributos = {
483
- Tributo: input.taxes.map((t) => ({
484
- Id: t.id,
485
- ...t.description === void 0 ? {} : { Desc: t.description },
486
- BaseImp: t.baseAmount,
487
- Alic: t.rate,
488
- Importe: t.amount
489
- }))
490
- };
491
- }
492
- if (input.vatRates) {
493
- data.Iva = {
494
- AlicIva: input.vatRates.map((v) => ({
495
- Id: v.id,
496
- BaseImp: v.baseAmount,
497
- Importe: v.amount
498
- }))
499
- };
500
- }
501
- if (input.optionalFields) {
502
- data.Opcionales = {
503
- Opcional: input.optionalFields.map((o) => ({
504
- Id: o.id,
505
- Valor: o.value
506
- }))
507
- };
508
- }
509
- if (input.buyers) {
510
- data.Compradores = {
511
- Comprador: input.buyers.map((b) => ({
512
- DocTipo: b.documentType,
513
- DocNro: b.documentNumber,
514
- Porcentaje: b.percentage
515
- }))
516
- };
517
- }
518
- if (input.activities) {
519
- data.Actividades = {
520
- Actividad: input.activities.map((a) => ({
521
- Id: a.id
522
- }))
523
- };
524
- }
525
- return data;
526
- }
527
- function normalizeWsfeVoucherInput(input) {
528
- const {
529
- voucherDate,
530
- exchangeRate,
531
- serviceStartDate,
532
- serviceEndDate,
533
- paymentDueDate,
534
- associatedVouchers,
535
- associatedPeriod,
536
- ...rest
537
- } = input;
538
- const normalizedExchangeRate = normalizeWsfeExchangeRate(input, exchangeRate);
539
- return {
540
- ...rest,
541
- voucherDate: normalizeWsfeDateInput(voucherDate, "voucherDate"),
542
- ...normalizedExchangeRate === void 0 ? {} : { exchangeRate: normalizedExchangeRate },
543
- ...serviceStartDate === void 0 ? {} : {
544
- serviceStartDate: normalizeWsfeDateInput(
545
- serviceStartDate,
546
- "serviceStartDate"
547
- )
548
- },
549
- ...serviceEndDate === void 0 ? {} : {
550
- serviceEndDate: normalizeWsfeDateInput(
551
- serviceEndDate,
552
- "serviceEndDate"
553
- )
554
- },
555
- ...paymentDueDate === void 0 ? {} : {
556
- paymentDueDate: normalizeWsfeDateInput(
557
- paymentDueDate,
558
- "paymentDueDate"
559
- )
560
- },
561
- ...associatedVouchers === void 0 ? {} : {
562
- associatedVouchers: associatedVouchers.map((voucher, index) => {
563
- const { voucherDate: associatedVoucherDate, ...associatedRest } = voucher;
564
- return {
565
- ...associatedRest,
566
- ...associatedVoucherDate === void 0 ? {} : {
567
- voucherDate: normalizeWsfeDateInput(
568
- associatedVoucherDate,
569
- `associatedVouchers[${index}].voucherDate`
570
- )
571
- }
572
- };
573
- })
574
- },
575
- ...associatedPeriod === void 0 ? {} : {
576
- associatedPeriod: {
577
- startDate: normalizeWsfeDateInput(
578
- associatedPeriod.startDate,
579
- "associatedPeriod.startDate"
580
- ),
581
- endDate: normalizeWsfeDateInput(
582
- associatedPeriod.endDate,
583
- "associatedPeriod.endDate"
584
- )
585
- }
586
- }
587
- };
588
- }
589
- function normalizeWsfeExchangeRate(input, exchangeRate) {
590
- if (input.currencyId === "PES") {
591
- if (exchangeRate !== void 0 && exchangeRate !== 1) {
592
- throw new ArcaInputError(
593
- "exchangeRate must be 1 when currencyId is PES."
594
- );
595
- }
596
- return 1;
597
- }
598
- if (exchangeRate === void 0) {
599
- if (input.sameCurrencyForeignCancellation === "S") {
600
- return void 0;
601
- }
602
- throw new ArcaInputError(
603
- "exchangeRate is required unless sameCurrencyForeignCancellation is S for a foreign-currency voucher."
604
- );
605
- }
606
- if (!(Number.isFinite(exchangeRate) && exchangeRate > 0)) {
607
- throw new ArcaInputError(
608
- "exchangeRate must be a positive finite number for a foreign-currency voucher."
609
- );
610
- }
611
- return exchangeRate;
612
- }
613
- function normalizeWsfeDateInput(value, fieldName) {
614
- if (typeof value !== "string") {
615
- throw new ArcaInputError(
616
- `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,
617
- {
618
- detail: { field: fieldName, value }
619
- }
620
- );
621
- }
622
- const normalizedValue = value.trim();
623
- const afipMatch = normalizedValue.match(/^(\d{4})(\d{2})(\d{2})$/);
624
- if (afipMatch) {
625
- const [, year, month, day] = afipMatch;
626
- assertValidCalendarDate(year, month, day, fieldName, normalizedValue);
627
- return normalizedValue;
628
- }
629
- const isoMatch = normalizedValue.match(/^(\d{4})-(\d{2})-(\d{2})$/);
630
- if (isoMatch) {
631
- const [, year, month, day] = isoMatch;
632
- assertValidCalendarDate(year, month, day, fieldName, normalizedValue);
633
- return `${year}${month}${day}`;
634
- }
635
- throw new ArcaInputError(
636
- `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,
637
- {
638
- detail: { field: fieldName, value: normalizedValue }
639
- }
640
- );
641
- }
642
- function assertValidCalendarDate(yearInput, monthInput, dayInput, fieldName, value) {
643
- const year = Number(yearInput);
644
- const month = Number(monthInput);
645
- const day = Number(dayInput);
646
- const candidate = new Date(Date.UTC(year, month - 1, day));
647
- if (candidate.getUTCFullYear() !== year || candidate.getUTCMonth() !== month - 1 || candidate.getUTCDate() !== day) {
648
- throw new ArcaInputError(
649
- `Invalid WSFE ${fieldName}: received a non-existent calendar date`,
650
- {
651
- detail: { field: fieldName, value }
652
- }
653
- );
654
- }
655
- }
656
- function mapWsfeSalesPoint(raw) {
657
- const record = raw;
658
- return {
659
- number: Number(record.Nro ?? 0),
660
- ...record.EmisionTipo === void 0 ? {} : { emissionType: String(record.EmisionTipo) },
661
- ...record.Bloqueado === void 0 ? {} : { blocked: String(record.Bloqueado) },
662
- ...record.FchBaja === void 0 ? {} : { deletedSince: String(record.FchBaja) }
663
- };
664
- }
665
- function mapWsfeCatalogEntry(raw) {
666
- const record = raw;
667
- return {
668
- id: Number(record.Id ?? 0),
669
- description: String(record.Desc ?? "")
670
- };
671
- }
672
- function mapWsfeActivityType(raw) {
673
- const record = raw;
674
- return {
675
- id: Number(record.Id ?? 0),
676
- description: String(record.Desc ?? ""),
677
- order: Number(record.Orden ?? 0)
678
- };
679
- }
680
- function mapWsfeReceiverVatCondition(raw) {
681
- const record = raw;
682
- return {
683
- id: Number(record.Id ?? 0),
684
- description: String(record.Desc ?? ""),
685
- voucherClass: String(record.Cmp_Clase ?? "")
686
- };
687
- }
688
- function mapWsfeCurrencyType(raw) {
689
- const record = raw;
690
- return {
691
- id: String(record.Id ?? ""),
692
- description: String(record.Desc ?? ""),
693
- validFrom: String(record.FchDesde ?? ""),
694
- validTo: String(record.FchHasta ?? "")
695
- };
696
- }
697
- function mapWsfeServerStatus(raw) {
698
- return {
699
- appServer: String(raw.AppServer ?? ""),
700
- dbServer: String(raw.DbServer ?? ""),
701
- authServer: String(raw.AuthServer ?? "")
702
- };
703
- }
704
- function mapWsfeQuotation(raw) {
705
- return {
706
- currencyId: String(raw.MonId ?? ""),
707
- rate: Number(raw.MonCotiz ?? 0),
708
- date: String(raw.FchCotiz ?? "")
709
- };
710
- }
711
- function mapWsfeVoucherInfo(raw) {
712
- const voucher = {
713
- voucherNumber: Number(raw.CbteDesde ?? raw.CbteHasta ?? 0),
714
- raw
715
- };
716
- assignWsfeValue(voucher, "voucherDate", normalizeWsfeString(raw.CbteFch));
717
- assignWsfeValue(voucher, "salesPoint", normalizeWsfeNumber(raw.PtoVta));
718
- assignWsfeValue(voucher, "voucherType", normalizeWsfeNumber(raw.CbteTipo));
719
- assignWsfeValue(voucher, "concept", normalizeWsfeNumber(raw.Concepto));
720
- assignWsfeValue(voucher, "documentType", normalizeWsfeNumber(raw.DocTipo));
721
- assignWsfeValue(voucher, "documentNumber", normalizeWsfeString(raw.DocNro));
722
- assignWsfeValue(
723
- voucher,
724
- "receiverVatConditionId",
725
- normalizeWsfeNumber(raw.CondicionIVAReceptorId)
726
- );
727
- assignWsfeValue(voucher, "totalAmount", normalizeWsfeNumber(raw.ImpTotal));
728
- assignWsfeValue(
729
- voucher,
730
- "nonTaxableAmount",
731
- normalizeWsfeNumber(raw.ImpTotConc)
732
- );
733
- assignWsfeValue(voucher, "netAmount", normalizeWsfeNumber(raw.ImpNeto));
734
- assignWsfeValue(voucher, "exemptAmount", normalizeWsfeNumber(raw.ImpOpEx));
735
- assignWsfeValue(voucher, "taxAmount", normalizeWsfeNumber(raw.ImpTrib));
736
- assignWsfeValue(voucher, "vatAmount", normalizeWsfeNumber(raw.ImpIVA));
737
- assignWsfeValue(voucher, "currencyId", normalizeWsfeString(raw.MonId));
738
- assignWsfeValue(voucher, "exchangeRate", normalizeWsfeNumber(raw.MonCotiz));
739
- assignWsfeValue(voucher, "result", normalizeWsfeString(raw.Resultado));
740
- assignWsfeValue(
741
- voucher,
742
- "cae",
743
- normalizeWsfeString(raw.CodAutorizacion ?? raw.CAE)
744
- );
745
- assignWsfeValue(
746
- voucher,
747
- "caeExpiry",
748
- normalizeWsfeString(raw.FchVto ?? raw.CAEFchVto)
749
- );
750
- return voucher;
751
- }
752
- function createWsfeAuth(representedTaxId, token, sign) {
753
- return {
754
- Token: token,
755
- Sign: sign,
756
- Cuit: Number.parseInt(String(representedTaxId), 10)
757
- };
758
- }
759
- function unwrapWsfeOperationEnvelope(operation, response) {
760
- const operationResponse = response[`${operation}Response`];
761
- const result = operationResponse?.[`${operation}Result`] ?? response[`${operation}Result`] ?? response;
762
- return result;
763
- }
764
- function throwForWsfeOperationErrors(operation, result) {
765
- const errors = extractWsfeGlobalIssues(result, operation);
766
- if (errors.length > 0) {
767
- throw createWsfeServiceError(operation, result, errors);
768
- }
769
- }
770
- function normalizeWsfeDetailResponse(result) {
771
- const detailResponse = result.FeDetResp;
772
- const rawDetail = detailResponse?.FECAEDetResponse;
773
- if (Array.isArray(rawDetail)) {
774
- return rawDetail[0] ?? {};
775
- }
776
- return rawDetail ?? {};
777
- }
778
- function classifyWsfeAuthorization(result, voucherNumber) {
779
- const operation = "FECAESolicitar";
780
- const header = toWsfeRecord(result.FeCabResp) ?? {};
781
- const detail = normalizeWsfeDetailResponse(result);
782
- const headerResult = normalizeWsfeResult(header.Resultado);
783
- const detailResult = normalizeWsfeResult(detail.Resultado);
784
- const resultCode = detailResult ?? headerResult;
785
- const resultLevel = getWsfeResultLevel(headerResult, detailResult);
786
- const cae = normalizeWsfeString(detail.CAE);
787
- const caeExpiry = normalizeWsfeString(detail.CAEFchVto);
788
- const errors = extractWsfeGlobalIssues(result, operation, "header");
789
- const observations = extractWsfeObservations(
790
- detail,
791
- detailResult === "R" ? "business" : "observation"
792
- );
793
- const hasInfrastructureError = errors.some(
794
- (issue) => issue.category === "infrastructure"
795
- );
796
- const base = {
797
- service: "wsfe",
798
- operation,
799
- results: createWsfeResults(headerResult, detailResult),
800
- errors,
801
- observations,
802
- raw: result
803
- };
804
- const context = {
805
- base,
806
- headerResult,
807
- detailResult,
808
- resultCode,
809
- resultLevel,
810
- cae,
811
- caeExpiry
812
- };
813
- if (hasContradictoryWsfeResults(context)) {
814
- return createWsfeStructuredIndeterminate(context, "contradictory_response");
815
- }
816
- if (hasInfrastructureError) {
817
- return createWsfeStructuredIndeterminate(context, "incomplete_response");
818
- }
819
- if (isAuthorizedWsfeContext(context)) {
820
- return {
821
- ...base,
822
- kind: "authorized",
823
- result: "A",
824
- resultLevel: "detail",
825
- cae: context.cae,
826
- caeExpiry: context.caeExpiry,
827
- voucherNumber
828
- };
829
- }
830
- if (isRejectedWsfeDetailContext(context)) {
831
- return {
832
- ...base,
833
- kind: "rejected",
834
- result: "R",
835
- resultLevel: "detail"
836
- };
837
- }
838
- if (isRejectedWsfeHeaderContext(context)) {
839
- return {
840
- ...base,
841
- kind: "rejected",
842
- result: "R",
843
- resultLevel: "header"
844
- };
845
- }
846
- return createWsfeStructuredIndeterminate(
847
- context,
848
- hasWsfeCaeContradiction(context) ? "contradictory_response" : "incomplete_response"
849
- );
850
- }
851
- function getWsfeResultLevel(headerResult, detailResult) {
852
- if (detailResult) {
853
- return "detail";
854
- }
855
- return headerResult ? "header" : void 0;
856
- }
857
- function hasContradictoryWsfeResults(context) {
858
- return Boolean(
859
- context.headerResult && context.detailResult && context.headerResult !== context.detailResult
860
- );
861
- }
862
- function isAuthorizedWsfeContext(context) {
863
- return Boolean(
864
- context.detailResult === "A" && context.headerResult !== "R" && context.base.errors.length === 0 && context.cae && context.caeExpiry
865
- );
866
- }
867
- function isRejectedWsfeDetailContext(context) {
868
- return context.detailResult === "R" && context.headerResult !== "A" && !context.cae;
869
- }
870
- function isRejectedWsfeHeaderContext(context) {
871
- return context.headerResult === "R" && context.detailResult === void 0 && !context.cae && context.base.errors.length > 0 && context.base.errors.every((issue) => issue.category === "business");
872
- }
873
- function hasWsfeCaeContradiction(context) {
874
- return (context.resultCode === "A" || context.resultCode === "R") && Boolean(context.cae);
875
- }
876
- function createWsfeStructuredIndeterminate(context, reason) {
877
- const outcome = {
878
- ...context.base,
879
- kind: "indeterminate",
880
- reason
881
- };
882
- assignWsfeValue(outcome, "result", context.resultCode);
883
- assignWsfeValue(outcome, "resultLevel", context.resultLevel);
884
- assignWsfeValue(outcome, "cae", context.cae);
885
- assignWsfeValue(outcome, "caeExpiry", context.caeExpiry);
886
- return outcome;
887
- }
888
- function createWsfeResults(headerResult, detailResult) {
889
- const results = {};
890
- assignWsfeValue(results, "header", headerResult);
891
- assignWsfeValue(results, "detail", detailResult);
892
- return results;
893
- }
894
- function createWsfeIndeterminateOutcome(error) {
895
- return {
896
- kind: "indeterminate",
897
- service: "wsfe",
898
- operation: "FECAESolicitar",
899
- results: {},
900
- reason: getArcaIndeterminateReason(error),
901
- errors: [],
902
- observations: []
903
- };
904
- }
905
- function getArcaIndeterminateReason(error) {
906
- if (error instanceof ArcaTransportError) {
907
- return "transport_error";
908
- }
909
- if (error instanceof ArcaSoapFaultError) {
910
- return "soap_fault";
911
- }
912
- if (error instanceof ArcaInvalidSoapResponseError) {
913
- return "invalid_response";
914
- }
915
- return "unexpected_error";
916
- }
917
- function createWsfeOutcomeError(outcome) {
918
- const issues = [...outcome.errors, ...outcome.observations];
919
- const firstIssue = issues[0];
920
- const message = firstIssue ? formatWsfeIssue(firstIssue) : outcome.kind === "rejected" ? "WSFE rejected the voucher authorization" : outcome.result === "A" ? "WSFE did not return CAE authorization data" : "WSFE did not return conclusive voucher authorization data";
921
- return new ArcaServiceError(message, {
922
- service: "wsfe",
923
- operation: outcome.operation,
924
- ...firstIssue?.code === void 0 ? {} : { serviceCode: firstIssue.code },
925
- ...outcome.result === void 0 ? {} : { result: outcome.result },
926
- ...outcome.resultLevel === void 0 ? {} : { resultLevel: outcome.resultLevel },
927
- results: outcome.results,
928
- ...outcome.kind === "indeterminate" && outcome.cae ? { cae: outcome.cae } : {},
929
- issues,
930
- detail: outcome.raw
931
- });
932
- }
933
- function createWsfeServiceError(operation, result, issues) {
934
- const firstIssue = issues[0];
935
- return new ArcaServiceError(
936
- firstIssue ? formatWsfeIssue(firstIssue) : "WSFE returned a service error",
937
- {
938
- service: "wsfe",
939
- operation,
940
- ...firstIssue?.code === void 0 ? {} : { serviceCode: firstIssue.code },
941
- issues,
942
- detail: result
943
- }
944
- );
945
- }
946
- function extractWsfeGlobalIssues(result, operation, resultLevel) {
947
- const errorsContainer = toWsfeRecord(result.Errors);
948
- return normalizeWsfeIssueEntries(errorsContainer?.Err).map((entry) => ({
949
- service: "wsfe",
950
- operation,
951
- source: "error",
952
- category: operation === "FECAESolicitar" && WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES.has(entry.code ?? "") ? "infrastructure" : operation === "FECAESolicitar" ? "business" : "unknown",
953
- ...entry.code === void 0 ? {} : { code: entry.code },
954
- message: entry.message,
955
- ...resultLevel === void 0 ? {} : { resultLevel }
956
- }));
957
- }
958
- function extractWsfeObservations(detail, category) {
959
- const observationsContainer = toWsfeRecord(detail.Observaciones);
960
- return normalizeWsfeIssueEntries(observationsContainer?.Obs).map((entry) => ({
961
- service: "wsfe",
962
- operation: "FECAESolicitar",
963
- source: "observation",
964
- category,
965
- ...entry.code === void 0 ? {} : { code: entry.code },
966
- message: entry.message,
967
- resultLevel: "detail"
968
- }));
969
- }
970
- function normalizeWsfeIssueEntries(rawErrors) {
971
- const entries = Array.isArray(rawErrors) ? rawErrors : rawErrors ? [rawErrors] : [];
972
- return entries.map((entry) => entry).map((entry) => {
973
- const code = entry.Code ?? entry.code;
974
- const message = entry.Msg ?? entry.msg ?? "Unknown WSFE error";
975
- return {
976
- ...code === void 0 ? {} : { code: String(code) },
977
- message: String(message)
978
- };
979
- });
980
- }
981
- function formatWsfeIssue(issue) {
982
- return issue.code ? `(${issue.code}) ${issue.message}` : issue.message;
983
- }
984
- function normalizeWsfeResult(value) {
985
- if (typeof value !== "string") {
986
- return void 0;
987
- }
988
- const normalized = value.trim().toUpperCase();
989
- return normalized || void 0;
990
- }
991
- function normalizeWsfeString(value) {
992
- if (value === void 0 || value === null) {
993
- return void 0;
994
- }
995
- const normalized = String(value).trim();
996
- return normalized || void 0;
997
- }
998
- function normalizeWsfeNumber(value) {
999
- if (value === void 0 || value === null || value === "") {
1000
- return void 0;
1001
- }
1002
- const normalized = Number(value);
1003
- return Number.isFinite(normalized) ? normalized : void 0;
1004
- }
1005
- function assignWsfeValue(target, key, value) {
1006
- if (value !== void 0) {
1007
- target[key] = value;
1008
- }
1009
- }
1010
- function toWsfeRecord(value) {
1011
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1012
- }
1013
- var WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES = /* @__PURE__ */ new Set([
1014
- "500",
1015
- "501",
1016
- "502",
1017
- "600",
1018
- "601"
1019
- ]);
1020
- function getWsfeResultEntries(result, key) {
1021
- const rawEntries = result.ResultGet?.[key];
1022
- if (!rawEntries) {
1023
- return [];
1024
- }
1025
- return (Array.isArray(rawEntries) ? rawEntries : [rawEntries]).map(
1026
- (entry) => entry
1027
- );
1028
- }
1
+ import {
2
+ buildFacturaB,
3
+ buildFacturaC,
4
+ createWsfeService
5
+ } from "./chunk-C55KOV5N.mjs";
6
+ import "./chunk-VVY2LZIZ.mjs";
7
+ import "./chunk-IOKZX6CA.mjs";
8
+ import "./chunk-MBWOFO67.mjs";
1029
9
  export {
10
+ buildFacturaB,
11
+ buildFacturaC,
1030
12
  createWsfeService
1031
13
  };
1032
14
  //# sourceMappingURL=wsfe.mjs.map