@happyvertical/accounting 0.103.6 → 0.104.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 +132 -18
- package/dist/chunks/invoice-request-D5fbd6Id.js +479 -0
- package/dist/chunks/invoice-request-D5fbd6Id.js.map +1 -0
- package/dist/chunks/{quickbooks-jX3_uKoz.js → quickbooks-CIedOmSC.js} +44 -8
- package/dist/chunks/quickbooks-CIedOmSC.js.map +1 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -3
- package/dist/index.js.map +1 -1
- package/dist/providers/quickbooks/index.d.ts +3 -2
- package/dist/providers/quickbooks/index.d.ts.map +1 -1
- package/dist/providers/quickbooks/invoice-request.d.ts +61 -19
- package/dist/providers/quickbooks/invoice-request.d.ts.map +1 -1
- package/dist/providers/quickbooks/line-amount.d.ts +6 -0
- package/dist/providers/quickbooks/line-amount.d.ts.map +1 -1
- package/dist/types.d.ts +91 -10
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/invoice-request-CnemKZt9.js +0 -132
- package/dist/chunks/invoice-request-CnemKZt9.js.map +0 -1
- package/dist/chunks/quickbooks-jX3_uKoz.js.map +0 -1
package/README.md
CHANGED
|
@@ -70,27 +70,58 @@ const invoice = {
|
|
|
70
70
|
|
|
71
71
|
The QuickBooks adapter maps these values to `SalesItemLineDetail.ItemRef`,
|
|
72
72
|
`SalesItemLineDetail.TaxCodeRef`, `GlobalTaxCalculation`, and
|
|
73
|
-
`TxnTaxDetail
|
|
74
|
-
`
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
and
|
|
73
|
+
`TxnTaxDetail`. It supports `TaxExcluded`, zero-tax `NotApplicable`, and frozen
|
|
74
|
+
`TaxInclusive` snapshots. For an inclusive line, pass the stored net amount as
|
|
75
|
+
`amount`, its stored tax as `taxAmount`, the stored gross amount as
|
|
76
|
+
`taxInclusiveAmount`, and stored per-component amounts as `taxComponents`.
|
|
77
|
+
An explicit zero-tax inclusive snapshot may supply an empty component list when
|
|
78
|
+
its net and gross facts are equal, including when an off-grid reduced unit price
|
|
79
|
+
requires the generated negative discount line.
|
|
80
|
+
The adapter sends net `Amount` and gross
|
|
81
|
+
`SalesItemLineDetail.TaxInclusiveAmt`; Intuit defines that nested field as the
|
|
82
|
+
total including tax in its [SDK reference](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippphpdevkitv3/entities/files/IPPSalesOrderItemLineDetail.html).
|
|
83
|
+
It emits the stored component tax exactly as `TxnTaxDetail.TaxLine[].Amount`.
|
|
84
|
+
When any component detail is present, every taxed line must carry it and the
|
|
85
|
+
minor-unit aggregate must equal the frozen header tax. Each component therefore
|
|
86
|
+
needs a realm `quickbooksTaxRateRef`; its frozen
|
|
87
|
+
`rate` is a fraction from `0` through `1` and becomes QBO's percent-form
|
|
88
|
+
`TaxPercent` (for example `0.13` becomes `13`). Intuit's invoice example shows
|
|
89
|
+
the writable `TaxLineDetail` fields, and its TaxLineDetail reference requires
|
|
90
|
+
an international `TaxRateRef` to belong to a tax code used on a transaction
|
|
91
|
+
line: [invoice API](https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/invoice),
|
|
92
|
+
[TaxLineDetail reference](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/393902ec-f79c-bb8f-82fd-0f3bd296dd27.htm).
|
|
93
|
+
It validates every component sum, rate-to-frozen-amount allocation (each stored
|
|
94
|
+
component is the exact floor or ceiling allowed by line/document rounding), and
|
|
95
|
+
header reconciliation before any network request. Every mapped line must supply both realm-specific references;
|
|
96
|
+
the caller must validate that those IDs belong to the configured company.
|
|
79
97
|
|
|
80
98
|
Legacy untaxed invoices without `quickbooksMapping` remain supported. The
|
|
81
99
|
adapter fails before authentication or HTTP when an input would otherwise be
|
|
82
|
-
silently discarded: nonzero
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
the
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
100
|
+
silently discarded: nonzero numeric `taxRate`, generic `taxCode`, `automaticTax`,
|
|
101
|
+
inconsistent totals, partial mappings, or invalid references. `unitPrice` and
|
|
102
|
+
`discount` are in the document's amount mode: net for exclusive inputs and gross
|
|
103
|
+
for inclusive ones; `amount` is always the already-discounted net snapshot. A
|
|
104
|
+
discount uses a reduced QBO unit price only when that price fits the currency's
|
|
105
|
+
ISO 4217 minor-unit grid. Otherwise, for an inclusive line, the adapter derives
|
|
106
|
+
the negative net amount from the frozen gross discount and frozen component
|
|
107
|
+
rates, and then adds a negative `Discount on line N` sales line with the same item and tax-code
|
|
108
|
+
references. It never sends QBO's unsupported line-discount field or subtracts a
|
|
109
|
+
discount twice. Negative generated discount lines are internal; caller invoice
|
|
110
|
+
lines remain non-negative. An explicit exclusive line `amount` must agree with
|
|
111
|
+
`quantity × unitPrice` after discount, either exactly or as its decimal
|
|
112
|
+
**half-up** result at the explicitly supplied currency's ISO 4217 minor
|
|
113
|
+
precision. For example, CAD quantity `1.0005` × unit price `10` accepts the
|
|
114
|
+
retained line amount `10.01`. The adapter preserves approved snapshots and never
|
|
115
|
+
changes subtotal/tax reconciliation.
|
|
116
|
+
|
|
117
|
+
A frozen monetary snapshot means a `TaxInclusive` document, or a line carrying
|
|
118
|
+
`taxAmount`, `taxComponents`, `taxInclusiveAmount`, or a nonzero `discount`.
|
|
119
|
+
Those snapshots (document subtotal/tax/total and relevant line net/gross,
|
|
120
|
+
component tax, and discount) must fit the explicitly supplied ISO 4217 grid.
|
|
121
|
+
The source `unitPrice` may remain fractional when its retained line amount is
|
|
122
|
+
on that grid. Legacy exclusive exact-product inputs that carry only an `amount`
|
|
123
|
+
or QuickBooks mapping retain the base validation and do not require a known
|
|
124
|
+
currency. Unknown or missing currency never authorizes frozen snapshot rounding.
|
|
94
125
|
|
|
95
126
|
Precision comes from [ISO 4217 List One published 2026-09-17](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml),
|
|
96
127
|
not runtime display formatting (which differs for IQD, MGA and RSD). Zero-, two-,
|
|
@@ -179,6 +210,44 @@ environment, request ID, timestamps, and returned IDs without credentials.
|
|
|
179
210
|
No replay retention period or exactly-once guarantee is asserted here; reconcile
|
|
180
211
|
old or uncertain requests against QuickBooks before any new creation identity.
|
|
181
212
|
|
|
213
|
+
## QuickBooks credit memos
|
|
214
|
+
|
|
215
|
+
`creditMemos` is an optional provider capability. QuickBooks supports positive
|
|
216
|
+
frozen customer credit notes through `CreditMemo`; providers that omit the
|
|
217
|
+
capability must be refused by the caller. A `CreditMemoInput` uses the same
|
|
218
|
+
net/gross/tax snapshot rules as an invoice, has a
|
|
219
|
+
`creditedInvoiceExternalId` for durable reconciliation, and is created with a
|
|
220
|
+
separate descriptor:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import {
|
|
224
|
+
prepareQuickBooksCreditMemoRequest,
|
|
225
|
+
requireCreditMemoOperations,
|
|
226
|
+
} from '@happyvertical/accounting';
|
|
227
|
+
|
|
228
|
+
const request = prepareQuickBooksCreditMemoRequest(creditMemo, {
|
|
229
|
+
requestId: outbox.requestId,
|
|
230
|
+
realmId: outbox.realmId,
|
|
231
|
+
environment: 'sandbox',
|
|
232
|
+
});
|
|
233
|
+
await requireCreditMemoOperations(qbo).push({
|
|
234
|
+
...creditMemo,
|
|
235
|
+
quickbooksCreditMemoRequest: request,
|
|
236
|
+
});
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
The descriptor carries its realm, environment, and caller-owned request ID, and
|
|
240
|
+
hashes the mapped frozen credit payload together with
|
|
241
|
+
`creditedInvoiceExternalId`. It does not include mutable payment, allocation,
|
|
242
|
+
or status fields, so a retry of the same frozen revision keeps the same request
|
|
243
|
+
identity. Creating a QBO
|
|
244
|
+
`CreditMemo` does not itself apply that credit to the named invoice through this
|
|
245
|
+
API contract; an application must record any later QBO payment/application step
|
|
246
|
+
explicitly. This package does not assume an account's automatic-credit setting.
|
|
247
|
+
It has the same retry and unknown-outcome rules as a keyed invoice create. No
|
|
248
|
+
live Intuit sandbox assertion is made by this package's contract tests; they
|
|
249
|
+
verify serialized payloads, request IDs, retries, and refusal paths.
|
|
250
|
+
|
|
182
251
|
## Stripe invoices
|
|
183
252
|
|
|
184
253
|
Accounting amounts use currency major units: `12.34` means USD 12.34 and
|
|
@@ -435,3 +504,48 @@ After `webhooks.verify` succeeds, the parsed Stripe webhook exposes its provider
|
|
|
435
504
|
Persist that identifier in a durable inbox before applying side effects; the
|
|
436
505
|
in-process parser alone cannot deduplicate deliveries across restarts or
|
|
437
506
|
replicas.
|
|
507
|
+
|
|
508
|
+
### Ordered compound tax snapshots
|
|
509
|
+
|
|
510
|
+
A frozen component may set `compound: true` and `taxableAmount` (currency major
|
|
511
|
+
units). It then taxes the line's net amount plus **all preceding components in
|
|
512
|
+
that line's ordered snapshot**. Its explicit basis must equal that sum of stored
|
|
513
|
+
facts; neither a replacement rate nor a jurisdiction rule is inferred. Different
|
|
514
|
+
applicable line subsets use their corresponding realm tax codes.
|
|
515
|
+
|
|
516
|
+
Compound lines also require verified configuration evidence:
|
|
517
|
+
|
|
518
|
+
```ts
|
|
519
|
+
quickbooksMapping: {
|
|
520
|
+
itemRef: '123',
|
|
521
|
+
taxCodeRef: 'configured-compound-code',
|
|
522
|
+
taxComponents: [
|
|
523
|
+
{ taxRateRef: 'gst-rate', compound: false },
|
|
524
|
+
{ taxRateRef: 'provincial-rate', compound: true },
|
|
525
|
+
],
|
|
526
|
+
}
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
The host must verify this sequence against the target company's existing TaxCode,
|
|
530
|
+
including its applicability and ordering, and persist the verification provenance
|
|
531
|
+
with tenant configuration. The SDK requires an exact match with frozen component
|
|
532
|
+
references and flags; it cannot verify a remote realm from an ID alone and does
|
|
533
|
+
not create or modify tax codes. Missing, duplicate, unknown or mismatched order
|
|
534
|
+
metadata fails before a request can be sent. Tax-only dependencies other than
|
|
535
|
+
all previous applicable components are outside this contract.
|
|
536
|
+
|
|
537
|
+
Exclusive validation uses preceding stored rounded/allocated taxes. Inclusive
|
|
538
|
+
validation extracts exact ordered rational factors and checks the same permitted
|
|
539
|
+
floor/ceiling allocation as additive snapshots. Inclusive discount projection
|
|
540
|
+
uses those factors too. Stored component amounts and original rates are preserved
|
|
541
|
+
in `TxnTaxDetail.TaxLine`; an explicit basis is aggregated by rate into
|
|
542
|
+
`TaxLineDetail.NetAmountTaxable`. Additive snapshots without these new fields
|
|
543
|
+
retain their prior payload bytes and retry descriptor hashes. Credit memos use
|
|
544
|
+
the same representation. This preserves source facts; sandbox acceptance and
|
|
545
|
+
provider readback still require the host's authorized integration verification.
|
|
546
|
+
|
|
547
|
+
Intuit's [TaxRateDetail schema](https://static.developer.intuit.com/sdkdocs/qbv3doc/ipp-v3-java-devkit-javadoc/com/intuit/ipp/data/TaxRateDetail.html)
|
|
548
|
+
defines applicability/order, including
|
|
549
|
+
[TaxOnAmountPlusTax](https://static.developer.intuit.com/sdkdocs/qbv3doc/ipp-v3-java-devkit-javadoc/com/intuit/ipp/data/TaxTypeApplicablityEnum.html).
|
|
550
|
+
Its [TaxLineDetail reference](https://static.developer.intuit.com/sdkdocs/qbv3doc/ippdotnetdevkitv3/html/393902ec-f79c-bb8f-82fd-0f3bd296dd27.htm)
|
|
551
|
+
documents the applicable-rate taxable base and realm rate-reference constraint.
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
//#region src/providers/quickbooks/line-amount.ts
|
|
3
|
+
var currencyPrecision = new Map([
|
|
4
|
+
[0, "BIF CLP DJF GNF ISK JPY KMF KRW PYG RWF UGX UYI VND VUV XAF XOF XPF"],
|
|
5
|
+
[2, "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"],
|
|
6
|
+
[3, "BHD IQD JOD KWD LYD OMR TND"],
|
|
7
|
+
[4, "CLF UYW"]
|
|
8
|
+
].flatMap(([precision, codes]) => codes.split(" ").map((code) => [code, precision])));
|
|
9
|
+
/** ISO minor-unit factor, or undefined when the code is unknown or omitted. */
|
|
10
|
+
function currencyMinorUnitFactor(currency) {
|
|
11
|
+
if (typeof currency !== "string") return void 0;
|
|
12
|
+
const precision = currencyPrecision.get(currency.toUpperCase());
|
|
13
|
+
return precision === void 0 ? void 0 : 10 ** precision;
|
|
14
|
+
}
|
|
15
|
+
/** True only for a finite amount exactly representable on the ISO minor-unit grid. */
|
|
16
|
+
function isCurrencyMinorUnit(amount, currency) {
|
|
17
|
+
if (!Number.isFinite(amount) || typeof currency !== "string") return false;
|
|
18
|
+
const precision = currencyPrecision.get(currency.toUpperCase());
|
|
19
|
+
if (precision === void 0) return false;
|
|
20
|
+
const value = decimalRatio(Math.abs(amount));
|
|
21
|
+
return value.numerator * 10n ** BigInt(precision) % value.denominator === 0n;
|
|
22
|
+
}
|
|
23
|
+
/** Round a finite major-unit amount half-up to a known ISO currency grid. */
|
|
24
|
+
function roundCurrencyAmount(amount, currency) {
|
|
25
|
+
if (!Number.isFinite(amount) || typeof currency !== "string") return void 0;
|
|
26
|
+
const precision = currencyPrecision.get(currency.toUpperCase());
|
|
27
|
+
if (precision === void 0) return void 0;
|
|
28
|
+
const sign = amount < 0 ? -1n : 1n;
|
|
29
|
+
const value = decimalRatio(Math.abs(amount));
|
|
30
|
+
const scale = 10n ** BigInt(precision);
|
|
31
|
+
const numerator = value.numerator * scale;
|
|
32
|
+
const rounded = numerator / value.denominator + (numerator % value.denominator * 2n >= value.denominator ? 1n : 0n);
|
|
33
|
+
return Number(sign * rounded) / Number(scale);
|
|
34
|
+
}
|
|
35
|
+
/** Exact decimal interpretation of the finite nonnegative public number value. */
|
|
36
|
+
function decimalRatio(value) {
|
|
37
|
+
const [significand, exponent = "0"] = value.toString().split("e");
|
|
38
|
+
const [whole, fraction = ""] = significand.split(".");
|
|
39
|
+
const coefficient = BigInt(whole + fraction);
|
|
40
|
+
const scale = fraction.length - Number(exponent);
|
|
41
|
+
return scale >= 0 ? {
|
|
42
|
+
numerator: coefficient,
|
|
43
|
+
denominator: 10n ** BigInt(scale)
|
|
44
|
+
} : {
|
|
45
|
+
numerator: coefficient * 10n ** BigInt(-scale),
|
|
46
|
+
denominator: 1n
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** Admit only the exact half-up minor-unit result; never rewrite caller money. */
|
|
50
|
+
function matchesCurrencyRoundedLineAmount(quantity, unitPrice, amount, currency) {
|
|
51
|
+
if (typeof currency !== "string") return false;
|
|
52
|
+
const precision = currencyPrecision.get(currency.toUpperCase());
|
|
53
|
+
if (precision === void 0) return false;
|
|
54
|
+
const minorScale = 10n ** BigInt(precision);
|
|
55
|
+
const retained = decimalRatio(amount);
|
|
56
|
+
const retainedMinor = retained.numerator * minorScale;
|
|
57
|
+
if (retainedMinor % retained.denominator !== 0n) return false;
|
|
58
|
+
const qty = decimalRatio(quantity);
|
|
59
|
+
const price = decimalRatio(unitPrice);
|
|
60
|
+
const numerator = qty.numerator * price.numerator * minorScale;
|
|
61
|
+
const denominator = qty.denominator * price.denominator;
|
|
62
|
+
const rounded = numerator / denominator + (numerator % denominator * 2n >= denominator ? 1n : 0n);
|
|
63
|
+
return retainedMinor / retained.denominator === rounded;
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/providers/quickbooks/invoice-request.ts
|
|
67
|
+
/** Prepare once, persist before sending, and reuse unchanged. Performs no I/O. */
|
|
68
|
+
function prepareQuickBooksInvoiceRequest(invoice, identity) {
|
|
69
|
+
if (invoice.externalId) throw new Error("QuickBooks request identity is only for invoice creation");
|
|
70
|
+
return prepareRequest(mapInvoiceToQBO(invoice), identity, "invoice");
|
|
71
|
+
}
|
|
72
|
+
/** Prepare once, persist before sending, and reuse unchanged. Performs no I/O. */
|
|
73
|
+
function prepareQuickBooksCreditMemoRequest(creditMemo, identity) {
|
|
74
|
+
if (creditMemo.externalId) throw new Error("QuickBooks request identity is only for credit memo creation");
|
|
75
|
+
return prepareRequest(mapCreditMemoToQBO(creditMemo), {
|
|
76
|
+
...identity,
|
|
77
|
+
creditedInvoiceExternalId: creditMemo.creditedInvoiceExternalId
|
|
78
|
+
}, "credit memo");
|
|
79
|
+
}
|
|
80
|
+
function prepareRequest(mapped, identity, kind) {
|
|
81
|
+
const payload = JSON.stringify(mapped);
|
|
82
|
+
const request = {
|
|
83
|
+
...identity,
|
|
84
|
+
payloadHash: hashDescriptorPayload(payload, identity, kind)
|
|
85
|
+
};
|
|
86
|
+
validateRequest(request, identity.realmId, identity.environment, payload, kind);
|
|
87
|
+
return Object.freeze(request);
|
|
88
|
+
}
|
|
89
|
+
function hash(payload) {
|
|
90
|
+
return createHash("sha256").update(payload).digest("hex");
|
|
91
|
+
}
|
|
92
|
+
/** Bind a credit memo's immutable source invoice without sending it to QBO. */
|
|
93
|
+
function hashDescriptorPayload(payload, request, kind) {
|
|
94
|
+
if (kind === "invoice") return hash(payload);
|
|
95
|
+
return hash(JSON.stringify({
|
|
96
|
+
payload,
|
|
97
|
+
linkage: { creditedInvoiceExternalId: request.creditedInvoiceExternalId }
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
function validateQuickBooksInvoiceRequest(request, realmId, environment, payload) {
|
|
101
|
+
validateRequest(request, realmId, environment, payload, "invoice");
|
|
102
|
+
}
|
|
103
|
+
function validateQuickBooksCreditMemoRequest(request, realmId, environment, payload) {
|
|
104
|
+
validateRequest(request, realmId, environment, payload, "credit memo");
|
|
105
|
+
}
|
|
106
|
+
function validateRequest(request, realmId, environment, payload, kind) {
|
|
107
|
+
if (!request || typeof request.requestId !== "string" || !/^[A-Za-z0-9._-]{1,50}$/.test(request.requestId)) throw new Error("QuickBooks requestId must contain 1–50 URL-safe letters, digits, dots, underscores or hyphens");
|
|
108
|
+
if (!request.realmId || request.realmId !== realmId || !["sandbox", "production"].includes(request.environment) || request.environment !== environment) throw new Error(`QuickBooks ${kind} request realm/environment mismatch`);
|
|
109
|
+
if (!payload || request.payloadHash !== hashDescriptorPayload(payload, request, kind)) throw new Error(`QuickBooks ${kind} request payload mismatch; reconcile the original request`);
|
|
110
|
+
if (kind === "credit memo" && (!("creditedInvoiceExternalId" in request) || !request.creditedInvoiceExternalId || request.creditedInvoiceExternalId.trim() !== request.creditedInvoiceExternalId)) throw new Error("QuickBooks credit memo request requires a credited invoice external ID");
|
|
111
|
+
const parsed = JSON.parse(payload);
|
|
112
|
+
if (parsed.Id !== void 0 || parsed.SyncToken !== void 0) throw new Error(`QuickBooks request identity is only for ${kind} creation`);
|
|
113
|
+
}
|
|
114
|
+
function formatLocalDate(date) {
|
|
115
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
116
|
+
}
|
|
117
|
+
function close(a, b) {
|
|
118
|
+
return Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)) * 8;
|
|
119
|
+
}
|
|
120
|
+
function finite(value, label, allowNegative = false) {
|
|
121
|
+
if (!Number.isFinite(value) || !allowNegative && value < 0) throw new Error(`QuickBooks ${label} must be a finite ${allowNegative ? "" : "non-negative "}amount`);
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
function reference(value, label) {
|
|
125
|
+
if (!value || value.trim() !== value || value.length > 255) throw new Error(`QuickBooks ${label} must be a non-empty realm reference`);
|
|
126
|
+
return { value };
|
|
127
|
+
}
|
|
128
|
+
function canonicalRateNumber(value) {
|
|
129
|
+
for (let places = 0; places <= 12; places++) {
|
|
130
|
+
const candidate = Number(value.toFixed(places));
|
|
131
|
+
if (close(value, candidate)) return candidate.toString();
|
|
132
|
+
}
|
|
133
|
+
return value.toString();
|
|
134
|
+
}
|
|
135
|
+
function decimalRate(value, label) {
|
|
136
|
+
const text = typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value) ? value : typeof value === "number" && Number.isFinite(value) && value >= 0 ? canonicalRateNumber(value) : void 0;
|
|
137
|
+
if (!text || !/^\d+(?:\.\d+)?$/.test(text)) throw new Error(`QuickBooks ${label} needs a frozen component rate from 0 through 1`);
|
|
138
|
+
const [whole, fraction = ""] = text.split(".");
|
|
139
|
+
const denominator = 10n ** BigInt(fraction.length);
|
|
140
|
+
const numerator = BigInt(`${whole}${fraction}`);
|
|
141
|
+
if (numerator > denominator) throw new Error(`QuickBooks ${label} needs a frozen component rate from 0 through 1`);
|
|
142
|
+
return {
|
|
143
|
+
numerator,
|
|
144
|
+
denominator,
|
|
145
|
+
value: Number(text)
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function ratesEqual(left, right) {
|
|
149
|
+
return left.numerator * right.denominator === right.numerator * left.denominator;
|
|
150
|
+
}
|
|
151
|
+
function addRates(left, right) {
|
|
152
|
+
const numerator = left.numerator * right.denominator + right.numerator * left.denominator;
|
|
153
|
+
const denominator = left.denominator * right.denominator;
|
|
154
|
+
return {
|
|
155
|
+
numerator,
|
|
156
|
+
denominator,
|
|
157
|
+
value: Number(numerator) / Number(denominator)
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function taxPercent(rate) {
|
|
161
|
+
return Number(rate.numerator * 100n) / Number(rate.denominator);
|
|
162
|
+
}
|
|
163
|
+
function currencyMinor(amount, currency, label) {
|
|
164
|
+
const factor = currencyMinorUnitFactor(currency);
|
|
165
|
+
const rounded = roundCurrencyAmount(amount, currency);
|
|
166
|
+
if (factor === void 0 || rounded === void 0 || !isCurrencyMinorUnit(amount, currency) && !close(amount, rounded)) throw new Error(`QuickBooks ${label} must fit the explicitly supplied currency's ISO 4217 minor-unit grid`);
|
|
167
|
+
return BigInt(Math.round((isCurrencyMinorUnit(amount, currency) ? amount : rounded) * factor));
|
|
168
|
+
}
|
|
169
|
+
function currencyMajor(minor, currency) {
|
|
170
|
+
const factor = currencyMinorUnitFactor(currency);
|
|
171
|
+
if (factor === void 0) throw new Error("QuickBooks needs a known currency");
|
|
172
|
+
return Number(minor) / factor;
|
|
173
|
+
}
|
|
174
|
+
function taxMinorMatchesAllocation(taxMinor, numerator, denominator) {
|
|
175
|
+
const floor = numerator / denominator;
|
|
176
|
+
const remainder = numerator % denominator;
|
|
177
|
+
return taxMinor === floor || remainder !== 0n && taxMinor === floor + 1n;
|
|
178
|
+
}
|
|
179
|
+
/** Exact per-component factors relative to net; component order is significant. */
|
|
180
|
+
function orderedFactors(components) {
|
|
181
|
+
let total = {
|
|
182
|
+
numerator: 0n,
|
|
183
|
+
denominator: 1n,
|
|
184
|
+
value: 0
|
|
185
|
+
};
|
|
186
|
+
return {
|
|
187
|
+
factors: components.map((component) => {
|
|
188
|
+
const basis = component.compound ? addRates({
|
|
189
|
+
numerator: 1n,
|
|
190
|
+
denominator: 1n,
|
|
191
|
+
value: 1
|
|
192
|
+
}, total) : {
|
|
193
|
+
numerator: 1n,
|
|
194
|
+
denominator: 1n,
|
|
195
|
+
value: 1
|
|
196
|
+
};
|
|
197
|
+
const numerator = component.rate.numerator * basis.numerator;
|
|
198
|
+
const denominator = component.rate.denominator * basis.denominator;
|
|
199
|
+
const factor = {
|
|
200
|
+
numerator,
|
|
201
|
+
denominator,
|
|
202
|
+
value: Number(numerator) / Number(denominator)
|
|
203
|
+
};
|
|
204
|
+
total = addRates(total, factor);
|
|
205
|
+
return factor;
|
|
206
|
+
}),
|
|
207
|
+
total
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function validateFrozenComponentRates(components, taxableAmount, currency, inclusive, label) {
|
|
211
|
+
const taxableMinor = currencyMinor(taxableAmount, currency, `${label} taxable amount`);
|
|
212
|
+
const { factors, total } = orderedFactors(components);
|
|
213
|
+
for (const [index, component] of components.entries()) {
|
|
214
|
+
const factor = factors[index];
|
|
215
|
+
const numerator = inclusive ? taxableMinor * factor.numerator * total.denominator : component.basisMinor * component.rate.numerator;
|
|
216
|
+
const denominator = inclusive ? factor.denominator * (total.denominator + total.numerator) : component.rate.denominator;
|
|
217
|
+
if (!taxMinorMatchesAllocation(component.taxMinor, numerator, denominator)) throw new Error(`QuickBooks ${label} tax component rate is inconsistent with its frozen tax amount`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function frozenCurrencyAmount(value, label, currency, allowNegative = false) {
|
|
221
|
+
finite(value, label, allowNegative);
|
|
222
|
+
const rounded = roundCurrencyAmount(value, currency);
|
|
223
|
+
if (!isCurrencyMinorUnit(value, currency) && (rounded === void 0 || !close(value, rounded))) throw new Error(`QuickBooks ${label} must fit the explicitly supplied currency's ISO 4217 minor-unit grid`);
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
function hasFrozenSnapshots(input) {
|
|
227
|
+
return input.quickbooksMapping?.globalTaxCalculation === "TaxInclusive" || input.lineItems.some((item) => item.taxAmount !== void 0 || item.taxComponents !== void 0 || item.taxInclusiveAmount !== void 0 || item.discount !== void 0 && item.discount !== 0);
|
|
228
|
+
}
|
|
229
|
+
/** Limit accumulated binary error when a valid document has many decimal lines. */
|
|
230
|
+
function compensatedSum(values) {
|
|
231
|
+
let sum = 0;
|
|
232
|
+
let compensation = 0;
|
|
233
|
+
for (const value of values) {
|
|
234
|
+
const adjusted = value - compensation;
|
|
235
|
+
const next = sum + adjusted;
|
|
236
|
+
compensation = next - sum - adjusted;
|
|
237
|
+
sum = next;
|
|
238
|
+
}
|
|
239
|
+
return sum;
|
|
240
|
+
}
|
|
241
|
+
function mapDocumentLines(input) {
|
|
242
|
+
const mode = input.quickbooksMapping?.globalTaxCalculation;
|
|
243
|
+
if (mode && ![
|
|
244
|
+
"TaxExcluded",
|
|
245
|
+
"TaxInclusive",
|
|
246
|
+
"NotApplicable"
|
|
247
|
+
].includes(mode)) throw new Error("QuickBooks globalTaxCalculation must be TaxExcluded, TaxInclusive or NotApplicable");
|
|
248
|
+
const frozen = hasFrozenSnapshots(input);
|
|
249
|
+
const validateAmount = (value, label) => frozen ? frozenCurrencyAmount(value, label, input.currency) : finite(value, label);
|
|
250
|
+
validateAmount(input.subtotal, "subtotal");
|
|
251
|
+
validateAmount(input.taxAmount, "tax amount");
|
|
252
|
+
validateAmount(input.totalAmount, "total amount");
|
|
253
|
+
if (input.lineItems.length === 0) throw new Error("QuickBooks invoices require at least one sales line");
|
|
254
|
+
const hasLineMapping = input.lineItems.some((item) => item.quickbooksMapping);
|
|
255
|
+
if ((input.taxAmount > 0 || hasLineMapping) && !input.quickbooksMapping) throw new Error("QuickBooks mapped or nonzero-tax invoices require explicit globalTaxCalculation");
|
|
256
|
+
if (input.quickbooksMapping && input.lineItems.some((item) => !item.quickbooksMapping)) throw new Error("QuickBooks mapped invoices require itemRef and taxCodeRef on every line");
|
|
257
|
+
if (input.taxAmount > 0 && mode === "NotApplicable") throw new Error("QuickBooks nonzero tax cannot use NotApplicable global tax calculation");
|
|
258
|
+
const mapped = [];
|
|
259
|
+
const taxLines = /* @__PURE__ */ new Map();
|
|
260
|
+
const snapshotLineTaxes = [];
|
|
261
|
+
let hasAnyLineTax = false;
|
|
262
|
+
let hasCompleteLineTax = true;
|
|
263
|
+
const lineTaxSnapshots = [];
|
|
264
|
+
for (const [index, item] of input.lineItems.entries()) {
|
|
265
|
+
const line = mapLine(item, index, input.currency, mode, frozen);
|
|
266
|
+
mapped.push(...line.lines);
|
|
267
|
+
lineTaxSnapshots.push({
|
|
268
|
+
taxAmount: line.taxAmount,
|
|
269
|
+
taxComponents: line.taxComponents
|
|
270
|
+
});
|
|
271
|
+
if (line.taxAmount === void 0) hasCompleteLineTax = false;
|
|
272
|
+
else {
|
|
273
|
+
hasAnyLineTax = true;
|
|
274
|
+
snapshotLineTaxes.push(line.taxAmount);
|
|
275
|
+
}
|
|
276
|
+
for (const component of line.taxComponents) {
|
|
277
|
+
const existing = taxLines.get(component.taxRateRef);
|
|
278
|
+
if (existing) {
|
|
279
|
+
if (!ratesEqual(existing.rate, component.rate)) throw new Error(`QuickBooks tax rate ${component.taxRateRef} has inconsistent frozen rates`);
|
|
280
|
+
existing.amountMinor += component.taxMinor;
|
|
281
|
+
existing.basisMinor += component.basisMinor;
|
|
282
|
+
existing.explicitBasis ||= component.explicitBasis;
|
|
283
|
+
if (existing.explicitBasis && !Number.isSafeInteger(Number(existing.basisMinor))) throw new Error("QuickBooks aggregate taxable basis exceeds safe minor units");
|
|
284
|
+
} else taxLines.set(component.taxRateRef, {
|
|
285
|
+
rate: component.rate,
|
|
286
|
+
amountMinor: component.taxMinor,
|
|
287
|
+
basisMinor: component.basisMinor,
|
|
288
|
+
explicitBasis: component.explicitBasis
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (!close(compensatedSum(mapped.map((line) => line.Amount)), input.subtotal)) throw new Error("QuickBooks line amounts must equal the invoice subtotal");
|
|
293
|
+
if (!close(input.subtotal + input.taxAmount, input.totalAmount)) throw new Error("QuickBooks subtotal plus tax must equal the invoice total");
|
|
294
|
+
if (taxLines.size > 0) {
|
|
295
|
+
if (lineTaxSnapshots.some((line) => line.taxAmount === void 0 || line.taxAmount > 0 && line.taxComponents.length === 0)) throw new Error("QuickBooks component tax detail requires components on every taxed line");
|
|
296
|
+
const totalTaxMinor = currencyMinor(input.taxAmount, input.currency, "tax amount");
|
|
297
|
+
if ([...taxLines.values()].reduce((sum, line) => sum + line.amountMinor, 0n) !== totalTaxMinor) throw new Error("QuickBooks component tax detail must equal the invoice tax amount");
|
|
298
|
+
}
|
|
299
|
+
if (hasAnyLineTax && !hasCompleteLineTax) throw new Error("QuickBooks stored line tax must be supplied on every line when any line supplies it");
|
|
300
|
+
if (hasAnyLineTax && !close(compensatedSum(snapshotLineTaxes), input.taxAmount)) throw new Error("QuickBooks stored line tax must equal the invoice tax amount");
|
|
301
|
+
return {
|
|
302
|
+
lines: mapped,
|
|
303
|
+
taxLines: [...taxLines.entries()].map(([taxRateRef, detail]) => ({
|
|
304
|
+
Amount: currencyMajor(detail.amountMinor, input.currency),
|
|
305
|
+
DetailType: "TaxLineDetail",
|
|
306
|
+
TaxLineDetail: {
|
|
307
|
+
TaxRateRef: { value: taxRateRef },
|
|
308
|
+
TaxPercent: taxPercent(detail.rate),
|
|
309
|
+
PercentBased: true,
|
|
310
|
+
...detail.explicitBasis ? { NetAmountTaxable: currencyMajor(detail.basisMinor, input.currency) } : {}
|
|
311
|
+
}
|
|
312
|
+
}))
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function mapLine(item, index, currency, mode, enforceCurrencyGrid) {
|
|
316
|
+
const label = `line ${index + 1}`;
|
|
317
|
+
if (item.taxRate !== void 0 && item.taxRate !== 0) throw new Error("QuickBooks numeric taxRate is not supported; use a realm taxCodeRef");
|
|
318
|
+
if (item.taxCode !== void 0) throw new Error("QuickBooks generic taxCode is not a realm tax reference; use quickbooksMapping.taxCodeRef");
|
|
319
|
+
finite(item.quantity, `${label} quantity`);
|
|
320
|
+
if (item.quantity <= 0) throw new Error(`QuickBooks ${label} quantity must be greater than zero`);
|
|
321
|
+
finite(item.unitPrice, `${label} unit price`);
|
|
322
|
+
const baseDocumentAmount = item.quantity * item.unitPrice;
|
|
323
|
+
finite(baseDocumentAmount, `${label} pre-discount amount`);
|
|
324
|
+
const validateAmount = (value, amountLabel, allowNegative = false) => enforceCurrencyGrid ? frozenCurrencyAmount(value, amountLabel, currency, allowNegative) : finite(value, amountLabel, allowNegative);
|
|
325
|
+
const discount = validateAmount(item.discount ?? 0, `${label} discount`);
|
|
326
|
+
if (discount > baseDocumentAmount && !close(discount, baseDocumentAmount)) throw new Error(`QuickBooks ${label} discount cannot exceed quantity times unit price`);
|
|
327
|
+
const netAmount = validateAmount(item.amount ?? baseDocumentAmount - discount, `${label} amount`);
|
|
328
|
+
const taxAmount = item.taxAmount === void 0 ? void 0 : validateAmount(item.taxAmount, `${label} tax amount`);
|
|
329
|
+
const taxComponents = [];
|
|
330
|
+
const componentIds = /* @__PURE__ */ new Set();
|
|
331
|
+
const componentRateRefs = /* @__PURE__ */ new Set();
|
|
332
|
+
if (item.taxComponents !== void 0) {
|
|
333
|
+
if (taxAmount === void 0) throw new Error(`QuickBooks ${label} tax components require a line tax amount`);
|
|
334
|
+
if (!close(item.taxComponents.reduce((sum, component, componentIndex) => {
|
|
335
|
+
if (!component || typeof component !== "object" || Object.keys(component).some((key) => ![
|
|
336
|
+
"taxCode",
|
|
337
|
+
"rate",
|
|
338
|
+
"quickbooksTaxRateRef",
|
|
339
|
+
"taxAmount",
|
|
340
|
+
"compound",
|
|
341
|
+
"taxableAmount"
|
|
342
|
+
].includes(key))) throw new Error(`QuickBooks ${label} tax component has unsupported fields`);
|
|
343
|
+
if (component.compound !== void 0 && typeof component.compound !== "boolean") throw new Error(`QuickBooks ${label} compound must be boolean`);
|
|
344
|
+
if (component.compound && component.taxableAmount === void 0) throw new Error(`QuickBooks ${label} compound tax requires its frozen taxableAmount`);
|
|
345
|
+
if (!component.taxCode || component.taxCode.trim() !== component.taxCode) throw new Error(`QuickBooks ${label} tax component ${componentIndex + 1} needs a tax code`);
|
|
346
|
+
const rate = decimalRate(component.rate, `${label} tax component ${componentIndex + 1}`);
|
|
347
|
+
const taxRateRef = reference(component.quickbooksTaxRateRef, `${label} tax component ${componentIndex + 1} quickbooksTaxRateRef`).value;
|
|
348
|
+
const componentAmount = validateAmount(component.taxAmount, `${label} tax component ${componentIndex + 1}`);
|
|
349
|
+
if (componentIds.has(component.taxCode) || componentRateRefs.has(taxRateRef)) throw new Error(`QuickBooks ${label} repeats a tax component or rate reference`);
|
|
350
|
+
componentIds.add(component.taxCode);
|
|
351
|
+
componentRateRefs.add(taxRateRef);
|
|
352
|
+
const expectedBasis = currencyMinor(netAmount, currency, `${label} net amount`) + (component.compound ? taxComponents.reduce((sum, prior) => sum + prior.taxMinor, 0n) : 0n);
|
|
353
|
+
const basisMinor = component.taxableAmount === void 0 ? expectedBasis : currencyMinor(validateAmount(component.taxableAmount, `${label} taxable basis`), currency, `${label} taxable basis`);
|
|
354
|
+
if (!Number.isSafeInteger(Number(basisMinor))) throw new Error(`QuickBooks ${label} taxable basis exceeds safe minor units`);
|
|
355
|
+
if (basisMinor !== expectedBasis) throw new Error(`QuickBooks ${label} frozen taxable basis does not match its ordered components`);
|
|
356
|
+
taxComponents.push({
|
|
357
|
+
taxRateRef,
|
|
358
|
+
rate,
|
|
359
|
+
compound: component.compound ?? false,
|
|
360
|
+
basisMinor,
|
|
361
|
+
explicitBasis: component.taxableAmount !== void 0,
|
|
362
|
+
taxMinor: currencyMinor(componentAmount, currency, `${label} tax component ${componentIndex + 1}`)
|
|
363
|
+
});
|
|
364
|
+
return sum + componentAmount;
|
|
365
|
+
}, 0), taxAmount)) throw new Error(`QuickBooks ${label} tax components must equal the line tax amount`);
|
|
366
|
+
}
|
|
367
|
+
const inclusive = mode === "TaxInclusive";
|
|
368
|
+
const grossAmount = item.taxInclusiveAmount;
|
|
369
|
+
if (!inclusive && grossAmount !== void 0) throw new Error(`QuickBooks ${label} tax-inclusive amount requires TaxInclusive global tax calculation`);
|
|
370
|
+
if (inclusive) {
|
|
371
|
+
if (grossAmount === void 0 || taxAmount === void 0 || taxAmount > 0 && !item.taxComponents?.length) throw new Error(`QuickBooks ${label} TaxInclusive snapshots require gross amount, line tax and tax components for nonzero tax`);
|
|
372
|
+
validateAmount(grossAmount, `${label} tax-inclusive amount`);
|
|
373
|
+
if (!close(netAmount + taxAmount, grossAmount)) throw new Error(`QuickBooks ${label} net amount plus tax must equal gross amount`);
|
|
374
|
+
if (!close(baseDocumentAmount - discount, grossAmount)) throw new Error(`QuickBooks ${label} gross amount must equal quantity times gross unit price less gross discount`);
|
|
375
|
+
} else if (!close(netAmount, baseDocumentAmount - discount) && !matchesCurrencyRoundedLineAmount(item.quantity, item.unitPrice, netAmount + discount, currency)) throw new Error(`QuickBooks ${label} amount must equal quantity times unit price less discount`);
|
|
376
|
+
const mappedComponents = item.quickbooksMapping?.taxComponents;
|
|
377
|
+
if (taxComponents.some((component) => component.compound) && mappedComponents === void 0) throw new Error(`QuickBooks ${label} compound tax requires caller-verified ordered tax-code mapping`);
|
|
378
|
+
if (mappedComponents !== void 0) {
|
|
379
|
+
if (!Array.isArray(mappedComponents) || mappedComponents.length !== taxComponents.length) throw new Error(`QuickBooks ${label} ordered tax-code mapping must match every frozen component`);
|
|
380
|
+
const refs = /* @__PURE__ */ new Set();
|
|
381
|
+
for (const [position, mapped] of mappedComponents.entries()) {
|
|
382
|
+
if (!mapped || typeof mapped !== "object" || Object.keys(mapped).some((key) => !["taxRateRef", "compound"].includes(key)) || typeof mapped.compound !== "boolean") throw new Error(`QuickBooks ${label} ordered tax-code mapping has unknown order metadata`);
|
|
383
|
+
const ref = reference(mapped.taxRateRef, `${label} mapped tax rate`).value;
|
|
384
|
+
const component = taxComponents[position];
|
|
385
|
+
if (refs.has(ref) || ref !== component.taxRateRef || mapped.compound !== component.compound) throw new Error(`QuickBooks ${label} ordered tax-code mapping does not match frozen components`);
|
|
386
|
+
refs.add(ref);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (taxComponents.length > 0) validateFrozenComponentRates(taxComponents, inclusive ? grossAmount : netAmount, currency, inclusive, label);
|
|
390
|
+
const itemRef = item.quickbooksMapping ? reference(item.quickbooksMapping.itemRef, `${label} itemRef`) : void 0;
|
|
391
|
+
const taxCodeRef = item.quickbooksMapping ? reference(item.quickbooksMapping.taxCodeRef, `${label} taxCodeRef`) : void 0;
|
|
392
|
+
const line = (amount, quantity, unitPrice, description, taxInclusiveAmount) => ({
|
|
393
|
+
LineNum: index + 1,
|
|
394
|
+
Description: description,
|
|
395
|
+
Amount: amount,
|
|
396
|
+
DetailType: "SalesItemLineDetail",
|
|
397
|
+
SalesItemLineDetail: {
|
|
398
|
+
Qty: quantity,
|
|
399
|
+
UnitPrice: unitPrice,
|
|
400
|
+
ItemRef: itemRef,
|
|
401
|
+
TaxCodeRef: taxCodeRef,
|
|
402
|
+
...taxInclusiveAmount === void 0 ? {} : { TaxInclusiveAmt: taxInclusiveAmount }
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
if (discount === 0 && !inclusive) return {
|
|
406
|
+
lines: [line(netAmount, item.quantity, item.unitPrice, item.description)],
|
|
407
|
+
taxAmount,
|
|
408
|
+
taxComponents
|
|
409
|
+
};
|
|
410
|
+
if (discount === 0 || isCurrencyMinorUnit(netAmount / item.quantity, currency)) return {
|
|
411
|
+
lines: [line(netAmount, item.quantity, netAmount / item.quantity, item.description, inclusive ? grossAmount : void 0)],
|
|
412
|
+
taxAmount,
|
|
413
|
+
taxComponents
|
|
414
|
+
};
|
|
415
|
+
let preDiscountAmount = netAmount + discount;
|
|
416
|
+
let negativeAmount = -discount;
|
|
417
|
+
const preDiscountGross = inclusive ? baseDocumentAmount : void 0;
|
|
418
|
+
if (inclusive) {
|
|
419
|
+
const components = item.taxComponents;
|
|
420
|
+
const exemptSnapshot = taxAmount === 0 && !components?.length;
|
|
421
|
+
if (!components?.length && !exemptSnapshot) throw new Error(`QuickBooks ${label} needs frozen component rates for an inclusive negative discount line`);
|
|
422
|
+
let discountNet = roundCurrencyAmount(discount / (1 + (exemptSnapshot ? 0 : (components ?? []).reduce((sum, component, componentIndex) => sum + decimalRate(component.rate, `${label} tax component ${componentIndex + 1}`).value, 0))), currency);
|
|
423
|
+
if (taxComponents.some((component) => component.compound)) {
|
|
424
|
+
const { total } = orderedFactors(taxComponents);
|
|
425
|
+
const numerator = currencyMinor(discount, currency, `${label} discount`) * total.denominator;
|
|
426
|
+
const denominator = total.denominator + total.numerator;
|
|
427
|
+
discountNet = currencyMajor((2n * numerator + denominator) / (2n * denominator), currency);
|
|
428
|
+
}
|
|
429
|
+
if (discountNet === void 0) throw new Error(`QuickBooks ${label} needs a recognized currency to map an inclusive fractional-unit discount`);
|
|
430
|
+
preDiscountAmount = netAmount + discountNet;
|
|
431
|
+
negativeAmount = -discountNet;
|
|
432
|
+
}
|
|
433
|
+
if (enforceCurrencyGrid) {
|
|
434
|
+
frozenCurrencyAmount(preDiscountAmount, `${label} generated pre-discount amount`, currency);
|
|
435
|
+
frozenCurrencyAmount(negativeAmount, `${label} generated discount amount`, currency, true);
|
|
436
|
+
}
|
|
437
|
+
let negativeGross;
|
|
438
|
+
if (inclusive) {
|
|
439
|
+
if (grossAmount === void 0 || preDiscountGross === void 0) throw new Error(`QuickBooks ${label} needs frozen gross amounts for an inclusive negative discount line`);
|
|
440
|
+
const unroundedNegativeGross = grossAmount - preDiscountGross;
|
|
441
|
+
negativeGross = roundCurrencyAmount(unroundedNegativeGross, currency) ?? unroundedNegativeGross;
|
|
442
|
+
}
|
|
443
|
+
if (enforceCurrencyGrid && negativeGross !== void 0) frozenCurrencyAmount(negativeGross, `${label} generated gross discount amount`, currency, true);
|
|
444
|
+
return {
|
|
445
|
+
lines: [line(preDiscountAmount, item.quantity, preDiscountAmount / item.quantity, item.description, preDiscountGross), line(negativeAmount, 1, negativeAmount, `Discount on line ${index + 1}`, negativeGross)],
|
|
446
|
+
taxAmount,
|
|
447
|
+
taxComponents
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
function basePayload(input, number, dueDate) {
|
|
451
|
+
const { lines, taxLines } = mapDocumentLines(input);
|
|
452
|
+
return {
|
|
453
|
+
CustomerRef: { value: input.customerExternalId || input.customerId },
|
|
454
|
+
DocNumber: number,
|
|
455
|
+
TxnDate: formatLocalDate(input.issueDate),
|
|
456
|
+
...dueDate ? { DueDate: formatLocalDate(dueDate) } : {},
|
|
457
|
+
Line: lines,
|
|
458
|
+
GlobalTaxCalculation: input.quickbooksMapping?.globalTaxCalculation,
|
|
459
|
+
TxnTaxDetail: input.quickbooksMapping ? {
|
|
460
|
+
TotalTax: input.taxAmount,
|
|
461
|
+
...taxLines.length > 0 ? { TaxLine: taxLines } : {}
|
|
462
|
+
} : void 0,
|
|
463
|
+
CurrencyRef: input.currency ? { value: input.currency } : void 0,
|
|
464
|
+
CustomerMemo: input.memo ? { value: input.memo } : void 0
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
function mapInvoiceToQBO(invoice) {
|
|
468
|
+
if (invoice.collectionMethod === "charge_automatically") throw new Error("QuickBooks does not support charge_automatically invoice collection");
|
|
469
|
+
if (invoice.automaticTax) throw new Error("QuickBooks does not support automaticTax invoice calculation");
|
|
470
|
+
return basePayload(invoice, invoice.invoiceNumber, invoice.dueDate);
|
|
471
|
+
}
|
|
472
|
+
function mapCreditMemoToQBO(creditMemo) {
|
|
473
|
+
if (!creditMemo.creditedInvoiceExternalId || creditMemo.creditedInvoiceExternalId.trim() !== creditMemo.creditedInvoiceExternalId) throw new Error("QuickBooks credit memos require a credited invoice external ID");
|
|
474
|
+
return basePayload(creditMemo, creditMemo.creditMemoNumber);
|
|
475
|
+
}
|
|
476
|
+
//#endregion
|
|
477
|
+
export { validateQuickBooksCreditMemoRequest as a, prepareQuickBooksInvoiceRequest as i, mapInvoiceToQBO as n, validateQuickBooksInvoiceRequest as o, prepareQuickBooksCreditMemoRequest as r, mapCreditMemoToQBO as t };
|
|
478
|
+
|
|
479
|
+
//# sourceMappingURL=invoice-request-D5fbd6Id.js.map
|