facturas 0.7.0 → 0.7.1

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.
@@ -27,12 +27,13 @@ function createWsmtxcaService(options) {
27
27
  bodyElementName: `${operation}Request`,
28
28
  bodyElementNamespaceMode: "prefix",
29
29
  body: {
30
- ...body,
30
+ // WSMTXCA request types use an XML sequence with authentication first.
31
31
  authRequest: createWsmtxcaAuth(
32
32
  input.representedTaxId ?? options.config.taxId,
33
33
  auth.token,
34
34
  auth.sign
35
- )
35
+ ),
36
+ ...body
36
37
  }
37
38
  });
38
39
  return unwrapWsmtxcaOperationResponse(response.result, operation);
@@ -699,4 +700,4 @@ function formatCompactDateToIso(dateValue) {
699
700
  export {
700
701
  createWsmtxcaService
701
702
  };
702
- //# sourceMappingURL=chunk-PKE4Z4GE.mjs.map
703
+ //# sourceMappingURL=chunk-A3C3Y5PI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/services/wsmtxca.ts"],"sourcesContent":["import {\n ArcaInputError,\n ArcaInvalidSoapResponseError,\n ArcaServiceError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport {\n classifyArcaAuthenticationError,\n classifyArcaAuthenticationIssues,\n createArcaAuthenticationErrorFromEvidence,\n createArcaAuthenticationEvidence,\n executeWithAuthenticationRecovery,\n} from \"../internal/authentication\";\nimport type { ArcaClientConfig, ArcaRepresentedTaxId } from \"../internal/types\";\nimport type { SoapTransport } from \"../soap\";\nimport type { WsaaAuthModule } from \"../wsaa\";\nimport type {\n ArcaAuthorizationIndeterminateReason,\n ArcaAuthorizationOutcome,\n ArcaFiscalIssue,\n ArcaVoucherLookupResult,\n} from \"./fiscal-evidence\";\n\n/** Input data for one WSMTXCA voucher authorization. */\nexport type WsmtxcaAuthorizeVoucherInput = {\n representedTaxId?: ArcaRepresentedTaxId;\n data: Record<string, unknown>;\n forceRefresh?: boolean;\n};\n\n/** Result of a successful WSMTXCA voucher authorization. */\nexport type WsmtxcaAuthorizationResult = {\n cae: string;\n caeExpiry?: string;\n voucherNumber: number;\n messages: string[];\n raw: Record<string, unknown>;\n};\n\n/** Structured evidence from one exact WSMTXCA authorization attempt. */\nexport type WsmtxcaAuthorizationOutcome = ArcaAuthorizationOutcome<\"wsmtxca\">;\n\n/** Result of querying the last authorized voucher number. */\nexport type WsmtxcaLastAuthorizedVoucherResult = {\n voucherNumber: number;\n raw: Record<string, unknown>;\n};\n\n/** A point of sale enabled for WSMTXCA. */\nexport type WsmtxcaSalesPoint = {\n number: number;\n blocked: boolean;\n deletedAt?: string;\n};\n\n/** Result of querying WSMTXCA points of sale. */\nexport type WsmtxcaSalesPointsResult = {\n salesPoints: WsmtxcaSalesPoint[];\n raw: Record<string, unknown>;\n};\n\n/** Typed provider fields used to match one exact WSMTXCA voucher. */\nexport type WsmtxcaVoucherInfo = {\n voucherNumber?: number;\n invoiceDate?: string;\n salesPoint?: number;\n voucherType?: number;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n totalAmount?: number;\n subtotalAmount?: number;\n taxableAmount?: number;\n nonTaxableAmount?: number;\n exemptAmount?: number;\n taxAmount?: number;\n vatAmount?: number;\n currencyId?: string;\n exchangeRate?: number;\n cae?: string;\n caeExpiry?: string;\n raw: Record<string, unknown>;\n};\n\n/** Typed exact-voucher consultation result for WSMTXCA. */\nexport type WsmtxcaVoucherLookupOutcome = ArcaVoucherLookupResult<\n WsmtxcaVoucherInfo,\n \"wsmtxca\"\n>;\n\n/** Result of looking up a specific WSMTXCA voucher. */\nexport type WsmtxcaVoucherLookupResult = {\n invoiceDate: string;\n voucher: Record<string, unknown>;\n messages: string[];\n raw: Record<string, unknown>;\n};\n\n/** WSMTXCA electronic invoicing service (Factura de Crédito Electrónica). */\nexport type WsmtxcaService = {\n /** Attempts one authorization without transport retries and returns provider evidence. */\n authorizeVoucherOutcome(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationOutcome>;\n /** Authorizes a voucher and returns the CAE. */\n authorizeVoucher(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult>;\n /** Returns the last authorized voucher number for the given sales point and type. */\n getLastAuthorizedVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult>;\n /** Returns the points of sale enabled for WSMTXCA. */\n getSalesPoints(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult>;\n /** Consults one exact voucher and normalizes WSMTXCA error 1503 to `not_found`. */\n lookupVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome>;\n /** Retrieves details for a specific voucher. */\n getVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupResult>;\n};\n\nexport type CreateWsmtxcaServiceOptions = {\n config: ArcaClientConfig;\n auth: WsaaAuthModule;\n soap: SoapTransport;\n};\n\n/** Creates a WSMTXCA service instance wired with authentication and SOAP transport. */\nexport function createWsmtxcaService(\n options: CreateWsmtxcaServiceOptions\n): WsmtxcaService {\n async function executeWsmtxcaAuthenticatedOperation(\n operation: WsmtxcaOperation,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {},\n retries?: number\n ) {\n const auth = await options.auth.login(\"wsmtxca\", {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsmtxca\",\n operation,\n ...(retries === undefined ? {} : { retries }),\n bodyElementName: `${operation}Request`,\n bodyElementNamespaceMode: \"prefix\",\n body: {\n // WSMTXCA request types use an XML sequence with authentication first.\n authRequest: createWsmtxcaAuth(\n input.representedTaxId ?? options.config.taxId,\n auth.token,\n auth.sign\n ),\n ...body,\n },\n });\n\n return unwrapWsmtxcaOperationResponse(response.result, operation);\n }\n\n async function executeWsmtxcaAuthorization({\n representedTaxId,\n data,\n forceRefresh,\n }: WsmtxcaAuthorizeVoucherInput): Promise<{\n outcome: WsmtxcaAuthorizationOutcome;\n error?: unknown;\n }> {\n if (Object.hasOwn(data, \"authRequest\")) {\n throw new ArcaInputError(\n 'WSMTXCA authorization data cannot include the reserved top-level field \"authRequest\".',\n {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field: \"data.authRequest\",\n expected: \"omitted because facturas manages authentication fields\",\n }\n );\n }\n\n try {\n const raw = await executeWsmtxcaAuthenticatedOperation(\n \"autorizarComprobante\",\n { representedTaxId, forceRefresh },\n data,\n 0\n );\n return { outcome: classifyWsmtxcaAuthorization(raw) };\n } catch (error) {\n return {\n outcome: createWsmtxcaIndeterminateOutcome(error),\n error,\n };\n }\n }\n\n async function authorizeVoucherOutcome(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationOutcome> {\n return (await executeWsmtxcaAuthorization(input)).outcome;\n }\n\n function authorizeVoucher(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n forceRefresh: input.forceRefresh,\n execute: (forceRefresh) =>\n authorizeVoucherOnce({ ...input, forceRefresh }),\n });\n }\n\n async function authorizeVoucherOnce(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult> {\n const execution = await executeWsmtxcaAuthorization(input);\n if (execution.error) {\n throw execution.error;\n }\n if (execution.outcome.kind !== \"authorized\") {\n throw createWsmtxcaOutcomeError(execution.outcome);\n }\n\n const { outcome } = execution;\n return {\n cae: outcome.cae,\n ...(outcome.caeExpiry === undefined\n ? {}\n : { caeExpiry: outcome.caeExpiry }),\n voucherNumber: outcome.voucherNumber,\n messages: formatWsmtxcaIssues([\n ...outcome.errors,\n ...outcome.observations,\n ]),\n raw: outcome.raw ?? {},\n };\n }\n\n function getLastAuthorizedVoucher({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarUltimoComprobanteAutorizado\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n getLastAuthorizedVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function getLastAuthorizedVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult> {\n const operation = \"consultarUltimoComprobanteAutorizado\";\n const raw = await executeWsmtxcaAuthenticatedOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n consultaUltimoComprobanteAutorizadoRequest: {\n codigoTipoComprobante: voucherType,\n numeroPuntoVenta: salesPoint,\n },\n }\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"1502\")) {\n return { voucherNumber: 0, raw };\n }\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n\n return {\n voucherNumber: parseWsmtxcaVoucherNumber(\n raw.numeroComprobante ?? raw.cbteNro ?? raw.nroComprobante,\n \"WSMTXCA did not return the last authorized voucher number\",\n true\n ),\n raw,\n };\n }\n\n function getSalesPoints({\n representedTaxId,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarPuntosVenta\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n getSalesPointsOnce({\n representedTaxId,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function getSalesPointsOnce({\n representedTaxId,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult> {\n const operation = \"consultarPuntosVenta\";\n const raw = await executeWsmtxcaAuthenticatedOperation(operation, {\n representedTaxId,\n forceRefresh,\n });\n throwForWsmtxcaOperationErrors(operation, raw);\n const rawSalesPoints = toRecord(raw.arrayPuntosVenta)?.puntoVenta;\n const entries = Array.isArray(rawSalesPoints)\n ? rawSalesPoints\n : rawSalesPoints\n ? [rawSalesPoints]\n : [];\n const salesPoints = entries.flatMap((entry) => {\n const record = toRecord(entry);\n const number = parseOptionalPositiveInteger(record?.numeroPuntoVenta);\n if (number === undefined) {\n return [];\n }\n const deletedAt = normalizeWsmtxcaResponseDate(record?.fechaBaja);\n return [\n {\n number,\n blocked: String(record?.bloqueado ?? \"N\").toUpperCase() === \"S\",\n ...(deletedAt === undefined ? {} : { deletedAt }),\n },\n ];\n });\n\n return { salesPoints, raw };\n }\n\n function lookupVoucher({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarComprobante\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n lookupVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function lookupVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome> {\n const operation = \"consultarComprobante\";\n const raw = await executeWsmtxcaAuthenticatedOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n consultaComprobanteRequest: {\n codigoTipoComprobante: voucherType,\n numeroPuntoVenta: salesPoint,\n numeroComprobante: voucherNumber,\n },\n }\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n const observations = extractWsmtxcaIssues(raw, operation, \"observation\");\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"1503\")) {\n return {\n kind: \"not_found\",\n service: \"wsmtxca\",\n operation,\n errors,\n observations,\n raw,\n };\n }\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n\n const voucher = extractWsmtxcaVoucherPayload(raw);\n if (voucher === raw && !toRecord(raw.comprobante)) {\n throw new ArcaServiceError(\n \"WSMTXCA did not return the voucher issue date\",\n {\n service: \"wsmtxca\",\n operation,\n issues: observations,\n }\n );\n }\n\n return {\n kind: \"found\",\n service: \"wsmtxca\",\n operation,\n voucher: mapWsmtxcaVoucherInfo(voucher),\n observations,\n raw,\n };\n }\n\n async function getVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupResult> {\n const lookup = await lookupVoucher(input);\n if (lookup.kind === \"not_found\") {\n throw createWsmtxcaServiceError(lookup.operation, lookup.errors);\n }\n\n const invoiceDate = lookup.voucher.invoiceDate;\n if (!invoiceDate) {\n throw new ArcaServiceError(\n formatWsmtxcaIssues(lookup.observations)[0] ??\n \"WSMTXCA did not return the voucher issue date\",\n {\n service: \"wsmtxca\",\n operation: lookup.operation,\n issues: lookup.observations,\n }\n );\n }\n\n return {\n invoiceDate,\n voucher: lookup.voucher.raw,\n messages: formatWsmtxcaIssues(lookup.observations),\n raw: lookup.raw,\n };\n }\n\n return {\n authorizeVoucherOutcome,\n authorizeVoucher,\n getLastAuthorizedVoucher,\n getSalesPoints,\n lookupVoucher,\n getVoucher,\n };\n}\n\nfunction createWsmtxcaAuth(\n representedTaxId: number | string,\n token: string,\n sign: string\n) {\n return {\n token,\n sign,\n cuitRepresentada: Number.parseInt(String(representedTaxId), 10),\n };\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\ntype WsmtxcaOperation =\n | \"autorizarComprobante\"\n | \"consultarUltimoComprobanteAutorizado\"\n | \"consultarPuntosVenta\"\n | \"consultarComprobante\";\n\nfunction unwrapWsmtxcaOperationResponse(\n response: unknown,\n operation: WsmtxcaOperation\n) {\n const responseRecord = toRecord(response) ?? {};\n\n if (operation === \"autorizarComprobante\") {\n return (\n toRecord(responseRecord.autorizarComprobanteResponse) ??\n toRecord(responseRecord.autorizarComprobanteResult) ??\n toRecord(responseRecord.comprobanteCAEResponse) ??\n toRecord(responseRecord.comprobanteCAEReponse) ??\n responseRecord\n );\n }\n\n if (operation === \"consultarComprobante\") {\n return (\n toRecord(responseRecord.consultarComprobanteResponse) ??\n toRecord(responseRecord.consultaComprobanteResponse) ??\n toRecord(responseRecord.consultarComprobanteResult) ??\n responseRecord\n );\n }\n\n if (operation === \"consultarPuntosVenta\") {\n return (\n toRecord(responseRecord.consultarPuntosVentaResponse) ??\n toRecord(responseRecord.consultarPuntosVentaResult) ??\n responseRecord\n );\n }\n\n return (\n toRecord(responseRecord.consultarUltimoComprobanteAutorizadoResponse) ??\n toRecord(responseRecord.consultaUltimoComprobanteAutorizadoResponse) ??\n toRecord(responseRecord.consultarUltimoComprobanteAutorizadoResult) ??\n responseRecord\n );\n}\n\nfunction extractWsmtxcaAuthorizationPayload(raw: Record<string, unknown>) {\n return (\n toRecord(raw.comprobanteResponse) ??\n toRecord(raw.comprobanteCAEResponse) ??\n toRecord(raw.comprobanteCAEReponse) ??\n raw\n );\n}\n\nfunction extractWsmtxcaVoucherPayload(raw: Record<string, unknown>) {\n return (\n toRecord(raw.comprobanteResponse) ??\n toRecord(raw.comprobante) ??\n toRecord(raw.cmp) ??\n raw\n );\n}\n\nfunction classifyWsmtxcaAuthorization(\n raw: Record<string, unknown>\n): WsmtxcaAuthorizationOutcome {\n const operation = \"autorizarComprobante\";\n const payload = extractWsmtxcaAuthorizationPayload(raw);\n const result = normalizeWsmtxcaResult(raw.resultado ?? payload.resultado);\n const cae = normalizeWsmtxcaString(\n payload.CAE ?? payload.codigoAutorizacion ?? raw.codigoAutorizacion\n );\n const caeExpiry = normalizeWsmtxcaResponseDate(\n payload.fechaVencimientoCAE ??\n payload.fechaVencimiento ??\n raw.fechaVencimiento\n );\n const voucherNumber = parseOptionalPositiveInteger(\n payload.numeroComprobante ?? raw.numeroComprobante\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n const observations = extractWsmtxcaIssues(raw, operation, \"observation\");\n const base = {\n service: \"wsmtxca\" as const,\n operation,\n results: createWsmtxcaResults(result),\n errors,\n observations,\n raw,\n };\n\n const authenticationOutcome = createWsmtxcaAuthenticationOutcome({\n base,\n result,\n cae,\n voucherNumber,\n });\n if (authenticationOutcome) {\n return authenticationOutcome;\n }\n\n if (\n (result === \"A\" || result === \"O\") &&\n cae &&\n voucherNumber !== undefined &&\n errors.length === 0\n ) {\n return {\n ...base,\n kind: \"authorized\",\n result,\n resultLevel: \"operation\",\n cae,\n ...(caeExpiry === undefined ? {} : { caeExpiry }),\n voucherNumber,\n };\n }\n\n if (result === \"R\" && !cae && errors.length > 0) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"operation\",\n };\n }\n\n const outcome: WsmtxcaAuthorizationOutcome = {\n ...base,\n kind: \"indeterminate\",\n reason:\n (result === \"R\" && Boolean(cae)) ||\n ((result === \"A\" || result === \"O\") && Boolean(errors.length))\n ? \"contradictory_response\"\n : \"incomplete_response\",\n ...(result === undefined ? {} : { result }),\n ...(result === undefined ? {} : { resultLevel: \"operation\" }),\n };\n assignWsmtxcaValue(outcome, \"cae\", cae);\n assignWsmtxcaValue(outcome, \"caeExpiry\", caeExpiry);\n assignWsmtxcaValue(outcome, \"voucherNumber\", voucherNumber);\n return outcome;\n}\n\nfunction createWsmtxcaAuthenticationOutcome({\n base,\n result,\n cae,\n voucherNumber,\n}: {\n base: {\n service: \"wsmtxca\";\n operation: string;\n results: ReturnType<typeof createWsmtxcaResults>;\n errors: ArcaFiscalIssue[];\n observations: ArcaFiscalIssue[];\n raw: Record<string, unknown>;\n };\n result?: string;\n cae?: string;\n voucherNumber?: number;\n}): WsmtxcaAuthorizationOutcome | undefined {\n const authenticationError = classifyArcaAuthenticationIssues(base.errors, {\n service: base.service,\n operation: base.operation,\n });\n if (\n !authenticationError ||\n result === \"A\" ||\n result === \"O\" ||\n cae ||\n voucherNumber !== undefined\n ) {\n return undefined;\n }\n\n return {\n ...base,\n kind: \"indeterminate\",\n reason: \"authentication_rejected\",\n authentication: createArcaAuthenticationEvidence(authenticationError),\n ...(result === undefined ? {} : { result }),\n ...(result === undefined ? {} : { resultLevel: \"operation\" }),\n };\n}\n\nfunction createWsmtxcaIndeterminateOutcome(\n error: unknown\n): WsmtxcaAuthorizationOutcome {\n const authenticationError = classifyArcaAuthenticationError(error, {\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n });\n return {\n kind: \"indeterminate\",\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n results: {},\n reason: authenticationError\n ? \"authentication_rejected\"\n : getWsmtxcaIndeterminateReason(error),\n ...(authenticationError\n ? {\n authentication: createArcaAuthenticationEvidence(authenticationError),\n }\n : {}),\n errors: [],\n observations: [],\n };\n}\n\nfunction getWsmtxcaIndeterminateReason(\n error: unknown\n): ArcaAuthorizationIndeterminateReason {\n if (error instanceof ArcaTransportError) {\n return \"transport_error\";\n }\n if (error instanceof ArcaSoapFaultError) {\n return \"soap_fault\";\n }\n if (error instanceof ArcaInvalidSoapResponseError) {\n return \"invalid_response\";\n }\n return \"unexpected_error\";\n}\n\nfunction createWsmtxcaOutcomeError(\n outcome: Exclude<WsmtxcaAuthorizationOutcome, { kind: \"authorized\" }>\n) {\n if (outcome.kind === \"indeterminate\" && outcome.authentication) {\n return createArcaAuthenticationErrorFromEvidence(outcome.authentication, {\n service: \"wsmtxca\",\n operation: outcome.operation,\n });\n }\n\n const issues = [...outcome.errors, ...outcome.observations];\n const messages = formatWsmtxcaIssues(issues);\n const firstIssue = issues[0];\n return new ArcaServiceError(\n messages.join(\" | \") ||\n (outcome.kind === \"rejected\"\n ? \"WSMTXCA rejected the voucher authorization\"\n : \"WSMTXCA did not return conclusive voucher authorization data\"),\n {\n service: \"wsmtxca\",\n operation: outcome.operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n ...(outcome.result === undefined ? {} : { result: outcome.result }),\n ...(outcome.resultLevel === undefined\n ? {}\n : { resultLevel: outcome.resultLevel }),\n results: outcome.results,\n ...(outcome.kind === \"indeterminate\" && outcome.cae\n ? { cae: outcome.cae }\n : {}),\n issues,\n }\n );\n}\n\nfunction createWsmtxcaResults(operationResult?: string) {\n const results: { operation?: string } = {};\n assignWsmtxcaValue(results, \"operation\", operationResult);\n return results;\n}\n\nfunction createWsmtxcaServiceError(\n operation: string,\n issues: ArcaFiscalIssue[]\n) {\n const authenticationError = classifyArcaAuthenticationIssues(issues, {\n service: \"wsmtxca\",\n operation,\n });\n if (authenticationError) {\n return authenticationError;\n }\n\n const firstIssue = issues[0];\n return new ArcaServiceError(\n formatWsmtxcaIssues(issues).join(\" | \") ||\n \"WSMTXCA returned a service error\",\n {\n service: \"wsmtxca\",\n operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n issues,\n }\n );\n}\n\nfunction throwForWsmtxcaOperationErrors(\n operation: string,\n raw: Record<string, unknown>\n): void {\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n}\n\nfunction extractWsmtxcaIssues(\n raw: Record<string, unknown>,\n operation: string,\n source: \"error\" | \"observation\"\n): ArcaFiscalIssue[] {\n const container = toRecord(\n source === \"error\" ? raw.arrayErrores : raw.arrayObservaciones\n );\n return normalizeWsmtxcaIssueEntries(container?.codigoDescripcion).map(\n (entry) => ({\n service: \"wsmtxca\",\n operation,\n source,\n category:\n source === \"observation\"\n ? \"observation\"\n : operation === \"autorizarComprobante\"\n ? \"business\"\n : \"unknown\",\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n ...(operation === \"autorizarComprobante\"\n ? { resultLevel: \"operation\" as const }\n : {}),\n })\n );\n}\n\nfunction normalizeWsmtxcaIssueEntries(value: unknown) {\n const entries = Array.isArray(value) ? value : value ? [value] : [];\n return entries.map((entry) => {\n const record = toRecord(entry) ?? {};\n const code = record.codigo;\n const description = record.descripcion;\n return {\n ...(code === undefined || code === null ? {} : { code: String(code) }),\n message:\n description === undefined || description === null\n ? \"Unknown WSMTXCA issue\"\n : String(description),\n };\n });\n}\n\nfunction formatWsmtxcaIssues(issues: ArcaFiscalIssue[]): string[] {\n return issues.map((issue) => {\n const prefix = issue.source === \"error\" ? \"Error\" : \"Obs\";\n return `${prefix}${issue.code ? ` ${issue.code}` : \"\"}: ${issue.message}`;\n });\n}\n\nfunction mapWsmtxcaVoucherInfo(\n raw: Record<string, unknown>\n): WsmtxcaVoucherInfo {\n const voucher: WsmtxcaVoucherInfo = { raw };\n const invoiceDate = normalizeWsmtxcaResponseDate(\n raw.fechaEmision ?? raw.fecha ?? raw.CbteFch\n );\n const cae = normalizeWsmtxcaString(raw.codigoAutorizacion ?? raw.CAE);\n const caeExpiry = normalizeWsmtxcaResponseDate(\n raw.fechaVencimiento ?? raw.fechaVencimientoCAE\n );\n const vatAmount = sumWsmtxcaVatAmounts(raw.arraySubtotalesIVA);\n\n assignWsmtxcaValue(\n voucher,\n \"voucherNumber\",\n parseOptionalPositiveInteger(raw.numeroComprobante)\n );\n assignWsmtxcaValue(voucher, \"invoiceDate\", invoiceDate);\n assignWsmtxcaValue(\n voucher,\n \"salesPoint\",\n parseOptionalPositiveInteger(raw.numeroPuntoVenta)\n );\n assignWsmtxcaValue(\n voucher,\n \"voucherType\",\n parseOptionalPositiveInteger(raw.codigoTipoComprobante)\n );\n assignWsmtxcaValue(\n voucher,\n \"concept\",\n parseOptionalNumber(raw.codigoConcepto)\n );\n assignWsmtxcaValue(\n voucher,\n \"documentType\",\n parseOptionalNumber(raw.codigoTipoDocumento)\n );\n assignWsmtxcaValue(\n voucher,\n \"documentNumber\",\n normalizeWsmtxcaString(raw.numeroDocumento)\n );\n assignWsmtxcaValue(\n voucher,\n \"receiverVatConditionId\",\n parseOptionalNumber(raw.condicionIVAReceptor)\n );\n assignWsmtxcaValue(\n voucher,\n \"totalAmount\",\n parseOptionalNumber(raw.importeTotal)\n );\n assignWsmtxcaValue(\n voucher,\n \"subtotalAmount\",\n parseOptionalNumber(raw.importeSubtotal)\n );\n assignWsmtxcaValue(\n voucher,\n \"taxableAmount\",\n parseOptionalNumber(raw.importeGravado)\n );\n assignWsmtxcaValue(\n voucher,\n \"nonTaxableAmount\",\n parseOptionalNumber(raw.importeNoGravado)\n );\n assignWsmtxcaValue(\n voucher,\n \"exemptAmount\",\n parseOptionalNumber(raw.importeExento)\n );\n assignWsmtxcaValue(\n voucher,\n \"taxAmount\",\n parseOptionalNumber(raw.importeOtrosTributos)\n );\n assignWsmtxcaValue(voucher, \"vatAmount\", vatAmount);\n assignWsmtxcaValue(\n voucher,\n \"currencyId\",\n normalizeWsmtxcaString(raw.codigoMoneda)\n );\n assignWsmtxcaValue(\n voucher,\n \"exchangeRate\",\n parseOptionalNumber(raw.cotizacionMoneda)\n );\n assignWsmtxcaValue(voucher, \"cae\", cae);\n assignWsmtxcaValue(voucher, \"caeExpiry\", caeExpiry);\n\n return voucher;\n}\n\nfunction sumWsmtxcaVatAmounts(value: unknown): number | undefined {\n const subtotals = toRecord(value)?.subtotalIVA;\n const entries = Array.isArray(subtotals)\n ? subtotals\n : subtotals\n ? [subtotals]\n : [];\n const amounts = entries\n .map((entry) => parseOptionalNumber(toRecord(entry)?.importe))\n .filter((amount): amount is number => amount !== undefined);\n return amounts.length > 0\n ? amounts.reduce((total, amount) => total + amount, 0)\n : undefined;\n}\n\nfunction parseWsmtxcaVoucherNumber(\n value: unknown,\n message: string,\n allowZero = false\n) {\n const parsed = Number.parseInt(String(value ?? \"\"), 10);\n if (!Number.isFinite(parsed) || (allowZero ? parsed < 0 : parsed <= 0)) {\n throw new ArcaServiceError(message, {\n service: \"wsmtxca\",\n });\n }\n return parsed;\n}\n\nfunction parseOptionalPositiveInteger(value: unknown): number | undefined {\n const parsed = Number.parseInt(String(value ?? \"\"), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction parseOptionalNumber(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction normalizeWsmtxcaResult(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim().toUpperCase();\n return normalized || undefined;\n}\n\nfunction normalizeWsmtxcaString(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const normalized = String(value).trim();\n return normalized || undefined;\n}\n\nfunction assignWsmtxcaValue<TTarget, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined\n) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n\nfunction normalizeWsmtxcaResponseDate(value: unknown): string | undefined {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return formatCompactDateToIso(value);\n }\n\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n if (/^\\d{8}$/.test(trimmed)) {\n return formatCompactDateToIso(Number.parseInt(trimmed, 10));\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(trimmed)) {\n return trimmed.slice(0, 10);\n }\n\n return undefined;\n}\n\nfunction formatCompactDateToIso(dateValue?: number | null): string | undefined {\n if (!dateValue) {\n return undefined;\n }\n\n const raw = String(dateValue);\n if (raw.length !== 8) {\n return undefined;\n }\n\n return `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmJO,SAAS,qBACd,SACgB;AAChB,iBAAe,qCACb,WACA,OAIA,OAAgC,CAAC,GACjC,SACA;AACA,UAAM,OAAO,MAAM,QAAQ,KAAK,MAAM,WAAW;AAAA,MAC/C,kBAAkB,MAAM;AAAA,MACxB,cAAc,MAAM;AAAA,IACtB,CAAC;AACD,UAAM,WAAW,MAAM,QAAQ,KAAK,QAGlC;AAAA,MACA,SAAS;AAAA,MACT;AAAA,MACA,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAAA,MAC3C,iBAAiB,GAAG,SAAS;AAAA,MAC7B,0BAA0B;AAAA,MAC1B,MAAM;AAAA;AAAA,QAEJ,aAAa;AAAA,UACX,MAAM,oBAAoB,QAAQ,OAAO;AAAA,UACzC,KAAK;AAAA,UACL,KAAK;AAAA,QACP;AAAA,QACA,GAAG;AAAA,MACL;AAAA,IACF,CAAC;AAED,WAAO,+BAA+B,SAAS,QAAQ,SAAS;AAAA,EAClE;AAEA,iBAAe,4BAA4B;AAAA,IACzC;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAGG;AACD,QAAI,OAAO,OAAO,MAAM,aAAa,GAAG;AACtC,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,UACE,MAAM;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@ function calculateVatMinorUnits(taxableMinorUnits, vatRate, field) {
103
103
  expected: "one of 0, 2.5, 5, 10.5, 21, or 27"
104
104
  });
105
105
  }
106
- return (taxableMinorUnits * basisPoints + 5000n) / 10000n;
106
+ return roundHalfEvenRatio(taxableMinorUnits * basisPoints, 10000n);
107
+ }
108
+ function roundHalfEvenRatio(numerator, denominator) {
109
+ if (numerator < 0n || denominator <= 0n) {
110
+ throw new RangeError(
111
+ "roundHalfEvenRatio requires a non-negative numerator and a positive denominator."
112
+ );
113
+ }
114
+ const quotient = numerator / denominator;
115
+ const doubledRemainder = numerator % denominator * 2n;
116
+ if (doubledRemainder > denominator) {
117
+ return quotient + 1n;
118
+ }
119
+ if (doubledRemainder < denominator) {
120
+ return quotient;
121
+ }
122
+ return quotient % 2n === 0n ? quotient : quotient + 1n;
107
123
  }
108
124
  function isWithinArcaTolerance(actualMinorUnits, expectedMinorUnits, absoluteCentAllowance = 1) {
109
125
  const difference = absoluteBigInt(actualMinorUnits - expectedMinorUnits);
@@ -1583,4 +1599,4 @@ export {
1583
1599
  buildFacturaB,
1584
1600
  buildFacturaC
1585
1601
  };
1586
- //# sourceMappingURL=chunk-C55KOV5N.mjs.map
1602
+ //# sourceMappingURL=chunk-OHHXHYLV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/decimal.ts","../src/services/wsfe.ts","../src/services/wsfe-builders.ts"],"sourcesContent":["import { ArcaInputError } from \"../errors\";\n\nconst AMOUNT_SCALE = 100;\nconst EXCHANGE_RATE_SCALE = 1_000_000;\nconst EXCHANGE_RATE_SCALE_BIGINT = 1_000_000n;\nconst PERCENTAGE_SCALE = 100;\n\n// WSFE documents amount fields as 13 integer digits plus 2 decimals.\nconst MAX_ARCA_AMOUNT_MINOR_UNITS = 999_999_999_999_999n;\n// MonCotiz is documented as 4 integer digits plus 6 decimals.\nconst MAX_ARCA_EXCHANGE_RATE_SCALED = 9_999_999_999n;\n// Tributo.Alic is documented as 3 integer digits plus 2 decimals.\nconst MAX_ARCA_PERCENTAGE_HUNDREDTHS = 99_999n;\n\nexport const SUPPORTED_VAT_RATES = [0, 2.5, 5, 10.5, 21, 27] as const;\nexport type SupportedVatRate = (typeof SUPPORTED_VAT_RATES)[number];\n\nconst VAT_RATE_BASIS_POINTS: Record<SupportedVatRate, bigint> = {\n 0: 0n,\n 2.5: 250n,\n 5: 500n,\n 10.5: 1050n,\n 21: 2100n,\n 27: 2700n,\n};\n\nexport function normalizeArcaAmountToMinorUnits(\n value: number,\n field: string\n): bigint {\n return normalizeScaledNumber({\n value,\n field,\n scale: AMOUNT_SCALE,\n maximum: MAX_ARCA_AMOUNT_MINOR_UNITS,\n expected: \"a finite non-negative amount with at most 2 decimal places\",\n });\n}\n\nexport function serializeArcaAmount(value: number, field: string): string {\n return formatScaledInteger(normalizeArcaAmountToMinorUnits(value, field), 2);\n}\n\nexport function serializeArcaMinorUnits(value: number, field: string): string {\n return formatScaledInteger(assertArcaMinorUnits(value, field), 2);\n}\n\nexport function serializeArcaPercentage(value: number, field: string): string {\n const scaled = normalizeScaledNumber({\n value,\n field,\n scale: PERCENTAGE_SCALE,\n maximum: MAX_ARCA_PERCENTAGE_HUNDREDTHS,\n expected: \"a finite non-negative percentage with at most 2 decimal places\",\n });\n return formatScaledInteger(scaled, 2);\n}\n\nexport function serializeArcaExchangeRate(\n value: number | string,\n field: string\n): string {\n const scaled =\n typeof value === \"number\"\n ? normalizeExchangeRateNumber(value, field)\n : normalizeExchangeRateString(value, field);\n\n if (scaled <= 0n || scaled > MAX_ARCA_EXCHANGE_RATE_SCALED) {\n throwInvalidExchangeRate(field);\n }\n\n return formatScaledInteger(scaled, 6, true);\n}\n\nexport function assertArcaMinorUnits(value: number, field: string): bigint {\n if (!(Number.isSafeInteger(value) && value >= 0)) {\n throw new ArcaInputError(\n `${field} must be a non-negative safe integer in currency minor units.`,\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"a non-negative safe integer in currency minor units\",\n }\n );\n }\n\n const minorUnits = BigInt(value);\n if (minorUnits > MAX_ARCA_AMOUNT_MINOR_UNITS) {\n throw new ArcaInputError(`${field} exceeds the WSFE amount limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"at most 13 integer digits and 2 decimal places\",\n });\n }\n\n return minorUnits;\n}\n\nexport function arcaMinorUnitsToNumber(\n minorUnits: bigint,\n field: string\n): number {\n if (minorUnits < 0n || minorUnits > MAX_ARCA_AMOUNT_MINOR_UNITS) {\n throw new ArcaInputError(`${field} exceeds the WSFE amount limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"at most 13 integer digits and 2 decimal places\",\n });\n }\n\n return Number(formatScaledInteger(minorUnits, 2));\n}\n\nexport function calculateVatMinorUnits(\n taxableMinorUnits: bigint,\n vatRate: SupportedVatRate,\n field: string\n): bigint {\n const basisPoints = VAT_RATE_BASIS_POINTS[vatRate];\n if (basisPoints === undefined) {\n throw new ArcaInputError(`${field} is not a supported VAT rate.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected: \"one of 0, 2.5, 5, 10.5, 21, or 27\",\n });\n }\n\n return roundHalfEvenRatio(taxableMinorUnits * basisPoints, 10_000n);\n}\n\n/**\n * Divides two non-negative integers and rounds the quotient to the nearest\n * integer, breaking exact ties toward the even neighbour.\n *\n * This is the rounding criterion the WSFE developer manual documents for the\n * service (\"Round Half Even\", section on validation tolerances), so VAT\n * derived here matches what ARCA computes for the same base and rate.\n */\nexport function roundHalfEvenRatio(\n numerator: bigint,\n denominator: bigint\n): bigint {\n if (numerator < 0n || denominator <= 0n) {\n throw new RangeError(\n \"roundHalfEvenRatio requires a non-negative numerator and a positive denominator.\"\n );\n }\n\n const quotient = numerator / denominator;\n const doubledRemainder = (numerator % denominator) * 2n;\n if (doubledRemainder > denominator) {\n return quotient + 1n;\n }\n if (doubledRemainder < denominator) {\n return quotient;\n }\n return quotient % 2n === 0n ? quotient : quotient + 1n;\n}\n\nexport function isWithinArcaTolerance(\n actualMinorUnits: bigint,\n expectedMinorUnits: bigint,\n absoluteCentAllowance = 1\n): boolean {\n const difference = absoluteBigInt(actualMinorUnits - expectedMinorUnits);\n if (difference <= BigInt(Math.max(1, absoluteCentAllowance))) {\n return true;\n }\n\n const comparisonBase = absoluteBigInt(expectedMinorUnits);\n return comparisonBase > 0n && difference * 10_000n <= comparisonBase;\n}\n\nfunction normalizeScaledNumber({\n value,\n field,\n scale,\n maximum,\n expected,\n}: {\n value: number;\n field: string;\n scale: number;\n maximum: bigint;\n expected: string;\n}): bigint {\n if (!(Number.isFinite(value) && value >= 0)) {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n const scaled = value * scale;\n const nearestInteger = Math.round(scaled);\n const representationTolerance = Math.max(\n 1e-9,\n Math.abs(scaled) * Number.EPSILON * 4\n );\n\n if (Math.abs(scaled - nearestInteger) > representationTolerance) {\n throw new ArcaInputError(\n `${field} has more precision than its ARCA field allows.`,\n {\n code: \"ARCA_INPUT_AMOUNT_PRECISION\",\n field,\n expected,\n }\n );\n }\n\n if (!Number.isSafeInteger(nearestInteger)) {\n throw new ArcaInputError(`${field} exceeds the safely supported range.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n const normalized = BigInt(nearestInteger);\n if (normalized > maximum) {\n throw new ArcaInputError(`${field} exceeds the ARCA field limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n return normalized;\n}\n\nfunction normalizeExchangeRateNumber(value: number, field: string): bigint {\n if (!(Number.isFinite(value) && value > 0)) {\n throwInvalidExchangeRate(field);\n }\n\n const scaled = value * EXCHANGE_RATE_SCALE;\n const nearestInteger = Math.round(scaled);\n const representationTolerance = Math.max(\n 1e-9,\n Math.abs(scaled) * Number.EPSILON * 4\n );\n\n if (\n Math.abs(scaled - nearestInteger) > representationTolerance ||\n !Number.isSafeInteger(nearestInteger)\n ) {\n throwInvalidExchangeRate(field);\n }\n\n return BigInt(nearestInteger);\n}\n\nfunction normalizeExchangeRateString(value: string, field: string): bigint {\n const match = value.match(/^(0|[1-9]\\d{0,3})(?:\\.(\\d{1,6}))?$/);\n if (!match) {\n throwInvalidExchangeRate(field);\n }\n\n const [, integerPart, fractionPart = \"\"] = match;\n return (\n BigInt(integerPart) * EXCHANGE_RATE_SCALE_BIGINT +\n BigInt(fractionPart.padEnd(6, \"0\"))\n );\n}\n\nfunction throwInvalidExchangeRate(field: string): never {\n throw new ArcaInputError(\n `${field} must be a positive decimal with at most 4 integer and 6 fractional digits.`,\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field,\n expected:\n \"a positive decimal with up to 4 integer and 6 fractional digits\",\n }\n );\n}\n\nfunction formatScaledInteger(\n value: bigint,\n fractionDigits: number,\n trimTrailingZeros = false\n): string {\n const scale = 10n ** BigInt(fractionDigits);\n const integerPart = value / scale;\n const fractionPart = (value % scale).toString().padStart(fractionDigits, \"0\");\n\n if (trimTrailingZeros) {\n const trimmedFraction = fractionPart.replace(/0+$/, \"\");\n return trimmedFraction.length === 0\n ? integerPart.toString()\n : `${integerPart}.${trimmedFraction}`;\n }\n\n return `${integerPart}.${fractionPart}`;\n}\n\nfunction absoluteBigInt(value: bigint): bigint {\n return value < 0n ? -value : value;\n}\n","import {\n ArcaInputError,\n ArcaInvalidSoapResponseError,\n ArcaServiceError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport {\n classifyArcaAuthenticationError,\n classifyArcaAuthenticationIssues,\n createArcaAuthenticationErrorFromEvidence,\n createArcaAuthenticationEvidence,\n executeWithAuthenticationRecovery,\n} from \"../internal/authentication\";\nimport {\n isWithinArcaTolerance,\n normalizeArcaAmountToMinorUnits,\n serializeArcaAmount,\n serializeArcaExchangeRate,\n serializeArcaPercentage,\n} from \"../internal/decimal\";\nimport type { ArcaClientConfig, ArcaRepresentedTaxId } from \"../internal/types\";\nimport type { SoapTransport } from \"../soap\";\nimport type { WsaaAuthModule } from \"../wsaa\";\nimport type {\n ArcaAuthorizationIndeterminateReason,\n ArcaAuthorizationOutcome,\n ArcaFiscalIssue,\n ArcaFiscalResultLevel,\n ArcaVoucherLookupResult,\n} from \"./fiscal-evidence\";\n\n/** Accepted public date inputs for WSFE request fields. */\nexport type WsfeDateInput =\n | `${number}${number}${number}${number}-${number}${number}-${number}${number}`\n | `${number}${number}${number}${number}${number}${number}${number}${number}`;\n\n/** An associated voucher referenced by a WSFE invoice request. */\nexport type WsfeAssociatedVoucher = {\n type: number;\n salesPoint: number;\n number: number;\n taxId?: string;\n voucherDate?: WsfeDateInput;\n};\n\n/** An associated period used by WSFE credit/debit notes without associated vouchers. */\nexport type WsfeAssociatedPeriod = {\n startDate: WsfeDateInput;\n endDate: WsfeDateInput;\n};\n\n/** A tax (tributo) item in a WSFE invoice request. */\nexport type WsfeTax = {\n id: number;\n description?: string;\n baseAmount: number;\n rate: number;\n amount: number;\n};\n\n/** A VAT rate (alícuota IVA) item in a WSFE invoice request. */\nexport type WsfeVatRate = {\n id: number;\n baseAmount: number;\n amount: number;\n};\n\n/** An optional field (campo opcional) in a WSFE invoice request. */\nexport type WsfeOptionalField = {\n id: string;\n value: string;\n};\n\n/** A buyer (comprador) in a WSFE invoice request. */\nexport type WsfeBuyer = {\n documentType: number;\n documentNumber: number;\n percentage: number;\n};\n\n/** An activity associated with a WSFE invoice request. */\nexport type WsfeActivity = {\n id: number;\n};\n\n/** Input data for authorizing a WSFE voucher. */\nexport type WsfeVoucherInput = {\n salesPoint: number;\n voucherType: number;\n concept: number;\n documentType: number;\n documentNumber: number;\n receiverVatConditionId: number;\n voucherDate: WsfeDateInput;\n totalAmount: number;\n nonTaxableAmount: number;\n netAmount: number;\n exemptAmount: number;\n taxAmount: number;\n vatAmount: number;\n currencyId: string;\n exchangeRate?: number | string;\n sameCurrencyForeignCancellation?: \"S\" | \"N\";\n serviceStartDate?: WsfeDateInput;\n serviceEndDate?: WsfeDateInput;\n paymentDueDate?: WsfeDateInput;\n associatedVouchers?: WsfeAssociatedVoucher[];\n associatedPeriod?: WsfeAssociatedPeriod;\n taxes?: WsfeTax[];\n vatRates?: WsfeVatRate[];\n optionalFields?: WsfeOptionalField[];\n buyers?: WsfeBuyer[];\n activities?: WsfeActivity[];\n};\n\n/** Input for authorizing a WSFE voucher with an explicit voucher number. */\nexport type WsfeAuthorizeVoucherInput = {\n representedTaxId?: number | string;\n data: WsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n};\n\n/** Result of a successful WSFE voucher authorization. */\nexport type WsfeAuthorizationResult = {\n cae: string;\n caeExpiry: string;\n voucherNumber: number;\n raw: Record<string, unknown>;\n};\n\n/** Structured evidence from one exact WSFE authorization attempt. */\nexport type WsfeAuthorizationOutcome = ArcaAuthorizationOutcome<\"wsfe\">;\n\n/** A point-of-sale entry returned by {@link WsfeService.getSalesPoints}. */\nexport type WsfeSalesPoint = {\n number: number;\n emissionType?: string;\n blocked?: string;\n deletedSince?: string;\n};\n\n/** Voucher details returned by {@link WsfeService.getVoucherInfo}. */\nexport type WsfeVoucherInfo = {\n voucherNumber: number;\n voucherDate?: string;\n salesPoint?: number;\n voucherType?: number;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n totalAmount?: number;\n nonTaxableAmount?: number;\n netAmount?: number;\n exemptAmount?: number;\n taxAmount?: number;\n vatAmount?: number;\n currencyId?: string;\n exchangeRate?: number;\n result?: string;\n cae?: string;\n caeExpiry?: string;\n raw: Record<string, unknown>;\n};\n\n/** Typed exact-voucher consultation result for WSFE. */\nexport type WsfeVoucherLookupResult = ArcaVoucherLookupResult<\n WsfeVoucherInfo,\n \"wsfe\"\n>;\n\nexport type WsfeCatalogEntry = {\n id: number;\n description: string;\n};\n\nexport type WsfeActivityType = WsfeCatalogEntry & {\n order: number;\n};\n\nexport type WsfeReceiverVatCondition = WsfeCatalogEntry & {\n voucherClass: string;\n};\n\nexport type WsfeCurrencyType = {\n id: string;\n description: string;\n validFrom: string;\n validTo: string;\n};\n\nexport type WsfeServerStatus = {\n appServer: string;\n dbServer: string;\n authServer: string;\n};\n\nexport type WsfeQuotation = {\n currencyId: string;\n rate: number;\n date: string;\n};\n\n/** WSFE electronic invoicing service. */\nexport type WsfeService = {\n /**\n * Attempts one exact authorization without transport retries and returns\n * structured provider evidence instead of flattening the result to throw/success.\n */\n authorizeVoucherOutcome(\n input: WsfeAuthorizeVoucherInput\n ): Promise<WsfeAuthorizationOutcome>;\n /** Authorizes a voucher with the explicit number sent as `CbteDesde` and `CbteHasta`. */\n authorizeVoucher(\n input: WsfeAuthorizeVoucherInput\n ): Promise<WsfeAuthorizationResult>;\n /** Authorizes a new voucher by fetching the next number and requesting a CAE. */\n createNextVoucher(input: {\n representedTaxId?: number | string;\n data: WsfeVoucherInput;\n forceRefresh?: boolean;\n }): Promise<WsfeAuthorizationResult>;\n /** Returns the next available voucher number for the given sales point and type. */\n getNextVoucherNumber(input: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<number>;\n /**\n * @deprecated Use `getNextVoucherNumber()` instead.\n * Returns the next available voucher number, not the last authorized one.\n */\n getLastVoucher(input: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<number>;\n /** Lists all configured points of sale for the taxpayer. */\n getSalesPoints(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeSalesPoint[]>;\n /** Lists voucher types accepted by WSFE. */\n getVoucherTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists document types accepted by WSFE. */\n getDocumentTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists concept types accepted by WSFE. */\n getConceptTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists live ARCA currency identifiers such as PES and DOL, not ISO codes. */\n getCurrencyTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCurrencyType[]>;\n /** Lists VAT rates accepted by WSFE. */\n getVatRates(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists tax types accepted by WSFE. */\n getTaxTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists optional field types accepted by WSFE. */\n getOptionalTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists activities enabled for the taxpayer. */\n getActivities(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeActivityType[]>;\n /** Lists receiver VAT condition values accepted by WSFE. */\n getReceiverVatConditions(input: {\n representedTaxId?: number | string;\n voucherClass?: string;\n forceRefresh?: boolean;\n }): Promise<WsfeReceiverVatCondition[]>;\n /** Reports WSFE backend status without requiring taxpayer authorization. */\n getServerStatus(): Promise<WsfeServerStatus>;\n /** Returns the exchange rate for a given currency. */\n getQuotation(input: {\n currencyId: string;\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeQuotation>;\n /** Retrieves details for a specific voucher. Returns `null` if not found. */\n getVoucherInfo(input: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherInfo | null>;\n /** Consults one exact voucher and normalizes WSFE error 602 to `not_found`. */\n lookupVoucher(input: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult>;\n};\n\nexport type CreateWsfeServiceOptions = {\n config: ArcaClientConfig;\n auth: WsaaAuthModule;\n soap: SoapTransport;\n};\n\ntype NormalizedWsfeAssociatedVoucher = Omit<\n WsfeAssociatedVoucher,\n \"voucherDate\"\n> & {\n voucherDate?: string;\n};\n\ntype NormalizedWsfeAssociatedPeriod = {\n startDate: string;\n endDate: string;\n};\n\ntype NormalizedWsfeTax = Omit<WsfeTax, \"baseAmount\" | \"rate\" | \"amount\"> & {\n baseAmount: string;\n rate: string;\n amount: string;\n};\n\ntype NormalizedWsfeVatRate = Omit<WsfeVatRate, \"baseAmount\" | \"amount\"> & {\n baseAmount: string;\n amount: string;\n};\n\ntype NormalizedWsfeVoucherInput = Omit<\n WsfeVoucherInput,\n | \"voucherDate\"\n | \"serviceStartDate\"\n | \"serviceEndDate\"\n | \"paymentDueDate\"\n | \"associatedVouchers\"\n | \"associatedPeriod\"\n | \"totalAmount\"\n | \"nonTaxableAmount\"\n | \"netAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatAmount\"\n | \"exchangeRate\"\n | \"taxes\"\n | \"vatRates\"\n> & {\n voucherDate: string;\n totalAmount: string;\n nonTaxableAmount: string;\n netAmount: string;\n exemptAmount: string;\n taxAmount: string;\n vatAmount: string;\n exchangeRate?: string;\n serviceStartDate?: string;\n serviceEndDate?: string;\n paymentDueDate?: string;\n associatedVouchers?: NormalizedWsfeAssociatedVoucher[];\n associatedPeriod?: NormalizedWsfeAssociatedPeriod;\n taxes?: NormalizedWsfeTax[];\n vatRates?: NormalizedWsfeVatRate[];\n};\n\n/** Creates a WSFE service instance wired with authentication and SOAP transport. */\nexport function createWsfeService(\n options: CreateWsfeServiceOptions\n): WsfeService {\n async function executeWsfeAuthenticatedRawOperation(\n operation: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {},\n retries?: number\n ) {\n const auth = await options.auth.login(\"wsfe\", {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsfe\",\n operation,\n ...(retries === undefined ? {} : { retries }),\n body: {\n Auth: createWsfeAuth(\n input.representedTaxId ?? options.config.taxId,\n auth.token,\n auth.sign\n ),\n ...body,\n },\n });\n\n return unwrapWsfeOperationEnvelope(operation, response.result);\n }\n\n function executeWsfeAuthenticatedOperation(\n operation: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {}\n ) {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation,\n forceRefresh: input.forceRefresh,\n async execute(forceRefresh) {\n const result = await executeWsfeAuthenticatedRawOperation(\n operation,\n { representedTaxId: input.representedTaxId, forceRefresh },\n body\n );\n throwForWsfeOperationErrors(operation, result);\n return result;\n },\n });\n }\n\n async function executeWsfeOperation(\n operation: string,\n body: Record<string, unknown> = {}\n ) {\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsfe\",\n operation,\n body,\n });\n\n const result = unwrapWsfeOperationEnvelope(operation, response.result);\n throwForWsfeOperationErrors(operation, result);\n return result;\n }\n\n async function getNextVoucherNumber({\n representedTaxId,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FECompUltimoAutorizado\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n PtoVta: salesPoint,\n CbteTipo: voucherType,\n }\n );\n return Number(result.CbteNro ?? 0) + 1;\n }\n\n async function getWsfeCatalog(\n operation: string,\n resultKey: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }\n ): Promise<WsfeCatalogEntry[]> {\n const result = await executeWsfeAuthenticatedOperation(operation, {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n return getWsfeResultEntries(result, resultKey).map(mapWsfeCatalogEntry);\n }\n\n function authorizeVoucher({\n representedTaxId,\n data,\n voucherNumber,\n forceRefresh,\n }: WsfeAuthorizeVoucherInput): Promise<WsfeAuthorizationResult> {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n return authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n });\n }\n\n function authorizeVoucherOutcome({\n representedTaxId,\n data,\n voucherNumber,\n forceRefresh,\n }: WsfeAuthorizeVoucherInput): Promise<WsfeAuthorizationOutcome> {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n return executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }).then(({ outcome }) => outcome);\n }\n\n function authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n allowAuthenticationRecovery,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n allowAuthenticationRecovery?: boolean;\n }): Promise<WsfeAuthorizationResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n forceRefresh,\n allowRetry: allowAuthenticationRecovery,\n execute: (attemptForceRefresh) =>\n authorizeNormalizedVoucherOnce({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function authorizeNormalizedVoucherOnce({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsfeAuthorizationResult> {\n const execution = await executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n });\n\n if (execution.error) {\n throw execution.error;\n }\n\n if (execution.outcome.kind !== \"authorized\") {\n throw createWsfeOutcomeError(execution.outcome);\n }\n\n const { cae, caeExpiry, raw } = execution.outcome;\n if (!(caeExpiry && raw)) {\n throw new ArcaServiceError(\"WSFE did not return CAE authorization data\", {\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n result: execution.outcome.result,\n resultLevel: execution.outcome.resultLevel,\n results: execution.outcome.results,\n cae,\n issues: [\n ...execution.outcome.errors,\n ...execution.outcome.observations,\n ],\n });\n }\n\n return {\n cae,\n caeExpiry,\n voucherNumber,\n raw,\n };\n }\n\n async function executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<{\n outcome: WsfeAuthorizationOutcome;\n error?: unknown;\n }> {\n const requestData = mapWsfeVoucherInput(normalizedInput, voucherNumber);\n\n try {\n const result = await executeWsfeAuthenticatedRawOperation(\n \"FECAESolicitar\",\n { representedTaxId, forceRefresh },\n {\n FeCAEReq: {\n FeCabReq: {\n CantReg: 1,\n PtoVta: normalizedInput.salesPoint,\n CbteTipo: normalizedInput.voucherType,\n },\n FeDetReq: {\n FECAEDetRequest: requestData,\n },\n },\n },\n 0\n );\n\n return {\n outcome: classifyWsfeAuthorization(result, voucherNumber),\n };\n } catch (error) {\n return {\n outcome: createWsfeIndeterminateOutcome(error),\n error,\n };\n }\n }\n\n function lookupVoucher({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation: \"FECompConsultar\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n lookupVoucherOnce({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function lookupVoucherOnce({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult> {\n const operation = \"FECompConsultar\";\n const result = await executeWsfeAuthenticatedRawOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n FeCompConsReq: {\n CbteNro: number,\n PtoVta: salesPoint,\n CbteTipo: voucherType,\n },\n }\n );\n const errors = extractWsfeGlobalIssues(result, operation);\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"602\")) {\n return {\n kind: \"not_found\",\n service: \"wsfe\",\n operation,\n errors,\n observations: [],\n raw: result,\n };\n }\n\n if (errors.length > 0) {\n throw createWsfeServiceError(operation, errors);\n }\n\n const raw = toWsfeRecord(result.ResultGet);\n if (!raw) {\n throw new ArcaServiceError(\"WSFE did not return the consulted voucher\", {\n service: \"wsfe\",\n operation,\n });\n }\n\n return {\n kind: \"found\",\n service: \"wsfe\",\n operation,\n voucher: mapWsfeVoucherInfo(raw),\n observations: [],\n raw: result,\n };\n }\n\n return {\n authorizeVoucherOutcome,\n authorizeVoucher,\n async createNextVoucher({ representedTaxId, data, forceRefresh }) {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n\n const voucherNumber = await getNextVoucherNumber({\n representedTaxId,\n salesPoint: normalizedInput.salesPoint,\n voucherType: normalizedInput.voucherType,\n forceRefresh,\n });\n\n return authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n allowAuthenticationRecovery: forceRefresh !== true,\n });\n },\n getNextVoucherNumber,\n getLastVoucher(input) {\n return getNextVoucherNumber(input);\n },\n async getSalesPoints({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetPtosVenta\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n const rawPoints = (\n result.ResultGet as Record<string, unknown> | undefined\n )?.PtoVenta;\n if (!rawPoints) {\n return [];\n }\n const entries = Array.isArray(rawPoints) ? rawPoints : [rawPoints];\n return entries.map(mapWsfeSalesPoint);\n },\n getVoucherTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposCbte\", \"CbteTipo\", input);\n },\n getDocumentTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposDoc\", \"DocTipo\", input);\n },\n getConceptTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposConcepto\", \"ConceptoTipo\", input);\n },\n async getCurrencyTypes({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetTiposMonedas\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n return getWsfeResultEntries(result, \"Moneda\").map(mapWsfeCurrencyType);\n },\n getVatRates(input) {\n return getWsfeCatalog(\"FEParamGetTiposIva\", \"IvaTipo\", input);\n },\n getTaxTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposTributos\", \"TributoTipo\", input);\n },\n getOptionalTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposOpcional\", \"OpcionalTipo\", input);\n },\n async getActivities({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetActividades\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n return getWsfeResultEntries(result, \"ActividadesTipo\").map(\n mapWsfeActivityType\n );\n },\n async getReceiverVatConditions({\n representedTaxId,\n voucherClass,\n forceRefresh,\n }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetCondicionIvaReceptor\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n ...(voucherClass === undefined ? {} : { ClaseCmp: voucherClass }),\n }\n );\n return getWsfeResultEntries(result, \"CondicionIvaReceptor\").map(\n mapWsfeReceiverVatCondition\n );\n },\n async getServerStatus() {\n const result = await executeWsfeOperation(\"FEDummy\");\n return mapWsfeServerStatus(result);\n },\n async getQuotation({ currencyId, representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetCotizacion\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n MonId: currencyId,\n }\n );\n const raw =\n (result.ResultGet as Record<string, unknown> | undefined) ?? {};\n return mapWsfeQuotation(raw);\n },\n async getVoucherInfo(input) {\n const lookup = await lookupVoucher(input);\n return lookup.kind === \"found\" ? lookup.voucher : null;\n },\n lookupVoucher,\n };\n}\n\nfunction mapWsfeVoucherInput(\n input: NormalizedWsfeVoucherInput,\n voucherNumber: number\n): Record<string, unknown> {\n const data: Record<string, unknown> = {\n Concepto: input.concept,\n DocTipo: input.documentType,\n DocNro: input.documentNumber,\n CbteDesde: voucherNumber,\n CbteHasta: voucherNumber,\n CbteFch: input.voucherDate,\n ImpTotal: input.totalAmount,\n ImpTotConc: input.nonTaxableAmount,\n ImpNeto: input.netAmount,\n ImpOpEx: input.exemptAmount,\n ImpTrib: input.taxAmount,\n ImpIVA: input.vatAmount,\n MonId: input.currencyId,\n CondicionIVAReceptorId: input.receiverVatConditionId,\n PtoVta: input.salesPoint,\n CbteTipo: input.voucherType,\n };\n\n if (input.exchangeRate !== undefined) {\n data.MonCotiz = input.exchangeRate;\n }\n\n if (\n input.currencyId !== \"PES\" &&\n input.sameCurrencyForeignCancellation !== undefined\n ) {\n data.CanMisMonExt = input.sameCurrencyForeignCancellation;\n }\n\n if (input.serviceStartDate !== undefined) {\n data.FchServDesde = input.serviceStartDate;\n }\n if (input.serviceEndDate !== undefined) {\n data.FchServHasta = input.serviceEndDate;\n }\n if (input.paymentDueDate !== undefined) {\n data.FchVtoPago = input.paymentDueDate;\n }\n\n if (input.associatedVouchers) {\n data.CbtesAsoc = {\n CbteAsoc: input.associatedVouchers.map((v) => ({\n Tipo: v.type,\n PtoVta: v.salesPoint,\n Nro: v.number,\n ...(v.taxId === undefined ? {} : { Cuit: v.taxId }),\n ...(v.voucherDate === undefined ? {} : { CbteFch: v.voucherDate }),\n })),\n };\n }\n\n if (input.associatedPeriod) {\n data.PeriodoAsoc = {\n FchDesde: input.associatedPeriod.startDate,\n FchHasta: input.associatedPeriod.endDate,\n };\n }\n\n if (input.taxes) {\n data.Tributos = {\n Tributo: input.taxes.map((t) => ({\n Id: t.id,\n ...(t.description === undefined ? {} : { Desc: t.description }),\n BaseImp: t.baseAmount,\n Alic: t.rate,\n Importe: t.amount,\n })),\n };\n }\n\n if (input.vatRates) {\n data.Iva = {\n AlicIva: input.vatRates.map((v) => ({\n Id: v.id,\n BaseImp: v.baseAmount,\n Importe: v.amount,\n })),\n };\n }\n\n if (input.optionalFields) {\n data.Opcionales = {\n Opcional: input.optionalFields.map((o) => ({\n Id: o.id,\n Valor: o.value,\n })),\n };\n }\n\n if (input.buyers) {\n data.Compradores = {\n Comprador: input.buyers.map((b) => ({\n DocTipo: b.documentType,\n DocNro: b.documentNumber,\n Porcentaje: b.percentage,\n })),\n };\n }\n\n if (input.activities) {\n data.Actividades = {\n Actividad: input.activities.map((a) => ({\n Id: a.id,\n })),\n };\n }\n\n return data;\n}\n\nfunction normalizeWsfeVoucherInput(\n input: WsfeVoucherInput\n): NormalizedWsfeVoucherInput {\n if (input.receiverVatConditionId === undefined) {\n throw new ArcaInputError(\"receiverVatConditionId is required.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"receiverVatConditionId\",\n expected: \"a receiver VAT condition accepted for the voucher class\",\n });\n }\n\n const {\n voucherDate,\n exchangeRate,\n serviceStartDate,\n serviceEndDate,\n paymentDueDate,\n associatedVouchers,\n associatedPeriod,\n taxes,\n vatRates,\n ...rest\n } = input;\n const normalizedExchangeRate = normalizeWsfeExchangeRate(input, exchangeRate);\n const normalizedAmounts = normalizeAndValidateWsfeAmounts(input);\n\n return {\n ...rest,\n ...normalizedAmounts,\n voucherDate: normalizeWsfeDateInput(voucherDate, \"voucherDate\"),\n ...(normalizedExchangeRate === undefined\n ? {}\n : { exchangeRate: normalizedExchangeRate }),\n ...(serviceStartDate === undefined\n ? {}\n : {\n serviceStartDate: normalizeWsfeDateInput(\n serviceStartDate,\n \"serviceStartDate\"\n ),\n }),\n ...(serviceEndDate === undefined\n ? {}\n : {\n serviceEndDate: normalizeWsfeDateInput(\n serviceEndDate,\n \"serviceEndDate\"\n ),\n }),\n ...(paymentDueDate === undefined\n ? {}\n : {\n paymentDueDate: normalizeWsfeDateInput(\n paymentDueDate,\n \"paymentDueDate\"\n ),\n }),\n ...(associatedVouchers === undefined\n ? {}\n : {\n associatedVouchers: associatedVouchers.map((voucher, index) => {\n const { voucherDate: associatedVoucherDate, ...associatedRest } =\n voucher;\n\n return {\n ...associatedRest,\n ...(associatedVoucherDate === undefined\n ? {}\n : {\n voucherDate: normalizeWsfeDateInput(\n associatedVoucherDate,\n `associatedVouchers[${index}].voucherDate`\n ),\n }),\n };\n }),\n }),\n ...(associatedPeriod === undefined\n ? {}\n : {\n associatedPeriod: {\n startDate: normalizeWsfeDateInput(\n associatedPeriod.startDate,\n \"associatedPeriod.startDate\"\n ),\n endDate: normalizeWsfeDateInput(\n associatedPeriod.endDate,\n \"associatedPeriod.endDate\"\n ),\n },\n }),\n ...(taxes === undefined\n ? {}\n : {\n taxes: taxes.map((tax, index) => ({\n ...tax,\n baseAmount: serializeArcaAmount(\n tax.baseAmount,\n `taxes[${index}].baseAmount`\n ),\n rate: serializeArcaPercentage(tax.rate, `taxes[${index}].rate`),\n amount: serializeArcaAmount(tax.amount, `taxes[${index}].amount`),\n })),\n }),\n ...(vatRates === undefined\n ? {}\n : {\n vatRates: vatRates.map((vatRate, index) => ({\n ...vatRate,\n baseAmount: serializeArcaAmount(\n vatRate.baseAmount,\n `vatRates[${index}].baseAmount`\n ),\n amount: serializeArcaAmount(\n vatRate.amount,\n `vatRates[${index}].amount`\n ),\n })),\n }),\n };\n}\n\nfunction normalizeAndValidateWsfeAmounts(\n input: WsfeVoucherInput\n): Pick<\n NormalizedWsfeVoucherInput,\n | \"totalAmount\"\n | \"nonTaxableAmount\"\n | \"netAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatAmount\"\n> {\n const totalAmount = normalizeArcaAmountToMinorUnits(\n input.totalAmount,\n \"totalAmount\"\n );\n const nonTaxableAmount = normalizeArcaAmountToMinorUnits(\n input.nonTaxableAmount,\n \"nonTaxableAmount\"\n );\n const netAmount = normalizeArcaAmountToMinorUnits(\n input.netAmount,\n \"netAmount\"\n );\n const exemptAmount = normalizeArcaAmountToMinorUnits(\n input.exemptAmount,\n \"exemptAmount\"\n );\n const taxAmount = normalizeArcaAmountToMinorUnits(\n input.taxAmount,\n \"taxAmount\"\n );\n const vatAmount = normalizeArcaAmountToMinorUnits(\n input.vatAmount,\n \"vatAmount\"\n );\n\n const decomposedTotal =\n nonTaxableAmount + netAmount + exemptAmount + taxAmount + vatAmount;\n assertWsfeAmountMatch(\n totalAmount,\n decomposedTotal,\n \"totalAmount\",\n \"the sum of nonTaxableAmount, netAmount, exemptAmount, taxAmount, and vatAmount\"\n );\n\n const vatRates = input.vatRates ?? [];\n if (vatAmount > 0n && vatRates.length === 0) {\n throw new ArcaInputError(\n \"vatRates is required when vatAmount is greater than zero.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"vatRates\",\n expected: \"VAT detail whose amounts reconcile with vatAmount\",\n }\n );\n }\n\n if (vatRates.length > 0) {\n const normalizedVatRates = vatRates.map((vatRate, index) => ({\n baseAmount: normalizeArcaAmountToMinorUnits(\n vatRate.baseAmount,\n `vatRates[${index}].baseAmount`\n ),\n amount: normalizeArcaAmountToMinorUnits(\n vatRate.amount,\n `vatRates[${index}].amount`\n ),\n }));\n const vatRateAmountSum = normalizedVatRates.reduce(\n (sum, vatRate) => sum + vatRate.amount,\n 0n\n );\n const vatRateBaseSum = normalizedVatRates.reduce(\n (sum, vatRate) => sum + vatRate.baseAmount,\n 0n\n );\n\n assertWsfeAmountMatch(\n vatAmount,\n vatRateAmountSum,\n \"vatAmount\",\n \"the sum of vatRates[].amount\",\n vatRates.length\n );\n if (requiresWsfeVatBaseReconciliation(input.voucherType)) {\n assertWsfeAmountMatch(\n netAmount,\n vatRateBaseSum,\n \"netAmount\",\n \"the sum of vatRates[].baseAmount\",\n vatRates.length\n );\n }\n }\n\n const taxes = input.taxes ?? [];\n if (taxAmount > 0n && taxes.length === 0) {\n throw new ArcaInputError(\n \"taxes is required when taxAmount is greater than zero.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"taxes\",\n expected: \"tax detail whose amounts reconcile with taxAmount\",\n }\n );\n }\n\n if (taxes.length > 0) {\n const taxAmountSum = taxes.reduce((sum, tax, index) => {\n normalizeArcaAmountToMinorUnits(\n tax.baseAmount,\n `taxes[${index}].baseAmount`\n );\n serializeArcaPercentage(tax.rate, `taxes[${index}].rate`);\n return (\n sum +\n normalizeArcaAmountToMinorUnits(tax.amount, `taxes[${index}].amount`)\n );\n }, 0n);\n\n assertWsfeAmountMatch(\n taxAmount,\n taxAmountSum,\n \"taxAmount\",\n \"the sum of taxes[].amount\",\n taxes.length\n );\n }\n\n return {\n totalAmount: serializeArcaAmount(input.totalAmount, \"totalAmount\"),\n nonTaxableAmount: serializeArcaAmount(\n input.nonTaxableAmount,\n \"nonTaxableAmount\"\n ),\n netAmount: serializeArcaAmount(input.netAmount, \"netAmount\"),\n exemptAmount: serializeArcaAmount(input.exemptAmount, \"exemptAmount\"),\n taxAmount: serializeArcaAmount(input.taxAmount, \"taxAmount\"),\n vatAmount: serializeArcaAmount(input.vatAmount, \"vatAmount\"),\n };\n}\n\nfunction requiresWsfeVatBaseReconciliation(voucherType: number): boolean {\n // WSFE validation 10061 exempts debit/credit notes, class C vouchers,\n // and class A vouchers with the retention legend.\n return ![2, 3, 7, 8, 11, 12, 13, 15, 52, 53].includes(voucherType);\n}\n\nfunction assertWsfeAmountMatch(\n actual: bigint,\n expectedAmount: bigint,\n field: string,\n expectedDescription: string,\n absoluteCentAllowance = 1\n) {\n if (!isWithinArcaTolerance(actual, expectedAmount, absoluteCentAllowance)) {\n throw new ArcaInputError(\n `${field} does not reconcile within ARCA's documented tolerance.`,\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field,\n expected: `within ARCA tolerance of ${expectedDescription}`,\n }\n );\n }\n}\n\nfunction normalizeWsfeExchangeRate(\n input: Pick<\n WsfeVoucherInput,\n \"currencyId\" | \"sameCurrencyForeignCancellation\"\n >,\n exchangeRate: number | string | undefined\n): string | undefined {\n if (input.currencyId === \"PES\") {\n if (\n exchangeRate !== undefined &&\n serializeArcaExchangeRate(exchangeRate, \"exchangeRate\") !== \"1\"\n ) {\n throw new ArcaInputError(\n \"exchangeRate must be 1 when currencyId is PES.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"1 when currencyId is PES\",\n }\n );\n }\n return \"1\";\n }\n\n if (exchangeRate === undefined) {\n if (input.sameCurrencyForeignCancellation === \"S\") {\n return undefined;\n }\n throw new ArcaInputError(\n \"exchangeRate is required unless sameCurrencyForeignCancellation is S for a foreign-currency voucher.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected:\n \"a positive exchange rate unless sameCurrencyForeignCancellation is S\",\n }\n );\n }\n\n return serializeArcaExchangeRate(exchangeRate, \"exchangeRate\");\n}\n\nfunction normalizeWsfeDateInput(\n value: WsfeDateInput,\n fieldName: string\n): string {\n if (typeof value !== \"string\") {\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"a YYYY-MM-DD or YYYYMMDD calendar date string\",\n }\n );\n }\n\n const normalizedValue = value.trim();\n const afipMatch = normalizedValue.match(/^(\\d{4})(\\d{2})(\\d{2})$/);\n if (afipMatch) {\n const [, year, month, day] = afipMatch;\n assertValidCalendarDate(year, month, day, fieldName);\n return normalizedValue;\n }\n\n const isoMatch = normalizedValue.match(/^(\\d{4})-(\\d{2})-(\\d{2})$/);\n if (isoMatch) {\n const [, year, month, day] = isoMatch;\n assertValidCalendarDate(year, month, day, fieldName);\n return `${year}${month}${day}`;\n }\n\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"a YYYY-MM-DD or YYYYMMDD calendar date string\",\n }\n );\n}\n\nfunction assertValidCalendarDate(\n yearInput: string,\n monthInput: string,\n dayInput: string,\n fieldName: string\n) {\n const year = Number(yearInput);\n const month = Number(monthInput);\n const day = Number(dayInput);\n const candidate = new Date(Date.UTC(year, month - 1, day));\n\n if (\n candidate.getUTCFullYear() !== year ||\n candidate.getUTCMonth() !== month - 1 ||\n candidate.getUTCDate() !== day\n ) {\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: received a non-existent calendar date`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"an existing calendar date\",\n }\n );\n }\n}\n\nfunction mapWsfeSalesPoint(raw: unknown): WsfeSalesPoint {\n const record = raw as Record<string, unknown>;\n return {\n number: Number(record.Nro ?? 0),\n ...(record.EmisionTipo === undefined\n ? {}\n : { emissionType: String(record.EmisionTipo) }),\n ...(record.Bloqueado === undefined\n ? {}\n : { blocked: String(record.Bloqueado) }),\n ...(record.FchBaja === undefined\n ? {}\n : { deletedSince: String(record.FchBaja) }),\n };\n}\n\nfunction mapWsfeCatalogEntry(raw: unknown): WsfeCatalogEntry {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n };\n}\n\nfunction mapWsfeActivityType(raw: unknown): WsfeActivityType {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n order: Number(record.Orden ?? 0),\n };\n}\n\nfunction mapWsfeReceiverVatCondition(raw: unknown): WsfeReceiverVatCondition {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n voucherClass: String(record.Cmp_Clase ?? \"\"),\n };\n}\n\nfunction mapWsfeCurrencyType(raw: unknown): WsfeCurrencyType {\n const record = raw as Record<string, unknown>;\n return {\n id: String(record.Id ?? \"\"),\n description: String(record.Desc ?? \"\"),\n validFrom: String(record.FchDesde ?? \"\"),\n validTo: String(record.FchHasta ?? \"\"),\n };\n}\n\nfunction mapWsfeServerStatus(raw: Record<string, unknown>): WsfeServerStatus {\n return {\n appServer: String(raw.AppServer ?? \"\"),\n dbServer: String(raw.DbServer ?? \"\"),\n authServer: String(raw.AuthServer ?? \"\"),\n };\n}\n\nfunction mapWsfeQuotation(raw: Record<string, unknown>): WsfeQuotation {\n return {\n currencyId: String(raw.MonId ?? \"\"),\n rate: Number(raw.MonCotiz ?? 0),\n date: String(raw.FchCotiz ?? \"\"),\n };\n}\n\nfunction mapWsfeVoucherInfo(raw: Record<string, unknown>): WsfeVoucherInfo {\n const voucher: WsfeVoucherInfo = {\n voucherNumber: Number(raw.CbteDesde ?? raw.CbteHasta ?? 0),\n raw,\n };\n\n assignWsfeValue(voucher, \"voucherDate\", normalizeWsfeString(raw.CbteFch));\n assignWsfeValue(voucher, \"salesPoint\", normalizeWsfeNumber(raw.PtoVta));\n assignWsfeValue(voucher, \"voucherType\", normalizeWsfeNumber(raw.CbteTipo));\n assignWsfeValue(voucher, \"concept\", normalizeWsfeNumber(raw.Concepto));\n assignWsfeValue(voucher, \"documentType\", normalizeWsfeNumber(raw.DocTipo));\n assignWsfeValue(voucher, \"documentNumber\", normalizeWsfeString(raw.DocNro));\n assignWsfeValue(\n voucher,\n \"receiverVatConditionId\",\n normalizeWsfeNumber(raw.CondicionIVAReceptorId)\n );\n assignWsfeValue(voucher, \"totalAmount\", normalizeWsfeNumber(raw.ImpTotal));\n assignWsfeValue(\n voucher,\n \"nonTaxableAmount\",\n normalizeWsfeNumber(raw.ImpTotConc)\n );\n assignWsfeValue(voucher, \"netAmount\", normalizeWsfeNumber(raw.ImpNeto));\n assignWsfeValue(voucher, \"exemptAmount\", normalizeWsfeNumber(raw.ImpOpEx));\n assignWsfeValue(voucher, \"taxAmount\", normalizeWsfeNumber(raw.ImpTrib));\n assignWsfeValue(voucher, \"vatAmount\", normalizeWsfeNumber(raw.ImpIVA));\n assignWsfeValue(voucher, \"currencyId\", normalizeWsfeString(raw.MonId));\n assignWsfeValue(voucher, \"exchangeRate\", normalizeWsfeNumber(raw.MonCotiz));\n assignWsfeValue(voucher, \"result\", normalizeWsfeString(raw.Resultado));\n assignWsfeValue(\n voucher,\n \"cae\",\n normalizeWsfeString(raw.CodAutorizacion ?? raw.CAE)\n );\n assignWsfeValue(\n voucher,\n \"caeExpiry\",\n normalizeWsfeString(raw.FchVto ?? raw.CAEFchVto)\n );\n\n return voucher;\n}\n\nfunction createWsfeAuth(\n representedTaxId: number | string,\n token: string,\n sign: string\n) {\n return {\n Token: token,\n Sign: sign,\n Cuit: Number.parseInt(String(representedTaxId), 10),\n };\n}\n\nfunction unwrapWsfeOperationEnvelope(\n operation: string,\n response: Record<string, unknown>\n) {\n const operationResponse = response[`${operation}Response`] as\n | Record<string, unknown>\n | undefined;\n const result = (operationResponse?.[`${operation}Result`] ??\n response[`${operation}Result`] ??\n response) as Record<string, unknown>;\n\n return result;\n}\n\nfunction throwForWsfeOperationErrors(\n operation: string,\n result: Record<string, unknown>\n) {\n const errors = extractWsfeGlobalIssues(result, operation);\n if (errors.length > 0) {\n throw createWsfeServiceError(operation, errors);\n }\n}\n\nfunction normalizeWsfeDetailResponse(result: Record<string, unknown>) {\n const detailResponse = result.FeDetResp as\n | Record<string, unknown>\n | undefined;\n const rawDetail = detailResponse?.FECAEDetResponse;\n\n if (Array.isArray(rawDetail)) {\n return (rawDetail[0] as Record<string, unknown>) ?? {};\n }\n\n return (rawDetail as Record<string, unknown> | undefined) ?? {};\n}\n\nfunction classifyWsfeAuthorization(\n result: Record<string, unknown>,\n voucherNumber: number\n): WsfeAuthorizationOutcome {\n const operation = \"FECAESolicitar\";\n const header = toWsfeRecord(result.FeCabResp) ?? {};\n const detail = normalizeWsfeDetailResponse(result);\n const headerResult = normalizeWsfeResult(header.Resultado);\n const detailResult = normalizeWsfeResult(detail.Resultado);\n const resultCode = detailResult ?? headerResult;\n const resultLevel = getWsfeResultLevel(headerResult, detailResult);\n const cae = normalizeWsfeString(detail.CAE);\n const caeExpiry = normalizeWsfeString(detail.CAEFchVto);\n const errors = extractWsfeGlobalIssues(result, operation, \"header\");\n const observations = extractWsfeObservations(\n detail,\n detailResult === \"R\" ? \"business\" : \"observation\"\n );\n const hasInfrastructureError = errors.some(\n (issue) => issue.category === \"infrastructure\"\n );\n const base = {\n service: \"wsfe\" as const,\n operation,\n results: createWsfeResults(headerResult, detailResult),\n errors,\n observations,\n raw: result,\n };\n const context: WsfeAuthorizationContext = {\n base,\n headerResult,\n detailResult,\n resultCode,\n resultLevel,\n cae,\n caeExpiry,\n };\n\n if (hasContradictoryWsfeResults(context)) {\n return createWsfeStructuredIndeterminate(context, \"contradictory_response\");\n }\n\n const authenticationError = classifyArcaAuthenticationIssues(errors, {\n service: \"wsfe\",\n operation,\n });\n if (\n authenticationError &&\n detailResult === undefined &&\n headerResult !== \"A\" &&\n headerResult !== \"O\" &&\n !cae\n ) {\n return {\n ...createWsfeStructuredIndeterminate(context, \"authentication_rejected\"),\n authentication: createArcaAuthenticationEvidence(authenticationError),\n };\n }\n\n if (hasInfrastructureError) {\n return createWsfeStructuredIndeterminate(context, \"incomplete_response\");\n }\n\n if (isAuthorizedWsfeContext(context)) {\n return {\n ...base,\n kind: \"authorized\",\n result: \"A\",\n resultLevel: \"detail\",\n cae: context.cae,\n caeExpiry: context.caeExpiry,\n voucherNumber,\n };\n }\n\n if (isRejectedWsfeDetailContext(context)) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"detail\",\n };\n }\n\n if (isRejectedWsfeHeaderContext(context)) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"header\",\n };\n }\n\n return createWsfeStructuredIndeterminate(\n context,\n hasWsfeCaeContradiction(context)\n ? \"contradictory_response\"\n : \"incomplete_response\"\n );\n}\n\ntype WsfeAuthorizationContext = {\n base: {\n service: \"wsfe\";\n operation: string;\n results: { header?: string; detail?: string };\n errors: ArcaFiscalIssue[];\n observations: ArcaFiscalIssue[];\n raw: Record<string, unknown>;\n };\n headerResult?: string;\n detailResult?: string;\n resultCode?: string;\n resultLevel?: ArcaFiscalResultLevel;\n cae?: string;\n caeExpiry?: string;\n};\n\nfunction getWsfeResultLevel(\n headerResult?: string,\n detailResult?: string\n): ArcaFiscalResultLevel | undefined {\n if (detailResult) {\n return \"detail\";\n }\n return headerResult ? \"header\" : undefined;\n}\n\nfunction hasContradictoryWsfeResults(context: WsfeAuthorizationContext) {\n return Boolean(\n context.headerResult &&\n context.detailResult &&\n context.headerResult !== context.detailResult\n );\n}\n\nfunction isAuthorizedWsfeContext(\n context: WsfeAuthorizationContext\n): context is WsfeAuthorizationContext & { cae: string; caeExpiry: string } {\n return Boolean(\n context.detailResult === \"A\" &&\n context.headerResult !== \"R\" &&\n context.base.errors.length === 0 &&\n context.cae &&\n context.caeExpiry\n );\n}\n\nfunction isRejectedWsfeDetailContext(context: WsfeAuthorizationContext) {\n return (\n context.detailResult === \"R\" && context.headerResult !== \"A\" && !context.cae\n );\n}\n\nfunction isRejectedWsfeHeaderContext(context: WsfeAuthorizationContext) {\n return (\n context.headerResult === \"R\" &&\n context.detailResult === undefined &&\n !context.cae &&\n context.base.errors.length > 0 &&\n context.base.errors.every((issue) => issue.category === \"business\")\n );\n}\n\nfunction hasWsfeCaeContradiction(context: WsfeAuthorizationContext) {\n return (\n (context.resultCode === \"A\" || context.resultCode === \"R\") &&\n Boolean(context.cae)\n );\n}\n\nfunction createWsfeStructuredIndeterminate(\n context: WsfeAuthorizationContext,\n reason: ArcaAuthorizationIndeterminateReason\n): Extract<WsfeAuthorizationOutcome, { kind: \"indeterminate\" }> {\n const outcome: Extract<WsfeAuthorizationOutcome, { kind: \"indeterminate\" }> =\n {\n ...context.base,\n kind: \"indeterminate\",\n reason,\n };\n assignWsfeValue(outcome, \"result\", context.resultCode);\n assignWsfeValue(outcome, \"resultLevel\", context.resultLevel);\n assignWsfeValue(outcome, \"cae\", context.cae);\n assignWsfeValue(outcome, \"caeExpiry\", context.caeExpiry);\n return outcome;\n}\n\nfunction createWsfeResults(headerResult?: string, detailResult?: string) {\n const results: { header?: string; detail?: string } = {};\n assignWsfeValue(results, \"header\", headerResult);\n assignWsfeValue(results, \"detail\", detailResult);\n return results;\n}\n\nfunction createWsfeIndeterminateOutcome(\n error: unknown\n): WsfeAuthorizationOutcome {\n const authenticationError = classifyArcaAuthenticationError(error, {\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n });\n return {\n kind: \"indeterminate\",\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n results: {},\n reason: authenticationError\n ? \"authentication_rejected\"\n : getArcaIndeterminateReason(error),\n ...(authenticationError\n ? {\n authentication: createArcaAuthenticationEvidence(authenticationError),\n }\n : {}),\n errors: [],\n observations: [],\n };\n}\n\nfunction getArcaIndeterminateReason(\n error: unknown\n): ArcaAuthorizationIndeterminateReason {\n if (error instanceof ArcaTransportError) {\n return \"transport_error\";\n }\n if (error instanceof ArcaSoapFaultError) {\n return \"soap_fault\";\n }\n if (error instanceof ArcaInvalidSoapResponseError) {\n return \"invalid_response\";\n }\n return \"unexpected_error\";\n}\n\nfunction createWsfeOutcomeError(\n outcome: Exclude<WsfeAuthorizationOutcome, { kind: \"authorized\" }>\n) {\n if (outcome.kind === \"indeterminate\" && outcome.authentication) {\n return createArcaAuthenticationErrorFromEvidence(outcome.authentication, {\n service: \"wsfe\",\n operation: outcome.operation,\n });\n }\n\n const issues = [...outcome.errors, ...outcome.observations];\n const firstIssue = issues[0];\n const message = firstIssue\n ? formatWsfeIssue(firstIssue)\n : outcome.kind === \"rejected\"\n ? \"WSFE rejected the voucher authorization\"\n : outcome.result === \"A\"\n ? \"WSFE did not return CAE authorization data\"\n : \"WSFE did not return conclusive voucher authorization data\";\n\n return new ArcaServiceError(message, {\n service: \"wsfe\",\n operation: outcome.operation,\n ...(firstIssue?.code === undefined ? {} : { serviceCode: firstIssue.code }),\n ...(outcome.result === undefined ? {} : { result: outcome.result }),\n ...(outcome.resultLevel === undefined\n ? {}\n : { resultLevel: outcome.resultLevel }),\n results: outcome.results,\n ...(outcome.kind === \"indeterminate\" && outcome.cae\n ? { cae: outcome.cae }\n : {}),\n issues,\n });\n}\n\nfunction createWsfeServiceError(operation: string, issues: ArcaFiscalIssue[]) {\n const authenticationError = classifyArcaAuthenticationIssues(issues, {\n service: \"wsfe\",\n operation,\n });\n if (authenticationError) {\n return authenticationError;\n }\n\n const firstIssue = issues[0];\n return new ArcaServiceError(\n firstIssue ? formatWsfeIssue(firstIssue) : \"WSFE returned a service error\",\n {\n service: \"wsfe\",\n operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n issues,\n }\n );\n}\n\nfunction extractWsfeGlobalIssues(\n result: Record<string, unknown>,\n operation: string,\n resultLevel?: ArcaFiscalResultLevel\n): ArcaFiscalIssue[] {\n const errorsContainer = toWsfeRecord(result.Errors);\n return normalizeWsfeIssueEntries(errorsContainer?.Err).map((entry) => ({\n service: \"wsfe\",\n operation,\n source: \"error\",\n category:\n operation === \"FECAESolicitar\" &&\n WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES.has(entry.code ?? \"\")\n ? \"infrastructure\"\n : operation === \"FECAESolicitar\"\n ? \"business\"\n : \"unknown\",\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n ...(resultLevel === undefined ? {} : { resultLevel }),\n }));\n}\n\nfunction extractWsfeObservations(\n detail: Record<string, unknown>,\n category: ArcaFiscalIssue[\"category\"]\n): ArcaFiscalIssue[] {\n const observationsContainer = toWsfeRecord(detail.Observaciones);\n return normalizeWsfeIssueEntries(observationsContainer?.Obs).map((entry) => ({\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n source: \"observation\",\n category,\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n resultLevel: \"detail\",\n }));\n}\n\nfunction normalizeWsfeIssueEntries(rawErrors: unknown) {\n const entries = Array.isArray(rawErrors)\n ? rawErrors\n : rawErrors\n ? [rawErrors]\n : [];\n\n return entries\n .map((entry) => entry as Record<string, unknown>)\n .map((entry) => {\n const code = entry.Code ?? entry.code;\n const message = entry.Msg ?? entry.msg ?? \"Unknown WSFE error\";\n return {\n ...(code === undefined ? {} : { code: String(code) }),\n message: String(message),\n };\n });\n}\n\nfunction formatWsfeIssue(issue: ArcaFiscalIssue) {\n return issue.code ? `(${issue.code}) ${issue.message}` : issue.message;\n}\n\nfunction normalizeWsfeResult(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim().toUpperCase();\n return normalized || undefined;\n}\n\nfunction normalizeWsfeString(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const normalized = String(value).trim();\n return normalized || undefined;\n}\n\nfunction normalizeWsfeNumber(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const normalized = Number(value);\n return Number.isFinite(normalized) ? normalized : undefined;\n}\n\nfunction assignWsfeValue<TTarget, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined\n) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n\nfunction toWsfeRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nconst WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES = new Set([\n \"500\",\n \"501\",\n \"502\",\n \"600\",\n \"601\",\n]);\n\nfunction getWsfeResultEntries(\n result: Record<string, unknown>,\n key: string\n): Record<string, unknown>[] {\n const rawEntries = (\n result.ResultGet as Record<string, unknown> | undefined\n )?.[key];\n if (!rawEntries) {\n return [];\n }\n\n return (Array.isArray(rawEntries) ? rawEntries : [rawEntries]).map(\n (entry) => entry as Record<string, unknown>\n );\n}\n","import {\n ARCA_CURRENCY_IDS,\n ARCA_VAT_RATES,\n ARCA_VOUCHER_TYPES,\n} from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n calculateVatMinorUnits,\n type SupportedVatRate,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport type { WsfeDateInput, WsfeVatRate, WsfeVoucherInput } from \"./wsfe\";\n\nexport type WsfeBuilderCurrencyInput =\n | {\n currency?: \"ARS\";\n exchangeRate?: never;\n sameCurrencyForeignCancellation?: never;\n }\n | {\n currency: \"USD\";\n exchangeRate: string;\n sameCurrencyForeignCancellation?: false;\n }\n | {\n currency: \"USD\";\n exchangeRate?: never;\n sameCurrencyForeignCancellation: true;\n };\n\nexport type WsfeBuilderVatRate = SupportedVatRate;\n\ntype WsfeInvoiceBuilderBaseInput = {\n salesPoint: number;\n concept: number;\n documentType: number;\n documentNumber: number;\n receiverVatConditionId: number;\n voucherDate: WsfeDateInput;\n serviceStartDate?: WsfeDateInput;\n serviceEndDate?: WsfeDateInput;\n paymentDueDate?: WsfeDateInput;\n};\n\nexport type BuildFacturaBInput = WsfeInvoiceBuilderBaseInput &\n WsfeBuilderCurrencyInput & {\n /** Positive integer currency minor units forming the taxable base. */\n taxableAmount: number;\n vatRate: WsfeBuilderVatRate;\n };\n\nexport type BuildFacturaCInput = WsfeInvoiceBuilderBaseInput &\n WsfeBuilderCurrencyInput & {\n amount: number;\n };\n\nconst VAT_RATE_IDS: Record<SupportedVatRate, number> = {\n 0: ARCA_VAT_RATES.IVA_0,\n 2.5: ARCA_VAT_RATES.IVA_2_5,\n 5: ARCA_VAT_RATES.IVA_5,\n 10.5: ARCA_VAT_RATES.IVA_10_5,\n 21: ARCA_VAT_RATES.IVA_21,\n 27: ARCA_VAT_RATES.IVA_27,\n};\n\n/** Builds a narrow Factura B exact WSFE input from integer currency minor units. */\nexport function buildFacturaB(input: BuildFacturaBInput): WsfeVoucherInput {\n const taxableMinorUnits = assertArcaMinorUnits(\n input.taxableAmount,\n \"taxableAmount\"\n );\n if (taxableMinorUnits === 0n) {\n throw new ArcaInputError(\n \"taxableAmount must be greater than zero for Factura B.\",\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field: \"taxableAmount\",\n expected: \"a positive safe integer in currency minor units\",\n }\n );\n }\n\n const vatMinorUnits = calculateVatMinorUnits(\n taxableMinorUnits,\n input.vatRate,\n \"vatRate\"\n );\n const totalMinorUnits = taxableMinorUnits + vatMinorUnits;\n const vatRateId = VAT_RATE_IDS[input.vatRate];\n\n if (vatRateId === undefined) {\n throw new ArcaInputError(\"vatRate is not a supported VAT rate.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"vatRate\",\n expected: \"one of 0, 2.5, 5, 10.5, 21, or 27\",\n });\n }\n\n if (input.vatRate !== 0 && vatMinorUnits === 0n) {\n throw new ArcaInputError(\n \"taxableAmount is too small to produce VAT at the selected positive vatRate.\",\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field: \"taxableAmount\",\n expected:\n \"an amount that rounds to at least one currency minor unit of VAT for a positive vatRate\",\n }\n );\n }\n\n const vatRates: WsfeVatRate[] = [\n Object.freeze({\n id: vatRateId,\n baseAmount: arcaMinorUnitsToNumber(taxableMinorUnits, \"taxableAmount\"),\n amount: arcaMinorUnitsToNumber(vatMinorUnits, \"vatAmount\"),\n }),\n ];\n Object.freeze(vatRates);\n\n return Object.freeze({\n ...buildCommonExactInput(input),\n voucherType: ARCA_VOUCHER_TYPES.FACTURA_B,\n totalAmount: arcaMinorUnitsToNumber(totalMinorUnits, \"totalAmount\"),\n nonTaxableAmount: 0,\n netAmount: arcaMinorUnitsToNumber(taxableMinorUnits, \"taxableAmount\"),\n exemptAmount: 0,\n taxAmount: 0,\n vatAmount: arcaMinorUnitsToNumber(vatMinorUnits, \"vatAmount\"),\n vatRates,\n });\n}\n\n/** Builds a narrow Factura C exact WSFE input from integer currency minor units. */\nexport function buildFacturaC(input: BuildFacturaCInput): WsfeVoucherInput {\n const amountMinorUnits = assertArcaMinorUnits(input.amount, \"amount\");\n const amount = arcaMinorUnitsToNumber(amountMinorUnits, \"amount\");\n\n return Object.freeze({\n ...buildCommonExactInput(input),\n voucherType: ARCA_VOUCHER_TYPES.FACTURA_C,\n totalAmount: amount,\n nonTaxableAmount: 0,\n // ARCA defines ImpNeto as the subtotal for class C vouchers.\n netAmount: amount,\n exemptAmount: 0,\n taxAmount: 0,\n vatAmount: 0,\n });\n}\n\nfunction buildCommonExactInput(\n input: WsfeInvoiceBuilderBaseInput & WsfeBuilderCurrencyInput\n): Pick<\n WsfeVoucherInput,\n | \"salesPoint\"\n | \"concept\"\n | \"documentType\"\n | \"documentNumber\"\n | \"receiverVatConditionId\"\n | \"voucherDate\"\n | \"currencyId\"\n | \"exchangeRate\"\n | \"sameCurrencyForeignCancellation\"\n | \"serviceStartDate\"\n | \"serviceEndDate\"\n | \"paymentDueDate\"\n> {\n return {\n salesPoint: input.salesPoint,\n concept: input.concept,\n documentType: input.documentType,\n documentNumber: input.documentNumber,\n receiverVatConditionId: input.receiverVatConditionId,\n voucherDate: input.voucherDate,\n ...normalizeBuilderCurrency(input),\n ...(input.serviceStartDate === undefined\n ? {}\n : { serviceStartDate: input.serviceStartDate }),\n ...(input.serviceEndDate === undefined\n ? {}\n : { serviceEndDate: input.serviceEndDate }),\n ...(input.paymentDueDate === undefined\n ? {}\n : { paymentDueDate: input.paymentDueDate }),\n };\n}\n\nfunction normalizeBuilderCurrency(\n input: WsfeBuilderCurrencyInput\n): Pick<\n WsfeVoucherInput,\n \"currencyId\" | \"exchangeRate\" | \"sameCurrencyForeignCancellation\"\n> {\n const unsafeInput = input as {\n currency?: string;\n exchangeRate?: unknown;\n sameCurrencyForeignCancellation?: unknown;\n };\n const currency = unsafeInput.currency ?? \"ARS\";\n\n if (\n unsafeInput.sameCurrencyForeignCancellation !== undefined &&\n typeof unsafeInput.sameCurrencyForeignCancellation !== \"boolean\"\n ) {\n throw new ArcaInputError(\n \"sameCurrencyForeignCancellation must be a boolean when provided.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"sameCurrencyForeignCancellation\",\n expected: \"true, false, or omitted\",\n }\n );\n }\n\n if (currency === \"ARS\") {\n if (unsafeInput.exchangeRate !== undefined) {\n throw new ArcaInputError(\n \"exchangeRate must be omitted when currency is ARS.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"omitted when currency is ARS\",\n }\n );\n }\n if (unsafeInput.sameCurrencyForeignCancellation !== undefined) {\n throw new ArcaInputError(\n \"sameCurrencyForeignCancellation applies only when currency is USD.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"sameCurrencyForeignCancellation\",\n expected: \"omitted when currency is ARS\",\n }\n );\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.ARS,\n exchangeRate: \"1\",\n };\n }\n\n if (currency !== \"USD\") {\n throw new ArcaInputError(\"currency is not supported by this builder.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"currency\",\n expected: \"ARS or USD\",\n });\n }\n\n if (unsafeInput.sameCurrencyForeignCancellation === true) {\n if (unsafeInput.exchangeRate !== undefined) {\n throw new ArcaInputError(\n \"exchangeRate must be omitted for same-currency foreign cancellation.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"omitted when sameCurrencyForeignCancellation is true\",\n }\n );\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.USD,\n sameCurrencyForeignCancellation: \"S\",\n };\n }\n\n if (typeof unsafeInput.exchangeRate !== \"string\") {\n throw new ArcaInputError(\"exchangeRate is required for USD invoices.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected:\n \"a decimal string unless sameCurrencyForeignCancellation is true\",\n });\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.USD,\n exchangeRate: serializeArcaExchangeRate(\n unsafeInput.exchangeRate,\n \"exchangeRate\"\n ),\n ...(unsafeInput.sameCurrencyForeignCancellation === false\n ? { sameCurrencyForeignCancellation: \"N\" as const }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,eAAe;AACrB,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,mBAAmB;AAGzB,IAAM,8BAA8B;AAEpC,IAAM,gCAAgC;AAEtC,IAAM,iCAAiC;AAKvC,IAAM,wBAA0D;AAAA,EAC9D,GAAG;AAAA,EACH,KAAK;AAAA,EACL,GAAG;AAAA,EACH,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,IAAI;AACN;AAEO,SAAS,gCACd,OACA,OACQ;AACR,SAAO,sBAAsB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA,EACZ,CAAC;AACH;AAEO,SAAS,oBAAoB,OAAe,OAAuB;AACxE,SAAO,oBAAoB,gCAAgC,OAAO,KAAK,GAAG,CAAC;AAC7E;AAMO,SAAS,wBAAwB,OAAe,OAAuB;AAC5E,QAAM,SAAS,sBAAsB;AAAA,IACnC;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA,EACZ,CAAC;AACD,SAAO,oBAAoB,QAAQ,CAAC;AACtC;AAEO,SAAS,0BACd,OACA,OACQ;AACR,QAAM,SACJ,OAAO,UAAU,WACb,4BAA4B,OAAO,KAAK,IACxC,4BAA4B,OAAO,KAAK;AAE9C,MAAI,UAAU,MAAM,SAAS,+BAA+B;AAC1D,6BAAyB,KAAK;AAAA,EAChC;AAEA,SAAO,oBAAoB,QAAQ,GAAG,IAAI;AAC5C;AAEO,SAAS,qBAAqB,OAAe,OAAuB;AACzE,MAAI,EAAE,OAAO,cAAc,KAAK,K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,MAAM;AAAA,UACN,OAAO;AAAA,UACP,UAAU;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,YAAY,kBAAkB;AAAA,MAC9B,iCAAiC;AAAA,IACnC;AAAA,EACF;AAEA,MAAI,OAAO,YAAY,iBAAiB,UAAU;AAChD,UAAM,IAAI,eAAe,8CAA8C;AAAA,MACrE,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UACE;AAAA,IACJ,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,YAAY,kBAAkB;AAAA,IAC9B,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ;AAAA,IACF;AAAA,IACA,GAAI,YAAY,oCAAoC,QAChD,EAAE,iCAAiC,IAAa,IAChD,CAAC;AAAA,EACP;AACF;","names":[]}
package/dist/index.mjs CHANGED
@@ -5,11 +5,11 @@ import {
5
5
  buildFacturaB,
6
6
  buildFacturaC,
7
7
  createWsfeService
8
- } from "./chunk-C55KOV5N.mjs";
8
+ } from "./chunk-OHHXHYLV.mjs";
9
9
  import "./chunk-VVY2LZIZ.mjs";
10
10
  import {
11
11
  createWsmtxcaService
12
- } from "./chunk-PKE4Z4GE.mjs";
12
+ } from "./chunk-A3C3Y5PI.mjs";
13
13
  import "./chunk-IOKZX6CA.mjs";
14
14
  import {
15
15
  ArcaAuthenticationError,
package/dist/wsfe.mjs CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  buildFacturaB,
3
3
  buildFacturaC,
4
4
  createWsfeService
5
- } from "./chunk-C55KOV5N.mjs";
5
+ } from "./chunk-OHHXHYLV.mjs";
6
6
  import "./chunk-VVY2LZIZ.mjs";
7
7
  import "./chunk-IOKZX6CA.mjs";
8
8
  import "./chunk-MBWOFO67.mjs";
package/dist/wsmtxca.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createWsmtxcaService
3
- } from "./chunk-PKE4Z4GE.mjs";
3
+ } from "./chunk-A3C3Y5PI.mjs";
4
4
  import "./chunk-IOKZX6CA.mjs";
5
5
  import "./chunk-MBWOFO67.mjs";
6
6
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "facturas",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "Node.js client for ARCA services including WSFE, WSMTXCA, and padron lookups.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/decimal.ts","../src/services/wsfe.ts","../src/services/wsfe-builders.ts"],"sourcesContent":["import { ArcaInputError } from \"../errors\";\n\nconst AMOUNT_SCALE = 100;\nconst EXCHANGE_RATE_SCALE = 1_000_000;\nconst EXCHANGE_RATE_SCALE_BIGINT = 1_000_000n;\nconst PERCENTAGE_SCALE = 100;\n\n// WSFE documents amount fields as 13 integer digits plus 2 decimals.\nconst MAX_ARCA_AMOUNT_MINOR_UNITS = 999_999_999_999_999n;\n// MonCotiz is documented as 4 integer digits plus 6 decimals.\nconst MAX_ARCA_EXCHANGE_RATE_SCALED = 9_999_999_999n;\n// Tributo.Alic is documented as 3 integer digits plus 2 decimals.\nconst MAX_ARCA_PERCENTAGE_HUNDREDTHS = 99_999n;\n\nexport const SUPPORTED_VAT_RATES = [0, 2.5, 5, 10.5, 21, 27] as const;\nexport type SupportedVatRate = (typeof SUPPORTED_VAT_RATES)[number];\n\nconst VAT_RATE_BASIS_POINTS: Record<SupportedVatRate, bigint> = {\n 0: 0n,\n 2.5: 250n,\n 5: 500n,\n 10.5: 1050n,\n 21: 2100n,\n 27: 2700n,\n};\n\nexport function normalizeArcaAmountToMinorUnits(\n value: number,\n field: string\n): bigint {\n return normalizeScaledNumber({\n value,\n field,\n scale: AMOUNT_SCALE,\n maximum: MAX_ARCA_AMOUNT_MINOR_UNITS,\n expected: \"a finite non-negative amount with at most 2 decimal places\",\n });\n}\n\nexport function serializeArcaAmount(value: number, field: string): string {\n return formatScaledInteger(normalizeArcaAmountToMinorUnits(value, field), 2);\n}\n\nexport function serializeArcaMinorUnits(value: number, field: string): string {\n return formatScaledInteger(assertArcaMinorUnits(value, field), 2);\n}\n\nexport function serializeArcaPercentage(value: number, field: string): string {\n const scaled = normalizeScaledNumber({\n value,\n field,\n scale: PERCENTAGE_SCALE,\n maximum: MAX_ARCA_PERCENTAGE_HUNDREDTHS,\n expected: \"a finite non-negative percentage with at most 2 decimal places\",\n });\n return formatScaledInteger(scaled, 2);\n}\n\nexport function serializeArcaExchangeRate(\n value: number | string,\n field: string\n): string {\n const scaled =\n typeof value === \"number\"\n ? normalizeExchangeRateNumber(value, field)\n : normalizeExchangeRateString(value, field);\n\n if (scaled <= 0n || scaled > MAX_ARCA_EXCHANGE_RATE_SCALED) {\n throwInvalidExchangeRate(field);\n }\n\n return formatScaledInteger(scaled, 6, true);\n}\n\nexport function assertArcaMinorUnits(value: number, field: string): bigint {\n if (!(Number.isSafeInteger(value) && value >= 0)) {\n throw new ArcaInputError(\n `${field} must be a non-negative safe integer in currency minor units.`,\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"a non-negative safe integer in currency minor units\",\n }\n );\n }\n\n const minorUnits = BigInt(value);\n if (minorUnits > MAX_ARCA_AMOUNT_MINOR_UNITS) {\n throw new ArcaInputError(`${field} exceeds the WSFE amount limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"at most 13 integer digits and 2 decimal places\",\n });\n }\n\n return minorUnits;\n}\n\nexport function arcaMinorUnitsToNumber(\n minorUnits: bigint,\n field: string\n): number {\n if (minorUnits < 0n || minorUnits > MAX_ARCA_AMOUNT_MINOR_UNITS) {\n throw new ArcaInputError(`${field} exceeds the WSFE amount limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected: \"at most 13 integer digits and 2 decimal places\",\n });\n }\n\n return Number(formatScaledInteger(minorUnits, 2));\n}\n\nexport function calculateVatMinorUnits(\n taxableMinorUnits: bigint,\n vatRate: SupportedVatRate,\n field: string\n): bigint {\n const basisPoints = VAT_RATE_BASIS_POINTS[vatRate];\n if (basisPoints === undefined) {\n throw new ArcaInputError(`${field} is not a supported VAT rate.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected: \"one of 0, 2.5, 5, 10.5, 21, or 27\",\n });\n }\n\n // Adding half the denominator implements deterministic half-up rounding.\n return (taxableMinorUnits * basisPoints + 5000n) / 10_000n;\n}\n\nexport function isWithinArcaTolerance(\n actualMinorUnits: bigint,\n expectedMinorUnits: bigint,\n absoluteCentAllowance = 1\n): boolean {\n const difference = absoluteBigInt(actualMinorUnits - expectedMinorUnits);\n if (difference <= BigInt(Math.max(1, absoluteCentAllowance))) {\n return true;\n }\n\n const comparisonBase = absoluteBigInt(expectedMinorUnits);\n return comparisonBase > 0n && difference * 10_000n <= comparisonBase;\n}\n\nfunction normalizeScaledNumber({\n value,\n field,\n scale,\n maximum,\n expected,\n}: {\n value: number;\n field: string;\n scale: number;\n maximum: bigint;\n expected: string;\n}): bigint {\n if (!(Number.isFinite(value) && value >= 0)) {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n const scaled = value * scale;\n const nearestInteger = Math.round(scaled);\n const representationTolerance = Math.max(\n 1e-9,\n Math.abs(scaled) * Number.EPSILON * 4\n );\n\n if (Math.abs(scaled - nearestInteger) > representationTolerance) {\n throw new ArcaInputError(\n `${field} has more precision than its ARCA field allows.`,\n {\n code: \"ARCA_INPUT_AMOUNT_PRECISION\",\n field,\n expected,\n }\n );\n }\n\n if (!Number.isSafeInteger(nearestInteger)) {\n throw new ArcaInputError(`${field} exceeds the safely supported range.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n const normalized = BigInt(nearestInteger);\n if (normalized > maximum) {\n throw new ArcaInputError(`${field} exceeds the ARCA field limit.`, {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field,\n expected,\n });\n }\n\n return normalized;\n}\n\nfunction normalizeExchangeRateNumber(value: number, field: string): bigint {\n if (!(Number.isFinite(value) && value > 0)) {\n throwInvalidExchangeRate(field);\n }\n\n const scaled = value * EXCHANGE_RATE_SCALE;\n const nearestInteger = Math.round(scaled);\n const representationTolerance = Math.max(\n 1e-9,\n Math.abs(scaled) * Number.EPSILON * 4\n );\n\n if (\n Math.abs(scaled - nearestInteger) > representationTolerance ||\n !Number.isSafeInteger(nearestInteger)\n ) {\n throwInvalidExchangeRate(field);\n }\n\n return BigInt(nearestInteger);\n}\n\nfunction normalizeExchangeRateString(value: string, field: string): bigint {\n const match = value.match(/^(0|[1-9]\\d{0,3})(?:\\.(\\d{1,6}))?$/);\n if (!match) {\n throwInvalidExchangeRate(field);\n }\n\n const [, integerPart, fractionPart = \"\"] = match;\n return (\n BigInt(integerPart) * EXCHANGE_RATE_SCALE_BIGINT +\n BigInt(fractionPart.padEnd(6, \"0\"))\n );\n}\n\nfunction throwInvalidExchangeRate(field: string): never {\n throw new ArcaInputError(\n `${field} must be a positive decimal with at most 4 integer and 6 fractional digits.`,\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field,\n expected:\n \"a positive decimal with up to 4 integer and 6 fractional digits\",\n }\n );\n}\n\nfunction formatScaledInteger(\n value: bigint,\n fractionDigits: number,\n trimTrailingZeros = false\n): string {\n const scale = 10n ** BigInt(fractionDigits);\n const integerPart = value / scale;\n const fractionPart = (value % scale).toString().padStart(fractionDigits, \"0\");\n\n if (trimTrailingZeros) {\n const trimmedFraction = fractionPart.replace(/0+$/, \"\");\n return trimmedFraction.length === 0\n ? integerPart.toString()\n : `${integerPart}.${trimmedFraction}`;\n }\n\n return `${integerPart}.${fractionPart}`;\n}\n\nfunction absoluteBigInt(value: bigint): bigint {\n return value < 0n ? -value : value;\n}\n","import {\n ArcaInputError,\n ArcaInvalidSoapResponseError,\n ArcaServiceError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport {\n classifyArcaAuthenticationError,\n classifyArcaAuthenticationIssues,\n createArcaAuthenticationErrorFromEvidence,\n createArcaAuthenticationEvidence,\n executeWithAuthenticationRecovery,\n} from \"../internal/authentication\";\nimport {\n isWithinArcaTolerance,\n normalizeArcaAmountToMinorUnits,\n serializeArcaAmount,\n serializeArcaExchangeRate,\n serializeArcaPercentage,\n} from \"../internal/decimal\";\nimport type { ArcaClientConfig, ArcaRepresentedTaxId } from \"../internal/types\";\nimport type { SoapTransport } from \"../soap\";\nimport type { WsaaAuthModule } from \"../wsaa\";\nimport type {\n ArcaAuthorizationIndeterminateReason,\n ArcaAuthorizationOutcome,\n ArcaFiscalIssue,\n ArcaFiscalResultLevel,\n ArcaVoucherLookupResult,\n} from \"./fiscal-evidence\";\n\n/** Accepted public date inputs for WSFE request fields. */\nexport type WsfeDateInput =\n | `${number}${number}${number}${number}-${number}${number}-${number}${number}`\n | `${number}${number}${number}${number}${number}${number}${number}${number}`;\n\n/** An associated voucher referenced by a WSFE invoice request. */\nexport type WsfeAssociatedVoucher = {\n type: number;\n salesPoint: number;\n number: number;\n taxId?: string;\n voucherDate?: WsfeDateInput;\n};\n\n/** An associated period used by WSFE credit/debit notes without associated vouchers. */\nexport type WsfeAssociatedPeriod = {\n startDate: WsfeDateInput;\n endDate: WsfeDateInput;\n};\n\n/** A tax (tributo) item in a WSFE invoice request. */\nexport type WsfeTax = {\n id: number;\n description?: string;\n baseAmount: number;\n rate: number;\n amount: number;\n};\n\n/** A VAT rate (alícuota IVA) item in a WSFE invoice request. */\nexport type WsfeVatRate = {\n id: number;\n baseAmount: number;\n amount: number;\n};\n\n/** An optional field (campo opcional) in a WSFE invoice request. */\nexport type WsfeOptionalField = {\n id: string;\n value: string;\n};\n\n/** A buyer (comprador) in a WSFE invoice request. */\nexport type WsfeBuyer = {\n documentType: number;\n documentNumber: number;\n percentage: number;\n};\n\n/** An activity associated with a WSFE invoice request. */\nexport type WsfeActivity = {\n id: number;\n};\n\n/** Input data for authorizing a WSFE voucher. */\nexport type WsfeVoucherInput = {\n salesPoint: number;\n voucherType: number;\n concept: number;\n documentType: number;\n documentNumber: number;\n receiverVatConditionId: number;\n voucherDate: WsfeDateInput;\n totalAmount: number;\n nonTaxableAmount: number;\n netAmount: number;\n exemptAmount: number;\n taxAmount: number;\n vatAmount: number;\n currencyId: string;\n exchangeRate?: number | string;\n sameCurrencyForeignCancellation?: \"S\" | \"N\";\n serviceStartDate?: WsfeDateInput;\n serviceEndDate?: WsfeDateInput;\n paymentDueDate?: WsfeDateInput;\n associatedVouchers?: WsfeAssociatedVoucher[];\n associatedPeriod?: WsfeAssociatedPeriod;\n taxes?: WsfeTax[];\n vatRates?: WsfeVatRate[];\n optionalFields?: WsfeOptionalField[];\n buyers?: WsfeBuyer[];\n activities?: WsfeActivity[];\n};\n\n/** Input for authorizing a WSFE voucher with an explicit voucher number. */\nexport type WsfeAuthorizeVoucherInput = {\n representedTaxId?: number | string;\n data: WsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n};\n\n/** Result of a successful WSFE voucher authorization. */\nexport type WsfeAuthorizationResult = {\n cae: string;\n caeExpiry: string;\n voucherNumber: number;\n raw: Record<string, unknown>;\n};\n\n/** Structured evidence from one exact WSFE authorization attempt. */\nexport type WsfeAuthorizationOutcome = ArcaAuthorizationOutcome<\"wsfe\">;\n\n/** A point-of-sale entry returned by {@link WsfeService.getSalesPoints}. */\nexport type WsfeSalesPoint = {\n number: number;\n emissionType?: string;\n blocked?: string;\n deletedSince?: string;\n};\n\n/** Voucher details returned by {@link WsfeService.getVoucherInfo}. */\nexport type WsfeVoucherInfo = {\n voucherNumber: number;\n voucherDate?: string;\n salesPoint?: number;\n voucherType?: number;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n totalAmount?: number;\n nonTaxableAmount?: number;\n netAmount?: number;\n exemptAmount?: number;\n taxAmount?: number;\n vatAmount?: number;\n currencyId?: string;\n exchangeRate?: number;\n result?: string;\n cae?: string;\n caeExpiry?: string;\n raw: Record<string, unknown>;\n};\n\n/** Typed exact-voucher consultation result for WSFE. */\nexport type WsfeVoucherLookupResult = ArcaVoucherLookupResult<\n WsfeVoucherInfo,\n \"wsfe\"\n>;\n\nexport type WsfeCatalogEntry = {\n id: number;\n description: string;\n};\n\nexport type WsfeActivityType = WsfeCatalogEntry & {\n order: number;\n};\n\nexport type WsfeReceiverVatCondition = WsfeCatalogEntry & {\n voucherClass: string;\n};\n\nexport type WsfeCurrencyType = {\n id: string;\n description: string;\n validFrom: string;\n validTo: string;\n};\n\nexport type WsfeServerStatus = {\n appServer: string;\n dbServer: string;\n authServer: string;\n};\n\nexport type WsfeQuotation = {\n currencyId: string;\n rate: number;\n date: string;\n};\n\n/** WSFE electronic invoicing service. */\nexport type WsfeService = {\n /**\n * Attempts one exact authorization without transport retries and returns\n * structured provider evidence instead of flattening the result to throw/success.\n */\n authorizeVoucherOutcome(\n input: WsfeAuthorizeVoucherInput\n ): Promise<WsfeAuthorizationOutcome>;\n /** Authorizes a voucher with the explicit number sent as `CbteDesde` and `CbteHasta`. */\n authorizeVoucher(\n input: WsfeAuthorizeVoucherInput\n ): Promise<WsfeAuthorizationResult>;\n /** Authorizes a new voucher by fetching the next number and requesting a CAE. */\n createNextVoucher(input: {\n representedTaxId?: number | string;\n data: WsfeVoucherInput;\n forceRefresh?: boolean;\n }): Promise<WsfeAuthorizationResult>;\n /** Returns the next available voucher number for the given sales point and type. */\n getNextVoucherNumber(input: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<number>;\n /**\n * @deprecated Use `getNextVoucherNumber()` instead.\n * Returns the next available voucher number, not the last authorized one.\n */\n getLastVoucher(input: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<number>;\n /** Lists all configured points of sale for the taxpayer. */\n getSalesPoints(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeSalesPoint[]>;\n /** Lists voucher types accepted by WSFE. */\n getVoucherTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists document types accepted by WSFE. */\n getDocumentTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists concept types accepted by WSFE. */\n getConceptTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists live ARCA currency identifiers such as PES and DOL, not ISO codes. */\n getCurrencyTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCurrencyType[]>;\n /** Lists VAT rates accepted by WSFE. */\n getVatRates(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists tax types accepted by WSFE. */\n getTaxTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists optional field types accepted by WSFE. */\n getOptionalTypes(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeCatalogEntry[]>;\n /** Lists activities enabled for the taxpayer. */\n getActivities(input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeActivityType[]>;\n /** Lists receiver VAT condition values accepted by WSFE. */\n getReceiverVatConditions(input: {\n representedTaxId?: number | string;\n voucherClass?: string;\n forceRefresh?: boolean;\n }): Promise<WsfeReceiverVatCondition[]>;\n /** Reports WSFE backend status without requiring taxpayer authorization. */\n getServerStatus(): Promise<WsfeServerStatus>;\n /** Returns the exchange rate for a given currency. */\n getQuotation(input: {\n currencyId: string;\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n }): Promise<WsfeQuotation>;\n /** Retrieves details for a specific voucher. Returns `null` if not found. */\n getVoucherInfo(input: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherInfo | null>;\n /** Consults one exact voucher and normalizes WSFE error 602 to `not_found`. */\n lookupVoucher(input: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult>;\n};\n\nexport type CreateWsfeServiceOptions = {\n config: ArcaClientConfig;\n auth: WsaaAuthModule;\n soap: SoapTransport;\n};\n\ntype NormalizedWsfeAssociatedVoucher = Omit<\n WsfeAssociatedVoucher,\n \"voucherDate\"\n> & {\n voucherDate?: string;\n};\n\ntype NormalizedWsfeAssociatedPeriod = {\n startDate: string;\n endDate: string;\n};\n\ntype NormalizedWsfeTax = Omit<WsfeTax, \"baseAmount\" | \"rate\" | \"amount\"> & {\n baseAmount: string;\n rate: string;\n amount: string;\n};\n\ntype NormalizedWsfeVatRate = Omit<WsfeVatRate, \"baseAmount\" | \"amount\"> & {\n baseAmount: string;\n amount: string;\n};\n\ntype NormalizedWsfeVoucherInput = Omit<\n WsfeVoucherInput,\n | \"voucherDate\"\n | \"serviceStartDate\"\n | \"serviceEndDate\"\n | \"paymentDueDate\"\n | \"associatedVouchers\"\n | \"associatedPeriod\"\n | \"totalAmount\"\n | \"nonTaxableAmount\"\n | \"netAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatAmount\"\n | \"exchangeRate\"\n | \"taxes\"\n | \"vatRates\"\n> & {\n voucherDate: string;\n totalAmount: string;\n nonTaxableAmount: string;\n netAmount: string;\n exemptAmount: string;\n taxAmount: string;\n vatAmount: string;\n exchangeRate?: string;\n serviceStartDate?: string;\n serviceEndDate?: string;\n paymentDueDate?: string;\n associatedVouchers?: NormalizedWsfeAssociatedVoucher[];\n associatedPeriod?: NormalizedWsfeAssociatedPeriod;\n taxes?: NormalizedWsfeTax[];\n vatRates?: NormalizedWsfeVatRate[];\n};\n\n/** Creates a WSFE service instance wired with authentication and SOAP transport. */\nexport function createWsfeService(\n options: CreateWsfeServiceOptions\n): WsfeService {\n async function executeWsfeAuthenticatedRawOperation(\n operation: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {},\n retries?: number\n ) {\n const auth = await options.auth.login(\"wsfe\", {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsfe\",\n operation,\n ...(retries === undefined ? {} : { retries }),\n body: {\n Auth: createWsfeAuth(\n input.representedTaxId ?? options.config.taxId,\n auth.token,\n auth.sign\n ),\n ...body,\n },\n });\n\n return unwrapWsfeOperationEnvelope(operation, response.result);\n }\n\n function executeWsfeAuthenticatedOperation(\n operation: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {}\n ) {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation,\n forceRefresh: input.forceRefresh,\n async execute(forceRefresh) {\n const result = await executeWsfeAuthenticatedRawOperation(\n operation,\n { representedTaxId: input.representedTaxId, forceRefresh },\n body\n );\n throwForWsfeOperationErrors(operation, result);\n return result;\n },\n });\n }\n\n async function executeWsfeOperation(\n operation: string,\n body: Record<string, unknown> = {}\n ) {\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsfe\",\n operation,\n body,\n });\n\n const result = unwrapWsfeOperationEnvelope(operation, response.result);\n throwForWsfeOperationErrors(operation, result);\n return result;\n }\n\n async function getNextVoucherNumber({\n representedTaxId,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FECompUltimoAutorizado\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n PtoVta: salesPoint,\n CbteTipo: voucherType,\n }\n );\n return Number(result.CbteNro ?? 0) + 1;\n }\n\n async function getWsfeCatalog(\n operation: string,\n resultKey: string,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }\n ): Promise<WsfeCatalogEntry[]> {\n const result = await executeWsfeAuthenticatedOperation(operation, {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n return getWsfeResultEntries(result, resultKey).map(mapWsfeCatalogEntry);\n }\n\n function authorizeVoucher({\n representedTaxId,\n data,\n voucherNumber,\n forceRefresh,\n }: WsfeAuthorizeVoucherInput): Promise<WsfeAuthorizationResult> {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n return authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n });\n }\n\n function authorizeVoucherOutcome({\n representedTaxId,\n data,\n voucherNumber,\n forceRefresh,\n }: WsfeAuthorizeVoucherInput): Promise<WsfeAuthorizationOutcome> {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n return executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }).then(({ outcome }) => outcome);\n }\n\n function authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n allowAuthenticationRecovery,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n allowAuthenticationRecovery?: boolean;\n }): Promise<WsfeAuthorizationResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n forceRefresh,\n allowRetry: allowAuthenticationRecovery,\n execute: (attemptForceRefresh) =>\n authorizeNormalizedVoucherOnce({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function authorizeNormalizedVoucherOnce({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsfeAuthorizationResult> {\n const execution = await executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n });\n\n if (execution.error) {\n throw execution.error;\n }\n\n if (execution.outcome.kind !== \"authorized\") {\n throw createWsfeOutcomeError(execution.outcome);\n }\n\n const { cae, caeExpiry, raw } = execution.outcome;\n if (!(caeExpiry && raw)) {\n throw new ArcaServiceError(\"WSFE did not return CAE authorization data\", {\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n result: execution.outcome.result,\n resultLevel: execution.outcome.resultLevel,\n results: execution.outcome.results,\n cae,\n issues: [\n ...execution.outcome.errors,\n ...execution.outcome.observations,\n ],\n });\n }\n\n return {\n cae,\n caeExpiry,\n voucherNumber,\n raw,\n };\n }\n\n async function executeWsfeAuthorization({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n data: NormalizedWsfeVoucherInput;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<{\n outcome: WsfeAuthorizationOutcome;\n error?: unknown;\n }> {\n const requestData = mapWsfeVoucherInput(normalizedInput, voucherNumber);\n\n try {\n const result = await executeWsfeAuthenticatedRawOperation(\n \"FECAESolicitar\",\n { representedTaxId, forceRefresh },\n {\n FeCAEReq: {\n FeCabReq: {\n CantReg: 1,\n PtoVta: normalizedInput.salesPoint,\n CbteTipo: normalizedInput.voucherType,\n },\n FeDetReq: {\n FECAEDetRequest: requestData,\n },\n },\n },\n 0\n );\n\n return {\n outcome: classifyWsfeAuthorization(result, voucherNumber),\n };\n } catch (error) {\n return {\n outcome: createWsfeIndeterminateOutcome(error),\n error,\n };\n }\n }\n\n function lookupVoucher({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsfe\",\n operation: \"FECompConsultar\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n lookupVoucherOnce({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function lookupVoucherOnce({\n representedTaxId,\n number,\n salesPoint,\n voucherType,\n forceRefresh,\n }: {\n representedTaxId?: number | string;\n number: number;\n salesPoint: number;\n voucherType: number;\n forceRefresh?: boolean;\n }): Promise<WsfeVoucherLookupResult> {\n const operation = \"FECompConsultar\";\n const result = await executeWsfeAuthenticatedRawOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n FeCompConsReq: {\n CbteNro: number,\n PtoVta: salesPoint,\n CbteTipo: voucherType,\n },\n }\n );\n const errors = extractWsfeGlobalIssues(result, operation);\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"602\")) {\n return {\n kind: \"not_found\",\n service: \"wsfe\",\n operation,\n errors,\n observations: [],\n raw: result,\n };\n }\n\n if (errors.length > 0) {\n throw createWsfeServiceError(operation, errors);\n }\n\n const raw = toWsfeRecord(result.ResultGet);\n if (!raw) {\n throw new ArcaServiceError(\"WSFE did not return the consulted voucher\", {\n service: \"wsfe\",\n operation,\n });\n }\n\n return {\n kind: \"found\",\n service: \"wsfe\",\n operation,\n voucher: mapWsfeVoucherInfo(raw),\n observations: [],\n raw: result,\n };\n }\n\n return {\n authorizeVoucherOutcome,\n authorizeVoucher,\n async createNextVoucher({ representedTaxId, data, forceRefresh }) {\n const normalizedInput = normalizeWsfeVoucherInput(data);\n\n const voucherNumber = await getNextVoucherNumber({\n representedTaxId,\n salesPoint: normalizedInput.salesPoint,\n voucherType: normalizedInput.voucherType,\n forceRefresh,\n });\n\n return authorizeNormalizedVoucher({\n representedTaxId,\n data: normalizedInput,\n voucherNumber,\n allowAuthenticationRecovery: forceRefresh !== true,\n });\n },\n getNextVoucherNumber,\n getLastVoucher(input) {\n return getNextVoucherNumber(input);\n },\n async getSalesPoints({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetPtosVenta\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n const rawPoints = (\n result.ResultGet as Record<string, unknown> | undefined\n )?.PtoVenta;\n if (!rawPoints) {\n return [];\n }\n const entries = Array.isArray(rawPoints) ? rawPoints : [rawPoints];\n return entries.map(mapWsfeSalesPoint);\n },\n getVoucherTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposCbte\", \"CbteTipo\", input);\n },\n getDocumentTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposDoc\", \"DocTipo\", input);\n },\n getConceptTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposConcepto\", \"ConceptoTipo\", input);\n },\n async getCurrencyTypes({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetTiposMonedas\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n return getWsfeResultEntries(result, \"Moneda\").map(mapWsfeCurrencyType);\n },\n getVatRates(input) {\n return getWsfeCatalog(\"FEParamGetTiposIva\", \"IvaTipo\", input);\n },\n getTaxTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposTributos\", \"TributoTipo\", input);\n },\n getOptionalTypes(input) {\n return getWsfeCatalog(\"FEParamGetTiposOpcional\", \"OpcionalTipo\", input);\n },\n async getActivities({ representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetActividades\",\n {\n representedTaxId,\n forceRefresh,\n }\n );\n return getWsfeResultEntries(result, \"ActividadesTipo\").map(\n mapWsfeActivityType\n );\n },\n async getReceiverVatConditions({\n representedTaxId,\n voucherClass,\n forceRefresh,\n }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetCondicionIvaReceptor\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n ...(voucherClass === undefined ? {} : { ClaseCmp: voucherClass }),\n }\n );\n return getWsfeResultEntries(result, \"CondicionIvaReceptor\").map(\n mapWsfeReceiverVatCondition\n );\n },\n async getServerStatus() {\n const result = await executeWsfeOperation(\"FEDummy\");\n return mapWsfeServerStatus(result);\n },\n async getQuotation({ currencyId, representedTaxId, forceRefresh }) {\n const result = await executeWsfeAuthenticatedOperation(\n \"FEParamGetCotizacion\",\n {\n representedTaxId,\n forceRefresh,\n },\n {\n MonId: currencyId,\n }\n );\n const raw =\n (result.ResultGet as Record<string, unknown> | undefined) ?? {};\n return mapWsfeQuotation(raw);\n },\n async getVoucherInfo(input) {\n const lookup = await lookupVoucher(input);\n return lookup.kind === \"found\" ? lookup.voucher : null;\n },\n lookupVoucher,\n };\n}\n\nfunction mapWsfeVoucherInput(\n input: NormalizedWsfeVoucherInput,\n voucherNumber: number\n): Record<string, unknown> {\n const data: Record<string, unknown> = {\n Concepto: input.concept,\n DocTipo: input.documentType,\n DocNro: input.documentNumber,\n CbteDesde: voucherNumber,\n CbteHasta: voucherNumber,\n CbteFch: input.voucherDate,\n ImpTotal: input.totalAmount,\n ImpTotConc: input.nonTaxableAmount,\n ImpNeto: input.netAmount,\n ImpOpEx: input.exemptAmount,\n ImpTrib: input.taxAmount,\n ImpIVA: input.vatAmount,\n MonId: input.currencyId,\n CondicionIVAReceptorId: input.receiverVatConditionId,\n PtoVta: input.salesPoint,\n CbteTipo: input.voucherType,\n };\n\n if (input.exchangeRate !== undefined) {\n data.MonCotiz = input.exchangeRate;\n }\n\n if (\n input.currencyId !== \"PES\" &&\n input.sameCurrencyForeignCancellation !== undefined\n ) {\n data.CanMisMonExt = input.sameCurrencyForeignCancellation;\n }\n\n if (input.serviceStartDate !== undefined) {\n data.FchServDesde = input.serviceStartDate;\n }\n if (input.serviceEndDate !== undefined) {\n data.FchServHasta = input.serviceEndDate;\n }\n if (input.paymentDueDate !== undefined) {\n data.FchVtoPago = input.paymentDueDate;\n }\n\n if (input.associatedVouchers) {\n data.CbtesAsoc = {\n CbteAsoc: input.associatedVouchers.map((v) => ({\n Tipo: v.type,\n PtoVta: v.salesPoint,\n Nro: v.number,\n ...(v.taxId === undefined ? {} : { Cuit: v.taxId }),\n ...(v.voucherDate === undefined ? {} : { CbteFch: v.voucherDate }),\n })),\n };\n }\n\n if (input.associatedPeriod) {\n data.PeriodoAsoc = {\n FchDesde: input.associatedPeriod.startDate,\n FchHasta: input.associatedPeriod.endDate,\n };\n }\n\n if (input.taxes) {\n data.Tributos = {\n Tributo: input.taxes.map((t) => ({\n Id: t.id,\n ...(t.description === undefined ? {} : { Desc: t.description }),\n BaseImp: t.baseAmount,\n Alic: t.rate,\n Importe: t.amount,\n })),\n };\n }\n\n if (input.vatRates) {\n data.Iva = {\n AlicIva: input.vatRates.map((v) => ({\n Id: v.id,\n BaseImp: v.baseAmount,\n Importe: v.amount,\n })),\n };\n }\n\n if (input.optionalFields) {\n data.Opcionales = {\n Opcional: input.optionalFields.map((o) => ({\n Id: o.id,\n Valor: o.value,\n })),\n };\n }\n\n if (input.buyers) {\n data.Compradores = {\n Comprador: input.buyers.map((b) => ({\n DocTipo: b.documentType,\n DocNro: b.documentNumber,\n Porcentaje: b.percentage,\n })),\n };\n }\n\n if (input.activities) {\n data.Actividades = {\n Actividad: input.activities.map((a) => ({\n Id: a.id,\n })),\n };\n }\n\n return data;\n}\n\nfunction normalizeWsfeVoucherInput(\n input: WsfeVoucherInput\n): NormalizedWsfeVoucherInput {\n if (input.receiverVatConditionId === undefined) {\n throw new ArcaInputError(\"receiverVatConditionId is required.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"receiverVatConditionId\",\n expected: \"a receiver VAT condition accepted for the voucher class\",\n });\n }\n\n const {\n voucherDate,\n exchangeRate,\n serviceStartDate,\n serviceEndDate,\n paymentDueDate,\n associatedVouchers,\n associatedPeriod,\n taxes,\n vatRates,\n ...rest\n } = input;\n const normalizedExchangeRate = normalizeWsfeExchangeRate(input, exchangeRate);\n const normalizedAmounts = normalizeAndValidateWsfeAmounts(input);\n\n return {\n ...rest,\n ...normalizedAmounts,\n voucherDate: normalizeWsfeDateInput(voucherDate, \"voucherDate\"),\n ...(normalizedExchangeRate === undefined\n ? {}\n : { exchangeRate: normalizedExchangeRate }),\n ...(serviceStartDate === undefined\n ? {}\n : {\n serviceStartDate: normalizeWsfeDateInput(\n serviceStartDate,\n \"serviceStartDate\"\n ),\n }),\n ...(serviceEndDate === undefined\n ? {}\n : {\n serviceEndDate: normalizeWsfeDateInput(\n serviceEndDate,\n \"serviceEndDate\"\n ),\n }),\n ...(paymentDueDate === undefined\n ? {}\n : {\n paymentDueDate: normalizeWsfeDateInput(\n paymentDueDate,\n \"paymentDueDate\"\n ),\n }),\n ...(associatedVouchers === undefined\n ? {}\n : {\n associatedVouchers: associatedVouchers.map((voucher, index) => {\n const { voucherDate: associatedVoucherDate, ...associatedRest } =\n voucher;\n\n return {\n ...associatedRest,\n ...(associatedVoucherDate === undefined\n ? {}\n : {\n voucherDate: normalizeWsfeDateInput(\n associatedVoucherDate,\n `associatedVouchers[${index}].voucherDate`\n ),\n }),\n };\n }),\n }),\n ...(associatedPeriod === undefined\n ? {}\n : {\n associatedPeriod: {\n startDate: normalizeWsfeDateInput(\n associatedPeriod.startDate,\n \"associatedPeriod.startDate\"\n ),\n endDate: normalizeWsfeDateInput(\n associatedPeriod.endDate,\n \"associatedPeriod.endDate\"\n ),\n },\n }),\n ...(taxes === undefined\n ? {}\n : {\n taxes: taxes.map((tax, index) => ({\n ...tax,\n baseAmount: serializeArcaAmount(\n tax.baseAmount,\n `taxes[${index}].baseAmount`\n ),\n rate: serializeArcaPercentage(tax.rate, `taxes[${index}].rate`),\n amount: serializeArcaAmount(tax.amount, `taxes[${index}].amount`),\n })),\n }),\n ...(vatRates === undefined\n ? {}\n : {\n vatRates: vatRates.map((vatRate, index) => ({\n ...vatRate,\n baseAmount: serializeArcaAmount(\n vatRate.baseAmount,\n `vatRates[${index}].baseAmount`\n ),\n amount: serializeArcaAmount(\n vatRate.amount,\n `vatRates[${index}].amount`\n ),\n })),\n }),\n };\n}\n\nfunction normalizeAndValidateWsfeAmounts(\n input: WsfeVoucherInput\n): Pick<\n NormalizedWsfeVoucherInput,\n | \"totalAmount\"\n | \"nonTaxableAmount\"\n | \"netAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatAmount\"\n> {\n const totalAmount = normalizeArcaAmountToMinorUnits(\n input.totalAmount,\n \"totalAmount\"\n );\n const nonTaxableAmount = normalizeArcaAmountToMinorUnits(\n input.nonTaxableAmount,\n \"nonTaxableAmount\"\n );\n const netAmount = normalizeArcaAmountToMinorUnits(\n input.netAmount,\n \"netAmount\"\n );\n const exemptAmount = normalizeArcaAmountToMinorUnits(\n input.exemptAmount,\n \"exemptAmount\"\n );\n const taxAmount = normalizeArcaAmountToMinorUnits(\n input.taxAmount,\n \"taxAmount\"\n );\n const vatAmount = normalizeArcaAmountToMinorUnits(\n input.vatAmount,\n \"vatAmount\"\n );\n\n const decomposedTotal =\n nonTaxableAmount + netAmount + exemptAmount + taxAmount + vatAmount;\n assertWsfeAmountMatch(\n totalAmount,\n decomposedTotal,\n \"totalAmount\",\n \"the sum of nonTaxableAmount, netAmount, exemptAmount, taxAmount, and vatAmount\"\n );\n\n const vatRates = input.vatRates ?? [];\n if (vatAmount > 0n && vatRates.length === 0) {\n throw new ArcaInputError(\n \"vatRates is required when vatAmount is greater than zero.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"vatRates\",\n expected: \"VAT detail whose amounts reconcile with vatAmount\",\n }\n );\n }\n\n if (vatRates.length > 0) {\n const normalizedVatRates = vatRates.map((vatRate, index) => ({\n baseAmount: normalizeArcaAmountToMinorUnits(\n vatRate.baseAmount,\n `vatRates[${index}].baseAmount`\n ),\n amount: normalizeArcaAmountToMinorUnits(\n vatRate.amount,\n `vatRates[${index}].amount`\n ),\n }));\n const vatRateAmountSum = normalizedVatRates.reduce(\n (sum, vatRate) => sum + vatRate.amount,\n 0n\n );\n const vatRateBaseSum = normalizedVatRates.reduce(\n (sum, vatRate) => sum + vatRate.baseAmount,\n 0n\n );\n\n assertWsfeAmountMatch(\n vatAmount,\n vatRateAmountSum,\n \"vatAmount\",\n \"the sum of vatRates[].amount\",\n vatRates.length\n );\n if (requiresWsfeVatBaseReconciliation(input.voucherType)) {\n assertWsfeAmountMatch(\n netAmount,\n vatRateBaseSum,\n \"netAmount\",\n \"the sum of vatRates[].baseAmount\",\n vatRates.length\n );\n }\n }\n\n const taxes = input.taxes ?? [];\n if (taxAmount > 0n && taxes.length === 0) {\n throw new ArcaInputError(\n \"taxes is required when taxAmount is greater than zero.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"taxes\",\n expected: \"tax detail whose amounts reconcile with taxAmount\",\n }\n );\n }\n\n if (taxes.length > 0) {\n const taxAmountSum = taxes.reduce((sum, tax, index) => {\n normalizeArcaAmountToMinorUnits(\n tax.baseAmount,\n `taxes[${index}].baseAmount`\n );\n serializeArcaPercentage(tax.rate, `taxes[${index}].rate`);\n return (\n sum +\n normalizeArcaAmountToMinorUnits(tax.amount, `taxes[${index}].amount`)\n );\n }, 0n);\n\n assertWsfeAmountMatch(\n taxAmount,\n taxAmountSum,\n \"taxAmount\",\n \"the sum of taxes[].amount\",\n taxes.length\n );\n }\n\n return {\n totalAmount: serializeArcaAmount(input.totalAmount, \"totalAmount\"),\n nonTaxableAmount: serializeArcaAmount(\n input.nonTaxableAmount,\n \"nonTaxableAmount\"\n ),\n netAmount: serializeArcaAmount(input.netAmount, \"netAmount\"),\n exemptAmount: serializeArcaAmount(input.exemptAmount, \"exemptAmount\"),\n taxAmount: serializeArcaAmount(input.taxAmount, \"taxAmount\"),\n vatAmount: serializeArcaAmount(input.vatAmount, \"vatAmount\"),\n };\n}\n\nfunction requiresWsfeVatBaseReconciliation(voucherType: number): boolean {\n // WSFE validation 10061 exempts debit/credit notes, class C vouchers,\n // and class A vouchers with the retention legend.\n return ![2, 3, 7, 8, 11, 12, 13, 15, 52, 53].includes(voucherType);\n}\n\nfunction assertWsfeAmountMatch(\n actual: bigint,\n expectedAmount: bigint,\n field: string,\n expectedDescription: string,\n absoluteCentAllowance = 1\n) {\n if (!isWithinArcaTolerance(actual, expectedAmount, absoluteCentAllowance)) {\n throw new ArcaInputError(\n `${field} does not reconcile within ARCA's documented tolerance.`,\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field,\n expected: `within ARCA tolerance of ${expectedDescription}`,\n }\n );\n }\n}\n\nfunction normalizeWsfeExchangeRate(\n input: Pick<\n WsfeVoucherInput,\n \"currencyId\" | \"sameCurrencyForeignCancellation\"\n >,\n exchangeRate: number | string | undefined\n): string | undefined {\n if (input.currencyId === \"PES\") {\n if (\n exchangeRate !== undefined &&\n serializeArcaExchangeRate(exchangeRate, \"exchangeRate\") !== \"1\"\n ) {\n throw new ArcaInputError(\n \"exchangeRate must be 1 when currencyId is PES.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"1 when currencyId is PES\",\n }\n );\n }\n return \"1\";\n }\n\n if (exchangeRate === undefined) {\n if (input.sameCurrencyForeignCancellation === \"S\") {\n return undefined;\n }\n throw new ArcaInputError(\n \"exchangeRate is required unless sameCurrencyForeignCancellation is S for a foreign-currency voucher.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected:\n \"a positive exchange rate unless sameCurrencyForeignCancellation is S\",\n }\n );\n }\n\n return serializeArcaExchangeRate(exchangeRate, \"exchangeRate\");\n}\n\nfunction normalizeWsfeDateInput(\n value: WsfeDateInput,\n fieldName: string\n): string {\n if (typeof value !== \"string\") {\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"a YYYY-MM-DD or YYYYMMDD calendar date string\",\n }\n );\n }\n\n const normalizedValue = value.trim();\n const afipMatch = normalizedValue.match(/^(\\d{4})(\\d{2})(\\d{2})$/);\n if (afipMatch) {\n const [, year, month, day] = afipMatch;\n assertValidCalendarDate(year, month, day, fieldName);\n return normalizedValue;\n }\n\n const isoMatch = normalizedValue.match(/^(\\d{4})-(\\d{2})-(\\d{2})$/);\n if (isoMatch) {\n const [, year, month, day] = isoMatch;\n assertValidCalendarDate(year, month, day, fieldName);\n return `${year}${month}${day}`;\n }\n\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: expected a YYYY-MM-DD or YYYYMMDD string`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"a YYYY-MM-DD or YYYYMMDD calendar date string\",\n }\n );\n}\n\nfunction assertValidCalendarDate(\n yearInput: string,\n monthInput: string,\n dayInput: string,\n fieldName: string\n) {\n const year = Number(yearInput);\n const month = Number(monthInput);\n const day = Number(dayInput);\n const candidate = new Date(Date.UTC(year, month - 1, day));\n\n if (\n candidate.getUTCFullYear() !== year ||\n candidate.getUTCMonth() !== month - 1 ||\n candidate.getUTCDate() !== day\n ) {\n throw new ArcaInputError(\n `Invalid WSFE ${fieldName}: received a non-existent calendar date`,\n {\n code: \"ARCA_INPUT_INVALID_DATE\",\n field: fieldName,\n expected: \"an existing calendar date\",\n }\n );\n }\n}\n\nfunction mapWsfeSalesPoint(raw: unknown): WsfeSalesPoint {\n const record = raw as Record<string, unknown>;\n return {\n number: Number(record.Nro ?? 0),\n ...(record.EmisionTipo === undefined\n ? {}\n : { emissionType: String(record.EmisionTipo) }),\n ...(record.Bloqueado === undefined\n ? {}\n : { blocked: String(record.Bloqueado) }),\n ...(record.FchBaja === undefined\n ? {}\n : { deletedSince: String(record.FchBaja) }),\n };\n}\n\nfunction mapWsfeCatalogEntry(raw: unknown): WsfeCatalogEntry {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n };\n}\n\nfunction mapWsfeActivityType(raw: unknown): WsfeActivityType {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n order: Number(record.Orden ?? 0),\n };\n}\n\nfunction mapWsfeReceiverVatCondition(raw: unknown): WsfeReceiverVatCondition {\n const record = raw as Record<string, unknown>;\n return {\n id: Number(record.Id ?? 0),\n description: String(record.Desc ?? \"\"),\n voucherClass: String(record.Cmp_Clase ?? \"\"),\n };\n}\n\nfunction mapWsfeCurrencyType(raw: unknown): WsfeCurrencyType {\n const record = raw as Record<string, unknown>;\n return {\n id: String(record.Id ?? \"\"),\n description: String(record.Desc ?? \"\"),\n validFrom: String(record.FchDesde ?? \"\"),\n validTo: String(record.FchHasta ?? \"\"),\n };\n}\n\nfunction mapWsfeServerStatus(raw: Record<string, unknown>): WsfeServerStatus {\n return {\n appServer: String(raw.AppServer ?? \"\"),\n dbServer: String(raw.DbServer ?? \"\"),\n authServer: String(raw.AuthServer ?? \"\"),\n };\n}\n\nfunction mapWsfeQuotation(raw: Record<string, unknown>): WsfeQuotation {\n return {\n currencyId: String(raw.MonId ?? \"\"),\n rate: Number(raw.MonCotiz ?? 0),\n date: String(raw.FchCotiz ?? \"\"),\n };\n}\n\nfunction mapWsfeVoucherInfo(raw: Record<string, unknown>): WsfeVoucherInfo {\n const voucher: WsfeVoucherInfo = {\n voucherNumber: Number(raw.CbteDesde ?? raw.CbteHasta ?? 0),\n raw,\n };\n\n assignWsfeValue(voucher, \"voucherDate\", normalizeWsfeString(raw.CbteFch));\n assignWsfeValue(voucher, \"salesPoint\", normalizeWsfeNumber(raw.PtoVta));\n assignWsfeValue(voucher, \"voucherType\", normalizeWsfeNumber(raw.CbteTipo));\n assignWsfeValue(voucher, \"concept\", normalizeWsfeNumber(raw.Concepto));\n assignWsfeValue(voucher, \"documentType\", normalizeWsfeNumber(raw.DocTipo));\n assignWsfeValue(voucher, \"documentNumber\", normalizeWsfeString(raw.DocNro));\n assignWsfeValue(\n voucher,\n \"receiverVatConditionId\",\n normalizeWsfeNumber(raw.CondicionIVAReceptorId)\n );\n assignWsfeValue(voucher, \"totalAmount\", normalizeWsfeNumber(raw.ImpTotal));\n assignWsfeValue(\n voucher,\n \"nonTaxableAmount\",\n normalizeWsfeNumber(raw.ImpTotConc)\n );\n assignWsfeValue(voucher, \"netAmount\", normalizeWsfeNumber(raw.ImpNeto));\n assignWsfeValue(voucher, \"exemptAmount\", normalizeWsfeNumber(raw.ImpOpEx));\n assignWsfeValue(voucher, \"taxAmount\", normalizeWsfeNumber(raw.ImpTrib));\n assignWsfeValue(voucher, \"vatAmount\", normalizeWsfeNumber(raw.ImpIVA));\n assignWsfeValue(voucher, \"currencyId\", normalizeWsfeString(raw.MonId));\n assignWsfeValue(voucher, \"exchangeRate\", normalizeWsfeNumber(raw.MonCotiz));\n assignWsfeValue(voucher, \"result\", normalizeWsfeString(raw.Resultado));\n assignWsfeValue(\n voucher,\n \"cae\",\n normalizeWsfeString(raw.CodAutorizacion ?? raw.CAE)\n );\n assignWsfeValue(\n voucher,\n \"caeExpiry\",\n normalizeWsfeString(raw.FchVto ?? raw.CAEFchVto)\n );\n\n return voucher;\n}\n\nfunction createWsfeAuth(\n representedTaxId: number | string,\n token: string,\n sign: string\n) {\n return {\n Token: token,\n Sign: sign,\n Cuit: Number.parseInt(String(representedTaxId), 10),\n };\n}\n\nfunction unwrapWsfeOperationEnvelope(\n operation: string,\n response: Record<string, unknown>\n) {\n const operationResponse = response[`${operation}Response`] as\n | Record<string, unknown>\n | undefined;\n const result = (operationResponse?.[`${operation}Result`] ??\n response[`${operation}Result`] ??\n response) as Record<string, unknown>;\n\n return result;\n}\n\nfunction throwForWsfeOperationErrors(\n operation: string,\n result: Record<string, unknown>\n) {\n const errors = extractWsfeGlobalIssues(result, operation);\n if (errors.length > 0) {\n throw createWsfeServiceError(operation, errors);\n }\n}\n\nfunction normalizeWsfeDetailResponse(result: Record<string, unknown>) {\n const detailResponse = result.FeDetResp as\n | Record<string, unknown>\n | undefined;\n const rawDetail = detailResponse?.FECAEDetResponse;\n\n if (Array.isArray(rawDetail)) {\n return (rawDetail[0] as Record<string, unknown>) ?? {};\n }\n\n return (rawDetail as Record<string, unknown> | undefined) ?? {};\n}\n\nfunction classifyWsfeAuthorization(\n result: Record<string, unknown>,\n voucherNumber: number\n): WsfeAuthorizationOutcome {\n const operation = \"FECAESolicitar\";\n const header = toWsfeRecord(result.FeCabResp) ?? {};\n const detail = normalizeWsfeDetailResponse(result);\n const headerResult = normalizeWsfeResult(header.Resultado);\n const detailResult = normalizeWsfeResult(detail.Resultado);\n const resultCode = detailResult ?? headerResult;\n const resultLevel = getWsfeResultLevel(headerResult, detailResult);\n const cae = normalizeWsfeString(detail.CAE);\n const caeExpiry = normalizeWsfeString(detail.CAEFchVto);\n const errors = extractWsfeGlobalIssues(result, operation, \"header\");\n const observations = extractWsfeObservations(\n detail,\n detailResult === \"R\" ? \"business\" : \"observation\"\n );\n const hasInfrastructureError = errors.some(\n (issue) => issue.category === \"infrastructure\"\n );\n const base = {\n service: \"wsfe\" as const,\n operation,\n results: createWsfeResults(headerResult, detailResult),\n errors,\n observations,\n raw: result,\n };\n const context: WsfeAuthorizationContext = {\n base,\n headerResult,\n detailResult,\n resultCode,\n resultLevel,\n cae,\n caeExpiry,\n };\n\n if (hasContradictoryWsfeResults(context)) {\n return createWsfeStructuredIndeterminate(context, \"contradictory_response\");\n }\n\n const authenticationError = classifyArcaAuthenticationIssues(errors, {\n service: \"wsfe\",\n operation,\n });\n if (\n authenticationError &&\n detailResult === undefined &&\n headerResult !== \"A\" &&\n headerResult !== \"O\" &&\n !cae\n ) {\n return {\n ...createWsfeStructuredIndeterminate(context, \"authentication_rejected\"),\n authentication: createArcaAuthenticationEvidence(authenticationError),\n };\n }\n\n if (hasInfrastructureError) {\n return createWsfeStructuredIndeterminate(context, \"incomplete_response\");\n }\n\n if (isAuthorizedWsfeContext(context)) {\n return {\n ...base,\n kind: \"authorized\",\n result: \"A\",\n resultLevel: \"detail\",\n cae: context.cae,\n caeExpiry: context.caeExpiry,\n voucherNumber,\n };\n }\n\n if (isRejectedWsfeDetailContext(context)) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"detail\",\n };\n }\n\n if (isRejectedWsfeHeaderContext(context)) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"header\",\n };\n }\n\n return createWsfeStructuredIndeterminate(\n context,\n hasWsfeCaeContradiction(context)\n ? \"contradictory_response\"\n : \"incomplete_response\"\n );\n}\n\ntype WsfeAuthorizationContext = {\n base: {\n service: \"wsfe\";\n operation: string;\n results: { header?: string; detail?: string };\n errors: ArcaFiscalIssue[];\n observations: ArcaFiscalIssue[];\n raw: Record<string, unknown>;\n };\n headerResult?: string;\n detailResult?: string;\n resultCode?: string;\n resultLevel?: ArcaFiscalResultLevel;\n cae?: string;\n caeExpiry?: string;\n};\n\nfunction getWsfeResultLevel(\n headerResult?: string,\n detailResult?: string\n): ArcaFiscalResultLevel | undefined {\n if (detailResult) {\n return \"detail\";\n }\n return headerResult ? \"header\" : undefined;\n}\n\nfunction hasContradictoryWsfeResults(context: WsfeAuthorizationContext) {\n return Boolean(\n context.headerResult &&\n context.detailResult &&\n context.headerResult !== context.detailResult\n );\n}\n\nfunction isAuthorizedWsfeContext(\n context: WsfeAuthorizationContext\n): context is WsfeAuthorizationContext & { cae: string; caeExpiry: string } {\n return Boolean(\n context.detailResult === \"A\" &&\n context.headerResult !== \"R\" &&\n context.base.errors.length === 0 &&\n context.cae &&\n context.caeExpiry\n );\n}\n\nfunction isRejectedWsfeDetailContext(context: WsfeAuthorizationContext) {\n return (\n context.detailResult === \"R\" && context.headerResult !== \"A\" && !context.cae\n );\n}\n\nfunction isRejectedWsfeHeaderContext(context: WsfeAuthorizationContext) {\n return (\n context.headerResult === \"R\" &&\n context.detailResult === undefined &&\n !context.cae &&\n context.base.errors.length > 0 &&\n context.base.errors.every((issue) => issue.category === \"business\")\n );\n}\n\nfunction hasWsfeCaeContradiction(context: WsfeAuthorizationContext) {\n return (\n (context.resultCode === \"A\" || context.resultCode === \"R\") &&\n Boolean(context.cae)\n );\n}\n\nfunction createWsfeStructuredIndeterminate(\n context: WsfeAuthorizationContext,\n reason: ArcaAuthorizationIndeterminateReason\n): Extract<WsfeAuthorizationOutcome, { kind: \"indeterminate\" }> {\n const outcome: Extract<WsfeAuthorizationOutcome, { kind: \"indeterminate\" }> =\n {\n ...context.base,\n kind: \"indeterminate\",\n reason,\n };\n assignWsfeValue(outcome, \"result\", context.resultCode);\n assignWsfeValue(outcome, \"resultLevel\", context.resultLevel);\n assignWsfeValue(outcome, \"cae\", context.cae);\n assignWsfeValue(outcome, \"caeExpiry\", context.caeExpiry);\n return outcome;\n}\n\nfunction createWsfeResults(headerResult?: string, detailResult?: string) {\n const results: { header?: string; detail?: string } = {};\n assignWsfeValue(results, \"header\", headerResult);\n assignWsfeValue(results, \"detail\", detailResult);\n return results;\n}\n\nfunction createWsfeIndeterminateOutcome(\n error: unknown\n): WsfeAuthorizationOutcome {\n const authenticationError = classifyArcaAuthenticationError(error, {\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n });\n return {\n kind: \"indeterminate\",\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n results: {},\n reason: authenticationError\n ? \"authentication_rejected\"\n : getArcaIndeterminateReason(error),\n ...(authenticationError\n ? {\n authentication: createArcaAuthenticationEvidence(authenticationError),\n }\n : {}),\n errors: [],\n observations: [],\n };\n}\n\nfunction getArcaIndeterminateReason(\n error: unknown\n): ArcaAuthorizationIndeterminateReason {\n if (error instanceof ArcaTransportError) {\n return \"transport_error\";\n }\n if (error instanceof ArcaSoapFaultError) {\n return \"soap_fault\";\n }\n if (error instanceof ArcaInvalidSoapResponseError) {\n return \"invalid_response\";\n }\n return \"unexpected_error\";\n}\n\nfunction createWsfeOutcomeError(\n outcome: Exclude<WsfeAuthorizationOutcome, { kind: \"authorized\" }>\n) {\n if (outcome.kind === \"indeterminate\" && outcome.authentication) {\n return createArcaAuthenticationErrorFromEvidence(outcome.authentication, {\n service: \"wsfe\",\n operation: outcome.operation,\n });\n }\n\n const issues = [...outcome.errors, ...outcome.observations];\n const firstIssue = issues[0];\n const message = firstIssue\n ? formatWsfeIssue(firstIssue)\n : outcome.kind === \"rejected\"\n ? \"WSFE rejected the voucher authorization\"\n : outcome.result === \"A\"\n ? \"WSFE did not return CAE authorization data\"\n : \"WSFE did not return conclusive voucher authorization data\";\n\n return new ArcaServiceError(message, {\n service: \"wsfe\",\n operation: outcome.operation,\n ...(firstIssue?.code === undefined ? {} : { serviceCode: firstIssue.code }),\n ...(outcome.result === undefined ? {} : { result: outcome.result }),\n ...(outcome.resultLevel === undefined\n ? {}\n : { resultLevel: outcome.resultLevel }),\n results: outcome.results,\n ...(outcome.kind === \"indeterminate\" && outcome.cae\n ? { cae: outcome.cae }\n : {}),\n issues,\n });\n}\n\nfunction createWsfeServiceError(operation: string, issues: ArcaFiscalIssue[]) {\n const authenticationError = classifyArcaAuthenticationIssues(issues, {\n service: \"wsfe\",\n operation,\n });\n if (authenticationError) {\n return authenticationError;\n }\n\n const firstIssue = issues[0];\n return new ArcaServiceError(\n firstIssue ? formatWsfeIssue(firstIssue) : \"WSFE returned a service error\",\n {\n service: \"wsfe\",\n operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n issues,\n }\n );\n}\n\nfunction extractWsfeGlobalIssues(\n result: Record<string, unknown>,\n operation: string,\n resultLevel?: ArcaFiscalResultLevel\n): ArcaFiscalIssue[] {\n const errorsContainer = toWsfeRecord(result.Errors);\n return normalizeWsfeIssueEntries(errorsContainer?.Err).map((entry) => ({\n service: \"wsfe\",\n operation,\n source: \"error\",\n category:\n operation === \"FECAESolicitar\" &&\n WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES.has(entry.code ?? \"\")\n ? \"infrastructure\"\n : operation === \"FECAESolicitar\"\n ? \"business\"\n : \"unknown\",\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n ...(resultLevel === undefined ? {} : { resultLevel }),\n }));\n}\n\nfunction extractWsfeObservations(\n detail: Record<string, unknown>,\n category: ArcaFiscalIssue[\"category\"]\n): ArcaFiscalIssue[] {\n const observationsContainer = toWsfeRecord(detail.Observaciones);\n return normalizeWsfeIssueEntries(observationsContainer?.Obs).map((entry) => ({\n service: \"wsfe\",\n operation: \"FECAESolicitar\",\n source: \"observation\",\n category,\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n resultLevel: \"detail\",\n }));\n}\n\nfunction normalizeWsfeIssueEntries(rawErrors: unknown) {\n const entries = Array.isArray(rawErrors)\n ? rawErrors\n : rawErrors\n ? [rawErrors]\n : [];\n\n return entries\n .map((entry) => entry as Record<string, unknown>)\n .map((entry) => {\n const code = entry.Code ?? entry.code;\n const message = entry.Msg ?? entry.msg ?? \"Unknown WSFE error\";\n return {\n ...(code === undefined ? {} : { code: String(code) }),\n message: String(message),\n };\n });\n}\n\nfunction formatWsfeIssue(issue: ArcaFiscalIssue) {\n return issue.code ? `(${issue.code}) ${issue.message}` : issue.message;\n}\n\nfunction normalizeWsfeResult(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim().toUpperCase();\n return normalized || undefined;\n}\n\nfunction normalizeWsfeString(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const normalized = String(value).trim();\n return normalized || undefined;\n}\n\nfunction normalizeWsfeNumber(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const normalized = Number(value);\n return Number.isFinite(normalized) ? normalized : undefined;\n}\n\nfunction assignWsfeValue<TTarget, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined\n) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n\nfunction toWsfeRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nconst WSFE_AUTHORIZATION_INFRASTRUCTURE_CODES = new Set([\n \"500\",\n \"501\",\n \"502\",\n \"600\",\n \"601\",\n]);\n\nfunction getWsfeResultEntries(\n result: Record<string, unknown>,\n key: string\n): Record<string, unknown>[] {\n const rawEntries = (\n result.ResultGet as Record<string, unknown> | undefined\n )?.[key];\n if (!rawEntries) {\n return [];\n }\n\n return (Array.isArray(rawEntries) ? rawEntries : [rawEntries]).map(\n (entry) => entry as Record<string, unknown>\n );\n}\n","import {\n ARCA_CURRENCY_IDS,\n ARCA_VAT_RATES,\n ARCA_VOUCHER_TYPES,\n} from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n calculateVatMinorUnits,\n type SupportedVatRate,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport type { WsfeDateInput, WsfeVatRate, WsfeVoucherInput } from \"./wsfe\";\n\nexport type WsfeBuilderCurrencyInput =\n | {\n currency?: \"ARS\";\n exchangeRate?: never;\n sameCurrencyForeignCancellation?: never;\n }\n | {\n currency: \"USD\";\n exchangeRate: string;\n sameCurrencyForeignCancellation?: false;\n }\n | {\n currency: \"USD\";\n exchangeRate?: never;\n sameCurrencyForeignCancellation: true;\n };\n\nexport type WsfeBuilderVatRate = SupportedVatRate;\n\ntype WsfeInvoiceBuilderBaseInput = {\n salesPoint: number;\n concept: number;\n documentType: number;\n documentNumber: number;\n receiverVatConditionId: number;\n voucherDate: WsfeDateInput;\n serviceStartDate?: WsfeDateInput;\n serviceEndDate?: WsfeDateInput;\n paymentDueDate?: WsfeDateInput;\n};\n\nexport type BuildFacturaBInput = WsfeInvoiceBuilderBaseInput &\n WsfeBuilderCurrencyInput & {\n /** Positive integer currency minor units forming the taxable base. */\n taxableAmount: number;\n vatRate: WsfeBuilderVatRate;\n };\n\nexport type BuildFacturaCInput = WsfeInvoiceBuilderBaseInput &\n WsfeBuilderCurrencyInput & {\n amount: number;\n };\n\nconst VAT_RATE_IDS: Record<SupportedVatRate, number> = {\n 0: ARCA_VAT_RATES.IVA_0,\n 2.5: ARCA_VAT_RATES.IVA_2_5,\n 5: ARCA_VAT_RATES.IVA_5,\n 10.5: ARCA_VAT_RATES.IVA_10_5,\n 21: ARCA_VAT_RATES.IVA_21,\n 27: ARCA_VAT_RATES.IVA_27,\n};\n\n/** Builds a narrow Factura B exact WSFE input from integer currency minor units. */\nexport function buildFacturaB(input: BuildFacturaBInput): WsfeVoucherInput {\n const taxableMinorUnits = assertArcaMinorUnits(\n input.taxableAmount,\n \"taxableAmount\"\n );\n if (taxableMinorUnits === 0n) {\n throw new ArcaInputError(\n \"taxableAmount must be greater than zero for Factura B.\",\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field: \"taxableAmount\",\n expected: \"a positive safe integer in currency minor units\",\n }\n );\n }\n\n const vatMinorUnits = calculateVatMinorUnits(\n taxableMinorUnits,\n input.vatRate,\n \"vatRate\"\n );\n const totalMinorUnits = taxableMinorUnits + vatMinorUnits;\n const vatRateId = VAT_RATE_IDS[input.vatRate];\n\n if (vatRateId === undefined) {\n throw new ArcaInputError(\"vatRate is not a supported VAT rate.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"vatRate\",\n expected: \"one of 0, 2.5, 5, 10.5, 21, or 27\",\n });\n }\n\n if (input.vatRate !== 0 && vatMinorUnits === 0n) {\n throw new ArcaInputError(\n \"taxableAmount is too small to produce VAT at the selected positive vatRate.\",\n {\n code: \"ARCA_INPUT_INVALID_AMOUNT\",\n field: \"taxableAmount\",\n expected:\n \"an amount that rounds to at least one currency minor unit of VAT for a positive vatRate\",\n }\n );\n }\n\n const vatRates: WsfeVatRate[] = [\n Object.freeze({\n id: vatRateId,\n baseAmount: arcaMinorUnitsToNumber(taxableMinorUnits, \"taxableAmount\"),\n amount: arcaMinorUnitsToNumber(vatMinorUnits, \"vatAmount\"),\n }),\n ];\n Object.freeze(vatRates);\n\n return Object.freeze({\n ...buildCommonExactInput(input),\n voucherType: ARCA_VOUCHER_TYPES.FACTURA_B,\n totalAmount: arcaMinorUnitsToNumber(totalMinorUnits, \"totalAmount\"),\n nonTaxableAmount: 0,\n netAmount: arcaMinorUnitsToNumber(taxableMinorUnits, \"taxableAmount\"),\n exemptAmount: 0,\n taxAmount: 0,\n vatAmount: arcaMinorUnitsToNumber(vatMinorUnits, \"vatAmount\"),\n vatRates,\n });\n}\n\n/** Builds a narrow Factura C exact WSFE input from integer currency minor units. */\nexport function buildFacturaC(input: BuildFacturaCInput): WsfeVoucherInput {\n const amountMinorUnits = assertArcaMinorUnits(input.amount, \"amount\");\n const amount = arcaMinorUnitsToNumber(amountMinorUnits, \"amount\");\n\n return Object.freeze({\n ...buildCommonExactInput(input),\n voucherType: ARCA_VOUCHER_TYPES.FACTURA_C,\n totalAmount: amount,\n nonTaxableAmount: 0,\n // ARCA defines ImpNeto as the subtotal for class C vouchers.\n netAmount: amount,\n exemptAmount: 0,\n taxAmount: 0,\n vatAmount: 0,\n });\n}\n\nfunction buildCommonExactInput(\n input: WsfeInvoiceBuilderBaseInput & WsfeBuilderCurrencyInput\n): Pick<\n WsfeVoucherInput,\n | \"salesPoint\"\n | \"concept\"\n | \"documentType\"\n | \"documentNumber\"\n | \"receiverVatConditionId\"\n | \"voucherDate\"\n | \"currencyId\"\n | \"exchangeRate\"\n | \"sameCurrencyForeignCancellation\"\n | \"serviceStartDate\"\n | \"serviceEndDate\"\n | \"paymentDueDate\"\n> {\n return {\n salesPoint: input.salesPoint,\n concept: input.concept,\n documentType: input.documentType,\n documentNumber: input.documentNumber,\n receiverVatConditionId: input.receiverVatConditionId,\n voucherDate: input.voucherDate,\n ...normalizeBuilderCurrency(input),\n ...(input.serviceStartDate === undefined\n ? {}\n : { serviceStartDate: input.serviceStartDate }),\n ...(input.serviceEndDate === undefined\n ? {}\n : { serviceEndDate: input.serviceEndDate }),\n ...(input.paymentDueDate === undefined\n ? {}\n : { paymentDueDate: input.paymentDueDate }),\n };\n}\n\nfunction normalizeBuilderCurrency(\n input: WsfeBuilderCurrencyInput\n): Pick<\n WsfeVoucherInput,\n \"currencyId\" | \"exchangeRate\" | \"sameCurrencyForeignCancellation\"\n> {\n const unsafeInput = input as {\n currency?: string;\n exchangeRate?: unknown;\n sameCurrencyForeignCancellation?: unknown;\n };\n const currency = unsafeInput.currency ?? \"ARS\";\n\n if (\n unsafeInput.sameCurrencyForeignCancellation !== undefined &&\n typeof unsafeInput.sameCurrencyForeignCancellation !== \"boolean\"\n ) {\n throw new ArcaInputError(\n \"sameCurrencyForeignCancellation must be a boolean when provided.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"sameCurrencyForeignCancellation\",\n expected: \"true, false, or omitted\",\n }\n );\n }\n\n if (currency === \"ARS\") {\n if (unsafeInput.exchangeRate !== undefined) {\n throw new ArcaInputError(\n \"exchangeRate must be omitted when currency is ARS.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"omitted when currency is ARS\",\n }\n );\n }\n if (unsafeInput.sameCurrencyForeignCancellation !== undefined) {\n throw new ArcaInputError(\n \"sameCurrencyForeignCancellation applies only when currency is USD.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"sameCurrencyForeignCancellation\",\n expected: \"omitted when currency is ARS\",\n }\n );\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.ARS,\n exchangeRate: \"1\",\n };\n }\n\n if (currency !== \"USD\") {\n throw new ArcaInputError(\"currency is not supported by this builder.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"currency\",\n expected: \"ARS or USD\",\n });\n }\n\n if (unsafeInput.sameCurrencyForeignCancellation === true) {\n if (unsafeInput.exchangeRate !== undefined) {\n throw new ArcaInputError(\n \"exchangeRate must be omitted for same-currency foreign cancellation.\",\n {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"omitted when sameCurrencyForeignCancellation is true\",\n }\n );\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.USD,\n sameCurrencyForeignCancellation: \"S\",\n };\n }\n\n if (typeof unsafeInput.exchangeRate !== \"string\") {\n throw new ArcaInputError(\"exchangeRate is required for USD invoices.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected:\n \"a decimal string unless sameCurrencyForeignCancellation is true\",\n });\n }\n\n return {\n currencyId: ARCA_CURRENCY_IDS.USD,\n exchangeRate: serializeArcaExchangeRate(\n unsafeInput.exchangeRate,\n \"exchangeRate\"\n ),\n ...(unsafeInput.sameCurrencyForeignCancellation === false\n ? { sameCurrencyForeignCancellation: \"N\" as const }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,eAAe;AACrB,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,mBAAmB;AAGzB,IAAM,8BAA8B;AAEpC,IAAM,gCAAgC;AAEtC,IAAM,iCAAiC;AAKvC,IAAM,wBAA0D;AAAA,EAC9D,GAAG;AAAA,EACH,KAAK;AAAA,EACL,GAAG;AAAA,EACH,MAAM;AAAA,EACN,IAAI;AAAA,EACJ,IAAI;AACN;AAEO,SAAS,gCACd,OACA,OACQ;AACR,SAAO,sBAAsB;AAAA,IAC3B;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA,EACZ,CAAC;AACH;AAEO,SAAS,oBAAoB,OAAe,OAAuB;AACxE,SAAO,oBAAoB,gCAAgC,OAAO,KAAK,GAAG,CAAC;AAC7E;AAMO,SAAS,wBAAwB,OAAe,OAAuB;AAC5E,QAAM,SAAS,sBAAsB;AAAA,IACnC;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,SAAS;AAAA,IACT,UAAU;AAAA,EACZ,CAAC;AACD,SAAO,oBAAoB,QAAQ,CAAC;AACtC;AAEO,SAAS,0BACd,OACA,OACQ;AACR,QAAM,SACJ,OAAO,U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AO;AAAA,MACL,YAAY,kBAAkB;AAAA,MAC9B,iCAAiC;AAAA,IACnC;AAAA,EACF;AAEA,MAAI,OAAO,YAAY,iBAAiB,UAAU;AAChD,UAAM,IAAI,eAAe,8CAA8C;AAAA,MACrE,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UACE;AAAA,IACJ,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,YAAY,kBAAkB;AAAA,IAC9B,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ;AAAA,IACF;AAAA,IACA,GAAI,YAAY,oCAAoC,QAChD,EAAE,iCAAiC,IAAa,IAChD,CAAC;AAAA,EACP;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/services/wsmtxca.ts"],"sourcesContent":["import {\n ArcaInputError,\n ArcaInvalidSoapResponseError,\n ArcaServiceError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport {\n classifyArcaAuthenticationError,\n classifyArcaAuthenticationIssues,\n createArcaAuthenticationErrorFromEvidence,\n createArcaAuthenticationEvidence,\n executeWithAuthenticationRecovery,\n} from \"../internal/authentication\";\nimport type { ArcaClientConfig, ArcaRepresentedTaxId } from \"../internal/types\";\nimport type { SoapTransport } from \"../soap\";\nimport type { WsaaAuthModule } from \"../wsaa\";\nimport type {\n ArcaAuthorizationIndeterminateReason,\n ArcaAuthorizationOutcome,\n ArcaFiscalIssue,\n ArcaVoucherLookupResult,\n} from \"./fiscal-evidence\";\n\n/** Input data for one WSMTXCA voucher authorization. */\nexport type WsmtxcaAuthorizeVoucherInput = {\n representedTaxId?: ArcaRepresentedTaxId;\n data: Record<string, unknown>;\n forceRefresh?: boolean;\n};\n\n/** Result of a successful WSMTXCA voucher authorization. */\nexport type WsmtxcaAuthorizationResult = {\n cae: string;\n caeExpiry?: string;\n voucherNumber: number;\n messages: string[];\n raw: Record<string, unknown>;\n};\n\n/** Structured evidence from one exact WSMTXCA authorization attempt. */\nexport type WsmtxcaAuthorizationOutcome = ArcaAuthorizationOutcome<\"wsmtxca\">;\n\n/** Result of querying the last authorized voucher number. */\nexport type WsmtxcaLastAuthorizedVoucherResult = {\n voucherNumber: number;\n raw: Record<string, unknown>;\n};\n\n/** A point of sale enabled for WSMTXCA. */\nexport type WsmtxcaSalesPoint = {\n number: number;\n blocked: boolean;\n deletedAt?: string;\n};\n\n/** Result of querying WSMTXCA points of sale. */\nexport type WsmtxcaSalesPointsResult = {\n salesPoints: WsmtxcaSalesPoint[];\n raw: Record<string, unknown>;\n};\n\n/** Typed provider fields used to match one exact WSMTXCA voucher. */\nexport type WsmtxcaVoucherInfo = {\n voucherNumber?: number;\n invoiceDate?: string;\n salesPoint?: number;\n voucherType?: number;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n totalAmount?: number;\n subtotalAmount?: number;\n taxableAmount?: number;\n nonTaxableAmount?: number;\n exemptAmount?: number;\n taxAmount?: number;\n vatAmount?: number;\n currencyId?: string;\n exchangeRate?: number;\n cae?: string;\n caeExpiry?: string;\n raw: Record<string, unknown>;\n};\n\n/** Typed exact-voucher consultation result for WSMTXCA. */\nexport type WsmtxcaVoucherLookupOutcome = ArcaVoucherLookupResult<\n WsmtxcaVoucherInfo,\n \"wsmtxca\"\n>;\n\n/** Result of looking up a specific WSMTXCA voucher. */\nexport type WsmtxcaVoucherLookupResult = {\n invoiceDate: string;\n voucher: Record<string, unknown>;\n messages: string[];\n raw: Record<string, unknown>;\n};\n\n/** WSMTXCA electronic invoicing service (Factura de Crédito Electrónica). */\nexport type WsmtxcaService = {\n /** Attempts one authorization without transport retries and returns provider evidence. */\n authorizeVoucherOutcome(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationOutcome>;\n /** Authorizes a voucher and returns the CAE. */\n authorizeVoucher(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult>;\n /** Returns the last authorized voucher number for the given sales point and type. */\n getLastAuthorizedVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult>;\n /** Returns the points of sale enabled for WSMTXCA. */\n getSalesPoints(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult>;\n /** Consults one exact voucher and normalizes WSMTXCA error 1503 to `not_found`. */\n lookupVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome>;\n /** Retrieves details for a specific voucher. */\n getVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupResult>;\n};\n\nexport type CreateWsmtxcaServiceOptions = {\n config: ArcaClientConfig;\n auth: WsaaAuthModule;\n soap: SoapTransport;\n};\n\n/** Creates a WSMTXCA service instance wired with authentication and SOAP transport. */\nexport function createWsmtxcaService(\n options: CreateWsmtxcaServiceOptions\n): WsmtxcaService {\n async function executeWsmtxcaAuthenticatedOperation(\n operation: WsmtxcaOperation,\n input: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n },\n body: Record<string, unknown> = {},\n retries?: number\n ) {\n const auth = await options.auth.login(\"wsmtxca\", {\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n });\n const response = await options.soap.execute<\n Record<string, unknown>,\n Record<string, unknown>\n >({\n service: \"wsmtxca\",\n operation,\n ...(retries === undefined ? {} : { retries }),\n bodyElementName: `${operation}Request`,\n bodyElementNamespaceMode: \"prefix\",\n body: {\n ...body,\n authRequest: createWsmtxcaAuth(\n input.representedTaxId ?? options.config.taxId,\n auth.token,\n auth.sign\n ),\n },\n });\n\n return unwrapWsmtxcaOperationResponse(response.result, operation);\n }\n\n async function executeWsmtxcaAuthorization({\n representedTaxId,\n data,\n forceRefresh,\n }: WsmtxcaAuthorizeVoucherInput): Promise<{\n outcome: WsmtxcaAuthorizationOutcome;\n error?: unknown;\n }> {\n if (Object.hasOwn(data, \"authRequest\")) {\n throw new ArcaInputError(\n 'WSMTXCA authorization data cannot include the reserved top-level field \"authRequest\".',\n {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field: \"data.authRequest\",\n expected: \"omitted because facturas manages authentication fields\",\n }\n );\n }\n\n try {\n const raw = await executeWsmtxcaAuthenticatedOperation(\n \"autorizarComprobante\",\n { representedTaxId, forceRefresh },\n data,\n 0\n );\n return { outcome: classifyWsmtxcaAuthorization(raw) };\n } catch (error) {\n return {\n outcome: createWsmtxcaIndeterminateOutcome(error),\n error,\n };\n }\n }\n\n async function authorizeVoucherOutcome(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationOutcome> {\n return (await executeWsmtxcaAuthorization(input)).outcome;\n }\n\n function authorizeVoucher(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n forceRefresh: input.forceRefresh,\n execute: (forceRefresh) =>\n authorizeVoucherOnce({ ...input, forceRefresh }),\n });\n }\n\n async function authorizeVoucherOnce(\n input: WsmtxcaAuthorizeVoucherInput\n ): Promise<WsmtxcaAuthorizationResult> {\n const execution = await executeWsmtxcaAuthorization(input);\n if (execution.error) {\n throw execution.error;\n }\n if (execution.outcome.kind !== \"authorized\") {\n throw createWsmtxcaOutcomeError(execution.outcome);\n }\n\n const { outcome } = execution;\n return {\n cae: outcome.cae,\n ...(outcome.caeExpiry === undefined\n ? {}\n : { caeExpiry: outcome.caeExpiry }),\n voucherNumber: outcome.voucherNumber,\n messages: formatWsmtxcaIssues([\n ...outcome.errors,\n ...outcome.observations,\n ]),\n raw: outcome.raw ?? {},\n };\n }\n\n function getLastAuthorizedVoucher({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarUltimoComprobanteAutorizado\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n getLastAuthorizedVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function getLastAuthorizedVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaLastAuthorizedVoucherResult> {\n const operation = \"consultarUltimoComprobanteAutorizado\";\n const raw = await executeWsmtxcaAuthenticatedOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n consultaUltimoComprobanteAutorizadoRequest: {\n codigoTipoComprobante: voucherType,\n numeroPuntoVenta: salesPoint,\n },\n }\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"1502\")) {\n return { voucherNumber: 0, raw };\n }\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n\n return {\n voucherNumber: parseWsmtxcaVoucherNumber(\n raw.numeroComprobante ?? raw.cbteNro ?? raw.nroComprobante,\n \"WSMTXCA did not return the last authorized voucher number\",\n true\n ),\n raw,\n };\n }\n\n function getSalesPoints({\n representedTaxId,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarPuntosVenta\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n getSalesPointsOnce({\n representedTaxId,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function getSalesPointsOnce({\n representedTaxId,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaSalesPointsResult> {\n const operation = \"consultarPuntosVenta\";\n const raw = await executeWsmtxcaAuthenticatedOperation(operation, {\n representedTaxId,\n forceRefresh,\n });\n throwForWsmtxcaOperationErrors(operation, raw);\n const rawSalesPoints = toRecord(raw.arrayPuntosVenta)?.puntoVenta;\n const entries = Array.isArray(rawSalesPoints)\n ? rawSalesPoints\n : rawSalesPoints\n ? [rawSalesPoints]\n : [];\n const salesPoints = entries.flatMap((entry) => {\n const record = toRecord(entry);\n const number = parseOptionalPositiveInteger(record?.numeroPuntoVenta);\n if (number === undefined) {\n return [];\n }\n const deletedAt = normalizeWsmtxcaResponseDate(record?.fechaBaja);\n return [\n {\n number,\n blocked: String(record?.bloqueado ?? \"N\").toUpperCase() === \"S\",\n ...(deletedAt === undefined ? {} : { deletedAt }),\n },\n ];\n });\n\n return { salesPoints, raw };\n }\n\n function lookupVoucher({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome> {\n return executeWithAuthenticationRecovery({\n service: \"wsmtxca\",\n operation: \"consultarComprobante\",\n forceRefresh,\n execute: (attemptForceRefresh) =>\n lookupVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh: attemptForceRefresh,\n }),\n });\n }\n\n async function lookupVoucherOnce({\n representedTaxId,\n voucherType,\n salesPoint,\n voucherNumber,\n forceRefresh,\n }: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupOutcome> {\n const operation = \"consultarComprobante\";\n const raw = await executeWsmtxcaAuthenticatedOperation(\n operation,\n { representedTaxId, forceRefresh },\n {\n consultaComprobanteRequest: {\n codigoTipoComprobante: voucherType,\n numeroPuntoVenta: salesPoint,\n numeroComprobante: voucherNumber,\n },\n }\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n const observations = extractWsmtxcaIssues(raw, operation, \"observation\");\n\n if (errors.length > 0 && errors.every((issue) => issue.code === \"1503\")) {\n return {\n kind: \"not_found\",\n service: \"wsmtxca\",\n operation,\n errors,\n observations,\n raw,\n };\n }\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n\n const voucher = extractWsmtxcaVoucherPayload(raw);\n if (voucher === raw && !toRecord(raw.comprobante)) {\n throw new ArcaServiceError(\n \"WSMTXCA did not return the voucher issue date\",\n {\n service: \"wsmtxca\",\n operation,\n issues: observations,\n }\n );\n }\n\n return {\n kind: \"found\",\n service: \"wsmtxca\",\n operation,\n voucher: mapWsmtxcaVoucherInfo(voucher),\n observations,\n raw,\n };\n }\n\n async function getVoucher(input: {\n representedTaxId?: ArcaRepresentedTaxId;\n voucherType: number;\n salesPoint: number;\n voucherNumber: number;\n forceRefresh?: boolean;\n }): Promise<WsmtxcaVoucherLookupResult> {\n const lookup = await lookupVoucher(input);\n if (lookup.kind === \"not_found\") {\n throw createWsmtxcaServiceError(lookup.operation, lookup.errors);\n }\n\n const invoiceDate = lookup.voucher.invoiceDate;\n if (!invoiceDate) {\n throw new ArcaServiceError(\n formatWsmtxcaIssues(lookup.observations)[0] ??\n \"WSMTXCA did not return the voucher issue date\",\n {\n service: \"wsmtxca\",\n operation: lookup.operation,\n issues: lookup.observations,\n }\n );\n }\n\n return {\n invoiceDate,\n voucher: lookup.voucher.raw,\n messages: formatWsmtxcaIssues(lookup.observations),\n raw: lookup.raw,\n };\n }\n\n return {\n authorizeVoucherOutcome,\n authorizeVoucher,\n getLastAuthorizedVoucher,\n getSalesPoints,\n lookupVoucher,\n getVoucher,\n };\n}\n\nfunction createWsmtxcaAuth(\n representedTaxId: number | string,\n token: string,\n sign: string\n) {\n return {\n token,\n sign,\n cuitRepresentada: Number.parseInt(String(representedTaxId), 10),\n };\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\ntype WsmtxcaOperation =\n | \"autorizarComprobante\"\n | \"consultarUltimoComprobanteAutorizado\"\n | \"consultarPuntosVenta\"\n | \"consultarComprobante\";\n\nfunction unwrapWsmtxcaOperationResponse(\n response: unknown,\n operation: WsmtxcaOperation\n) {\n const responseRecord = toRecord(response) ?? {};\n\n if (operation === \"autorizarComprobante\") {\n return (\n toRecord(responseRecord.autorizarComprobanteResponse) ??\n toRecord(responseRecord.autorizarComprobanteResult) ??\n toRecord(responseRecord.comprobanteCAEResponse) ??\n toRecord(responseRecord.comprobanteCAEReponse) ??\n responseRecord\n );\n }\n\n if (operation === \"consultarComprobante\") {\n return (\n toRecord(responseRecord.consultarComprobanteResponse) ??\n toRecord(responseRecord.consultaComprobanteResponse) ??\n toRecord(responseRecord.consultarComprobanteResult) ??\n responseRecord\n );\n }\n\n if (operation === \"consultarPuntosVenta\") {\n return (\n toRecord(responseRecord.consultarPuntosVentaResponse) ??\n toRecord(responseRecord.consultarPuntosVentaResult) ??\n responseRecord\n );\n }\n\n return (\n toRecord(responseRecord.consultarUltimoComprobanteAutorizadoResponse) ??\n toRecord(responseRecord.consultaUltimoComprobanteAutorizadoResponse) ??\n toRecord(responseRecord.consultarUltimoComprobanteAutorizadoResult) ??\n responseRecord\n );\n}\n\nfunction extractWsmtxcaAuthorizationPayload(raw: Record<string, unknown>) {\n return (\n toRecord(raw.comprobanteResponse) ??\n toRecord(raw.comprobanteCAEResponse) ??\n toRecord(raw.comprobanteCAEReponse) ??\n raw\n );\n}\n\nfunction extractWsmtxcaVoucherPayload(raw: Record<string, unknown>) {\n return (\n toRecord(raw.comprobanteResponse) ??\n toRecord(raw.comprobante) ??\n toRecord(raw.cmp) ??\n raw\n );\n}\n\nfunction classifyWsmtxcaAuthorization(\n raw: Record<string, unknown>\n): WsmtxcaAuthorizationOutcome {\n const operation = \"autorizarComprobante\";\n const payload = extractWsmtxcaAuthorizationPayload(raw);\n const result = normalizeWsmtxcaResult(raw.resultado ?? payload.resultado);\n const cae = normalizeWsmtxcaString(\n payload.CAE ?? payload.codigoAutorizacion ?? raw.codigoAutorizacion\n );\n const caeExpiry = normalizeWsmtxcaResponseDate(\n payload.fechaVencimientoCAE ??\n payload.fechaVencimiento ??\n raw.fechaVencimiento\n );\n const voucherNumber = parseOptionalPositiveInteger(\n payload.numeroComprobante ?? raw.numeroComprobante\n );\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n const observations = extractWsmtxcaIssues(raw, operation, \"observation\");\n const base = {\n service: \"wsmtxca\" as const,\n operation,\n results: createWsmtxcaResults(result),\n errors,\n observations,\n raw,\n };\n\n const authenticationOutcome = createWsmtxcaAuthenticationOutcome({\n base,\n result,\n cae,\n voucherNumber,\n });\n if (authenticationOutcome) {\n return authenticationOutcome;\n }\n\n if (\n (result === \"A\" || result === \"O\") &&\n cae &&\n voucherNumber !== undefined &&\n errors.length === 0\n ) {\n return {\n ...base,\n kind: \"authorized\",\n result,\n resultLevel: \"operation\",\n cae,\n ...(caeExpiry === undefined ? {} : { caeExpiry }),\n voucherNumber,\n };\n }\n\n if (result === \"R\" && !cae && errors.length > 0) {\n return {\n ...base,\n kind: \"rejected\",\n result: \"R\",\n resultLevel: \"operation\",\n };\n }\n\n const outcome: WsmtxcaAuthorizationOutcome = {\n ...base,\n kind: \"indeterminate\",\n reason:\n (result === \"R\" && Boolean(cae)) ||\n ((result === \"A\" || result === \"O\") && Boolean(errors.length))\n ? \"contradictory_response\"\n : \"incomplete_response\",\n ...(result === undefined ? {} : { result }),\n ...(result === undefined ? {} : { resultLevel: \"operation\" }),\n };\n assignWsmtxcaValue(outcome, \"cae\", cae);\n assignWsmtxcaValue(outcome, \"caeExpiry\", caeExpiry);\n assignWsmtxcaValue(outcome, \"voucherNumber\", voucherNumber);\n return outcome;\n}\n\nfunction createWsmtxcaAuthenticationOutcome({\n base,\n result,\n cae,\n voucherNumber,\n}: {\n base: {\n service: \"wsmtxca\";\n operation: string;\n results: ReturnType<typeof createWsmtxcaResults>;\n errors: ArcaFiscalIssue[];\n observations: ArcaFiscalIssue[];\n raw: Record<string, unknown>;\n };\n result?: string;\n cae?: string;\n voucherNumber?: number;\n}): WsmtxcaAuthorizationOutcome | undefined {\n const authenticationError = classifyArcaAuthenticationIssues(base.errors, {\n service: base.service,\n operation: base.operation,\n });\n if (\n !authenticationError ||\n result === \"A\" ||\n result === \"O\" ||\n cae ||\n voucherNumber !== undefined\n ) {\n return undefined;\n }\n\n return {\n ...base,\n kind: \"indeterminate\",\n reason: \"authentication_rejected\",\n authentication: createArcaAuthenticationEvidence(authenticationError),\n ...(result === undefined ? {} : { result }),\n ...(result === undefined ? {} : { resultLevel: \"operation\" }),\n };\n}\n\nfunction createWsmtxcaIndeterminateOutcome(\n error: unknown\n): WsmtxcaAuthorizationOutcome {\n const authenticationError = classifyArcaAuthenticationError(error, {\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n });\n return {\n kind: \"indeterminate\",\n service: \"wsmtxca\",\n operation: \"autorizarComprobante\",\n results: {},\n reason: authenticationError\n ? \"authentication_rejected\"\n : getWsmtxcaIndeterminateReason(error),\n ...(authenticationError\n ? {\n authentication: createArcaAuthenticationEvidence(authenticationError),\n }\n : {}),\n errors: [],\n observations: [],\n };\n}\n\nfunction getWsmtxcaIndeterminateReason(\n error: unknown\n): ArcaAuthorizationIndeterminateReason {\n if (error instanceof ArcaTransportError) {\n return \"transport_error\";\n }\n if (error instanceof ArcaSoapFaultError) {\n return \"soap_fault\";\n }\n if (error instanceof ArcaInvalidSoapResponseError) {\n return \"invalid_response\";\n }\n return \"unexpected_error\";\n}\n\nfunction createWsmtxcaOutcomeError(\n outcome: Exclude<WsmtxcaAuthorizationOutcome, { kind: \"authorized\" }>\n) {\n if (outcome.kind === \"indeterminate\" && outcome.authentication) {\n return createArcaAuthenticationErrorFromEvidence(outcome.authentication, {\n service: \"wsmtxca\",\n operation: outcome.operation,\n });\n }\n\n const issues = [...outcome.errors, ...outcome.observations];\n const messages = formatWsmtxcaIssues(issues);\n const firstIssue = issues[0];\n return new ArcaServiceError(\n messages.join(\" | \") ||\n (outcome.kind === \"rejected\"\n ? \"WSMTXCA rejected the voucher authorization\"\n : \"WSMTXCA did not return conclusive voucher authorization data\"),\n {\n service: \"wsmtxca\",\n operation: outcome.operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n ...(outcome.result === undefined ? {} : { result: outcome.result }),\n ...(outcome.resultLevel === undefined\n ? {}\n : { resultLevel: outcome.resultLevel }),\n results: outcome.results,\n ...(outcome.kind === \"indeterminate\" && outcome.cae\n ? { cae: outcome.cae }\n : {}),\n issues,\n }\n );\n}\n\nfunction createWsmtxcaResults(operationResult?: string) {\n const results: { operation?: string } = {};\n assignWsmtxcaValue(results, \"operation\", operationResult);\n return results;\n}\n\nfunction createWsmtxcaServiceError(\n operation: string,\n issues: ArcaFiscalIssue[]\n) {\n const authenticationError = classifyArcaAuthenticationIssues(issues, {\n service: \"wsmtxca\",\n operation,\n });\n if (authenticationError) {\n return authenticationError;\n }\n\n const firstIssue = issues[0];\n return new ArcaServiceError(\n formatWsmtxcaIssues(issues).join(\" | \") ||\n \"WSMTXCA returned a service error\",\n {\n service: \"wsmtxca\",\n operation,\n ...(firstIssue?.code === undefined\n ? {}\n : { serviceCode: firstIssue.code }),\n issues,\n }\n );\n}\n\nfunction throwForWsmtxcaOperationErrors(\n operation: string,\n raw: Record<string, unknown>\n): void {\n const errors = extractWsmtxcaIssues(raw, operation, \"error\");\n if (errors.length > 0) {\n throw createWsmtxcaServiceError(operation, errors);\n }\n}\n\nfunction extractWsmtxcaIssues(\n raw: Record<string, unknown>,\n operation: string,\n source: \"error\" | \"observation\"\n): ArcaFiscalIssue[] {\n const container = toRecord(\n source === \"error\" ? raw.arrayErrores : raw.arrayObservaciones\n );\n return normalizeWsmtxcaIssueEntries(container?.codigoDescripcion).map(\n (entry) => ({\n service: \"wsmtxca\",\n operation,\n source,\n category:\n source === \"observation\"\n ? \"observation\"\n : operation === \"autorizarComprobante\"\n ? \"business\"\n : \"unknown\",\n ...(entry.code === undefined ? {} : { code: entry.code }),\n message: entry.message,\n ...(operation === \"autorizarComprobante\"\n ? { resultLevel: \"operation\" as const }\n : {}),\n })\n );\n}\n\nfunction normalizeWsmtxcaIssueEntries(value: unknown) {\n const entries = Array.isArray(value) ? value : value ? [value] : [];\n return entries.map((entry) => {\n const record = toRecord(entry) ?? {};\n const code = record.codigo;\n const description = record.descripcion;\n return {\n ...(code === undefined || code === null ? {} : { code: String(code) }),\n message:\n description === undefined || description === null\n ? \"Unknown WSMTXCA issue\"\n : String(description),\n };\n });\n}\n\nfunction formatWsmtxcaIssues(issues: ArcaFiscalIssue[]): string[] {\n return issues.map((issue) => {\n const prefix = issue.source === \"error\" ? \"Error\" : \"Obs\";\n return `${prefix}${issue.code ? ` ${issue.code}` : \"\"}: ${issue.message}`;\n });\n}\n\nfunction mapWsmtxcaVoucherInfo(\n raw: Record<string, unknown>\n): WsmtxcaVoucherInfo {\n const voucher: WsmtxcaVoucherInfo = { raw };\n const invoiceDate = normalizeWsmtxcaResponseDate(\n raw.fechaEmision ?? raw.fecha ?? raw.CbteFch\n );\n const cae = normalizeWsmtxcaString(raw.codigoAutorizacion ?? raw.CAE);\n const caeExpiry = normalizeWsmtxcaResponseDate(\n raw.fechaVencimiento ?? raw.fechaVencimientoCAE\n );\n const vatAmount = sumWsmtxcaVatAmounts(raw.arraySubtotalesIVA);\n\n assignWsmtxcaValue(\n voucher,\n \"voucherNumber\",\n parseOptionalPositiveInteger(raw.numeroComprobante)\n );\n assignWsmtxcaValue(voucher, \"invoiceDate\", invoiceDate);\n assignWsmtxcaValue(\n voucher,\n \"salesPoint\",\n parseOptionalPositiveInteger(raw.numeroPuntoVenta)\n );\n assignWsmtxcaValue(\n voucher,\n \"voucherType\",\n parseOptionalPositiveInteger(raw.codigoTipoComprobante)\n );\n assignWsmtxcaValue(\n voucher,\n \"concept\",\n parseOptionalNumber(raw.codigoConcepto)\n );\n assignWsmtxcaValue(\n voucher,\n \"documentType\",\n parseOptionalNumber(raw.codigoTipoDocumento)\n );\n assignWsmtxcaValue(\n voucher,\n \"documentNumber\",\n normalizeWsmtxcaString(raw.numeroDocumento)\n );\n assignWsmtxcaValue(\n voucher,\n \"receiverVatConditionId\",\n parseOptionalNumber(raw.condicionIVAReceptor)\n );\n assignWsmtxcaValue(\n voucher,\n \"totalAmount\",\n parseOptionalNumber(raw.importeTotal)\n );\n assignWsmtxcaValue(\n voucher,\n \"subtotalAmount\",\n parseOptionalNumber(raw.importeSubtotal)\n );\n assignWsmtxcaValue(\n voucher,\n \"taxableAmount\",\n parseOptionalNumber(raw.importeGravado)\n );\n assignWsmtxcaValue(\n voucher,\n \"nonTaxableAmount\",\n parseOptionalNumber(raw.importeNoGravado)\n );\n assignWsmtxcaValue(\n voucher,\n \"exemptAmount\",\n parseOptionalNumber(raw.importeExento)\n );\n assignWsmtxcaValue(\n voucher,\n \"taxAmount\",\n parseOptionalNumber(raw.importeOtrosTributos)\n );\n assignWsmtxcaValue(voucher, \"vatAmount\", vatAmount);\n assignWsmtxcaValue(\n voucher,\n \"currencyId\",\n normalizeWsmtxcaString(raw.codigoMoneda)\n );\n assignWsmtxcaValue(\n voucher,\n \"exchangeRate\",\n parseOptionalNumber(raw.cotizacionMoneda)\n );\n assignWsmtxcaValue(voucher, \"cae\", cae);\n assignWsmtxcaValue(voucher, \"caeExpiry\", caeExpiry);\n\n return voucher;\n}\n\nfunction sumWsmtxcaVatAmounts(value: unknown): number | undefined {\n const subtotals = toRecord(value)?.subtotalIVA;\n const entries = Array.isArray(subtotals)\n ? subtotals\n : subtotals\n ? [subtotals]\n : [];\n const amounts = entries\n .map((entry) => parseOptionalNumber(toRecord(entry)?.importe))\n .filter((amount): amount is number => amount !== undefined);\n return amounts.length > 0\n ? amounts.reduce((total, amount) => total + amount, 0)\n : undefined;\n}\n\nfunction parseWsmtxcaVoucherNumber(\n value: unknown,\n message: string,\n allowZero = false\n) {\n const parsed = Number.parseInt(String(value ?? \"\"), 10);\n if (!Number.isFinite(parsed) || (allowZero ? parsed < 0 : parsed <= 0)) {\n throw new ArcaServiceError(message, {\n service: \"wsmtxca\",\n });\n }\n return parsed;\n}\n\nfunction parseOptionalPositiveInteger(value: unknown): number | undefined {\n const parsed = Number.parseInt(String(value ?? \"\"), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction parseOptionalNumber(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction normalizeWsmtxcaResult(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim().toUpperCase();\n return normalized || undefined;\n}\n\nfunction normalizeWsmtxcaString(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const normalized = String(value).trim();\n return normalized || undefined;\n}\n\nfunction assignWsmtxcaValue<TTarget, TKey extends keyof TTarget>(\n target: TTarget,\n key: TKey,\n value: TTarget[TKey] | undefined\n) {\n if (value !== undefined) {\n target[key] = value;\n }\n}\n\nfunction normalizeWsmtxcaResponseDate(value: unknown): string | undefined {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return formatCompactDateToIso(value);\n }\n\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n\n if (/^\\d{8}$/.test(trimmed)) {\n return formatCompactDateToIso(Number.parseInt(trimmed, 10));\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(trimmed)) {\n return trimmed.slice(0, 10);\n }\n\n return undefined;\n}\n\nfunction formatCompactDateToIso(dateValue?: number | null): string | undefined {\n if (!dateValue) {\n return undefined;\n }\n\n const raw = String(dateValue);\n if (raw.length !== 8) {\n return undefined;\n }\n\n return `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmJO,SAAS,qBACd,SACgB;AAChB,iBAAe,qCACb,WACA,OAIA,OAAgC,CAAC,GACjC,SACA;AACA,UAAM,OAAO,MAAM,QAAQ,KAAK,MAAM,WAAW;AAAA,MAC/C,kBAAkB,MAAM;AAAA,MACxB,cAAc,MAAM;AAAA,IACtB,CAAC;AACD,UAAM,WAAW,MAAM,QAAQ,KAAK,QAGlC;AAAA,MACA,SAAS;AAAA,MACT;AAAA,MACA,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAAA,MAC3C,iBAAiB,GAAG,SAAS;AAAA,MAC7B,0BAA0B;AAAA,MAC1B,MAAM;AAAA,QACJ,GAAG;AAAA,QACH,aAAa;AAAA,UACX,MAAM,oBAAoB,QAAQ,OAAO;AAAA,UACzC,KAAK;AAAA,UACL,KAAK;AAAA,QACP;AAAA,MACF;AAAA,IACF,CAAC;AAED,WAAO,+BAA+B,SAAS,QAAQ,SAAS;AAAA,EAClE;AAEA,iBAAe,4BAA4B;AAAA,IACzC;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAGG;AACD,QAAI,OAAO,OAAO,MAAM,aAAa,GAAG;AACtC,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,UACE,MAAM;AAAA,UACN,OAAO;AAAA,UACP,UAAU;AAAA,QACZ;AAAA,MACF;AAAA,IACF;AAEA,QAAI;AACF,YAAM,MAAM,MAAM;AAAA,QAChB;AAAA,QACA,EAAE,kBAAkB,aAAa;AAAA,QACjC;AAAA,QACA;AAAA,MACF;AACA,aAAO,EAAE,SAA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