facturas 0.25.1 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/{chunk-EL7OXUFE.mjs → chunk-NZ6KEUSM.mjs} +27 -14
- package/dist/chunk-NZ6KEUSM.mjs.map +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-BK-aaWiG.d.ts → client-n_Bkci4D.d.ts} +3 -1
- package/dist/index.d.ts +23 -5
- package/dist/index.mjs +132 -37
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-EL7OXUFE.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/services/voucher-document.ts","../src/store/memory.ts","../src/store/postgres.ts","../src/store/redis.ts"],"sourcesContent":["import { ArcaInputError } from \"../errors\";\nimport { normalizeArcaAmountToMinorUnits } from \"../internal/decimal\";\nimport { describeVoucherType } from \"./issuance-fields\";\nimport type { IssuedVoucher, VoucherTotals } from \"./vouchers-types\";\nimport {\n type AmountItem,\n calculateWsfeAmounts,\n settleVatItems,\n type VatItem,\n type VatRate,\n vatRateId,\n vatRatePercent,\n} from \"./wsfe-amounts\";\n\n/**\n * Fixed texts a printed voucher carries, as the norms word them. Rule ids\n * refer to `.github/PRINTED_VOUCHER_SOURCES.md`.\n */\nexport const PRINTED_VOUCHER_TEXT = {\n /** L4, before the voucher type code. */\n code: \"Código Nº\",\n /** C7, before the start of activities. */\n activitiesStart: \"INICIO DE ACTIVIDADES\",\n /** C8 and L9, before the CAE. */\n cae: \"C.A.E. N°\",\n /** C9 and L9, before the CAE due date, in type of at least 12 pt. */\n caeDueDate: \"Fecha Vto.:\",\n /** L8, the title of the consumer transparency block. */\n transparencyTitle:\n \"Régimen de Transparencia Fiscal al Consumidor (Ley 27.743)\",\n /** L8, the VAT contained in the price. */\n vatContained: \"IVA Contenido\",\n /** L8 and C24, the other national indirect taxes. */\n otherNationalIndirectTaxes: \"Otros Impuestos Nacionales Indirectos\",\n} as const;\n\n/** L9 asks for at least this type size for the CAE due date. */\nexport const PRINTED_CAE_DUE_DATE_MIN_FONT_SIZE_PT = 12;\n\n/** The issuer conditions a printed voucher can name (C5). */\nexport type PrintedIssuerCondition =\n | \"responsable_inscripto\"\n | \"exento\"\n | \"no_alcanzado\"\n | \"monotributo\"\n | \"monotributo_social\"\n | \"monotributo_trabajador_independiente_promovido\";\n\nexport type VoucherDocumentInput = {\n /** The voucher `issue()`, a note method or `recover()` answered authorized. */\n voucher: IssuedVoucher;\n /**\n * The same items the voucher was issued from, each with its description.\n * With a `globalDiscount`, the items before it.\n */\n items: readonly (VatItem | AmountItem)[];\n /**\n * A discount on the whole voucher, in minor units, that the issuer took off\n * the items it issued. Class A and B take it by ARCA VAT rate id, as the\n * authorized VAT rows: net on class A, with VAT on class B, as the lines.\n * Class C takes one amount. The SDK does not split it: each rate's lines,\n * less its discount, must add up to the authorized base of that rate.\n */\n globalDiscount?: number | Readonly<Record<number, number>>;\n issuer: {\n /** C1. */\n legalName: string;\n /** L1, only when the issuer has one. */\n tradeName?: string;\n /** C2: where the voucher is issued, or the fiscal address for travelling sellers. */\n address: string;\n /** C3, checked against the voucher's QR. */\n taxId: string;\n /** C5. */\n condition: PrintedIssuerCondition;\n /** C4: the ingresos brutos number, or the non-contributor condition. */\n grossIncome: string;\n /**\n * C7 as `YYYY-MM-DD`. `null` only for university professionals billing\n * their fees and service providers without premises (Anexo II, A, V 6).\n */\n activitiesStartDate: string | null;\n /**\n * G5: the issuer opted to issue class A \"PAGO EN CBU INFORMADA\" (RG 5762,\n * art. 20 and 21). Only class A vouchers print it.\n */\n paymentToInformedCbu?: boolean;\n };\n /**\n * G3: the observations ARCA returned with the CAE, as\n * `authorization.observations` of an `authorized` outcome carries them. On a\n * class A voucher their codes are printed (RG 4291, art. 12 and 14 c)).\n */\n observations?: readonly { code?: string | number }[];\n /** C13 to C17. Name and address are required unless the receiver is a consumidor final. */\n receiver?: { name?: string; address?: string };\n /** L6: contado, cuenta corriente and so on. */\n saleConditions: string;\n /** C12: the remitos issued for the operation, when there are any. */\n remitos?: readonly string[];\n};\n\nexport type VoucherDocumentLine = {\n code?: string;\n description: string;\n quantity: number;\n unit?: number;\n /** Major-unit decimal string: without VAT on class A, with VAT on class B. */\n unitPrice: string;\n discount?: number;\n /** Minor units: without VAT on class A, with VAT on class B, as issued on class C. */\n amount: number;\n /** Class A only: the line's rate, `exempt` or `untaxed`. */\n vatRate?: VatRate;\n};\n\n/**\n * Everything a printed voucher shows, derived and checked. Money is in minor\n * units of the voucher currency and dates are `YYYY-MM-DD`. Formatting and\n * layout belong to the renderer.\n */\nexport type VoucherDocument = {\n voucherClass: \"A\" | \"B\" | \"C\";\n voucherType: number;\n /** L4: the type code, three digits. */\n code: string;\n /** G4 and G5: the legend printed next to the letter A, when there is one. */\n letterLegend?: \"OPERACIÓN SUJETA A RETENCIÓN\" | \"PAGO EN CBU INFORMADA\";\n title: \"FACTURA\" | \"NOTA DE DÉBITO\" | \"NOTA DE CRÉDITO\";\n /** C6: sales point and number, `00003-00000041`. */\n number: string;\n /** C11. */\n issueDate: string;\n issuer: {\n tradeName?: string;\n legalName: string;\n address: string;\n taxId: string;\n conditionLegend: string;\n grossIncome: string;\n activitiesStartDate?: string;\n };\n receiver: {\n conditionLegend: string;\n name?: string;\n address?: string;\n /** Absent for an unidentified consumidor final. */\n document?: { type: number; label?: string; number: string };\n };\n saleConditions: string;\n remitos: string[];\n /** Concepts 2 and 3. */\n servicePeriod?: { from: string; to: string };\n paymentDueDate?: string;\n /** C22: the exchange rate is present for any currency but pesos. */\n currency: { id: string; exchangeRate?: string };\n lines: VoucherDocumentLine[];\n totals: {\n /**\n * The sum of the input's `globalDiscount`, 0 without one: net on class A,\n * with VAT on class B. The lines are before it and the subtotal after it.\n */\n globalDiscount: number;\n /**\n * Class A: net taxed. Class B: the lines with VAT. Class C: the lines.\n * Classes B and C take the global discount off the lines.\n */\n subtotal: number;\n exempt: number;\n untaxed: number;\n /** C25 and L7, class A only: one row per rate, as authorized. */\n vatRates: { id: number; rate?: number; base: number; amount: number }[];\n /** C23: ARCA's Tributos. */\n otherTaxes: { id: number; description: string; amount: number }[];\n /** C23: a VAT adjustment of the header that no line could carry. */\n adjustment: number;\n total: number;\n };\n /** L8 and G2, class B only. */\n transparency?: { vatContained: number; otherNationalIndirectTaxes: number };\n /** C8, C9 and L9. */\n authorization: { kind: \"CAE\"; code: string; dueDate: string };\n /** Q1 and Q2. */\n qr: string;\n /** Conditional legends, in order, each with its rule id. */\n legends: { rule: \"G1\" | \"G3\"; text: string }[];\n};\n\nconst ISSUER_LEGENDS: Record<PrintedIssuerCondition, string> = {\n responsable_inscripto: \"IVA RESPONSABLE INSCRIPTO\",\n exento: \"IVA EXENTO\",\n no_alcanzado: \"NO RESPONSABLE IVA\",\n monotributo: \"RESPONSABLE MONOTRIBUTO\",\n monotributo_social: \"MONOTRIBUTISTA SOCIAL\",\n monotributo_trabajador_independiente_promovido:\n \"MONOTRIBUTO TRABAJADOR INDEPENDIENTE PROMOVIDO\",\n};\n\n/** ARCA receiver IVA condition ids and their C13 to C17 legends. */\nconst RECEIVER_LEGENDS: Record<number, string> = {\n 1: \"IVA RESPONSABLE INSCRIPTO\",\n 4: \"IVA EXENTO\",\n 5: \"A CONSUMIDOR FINAL\",\n 6: \"RESPONSABLE MONOTRIBUTO\",\n 7: \"SUJETO NO CATEGORIZADO\",\n // Apartado A names no legend for these: ARCA's own condition names.\n 8: \"PROVEEDOR DEL EXTERIOR\",\n 9: \"CLIENTE DEL EXTERIOR\",\n 10: \"IVA LIBERADO - LEY Nº 19.640\",\n 13: \"MONOTRIBUTISTA SOCIAL\",\n 15: \"NO RESPONSABLE IVA\",\n 16: \"MONOTRIBUTO TRABAJADOR INDEPENDIENTE PROMOVIDO\",\n};\nconst CONSUMIDOR_FINAL = 5;\n/** C26 and G2: exento, consumidor final and no alcanzado. */\nconst VAT_CONTAINED_RECEIVERS = new Set([4, 5, 15]);\nconst MONOTRIBUTO_RECEIVERS = new Set([6, 13, 16]);\n\nconst DOCUMENT_LABELS: Record<number, string> = {\n 80: \"CUIT\",\n 86: \"CUIL\",\n 87: \"CDI\",\n 94: \"Pasaporte\",\n 96: \"DNI\",\n};\nconst UNIDENTIFIED_DOCUMENT = 99;\n\n/** G3: precedes the codes of the observations ARCA returned with the CAE. */\nconst ARCA_OBSERVATIONS_LABEL = \"Observaciones de ARCA:\";\n\n/** G1: RG 1415, art. 15, inc. a), as replaced by RG 5003, art. 20. */\nexport const MONOTRIBUTO_CREDIT_LEGEND =\n \"El crédito fiscal discriminado en el presente comprobante, sólo podrá ser computado a efectos del Régimen de Sostenimiento e Inclusión Fiscal para Pequeños Contribuyentes de la Ley Nº 27.618\";\n\n/** ARCA tributo ids read as national indirect taxes: Impuestos nacionales and Impuestos internos. */\nconst NATIONAL_INDIRECT_TAX_IDS = new Set([1, 4]);\nconst TAX_NAMES: Record<number, string> = {\n 1: \"Impuestos nacionales\",\n 2: \"Impuestos provinciales\",\n 3: \"Impuestos municipales\",\n 4: \"Impuestos internos\",\n 5: \"Ingresos brutos\",\n 6: \"Percepción de IVA\",\n 7: \"Percepción de ingresos brutos\",\n 8: \"Percepciones por impuestos municipales\",\n 9: \"Otras percepciones\",\n 13: \"Percepción de IVA a no categorizado\",\n 99: \"Otros tributos\",\n};\n\n/** RG 5762 replaced class M by class A with retention legend on this date. */\nconst RETENTION_LEGEND_FROM = \"2025-12-01\";\n\nconst TITLES = {\n invoice: \"FACTURA\",\n debit_note: \"NOTA DE DÉBITO\",\n credit_note: \"NOTA DE CRÉDITO\",\n} as const;\n\n/**\n * Derives what a printed class A, B or C voucher must show from the\n * authorized voucher, the items it was issued from and the issuer's profile.\n * Pure. It throws `ArcaInputError` when a required datum is missing, when the\n * items do not add up to the authorized money, or for a voucher it does not\n * render: FCE, and class M vouchers issued before 2025-12-01.\n */\nexport function buildVoucherDocument(\n input: VoucherDocumentInput\n): VoucherDocument {\n const { voucher, issuer } = input;\n const info = describeVoucherType(voucher.voucherType);\n if (info.family === \"fce\") {\n invalid(\n \"voucher.voucherType\",\n \"a class A, B or C invoice or note: FCE vouchers are not rendered yet\"\n );\n }\n if (\n info.family === \"retention_legend\" &&\n voucher.date < RETENTION_LEGEND_FROM\n ) {\n invalid(\n \"voucher.voucherType\",\n \"a voucher issued from 2025-12-01: types 51 to 53 were class M before RG 5762\"\n );\n }\n const voucherClass = voucher.voucherClass;\n assertIssuerMatchesClass(issuer.condition, voucherClass);\n if (voucher.qr === undefined) {\n invalid(\"voucher.qr\", \"the QR every printed voucher carries\");\n }\n const taxId = digits(issuer.taxId);\n if (\n taxId.length !== 11 ||\n (voucher.qrPayload !== undefined &&\n String(voucher.qrPayload.cuit) !== taxId)\n ) {\n invalid(\"issuer.taxId\", \"the 11-digit CUIT the voucher was issued under\");\n }\n const lines = documentLines(input, voucherClass);\n const header = voucher.header;\n const receiver = documentReceiver(input, header);\n return {\n voucherClass,\n voucherType: voucher.voucherType,\n code: String(voucher.voucherType).padStart(3, \"0\"),\n ...letterLegend(info.family, voucherClass, issuer.paymentToInformedCbu),\n title: TITLES[info.kind],\n number: `${String(voucher.salesPoint).padStart(5, \"0\")}-${String(voucher.number).padStart(8, \"0\")}`,\n issueDate: voucher.date,\n issuer: {\n ...(issuer.tradeName\n ? { tradeName: required(issuer.tradeName, \"issuer.tradeName\") }\n : {}),\n legalName: required(issuer.legalName, \"issuer.legalName\"),\n address: required(issuer.address, \"issuer.address\"),\n taxId,\n conditionLegend: ISSUER_LEGENDS[issuer.condition],\n grossIncome: required(issuer.grossIncome, \"issuer.grossIncome\"),\n ...activitiesStart(issuer.activitiesStartDate),\n },\n receiver,\n saleConditions: required(input.saleConditions, \"saleConditions\"),\n remitos: (input.remitos ?? []).map((remito, index) =>\n required(remito, `remitos[${index}]`)\n ),\n ...(header.serviceStartDate && header.serviceEndDate\n ? {\n servicePeriod: {\n from: header.serviceStartDate,\n to: header.serviceEndDate,\n },\n }\n : {}),\n ...(header.paymentDueDate ? { paymentDueDate: header.paymentDueDate } : {}),\n currency: {\n id: header.currencyId,\n ...(header.currencyId !== \"PES\" && header.exchangeRate !== undefined\n ? { exchangeRate: header.exchangeRate }\n : {}),\n },\n lines: lines.lines,\n totals: {\n globalDiscount: lines.globalDiscount,\n subtotal: lines.subtotal,\n exempt: voucher.totals.exempt,\n untaxed: voucher.totals.untaxed,\n vatRates: voucherClass === \"A\" ? voucher.totals.vatRates : [],\n otherTaxes: voucher.totals.taxes.map((tax) => ({\n id: tax.id,\n description: tax.description ?? TAX_NAMES[tax.id] ?? \"Otros tributos\",\n amount: tax.amount,\n })),\n adjustment: lines.adjustment,\n total: voucher.totals.total,\n },\n ...(voucherClass === \"B\" &&\n VAT_CONTAINED_RECEIVERS.has(header.receiverVatConditionId)\n ? {\n transparency: {\n vatContained: voucher.totals.vat,\n otherNationalIndirectTaxes: voucher.totals.taxes\n .filter((tax) => NATIONAL_INDIRECT_TAX_IDS.has(tax.id))\n .reduce((sum, tax) => sum + tax.amount, 0),\n },\n }\n : {}),\n authorization: {\n kind: \"CAE\",\n code: voucher.cae,\n dueDate: voucher.caeExpiry,\n },\n qr: voucher.qr,\n legends: legends(input, voucherClass),\n };\n}\n\nfunction letterLegend(\n family: string,\n voucherClass: \"A\" | \"B\" | \"C\",\n paymentToInformedCbu: boolean | undefined\n): Pick<VoucherDocument, \"letterLegend\"> {\n if (family === \"retention_legend\") {\n return { letterLegend: \"OPERACIÓN SUJETA A RETENCIÓN\" };\n }\n return voucherClass === \"A\" && paymentToInformedCbu === true\n ? { letterLegend: \"PAGO EN CBU INFORMADA\" }\n : {};\n}\n\nfunction legends(\n input: VoucherDocumentInput,\n voucherClass: \"A\" | \"B\" | \"C\"\n): VoucherDocument[\"legends\"] {\n if (voucherClass !== \"A\") {\n return [];\n }\n const found: VoucherDocument[\"legends\"] = [];\n if (MONOTRIBUTO_RECEIVERS.has(input.voucher.header.receiverVatConditionId)) {\n found.push({ rule: \"G1\", text: MONOTRIBUTO_CREDIT_LEGEND });\n }\n const codes = [\n ...new Set(\n (input.observations ?? [])\n .map((observation) => String(observation.code ?? \"\").trim())\n .filter((code) => code !== \"\")\n ),\n ];\n if (codes.length > 0) {\n found.push({\n rule: \"G3\",\n text: `${ARCA_OBSERVATIONS_LABEL} ${codes.join(\", \")}`,\n });\n }\n return found;\n}\n\nfunction assertIssuerMatchesClass(\n condition: PrintedIssuerCondition,\n voucherClass: \"A\" | \"B\" | \"C\"\n): void {\n if (!Object.hasOwn(ISSUER_LEGENDS, condition)) {\n invalid(\"issuer.condition\", Object.keys(ISSUER_LEGENDS).join(\", \"));\n }\n const vatRegistered = condition === \"responsable_inscripto\";\n if (vatRegistered !== (voucherClass !== \"C\")) {\n invalid(\n \"issuer.condition\",\n vatRegistered\n ? \"a condition that issues class C vouchers\"\n : \"responsable_inscripto, the only condition that issues class A and B vouchers\"\n );\n }\n}\n\nfunction documentReceiver(\n input: VoucherDocumentInput,\n header: IssuedVoucher[\"header\"]\n): VoucherDocument[\"receiver\"] {\n const condition = header.receiverVatConditionId;\n const conditionLegend = RECEIVER_LEGENDS[condition];\n if (conditionLegend === undefined) {\n invalid(\n \"voucher.header.receiverVatConditionId\",\n \"a receiver condition the SDK renders: 1, 4 to 10, 13, 15 or 16\"\n );\n }\n const name = input.receiver?.name?.trim();\n const address = input.receiver?.address?.trim();\n if (condition !== CONSUMIDOR_FINAL) {\n required(name, \"receiver.name\");\n required(address, \"receiver.address\");\n }\n const identified =\n header.documentType !== UNIDENTIFIED_DOCUMENT &&\n /[1-9]/.test(header.documentNumber);\n if (!identified && condition !== CONSUMIDOR_FINAL) {\n throw new ArcaInputError(\n \"Only a consumidor final may be unidentified on a printed voucher.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"voucher.header.documentNumber\",\n expected: \"the receiver's document (C13 to C17)\",\n }\n );\n }\n const label = DOCUMENT_LABELS[header.documentType];\n return {\n conditionLegend,\n ...(name ? { name } : {}),\n ...(address ? { address } : {}),\n ...(identified\n ? {\n document: {\n type: header.documentType,\n ...(label === undefined ? {} : { label }),\n number: header.documentNumber,\n },\n }\n : {}),\n };\n}\n\n/**\n * The items must describe the authorized money: the same net, exempt and\n * untaxed amounts and the same VAT bases. The printed lines then use the\n * per-item Half Even split, so they add up to the authorized header. With a\n * global discount the items are the lines before it, and each rate's lines\n * less its discount must give the authorized base of that rate.\n */\nfunction documentLines(\n input: VoucherDocumentInput,\n voucherClass: \"A\" | \"B\" | \"C\"\n): {\n lines: VoucherDocumentLine[];\n globalDiscount: number;\n subtotal: number;\n adjustment: number;\n} {\n const { items } = input;\n const totals = input.voucher.totals;\n if (!Array.isArray(items) || items.length === 0) {\n invalid(\"items\", \"the items the voucher was issued from\");\n }\n const discount = globalDiscount(input.globalDiscount, voucherClass);\n let computed: ReturnType<typeof calculateWsfeAmounts>;\n try {\n computed = calculateWsfeAmounts({\n voucherClass,\n items,\n // Items before a global discount add up to more than the authorized total.\n ...(discount ? {} : { total: totals.total - totals.otherTaxes }),\n });\n } catch (error) {\n if (\n error instanceof ArcaInputError &&\n error.code === \"ARCA_INPUT_AMOUNT_MISMATCH\"\n ) {\n mismatch(\"total\");\n }\n throw error;\n }\n if (!discount) {\n assertItemsMatchTotals(computed.data, totals, voucherClass);\n }\n const settled =\n voucherClass === \"C\"\n ? undefined\n : settleVatItems(\n { voucherClass, items },\n // The header's VAT adjustment belongs to the discounted money.\n discount ? 0 : computed.amounts.vatAdjustment\n );\n const lines = items.map((item, index): VoucherDocumentLine => {\n const path = `items[${index}]`;\n const money = settled?.items[index];\n const amount =\n money === undefined\n ? (item.amount as number)\n : voucherClass === \"A\"\n ? money.amount - money.vat\n : money.amount;\n return {\n ...(item.code === undefined ? {} : { code: item.code }),\n description: required(item.description, `${path}.description`),\n ...lineQuantity(item, amount, path),\n ...(item.unit === undefined ? {} : { unit: item.unit }),\n ...(item.discount ? { discount: item.discount } : {}),\n amount,\n ...(voucherClass === \"A\" && money !== undefined\n ? { vatRate: money.rate }\n : {}),\n };\n });\n const sum = lines.reduce((total, line) => total + line.amount, 0);\n const rows = totals.vatRates.reduce((total, row) => total + row.amount, 0);\n if (discount) {\n assertDiscountedLinesMatchTotals(\n voucherClass,\n lines,\n settled?.items,\n computed.data,\n totals,\n discount.byRate\n );\n return {\n lines,\n globalDiscount: discount.total,\n subtotal: voucherClass === \"A\" ? totals.netTaxed : sum - discount.total,\n adjustment: voucherClass === \"C\" ? 0 : totals.vat - rows,\n };\n }\n if (voucherClass === \"A\") {\n // The rows keep their computed VAT; an asserted total moves only the header.\n return {\n lines,\n globalDiscount: 0,\n subtotal: totals.netTaxed,\n adjustment: totals.vat - rows,\n };\n }\n return {\n lines,\n globalDiscount: 0,\n subtotal: sum,\n adjustment: settled?.unabsorbed ?? 0,\n };\n}\n\ntype GlobalDiscount = {\n total: number;\n /** By ARCA VAT rate id; class C keys its one amount by 0. */\n byRate: ReadonlyMap<number, number>;\n};\n\n/** Undefined when there is no discount, or every amount is zero. */\nfunction globalDiscount(\n value: VoucherDocumentInput[\"globalDiscount\"],\n voucherClass: \"A\" | \"B\" | \"C\"\n): GlobalDiscount | undefined {\n if (value === undefined) {\n return;\n }\n const byRate = new Map<number, number>();\n if (voucherClass === \"C\") {\n if (typeof value !== \"number\") {\n invalid(\n \"globalDiscount\",\n \"one amount in minor units on a class C voucher\"\n );\n }\n byRate.set(0, discountAmount(value, \"globalDiscount\"));\n } else {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n invalid(\n \"globalDiscount\",\n \"amounts by ARCA VAT rate id on a class A or B voucher, as the authorized VAT rows\"\n );\n }\n for (const [key, amount] of Object.entries(value)) {\n const id = Number(key);\n if (!/^\\d+$/.test(key) || vatRatePercent(id) === undefined) {\n invalid(`globalDiscount[${key}]`, \"keyed by an ARCA VAT rate id\");\n }\n const checked = discountAmount(amount, `globalDiscount[${key}]`);\n if (checked > 0) {\n byRate.set(id, checked);\n }\n }\n }\n const total = [...byRate.values()].reduce((sum, amount) => sum + amount, 0);\n return total === 0 ? undefined : { total, byRate };\n}\n\nfunction discountAmount(value: unknown, field: string): number {\n if (!(Number.isSafeInteger(value) && (value as number) >= 0)) {\n invalid(field, \"a non-negative safe integer in minor units\");\n }\n return value as number;\n}\n\n/**\n * Class A compares net lines with the authorized base of each rate, class B\n * lines with VAT with that base plus its VAT, and class C the lines with the\n * net. Exempt and untaxed lines take no discount.\n */\nfunction assertDiscountedLinesMatchTotals(\n voucherClass: \"A\" | \"B\" | \"C\",\n lines: readonly VoucherDocumentLine[],\n settled: readonly { rate: VatRate }[] | undefined,\n data: ReturnType<typeof calculateWsfeAmounts>[\"data\"],\n totals: VoucherTotals,\n discount: ReadonlyMap<number, number>\n): void {\n const minor = (value: number) =>\n Number(normalizeArcaAmountToMinorUnits(value, \"items\"));\n if (minor(data.exemptAmount) !== totals.exempt) {\n mismatch(\"exempt\");\n }\n if (minor(data.nonTaxableAmount) !== totals.untaxed) {\n mismatch(\"untaxed\");\n }\n const { byLines, authorized } =\n voucherClass === \"C\" || settled === undefined\n ? {\n byLines: new Map([\n [0, lines.reduce((sum, line) => sum + line.amount, 0)],\n ]),\n authorized: new Map([[0, totals.netTaxed]]),\n }\n : discountedRates(voucherClass, lines, settled, totals);\n for (const id of discount.keys()) {\n if (!byLines.has(id)) {\n invalid(\n `globalDiscount[${id}]`,\n \"keyed by a VAT rate id the items carry\"\n );\n }\n }\n for (const id of new Set([...byLines.keys(), ...authorized.keys()])) {\n const expected = authorized.get(id) ?? 0;\n if ((byLines.get(id) ?? 0) - (discount.get(id) ?? 0) !== expected) {\n throw new ArcaInputError(\n \"items less the global discount do not add up to the authorized voucher.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field:\n voucherClass === \"C\" ? \"globalDiscount\" : `globalDiscount[${id}]`,\n expected: `${expected} minor units of lines less discount`,\n }\n );\n }\n }\n}\n\n/** The taxed lines and the authorized money of each VAT rate id. */\nfunction discountedRates(\n voucherClass: \"A\" | \"B\",\n lines: readonly VoucherDocumentLine[],\n settled: readonly { rate: VatRate }[],\n totals: VoucherTotals\n): { byLines: Map<number, number>; authorized: Map<number, number> } {\n const byLines = new Map<number, number>();\n for (const [index, line] of lines.entries()) {\n const rate = settled[index]?.rate;\n if (typeof rate === \"number\") {\n const id = vatRateId(rate);\n byLines.set(id, (byLines.get(id) ?? 0) + line.amount);\n }\n }\n const authorized = new Map<number, number>();\n for (const row of totals.vatRates) {\n const amount = voucherClass === \"A\" ? row.base : row.base + row.amount;\n authorized.set(row.id, (authorized.get(row.id) ?? 0) + amount);\n }\n return { byLines, authorized };\n}\n\nfunction assertItemsMatchTotals(\n data: ReturnType<typeof calculateWsfeAmounts>[\"data\"],\n totals: VoucherTotals,\n voucherClass: \"A\" | \"B\" | \"C\"\n): void {\n const minor = (value: number) =>\n Number(normalizeArcaAmountToMinorUnits(value, \"items\"));\n for (const [field, value, authorized] of [\n [\"netTaxed\", data.netAmount, totals.netTaxed],\n [\"exempt\", data.exemptAmount, totals.exempt],\n [\"untaxed\", data.nonTaxableAmount, totals.untaxed],\n [\"vat\", data.vatAmount, totals.vat],\n ] as const) {\n if (minor(value) !== authorized) {\n mismatch(field);\n }\n }\n if (voucherClass === \"C\") {\n return;\n }\n const bases = (rows: readonly { id: number; base: number }[]) =>\n rows\n .filter((row) => row.base !== 0)\n .map((row) => `${row.id}:${row.base}`)\n .sort()\n .join(\",\");\n const computedBases = (data.vatRates ?? []).map((row) => ({\n id: row.id,\n base: minor(row.baseAmount),\n }));\n if (bases(computedBases) !== bases(totals.vatRates)) {\n mismatch(\"vatRates\");\n }\n}\n\n/** C20 and C21: a line without quantity is one unit at its amount. */\nfunction lineQuantity(\n item: VatItem | AmountItem,\n amount: number,\n path: string\n): { quantity: number; unitPrice: string } {\n const discount = item.discount ?? 0;\n if (!(Number.isSafeInteger(discount) && discount >= 0)) {\n invalid(`${path}.discount`, \"a non-negative safe integer in minor units\");\n }\n if (item.quantity === undefined && item.unitPrice === undefined) {\n // The line amount is net of the discount: the unit price is not.\n return { quantity: 1, unitPrice: majorUnits(amount + discount) };\n }\n const { quantity, unitPrice } = item;\n if (\n !(typeof quantity === \"number\" && Number.isFinite(quantity) && quantity > 0)\n ) {\n invalid(`${path}.quantity`, \"a positive quantity, given with unitPrice\");\n }\n if (typeof unitPrice !== \"string\" || !/^\\d+(\\.\\d{1,6})?$/.test(unitPrice)) {\n invalid(\n `${path}.unitPrice`,\n \"a major-unit decimal string with at most six decimals, given with quantity\"\n );\n }\n const printed = Math.round(quantity * Number(unitPrice) * 100) - discount;\n if (Math.abs(printed - amount) > 1) {\n throw new ArcaInputError(\n `${path}: quantity × unitPrice − discount does not match the line amount.`,\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: `${path}.unitPrice`,\n expected: `${amount} minor units, within one: without VAT on class A, with VAT on class B`,\n }\n );\n }\n return { quantity, unitPrice };\n}\n\nfunction activitiesStart(date: string | null): {\n activitiesStartDate?: string;\n} {\n if (date === null) {\n return {};\n }\n if (typeof date !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) {\n invalid(\n \"issuer.activitiesStartDate\",\n \"YYYY-MM-DD, or null for the exceptions of RG 1415, Anexo II, A, V 6\"\n );\n }\n return { activitiesStartDate: date };\n}\n\nfunction majorUnits(minor: number): string {\n const cents = String(minor).padStart(3, \"0\");\n return `${cents.slice(0, -2)}.${cents.slice(-2)}`;\n}\n\nfunction digits(value: string): string {\n return typeof value === \"string\" ? value.replace(/\\D/g, \"\") : \"\";\n}\n\nfunction required(value: string | undefined, field: string): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new ArcaInputError(`${field} is required on a printed voucher.`, {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field,\n });\n }\n return value.trim();\n}\n\nfunction mismatch(field: string): never {\n throw new ArcaInputError(\"items do not add up to the authorized voucher.\", {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: `items (${field})`,\n expected: \"the items the voucher was issued from\",\n });\n}\n\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n","import { abortable } from \"../internal/abort\";\nimport { throwIfAborted } from \"./lock\";\nimport type { ArcaStore } from \"./types\";\n\n/** In-process store for tests; reservations do not survive a restart. */\nexport function createMemoryStore(): ArcaStore {\n const values = new Map<string, string>();\n const locks = new Map<string, Promise<void>>();\n return {\n get: (key) => Promise.resolve(values.get(key) ?? null),\n set(key, value) {\n values.set(key, value);\n return Promise.resolve();\n },\n add(key, value) {\n if (values.has(key)) {\n return Promise.resolve(false);\n }\n values.set(key, value);\n return Promise.resolve(true);\n },\n delete(key) {\n values.delete(key);\n return Promise.resolve();\n },\n async withLock(key, fn, { signal } = {}) {\n throwIfAborted(signal);\n const previous = locks.get(key) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.catch(() => undefined).then(() => current);\n locks.set(key, queued);\n // An abort ends the wait early; the check below reports it.\n await abortable(\n previous.catch(() => undefined),\n signal\n ).catch(() => undefined);\n if (signal?.aborted) {\n // Hand the turn on, but keep this call's place until the holder\n // before it finishes: a caller arriving now must still wait for it.\n release();\n queued.then(() => {\n if (locks.get(key) === queued) {\n locks.delete(key);\n }\n });\n throwIfAborted(signal);\n }\n try {\n return await fn();\n } finally {\n release();\n if (locks.get(key) === queued) {\n locks.delete(key);\n }\n }\n },\n };\n}\n","import { ArcaConfigurationError } from \"../errors\";\nimport { ARCA_LEASE_MS, withLease } from \"./lock\";\nimport { type ArcaStore, storeCall } from \"./types\";\n\ntype Row = { key?: string; value?: string };\n/** Uses the caller's SQL client; provision the table before use. */\nexport function createPostgresStore({\n query,\n table = \"arca_store\",\n}: {\n query: (text: string, params: string[]) => Promise<Row[] | { rows: Row[] }>;\n table?: string;\n}): ArcaStore {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(table)) {\n throw new ArcaConfigurationError(\"Invalid ARCA store table identifier.\");\n }\n const name = `\"${table}\"`;\n const lease = Math.round(ARCA_LEASE_MS / 1000);\n const run = (text: string, params: string[]) =>\n storeCall(async () => {\n const result = await query(text, params);\n return Array.isArray(result) ? result : result.rows;\n });\n return {\n async get(key) {\n return (\n (await run(`SELECT value FROM ${name} WHERE key = $1`, [key]))[0]\n ?.value ?? null\n );\n },\n async set(key, value) {\n await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,\n [key, value]\n );\n },\n async add(key, value) {\n return (\n (\n await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key`,\n [key, value]\n )\n ).length > 0\n );\n },\n async delete(key) {\n await run(`DELETE FROM ${name} WHERE key = $1`, [key]);\n },\n withLock(key, fn, options) {\n // A lease row, not an advisory lock: it survives a transaction-mode\n // pooler, where a session-scoped lock would be taken on another backend.\n return withLease(\n {\n async acquire(owner) {\n const taken = await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key`,\n [key, owner]\n );\n if (taken.length > 0) {\n return true;\n }\n const expired = await run(\n `UPDATE ${name} SET value = $2, updated_at = now() WHERE key = $1 AND updated_at < now() - interval '${lease} seconds' RETURNING key`,\n [key, owner]\n );\n return expired.length > 0;\n },\n async renew(owner) {\n await run(\n `UPDATE ${name} SET updated_at = now() WHERE key = $1 AND value = $2`,\n [key, owner]\n );\n },\n async release(owner) {\n await run(`DELETE FROM ${name} WHERE key = $1 AND value = $2`, [\n key,\n owner,\n ]);\n },\n },\n fn,\n options\n );\n },\n };\n}\n","import { ArcaConfigurationError } from \"../errors\";\nimport { ARCA_LEASE_MS, withLease } from \"./lock\";\nimport { type ArcaLockOptions, type ArcaStore, storeCall } from \"./types\";\n\ntype RedisClient = {\n get(key: string): Promise<unknown>;\n set(key: string, value: string): Promise<unknown>;\n call?(...args: string[]): Promise<unknown>;\n del?(key: string): Promise<unknown>;\n};\n/** Uses ioredis or Upstash without importing either driver. */\nexport function createRedisStore(\n client: RedisClient,\n options: { flavor?: \"ioredis\" | \"upstash\" } = {}\n): ArcaStore {\n const flavor =\n options.flavor ??\n (typeof client.call === \"function\" ? \"ioredis\" : \"upstash\");\n if (flavor === \"ioredis\" && !client.call) {\n throw new ArcaConfigurationError(\n \"ARCA Redis ioredis flavor requires client.call.\"\n );\n }\n // The public structural type accepts ioredis's overloaded set method.\n // Only the Upstash flavor invokes its options-object overload.\n const upstashSet = client.set as (\n key: string,\n value: string,\n options: { nx?: true; xx?: true; px?: number }\n ) => Promise<unknown>;\n const read = async (key: string) => {\n const value = await client.get(key);\n if (value === null || value === undefined) {\n return null;\n }\n // Upstash can deserialize stored JSON automatically.\n return typeof value === \"string\" ? value : JSON.stringify(value);\n };\n // A lease, so a crashed holder frees the key; a renewal keeps a live one.\n const lease = (key: string, owner: string, mode: \"nx\" | \"xx\") =>\n storeCall(\n async () =>\n (flavor === \"ioredis\"\n ? await client.call?.(\n \"SET\",\n key,\n owner,\n mode.toUpperCase(),\n \"PX\",\n String(ARCA_LEASE_MS)\n )\n : await upstashSet.call(client, key, owner, {\n [mode]: true,\n px: ARCA_LEASE_MS,\n })) === \"OK\"\n );\n return {\n get: (key) => storeCall(() => read(key)),\n set: (key, value) =>\n storeCall(async () => {\n await client.set(key, value);\n }),\n add: (key, value) =>\n storeCall(\n async () =>\n (flavor === \"ioredis\"\n ? await client.call?.(\"SET\", key, value, \"NX\")\n : await upstashSet.call(client, key, value, { nx: true })) === \"OK\"\n ),\n ...(client.del\n ? {\n delete: (key: string) =>\n storeCall(async () => {\n await client.del?.(key);\n }),\n withLock: <T>(\n key: string,\n fn: () => Promise<T>,\n options?: ArcaLockOptions\n ) =>\n withLease(\n {\n acquire: (owner) => lease(key, owner, \"nx\"),\n renew: async (owner) => {\n // Check and set: only the holder extends its own lease.\n if ((await storeCall(() => read(key))) === owner) {\n await lease(key, owner, \"xx\");\n }\n },\n release: async (owner) => {\n await storeCall(async () => {\n if ((await read(key)) === owner) {\n await client.del?.(key);\n }\n });\n },\n },\n fn,\n options\n ),\n }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBO,IAAM,uBAAuB;AAAA;AAAA,EAElC,MAAM;AAAA;AAAA,EAEN,iBAAiB;AAAA;AAAA,EAEjB,KAAK;AAAA;AAAA,EAEL,YAAY;AAAA;AAAA,EAEZ,mBACE;AAAA;AAAA,EAEF,cAAc;AAAA;AAAA,EAEd,4BAA4B;AAC9B;AAGO,IAAM,wCAAwC;AAuJrD,IAAM,iBAAyD;AAAA,EAC7D,uBAAuB;AAAA,EACvB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,gDACE;AACJ;AAGA,IAAM,mBAA2C;AAAA,EAC/C,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AAAA;AAAA,EAEH,GAAG;AAAA,EACH,GAAG;AAAA,EACH,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AACN;AACA,IAAM,mBAAmB;AAEzB,IAAM,0BAA0B,oBAAI,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AAClD,IAAM,wBAAwB,oBAAI,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC;AAEjD,IAAM,kBAA0C;AAAA,EAC9C,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AACN;AACA,IAAM,wBAAwB;AAG9B,IAAM,0BAA0B;AAGzB,IAAM,4BACX;AAGF,IAAM,4BAA4B,oBAAI,I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,GAAG;AAAA,cACxB;AAAA,YACF,CAAC;AAAA,UACH;AAAA,QACF;AAAA,QACA;AAAA,QACAA;AAAA,MACF;AAAA,IACJ,IACA,CAAC;AAAA,EACP;AACF;","names":["options"]}
|
|
1
|
+
{"version":3,"sources":["../src/services/voucher-document.ts","../src/store/memory.ts","../src/store/postgres.ts","../src/store/redis.ts"],"sourcesContent":["import { ArcaInputError } from \"../errors\";\nimport { normalizeArcaAmountToMinorUnits } from \"../internal/decimal\";\nimport { describeVoucherType } from \"./issuance-fields\";\nimport type { IssuedVoucher, VoucherTotals } from \"./vouchers-types\";\nimport {\n type AmountItem,\n calculateWsfeAmounts,\n settleVatItems,\n type VatItem,\n type VatRate,\n vatRateId,\n vatRatePercent,\n} from \"./wsfe-amounts\";\n\n/**\n * Fixed texts a printed voucher carries, as the norms word them. Rule ids\n * refer to `.github/PRINTED_VOUCHER_SOURCES.md`.\n */\nexport const PRINTED_VOUCHER_TEXT = {\n /** L4, before the voucher type code. */\n code: \"Código Nº\",\n /** C7, before the start of activities. */\n activitiesStart: \"INICIO DE ACTIVIDADES\",\n /** C8 and L9, before the CAE. */\n cae: \"C.A.E. N°\",\n /** C9 and L9, before the CAE due date, in type of at least 12 pt. */\n caeDueDate: \"Fecha Vto.:\",\n /** L8, the title of the consumer transparency block. */\n transparencyTitle:\n \"Régimen de Transparencia Fiscal al Consumidor (Ley 27.743)\",\n /** L8, the VAT contained in the price. */\n vatContained: \"IVA Contenido\",\n /** L8 and C24, the other national indirect taxes. */\n otherNationalIndirectTaxes: \"Otros Impuestos Nacionales Indirectos\",\n} as const;\n\n/** L9 asks for at least this type size for the CAE due date. */\nexport const PRINTED_CAE_DUE_DATE_MIN_FONT_SIZE_PT = 12;\n\n/** The issuer conditions a printed voucher can name (C5). */\nexport type PrintedIssuerCondition =\n | \"responsable_inscripto\"\n | \"exento\"\n | \"no_alcanzado\"\n | \"monotributo\"\n | \"monotributo_social\"\n | \"monotributo_trabajador_independiente_promovido\";\n\n/** A labeled change already included in the authorized voucher's money. */\nexport type VoucherDocumentAdjustment = {\n label: string;\n /** Signed minor units: net by VAT rate id on A, gross by id on B, one amount on C. */\n amount: number | Readonly<Record<number, number>>;\n};\n\nexport type VoucherDocumentInput = {\n /** The voucher `issue()`, a note method or `recover()` answered authorized. */\n voucher: IssuedVoucher;\n /**\n * The same items the voucher was issued from, each with its description.\n * With a `globalDiscount` or `adjustments`, the items before those changes.\n */\n items: readonly (VatItem | AmountItem)[];\n /**\n * A discount on the whole voucher, in minor units, that the issuer took off\n * the items it issued. Class A and B take it by ARCA VAT rate id, as the\n * authorized VAT rows: net on class A, with VAT on class B, as the lines.\n * Class C takes one amount. The SDK does not split it: each rate's lines,\n * less its discount, must add up to the authorized base of that rate.\n */\n globalDiscount?: number | Readonly<Record<number, number>>;\n /**\n * Signed, labeled totals rows, already included when issuing. Like the\n * global discount, amounts are net by ARCA VAT rate id on A, with VAT by id\n * on B, and one amount on C. Each rate's lines less its global discount\n * plus its adjustments must equal its authorized base. No automatic split.\n */\n adjustments?: readonly VoucherDocumentAdjustment[];\n issuer: {\n /** C1. */\n legalName: string;\n /** L1, only when the issuer has one. */\n tradeName?: string;\n /** C2: where the voucher is issued, or the fiscal address for travelling sellers. */\n address: string;\n /** C3, checked against the voucher's QR. */\n taxId: string;\n /** C5. */\n condition: PrintedIssuerCondition;\n /** C4: the ingresos brutos number, or the non-contributor condition. */\n grossIncome: string;\n /**\n * C7 as `YYYY-MM-DD`. `null` only for university professionals billing\n * their fees and service providers without premises (Anexo II, A, V 6).\n */\n activitiesStartDate: string | null;\n /**\n * G5: the issuer opted to issue class A \"PAGO EN CBU INFORMADA\" (RG 5762,\n * art. 20 and 21). Only class A vouchers print it.\n */\n paymentToInformedCbu?: boolean;\n };\n /**\n * G3: the observations ARCA returned with the CAE, as\n * `authorization.observations` of an `authorized` outcome carries them. On a\n * class A voucher their codes are printed (RG 4291, art. 12 and 14 c)).\n */\n observations?: readonly { code?: string | number }[];\n /** C13 to C17. Name and address are required unless the receiver is a consumidor final. */\n receiver?: { name?: string; address?: string };\n /** L6: contado, cuenta corriente and so on. */\n saleConditions: string;\n /** C12: the remitos issued for the operation, when there are any. */\n remitos?: readonly string[];\n};\n\nexport type VoucherDocumentLine = {\n code?: string;\n description: string;\n quantity: number;\n unit?: number;\n /** Major-unit decimal string: without VAT on class A, with VAT on class B. */\n unitPrice: string;\n discount?: number;\n /** Minor units: without VAT on class A, with VAT on class B, as issued on class C. */\n amount: number;\n /** Class A only: the line's rate, `exempt` or `untaxed`. */\n vatRate?: VatRate;\n};\n\n/**\n * Everything a printed voucher shows, derived and checked. Money is in minor\n * units of the voucher currency and dates are `YYYY-MM-DD`. Formatting and\n * layout belong to the renderer.\n */\nexport type VoucherDocument = {\n voucherClass: \"A\" | \"B\" | \"C\";\n voucherType: number;\n /** L4: the type code, three digits. */\n code: string;\n /** G4 and G5: the legend printed next to the letter A, when there is one. */\n letterLegend?: \"OPERACIÓN SUJETA A RETENCIÓN\" | \"PAGO EN CBU INFORMADA\";\n title: \"FACTURA\" | \"NOTA DE DÉBITO\" | \"NOTA DE CRÉDITO\";\n /** C6: sales point and number, `00003-00000041`. */\n number: string;\n /** C11. */\n issueDate: string;\n issuer: {\n tradeName?: string;\n legalName: string;\n address: string;\n taxId: string;\n conditionLegend: string;\n grossIncome: string;\n activitiesStartDate?: string;\n };\n receiver: {\n conditionLegend: string;\n name?: string;\n address?: string;\n /** Absent for an unidentified consumidor final. */\n document?: { type: number; label?: string; number: string };\n };\n saleConditions: string;\n remitos: string[];\n /** Concepts 2 and 3. */\n servicePeriod?: { from: string; to: string };\n paymentDueDate?: string;\n /** C22: the exchange rate is present for any currency but pesos. */\n currency: { id: string; exchangeRate?: string };\n lines: VoucherDocumentLine[];\n totals: {\n /**\n * The sum of the input's `globalDiscount`, 0 without one: net on class A,\n * with VAT on class B. The lines are before it and the subtotal after it.\n */\n globalDiscount: number;\n /** Signed issuer-labeled rows, in input order. Absent without adjustments. */\n adjustments?: { label: string; amount: number }[];\n /**\n * Class A: net taxed. Class B: the lines with VAT. Class C: the lines.\n * Includes the global discount and the labeled adjustments.\n */\n subtotal: number;\n exempt: number;\n untaxed: number;\n /** C25 and L7, class A only: one row per rate, as authorized. */\n vatRates: { id: number; rate?: number; base: number; amount: number }[];\n /** C23: ARCA's Tributos. */\n otherTaxes: { id: number; description: string; amount: number }[];\n /** C23: a VAT adjustment of the header that no line could carry. */\n adjustment: number;\n total: number;\n };\n /** L8 and G2, class B only. */\n transparency?: { vatContained: number; otherNationalIndirectTaxes: number };\n /** C8, C9 and L9. */\n authorization: { kind: \"CAE\"; code: string; dueDate: string };\n /** Q1 and Q2. */\n qr: string;\n /** Conditional legends, in order, each with its rule id. */\n legends: { rule: \"G1\" | \"G3\"; text: string }[];\n};\n\nconst ISSUER_LEGENDS: Record<PrintedIssuerCondition, string> = {\n responsable_inscripto: \"IVA RESPONSABLE INSCRIPTO\",\n exento: \"IVA EXENTO\",\n no_alcanzado: \"NO RESPONSABLE IVA\",\n monotributo: \"RESPONSABLE MONOTRIBUTO\",\n monotributo_social: \"MONOTRIBUTISTA SOCIAL\",\n monotributo_trabajador_independiente_promovido:\n \"MONOTRIBUTO TRABAJADOR INDEPENDIENTE PROMOVIDO\",\n};\n\n/** ARCA receiver IVA condition ids and their C13 to C17 legends. */\nconst RECEIVER_LEGENDS: Record<number, string> = {\n 1: \"IVA RESPONSABLE INSCRIPTO\",\n 4: \"IVA EXENTO\",\n 5: \"A CONSUMIDOR FINAL\",\n 6: \"RESPONSABLE MONOTRIBUTO\",\n 7: \"SUJETO NO CATEGORIZADO\",\n // Apartado A names no legend for these: ARCA's own condition names.\n 8: \"PROVEEDOR DEL EXTERIOR\",\n 9: \"CLIENTE DEL EXTERIOR\",\n 10: \"IVA LIBERADO - LEY Nº 19.640\",\n 13: \"MONOTRIBUTISTA SOCIAL\",\n 15: \"NO RESPONSABLE IVA\",\n 16: \"MONOTRIBUTO TRABAJADOR INDEPENDIENTE PROMOVIDO\",\n};\nconst CONSUMIDOR_FINAL = 5;\n/** C26 and G2: exento, consumidor final and no alcanzado. */\nconst VAT_CONTAINED_RECEIVERS = new Set([4, 5, 15]);\nconst MONOTRIBUTO_RECEIVERS = new Set([6, 13, 16]);\n\nconst DOCUMENT_LABELS: Record<number, string> = {\n 80: \"CUIT\",\n 86: \"CUIL\",\n 87: \"CDI\",\n 94: \"Pasaporte\",\n 96: \"DNI\",\n};\nconst UNIDENTIFIED_DOCUMENT = 99;\n\n/** G3: precedes the codes of the observations ARCA returned with the CAE. */\nconst ARCA_OBSERVATIONS_LABEL = \"Observaciones de ARCA:\";\n\n/** G1: RG 1415, art. 15, inc. a), as replaced by RG 5003, art. 20. */\nexport const MONOTRIBUTO_CREDIT_LEGEND =\n \"El crédito fiscal discriminado en el presente comprobante, sólo podrá ser computado a efectos del Régimen de Sostenimiento e Inclusión Fiscal para Pequeños Contribuyentes de la Ley Nº 27.618\";\n\n/** ARCA tributo ids read as national indirect taxes: Impuestos nacionales and Impuestos internos. */\nconst NATIONAL_INDIRECT_TAX_IDS = new Set([1, 4]);\nconst TAX_NAMES: Record<number, string> = {\n 1: \"Impuestos nacionales\",\n 2: \"Impuestos provinciales\",\n 3: \"Impuestos municipales\",\n 4: \"Impuestos internos\",\n 5: \"Ingresos brutos\",\n 6: \"Percepción de IVA\",\n 7: \"Percepción de ingresos brutos\",\n 8: \"Percepciones por impuestos municipales\",\n 9: \"Otras percepciones\",\n 13: \"Percepción de IVA a no categorizado\",\n 99: \"Otros tributos\",\n};\n\n/** RG 5762 replaced class M by class A with retention legend on this date. */\nconst RETENTION_LEGEND_FROM = \"2025-12-01\";\n\nconst TITLES = {\n invoice: \"FACTURA\",\n debit_note: \"NOTA DE DÉBITO\",\n credit_note: \"NOTA DE CRÉDITO\",\n} as const;\n\n/**\n * Derives what a printed class A, B or C voucher must show from the\n * authorized voucher, the items it was issued from and the issuer's profile.\n * Pure. It throws `ArcaInputError` when a required datum is missing, when the\n * items do not add up to the authorized money, or for a voucher it does not\n * render: FCE, and class M vouchers issued before 2025-12-01.\n */\nexport function buildVoucherDocument(\n input: VoucherDocumentInput\n): VoucherDocument {\n const { voucher, issuer } = input;\n const info = describeVoucherType(voucher.voucherType);\n if (info.family === \"fce\") {\n invalid(\n \"voucher.voucherType\",\n \"a class A, B or C invoice or note: FCE vouchers are not rendered yet\"\n );\n }\n if (\n info.family === \"retention_legend\" &&\n voucher.date < RETENTION_LEGEND_FROM\n ) {\n invalid(\n \"voucher.voucherType\",\n \"a voucher issued from 2025-12-01: types 51 to 53 were class M before RG 5762\"\n );\n }\n const voucherClass = voucher.voucherClass;\n assertIssuerMatchesClass(issuer.condition, voucherClass);\n if (voucher.qr === undefined) {\n invalid(\"voucher.qr\", \"the QR every printed voucher carries\");\n }\n const taxId = digits(issuer.taxId);\n if (\n taxId.length !== 11 ||\n (voucher.qrPayload !== undefined &&\n String(voucher.qrPayload.cuit) !== taxId)\n ) {\n invalid(\"issuer.taxId\", \"the 11-digit CUIT the voucher was issued under\");\n }\n const lines = documentLines(input, voucherClass);\n const header = voucher.header;\n const receiver = documentReceiver(input, header);\n return {\n voucherClass,\n voucherType: voucher.voucherType,\n code: String(voucher.voucherType).padStart(3, \"0\"),\n ...letterLegend(info.family, voucherClass, issuer.paymentToInformedCbu),\n title: TITLES[info.kind],\n number: `${String(voucher.salesPoint).padStart(5, \"0\")}-${String(voucher.number).padStart(8, \"0\")}`,\n issueDate: voucher.date,\n issuer: {\n ...(issuer.tradeName\n ? { tradeName: required(issuer.tradeName, \"issuer.tradeName\") }\n : {}),\n legalName: required(issuer.legalName, \"issuer.legalName\"),\n address: required(issuer.address, \"issuer.address\"),\n taxId,\n conditionLegend: ISSUER_LEGENDS[issuer.condition],\n grossIncome: required(issuer.grossIncome, \"issuer.grossIncome\"),\n ...activitiesStart(issuer.activitiesStartDate),\n },\n receiver,\n saleConditions: required(input.saleConditions, \"saleConditions\"),\n remitos: (input.remitos ?? []).map((remito, index) =>\n required(remito, `remitos[${index}]`)\n ),\n ...(header.serviceStartDate && header.serviceEndDate\n ? {\n servicePeriod: {\n from: header.serviceStartDate,\n to: header.serviceEndDate,\n },\n }\n : {}),\n ...(header.paymentDueDate ? { paymentDueDate: header.paymentDueDate } : {}),\n currency: {\n id: header.currencyId,\n ...(header.currencyId !== \"PES\" && header.exchangeRate !== undefined\n ? { exchangeRate: header.exchangeRate }\n : {}),\n },\n lines: lines.lines,\n totals: {\n globalDiscount: lines.globalDiscount,\n ...(lines.adjustments.length > 0\n ? { adjustments: lines.adjustments }\n : {}),\n subtotal: lines.subtotal,\n exempt: voucher.totals.exempt,\n untaxed: voucher.totals.untaxed,\n vatRates: voucherClass === \"A\" ? voucher.totals.vatRates : [],\n otherTaxes: voucher.totals.taxes.map((tax) => ({\n id: tax.id,\n description: tax.description ?? TAX_NAMES[tax.id] ?? \"Otros tributos\",\n amount: tax.amount,\n })),\n adjustment: lines.adjustment,\n total: voucher.totals.total,\n },\n ...(voucherClass === \"B\" &&\n VAT_CONTAINED_RECEIVERS.has(header.receiverVatConditionId)\n ? {\n transparency: {\n vatContained: voucher.totals.vat,\n otherNationalIndirectTaxes: voucher.totals.taxes\n .filter((tax) => NATIONAL_INDIRECT_TAX_IDS.has(tax.id))\n .reduce((sum, tax) => sum + tax.amount, 0),\n },\n }\n : {}),\n authorization: {\n kind: \"CAE\",\n code: voucher.cae,\n dueDate: voucher.caeExpiry,\n },\n qr: voucher.qr,\n legends: legends(input, voucherClass),\n };\n}\n\nfunction letterLegend(\n family: string,\n voucherClass: \"A\" | \"B\" | \"C\",\n paymentToInformedCbu: boolean | undefined\n): Pick<VoucherDocument, \"letterLegend\"> {\n if (family === \"retention_legend\") {\n return { letterLegend: \"OPERACIÓN SUJETA A RETENCIÓN\" };\n }\n return voucherClass === \"A\" && paymentToInformedCbu === true\n ? { letterLegend: \"PAGO EN CBU INFORMADA\" }\n : {};\n}\n\nfunction legends(\n input: VoucherDocumentInput,\n voucherClass: \"A\" | \"B\" | \"C\"\n): VoucherDocument[\"legends\"] {\n if (voucherClass !== \"A\") {\n return [];\n }\n const found: VoucherDocument[\"legends\"] = [];\n if (MONOTRIBUTO_RECEIVERS.has(input.voucher.header.receiverVatConditionId)) {\n found.push({ rule: \"G1\", text: MONOTRIBUTO_CREDIT_LEGEND });\n }\n const codes = [\n ...new Set(\n (input.observations ?? [])\n .map((observation) => String(observation.code ?? \"\").trim())\n .filter((code) => code !== \"\")\n ),\n ];\n if (codes.length > 0) {\n found.push({\n rule: \"G3\",\n text: `${ARCA_OBSERVATIONS_LABEL} ${codes.join(\", \")}`,\n });\n }\n return found;\n}\n\nfunction assertIssuerMatchesClass(\n condition: PrintedIssuerCondition,\n voucherClass: \"A\" | \"B\" | \"C\"\n): void {\n if (!Object.hasOwn(ISSUER_LEGENDS, condition)) {\n invalid(\"issuer.condition\", Object.keys(ISSUER_LEGENDS).join(\", \"));\n }\n const vatRegistered = condition === \"responsable_inscripto\";\n if (vatRegistered !== (voucherClass !== \"C\")) {\n invalid(\n \"issuer.condition\",\n vatRegistered\n ? \"a condition that issues class C vouchers\"\n : \"responsable_inscripto, the only condition that issues class A and B vouchers\"\n );\n }\n}\n\nfunction documentReceiver(\n input: VoucherDocumentInput,\n header: IssuedVoucher[\"header\"]\n): VoucherDocument[\"receiver\"] {\n const condition = header.receiverVatConditionId;\n const conditionLegend = RECEIVER_LEGENDS[condition];\n if (conditionLegend === undefined) {\n invalid(\n \"voucher.header.receiverVatConditionId\",\n \"a receiver condition the SDK renders: 1, 4 to 10, 13, 15 or 16\"\n );\n }\n const name = input.receiver?.name?.trim();\n const address = input.receiver?.address?.trim();\n if (condition !== CONSUMIDOR_FINAL) {\n required(name, \"receiver.name\");\n required(address, \"receiver.address\");\n }\n const identified =\n header.documentType !== UNIDENTIFIED_DOCUMENT &&\n /[1-9]/.test(header.documentNumber);\n if (!identified && condition !== CONSUMIDOR_FINAL) {\n throw new ArcaInputError(\n \"Only a consumidor final may be unidentified on a printed voucher.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"voucher.header.documentNumber\",\n expected: \"the receiver's document (C13 to C17)\",\n }\n );\n }\n const label = DOCUMENT_LABELS[header.documentType];\n return {\n conditionLegend,\n ...(name ? { name } : {}),\n ...(address ? { address } : {}),\n ...(identified\n ? {\n document: {\n type: header.documentType,\n ...(label === undefined ? {} : { label }),\n number: header.documentNumber,\n },\n }\n : {}),\n };\n}\n\n/**\n * The items must describe the authorized money: the same net, exempt and\n * untaxed amounts and the same VAT bases. The printed lines then use the\n * per-item Half Even split, so they add up to the authorized header. With a\n * global discount or labeled adjustments the items are the lines before\n * those changes, which must reconcile with each authorized rate.\n */\nfunction documentLines(\n input: VoucherDocumentInput,\n voucherClass: \"A\" | \"B\" | \"C\"\n): {\n lines: VoucherDocumentLine[];\n globalDiscount: number;\n adjustments: { label: string; amount: number }[];\n subtotal: number;\n adjustment: number;\n} {\n const { items } = input;\n const totals = input.voucher.totals;\n if (!Array.isArray(items) || items.length === 0) {\n invalid(\"items\", \"the items the voucher was issued from\");\n }\n const discount = globalDiscount(input.globalDiscount, voucherClass);\n const adjustments = documentAdjustments(input.adjustments, voucherClass);\n const modified = discount !== undefined || adjustments.length > 0;\n const computed = documentAmounts(input, voucherClass, modified);\n if (!modified) {\n assertItemsMatchTotals(computed.data, totals, voucherClass);\n }\n const settled =\n voucherClass === \"C\"\n ? undefined\n : settleVatItems(\n { voucherClass, items },\n // The header's VAT residual belongs to the money after changes.\n modified ? 0 : computed.amounts.vatAdjustment\n );\n const lines = items.map((item, index): VoucherDocumentLine => {\n const path = `items[${index}]`;\n const money = settled?.items[index];\n const amount =\n money === undefined\n ? (item.amount as number)\n : voucherClass === \"A\"\n ? money.amount - money.vat\n : money.amount;\n return {\n ...(item.code === undefined ? {} : { code: item.code }),\n description: required(item.description, `${path}.description`),\n ...lineQuantity(item, amount, path),\n ...(item.unit === undefined ? {} : { unit: item.unit }),\n ...(item.discount ? { discount: item.discount } : {}),\n amount,\n ...(voucherClass === \"A\" && money !== undefined\n ? { vatRate: money.rate }\n : {}),\n };\n });\n const sum = lines.reduce((total, line) => total + line.amount, 0);\n const rows = totals.vatRates.reduce((total, row) => total + row.amount, 0);\n const adjustmentRows = adjustments.map(({ label, total }) => ({\n label,\n amount: total,\n }));\n if (modified) {\n assertModifiedLinesMatchTotals(\n voucherClass,\n lines,\n settled?.items,\n computed.data,\n totals,\n discount?.byRate ?? new Map(),\n adjustments\n );\n return {\n lines,\n globalDiscount: discount?.total ?? 0,\n adjustments: adjustmentRows,\n subtotal:\n voucherClass === \"A\"\n ? totals.netTaxed\n : sumMinorUnits(\n [\n sum,\n -(discount?.total ?? 0),\n ...adjustmentRows.map((row) => row.amount),\n ],\n \"adjustments\"\n ),\n adjustment: voucherClass === \"C\" ? 0 : totals.vat - rows,\n };\n }\n if (voucherClass === \"A\") {\n // The rows keep their computed VAT; an asserted total moves only the header.\n return {\n lines,\n globalDiscount: 0,\n adjustments: [],\n subtotal: totals.netTaxed,\n adjustment: totals.vat - rows,\n };\n }\n return {\n lines,\n globalDiscount: 0,\n adjustments: [],\n subtotal: sum,\n adjustment: settled?.unabsorbed ?? 0,\n };\n}\n\nfunction documentAmounts(\n input: VoucherDocumentInput,\n voucherClass: \"A\" | \"B\" | \"C\",\n modified: boolean\n): ReturnType<typeof calculateWsfeAmounts> {\n try {\n return calculateWsfeAmounts({\n voucherClass,\n items: input.items,\n // The printed items precede changes already in the authorized total.\n ...(modified\n ? {}\n : {\n total: input.voucher.totals.total - input.voucher.totals.otherTaxes,\n }),\n });\n } catch (error) {\n if (\n error instanceof ArcaInputError &&\n error.code === \"ARCA_INPUT_AMOUNT_MISMATCH\"\n ) {\n mismatch(\"total\");\n }\n throw error;\n }\n}\n\ntype GlobalDiscount = {\n total: number;\n /** By ARCA VAT rate id; class C keys its one amount by 0. */\n byRate: ReadonlyMap<number, number>;\n};\n\ntype DocumentAdjustment = GlobalDiscount & { label: string; field: string };\n\nfunction documentAdjustments(\n value: VoucherDocumentInput[\"adjustments\"],\n voucherClass: \"A\" | \"B\" | \"C\"\n): DocumentAdjustment[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n invalid(\"adjustments\", \"an array of labeled signed adjustments\");\n }\n return value.flatMap((entry: VoucherDocumentAdjustment, index: number) => {\n const field = `adjustments[${index}].amount`;\n if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n invalid(`adjustments[${index}]`, \"a labeled signed adjustment\");\n }\n const label = required(entry.label, `adjustments[${index}].label`);\n const byRate = adjustmentByRate(entry.amount, field, voucherClass);\n // A zero sum across different rates is still a change to reconcile and print.\n return byRate.size === 0\n ? []\n : [\n {\n label,\n field,\n byRate,\n total: sumMinorUnits([...byRate.values()], field),\n },\n ];\n });\n}\n\nfunction adjustmentByRate(\n amount: VoucherDocumentAdjustment[\"amount\"],\n field: string,\n voucherClass: \"A\" | \"B\" | \"C\"\n): Map<number, number> {\n if (voucherClass === \"C\") {\n const money = signedAmount(amount, field);\n return money === 0 ? new Map() : new Map([[0, money]]);\n }\n if (amount === null || typeof amount !== \"object\" || Array.isArray(amount)) {\n invalid(field, \"signed amounts by ARCA VAT rate id on class A or B\");\n }\n const byRate = new Map<number, number>();\n for (const [key, money] of Object.entries(amount)) {\n const id = Number(key);\n if (String(id) !== key || vatRatePercent(id) === undefined) {\n invalid(`${field}[${key}]`, \"keyed by an ARCA VAT rate id\");\n }\n const checked = signedAmount(money, `${field}[${key}]`);\n if (checked !== 0) {\n byRate.set(id, checked);\n }\n }\n return byRate;\n}\n\nfunction signedAmount(value: unknown, field: string): number {\n if (!Number.isSafeInteger(value)) {\n invalid(field, \"a signed safe integer in minor units\");\n }\n return value as number;\n}\n\nfunction sumMinorUnits(values: readonly number[], field: string): number {\n const sum = Number(\n values.reduce((total, amount) => total + BigInt(amount), 0n)\n );\n if (!Number.isSafeInteger(sum)) {\n invalid(field, \"a sum within the safe integer range in minor units\");\n }\n return sum;\n}\n\n/** Undefined when there is no discount, or every amount is zero. */\nfunction globalDiscount(\n value: VoucherDocumentInput[\"globalDiscount\"],\n voucherClass: \"A\" | \"B\" | \"C\"\n): GlobalDiscount | undefined {\n if (value === undefined) {\n return;\n }\n const byRate = new Map<number, number>();\n if (voucherClass === \"C\") {\n if (typeof value !== \"number\") {\n invalid(\n \"globalDiscount\",\n \"one amount in minor units on a class C voucher\"\n );\n }\n byRate.set(0, discountAmount(value, \"globalDiscount\"));\n } else {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n invalid(\n \"globalDiscount\",\n \"amounts by ARCA VAT rate id on a class A or B voucher, as the authorized VAT rows\"\n );\n }\n for (const [key, amount] of Object.entries(value)) {\n const id = Number(key);\n if (!/^\\d+$/.test(key) || vatRatePercent(id) === undefined) {\n invalid(`globalDiscount[${key}]`, \"keyed by an ARCA VAT rate id\");\n }\n const checked = discountAmount(amount, `globalDiscount[${key}]`);\n if (checked > 0) {\n byRate.set(id, checked);\n }\n }\n }\n const total = [...byRate.values()].reduce((sum, amount) => sum + amount, 0);\n return total === 0 ? undefined : { total, byRate };\n}\n\nfunction discountAmount(value: unknown, field: string): number {\n if (!(Number.isSafeInteger(value) && (value as number) >= 0)) {\n invalid(field, \"a non-negative safe integer in minor units\");\n }\n return value as number;\n}\n\n/**\n * Class A compares net lines with the authorized base of each rate, class B\n * lines with VAT with that base plus its VAT, and class C the lines with the\n * net. Exempt and untaxed lines take no discount or adjustment.\n */\nfunction assertModifiedLinesMatchTotals(\n voucherClass: \"A\" | \"B\" | \"C\",\n lines: readonly VoucherDocumentLine[],\n settled: readonly { rate: VatRate }[] | undefined,\n data: ReturnType<typeof calculateWsfeAmounts>[\"data\"],\n totals: VoucherTotals,\n discount: ReadonlyMap<number, number>,\n adjustments: readonly DocumentAdjustment[]\n): void {\n const minor = (value: number) =>\n Number(normalizeArcaAmountToMinorUnits(value, \"items\"));\n if (minor(data.exemptAmount) !== totals.exempt) {\n mismatch(\"exempt\");\n }\n if (minor(data.nonTaxableAmount) !== totals.untaxed) {\n mismatch(\"untaxed\");\n }\n const { byLines, authorized } =\n voucherClass === \"C\" || settled === undefined\n ? {\n byLines: new Map([\n [0, lines.reduce((sum, line) => sum + line.amount, 0)],\n ]),\n authorized: new Map([[0, totals.netTaxed]]),\n }\n : modifiedRates(voucherClass, lines, settled, totals);\n assertRatesPresent(byLines, discount, \"globalDiscount\");\n for (const adjustment of adjustments) {\n assertRatesPresent(byLines, adjustment.byRate, adjustment.field);\n }\n for (const id of new Set([...byLines.keys(), ...authorized.keys()])) {\n const expected = authorized.get(id) ?? 0;\n const actual =\n BigInt(byLines.get(id) ?? 0) -\n BigInt(discount.get(id) ?? 0) +\n adjustments.reduce(\n (sum, adjustment) => sum + BigInt(adjustment.byRate.get(id) ?? 0),\n 0n\n );\n if (actual !== BigInt(expected)) {\n throw new ArcaInputError(\n \"items less the global discount plus adjustments do not add up to the authorized voucher.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: modificationField(voucherClass, id, adjustments.length > 0),\n expected: `${expected} minor units of lines less discount plus adjustments`,\n }\n );\n }\n }\n}\n\nfunction assertRatesPresent(\n byLines: ReadonlyMap<number, number>,\n byRate: ReadonlyMap<number, number>,\n field: string\n): void {\n for (const id of byRate.keys()) {\n if (!byLines.has(id)) {\n invalid(`${field}[${id}]`, \"keyed by a VAT rate id the items carry\");\n }\n }\n}\n\nfunction modificationField(\n voucherClass: \"A\" | \"B\" | \"C\",\n id: number,\n adjusted: boolean\n): string {\n if (adjusted) {\n return voucherClass === \"C\"\n ? \"adjustments\"\n : `adjustments (VAT rate ${id})`;\n }\n return voucherClass === \"C\" ? \"globalDiscount\" : `globalDiscount[${id}]`;\n}\n\n/** The taxed lines and the authorized money of each VAT rate id. */\nfunction modifiedRates(\n voucherClass: \"A\" | \"B\",\n lines: readonly VoucherDocumentLine[],\n settled: readonly { rate: VatRate }[],\n totals: VoucherTotals\n): { byLines: Map<number, number>; authorized: Map<number, number> } {\n const byLines = new Map<number, number>();\n for (const [index, line] of lines.entries()) {\n const rate = settled[index]?.rate;\n if (typeof rate === \"number\") {\n const id = vatRateId(rate);\n byLines.set(id, (byLines.get(id) ?? 0) + line.amount);\n }\n }\n const authorized = new Map<number, number>();\n for (const row of totals.vatRates) {\n const amount = voucherClass === \"A\" ? row.base : row.base + row.amount;\n authorized.set(row.id, (authorized.get(row.id) ?? 0) + amount);\n }\n return { byLines, authorized };\n}\n\nfunction assertItemsMatchTotals(\n data: ReturnType<typeof calculateWsfeAmounts>[\"data\"],\n totals: VoucherTotals,\n voucherClass: \"A\" | \"B\" | \"C\"\n): void {\n const minor = (value: number) =>\n Number(normalizeArcaAmountToMinorUnits(value, \"items\"));\n for (const [field, value, authorized] of [\n [\"netTaxed\", data.netAmount, totals.netTaxed],\n [\"exempt\", data.exemptAmount, totals.exempt],\n [\"untaxed\", data.nonTaxableAmount, totals.untaxed],\n [\"vat\", data.vatAmount, totals.vat],\n ] as const) {\n if (minor(value) !== authorized) {\n mismatch(field);\n }\n }\n if (voucherClass === \"C\") {\n return;\n }\n const bases = (rows: readonly { id: number; base: number }[]) =>\n rows\n .filter((row) => row.base !== 0)\n .map((row) => `${row.id}:${row.base}`)\n .sort()\n .join(\",\");\n const computedBases = (data.vatRates ?? []).map((row) => ({\n id: row.id,\n base: minor(row.baseAmount),\n }));\n if (bases(computedBases) !== bases(totals.vatRates)) {\n mismatch(\"vatRates\");\n }\n}\n\n/** C20 and C21: a line without quantity is one unit at its amount. */\nfunction lineQuantity(\n item: VatItem | AmountItem,\n amount: number,\n path: string\n): { quantity: number; unitPrice: string } {\n const discount = item.discount ?? 0;\n if (!(Number.isSafeInteger(discount) && discount >= 0)) {\n invalid(`${path}.discount`, \"a non-negative safe integer in minor units\");\n }\n if (item.quantity === undefined && item.unitPrice === undefined) {\n // The line amount is net of the discount: the unit price is not.\n return { quantity: 1, unitPrice: majorUnits(amount + discount) };\n }\n const { quantity, unitPrice } = item;\n if (\n !(typeof quantity === \"number\" && Number.isFinite(quantity) && quantity > 0)\n ) {\n invalid(`${path}.quantity`, \"a positive quantity, given with unitPrice\");\n }\n if (typeof unitPrice !== \"string\" || !/^\\d+(\\.\\d{1,6})?$/.test(unitPrice)) {\n invalid(\n `${path}.unitPrice`,\n \"a major-unit decimal string with at most six decimals, given with quantity\"\n );\n }\n const printed = Math.round(quantity * Number(unitPrice) * 100) - discount;\n if (Math.abs(printed - amount) > 1) {\n throw new ArcaInputError(\n `${path}: quantity × unitPrice − discount does not match the line amount.`,\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: `${path}.unitPrice`,\n expected: `${amount} minor units, within one: without VAT on class A, with VAT on class B`,\n }\n );\n }\n return { quantity, unitPrice };\n}\n\nfunction activitiesStart(date: string | null): {\n activitiesStartDate?: string;\n} {\n if (date === null) {\n return {};\n }\n if (typeof date !== \"string\" || !/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) {\n invalid(\n \"issuer.activitiesStartDate\",\n \"YYYY-MM-DD, or null for the exceptions of RG 1415, Anexo II, A, V 6\"\n );\n }\n return { activitiesStartDate: date };\n}\n\nfunction majorUnits(minor: number): string {\n const cents = String(minor).padStart(3, \"0\");\n return `${cents.slice(0, -2)}.${cents.slice(-2)}`;\n}\n\nfunction digits(value: string): string {\n return typeof value === \"string\" ? value.replace(/\\D/g, \"\") : \"\";\n}\n\nfunction required(value: string | undefined, field: string): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new ArcaInputError(`${field} is required on a printed voucher.`, {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field,\n });\n }\n return value.trim();\n}\n\nfunction mismatch(field: string): never {\n throw new ArcaInputError(\"items do not add up to the authorized voucher.\", {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: `items (${field})`,\n expected: \"the items the voucher was issued from\",\n });\n}\n\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n","import { abortable } from \"../internal/abort\";\nimport { throwIfAborted } from \"./lock\";\nimport type { ArcaStore } from \"./types\";\n\n/** In-process store for tests; reservations do not survive a restart. */\nexport function createMemoryStore(): ArcaStore {\n const values = new Map<string, string>();\n const locks = new Map<string, Promise<void>>();\n return {\n get: (key) => Promise.resolve(values.get(key) ?? null),\n set(key, value) {\n values.set(key, value);\n return Promise.resolve();\n },\n add(key, value) {\n if (values.has(key)) {\n return Promise.resolve(false);\n }\n values.set(key, value);\n return Promise.resolve(true);\n },\n delete(key) {\n values.delete(key);\n return Promise.resolve();\n },\n async withLock(key, fn, { signal } = {}) {\n throwIfAborted(signal);\n const previous = locks.get(key) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.catch(() => undefined).then(() => current);\n locks.set(key, queued);\n // An abort ends the wait early; the check below reports it.\n await abortable(\n previous.catch(() => undefined),\n signal\n ).catch(() => undefined);\n if (signal?.aborted) {\n // Hand the turn on, but keep this call's place until the holder\n // before it finishes: a caller arriving now must still wait for it.\n release();\n queued.then(() => {\n if (locks.get(key) === queued) {\n locks.delete(key);\n }\n });\n throwIfAborted(signal);\n }\n try {\n return await fn();\n } finally {\n release();\n if (locks.get(key) === queued) {\n locks.delete(key);\n }\n }\n },\n };\n}\n","import { ArcaConfigurationError } from \"../errors\";\nimport { ARCA_LEASE_MS, withLease } from \"./lock\";\nimport { type ArcaStore, storeCall } from \"./types\";\n\ntype Row = { key?: string; value?: string };\n/** Uses the caller's SQL client; provision the table before use. */\nexport function createPostgresStore({\n query,\n table = \"arca_store\",\n}: {\n query: (text: string, params: string[]) => Promise<Row[] | { rows: Row[] }>;\n table?: string;\n}): ArcaStore {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(table)) {\n throw new ArcaConfigurationError(\"Invalid ARCA store table identifier.\");\n }\n const name = `\"${table}\"`;\n const lease = Math.round(ARCA_LEASE_MS / 1000);\n const run = (text: string, params: string[]) =>\n storeCall(async () => {\n const result = await query(text, params);\n return Array.isArray(result) ? result : result.rows;\n });\n return {\n async get(key) {\n return (\n (await run(`SELECT value FROM ${name} WHERE key = $1`, [key]))[0]\n ?.value ?? null\n );\n },\n async set(key, value) {\n await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`,\n [key, value]\n );\n },\n async add(key, value) {\n return (\n (\n await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key`,\n [key, value]\n )\n ).length > 0\n );\n },\n async delete(key) {\n await run(`DELETE FROM ${name} WHERE key = $1`, [key]);\n },\n withLock(key, fn, options) {\n // A lease row, not an advisory lock: it survives a transaction-mode\n // pooler, where a session-scoped lock would be taken on another backend.\n return withLease(\n {\n async acquire(owner) {\n const taken = await run(\n `INSERT INTO ${name} (key, value) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key`,\n [key, owner]\n );\n if (taken.length > 0) {\n return true;\n }\n const expired = await run(\n `UPDATE ${name} SET value = $2, updated_at = now() WHERE key = $1 AND updated_at < now() - interval '${lease} seconds' RETURNING key`,\n [key, owner]\n );\n return expired.length > 0;\n },\n async renew(owner) {\n await run(\n `UPDATE ${name} SET updated_at = now() WHERE key = $1 AND value = $2`,\n [key, owner]\n );\n },\n async release(owner) {\n await run(`DELETE FROM ${name} WHERE key = $1 AND value = $2`, [\n key,\n owner,\n ]);\n },\n },\n fn,\n options\n );\n },\n };\n}\n","import { ArcaConfigurationError } from \"../errors\";\nimport { ARCA_LEASE_MS, withLease } from \"./lock\";\nimport { type ArcaLockOptions, type ArcaStore, storeCall } from \"./types\";\n\ntype RedisClient = {\n get(key: string): Promise<unknown>;\n set(key: string, value: string): Promise<unknown>;\n call?(...args: string[]): Promise<unknown>;\n del?(key: string): Promise<unknown>;\n};\n/** Uses ioredis or Upstash without importing either driver. */\nexport function createRedisStore(\n client: RedisClient,\n options: { flavor?: \"ioredis\" | \"upstash\" } = {}\n): ArcaStore {\n const flavor =\n options.flavor ??\n (typeof client.call === \"function\" ? \"ioredis\" : \"upstash\");\n if (flavor === \"ioredis\" && !client.call) {\n throw new ArcaConfigurationError(\n \"ARCA Redis ioredis flavor requires client.call.\"\n );\n }\n // The public structural type accepts ioredis's overloaded set method.\n // Only the Upstash flavor invokes its options-object overload.\n const upstashSet = client.set as (\n key: string,\n value: string,\n options: { nx?: true; xx?: true; px?: number }\n ) => Promise<unknown>;\n const read = async (key: string) => {\n const value = await client.get(key);\n if (value === null || value === undefined) {\n return null;\n }\n // Upstash can deserialize stored JSON automatically.\n return typeof value === \"string\" ? value : JSON.stringify(value);\n };\n // A lease, so a crashed holder frees the key; a renewal keeps a live one.\n const lease = (key: string, owner: string, mode: \"nx\" | \"xx\") =>\n storeCall(\n async () =>\n (flavor === \"ioredis\"\n ? await client.call?.(\n \"SET\",\n key,\n owner,\n mode.toUpperCase(),\n \"PX\",\n String(ARCA_LEASE_MS)\n )\n : await upstashSet.call(client, key, owner, {\n [mode]: true,\n px: ARCA_LEASE_MS,\n })) === \"OK\"\n );\n return {\n get: (key) => storeCall(() => read(key)),\n set: (key, value) =>\n storeCall(async () => {\n await client.set(key, value);\n }),\n add: (key, value) =>\n storeCall(\n async () =>\n (flavor === \"ioredis\"\n ? await client.call?.(\"SET\", key, value, \"NX\")\n : await upstashSet.call(client, key, value, { nx: true })) === \"OK\"\n ),\n ...(client.del\n ? {\n delete: (key: string) =>\n storeCall(async () => {\n await client.del?.(key);\n }),\n withLock: <T>(\n key: string,\n fn: () => Promise<T>,\n options?: ArcaLockOptions\n ) =>\n withLease(\n {\n acquire: (owner) => lease(key, owner, \"nx\"),\n renew: async (owner) => {\n // Check and set: only the holder extends its own lease.\n if ((await storeCall(() => read(key))) === owner) {\n await lease(key, owner, \"xx\");\n }\n },\n release: async (owner) => {\n await storeCall(async () => {\n if ((await read(key)) === owner) {\n await client.del?.(key);\n }\n });\n },\n },\n fn,\n options\n ),\n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