facturas 0.6.0 → 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,1011 +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 sendsSameForeignCurrencyCancellation = input.currencyId !== "PES" && input.sameCurrencyForeignCancellation === "S";
430
- if (input.exchangeRate === void 0 && !sendsSameForeignCurrencyCancellation) {
431
- throw new ArcaInputError(
432
- "exchangeRate is required unless sameCurrencyForeignCancellation is S for a foreign-currency voucher."
433
- );
434
- }
435
- const data = {
436
- Concepto: input.concept,
437
- DocTipo: input.documentType,
438
- DocNro: input.documentNumber,
439
- CbteDesde: voucherNumber,
440
- CbteHasta: voucherNumber,
441
- CbteFch: input.voucherDate,
442
- ImpTotal: input.totalAmount,
443
- ImpTotConc: input.nonTaxableAmount,
444
- ImpNeto: input.netAmount,
445
- ImpOpEx: input.exemptAmount,
446
- ImpTrib: input.taxAmount,
447
- ImpIVA: input.vatAmount,
448
- MonId: input.currencyId,
449
- PtoVta: input.salesPoint,
450
- CbteTipo: input.voucherType
451
- };
452
- if (!sendsSameForeignCurrencyCancellation) {
453
- data.MonCotiz = input.exchangeRate;
454
- }
455
- if (input.receiverVatConditionId !== void 0) {
456
- data.CondicionIVAReceptorId = input.receiverVatConditionId;
457
- }
458
- if (input.currencyId !== "PES" && input.sameCurrencyForeignCancellation !== void 0) {
459
- data.CanMisMonExt = input.sameCurrencyForeignCancellation;
460
- }
461
- if (input.serviceStartDate !== void 0) {
462
- data.FchServDesde = input.serviceStartDate;
463
- }
464
- if (input.serviceEndDate !== void 0) {
465
- data.FchServHasta = input.serviceEndDate;
466
- }
467
- if (input.paymentDueDate !== void 0) {
468
- data.FchVtoPago = input.paymentDueDate;
469
- }
470
- if (input.associatedVouchers) {
471
- data.CbtesAsoc = {
472
- CbteAsoc: input.associatedVouchers.map((v) => ({
473
- Tipo: v.type,
474
- PtoVta: v.salesPoint,
475
- Nro: v.number,
476
- ...v.taxId === void 0 ? {} : { Cuit: v.taxId },
477
- ...v.voucherDate === void 0 ? {} : { CbteFch: v.voucherDate }
478
- }))
479
- };
480
- }
481
- if (input.associatedPeriod) {
482
- data.PeriodoAsoc = {
483
- FchDesde: input.associatedPeriod.startDate,
484
- FchHasta: input.associatedPeriod.endDate
485
- };
486
- }
487
- if (input.taxes) {
488
- data.Tributos = {
489
- Tributo: input.taxes.map((t) => ({
490
- Id: t.id,
491
- ...t.description === void 0 ? {} : { Desc: t.description },
492
- BaseImp: t.baseAmount,
493
- Alic: t.rate,
494
- Importe: t.amount
495
- }))
496
- };
497
- }
498
- if (input.vatRates) {
499
- data.Iva = {
500
- AlicIva: input.vatRates.map((v) => ({
501
- Id: v.id,
502
- BaseImp: v.baseAmount,
503
- Importe: v.amount
504
- }))
505
- };
506
- }
507
- if (input.optionalFields) {
508
- data.Opcionales = {
509
- Opcional: input.optionalFields.map((o) => ({
510
- Id: o.id,
511
- Valor: o.value
512
- }))
513
- };
514
- }
515
- if (input.buyers) {
516
- data.Compradores = {
517
- Comprador: input.buyers.map((b) => ({
518
- DocTipo: b.documentType,
519
- DocNro: b.documentNumber,
520
- Porcentaje: b.percentage
521
- }))
522
- };
523
- }
524
- if (input.activities) {
525
- data.Actividades = {
526
- Actividad: input.activities.map((a) => ({
527
- Id: a.id
528
- }))
529
- };
530
- }
531
- return data;
532
- }
533
- function normalizeWsfeVoucherInput(input) {
534
- const {
535
- voucherDate,
536
- serviceStartDate,
537
- serviceEndDate,
538
- paymentDueDate,
539
- associatedVouchers,
540
- associatedPeriod,
541
- ...rest
542
- } = input;
543
- return {
544
- ...rest,
545
- voucherDate: normalizeWsfeDateInput(voucherDate, "voucherDate"),
546
- ...serviceStartDate === void 0 ? {} : {
547
- serviceStartDate: normalizeWsfeDateInput(
548
- serviceStartDate,
549
- "serviceStartDate"
550
- )
551
- },
552
- ...serviceEndDate === void 0 ? {} : {
553
- serviceEndDate: normalizeWsfeDateInput(
554
- serviceEndDate,
555
- "serviceEndDate"
556
- )
557
- },
558
- ...paymentDueDate === void 0 ? {} : {
559
- paymentDueDate: normalizeWsfeDateInput(
560
- paymentDueDate,
561
- "paymentDueDate"
562
- )
563
- },
564
- ...associatedVouchers === void 0 ? {} : {
565
- associatedVouchers: associatedVouchers.map((voucher, index) => {
566
- const { voucherDate: associatedVoucherDate, ...associatedRest } = voucher;
567
- return {
568
- ...associatedRest,
569
- ...associatedVoucherDate === void 0 ? {} : {
570
- voucherDate: normalizeWsfeDateInput(
571
- associatedVoucherDate,
572
- `associatedVouchers[${index}].voucherDate`
573
- )
574
- }
575
- };
576
- })
577
- },
578
- ...associatedPeriod === void 0 ? {} : {
579
- associatedPeriod: {
580
- startDate: normalizeWsfeDateInput(
581
- associatedPeriod.startDate,
582
- "associatedPeriod.startDate"
583
- ),
584
- endDate: normalizeWsfeDateInput(
585
- associatedPeriod.endDate,
586
- "associatedPeriod.endDate"
587
- )
588
- }
589
- }
590
- };
591
- }
592
- function normalizeWsfeDateInput(value, fieldName) {
593
- if (typeof value !== "string") {
594
- throw new ArcaInputError(
595
- `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,
596
- {
597
- detail: { field: fieldName, value }
598
- }
599
- );
600
- }
601
- const normalizedValue = value.trim();
602
- const afipMatch = normalizedValue.match(/^(\d{4})(\d{2})(\d{2})$/);
603
- if (afipMatch) {
604
- const [, year, month, day] = afipMatch;
605
- assertValidCalendarDate(year, month, day, fieldName, normalizedValue);
606
- return normalizedValue;
607
- }
608
- const isoMatch = normalizedValue.match(/^(\d{4})-(\d{2})-(\d{2})$/);
609
- if (isoMatch) {
610
- const [, year, month, day] = isoMatch;
611
- assertValidCalendarDate(year, month, day, fieldName, normalizedValue);
612
- return `${year}${month}${day}`;
613
- }
614
- throw new ArcaInputError(
615
- `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,
616
- {
617
- detail: { field: fieldName, value: normalizedValue }
618
- }
619
- );
620
- }
621
- function assertValidCalendarDate(yearInput, monthInput, dayInput, fieldName, value) {
622
- const year = Number(yearInput);
623
- const month = Number(monthInput);
624
- const day = Number(dayInput);
625
- const candidate = new Date(Date.UTC(year, month - 1, day));
626
- if (candidate.getUTCFullYear() !== year || candidate.getUTCMonth() !== month - 1 || candidate.getUTCDate() !== day) {
627
- throw new ArcaInputError(
628
- `Invalid WSFE ${fieldName}: received a non-existent calendar date`,
629
- {
630
- detail: { field: fieldName, value }
631
- }
632
- );
633
- }
634
- }
635
- function mapWsfeSalesPoint(raw) {
636
- const record = raw;
637
- return {
638
- number: Number(record.Nro ?? 0),
639
- ...record.EmisionTipo === void 0 ? {} : { emissionType: String(record.EmisionTipo) },
640
- ...record.Bloqueado === void 0 ? {} : { blocked: String(record.Bloqueado) },
641
- ...record.FchBaja === void 0 ? {} : { deletedSince: String(record.FchBaja) }
642
- };
643
- }
644
- function mapWsfeCatalogEntry(raw) {
645
- const record = raw;
646
- return {
647
- id: Number(record.Id ?? 0),
648
- description: String(record.Desc ?? "")
649
- };
650
- }
651
- function mapWsfeActivityType(raw) {
652
- const record = raw;
653
- return {
654
- id: Number(record.Id ?? 0),
655
- description: String(record.Desc ?? ""),
656
- order: Number(record.Orden ?? 0)
657
- };
658
- }
659
- function mapWsfeReceiverVatCondition(raw) {
660
- const record = raw;
661
- return {
662
- id: Number(record.Id ?? 0),
663
- description: String(record.Desc ?? ""),
664
- voucherClass: String(record.Cmp_Clase ?? "")
665
- };
666
- }
667
- function mapWsfeCurrencyType(raw) {
668
- const record = raw;
669
- return {
670
- id: String(record.Id ?? ""),
671
- description: String(record.Desc ?? ""),
672
- validFrom: String(record.FchDesde ?? ""),
673
- validTo: String(record.FchHasta ?? "")
674
- };
675
- }
676
- function mapWsfeServerStatus(raw) {
677
- return {
678
- appServer: String(raw.AppServer ?? ""),
679
- dbServer: String(raw.DbServer ?? ""),
680
- authServer: String(raw.AuthServer ?? "")
681
- };
682
- }
683
- function mapWsfeQuotation(raw) {
684
- return {
685
- currencyId: String(raw.MonId ?? ""),
686
- rate: Number(raw.MonCotiz ?? 0),
687
- date: String(raw.FchCotiz ?? "")
688
- };
689
- }
690
- function mapWsfeVoucherInfo(raw) {
691
- const voucher = {
692
- voucherNumber: Number(raw.CbteDesde ?? raw.CbteHasta ?? 0),
693
- raw
694
- };
695
- assignWsfeValue(voucher, "voucherDate", normalizeWsfeString(raw.CbteFch));
696
- assignWsfeValue(voucher, "salesPoint", normalizeWsfeNumber(raw.PtoVta));
697
- assignWsfeValue(voucher, "voucherType", normalizeWsfeNumber(raw.CbteTipo));
698
- assignWsfeValue(voucher, "concept", normalizeWsfeNumber(raw.Concepto));
699
- assignWsfeValue(voucher, "documentType", normalizeWsfeNumber(raw.DocTipo));
700
- assignWsfeValue(voucher, "documentNumber", normalizeWsfeString(raw.DocNro));
701
- assignWsfeValue(
702
- voucher,
703
- "receiverVatConditionId",
704
- normalizeWsfeNumber(raw.CondicionIVAReceptorId)
705
- );
706
- assignWsfeValue(voucher, "totalAmount", normalizeWsfeNumber(raw.ImpTotal));
707
- assignWsfeValue(
708
- voucher,
709
- "nonTaxableAmount",
710
- normalizeWsfeNumber(raw.ImpTotConc)
711
- );
712
- assignWsfeValue(voucher, "netAmount", normalizeWsfeNumber(raw.ImpNeto));
713
- assignWsfeValue(voucher, "exemptAmount", normalizeWsfeNumber(raw.ImpOpEx));
714
- assignWsfeValue(voucher, "taxAmount", normalizeWsfeNumber(raw.ImpTrib));
715
- assignWsfeValue(voucher, "vatAmount", normalizeWsfeNumber(raw.ImpIVA));
716
- assignWsfeValue(voucher, "currencyId", normalizeWsfeString(raw.MonId));
717
- assignWsfeValue(voucher, "exchangeRate", normalizeWsfeNumber(raw.MonCotiz));
718
- assignWsfeValue(voucher, "result", normalizeWsfeString(raw.Resultado));
719
- assignWsfeValue(
720
- voucher,
721
- "cae",
722
- normalizeWsfeString(raw.CodAutorizacion ?? raw.CAE)
723
- );
724
- assignWsfeValue(
725
- voucher,
726
- "caeExpiry",
727
- normalizeWsfeString(raw.FchVto ?? raw.CAEFchVto)
728
- );
729
- return voucher;
730
- }
731
- function createWsfeAuth(representedTaxId, token, sign) {
732
- return {
733
- Token: token,
734
- Sign: sign,
735
- Cuit: Number.parseInt(String(representedTaxId), 10)
736
- };
737
- }
738
- function unwrapWsfeOperationEnvelope(operation, response) {
739
- const operationResponse = response[`${operation}Response`];
740
- const result = operationResponse?.[`${operation}Result`] ?? response[`${operation}Result`] ?? response;
741
- return result;
742
- }
743
- function throwForWsfeOperationErrors(operation, result) {
744
- const errors = extractWsfeGlobalIssues(result, operation);
745
- if (errors.length > 0) {
746
- throw createWsfeServiceError(operation, result, errors);
747
- }
748
- }
749
- function normalizeWsfeDetailResponse(result) {
750
- const detailResponse = result.FeDetResp;
751
- const rawDetail = detailResponse?.FECAEDetResponse;
752
- if (Array.isArray(rawDetail)) {
753
- return rawDetail[0] ?? {};
754
- }
755
- return rawDetail ?? {};
756
- }
757
- function classifyWsfeAuthorization(result, voucherNumber) {
758
- const operation = "FECAESolicitar";
759
- const header = toWsfeRecord(result.FeCabResp) ?? {};
760
- const detail = normalizeWsfeDetailResponse(result);
761
- const headerResult = normalizeWsfeResult(header.Resultado);
762
- const detailResult = normalizeWsfeResult(detail.Resultado);
763
- const resultCode = detailResult ?? headerResult;
764
- const resultLevel = getWsfeResultLevel(headerResult, detailResult);
765
- const cae = normalizeWsfeString(detail.CAE);
766
- const caeExpiry = normalizeWsfeString(detail.CAEFchVto);
767
- const errors = extractWsfeGlobalIssues(result, operation, "header");
768
- const observations = extractWsfeObservations(
769
- detail,
770
- detailResult === "R" ? "business" : "observation"
771
- );
772
- const hasInfrastructureError = errors.some(
773
- (issue) => issue.category === "infrastructure"
774
- );
775
- const base = {
776
- service: "wsfe",
777
- operation,
778
- results: createWsfeResults(headerResult, detailResult),
779
- errors,
780
- observations,
781
- raw: result
782
- };
783
- const context = {
784
- base,
785
- headerResult,
786
- detailResult,
787
- resultCode,
788
- resultLevel,
789
- cae,
790
- caeExpiry
791
- };
792
- if (hasContradictoryWsfeResults(context)) {
793
- return createWsfeStructuredIndeterminate(context, "contradictory_response");
794
- }
795
- if (hasInfrastructureError) {
796
- return createWsfeStructuredIndeterminate(context, "incomplete_response");
797
- }
798
- if (isAuthorizedWsfeContext(context)) {
799
- return {
800
- ...base,
801
- kind: "authorized",
802
- result: "A",
803
- resultLevel: "detail",
804
- cae: context.cae,
805
- caeExpiry: context.caeExpiry,
806
- voucherNumber
807
- };
808
- }
809
- if (isRejectedWsfeDetailContext(context)) {
810
- return {
811
- ...base,
812
- kind: "rejected",
813
- result: "R",
814
- resultLevel: "detail"
815
- };
816
- }
817
- if (isRejectedWsfeHeaderContext(context)) {
818
- return {
819
- ...base,
820
- kind: "rejected",
821
- result: "R",
822
- resultLevel: "header"
823
- };
824
- }
825
- return createWsfeStructuredIndeterminate(
826
- context,
827
- hasWsfeCaeContradiction(context) ? "contradictory_response" : "incomplete_response"
828
- );
829
- }
830
- function getWsfeResultLevel(headerResult, detailResult) {
831
- if (detailResult) {
832
- return "detail";
833
- }
834
- return headerResult ? "header" : void 0;
835
- }
836
- function hasContradictoryWsfeResults(context) {
837
- return Boolean(
838
- context.headerResult && context.detailResult && context.headerResult !== context.detailResult
839
- );
840
- }
841
- function isAuthorizedWsfeContext(context) {
842
- return Boolean(
843
- context.detailResult === "A" && context.headerResult !== "R" && context.base.errors.length === 0 && context.cae && context.caeExpiry
844
- );
845
- }
846
- function isRejectedWsfeDetailContext(context) {
847
- return context.detailResult === "R" && context.headerResult !== "A" && !context.cae;
848
- }
849
- function isRejectedWsfeHeaderContext(context) {
850
- return context.headerResult === "R" && context.detailResult === void 0 && !context.cae && context.base.errors.length > 0 && context.base.errors.every((issue) => issue.category === "business");
851
- }
852
- function hasWsfeCaeContradiction(context) {
853
- return (context.resultCode === "A" || context.resultCode === "R") && Boolean(context.cae);
854
- }
855
- function createWsfeStructuredIndeterminate(context, reason) {
856
- const outcome = {
857
- ...context.base,
858
- kind: "indeterminate",
859
- reason
860
- };
861
- assignWsfeValue(outcome, "result", context.resultCode);
862
- assignWsfeValue(outcome, "resultLevel", context.resultLevel);
863
- assignWsfeValue(outcome, "cae", context.cae);
864
- assignWsfeValue(outcome, "caeExpiry", context.caeExpiry);
865
- return outcome;
866
- }
867
- function createWsfeResults(headerResult, detailResult) {
868
- const results = {};
869
- assignWsfeValue(results, "header", headerResult);
870
- assignWsfeValue(results, "detail", detailResult);
871
- return results;
872
- }
873
- function createWsfeIndeterminateOutcome(error) {
874
- return {
875
- kind: "indeterminate",
876
- service: "wsfe",
877
- operation: "FECAESolicitar",
878
- results: {},
879
- reason: getArcaIndeterminateReason(error),
880
- errors: [],
881
- observations: []
882
- };
883
- }
884
- function getArcaIndeterminateReason(error) {
885
- if (error instanceof ArcaTransportError) {
886
- return "transport_error";
887
- }
888
- if (error instanceof ArcaSoapFaultError) {
889
- return "soap_fault";
890
- }
891
- if (error instanceof ArcaInvalidSoapResponseError) {
892
- return "invalid_response";
893
- }
894
- return "unexpected_error";
895
- }
896
- function createWsfeOutcomeError(outcome) {
897
- const issues = [...outcome.errors, ...outcome.observations];
898
- const firstIssue = issues[0];
899
- 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";
900
- return new ArcaServiceError(message, {
901
- service: "wsfe",
902
- operation: outcome.operation,
903
- ...firstIssue?.code === void 0 ? {} : { serviceCode: firstIssue.code },
904
- ...outcome.result === void 0 ? {} : { result: outcome.result },
905
- ...outcome.resultLevel === void 0 ? {} : { resultLevel: outcome.resultLevel },
906
- results: outcome.results,
907
- ...outcome.kind === "indeterminate" && outcome.cae ? { cae: outcome.cae } : {},
908
- issues,
909
- detail: outcome.raw
910
- });
911
- }
912
- function createWsfeServiceError(operation, result, issues) {
913
- const firstIssue = issues[0];
914
- return new ArcaServiceError(
915
- firstIssue ? formatWsfeIssue(firstIssue) : "WSFE returned a service error",
916
- {
917
- service: "wsfe",
918
- operation,
919
- ...firstIssue?.code === void 0 ? {} : { serviceCode: firstIssue.code },
920
- issues,
921
- detail: result
922
- }
923
- );
924
- }
925
- function extractWsfeGlobalIssues(result, operation, resultLevel) {
926
- const errorsContainer = toWsfeRecord(result.Errors);
927
- return normalizeWsfeIssueEntries(errorsContainer?.Err).map((entry) => ({
928
- service: "wsfe",
929
- operation,
930
- source: "error",
931
- category: operation === "FECAESolicitar" && WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES.has(entry.code ?? "") ? "infrastructure" : operation === "FECAESolicitar" ? "business" : "unknown",
932
- ...entry.code === void 0 ? {} : { code: entry.code },
933
- message: entry.message,
934
- ...resultLevel === void 0 ? {} : { resultLevel }
935
- }));
936
- }
937
- function extractWsfeObservations(detail, category) {
938
- const observationsContainer = toWsfeRecord(detail.Observaciones);
939
- return normalizeWsfeIssueEntries(observationsContainer?.Obs).map((entry) => ({
940
- service: "wsfe",
941
- operation: "FECAESolicitar",
942
- source: "observation",
943
- category,
944
- ...entry.code === void 0 ? {} : { code: entry.code },
945
- message: entry.message,
946
- resultLevel: "detail"
947
- }));
948
- }
949
- function normalizeWsfeIssueEntries(rawErrors) {
950
- const entries = Array.isArray(rawErrors) ? rawErrors : rawErrors ? [rawErrors] : [];
951
- return entries.map((entry) => entry).map((entry) => {
952
- const code = entry.Code ?? entry.code;
953
- const message = entry.Msg ?? entry.msg ?? "Unknown WSFE error";
954
- return {
955
- ...code === void 0 ? {} : { code: String(code) },
956
- message: String(message)
957
- };
958
- });
959
- }
960
- function formatWsfeIssue(issue) {
961
- return issue.code ? `(${issue.code}) ${issue.message}` : issue.message;
962
- }
963
- function normalizeWsfeResult(value) {
964
- if (typeof value !== "string") {
965
- return void 0;
966
- }
967
- const normalized = value.trim().toUpperCase();
968
- return normalized || void 0;
969
- }
970
- function normalizeWsfeString(value) {
971
- if (value === void 0 || value === null) {
972
- return void 0;
973
- }
974
- const normalized = String(value).trim();
975
- return normalized || void 0;
976
- }
977
- function normalizeWsfeNumber(value) {
978
- if (value === void 0 || value === null || value === "") {
979
- return void 0;
980
- }
981
- const normalized = Number(value);
982
- return Number.isFinite(normalized) ? normalized : void 0;
983
- }
984
- function assignWsfeValue(target, key, value) {
985
- if (value !== void 0) {
986
- target[key] = value;
987
- }
988
- }
989
- function toWsfeRecord(value) {
990
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
991
- }
992
- var WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES = /* @__PURE__ */ new Set([
993
- "500",
994
- "501",
995
- "502",
996
- "600",
997
- "601"
998
- ]);
999
- function getWsfeResultEntries(result, key) {
1000
- const rawEntries = result.ResultGet?.[key];
1001
- if (!rawEntries) {
1002
- return [];
1003
- }
1004
- return (Array.isArray(rawEntries) ? rawEntries : [rawEntries]).map(
1005
- (entry) => entry
1006
- );
1007
- }
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";
1008
9
  export {
10
+ buildFacturaB,
11
+ buildFacturaC,
1009
12
  createWsfeService
1010
13
  };
1011
14
  //# sourceMappingURL=wsfe.mjs.map