@happyvertical/accounting 0.104.0 → 0.105.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.
Files changed (31) hide show
  1. package/README.md +101 -0
  2. package/dist/chunks/{errors-BHWEFjkq.js → errors-DIqXkm4s.js} +4 -1
  3. package/dist/chunks/errors-DIqXkm4s.js.map +1 -0
  4. package/dist/chunks/{quickbooks-CIedOmSC.js → quickbooks-Bh9k87sj.js} +169 -7
  5. package/dist/chunks/quickbooks-Bh9k87sj.js.map +1 -0
  6. package/dist/chunks/{invoice-request-D5fbd6Id.js → receivable-transfer-DQmMBcRo.js} +183 -7
  7. package/dist/chunks/receivable-transfer-DQmMBcRo.js.map +1 -0
  8. package/dist/chunks/{stripe-CECceZH5.js → stripe-DOJLldVK.js} +2 -2
  9. package/dist/chunks/{stripe-CECceZH5.js.map → stripe-DOJLldVK.js.map} +1 -1
  10. package/dist/errors.d.ts +3 -0
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/index.d.ts +3 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +68 -5
  15. package/dist/index.js.map +1 -1
  16. package/dist/providers/quickbooks/document-readback.d.ts +18 -0
  17. package/dist/providers/quickbooks/document-readback.d.ts.map +1 -0
  18. package/dist/providers/quickbooks/index.d.ts +5 -7
  19. package/dist/providers/quickbooks/index.d.ts.map +1 -1
  20. package/dist/providers/quickbooks/invoice-request.d.ts +2 -0
  21. package/dist/providers/quickbooks/invoice-request.d.ts.map +1 -1
  22. package/dist/providers/quickbooks/receivable-operations.d.ts +22 -0
  23. package/dist/providers/quickbooks/receivable-operations.d.ts.map +1 -0
  24. package/dist/providers/quickbooks/receivable-transfer.d.ts +89 -0
  25. package/dist/providers/quickbooks/receivable-transfer.d.ts.map +1 -0
  26. package/dist/types.d.ts +5 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/dist/chunks/errors-BHWEFjkq.js.map +0 -1
  30. package/dist/chunks/invoice-request-D5fbd6Id.js.map +0 -1
  31. package/dist/chunks/quickbooks-CIedOmSC.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"invoice-request-D5fbd6Id.js","names":[],"sources":["../../src/providers/quickbooks/line-amount.ts","../../src/providers/quickbooks/invoice-request.ts"],"sourcesContent":["/** ISO 4217 List One, published 2026-09-17. Do not use Intl display digits:\n * ICU differs for e.g. IQD, MGA and RSD, and omits fund codes CLF/UYW.\n * https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml\n * N.A., unknown and missing codes cannot authorize currency rounding.\n */\nconst precisionGroups: readonly (readonly [number, string])[] = [\n [0, 'BIF CLP DJF GNF ISK JPY KMF KRW PYG RWF UGX UYI VND VUV XAF XOF XPF'],\n [\n 2,\n 'AED AFN ALL AMD AOA ARS AUD AWG AZN BAM BBD BDT BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CNY COP COU CRC CUP CVE CZK DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GTQ GYD HKD HNL HTG HUF IDR ILS INR IRR JMD KES KGS KHR KPW KYD KZT LAK LBP LKR LRD LSL MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD PAB PEN PGK PHP PKR PLN QAR RON RSD RUB SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SVC SYP SZL THB TJS TMT TOP TRY TTD TWD TZS UAH USD USN UYU UZS VED VES WST XAD XCD XCG YER ZAR ZMW ZWG',\n ],\n [3, 'BHD IQD JOD KWD LYD OMR TND'],\n [4, 'CLF UYW'],\n];\nconst currencyPrecision = new Map(\n precisionGroups.flatMap(([precision, codes]) =>\n codes.split(' ').map((code) => [code, precision] as const),\n ),\n);\n\n/** ISO minor-unit factor, or undefined when the code is unknown or omitted. */\nexport function currencyMinorUnitFactor(\n currency: string | undefined,\n): number | undefined {\n if (typeof currency !== 'string') return undefined;\n const precision = currencyPrecision.get(currency.toUpperCase());\n return precision === undefined ? undefined : 10 ** precision;\n}\n\n/** True only for a finite amount exactly representable on the ISO minor-unit grid. */\nexport function isCurrencyMinorUnit(\n amount: number,\n currency: string | undefined,\n): boolean {\n if (!Number.isFinite(amount) || typeof currency !== 'string') return false;\n const precision = currencyPrecision.get(currency.toUpperCase());\n if (precision === undefined) return false;\n const value = decimalRatio(Math.abs(amount));\n return (\n (value.numerator * 10n ** BigInt(precision)) % value.denominator === 0n\n );\n}\n\n/** Round a finite major-unit amount half-up to a known ISO currency grid. */\nexport function roundCurrencyAmount(\n amount: number,\n currency: string | undefined,\n): number | undefined {\n if (!Number.isFinite(amount) || typeof currency !== 'string')\n return undefined;\n const precision = currencyPrecision.get(currency.toUpperCase());\n if (precision === undefined) return undefined;\n const sign = amount < 0 ? -1n : 1n;\n const value = decimalRatio(Math.abs(amount));\n const scale = 10n ** BigInt(precision);\n const numerator = value.numerator * scale;\n const rounded =\n numerator / value.denominator +\n ((numerator % value.denominator) * 2n >= value.denominator ? 1n : 0n);\n return Number(sign * rounded) / Number(scale);\n}\n\n/** Exact decimal interpretation of the finite nonnegative public number value. */\nfunction decimalRatio(value: number): {\n numerator: bigint;\n denominator: bigint;\n} {\n const [significand, exponent = '0'] = value.toString().split('e');\n const [whole, fraction = ''] = significand.split('.');\n const coefficient = BigInt(whole + fraction);\n const scale = fraction.length - Number(exponent);\n return scale >= 0\n ? { numerator: coefficient, denominator: 10n ** BigInt(scale) }\n : { numerator: coefficient * 10n ** BigInt(-scale), denominator: 1n };\n}\n\n/** Admit only the exact half-up minor-unit result; never rewrite caller money. */\nexport function matchesCurrencyRoundedLineAmount(\n quantity: number,\n unitPrice: number,\n amount: number,\n currency: string | undefined,\n): boolean {\n if (typeof currency !== 'string') return false;\n const precision = currencyPrecision.get(currency.toUpperCase());\n if (precision === undefined) return false;\n const minorScale = 10n ** BigInt(precision);\n const retained = decimalRatio(amount);\n const retainedMinor = retained.numerator * minorScale;\n // An off-grid caller amount is not permission to round their supplied money.\n if (retainedMinor % retained.denominator !== 0n) return false;\n const qty = decimalRatio(quantity);\n const price = decimalRatio(unitPrice);\n const numerator = qty.numerator * price.numerator * minorScale;\n const denominator = qty.denominator * price.denominator;\n const quotient = numerator / denominator;\n const rounded =\n quotient + ((numerator % denominator) * 2n >= denominator ? 1n : 0n);\n return retainedMinor / retained.denominator === rounded;\n}\n","import { createHash } from 'node:crypto';\nimport type {\n CreditMemoInput,\n InvoiceInput,\n InvoiceLineItemInput,\n QuickBooksCreditMemoRequest,\n QuickBooksInvoiceRequest,\n} from '../../types.js';\nimport {\n currencyMinorUnitFactor,\n isCurrencyMinorUnit,\n matchesCurrencyRoundedLineAmount,\n roundCurrencyAmount,\n} from './line-amount.js';\n\ntype QuickBooksCreateRequest =\n | QuickBooksInvoiceRequest\n | QuickBooksCreditMemoRequest;\n\ninterface QuickBooksSalesLine {\n LineNum: number;\n Description: string;\n Amount: number;\n DetailType: 'SalesItemLineDetail';\n SalesItemLineDetail: {\n Qty: number;\n UnitPrice: number;\n ItemRef?: { value: string };\n TaxCodeRef?: { value: string };\n TaxInclusiveAmt?: number;\n };\n}\n\ninterface QuickBooksTaxLine {\n Amount: number;\n DetailType: 'TaxLineDetail';\n TaxLineDetail: {\n TaxRateRef: { value: string };\n TaxPercent: number;\n PercentBased: true;\n NetAmountTaxable?: number;\n };\n}\n\ninterface FrozenTaxComponent {\n taxRateRef: string;\n rate: DecimalRate;\n taxMinor: bigint;\n compound: boolean;\n basisMinor: bigint;\n explicitBasis: boolean;\n}\n\ninterface DecimalRate {\n numerator: bigint;\n denominator: bigint;\n value: number;\n}\n\n/** Prepare once, persist before sending, and reuse unchanged. Performs no I/O. */\nexport function prepareQuickBooksInvoiceRequest(\n invoice: InvoiceInput,\n identity: Omit<QuickBooksInvoiceRequest, 'payloadHash'>,\n): QuickBooksInvoiceRequest {\n if (invoice.externalId)\n throw new Error('QuickBooks request identity is only for invoice creation');\n return prepareRequest(mapInvoiceToQBO(invoice), identity, 'invoice');\n}\n\n/** Prepare once, persist before sending, and reuse unchanged. Performs no I/O. */\nexport function prepareQuickBooksCreditMemoRequest(\n creditMemo: CreditMemoInput,\n identity: Omit<\n QuickBooksCreditMemoRequest,\n 'payloadHash' | 'creditedInvoiceExternalId'\n >,\n): QuickBooksCreditMemoRequest {\n if (creditMemo.externalId)\n throw new Error(\n 'QuickBooks request identity is only for credit memo creation',\n );\n return prepareRequest(\n mapCreditMemoToQBO(creditMemo),\n {\n ...identity,\n creditedInvoiceExternalId: creditMemo.creditedInvoiceExternalId,\n },\n 'credit memo',\n );\n}\n\nfunction prepareRequest<T extends QuickBooksCreateRequest>(\n mapped: unknown,\n identity: Omit<T, 'payloadHash'>,\n kind: 'invoice' | 'credit memo',\n): T {\n const payload = JSON.stringify(mapped);\n const request = {\n ...identity,\n payloadHash: hashDescriptorPayload(payload, identity, kind),\n } as T;\n validateRequest(\n request,\n identity.realmId,\n identity.environment,\n payload,\n kind,\n );\n return Object.freeze(request);\n}\n\nfunction hash(payload: string): string {\n return createHash('sha256').update(payload).digest('hex');\n}\n\n/** Bind a credit memo's immutable source invoice without sending it to QBO. */\nfunction hashDescriptorPayload(\n payload: string,\n request:\n | QuickBooksCreateRequest\n | Omit<QuickBooksCreateRequest, 'payloadHash'>,\n kind: 'invoice' | 'credit memo',\n): string {\n if (kind === 'invoice') return hash(payload);\n const creditMemoRequest = request as QuickBooksCreditMemoRequest;\n return hash(\n JSON.stringify({\n payload,\n linkage: {\n creditedInvoiceExternalId: creditMemoRequest.creditedInvoiceExternalId,\n },\n }),\n );\n}\n\nexport function validateQuickBooksInvoiceRequest(\n request: QuickBooksInvoiceRequest,\n realmId: string,\n environment: 'sandbox' | 'production',\n payload: string | undefined,\n): void {\n validateRequest(request, realmId, environment, payload, 'invoice');\n}\n\nexport function validateQuickBooksCreditMemoRequest(\n request: QuickBooksCreditMemoRequest,\n realmId: string,\n environment: 'sandbox' | 'production',\n payload: string | undefined,\n): void {\n validateRequest(request, realmId, environment, payload, 'credit memo');\n}\n\nfunction validateRequest(\n request: QuickBooksCreateRequest,\n realmId: string,\n environment: 'sandbox' | 'production',\n payload: string | undefined,\n kind: 'invoice' | 'credit memo',\n): void {\n if (\n !request ||\n typeof request.requestId !== 'string' ||\n !/^[A-Za-z0-9._-]{1,50}$/.test(request.requestId)\n ) {\n throw new Error(\n 'QuickBooks requestId must contain 1–50 URL-safe letters, digits, dots, underscores or hyphens',\n );\n }\n if (\n !request.realmId ||\n request.realmId !== realmId ||\n !['sandbox', 'production'].includes(request.environment) ||\n request.environment !== environment\n ) {\n throw new Error(`QuickBooks ${kind} request realm/environment mismatch`);\n }\n if (\n !payload ||\n request.payloadHash !== hashDescriptorPayload(payload, request, kind)\n ) {\n throw new Error(\n `QuickBooks ${kind} request payload mismatch; reconcile the original request`,\n );\n }\n if (\n kind === 'credit memo' &&\n (!('creditedInvoiceExternalId' in request) ||\n !request.creditedInvoiceExternalId ||\n request.creditedInvoiceExternalId.trim() !==\n request.creditedInvoiceExternalId)\n ) {\n throw new Error(\n 'QuickBooks credit memo request requires a credited invoice external ID',\n );\n }\n const parsed = JSON.parse(payload);\n if (parsed.Id !== undefined || parsed.SyncToken !== undefined) {\n throw new Error(`QuickBooks request identity is only for ${kind} creation`);\n }\n}\n\nfunction formatLocalDate(date: Date): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\nfunction close(a: number, b: number): boolean {\n return (\n Number.isFinite(a) &&\n Number.isFinite(b) &&\n Math.abs(a - b) <=\n Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)) * 8\n );\n}\n\nfunction finite(value: number, label: string, allowNegative = false): number {\n if (!Number.isFinite(value) || (!allowNegative && value < 0))\n throw new Error(\n `QuickBooks ${label} must be a finite ${allowNegative ? '' : 'non-negative '}amount`,\n );\n return value;\n}\n\nfunction reference(value: string | undefined, label: string) {\n if (!value || value.trim() !== value || value.length > 255)\n throw new Error(`QuickBooks ${label} must be a non-empty realm reference`);\n return { value };\n}\n\nfunction canonicalRateNumber(value: number): string {\n // Number inputs can carry an adjacent binary representation of the exact\n // frozen decimal (for example 0.1 + 0.2). Prefer the shortest nearby decimal\n // through the calculator's supported precision, without changing a value\n // whose additional digits are materially distinct.\n for (let places = 0; places <= 12; places++) {\n const candidate = Number(value.toFixed(places));\n if (close(value, candidate)) return candidate.toString();\n }\n return value.toString();\n}\n\nfunction decimalRate(\n value: number | string | undefined,\n label: string,\n): DecimalRate {\n const text =\n typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value)\n ? value\n : typeof value === 'number' && Number.isFinite(value) && value >= 0\n ? canonicalRateNumber(value)\n : undefined;\n if (!text || !/^\\d+(?:\\.\\d+)?$/.test(text))\n throw new Error(\n `QuickBooks ${label} needs a frozen component rate from 0 through 1`,\n );\n const [whole, fraction = ''] = text.split('.');\n const denominator = 10n ** BigInt(fraction.length);\n const numerator = BigInt(`${whole}${fraction}`);\n if (numerator > denominator)\n throw new Error(\n `QuickBooks ${label} needs a frozen component rate from 0 through 1`,\n );\n return { numerator, denominator, value: Number(text) };\n}\n\nfunction ratesEqual(left: DecimalRate, right: DecimalRate): boolean {\n return (\n left.numerator * right.denominator === right.numerator * left.denominator\n );\n}\n\nfunction addRates(left: DecimalRate, right: DecimalRate): DecimalRate {\n const numerator =\n left.numerator * right.denominator + right.numerator * left.denominator;\n const denominator = left.denominator * right.denominator;\n return {\n numerator,\n denominator,\n value: Number(numerator) / Number(denominator),\n };\n}\n\nfunction taxPercent(rate: DecimalRate): number {\n return Number(rate.numerator * 100n) / Number(rate.denominator);\n}\n\nfunction currencyMinor(\n amount: number,\n currency: string | undefined,\n label: string,\n): bigint {\n const factor = currencyMinorUnitFactor(currency);\n const rounded = roundCurrencyAmount(amount, currency);\n if (\n factor === undefined ||\n rounded === undefined ||\n (!isCurrencyMinorUnit(amount, currency) && !close(amount, rounded))\n )\n throw new Error(\n `QuickBooks ${label} must fit the explicitly supplied currency's ISO 4217 minor-unit grid`,\n );\n // Match frozenCurrencyAmount: only a value already admitted as ordinary\n // binary noise is normalized before exact minor-unit aggregation. A genuine\n // off-grid value still refuses before any request is mapped.\n return BigInt(\n Math.round(\n (isCurrencyMinorUnit(amount, currency) ? amount : rounded) * factor,\n ),\n );\n}\n\nfunction currencyMajor(minor: bigint, currency: string | undefined): number {\n const factor = currencyMinorUnitFactor(currency);\n if (factor === undefined)\n throw new Error('QuickBooks needs a known currency');\n return Number(minor) / factor;\n}\n\nfunction taxMinorMatchesAllocation(\n taxMinor: bigint,\n numerator: bigint,\n denominator: bigint,\n): boolean {\n const floor = numerator / denominator;\n const remainder = numerator % denominator;\n return taxMinor === floor || (remainder !== 0n && taxMinor === floor + 1n);\n}\n\n/** Exact per-component factors relative to net; component order is significant. */\nfunction orderedFactors(components: readonly FrozenTaxComponent[]): {\n factors: DecimalRate[];\n total: DecimalRate;\n} {\n let total: DecimalRate = { numerator: 0n, denominator: 1n, value: 0 };\n const factors = components.map((component) => {\n const basis = component.compound\n ? addRates({ numerator: 1n, denominator: 1n, value: 1 }, total)\n : { numerator: 1n, denominator: 1n, value: 1 };\n const numerator = component.rate.numerator * basis.numerator;\n const denominator = component.rate.denominator * basis.denominator;\n const factor = {\n numerator,\n denominator,\n value: Number(numerator) / Number(denominator),\n };\n total = addRates(total, factor);\n return factor;\n });\n return { factors, total };\n}\n\nfunction validateFrozenComponentRates(\n components: readonly FrozenTaxComponent[],\n taxableAmount: number,\n currency: string | undefined,\n inclusive: boolean,\n label: string,\n): void {\n const taxableMinor = currencyMinor(\n taxableAmount,\n currency,\n `${label} taxable amount`,\n );\n const { factors, total } = orderedFactors(components);\n for (const [index, component] of components.entries()) {\n const factor = factors[index];\n const numerator = inclusive\n ? taxableMinor * factor.numerator * total.denominator\n : component.basisMinor * component.rate.numerator;\n const denominator = inclusive\n ? factor.denominator * (total.denominator + total.numerator)\n : component.rate.denominator;\n if (!taxMinorMatchesAllocation(component.taxMinor, numerator, denominator))\n throw new Error(\n `QuickBooks ${label} tax component rate is inconsistent with its frozen tax amount`,\n );\n }\n}\n\nfunction frozenCurrencyAmount(\n value: number,\n label: string,\n currency: string | undefined,\n allowNegative = false,\n): number {\n finite(value, label, allowNegative);\n const rounded = roundCurrencyAmount(value, currency);\n // Stored decimal money can reach JavaScript as an adjacent binary value\n // (for example 0.1 * 3). Accept that representation only when the known\n // currency round-trip differs by ordinary floating-point noise; this never\n // authorizes a real off-grid amount such as CAD 0.005 or JPY 100.5.\n if (\n !isCurrencyMinorUnit(value, currency) &&\n (rounded === undefined || !close(value, rounded))\n )\n throw new Error(\n `QuickBooks ${label} must fit the explicitly supplied currency's ISO 4217 minor-unit grid`,\n );\n return value;\n}\n\nfunction hasFrozenSnapshots(\n input: Pick<InvoiceInput, 'quickbooksMapping' | 'lineItems'>,\n): boolean {\n return (\n input.quickbooksMapping?.globalTaxCalculation === 'TaxInclusive' ||\n input.lineItems.some(\n (item) =>\n item.taxAmount !== undefined ||\n item.taxComponents !== undefined ||\n item.taxInclusiveAmount !== undefined ||\n (item.discount !== undefined && item.discount !== 0),\n )\n );\n}\n\n/** Limit accumulated binary error when a valid document has many decimal lines. */\nfunction compensatedSum(values: readonly number[]): number {\n let sum = 0;\n let compensation = 0;\n for (const value of values) {\n const adjusted = value - compensation;\n const next = sum + adjusted;\n compensation = next - sum - adjusted;\n sum = next;\n }\n return sum;\n}\n\nfunction mapDocumentLines(\n input: Pick<\n InvoiceInput,\n | 'lineItems'\n | 'subtotal'\n | 'taxAmount'\n | 'totalAmount'\n | 'currency'\n | 'quickbooksMapping'\n >,\n): { lines: QuickBooksSalesLine[]; taxLines: QuickBooksTaxLine[] } {\n const mode = input.quickbooksMapping?.globalTaxCalculation;\n if (mode && !['TaxExcluded', 'TaxInclusive', 'NotApplicable'].includes(mode))\n throw new Error(\n 'QuickBooks globalTaxCalculation must be TaxExcluded, TaxInclusive or NotApplicable',\n );\n const frozen = hasFrozenSnapshots(input);\n const validateAmount = (value: number, label: string) =>\n frozen\n ? frozenCurrencyAmount(value, label, input.currency)\n : finite(value, label);\n validateAmount(input.subtotal, 'subtotal');\n validateAmount(input.taxAmount, 'tax amount');\n validateAmount(input.totalAmount, 'total amount');\n if (input.lineItems.length === 0)\n throw new Error('QuickBooks invoices require at least one sales line');\n const hasLineMapping = input.lineItems.some((item) => item.quickbooksMapping);\n if ((input.taxAmount > 0 || hasLineMapping) && !input.quickbooksMapping)\n throw new Error(\n 'QuickBooks mapped or nonzero-tax invoices require explicit globalTaxCalculation',\n );\n if (\n input.quickbooksMapping &&\n input.lineItems.some((item) => !item.quickbooksMapping)\n )\n throw new Error(\n 'QuickBooks mapped invoices require itemRef and taxCodeRef on every line',\n );\n if (input.taxAmount > 0 && mode === 'NotApplicable')\n throw new Error(\n 'QuickBooks nonzero tax cannot use NotApplicable global tax calculation',\n );\n\n const mapped: QuickBooksSalesLine[] = [];\n const taxLines = new Map<\n string,\n {\n rate: DecimalRate;\n amountMinor: bigint;\n basisMinor: bigint;\n explicitBasis: boolean;\n }\n >();\n const snapshotLineTaxes: number[] = [];\n let hasAnyLineTax = false;\n let hasCompleteLineTax = true;\n const lineTaxSnapshots: Array<{\n taxAmount: number | undefined;\n taxComponents: readonly FrozenTaxComponent[];\n }> = [];\n for (const [index, item] of input.lineItems.entries()) {\n const line = mapLine(item, index, input.currency, mode, frozen);\n mapped.push(...line.lines);\n lineTaxSnapshots.push({\n taxAmount: line.taxAmount,\n taxComponents: line.taxComponents,\n });\n if (line.taxAmount === undefined) hasCompleteLineTax = false;\n else {\n hasAnyLineTax = true;\n snapshotLineTaxes.push(line.taxAmount);\n }\n for (const component of line.taxComponents) {\n const existing = taxLines.get(component.taxRateRef);\n if (existing) {\n if (!ratesEqual(existing.rate, component.rate))\n throw new Error(\n `QuickBooks tax rate ${component.taxRateRef} has inconsistent frozen rates`,\n );\n existing.amountMinor += component.taxMinor;\n existing.basisMinor += component.basisMinor;\n existing.explicitBasis ||= component.explicitBasis;\n if (\n existing.explicitBasis &&\n !Number.isSafeInteger(Number(existing.basisMinor))\n )\n throw new Error(\n 'QuickBooks aggregate taxable basis exceeds safe minor units',\n );\n } else {\n taxLines.set(component.taxRateRef, {\n rate: component.rate,\n amountMinor: component.taxMinor,\n basisMinor: component.basisMinor,\n explicitBasis: component.explicitBasis,\n });\n }\n }\n }\n const mappedSubtotal = compensatedSum(mapped.map((line) => line.Amount));\n if (!close(mappedSubtotal, input.subtotal))\n throw new Error('QuickBooks line amounts must equal the invoice subtotal');\n if (!close(input.subtotal + input.taxAmount, input.totalAmount))\n throw new Error(\n 'QuickBooks subtotal plus tax must equal the invoice total',\n );\n if (taxLines.size > 0) {\n if (\n lineTaxSnapshots.some(\n (line) =>\n line.taxAmount === undefined ||\n (line.taxAmount > 0 && line.taxComponents.length === 0),\n )\n )\n throw new Error(\n 'QuickBooks component tax detail requires components on every taxed line',\n );\n const totalTaxMinor = currencyMinor(\n input.taxAmount,\n input.currency,\n 'tax amount',\n );\n const detailTaxMinor = [...taxLines.values()].reduce(\n (sum, line) => sum + line.amountMinor,\n 0n,\n );\n if (detailTaxMinor !== totalTaxMinor)\n throw new Error(\n 'QuickBooks component tax detail must equal the invoice tax amount',\n );\n }\n if (hasAnyLineTax && !hasCompleteLineTax)\n throw new Error(\n 'QuickBooks stored line tax must be supplied on every line when any line supplies it',\n );\n if (\n hasAnyLineTax &&\n !close(compensatedSum(snapshotLineTaxes), input.taxAmount)\n )\n throw new Error(\n 'QuickBooks stored line tax must equal the invoice tax amount',\n );\n return {\n lines: mapped,\n taxLines: [...taxLines.entries()].map(([taxRateRef, detail]) => ({\n Amount: currencyMajor(detail.amountMinor, input.currency),\n DetailType: 'TaxLineDetail',\n TaxLineDetail: {\n TaxRateRef: { value: taxRateRef },\n TaxPercent: taxPercent(detail.rate),\n PercentBased: true,\n ...(detail.explicitBasis\n ? {\n NetAmountTaxable: currencyMajor(\n detail.basisMinor,\n input.currency,\n ),\n }\n : {}),\n },\n })),\n };\n}\n\nfunction mapLine(\n item: InvoiceLineItemInput,\n index: number,\n currency: string | undefined,\n mode: 'TaxExcluded' | 'TaxInclusive' | 'NotApplicable' | undefined,\n enforceCurrencyGrid: boolean,\n): {\n lines: QuickBooksSalesLine[];\n taxAmount?: number;\n taxComponents: FrozenTaxComponent[];\n} {\n const label = `line ${index + 1}`;\n if (item.taxRate !== undefined && item.taxRate !== 0)\n throw new Error(\n 'QuickBooks numeric taxRate is not supported; use a realm taxCodeRef',\n );\n if (item.taxCode !== undefined)\n throw new Error(\n 'QuickBooks generic taxCode is not a realm tax reference; use quickbooksMapping.taxCodeRef',\n );\n finite(item.quantity, `${label} quantity`);\n if (item.quantity <= 0)\n throw new Error(`QuickBooks ${label} quantity must be greater than zero`);\n finite(item.unitPrice, `${label} unit price`);\n const baseDocumentAmount = item.quantity * item.unitPrice;\n finite(baseDocumentAmount, `${label} pre-discount amount`);\n const validateAmount = (\n value: number,\n amountLabel: string,\n allowNegative = false,\n ) =>\n enforceCurrencyGrid\n ? frozenCurrencyAmount(value, amountLabel, currency, allowNegative)\n : finite(value, amountLabel, allowNegative);\n const discount = validateAmount(item.discount ?? 0, `${label} discount`);\n if (discount > baseDocumentAmount && !close(discount, baseDocumentAmount))\n throw new Error(\n `QuickBooks ${label} discount cannot exceed quantity times unit price`,\n );\n const netAmount = validateAmount(\n item.amount ?? baseDocumentAmount - discount,\n `${label} amount`,\n );\n const taxAmount =\n item.taxAmount === undefined\n ? undefined\n : validateAmount(item.taxAmount, `${label} tax amount`);\n const taxComponents: FrozenTaxComponent[] = [];\n const componentIds = new Set<string>();\n const componentRateRefs = new Set<string>();\n if (item.taxComponents !== undefined) {\n if (taxAmount === undefined)\n throw new Error(\n `QuickBooks ${label} tax components require a line tax amount`,\n );\n const componentTax = item.taxComponents.reduce(\n (sum, component, componentIndex) => {\n if (\n !component ||\n typeof component !== 'object' ||\n Object.keys(component).some(\n (key) =>\n ![\n 'taxCode',\n 'rate',\n 'quickbooksTaxRateRef',\n 'taxAmount',\n 'compound',\n 'taxableAmount',\n ].includes(key),\n )\n )\n throw new Error(\n `QuickBooks ${label} tax component has unsupported fields`,\n );\n if (\n component.compound !== undefined &&\n typeof component.compound !== 'boolean'\n )\n throw new Error(`QuickBooks ${label} compound must be boolean`);\n if (component.compound && component.taxableAmount === undefined)\n throw new Error(\n `QuickBooks ${label} compound tax requires its frozen taxableAmount`,\n );\n if (\n !component.taxCode ||\n component.taxCode.trim() !== component.taxCode\n )\n throw new Error(\n `QuickBooks ${label} tax component ${componentIndex + 1} needs a tax code`,\n );\n const rate = decimalRate(\n component.rate,\n `${label} tax component ${componentIndex + 1}`,\n );\n const taxRateRef = reference(\n component.quickbooksTaxRateRef,\n `${label} tax component ${componentIndex + 1} quickbooksTaxRateRef`,\n ).value;\n const componentAmount = validateAmount(\n component.taxAmount,\n `${label} tax component ${componentIndex + 1}`,\n );\n if (\n componentIds.has(component.taxCode) ||\n componentRateRefs.has(taxRateRef)\n )\n throw new Error(\n `QuickBooks ${label} repeats a tax component or rate reference`,\n );\n componentIds.add(component.taxCode);\n componentRateRefs.add(taxRateRef);\n const expectedBasis =\n currencyMinor(netAmount, currency, `${label} net amount`) +\n (component.compound\n ? taxComponents.reduce((sum, prior) => sum + prior.taxMinor, 0n)\n : 0n);\n const basisMinor =\n component.taxableAmount === undefined\n ? expectedBasis\n : currencyMinor(\n validateAmount(\n component.taxableAmount,\n `${label} taxable basis`,\n ),\n currency,\n `${label} taxable basis`,\n );\n if (!Number.isSafeInteger(Number(basisMinor)))\n throw new Error(\n `QuickBooks ${label} taxable basis exceeds safe minor units`,\n );\n if (basisMinor !== expectedBasis)\n throw new Error(\n `QuickBooks ${label} frozen taxable basis does not match its ordered components`,\n );\n taxComponents.push({\n taxRateRef,\n rate,\n compound: component.compound ?? false,\n basisMinor,\n explicitBasis: component.taxableAmount !== undefined,\n taxMinor: currencyMinor(\n componentAmount,\n currency,\n `${label} tax component ${componentIndex + 1}`,\n ),\n });\n return sum + componentAmount;\n },\n 0,\n );\n if (!close(componentTax, taxAmount))\n throw new Error(\n `QuickBooks ${label} tax components must equal the line tax amount`,\n );\n }\n\n const inclusive = mode === 'TaxInclusive';\n const grossAmount = item.taxInclusiveAmount;\n if (!inclusive && grossAmount !== undefined)\n throw new Error(\n `QuickBooks ${label} tax-inclusive amount requires TaxInclusive global tax calculation`,\n );\n if (inclusive) {\n if (\n grossAmount === undefined ||\n taxAmount === undefined ||\n (taxAmount > 0 && !item.taxComponents?.length)\n )\n throw new Error(\n `QuickBooks ${label} TaxInclusive snapshots require gross amount, line tax and tax components for nonzero tax`,\n );\n validateAmount(grossAmount, `${label} tax-inclusive amount`);\n if (!close(netAmount + taxAmount, grossAmount))\n throw new Error(\n `QuickBooks ${label} net amount plus tax must equal gross amount`,\n );\n if (!close(baseDocumentAmount - discount, grossAmount))\n throw new Error(\n `QuickBooks ${label} gross amount must equal quantity times gross unit price less gross discount`,\n );\n } else if (\n !close(netAmount, baseDocumentAmount - discount) &&\n !matchesCurrencyRoundedLineAmount(\n item.quantity,\n item.unitPrice,\n netAmount + discount,\n currency,\n )\n ) {\n throw new Error(\n `QuickBooks ${label} amount must equal quantity times unit price less discount`,\n );\n }\n const mappedComponents = item.quickbooksMapping?.taxComponents;\n if (\n taxComponents.some((component) => component.compound) &&\n mappedComponents === undefined\n )\n throw new Error(\n `QuickBooks ${label} compound tax requires caller-verified ordered tax-code mapping`,\n );\n if (mappedComponents !== undefined) {\n if (\n !Array.isArray(mappedComponents) ||\n mappedComponents.length !== taxComponents.length\n )\n throw new Error(\n `QuickBooks ${label} ordered tax-code mapping must match every frozen component`,\n );\n const refs = new Set<string>();\n for (const [position, mapped] of mappedComponents.entries()) {\n if (\n !mapped ||\n typeof mapped !== 'object' ||\n Object.keys(mapped).some(\n (key) => !['taxRateRef', 'compound'].includes(key),\n ) ||\n typeof mapped.compound !== 'boolean'\n )\n throw new Error(\n `QuickBooks ${label} ordered tax-code mapping has unknown order metadata`,\n );\n const ref = reference(\n mapped.taxRateRef,\n `${label} mapped tax rate`,\n ).value;\n const component = taxComponents[position];\n if (\n refs.has(ref) ||\n ref !== component.taxRateRef ||\n mapped.compound !== component.compound\n )\n throw new Error(\n `QuickBooks ${label} ordered tax-code mapping does not match frozen components`,\n );\n refs.add(ref);\n }\n }\n if (taxComponents.length > 0)\n validateFrozenComponentRates(\n taxComponents,\n inclusive ? (grossAmount as number) : netAmount,\n currency,\n inclusive,\n label,\n );\n\n const itemRef = item.quickbooksMapping\n ? reference(item.quickbooksMapping.itemRef, `${label} itemRef`)\n : undefined;\n const taxCodeRef = item.quickbooksMapping\n ? reference(item.quickbooksMapping.taxCodeRef, `${label} taxCodeRef`)\n : undefined;\n const line = (\n amount: number,\n quantity: number,\n unitPrice: number,\n description: string,\n taxInclusiveAmount?: number,\n ) => ({\n LineNum: index + 1,\n Description: description,\n Amount: amount,\n DetailType: 'SalesItemLineDetail' as const,\n SalesItemLineDetail: {\n Qty: quantity,\n UnitPrice: unitPrice,\n ItemRef: itemRef,\n TaxCodeRef: taxCodeRef,\n ...(taxInclusiveAmount === undefined\n ? {}\n : { TaxInclusiveAmt: taxInclusiveAmount }),\n },\n });\n\n if (discount === 0 && !inclusive) {\n return {\n lines: [line(netAmount, item.quantity, item.unitPrice, item.description)],\n taxAmount,\n taxComponents,\n };\n }\n if (\n discount === 0 ||\n isCurrencyMinorUnit(netAmount / item.quantity, currency)\n ) {\n return {\n lines: [\n line(\n netAmount,\n item.quantity,\n netAmount / item.quantity,\n item.description,\n inclusive ? grossAmount : undefined,\n ),\n ],\n taxAmount,\n taxComponents,\n };\n }\n\n let preDiscountAmount = netAmount + discount;\n let negativeAmount = -discount;\n const preDiscountGross = inclusive ? baseDocumentAmount : undefined;\n if (inclusive) {\n const components = item.taxComponents;\n const exemptSnapshot = taxAmount === 0 && !components?.length;\n if (!components?.length && !exemptSnapshot)\n throw new Error(\n `QuickBooks ${label} needs frozen component rates for an inclusive negative discount line`,\n );\n const rate = exemptSnapshot\n ? 0\n : (components ?? []).reduce(\n (sum, component, componentIndex) =>\n sum +\n decimalRate(\n component.rate,\n `${label} tax component ${componentIndex + 1}`,\n ).value,\n 0,\n );\n let discountNet = roundCurrencyAmount(discount / (1 + rate), currency);\n if (taxComponents.some((component) => component.compound)) {\n const { total } = orderedFactors(taxComponents);\n const numerator =\n currencyMinor(discount, currency, `${label} discount`) *\n total.denominator;\n const denominator = total.denominator + total.numerator;\n discountNet = currencyMajor(\n (2n * numerator + denominator) / (2n * denominator),\n currency,\n );\n }\n if (discountNet === undefined)\n throw new Error(\n `QuickBooks ${label} needs a recognized currency to map an inclusive fractional-unit discount`,\n );\n preDiscountAmount = netAmount + discountNet;\n negativeAmount = -discountNet;\n }\n if (enforceCurrencyGrid) {\n frozenCurrencyAmount(\n preDiscountAmount,\n `${label} generated pre-discount amount`,\n currency,\n );\n frozenCurrencyAmount(\n negativeAmount,\n `${label} generated discount amount`,\n currency,\n true,\n );\n }\n let negativeGross: number | undefined;\n if (inclusive) {\n if (grossAmount === undefined || preDiscountGross === undefined)\n throw new Error(\n `QuickBooks ${label} needs frozen gross amounts for an inclusive negative discount line`,\n );\n const unroundedNegativeGross = grossAmount - preDiscountGross;\n negativeGross =\n roundCurrencyAmount(unroundedNegativeGross, currency) ??\n unroundedNegativeGross;\n }\n if (enforceCurrencyGrid && negativeGross !== undefined) {\n frozenCurrencyAmount(\n negativeGross,\n `${label} generated gross discount amount`,\n currency,\n true,\n );\n }\n return {\n lines: [\n line(\n preDiscountAmount,\n item.quantity,\n preDiscountAmount / item.quantity,\n item.description,\n preDiscountGross,\n ),\n line(\n negativeAmount,\n 1,\n negativeAmount,\n `Discount on line ${index + 1}`,\n negativeGross,\n ),\n ],\n taxAmount,\n taxComponents,\n };\n}\n\nfunction basePayload(\n input: Pick<\n InvoiceInput,\n | 'customerId'\n | 'customerExternalId'\n | 'issueDate'\n | 'subtotal'\n | 'taxAmount'\n | 'totalAmount'\n | 'currency'\n | 'memo'\n | 'lineItems'\n | 'quickbooksMapping'\n >,\n number: string,\n dueDate?: Date,\n) {\n const { lines, taxLines } = mapDocumentLines(input);\n return {\n CustomerRef: { value: input.customerExternalId || input.customerId },\n DocNumber: number,\n TxnDate: formatLocalDate(input.issueDate),\n ...(dueDate ? { DueDate: formatLocalDate(dueDate) } : {}),\n Line: lines,\n GlobalTaxCalculation: input.quickbooksMapping?.globalTaxCalculation,\n TxnTaxDetail: input.quickbooksMapping\n ? {\n TotalTax: input.taxAmount,\n ...(taxLines.length > 0 ? { TaxLine: taxLines } : {}),\n }\n : undefined,\n CurrencyRef: input.currency ? { value: input.currency } : undefined,\n CustomerMemo: input.memo ? { value: input.memo } : undefined,\n };\n}\n\nexport function mapInvoiceToQBO(invoice: InvoiceInput) {\n if (invoice.collectionMethod === 'charge_automatically')\n throw new Error(\n 'QuickBooks does not support charge_automatically invoice collection',\n );\n if (invoice.automaticTax)\n throw new Error(\n 'QuickBooks does not support automaticTax invoice calculation',\n );\n return basePayload(\n invoice,\n invoice.invoiceNumber,\n invoice.dueDate,\n ) as ReturnType<typeof basePayload> & { DueDate: string };\n}\n\nexport function mapCreditMemoToQBO(creditMemo: CreditMemoInput) {\n if (\n !creditMemo.creditedInvoiceExternalId ||\n creditMemo.creditedInvoiceExternalId.trim() !==\n creditMemo.creditedInvoiceExternalId\n )\n throw new Error(\n 'QuickBooks credit memos require a credited invoice external ID',\n );\n return basePayload(creditMemo, creditMemo.creditMemoNumber);\n}\n"],"mappings":";;AAcA,IAAM,oBAAoB,IAAI,IAC5B;CATA,CAAC,GAAG,qEAAqE;CACzE,CACE,GACA,6iBACF;CACA,CAAC,GAAG,6BAA6B;CACjC,CAAC,GAAG,SAAS;AAGb,CAAA,CAAgB,SAAS,CAAC,WAAW,WACnC,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,SAAS,CAAC,MAAM,SAAS,CAAU,CAC3D,CACF;;AAGA,SAAgB,wBACd,UACoB;CAC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KAAA;EAC1D,cAAc,MAAM,OAAO,EAAE,OAAO,MAAM,KAAK,IAAI,KAAA;CACrD;AACF;AAEA,SAAgB,gBAAgB,SAAuB;CACrD,IAAI,QAAQ,qBAAqB,wBAC/B,MAAM,IAAI,MACR,qEACF;CACF,IAAI,QAAQ,cACV,MAAM,IAAI,MACR,8DACF;CACF,OAAO,YACL,SACA,QAAQ,eACR,QAAQ,OACV;AACF;AAEA,SAAgB,mBAAmB,YAA6B;CAC9D,IACE,CAAC,WAAW,6BACZ,WAAW,0BAA0B,KAAK,MACxC,WAAW,2BAEb,MAAM,IAAI,MACR,gEACF;CACF,OAAO,YAAY,YAAY,WAAW,gBAAgB;AAC5D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"quickbooks-CIedOmSC.js","names":[],"sources":["../../src/providers/quickbooks/index.ts"],"sourcesContent":["/**\n * QuickBooks Online Provider\n *\n * Implements the AccountingProvider interface for QuickBooks Online.\n * Uses the Intuit OAuth2 library for authentication and the QBO API for operations.\n */\n\n/// <reference path=\"../../intuit-oauth.d.ts\" />\n\nimport { createHmac } from 'node:crypto';\nimport { QuickBooksWriteError } from '../../errors.js';\nimport type {\n AccountingProvider,\n Address,\n AuditDiscrepancy,\n AuditMatch,\n AuditOperations,\n AuditReport,\n BillInput,\n BillOperations,\n CreditMemoInput,\n CreditMemoOperations,\n CustomerInput,\n CustomerOperations,\n DateRange,\n ExternalBill,\n ExternalCustomer,\n ExternalInvoice,\n ExternalPayment,\n ExternalRecord,\n ExternalVendor,\n FieldDiff,\n InvoiceInput,\n InvoiceOperations,\n ListOptions,\n PaymentInput,\n PaymentOperations,\n QuickBooksCreditMemoRequest,\n QuickBooksInvoiceRequest,\n QuickBooksOptions,\n SyncResult,\n TokenSet,\n VendorInput,\n VendorOperations,\n WebhookEvent,\n WebhookOperations,\n} from '../../types.js';\nimport {\n mapCreditMemoToQBO,\n mapInvoiceToQBO,\n validateQuickBooksCreditMemoRequest,\n validateQuickBooksInvoiceRequest,\n} from './invoice-request.js';\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Format a Date to YYYY-MM-DD in local timezone (not UTC)\n * This prevents timezone conversion issues where dates shift by a day\n */\nfunction formatLocalDate(date: Date): string {\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const day = String(date.getDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n}\n\n/**\n * Sleep for a given number of milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Compare two values for equality (handles dates, objects, etc.)\n */\nfunction valuesEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n if (typeof a === 'number' && typeof b === 'number') {\n // Allow for floating point precision issues\n return Math.abs(a - b) < 0.01;\n }\n return false;\n}\n\n// =============================================================================\n// QuickBooks Provider\n// =============================================================================\n\n/**\n * QuickBooks Online accounting provider\n */\nexport class QuickBooksProvider implements AccountingProvider {\n readonly type = 'quickbooks' as const;\n\n private options: QuickBooksOptions;\n private accessToken: string | null = null;\n private tokenExpiresAt: Date | null = null;\n\n readonly customers: CustomerOperations;\n readonly invoices: InvoiceOperations;\n readonly creditMemos: CreditMemoOperations;\n readonly vendors: VendorOperations;\n readonly bills: BillOperations;\n readonly payments: PaymentOperations;\n readonly audit: AuditOperations;\n readonly webhooks: WebhookOperations;\n\n constructor(options: QuickBooksOptions) {\n this.options = {\n timeout: 30000,\n maxRetries: 3,\n ...options,\n };\n\n // Initialize operation handlers\n this.customers = new QuickBooksCustomerOperations(this);\n this.invoices = new QuickBooksInvoiceOperations(this);\n this.creditMemos = new QuickBooksCreditMemoOperations(this);\n this.vendors = new QuickBooksVendorOperations(this);\n this.bills = new QuickBooksBillOperations(this);\n this.payments = new QuickBooksPaymentOperations(this);\n this.audit = new QuickBooksAuditOperations(this);\n this.webhooks = new QuickBooksWebhookOperations(this.options);\n }\n\n /**\n * Get the QBO API base URL\n */\n get baseUrl(): string {\n return this.options.environment === 'production'\n ? 'https://quickbooks.api.intuit.com'\n : 'https://sandbox-quickbooks.api.intuit.com';\n }\n\n /**\n * Get the company/realm ID\n */\n get realmId(): string {\n return this.options.realmId;\n }\n\n /**\n * Ensure we have a valid access token, refreshing if needed\n */\n async ensureAccessToken(): Promise<string> {\n // Check if current token is still valid (with 5 min buffer)\n if (this.accessToken && this.tokenExpiresAt) {\n const bufferMs = 5 * 60 * 1000;\n if (new Date().getTime() < this.tokenExpiresAt.getTime() - bufferMs) {\n return this.accessToken;\n }\n }\n\n // Refresh the token\n const tokens = await this.refreshAccessToken();\n this.accessToken = tokens.accessToken;\n this.tokenExpiresAt = tokens.expiresAt;\n\n // Update stored refresh token so subsequent refreshes use the new token\n this.options.refreshToken = tokens.refreshToken;\n\n // Notify callback if provided\n if (this.options.onTokenRefresh) {\n await this.options.onTokenRefresh(tokens);\n }\n\n return this.accessToken;\n }\n\n /**\n * Refresh the OAuth access token\n */\n private async refreshAccessToken(): Promise<TokenSet> {\n // Import intuit-oauth dynamically\n const OAuthClient = (await import('intuit-oauth')).default;\n\n const redirectUri =\n this.options.redirectUri ||\n 'https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl';\n\n const oauthClient = new OAuthClient({\n clientId: this.options.clientId,\n clientSecret: this.options.clientSecret,\n environment:\n this.options.environment === 'production' ? 'production' : 'sandbox',\n redirectUri,\n });\n\n oauthClient.setToken({\n refresh_token: this.options.refreshToken,\n access_token: this.accessToken || '',\n });\n\n const response = await oauthClient.refresh();\n const token = response.getJson();\n\n return {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresAt: new Date(Date.now() + token.expires_in * 1000),\n tokenType: token.token_type,\n };\n }\n\n /**\n * Make an authenticated request to the QBO API with timeout and retry support\n */\n async request<T>(\n method: 'GET' | 'POST' | 'DELETE',\n endpoint: string,\n body?: unknown,\n createRequest?: QuickBooksInvoiceRequest | QuickBooksCreditMemoRequest,\n ): Promise<T> {\n // Freeze identity and bytes before any asynchronous work.\n const serializedBody =\n body === undefined ? undefined : JSON.stringify(body);\n const realmId = this.realmId;\n const environment =\n this.options.environment === 'production' ? 'production' : 'sandbox';\n if (createRequest) {\n if (method !== 'POST' || !['invoice', 'creditmemo'].includes(endpoint)) {\n throw new Error(\n 'QuickBooks request identity is only supported for invoice or credit memo creation',\n );\n }\n if (endpoint === 'invoice')\n validateQuickBooksInvoiceRequest(\n createRequest as QuickBooksInvoiceRequest,\n realmId,\n environment,\n serializedBody,\n );\n else\n validateQuickBooksCreditMemoRequest(\n createRequest as QuickBooksCreditMemoRequest,\n realmId,\n environment,\n serializedBody,\n );\n }\n const requestId = createRequest?.requestId;\n const payloadHash = createRequest?.payloadHash;\n const url = new URL(`${this.baseUrl}/v3/company/${realmId}/${endpoint}`);\n if (requestId) url.searchParams.set('requestid', requestId);\n const timeout = this.options.timeout ?? 30000;\n const maxRetries =\n method === 'GET' || requestId ? (this.options.maxRetries ?? 3) : 0;\n const responseEntity = [\n 'Customer',\n 'Vendor',\n 'Bill',\n 'Invoice',\n 'CreditMemo',\n 'Payment',\n ].find((entity) => entity.toLowerCase() === endpoint.split(/[/?]/, 1)[0]);\n const accessToken = await this.ensureAccessToken();\n // A persisted identity may have been sent by an earlier worker. Without a\n // durable attempt history, even its first observed 4xx cannot prove that\n // the logical write was never accepted. Fail closed across process retries.\n let uncertain = requestId !== undefined;\n\n for (let attempt = 0; ; attempt++) {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n let status: number | undefined;\n let failure: unknown;\n try {\n const response = await fetch(url.toString(), {\n method,\n headers: {\n Authorization: `Bearer ${accessToken}`,\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: serializedBody,\n signal: controller.signal,\n });\n status = response.status;\n if (!response.ok) {\n throw new Error(\n `QBO API error (${status}): ${await response.text()}`,\n );\n }\n const result = await response.json();\n // Every supported write must return a usable remote identity. Validate\n // inside this boundary so malformed successes cannot escape reconciliation.\n if (\n method !== 'GET' &&\n responseEntity &&\n (typeof result?.[responseEntity]?.Id !== 'string' ||\n !result[responseEntity].Id.trim())\n ) {\n throw new Error(`QBO response is missing ${responseEntity}.Id`);\n }\n return result as T;\n } catch (error) {\n failure = error;\n uncertain ||=\n status === undefined ||\n status >= 500 ||\n (status >= 200 && status < 300);\n } finally {\n clearTimeout(timeoutId);\n }\n const retryable =\n status === undefined ||\n status === 429 ||\n status >= 500 ||\n (status >= 200 && status < 300);\n if (!retryable || attempt >= maxRetries) {\n if (method !== 'GET') {\n throw new QuickBooksWriteError({\n realmId,\n environment,\n endpoint,\n requestId,\n status,\n payloadHash,\n outcome: uncertain ? 'unknown' : 'rejected',\n cause: failure,\n });\n }\n throw failure;\n }\n await sleep(2 ** attempt * 1000);\n }\n }\n\n /**\n * Execute a QBO query with pagination support\n */\n async queryAll<T>(\n entity: string,\n whereClause?: string,\n maxResults = 1000,\n ): Promise<T[]> {\n const results: T[] = [];\n let startPosition = 1;\n const pageSize = 100; // QBO max is 1000, but smaller pages are safer\n\n while (results.length < maxResults) {\n let query = `SELECT * FROM ${entity}`;\n if (whereClause) {\n query += ` WHERE ${whereClause}`;\n }\n query += ` MAXRESULTS ${pageSize} STARTPOSITION ${startPosition}`;\n\n const response = await this.request<{\n QueryResponse: Record<string, T[] | undefined>;\n }>('GET', `query?query=${encodeURIComponent(query)}`);\n\n const items = response.QueryResponse[entity] || [];\n results.push(...items);\n\n // If we got fewer than pageSize, we've reached the end\n if (items.length < pageSize) {\n break;\n }\n\n startPosition += pageSize;\n }\n\n return results;\n }\n}\n\n// =============================================================================\n// Customer Operations\n// =============================================================================\n\nclass QuickBooksCustomerOperations implements CustomerOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async push(customer: CustomerInput): Promise<SyncResult> {\n const qboCustomer = mapCustomerToQBO(customer);\n\n const response = await this.provider.request<{ Customer: QBOCustomer }>(\n 'POST',\n 'customer',\n qboCustomer,\n );\n\n return {\n action: 'created',\n externalId: response.Customer.Id,\n syncedAt: new Date(),\n };\n }\n\n async pull(externalId: string): Promise<ExternalCustomer> {\n const response = await this.provider.request<{ Customer: QBOCustomer }>(\n 'GET',\n `customer/${externalId}`,\n );\n\n return mapQBOToCustomer(response.Customer);\n }\n\n async list(options?: ListOptions): Promise<ExternalCustomer[]> {\n const limit = options?.limit || 1000;\n const customers = await this.provider.queryAll<QBOCustomer>(\n 'Customer',\n undefined,\n limit,\n );\n return customers.map(mapQBOToCustomer);\n }\n\n async sync(customer: CustomerInput): Promise<SyncResult> {\n if (customer.externalId) {\n // Update existing\n const existing = await this.provider.request<{ Customer: QBOCustomer }>(\n 'GET',\n `customer/${customer.externalId}`,\n );\n\n const qboCustomer: QBOCustomerUpdate = {\n ...mapCustomerToQBO(customer),\n Id: customer.externalId,\n SyncToken: existing.Customer.SyncToken,\n };\n\n await this.provider.request('POST', 'customer', qboCustomer);\n\n return {\n action: 'updated',\n externalId: customer.externalId,\n syncedAt: new Date(),\n };\n }\n\n return this.push(customer);\n }\n}\n\n// =============================================================================\n// Invoice Operations\n// =============================================================================\n\nclass QuickBooksInvoiceOperations implements InvoiceOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async push(invoice: InvoiceInput): Promise<SyncResult> {\n if (invoice.externalId && invoice.quickbooksRequest)\n throw new Error(\n 'QuickBooks invoice request identity cannot be used for updates',\n );\n const qboInvoice = mapInvoiceToQBO(invoice);\n\n const response = await this.provider.request<{ Invoice: QBOInvoice }>(\n 'POST',\n 'invoice',\n qboInvoice,\n invoice.quickbooksRequest,\n );\n\n return {\n action: 'created',\n externalId: response.Invoice.Id,\n syncedAt: new Date(),\n };\n }\n\n async pull(externalId: string): Promise<ExternalInvoice> {\n const response = await this.provider.request<{ Invoice: QBOInvoice }>(\n 'GET',\n `invoice/${externalId}`,\n );\n\n return mapQBOToInvoice(response.Invoice);\n }\n\n async list(options?: ListOptions): Promise<ExternalInvoice[]> {\n const limit = options?.limit || 1000;\n let whereClause: string | undefined;\n\n if (options?.startDate) {\n whereClause = `TxnDate >= '${formatLocalDate(options.startDate)}'`;\n if (options?.endDate) {\n whereClause += ` AND TxnDate <= '${formatLocalDate(options.endDate)}'`;\n }\n }\n\n const invoices = await this.provider.queryAll<QBOInvoice>(\n 'Invoice',\n whereClause,\n limit,\n );\n return invoices.map(mapQBOToInvoice);\n }\n\n async sync(invoice: InvoiceInput): Promise<SyncResult> {\n if (invoice.externalId) {\n if (invoice.quickbooksRequest)\n throw new Error(\n 'QuickBooks invoice request identity cannot be used for updates',\n );\n const existing = await this.provider.request<{ Invoice: QBOInvoice }>(\n 'GET',\n `invoice/${invoice.externalId}`,\n );\n\n const qboInvoice: QBOInvoiceUpdate = {\n ...mapInvoiceToQBO(invoice),\n Id: invoice.externalId,\n SyncToken: existing.Invoice.SyncToken,\n };\n\n await this.provider.request('POST', 'invoice', qboInvoice);\n\n return {\n action: 'updated',\n externalId: invoice.externalId,\n syncedAt: new Date(),\n };\n }\n\n return this.push(invoice);\n }\n\n async send(externalId: string): Promise<void> {\n await this.provider.request('POST', `invoice/${externalId}/send`);\n }\n\n async void(externalId: string): Promise<void> {\n const existing = await this.provider.request<{ Invoice: QBOInvoice }>(\n 'GET',\n `invoice/${externalId}`,\n );\n\n await this.provider.request('POST', 'invoice', {\n Id: externalId,\n SyncToken: existing.Invoice.SyncToken,\n sparse: true,\n // QBO doesn't have a Void field - you delete the invoice instead\n // or create a credit memo. For now, we'll use sparse update to mark private note\n PrivateNote: 'VOIDED',\n });\n }\n}\n\n// =============================================================================\n// Credit memo operations\n// =============================================================================\n\nclass QuickBooksCreditMemoOperations implements CreditMemoOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async push(creditMemo: CreditMemoInput): Promise<SyncResult> {\n if (creditMemo.externalId && creditMemo.quickbooksCreditMemoRequest)\n throw new Error(\n 'QuickBooks credit memo request identity cannot be used for updates',\n );\n const mapped = mapCreditMemoToQBO(creditMemo);\n if (\n creditMemo.quickbooksCreditMemoRequest &&\n creditMemo.quickbooksCreditMemoRequest.creditedInvoiceExternalId !==\n creditMemo.creditedInvoiceExternalId\n )\n throw new Error(\n 'QuickBooks credit memo request linkage mismatch; reconcile the original request',\n );\n const response = await this.provider.request<{\n CreditMemo: { Id: string };\n }>('POST', 'creditmemo', mapped, creditMemo.quickbooksCreditMemoRequest);\n return {\n action: 'created',\n externalId: response.CreditMemo.Id,\n syncedAt: new Date(),\n };\n }\n\n async sync(creditMemo: CreditMemoInput): Promise<SyncResult> {\n if (!creditMemo.externalId) return this.push(creditMemo);\n if (creditMemo.quickbooksCreditMemoRequest)\n throw new Error(\n 'QuickBooks credit memo request identity cannot be used for updates',\n );\n // Refuse malformed frozen snapshots before authenticating or contacting QBO.\n const mapped = mapCreditMemoToQBO(creditMemo);\n const existing = await this.provider.request<{\n CreditMemo: { SyncToken: string };\n }>('GET', `creditmemo/${creditMemo.externalId}`);\n await this.provider.request('POST', 'creditmemo', {\n ...mapped,\n Id: creditMemo.externalId,\n SyncToken: existing.CreditMemo.SyncToken,\n });\n return {\n action: 'updated',\n externalId: creditMemo.externalId,\n syncedAt: new Date(),\n };\n }\n}\n\n// =============================================================================\n// Vendor Operations\n// =============================================================================\n\nclass QuickBooksVendorOperations implements VendorOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async push(vendor: VendorInput): Promise<SyncResult> {\n const qboVendor = mapVendorToQBO(vendor);\n\n const response = await this.provider.request<{ Vendor: QBOVendor }>(\n 'POST',\n 'vendor',\n qboVendor,\n );\n\n return {\n action: 'created',\n externalId: response.Vendor.Id,\n syncedAt: new Date(),\n };\n }\n\n async pull(externalId: string): Promise<ExternalVendor> {\n const response = await this.provider.request<{ Vendor: QBOVendor }>(\n 'GET',\n `vendor/${externalId}`,\n );\n\n return mapQBOToVendor(response.Vendor);\n }\n\n async list(options?: ListOptions): Promise<ExternalVendor[]> {\n const limit = options?.limit || 1000;\n const vendors = await this.provider.queryAll<QBOVendor>(\n 'Vendor',\n undefined,\n limit,\n );\n return vendors.map(mapQBOToVendor);\n }\n\n async sync(vendor: VendorInput): Promise<SyncResult> {\n if (vendor.externalId) {\n const existing = await this.provider.request<{ Vendor: QBOVendor }>(\n 'GET',\n `vendor/${vendor.externalId}`,\n );\n\n const qboVendor: QBOVendorUpdate = {\n ...mapVendorToQBO(vendor),\n Id: vendor.externalId,\n SyncToken: existing.Vendor.SyncToken,\n };\n\n await this.provider.request('POST', 'vendor', qboVendor);\n\n return {\n action: 'updated',\n externalId: vendor.externalId,\n syncedAt: new Date(),\n };\n }\n\n return this.push(vendor);\n }\n}\n\n// =============================================================================\n// Bill Operations\n// =============================================================================\n\nclass QuickBooksBillOperations implements BillOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async push(bill: BillInput): Promise<SyncResult> {\n const qboBill = mapBillToQBO(bill);\n\n const response = await this.provider.request<{ Bill: QBOBill }>(\n 'POST',\n 'bill',\n qboBill,\n );\n\n return {\n action: 'created',\n externalId: response.Bill.Id,\n syncedAt: new Date(),\n };\n }\n\n async pull(externalId: string): Promise<ExternalBill> {\n const response = await this.provider.request<{ Bill: QBOBill }>(\n 'GET',\n `bill/${externalId}`,\n );\n\n return mapQBOToBill(response.Bill);\n }\n\n async list(options?: ListOptions): Promise<ExternalBill[]> {\n const limit = options?.limit || 1000;\n let whereClause: string | undefined;\n\n if (options?.startDate) {\n whereClause = `TxnDate >= '${formatLocalDate(options.startDate)}'`;\n if (options?.endDate) {\n whereClause += ` AND TxnDate <= '${formatLocalDate(options.endDate)}'`;\n }\n }\n\n const bills = await this.provider.queryAll<QBOBill>(\n 'Bill',\n whereClause,\n limit,\n );\n return bills.map(mapQBOToBill);\n }\n\n async sync(bill: BillInput): Promise<SyncResult> {\n if (bill.externalId) {\n const existing = await this.provider.request<{ Bill: QBOBill }>(\n 'GET',\n `bill/${bill.externalId}`,\n );\n\n const qboBill: QBOBillUpdate = {\n ...mapBillToQBO(bill),\n Id: bill.externalId,\n SyncToken: existing.Bill.SyncToken,\n };\n\n await this.provider.request('POST', 'bill', qboBill);\n\n return {\n action: 'updated',\n externalId: bill.externalId,\n syncedAt: new Date(),\n };\n }\n\n return this.push(bill);\n }\n}\n\n// =============================================================================\n// Payment Operations\n// =============================================================================\n\nclass QuickBooksPaymentOperations implements PaymentOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async pull(externalId: string): Promise<ExternalPayment> {\n const response = await this.provider.request<{ Payment: QBOPayment }>(\n 'GET',\n `payment/${externalId}`,\n );\n\n return mapQBOToPayment(response.Payment);\n }\n\n async list(options?: ListOptions): Promise<ExternalPayment[]> {\n const limit = options?.limit || 1000;\n let whereClause: string | undefined;\n\n if (options?.startDate) {\n whereClause = `TxnDate >= '${formatLocalDate(options.startDate)}'`;\n if (options?.endDate) {\n whereClause += ` AND TxnDate <= '${formatLocalDate(options.endDate)}'`;\n }\n }\n\n const payments = await this.provider.queryAll<QBOPayment>(\n 'Payment',\n whereClause,\n limit,\n );\n return payments.map(mapQBOToPayment);\n }\n}\n\n// =============================================================================\n// Audit Operations\n// =============================================================================\n\nclass QuickBooksAuditOperations implements AuditOperations {\n constructor(private provider: QuickBooksProvider) {}\n\n async reconcileCustomers(\n locals: CustomerInput[],\n ): Promise<AuditReport<CustomerInput>> {\n const externals = await this.provider.customers.list({ limit: 10000 });\n return reconcileRecords(\n locals,\n externals,\n (l) => l.externalId,\n (e) => e.externalId,\n compareCustomer,\n );\n }\n\n async reconcileInvoices(\n locals: InvoiceInput[],\n dateRange?: DateRange,\n ): Promise<AuditReport<InvoiceInput>> {\n const externals = await this.provider.invoices.list({\n limit: 10000,\n startDate: dateRange?.start,\n endDate: dateRange?.end,\n });\n return reconcileRecords(\n locals,\n externals,\n (l) => l.externalId,\n (e) => e.externalId,\n compareInvoice,\n );\n }\n\n async reconcileVendors(\n locals: VendorInput[],\n ): Promise<AuditReport<VendorInput>> {\n const externals = await this.provider.vendors.list({ limit: 10000 });\n return reconcileRecords(\n locals,\n externals,\n (l) => l.externalId,\n (e) => e.externalId,\n compareVendor,\n );\n }\n\n async reconcileBills(\n locals: BillInput[],\n dateRange?: DateRange,\n ): Promise<AuditReport<BillInput>> {\n const externals = await this.provider.bills.list({\n limit: 10000,\n startDate: dateRange?.start,\n endDate: dateRange?.end,\n });\n return reconcileRecords(\n locals,\n externals,\n (l) => l.externalId,\n (e) => e.externalId,\n compareBill,\n );\n }\n\n async reconcilePayments(\n locals: PaymentInput[],\n dateRange?: DateRange,\n ): Promise<AuditReport<PaymentInput>> {\n const externals = await this.provider.payments.list({\n limit: 10000,\n startDate: dateRange?.start,\n endDate: dateRange?.end,\n });\n return reconcileRecords(\n locals,\n externals,\n (l) => l.externalId,\n (e) => e.externalId,\n comparePayment,\n );\n }\n}\n\n/**\n * Generic reconciliation function with field comparison\n */\nfunction reconcileRecords<TLocal, TExternal extends ExternalRecord>(\n locals: TLocal[],\n externals: TExternal[],\n getLocalExternalId: (local: TLocal) => string | undefined,\n getExternalId: (external: TExternal) => string,\n compareFields: (local: TLocal, external: TExternal) => FieldDiff[],\n): AuditReport<TLocal> {\n const externalMap = new Map(externals.map((e) => [getExternalId(e), e]));\n const matchedExternalIds = new Set<string>();\n\n const matched: AuditMatch<TLocal>[] = [];\n const localOnly: TLocal[] = [];\n const discrepancies: AuditDiscrepancy<TLocal>[] = [];\n\n for (const local of locals) {\n const externalId = getLocalExternalId(local);\n if (externalId && externalMap.has(externalId)) {\n const external = externalMap.get(externalId)!;\n matchedExternalIds.add(externalId);\n\n // Compare fields\n const differences = compareFields(local, external);\n\n if (differences.length === 0) {\n matched.push({\n local,\n external,\n status: 'identical',\n });\n } else {\n discrepancies.push({\n local,\n external,\n differences,\n });\n }\n } else {\n localOnly.push(local);\n }\n }\n\n const externalOnly = externals.filter(\n (e) => !matchedExternalIds.has(getExternalId(e)),\n );\n\n return {\n provider: 'quickbooks',\n auditedAt: new Date(),\n matched,\n localOnly,\n externalOnly,\n discrepancies,\n summary: {\n total: locals.length + externalOnly.length,\n matched: matched.length,\n localOnly: localOnly.length,\n externalOnly: externalOnly.length,\n discrepancies: discrepancies.length,\n },\n };\n}\n\n// Field comparison functions\nfunction compareCustomer(\n local: CustomerInput,\n external: ExternalCustomer,\n): FieldDiff[] {\n const diffs: FieldDiff[] = [];\n\n if (local.name !== external.name) {\n diffs.push({\n field: 'name',\n localValue: local.name,\n externalValue: external.name,\n });\n }\n if (local.email !== external.email) {\n diffs.push({\n field: 'email',\n localValue: local.email,\n externalValue: external.email,\n });\n }\n\n return diffs;\n}\n\nfunction compareInvoice(\n local: InvoiceInput,\n external: ExternalInvoice,\n): FieldDiff[] {\n const diffs: FieldDiff[] = [];\n\n if (!valuesEqual(local.totalAmount, external.totalAmount)) {\n diffs.push({\n field: 'totalAmount',\n localValue: local.totalAmount,\n externalValue: external.totalAmount,\n });\n }\n if (local.invoiceNumber !== external.invoiceNumber) {\n diffs.push({\n field: 'invoiceNumber',\n localValue: local.invoiceNumber,\n externalValue: external.invoiceNumber,\n });\n }\n\n return diffs;\n}\n\nfunction compareVendor(\n local: VendorInput,\n external: ExternalVendor,\n): FieldDiff[] {\n const diffs: FieldDiff[] = [];\n\n if (local.name !== external.name) {\n diffs.push({\n field: 'name',\n localValue: local.name,\n externalValue: external.name,\n });\n }\n if (local.email !== external.email) {\n diffs.push({\n field: 'email',\n localValue: local.email,\n externalValue: external.email,\n });\n }\n\n return diffs;\n}\n\nfunction compareBill(local: BillInput, external: ExternalBill): FieldDiff[] {\n const diffs: FieldDiff[] = [];\n\n if (!valuesEqual(local.totalAmount, external.totalAmount)) {\n diffs.push({\n field: 'totalAmount',\n localValue: local.totalAmount,\n externalValue: external.totalAmount,\n });\n }\n\n return diffs;\n}\n\nfunction comparePayment(\n local: PaymentInput,\n external: ExternalPayment,\n): FieldDiff[] {\n const diffs: FieldDiff[] = [];\n\n if (!valuesEqual(local.amount, external.amount)) {\n diffs.push({\n field: 'amount',\n localValue: local.amount,\n externalValue: external.amount,\n });\n }\n\n return diffs;\n}\n\n// =============================================================================\n// Webhook Operations\n// =============================================================================\n\nclass QuickBooksWebhookOperations implements WebhookOperations {\n constructor(private options: QuickBooksOptions) {}\n\n /**\n * Verify webhook signature using HMAC-SHA256\n * @see https://developer.intuit.com/app/developer/qbo/docs/develop/webhooks/verify-webhooks\n */\n verify(payload: string, signature: string, secret: string): boolean {\n // Use provided secret or fall back to configured webhook verifier token\n const verifierToken = secret || this.options.webhookVerifierToken;\n\n if (!verifierToken) {\n throw new Error(\n 'Webhook verifier token not provided. Pass it as the secret parameter or configure webhookVerifierToken in options.',\n );\n }\n\n // QBO uses HMAC-SHA256 and base64 encodes the signature\n const hmac = createHmac('sha256', verifierToken);\n hmac.update(payload);\n const expectedSignature = hmac.digest('base64');\n\n // Constant-time comparison to prevent timing attacks\n if (signature.length !== expectedSignature.length) {\n return false;\n }\n\n let result = 0;\n for (let i = 0; i < signature.length; i++) {\n result |= signature.charCodeAt(i) ^ expectedSignature.charCodeAt(i);\n }\n return result === 0;\n }\n\n parse(payload: string): WebhookEvent {\n let data: QBOWebhookPayload;\n try {\n data = JSON.parse(payload) as QBOWebhookPayload;\n } catch (error) {\n const message =\n error instanceof Error ? error.message : 'Unknown JSON parse error';\n throw new Error(`Invalid QuickBooks webhook payload: ${message}`);\n }\n\n // QBO webhook payload structure\n const eventNotifications = data.eventNotifications || [];\n const firstEvent = eventNotifications[0]?.dataChangeEvent?.entities?.[0];\n\n return {\n type: firstEvent?.operation || 'unknown',\n provider: 'quickbooks',\n timestamp: new Date(),\n payload: data,\n resourceType: mapQBOResourceType(firstEvent?.name),\n resourceId: firstEvent?.id,\n };\n }\n}\n\nfunction mapQBOResourceType(\n name?: string,\n): WebhookEvent['resourceType'] | undefined {\n switch (name?.toLowerCase()) {\n case 'customer':\n return 'customer';\n case 'invoice':\n return 'invoice';\n case 'payment':\n return 'payment';\n case 'vendor':\n return 'vendor';\n case 'bill':\n return 'bill';\n default:\n return undefined;\n }\n}\n\n// =============================================================================\n// Mapping Functions\n// =============================================================================\n\nfunction mapCustomerToQBO(customer: CustomerInput): QBOCustomerCreate {\n return {\n DisplayName: customer.name,\n PrimaryEmailAddr: customer.email ? { Address: customer.email } : undefined,\n PrimaryPhone: customer.phone\n ? { FreeFormNumber: customer.phone }\n : undefined,\n BillAddr: mapAddressToQBO(customer.billingAddress),\n ShipAddr: mapAddressToQBO(customer.shippingAddress),\n CurrencyRef: customer.currency ? { value: customer.currency } : undefined,\n };\n}\n\nfunction mapQBOToCustomer(qbo: QBOCustomer): ExternalCustomer {\n return {\n externalId: qbo.Id,\n provider: 'quickbooks',\n syncedAt: new Date(),\n name: qbo.DisplayName,\n email: qbo.PrimaryEmailAddr?.Address,\n phone: qbo.PrimaryPhone?.FreeFormNumber,\n billingAddress: mapQBOToAddress(qbo.BillAddr),\n balance: qbo.Balance,\n currency: qbo.CurrencyRef?.value,\n raw: qbo,\n };\n}\n\nfunction mapQBOToInvoice(qbo: QBOInvoice): ExternalInvoice {\n const balance = qbo.Balance ?? 0;\n const totalAmount = qbo.TotalAmt ?? 0;\n\n return {\n externalId: qbo.Id,\n provider: 'quickbooks',\n syncedAt: new Date(),\n invoiceNumber: qbo.DocNumber || '',\n customerExternalId: qbo.CustomerRef?.value || '',\n issueDate: new Date(qbo.TxnDate),\n dueDate: new Date(qbo.DueDate),\n subtotal: totalAmount - (qbo.TxnTaxDetail?.TotalTax ?? 0),\n taxAmount: qbo.TxnTaxDetail?.TotalTax ?? 0,\n totalAmount,\n amountPaid: totalAmount - balance,\n balance,\n status: mapInvoiceStatus(balance, totalAmount, qbo.DueDate),\n currency: qbo.CurrencyRef?.value || 'USD',\n raw: qbo,\n };\n}\n\nfunction mapInvoiceStatus(\n balance: number,\n total: number,\n dueDate: string,\n): ExternalInvoice['status'] {\n if (balance === 0) return 'paid';\n if (balance < total) return 'viewed'; // Partial payment\n if (new Date(dueDate) < new Date()) return 'overdue';\n return 'sent';\n}\n\nfunction mapVendorToQBO(vendor: VendorInput): QBOVendorCreate {\n return {\n DisplayName: vendor.name,\n PrimaryEmailAddr: vendor.email ? { Address: vendor.email } : undefined,\n PrimaryPhone: vendor.phone ? { FreeFormNumber: vendor.phone } : undefined,\n BillAddr: mapAddressToQBO(vendor.address),\n TaxIdentifier: vendor.taxId,\n CurrencyRef: vendor.currency ? { value: vendor.currency } : undefined,\n };\n}\n\nfunction mapQBOToVendor(qbo: QBOVendor): ExternalVendor {\n return {\n externalId: qbo.Id,\n provider: 'quickbooks',\n syncedAt: new Date(),\n name: qbo.DisplayName,\n email: qbo.PrimaryEmailAddr?.Address,\n phone: qbo.PrimaryPhone?.FreeFormNumber,\n address: mapQBOToAddress(qbo.BillAddr),\n balance: qbo.Balance,\n currency: qbo.CurrencyRef?.value,\n raw: qbo,\n };\n}\n\nfunction mapBillToQBO(bill: BillInput): QBOBillCreate {\n return {\n VendorRef: { value: bill.vendorExternalId || bill.vendorId },\n DocNumber: bill.billNumber,\n TxnDate: formatLocalDate(bill.billDate),\n DueDate: formatLocalDate(bill.dueDate),\n Line: bill.lineItems.map((item, idx) => ({\n LineNum: idx + 1,\n Description: item.description,\n Amount: item.amount ?? item.quantity * item.unitPrice,\n DetailType: 'AccountBasedExpenseLineDetail' as const,\n AccountBasedExpenseLineDetail: {\n AccountRef: item.accountCode ? { value: item.accountCode } : undefined,\n },\n })),\n CurrencyRef: bill.currency ? { value: bill.currency } : undefined,\n };\n}\n\nfunction mapQBOToBill(qbo: QBOBill): ExternalBill {\n const balance = qbo.Balance ?? 0;\n const totalAmount = qbo.TotalAmt ?? 0;\n\n return {\n externalId: qbo.Id,\n provider: 'quickbooks',\n syncedAt: new Date(),\n billNumber: qbo.DocNumber,\n vendorExternalId: qbo.VendorRef?.value || '',\n billDate: new Date(qbo.TxnDate),\n dueDate: new Date(qbo.DueDate),\n subtotal: totalAmount - (qbo.TxnTaxDetail?.TotalTax ?? 0),\n taxAmount: qbo.TxnTaxDetail?.TotalTax ?? 0,\n totalAmount,\n amountPaid: totalAmount - balance,\n balance,\n status: mapBillStatus(balance, totalAmount, qbo.DueDate),\n currency: qbo.CurrencyRef?.value || 'USD',\n raw: qbo,\n };\n}\n\nfunction mapBillStatus(\n balance: number,\n total: number,\n dueDate: string,\n): ExternalBill['status'] {\n if (balance === 0) return 'paid';\n if (new Date(dueDate) < new Date()) return 'overdue';\n return 'pending';\n}\n\nfunction mapQBOToPayment(qbo: QBOPayment): ExternalPayment {\n return {\n externalId: qbo.Id,\n provider: 'quickbooks',\n syncedAt: new Date(),\n amount: qbo.TotalAmt ?? 0,\n currency: qbo.CurrencyRef?.value || 'USD',\n paidAt: new Date(qbo.TxnDate),\n method: qbo.PaymentMethodRef?.name,\n transactionId: qbo.PaymentRefNum,\n invoiceExternalIds: qbo.Line?.filter((l) => l.LinkedTxn).flatMap(\n (l) => l.LinkedTxn?.map((t) => t.TxnId) || [],\n ),\n status: 'completed',\n raw: qbo,\n };\n}\n\nfunction mapAddressToQBO(address?: Address): QBOAddress | undefined {\n if (!address) return undefined;\n return {\n Line1: address.street1,\n Line2: address.street2,\n City: address.city,\n CountrySubDivisionCode: address.state,\n PostalCode: address.postalCode,\n Country: address.country,\n };\n}\n\nfunction mapQBOToAddress(qbo?: QBOAddress): Address | undefined {\n if (!qbo) return undefined;\n return {\n street1: qbo.Line1,\n street2: qbo.Line2,\n city: qbo.City,\n state: qbo.CountrySubDivisionCode,\n postalCode: qbo.PostalCode,\n country: qbo.Country,\n };\n}\n\n// =============================================================================\n// QBO API Types (internal, strongly typed)\n// =============================================================================\n\ninterface QBORef {\n value: string;\n name?: string;\n}\n\ninterface QBOAddress {\n Line1?: string;\n Line2?: string;\n City?: string;\n CountrySubDivisionCode?: string;\n PostalCode?: string;\n Country?: string;\n}\n\ninterface QBOEmail {\n Address: string;\n}\n\ninterface QBOPhone {\n FreeFormNumber: string;\n}\n\n// Customer types\ninterface QBOCustomerBase {\n DisplayName: string;\n PrimaryEmailAddr?: QBOEmail;\n PrimaryPhone?: QBOPhone;\n BillAddr?: QBOAddress;\n ShipAddr?: QBOAddress;\n Balance?: number;\n CurrencyRef?: QBORef;\n}\n\ninterface QBOCustomerCreate extends QBOCustomerBase {}\n\ninterface QBOCustomerUpdate extends QBOCustomerBase {\n Id: string;\n SyncToken: string;\n}\n\ninterface QBOCustomer extends QBOCustomerBase {\n Id: string;\n SyncToken: string;\n}\n\n// Invoice types\ninterface QBOInvoiceLine {\n LineNum: number;\n Description?: string;\n Amount: number;\n DetailType: 'SalesItemLineDetail';\n SalesItemLineDetail?: {\n Qty?: number;\n UnitPrice?: number;\n ItemRef?: QBORef;\n TaxCodeRef?: QBORef;\n TaxInclusiveAmt?: number;\n };\n}\n\ninterface QBOInvoiceBase {\n CustomerRef: QBORef;\n DocNumber?: string;\n TxnDate: string;\n DueDate: string;\n Line: QBOInvoiceLine[];\n TotalAmt?: number;\n Balance?: number;\n TxnTaxDetail?: {\n TotalTax?: number;\n };\n GlobalTaxCalculation?: 'TaxExcluded' | 'TaxInclusive' | 'NotApplicable';\n CurrencyRef?: QBORef;\n CustomerMemo?: { value: string };\n}\n\ninterface QBOInvoiceUpdate extends QBOInvoiceBase {\n Id: string;\n SyncToken: string;\n}\n\ninterface QBOInvoice extends QBOInvoiceBase {\n Id: string;\n SyncToken: string;\n}\n\n// Vendor types\ninterface QBOVendorBase {\n DisplayName: string;\n PrimaryEmailAddr?: QBOEmail;\n PrimaryPhone?: QBOPhone;\n BillAddr?: QBOAddress;\n Balance?: number;\n TaxIdentifier?: string;\n CurrencyRef?: QBORef;\n}\n\ninterface QBOVendorCreate extends QBOVendorBase {}\n\ninterface QBOVendorUpdate extends QBOVendorBase {\n Id: string;\n SyncToken: string;\n}\n\ninterface QBOVendor extends QBOVendorBase {\n Id: string;\n SyncToken: string;\n}\n\n// Bill types\ninterface QBOBillLine {\n LineNum: number;\n Description?: string;\n Amount: number;\n DetailType: 'AccountBasedExpenseLineDetail';\n AccountBasedExpenseLineDetail?: {\n AccountRef?: QBORef;\n };\n}\n\ninterface QBOBillBase {\n VendorRef: QBORef;\n DocNumber?: string;\n TxnDate: string;\n DueDate: string;\n Line: QBOBillLine[];\n TotalAmt?: number;\n Balance?: number;\n TxnTaxDetail?: {\n TotalTax?: number;\n };\n CurrencyRef?: QBORef;\n}\n\ninterface QBOBillCreate extends QBOBillBase {}\n\ninterface QBOBillUpdate extends QBOBillBase {\n Id: string;\n SyncToken: string;\n}\n\ninterface QBOBill extends QBOBillBase {\n Id: string;\n SyncToken: string;\n}\n\n// Payment types\ninterface QBOPaymentLine {\n Amount: number;\n LinkedTxn?: {\n TxnId: string;\n TxnType: string;\n }[];\n}\n\ninterface QBOPayment {\n Id: string;\n SyncToken: string;\n TxnDate: string;\n TotalAmt?: number;\n CustomerRef?: QBORef;\n PaymentMethodRef?: QBORef;\n PaymentRefNum?: string;\n Line?: QBOPaymentLine[];\n CurrencyRef?: QBORef;\n}\n\n// Webhook types\ninterface QBOWebhookPayload {\n eventNotifications?: {\n realmId: string;\n dataChangeEvent?: {\n entities?: {\n name: string;\n id: string;\n operation: string;\n lastUpdated: string;\n }[];\n };\n }[];\n}\n"],"mappings":";;;;;;;;;;;;;;AA8DA,SAAS,gBAAgB,MAAoB;CAI3C,OAAO,GAHM,KAAK,YAGR,EAAK,GAFD,OAAO,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAEpC,EAAM,GADZ,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,GAAG,GACpB;AAC7B;;;;AAKA,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;AAKA,SAAS,YAAY,GAAY,GAAqB;CACpD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,aAAa,QAAQ,aAAa,MACpC,OAAO,EAAE,QAAQ,MAAM,EAAE,QAAQ;CAEnC,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAExC,OAAO,KAAK,IAAI,IAAI,CAAC,IAAI;CAE3B,OAAO;AACT;;;;AASA,IAAa,qBAAb,MAA8D;CAC5D,OA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