@sdflc/backend-helpers 1.0.145 → 1.0.147

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 CHANGED
@@ -34,6 +34,7 @@ A comprehensive backend framework for Node.js applications providing database ac
34
34
  - [DiscordWebhookGw](#discordwebhookgw)
35
35
  - [HubSpotGw](#hubspotgw)
36
36
  - [MailchimpGw](#mailchimpgw)
37
+ - [QuickBooksGw](#quickbooksgw)
37
38
  - [HttpWebhookGw](#httpwebhookgw)
38
39
  - [Outbound URL safety](#outbound-url-safety)
39
40
  - [Testing a gateway](#testing-a-gateway)
@@ -1215,6 +1216,7 @@ request). `configure()` **replaces** the settings; it never merges them.
1215
1216
  | [`DiscordWebhookGw`](#discordwebhookgw) | `webhookUrl`, `username?`, `avatarUrl?` | `postMessage(message)` | `{ messageId }` |
1216
1217
  | [`HubSpotGw`](#hubspotgw) | `accessToken` | `upsertContact(contact)`, `addToList`, `addNote`, `listStaticLists`, `getList`, `verify` | `{ contactId, created }` … |
1217
1218
  | [`MailchimpGw`](#mailchimpgw) | `apiKey` | `upsertMember(audienceId, member)`, `addTags`, `addNote`, `listAudiences`, `getAudience` | `{ memberId, status }` … |
1219
+ | [`QuickBooksGw`](#quickbooksgw) | `clientId`, `clientSecret`, `environment?` | `authorizeUrl`, `exchangeCode`, `refreshTokens`, `revoke`, `query`, `createItem`, `createSalesReceipt`, `createRefundReceipt`, `createPurchase`, `createJournalEntry` … | the tokens / the record |
1218
1220
  | [`HttpWebhookGw`](#httpwebhookgw) | `url`, `method?`, `headers?`, `signingSecret?` | `send(request)` | `{ status, body }` |
1219
1221
 
1220
1222
  Every operation answers the same way:
@@ -1377,6 +1379,35 @@ const audiences = await mailchimp.listAudiences(); // [{ id, name, memberCount }
1377
1379
  city, state and zip are all there (Mailchimp refuses the member over a partial one), the country only as two letters.
1378
1380
  - Pure helpers: `mailchimpDataCenterOf(apiKey)`, `mailchimpSubscriberHash(email)`, `mailchimpAddressOf(address)`.
1379
1381
 
1382
+ ### QuickBooksGw
1383
+
1384
+ Connects a QuickBooks Online company (Intuit OAuth 2.0) and writes the records a sale needs. The settings are the
1385
+ **app's** (`clientId`, `clientSecret`, `environment: 'sandbox' | 'production'` — development keys reach sandbox
1386
+ companies only); a company's own tokens are passed per call, so one gateway serves every connected company.
1387
+
1388
+ ```typescript
1389
+ const qb = new QuickBooksGw().configure({ clientId, clientSecret, environment: 'sandbox' });
1390
+
1391
+ const url = qb.authorizeUrl({ state, redirectUri }); // Intuit's consent screen (accounting scope)
1392
+ const tokens = await qb.exchangeCode(code, redirectUri); // { accessToken, refreshToken, expiresAt, refreshExpiresAt }
1393
+ const company = { realmId, accessToken: tokens.getDataFirst().accessToken };
1394
+
1395
+ await qb.query(company, `select * from Account where AcctNum = ${quickBooksQuoted('4010')}`); // the rows
1396
+ await qb.createItem(company, { name: 'Tickets 4010', incomeAccountId: '79' }, 'item-4010');
1397
+ await qb.createSalesReceipt(company, { Line: [...], DepositToAccountRef: { value: '35' } }, 'payment-123');
1398
+ await qb.refreshTokens(refreshToken); // ⚠ returns a NEW refresh token — store it
1399
+ await qb.revoke(refreshToken); // disconnect
1400
+ ```
1401
+
1402
+ - Also `companyInfo`, `preferences`, `createCustomer`, `createRefundReceipt`, `createPurchase` (a fee leaving an account), `createJournalEntry` (debits and credits on any accounts).
1403
+ - **Every create takes a request id** (Intuit's `requestid`, 1–50 characters): Intuit answers a repeat with the first
1404
+ result, so the base class's retries never book twice. Refused before sending without one.
1405
+ - An expired access token comes back `UNAUTHORIZED` (not retried) — refresh and try once more. Intuit's faults (upper- or
1406
+ lower-case keys) and the token endpoint's `error_description` become the message; the client secret, the Basic header
1407
+ and the tokens are scrubbed out of everything returned. Every call names API version 75.
1408
+ - Pure helpers: `quickBooksQuoted(value)` (a value inside a query's quotes), `quickBooksNameOf(value)` (an item or
1409
+ customer name: no colon — QuickBooks reads it as parent:child — at most 100 characters).
1410
+
1380
1411
  ### HttpWebhookGw
1381
1412
 
1382
1413
  Sends JSON to any URL, for anything without a gateway of its own, optionally **signed**.
@@ -0,0 +1,110 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export type QuickBooksEnvironment = 'sandbox' | 'production';
5
+ export interface QuickBooksSettings {
6
+ clientId: string;
7
+ clientSecret: string;
8
+ /** Which Intuit environment the keys belong to. Default sandbox. */
9
+ environment?: QuickBooksEnvironment;
10
+ }
11
+ /** One connected company, for one call: its realm id and a live access token. */
12
+ export interface QuickBooksCompany {
13
+ realmId: string;
14
+ accessToken: string;
15
+ }
16
+ /** What a code exchange or a refresh answers (the times are ISO, computed from Intuit's seconds). */
17
+ export interface QuickBooksTokens {
18
+ accessToken: string;
19
+ refreshToken: string;
20
+ /** When the access token stops working (about an hour). */
21
+ expiresAt: string;
22
+ /** When the refresh token stops working, if Intuit said. */
23
+ refreshExpiresAt: string | null;
24
+ }
25
+ export declare const QUICKBOOKS_AUTHORIZE_URL = "https://appcenter.intuit.com/connect/oauth2";
26
+ export declare const QUICKBOOKS_TOKEN_URL = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";
27
+ export declare const QUICKBOOKS_REVOKE_URL = "https://developer.api.intuit.com/v2/oauth2/tokens/revoke";
28
+ export declare const QUICKBOOKS_API_URL: Record<QuickBooksEnvironment, string>;
29
+ /** The only scope an accounting writer needs. */
30
+ export declare const QUICKBOOKS_ACCOUNTING_SCOPE = "com.intuit.quickbooks.accounting";
31
+ /** The API version every call names (Intuit ignores anything older since August 2025). */
32
+ export declare const QUICKBOOKS_MINOR_VERSION = 75;
33
+ /** Intuit's limit on a `requestid`. */
34
+ export declare const QUICKBOOKS_REQUEST_ID_MAX = 50;
35
+ /** Intuit's limit on an item's or a customer's name. */
36
+ export declare const QUICKBOOKS_NAME_MAX = 100;
37
+ /** A value inside a query's single quotes: backslash and quote escaped. Pure. */
38
+ export declare const quickBooksQuoted: (value: unknown) => string;
39
+ /**
40
+ * A name an item or a customer may have: no colon (QuickBooks reads it as "parent:child"), no tab or line break, at most
41
+ * 100 characters — or '' when nothing is left. Pure.
42
+ */
43
+ export declare const quickBooksNameOf: (value: unknown) => string;
44
+ declare class QuickBooksGw extends BaseExternalApiGateway<QuickBooksSettings> {
45
+ constructor(props?: BaseExternalApiGatewayPropsInterface<QuickBooksSettings>);
46
+ protected validateSettings(settings: Partial<QuickBooksSettings>): string[];
47
+ protected secretValues(): string[];
48
+ /**
49
+ * Intuit's two error shapes: the token endpoint's `{ error, error_description }`, the API's
50
+ * `{ Fault: { Error: [{ Message, Detail, code }], type } }` (lower-case keys on an authentication failure).
51
+ */
52
+ protected errorMessageOf(reply: ExternalApiReply): string;
53
+ private get environment();
54
+ private basicAuth;
55
+ private badCompany;
56
+ private companyCall;
57
+ /**
58
+ * ⚠ `sentRefreshToken`: Intuit returns the SAME refresh token until it rotates it (about once a day), and every reply is
59
+ * scrubbed of the values the call sent — so an unchanged token arrives as `***`. It is the one we sent; storing `***`
60
+ * instead ended the connection at the next refresh (`invalid_grant`).
61
+ */
62
+ private tokensOf;
63
+ private tokenCall;
64
+ /** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
65
+ authorizeUrl(args: {
66
+ state: string;
67
+ redirectUri: string;
68
+ scope?: string;
69
+ }): string;
70
+ /** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
71
+ exchangeCode(code: string, redirectUri: string): Promise<OpResult>;
72
+ /** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
73
+ refreshTokens(refreshToken: string): Promise<OpResult>;
74
+ /** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
75
+ revoke(token: string): Promise<OpResult>;
76
+ /**
77
+ * A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
78
+ * OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
79
+ */
80
+ query(company: QuickBooksCompany, sql: string): Promise<OpResult>;
81
+ /** The company's name and country. OK with `{ name, country, raw }`. */
82
+ companyInfo(company: QuickBooksCompany): Promise<OpResult>;
83
+ /** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
84
+ preferences(company: QuickBooksCompany): Promise<OpResult>;
85
+ /** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase, JournalEntry). OK with the record. */
86
+ private create;
87
+ /** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
88
+ createItem(company: QuickBooksCompany, item: {
89
+ name: string;
90
+ incomeAccountId: string;
91
+ description?: string | null;
92
+ }, requestId: string): Promise<OpResult>;
93
+ /** A customer by display name (unique in the company across customers, vendors and employees). */
94
+ createCustomer(company: QuickBooksCompany, customer: {
95
+ displayName: string;
96
+ email?: string | null;
97
+ }, requestId: string): Promise<OpResult>;
98
+ /** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
99
+ createSalesReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
100
+ /** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
101
+ createRefundReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
102
+ /** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
103
+ createPurchase(company: QuickBooksCompany, purchase: Record<string, unknown>, requestId: string): Promise<OpResult>;
104
+ /**
105
+ * A journal entry (the body as Intuit takes it — `Line` of `JournalEntryLineDetail` debits and credits, which must
106
+ * balance). Unlike a Purchase it may draw on any account type: a fee kept out of an Undeposited Funds deposit, say.
107
+ */
108
+ createJournalEntry(company: QuickBooksCompany, entry: Record<string, unknown>, requestId: string): Promise<OpResult>;
109
+ }
110
+ export { QuickBooksGw };
@@ -0,0 +1,337 @@
1
+ // ./src/gateways/QuickBooksGw.ts
2
+ //
3
+ // QuickBooks Online (https://developer.intuit.com/app/developer/qbo/docs/api/accounting) — connecting a company with
4
+ // Intuit's OAuth 2.0 and writing the accounting records a sale needs: items, customers, sales receipts, refund receipts,
5
+ // purchases (a fee), plus the reads a mapping screen needs (accounts, items, tax codes, preferences).
6
+ //
7
+ // const qb = new QuickBooksGw().configure({ clientId, clientSecret, environment: 'sandbox' });
8
+ // const url = qb.authorizeUrl({ state, redirectUri }); // send the host there
9
+ // const tokens = await qb.exchangeCode(code, redirectUri); // on the way back (with realmId)
10
+ // const company = { realmId, accessToken: tokens.getDataFirst().accessToken };
11
+ // await qb.createSalesReceipt(company, receipt, 'payment-123'); // the requestid makes a retry harmless
12
+ //
13
+ // The settings are the APP's (GrassEqual's Intuit app): its client id and secret, and which Intuit environment the keys
14
+ // belong to — development keys reach sandbox companies only, production keys real ones. A company's own tokens are
15
+ // passed per call (`QuickBooksCompany`), never kept on the gateway: one gateway serves every connected company.
16
+ //
17
+ // ⚠ The client secret and every token are scrubbed out of every error and reply.
18
+ // ⚠ An access token lasts an hour; a call refused with 401 (UNAUTHORIZED) wants `refreshTokens` and one more try. A
19
+ // refresh RETURNS A NEW REFRESH TOKEN — store it every time (the old one stops working).
20
+ // ⚠ Every create takes a `requestId` (Intuit's `requestid`, at most 50 characters): the same id within Intuit's window is
21
+ // answered with the first result instead of a second record, which is what makes the base class's retries safe.
22
+ import { Buffer } from 'buffer';
23
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
24
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
25
+ export const QUICKBOOKS_AUTHORIZE_URL = 'https://appcenter.intuit.com/connect/oauth2';
26
+ export const QUICKBOOKS_TOKEN_URL = 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer';
27
+ export const QUICKBOOKS_REVOKE_URL = 'https://developer.api.intuit.com/v2/oauth2/tokens/revoke';
28
+ export const QUICKBOOKS_API_URL = {
29
+ sandbox: 'https://sandbox-quickbooks.api.intuit.com',
30
+ production: 'https://quickbooks.api.intuit.com',
31
+ };
32
+ /** The only scope an accounting writer needs. */
33
+ export const QUICKBOOKS_ACCOUNTING_SCOPE = 'com.intuit.quickbooks.accounting';
34
+ /** The API version every call names (Intuit ignores anything older since August 2025). */
35
+ export const QUICKBOOKS_MINOR_VERSION = 75;
36
+ /** Intuit's limit on a `requestid`. */
37
+ export const QUICKBOOKS_REQUEST_ID_MAX = 50;
38
+ /** Intuit's limit on an item's or a customer's name. */
39
+ export const QUICKBOOKS_NAME_MAX = 100;
40
+ const text = (value) => String(value ?? '').trim();
41
+ /** A value inside a query's single quotes: backslash and quote escaped. Pure. */
42
+ export const quickBooksQuoted = (value) => `'${text(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
43
+ /**
44
+ * A name an item or a customer may have: no colon (QuickBooks reads it as "parent:child"), no tab or line break, at most
45
+ * 100 characters — or '' when nothing is left. Pure.
46
+ */
47
+ export const quickBooksNameOf = (value) => text(value)
48
+ .replace(/[:\t\r\n]+/g, ' ')
49
+ .replace(/\s{2,}/g, ' ')
50
+ .trim()
51
+ .slice(0, QUICKBOOKS_NAME_MAX)
52
+ .trim();
53
+ class QuickBooksGw extends BaseExternalApiGateway {
54
+ constructor(props) {
55
+ super(props);
56
+ }
57
+ validateSettings(settings) {
58
+ const problems = [];
59
+ if (!text(settings.clientId)) {
60
+ problems.push('the client id is missing');
61
+ }
62
+ if (!text(settings.clientSecret)) {
63
+ problems.push('the client secret is missing');
64
+ }
65
+ if (settings.environment !== undefined &&
66
+ settings.environment !== 'sandbox' &&
67
+ settings.environment !== 'production') {
68
+ problems.push('the environment is sandbox or production');
69
+ }
70
+ return problems;
71
+ }
72
+ secretValues() {
73
+ const secret = text(this.settings.clientSecret);
74
+ return secret ? [secret, this.basicAuth()] : [];
75
+ }
76
+ /**
77
+ * Intuit's two error shapes: the token endpoint's `{ error, error_description }`, the API's
78
+ * `{ Fault: { Error: [{ Message, Detail, code }], type } }` (lower-case keys on an authentication failure).
79
+ */
80
+ errorMessageOf(reply) {
81
+ const body = reply.body;
82
+ if (body && typeof body === 'object') {
83
+ if (body.error && typeof body.error === 'string') {
84
+ return [body.error, body.error_description].filter(Boolean).join(': ').slice(0, 500);
85
+ }
86
+ const fault = body.Fault ?? body.fault;
87
+ const errors = Array.isArray(fault?.Error ?? fault?.error) ? (fault.Error ?? fault.error) : [];
88
+ const said = errors
89
+ .map((e) => [e?.Message ?? e?.message, e?.Detail ?? e?.detail, e?.code ? `(${e.code})` : ''].filter(Boolean).join(' — '))
90
+ .join('; ');
91
+ if (said) {
92
+ return said.slice(0, 500);
93
+ }
94
+ }
95
+ return super.errorMessageOf(reply);
96
+ }
97
+ get environment() {
98
+ return this.settings.environment === 'production' ? 'production' : 'sandbox';
99
+ }
100
+ basicAuth() {
101
+ return `Basic ${Buffer.from(`${text(this.settings.clientId)}:${text(this.settings.clientSecret)}`).toString('base64')}`;
102
+ }
103
+ badCompany(company) {
104
+ if (!/^\d{1,32}$/.test(text(company?.realmId))) {
105
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The company (realm id) is not one');
106
+ }
107
+ return text(company?.accessToken)
108
+ ? null
109
+ : OpResult.fail(OP_RESULT_CODES.UNAUTHORIZED, null, 'The company has no access token');
110
+ }
111
+ companyCall(company, method, path, query, json) {
112
+ const params = new URLSearchParams({ ...query, minorversion: String(QUICKBOOKS_MINOR_VERSION) });
113
+ return this.requestWithRetries({
114
+ url: `${QUICKBOOKS_API_URL[this.environment]}/v3/company/${text(company.realmId)}${path}?${params.toString()}`,
115
+ method,
116
+ headers: { Authorization: `Bearer ${text(company.accessToken)}`, Accept: 'application/json' },
117
+ ...(json === undefined ? {} : { json }),
118
+ secrets: [text(company.accessToken)],
119
+ });
120
+ }
121
+ /**
122
+ * ⚠ `sentRefreshToken`: Intuit returns the SAME refresh token until it rotates it (about once a day), and every reply is
123
+ * scrubbed of the values the call sent — so an unchanged token arrives as `***`. It is the one we sent; storing `***`
124
+ * instead ended the connection at the next refresh (`invalid_grant`).
125
+ */
126
+ tokensOf(body, sentRefreshToken = '') {
127
+ const accessToken = text(body?.access_token);
128
+ const returned = text(body?.refresh_token);
129
+ const refreshToken = returned === '***' && sentRefreshToken ? sentRefreshToken : returned;
130
+ if (!accessToken || !refreshToken) {
131
+ return null;
132
+ }
133
+ const now = Date.now();
134
+ const expiresIn = Number(body?.expires_in) || 3600;
135
+ const refreshIn = Number(body?.x_refresh_token_expires_in);
136
+ return {
137
+ accessToken,
138
+ refreshToken,
139
+ expiresAt: new Date(now + expiresIn * 1000).toISOString(),
140
+ refreshExpiresAt: Number.isFinite(refreshIn) && refreshIn > 0 ? new Date(now + refreshIn * 1000).toISOString() : null,
141
+ };
142
+ }
143
+ async tokenCall(form, secrets) {
144
+ // ⓘ What `tokensOf` restores when the reply was scrubbed of it (see there).
145
+ const sentRefreshToken = form.grant_type === 'refresh_token' ? text(form.refresh_token) : '';
146
+ if (!this.isConfigured()) {
147
+ return this.notConfigured();
148
+ }
149
+ const result = await this.requestWithRetries({
150
+ url: QUICKBOOKS_TOKEN_URL,
151
+ method: 'POST',
152
+ headers: {
153
+ Authorization: this.basicAuth(),
154
+ Accept: 'application/json',
155
+ 'Content-Type': 'application/x-www-form-urlencoded',
156
+ },
157
+ body: new URLSearchParams(form),
158
+ secrets,
159
+ });
160
+ if (result.didFail()) {
161
+ return result;
162
+ }
163
+ // ⓘ The reply is scrubbed of the values this call SENT (the code, the old refresh token). A new token arrives intact;
164
+ // an UNCHANGED refresh token arrives as `***` and is put back (`tokensOf`).
165
+ const tokens = this.tokensOf(result.getDataFirst()?.body, sentRefreshToken);
166
+ return tokens
167
+ ? OpResult.ok([tokens])
168
+ : OpResult.fail(OP_RESULT_CODES.FAILED, null, 'Intuit answered without the tokens');
169
+ }
170
+ /** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
171
+ authorizeUrl(args) {
172
+ if (!this.isConfigured()) {
173
+ return '';
174
+ }
175
+ const params = new URLSearchParams({
176
+ client_id: text(this.settings.clientId),
177
+ response_type: 'code',
178
+ scope: args.scope || QUICKBOOKS_ACCOUNTING_SCOPE,
179
+ redirect_uri: text(args.redirectUri),
180
+ state: text(args.state),
181
+ });
182
+ return `${QUICKBOOKS_AUTHORIZE_URL}?${params.toString()}`;
183
+ }
184
+ /** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
185
+ async exchangeCode(code, redirectUri) {
186
+ if (!text(code) || !text(redirectUri)) {
187
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The code and the redirect address are needed');
188
+ }
189
+ return this.tokenCall({ grant_type: 'authorization_code', code: text(code), redirect_uri: text(redirectUri) }, [
190
+ text(code),
191
+ ]);
192
+ }
193
+ /** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
194
+ async refreshTokens(refreshToken) {
195
+ if (!text(refreshToken)) {
196
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The refresh token is needed');
197
+ }
198
+ return this.tokenCall({ grant_type: 'refresh_token', refresh_token: text(refreshToken) }, [text(refreshToken)]);
199
+ }
200
+ /** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
201
+ async revoke(token) {
202
+ if (!this.isConfigured()) {
203
+ return this.notConfigured();
204
+ }
205
+ if (!text(token)) {
206
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The token is needed');
207
+ }
208
+ const result = await this.requestWithRetries({
209
+ url: QUICKBOOKS_REVOKE_URL,
210
+ method: 'POST',
211
+ headers: { Authorization: this.basicAuth(), Accept: 'application/json' },
212
+ json: { token: text(token) },
213
+ secrets: [text(token)],
214
+ });
215
+ return result.didFail() ? result : OpResult.ok([{ revoked: true }]);
216
+ }
217
+ /**
218
+ * A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
219
+ * OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
220
+ */
221
+ async query(company, sql) {
222
+ if (!this.isConfigured()) {
223
+ return this.notConfigured();
224
+ }
225
+ const bad = this.badCompany(company);
226
+ if (bad) {
227
+ return bad;
228
+ }
229
+ const result = await this.companyCall(company, 'GET', '/query', { query: text(sql) });
230
+ if (result.didFail()) {
231
+ return result;
232
+ }
233
+ const response = result.getDataFirst()?.body?.QueryResponse ?? {};
234
+ const rows = Object.values(response).find((v) => Array.isArray(v));
235
+ return OpResult.ok(Array.isArray(rows) ? rows : []);
236
+ }
237
+ /** The company's name and country. OK with `{ name, country, raw }`. */
238
+ async companyInfo(company) {
239
+ if (!this.isConfigured()) {
240
+ return this.notConfigured();
241
+ }
242
+ const bad = this.badCompany(company);
243
+ if (bad) {
244
+ return bad;
245
+ }
246
+ const result = await this.companyCall(company, 'GET', `/companyinfo/${text(company.realmId)}`, {});
247
+ if (result.didFail()) {
248
+ return result;
249
+ }
250
+ const info = result.getDataFirst()?.body?.CompanyInfo ?? {};
251
+ return OpResult.ok([
252
+ {
253
+ name: text(info.CompanyName) || text(info.LegalName) || null,
254
+ country: text(info.Country) || null,
255
+ raw: info,
256
+ },
257
+ ]);
258
+ }
259
+ /** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
260
+ async preferences(company) {
261
+ if (!this.isConfigured()) {
262
+ return this.notConfigured();
263
+ }
264
+ const bad = this.badCompany(company);
265
+ if (bad) {
266
+ return bad;
267
+ }
268
+ const result = await this.companyCall(company, 'GET', '/preferences', {});
269
+ return result.didFail() ? result : OpResult.ok([result.getDataFirst()?.body?.Preferences ?? {}]);
270
+ }
271
+ /** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase, JournalEntry). OK with the record. */
272
+ async create(company, entity, body, requestId) {
273
+ if (!this.isConfigured()) {
274
+ return this.notConfigured();
275
+ }
276
+ const bad = this.badCompany(company);
277
+ if (bad) {
278
+ return bad;
279
+ }
280
+ const id = text(requestId);
281
+ if (!id || id.length > QUICKBOOKS_REQUEST_ID_MAX) {
282
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `A request id of 1 to ${QUICKBOOKS_REQUEST_ID_MAX} characters is needed`);
283
+ }
284
+ const result = await this.companyCall(company, 'POST', `/${entity.toLowerCase()}`, { requestid: id }, body);
285
+ if (result.didFail()) {
286
+ return result;
287
+ }
288
+ const record = result.getDataFirst()?.body?.[entity] ?? null;
289
+ return record?.Id
290
+ ? OpResult.ok([record])
291
+ : OpResult.fail(OP_RESULT_CODES.FAILED, null, `QuickBooks answered without the ${entity}`);
292
+ }
293
+ /** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
294
+ createItem(company, item, requestId) {
295
+ const name = quickBooksNameOf(item?.name);
296
+ if (!name || !text(item?.incomeAccountId)) {
297
+ return Promise.resolve(OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'An item needs a name and an income account'));
298
+ }
299
+ return this.create(company, 'Item', {
300
+ Name: name,
301
+ Type: 'Service',
302
+ IncomeAccountRef: { value: text(item.incomeAccountId) },
303
+ ...(text(item.description) ? { Description: text(item.description).slice(0, 4000) } : {}),
304
+ }, requestId);
305
+ }
306
+ /** A customer by display name (unique in the company across customers, vendors and employees). */
307
+ createCustomer(company, customer, requestId) {
308
+ const displayName = quickBooksNameOf(customer?.displayName);
309
+ if (!displayName) {
310
+ return Promise.resolve(OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A customer needs a name'));
311
+ }
312
+ return this.create(company, 'Customer', {
313
+ DisplayName: displayName,
314
+ ...(text(customer.email).includes('@') ? { PrimaryEmailAddr: { Address: text(customer.email) } } : {}),
315
+ }, requestId);
316
+ }
317
+ /** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
318
+ createSalesReceipt(company, receipt, requestId) {
319
+ return this.create(company, 'SalesReceipt', receipt, requestId);
320
+ }
321
+ /** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
322
+ createRefundReceipt(company, receipt, requestId) {
323
+ return this.create(company, 'RefundReceipt', receipt, requestId);
324
+ }
325
+ /** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
326
+ createPurchase(company, purchase, requestId) {
327
+ return this.create(company, 'Purchase', purchase, requestId);
328
+ }
329
+ /**
330
+ * A journal entry (the body as Intuit takes it — `Line` of `JournalEntryLineDetail` debits and credits, which must
331
+ * balance). Unlike a Purchase it may draw on any account type: a fee kept out of an Undeposited Funds deposit, say.
332
+ */
333
+ createJournalEntry(company, entry, requestId) {
334
+ return this.create(company, 'JournalEntry', entry, requestId);
335
+ }
336
+ }
337
+ export { QuickBooksGw };
@@ -7,5 +7,6 @@ export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
8
  export * from './HubSpotGw';
9
9
  export * from './MailchimpGw';
10
+ export * from './QuickBooksGw';
10
11
  export * from './HttpWebhookGw';
11
12
  export * from './guardedFetch';
@@ -7,5 +7,6 @@ export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
8
  export * from './HubSpotGw';
9
9
  export * from './MailchimpGw';
10
+ export * from './QuickBooksGw';
10
11
  export * from './HttpWebhookGw';
11
12
  export * from './guardedFetch';
@@ -0,0 +1,110 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export type QuickBooksEnvironment = 'sandbox' | 'production';
5
+ export interface QuickBooksSettings {
6
+ clientId: string;
7
+ clientSecret: string;
8
+ /** Which Intuit environment the keys belong to. Default sandbox. */
9
+ environment?: QuickBooksEnvironment;
10
+ }
11
+ /** One connected company, for one call: its realm id and a live access token. */
12
+ export interface QuickBooksCompany {
13
+ realmId: string;
14
+ accessToken: string;
15
+ }
16
+ /** What a code exchange or a refresh answers (the times are ISO, computed from Intuit's seconds). */
17
+ export interface QuickBooksTokens {
18
+ accessToken: string;
19
+ refreshToken: string;
20
+ /** When the access token stops working (about an hour). */
21
+ expiresAt: string;
22
+ /** When the refresh token stops working, if Intuit said. */
23
+ refreshExpiresAt: string | null;
24
+ }
25
+ export declare const QUICKBOOKS_AUTHORIZE_URL = "https://appcenter.intuit.com/connect/oauth2";
26
+ export declare const QUICKBOOKS_TOKEN_URL = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer";
27
+ export declare const QUICKBOOKS_REVOKE_URL = "https://developer.api.intuit.com/v2/oauth2/tokens/revoke";
28
+ export declare const QUICKBOOKS_API_URL: Record<QuickBooksEnvironment, string>;
29
+ /** The only scope an accounting writer needs. */
30
+ export declare const QUICKBOOKS_ACCOUNTING_SCOPE = "com.intuit.quickbooks.accounting";
31
+ /** The API version every call names (Intuit ignores anything older since August 2025). */
32
+ export declare const QUICKBOOKS_MINOR_VERSION = 75;
33
+ /** Intuit's limit on a `requestid`. */
34
+ export declare const QUICKBOOKS_REQUEST_ID_MAX = 50;
35
+ /** Intuit's limit on an item's or a customer's name. */
36
+ export declare const QUICKBOOKS_NAME_MAX = 100;
37
+ /** A value inside a query's single quotes: backslash and quote escaped. Pure. */
38
+ export declare const quickBooksQuoted: (value: unknown) => string;
39
+ /**
40
+ * A name an item or a customer may have: no colon (QuickBooks reads it as "parent:child"), no tab or line break, at most
41
+ * 100 characters — or '' when nothing is left. Pure.
42
+ */
43
+ export declare const quickBooksNameOf: (value: unknown) => string;
44
+ declare class QuickBooksGw extends BaseExternalApiGateway<QuickBooksSettings> {
45
+ constructor(props?: BaseExternalApiGatewayPropsInterface<QuickBooksSettings>);
46
+ protected validateSettings(settings: Partial<QuickBooksSettings>): string[];
47
+ protected secretValues(): string[];
48
+ /**
49
+ * Intuit's two error shapes: the token endpoint's `{ error, error_description }`, the API's
50
+ * `{ Fault: { Error: [{ Message, Detail, code }], type } }` (lower-case keys on an authentication failure).
51
+ */
52
+ protected errorMessageOf(reply: ExternalApiReply): string;
53
+ private get environment();
54
+ private basicAuth;
55
+ private badCompany;
56
+ private companyCall;
57
+ /**
58
+ * ⚠ `sentRefreshToken`: Intuit returns the SAME refresh token until it rotates it (about once a day), and every reply is
59
+ * scrubbed of the values the call sent — so an unchanged token arrives as `***`. It is the one we sent; storing `***`
60
+ * instead ended the connection at the next refresh (`invalid_grant`).
61
+ */
62
+ private tokensOf;
63
+ private tokenCall;
64
+ /** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
65
+ authorizeUrl(args: {
66
+ state: string;
67
+ redirectUri: string;
68
+ scope?: string;
69
+ }): string;
70
+ /** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
71
+ exchangeCode(code: string, redirectUri: string): Promise<OpResult>;
72
+ /** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
73
+ refreshTokens(refreshToken: string): Promise<OpResult>;
74
+ /** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
75
+ revoke(token: string): Promise<OpResult>;
76
+ /**
77
+ * A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
78
+ * OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
79
+ */
80
+ query(company: QuickBooksCompany, sql: string): Promise<OpResult>;
81
+ /** The company's name and country. OK with `{ name, country, raw }`. */
82
+ companyInfo(company: QuickBooksCompany): Promise<OpResult>;
83
+ /** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
84
+ preferences(company: QuickBooksCompany): Promise<OpResult>;
85
+ /** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase, JournalEntry). OK with the record. */
86
+ private create;
87
+ /** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
88
+ createItem(company: QuickBooksCompany, item: {
89
+ name: string;
90
+ incomeAccountId: string;
91
+ description?: string | null;
92
+ }, requestId: string): Promise<OpResult>;
93
+ /** A customer by display name (unique in the company across customers, vendors and employees). */
94
+ createCustomer(company: QuickBooksCompany, customer: {
95
+ displayName: string;
96
+ email?: string | null;
97
+ }, requestId: string): Promise<OpResult>;
98
+ /** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
99
+ createSalesReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
100
+ /** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
101
+ createRefundReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
102
+ /** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
103
+ createPurchase(company: QuickBooksCompany, purchase: Record<string, unknown>, requestId: string): Promise<OpResult>;
104
+ /**
105
+ * A journal entry (the body as Intuit takes it — `Line` of `JournalEntryLineDetail` debits and credits, which must
106
+ * balance). Unlike a Purchase it may draw on any account type: a fee kept out of an Undeposited Funds deposit, say.
107
+ */
108
+ createJournalEntry(company: QuickBooksCompany, entry: Record<string, unknown>, requestId: string): Promise<OpResult>;
109
+ }
110
+ export { QuickBooksGw };
@@ -0,0 +1,342 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QuickBooksGw = exports.quickBooksNameOf = exports.quickBooksQuoted = exports.QUICKBOOKS_NAME_MAX = exports.QUICKBOOKS_REQUEST_ID_MAX = exports.QUICKBOOKS_MINOR_VERSION = exports.QUICKBOOKS_ACCOUNTING_SCOPE = exports.QUICKBOOKS_API_URL = exports.QUICKBOOKS_REVOKE_URL = exports.QUICKBOOKS_TOKEN_URL = exports.QUICKBOOKS_AUTHORIZE_URL = void 0;
4
+ // ./src/gateways/QuickBooksGw.ts
5
+ //
6
+ // QuickBooks Online (https://developer.intuit.com/app/developer/qbo/docs/api/accounting) — connecting a company with
7
+ // Intuit's OAuth 2.0 and writing the accounting records a sale needs: items, customers, sales receipts, refund receipts,
8
+ // purchases (a fee), plus the reads a mapping screen needs (accounts, items, tax codes, preferences).
9
+ //
10
+ // const qb = new QuickBooksGw().configure({ clientId, clientSecret, environment: 'sandbox' });
11
+ // const url = qb.authorizeUrl({ state, redirectUri }); // send the host there
12
+ // const tokens = await qb.exchangeCode(code, redirectUri); // on the way back (with realmId)
13
+ // const company = { realmId, accessToken: tokens.getDataFirst().accessToken };
14
+ // await qb.createSalesReceipt(company, receipt, 'payment-123'); // the requestid makes a retry harmless
15
+ //
16
+ // The settings are the APP's (GrassEqual's Intuit app): its client id and secret, and which Intuit environment the keys
17
+ // belong to — development keys reach sandbox companies only, production keys real ones. A company's own tokens are
18
+ // passed per call (`QuickBooksCompany`), never kept on the gateway: one gateway serves every connected company.
19
+ //
20
+ // ⚠ The client secret and every token are scrubbed out of every error and reply.
21
+ // ⚠ An access token lasts an hour; a call refused with 401 (UNAUTHORIZED) wants `refreshTokens` and one more try. A
22
+ // refresh RETURNS A NEW REFRESH TOKEN — store it every time (the old one stops working).
23
+ // ⚠ Every create takes a `requestId` (Intuit's `requestid`, at most 50 characters): the same id within Intuit's window is
24
+ // answered with the first result instead of a second record, which is what makes the base class's retries safe.
25
+ const buffer_1 = require("buffer");
26
+ const api_helpers_1 = require("@sdflc/api-helpers");
27
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
28
+ exports.QUICKBOOKS_AUTHORIZE_URL = 'https://appcenter.intuit.com/connect/oauth2';
29
+ exports.QUICKBOOKS_TOKEN_URL = 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer';
30
+ exports.QUICKBOOKS_REVOKE_URL = 'https://developer.api.intuit.com/v2/oauth2/tokens/revoke';
31
+ exports.QUICKBOOKS_API_URL = {
32
+ sandbox: 'https://sandbox-quickbooks.api.intuit.com',
33
+ production: 'https://quickbooks.api.intuit.com',
34
+ };
35
+ /** The only scope an accounting writer needs. */
36
+ exports.QUICKBOOKS_ACCOUNTING_SCOPE = 'com.intuit.quickbooks.accounting';
37
+ /** The API version every call names (Intuit ignores anything older since August 2025). */
38
+ exports.QUICKBOOKS_MINOR_VERSION = 75;
39
+ /** Intuit's limit on a `requestid`. */
40
+ exports.QUICKBOOKS_REQUEST_ID_MAX = 50;
41
+ /** Intuit's limit on an item's or a customer's name. */
42
+ exports.QUICKBOOKS_NAME_MAX = 100;
43
+ const text = (value) => String(value ?? '').trim();
44
+ /** A value inside a query's single quotes: backslash and quote escaped. Pure. */
45
+ const quickBooksQuoted = (value) => `'${text(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
46
+ exports.quickBooksQuoted = quickBooksQuoted;
47
+ /**
48
+ * A name an item or a customer may have: no colon (QuickBooks reads it as "parent:child"), no tab or line break, at most
49
+ * 100 characters — or '' when nothing is left. Pure.
50
+ */
51
+ const quickBooksNameOf = (value) => text(value)
52
+ .replace(/[:\t\r\n]+/g, ' ')
53
+ .replace(/\s{2,}/g, ' ')
54
+ .trim()
55
+ .slice(0, exports.QUICKBOOKS_NAME_MAX)
56
+ .trim();
57
+ exports.quickBooksNameOf = quickBooksNameOf;
58
+ class QuickBooksGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
59
+ constructor(props) {
60
+ super(props);
61
+ }
62
+ validateSettings(settings) {
63
+ const problems = [];
64
+ if (!text(settings.clientId)) {
65
+ problems.push('the client id is missing');
66
+ }
67
+ if (!text(settings.clientSecret)) {
68
+ problems.push('the client secret is missing');
69
+ }
70
+ if (settings.environment !== undefined &&
71
+ settings.environment !== 'sandbox' &&
72
+ settings.environment !== 'production') {
73
+ problems.push('the environment is sandbox or production');
74
+ }
75
+ return problems;
76
+ }
77
+ secretValues() {
78
+ const secret = text(this.settings.clientSecret);
79
+ return secret ? [secret, this.basicAuth()] : [];
80
+ }
81
+ /**
82
+ * Intuit's two error shapes: the token endpoint's `{ error, error_description }`, the API's
83
+ * `{ Fault: { Error: [{ Message, Detail, code }], type } }` (lower-case keys on an authentication failure).
84
+ */
85
+ errorMessageOf(reply) {
86
+ const body = reply.body;
87
+ if (body && typeof body === 'object') {
88
+ if (body.error && typeof body.error === 'string') {
89
+ return [body.error, body.error_description].filter(Boolean).join(': ').slice(0, 500);
90
+ }
91
+ const fault = body.Fault ?? body.fault;
92
+ const errors = Array.isArray(fault?.Error ?? fault?.error) ? (fault.Error ?? fault.error) : [];
93
+ const said = errors
94
+ .map((e) => [e?.Message ?? e?.message, e?.Detail ?? e?.detail, e?.code ? `(${e.code})` : ''].filter(Boolean).join(' — '))
95
+ .join('; ');
96
+ if (said) {
97
+ return said.slice(0, 500);
98
+ }
99
+ }
100
+ return super.errorMessageOf(reply);
101
+ }
102
+ get environment() {
103
+ return this.settings.environment === 'production' ? 'production' : 'sandbox';
104
+ }
105
+ basicAuth() {
106
+ return `Basic ${buffer_1.Buffer.from(`${text(this.settings.clientId)}:${text(this.settings.clientSecret)}`).toString('base64')}`;
107
+ }
108
+ badCompany(company) {
109
+ if (!/^\d{1,32}$/.test(text(company?.realmId))) {
110
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The company (realm id) is not one');
111
+ }
112
+ return text(company?.accessToken)
113
+ ? null
114
+ : api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'The company has no access token');
115
+ }
116
+ companyCall(company, method, path, query, json) {
117
+ const params = new URLSearchParams({ ...query, minorversion: String(exports.QUICKBOOKS_MINOR_VERSION) });
118
+ return this.requestWithRetries({
119
+ url: `${exports.QUICKBOOKS_API_URL[this.environment]}/v3/company/${text(company.realmId)}${path}?${params.toString()}`,
120
+ method,
121
+ headers: { Authorization: `Bearer ${text(company.accessToken)}`, Accept: 'application/json' },
122
+ ...(json === undefined ? {} : { json }),
123
+ secrets: [text(company.accessToken)],
124
+ });
125
+ }
126
+ /**
127
+ * ⚠ `sentRefreshToken`: Intuit returns the SAME refresh token until it rotates it (about once a day), and every reply is
128
+ * scrubbed of the values the call sent — so an unchanged token arrives as `***`. It is the one we sent; storing `***`
129
+ * instead ended the connection at the next refresh (`invalid_grant`).
130
+ */
131
+ tokensOf(body, sentRefreshToken = '') {
132
+ const accessToken = text(body?.access_token);
133
+ const returned = text(body?.refresh_token);
134
+ const refreshToken = returned === '***' && sentRefreshToken ? sentRefreshToken : returned;
135
+ if (!accessToken || !refreshToken) {
136
+ return null;
137
+ }
138
+ const now = Date.now();
139
+ const expiresIn = Number(body?.expires_in) || 3600;
140
+ const refreshIn = Number(body?.x_refresh_token_expires_in);
141
+ return {
142
+ accessToken,
143
+ refreshToken,
144
+ expiresAt: new Date(now + expiresIn * 1000).toISOString(),
145
+ refreshExpiresAt: Number.isFinite(refreshIn) && refreshIn > 0 ? new Date(now + refreshIn * 1000).toISOString() : null,
146
+ };
147
+ }
148
+ async tokenCall(form, secrets) {
149
+ // ⓘ What `tokensOf` restores when the reply was scrubbed of it (see there).
150
+ const sentRefreshToken = form.grant_type === 'refresh_token' ? text(form.refresh_token) : '';
151
+ if (!this.isConfigured()) {
152
+ return this.notConfigured();
153
+ }
154
+ const result = await this.requestWithRetries({
155
+ url: exports.QUICKBOOKS_TOKEN_URL,
156
+ method: 'POST',
157
+ headers: {
158
+ Authorization: this.basicAuth(),
159
+ Accept: 'application/json',
160
+ 'Content-Type': 'application/x-www-form-urlencoded',
161
+ },
162
+ body: new URLSearchParams(form),
163
+ secrets,
164
+ });
165
+ if (result.didFail()) {
166
+ return result;
167
+ }
168
+ // ⓘ The reply is scrubbed of the values this call SENT (the code, the old refresh token). A new token arrives intact;
169
+ // an UNCHANGED refresh token arrives as `***` and is put back (`tokensOf`).
170
+ const tokens = this.tokensOf(result.getDataFirst()?.body, sentRefreshToken);
171
+ return tokens
172
+ ? api_helpers_1.OpResult.ok([tokens])
173
+ : api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, null, 'Intuit answered without the tokens');
174
+ }
175
+ /** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
176
+ authorizeUrl(args) {
177
+ if (!this.isConfigured()) {
178
+ return '';
179
+ }
180
+ const params = new URLSearchParams({
181
+ client_id: text(this.settings.clientId),
182
+ response_type: 'code',
183
+ scope: args.scope || exports.QUICKBOOKS_ACCOUNTING_SCOPE,
184
+ redirect_uri: text(args.redirectUri),
185
+ state: text(args.state),
186
+ });
187
+ return `${exports.QUICKBOOKS_AUTHORIZE_URL}?${params.toString()}`;
188
+ }
189
+ /** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
190
+ async exchangeCode(code, redirectUri) {
191
+ if (!text(code) || !text(redirectUri)) {
192
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The code and the redirect address are needed');
193
+ }
194
+ return this.tokenCall({ grant_type: 'authorization_code', code: text(code), redirect_uri: text(redirectUri) }, [
195
+ text(code),
196
+ ]);
197
+ }
198
+ /** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
199
+ async refreshTokens(refreshToken) {
200
+ if (!text(refreshToken)) {
201
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The refresh token is needed');
202
+ }
203
+ return this.tokenCall({ grant_type: 'refresh_token', refresh_token: text(refreshToken) }, [text(refreshToken)]);
204
+ }
205
+ /** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
206
+ async revoke(token) {
207
+ if (!this.isConfigured()) {
208
+ return this.notConfigured();
209
+ }
210
+ if (!text(token)) {
211
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The token is needed');
212
+ }
213
+ const result = await this.requestWithRetries({
214
+ url: exports.QUICKBOOKS_REVOKE_URL,
215
+ method: 'POST',
216
+ headers: { Authorization: this.basicAuth(), Accept: 'application/json' },
217
+ json: { token: text(token) },
218
+ secrets: [text(token)],
219
+ });
220
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ revoked: true }]);
221
+ }
222
+ /**
223
+ * A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
224
+ * OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
225
+ */
226
+ async query(company, sql) {
227
+ if (!this.isConfigured()) {
228
+ return this.notConfigured();
229
+ }
230
+ const bad = this.badCompany(company);
231
+ if (bad) {
232
+ return bad;
233
+ }
234
+ const result = await this.companyCall(company, 'GET', '/query', { query: text(sql) });
235
+ if (result.didFail()) {
236
+ return result;
237
+ }
238
+ const response = result.getDataFirst()?.body?.QueryResponse ?? {};
239
+ const rows = Object.values(response).find((v) => Array.isArray(v));
240
+ return api_helpers_1.OpResult.ok(Array.isArray(rows) ? rows : []);
241
+ }
242
+ /** The company's name and country. OK with `{ name, country, raw }`. */
243
+ async companyInfo(company) {
244
+ if (!this.isConfigured()) {
245
+ return this.notConfigured();
246
+ }
247
+ const bad = this.badCompany(company);
248
+ if (bad) {
249
+ return bad;
250
+ }
251
+ const result = await this.companyCall(company, 'GET', `/companyinfo/${text(company.realmId)}`, {});
252
+ if (result.didFail()) {
253
+ return result;
254
+ }
255
+ const info = result.getDataFirst()?.body?.CompanyInfo ?? {};
256
+ return api_helpers_1.OpResult.ok([
257
+ {
258
+ name: text(info.CompanyName) || text(info.LegalName) || null,
259
+ country: text(info.Country) || null,
260
+ raw: info,
261
+ },
262
+ ]);
263
+ }
264
+ /** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
265
+ async preferences(company) {
266
+ if (!this.isConfigured()) {
267
+ return this.notConfigured();
268
+ }
269
+ const bad = this.badCompany(company);
270
+ if (bad) {
271
+ return bad;
272
+ }
273
+ const result = await this.companyCall(company, 'GET', '/preferences', {});
274
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([result.getDataFirst()?.body?.Preferences ?? {}]);
275
+ }
276
+ /** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase, JournalEntry). OK with the record. */
277
+ async create(company, entity, body, requestId) {
278
+ if (!this.isConfigured()) {
279
+ return this.notConfigured();
280
+ }
281
+ const bad = this.badCompany(company);
282
+ if (bad) {
283
+ return bad;
284
+ }
285
+ const id = text(requestId);
286
+ if (!id || id.length > exports.QUICKBOOKS_REQUEST_ID_MAX) {
287
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, `A request id of 1 to ${exports.QUICKBOOKS_REQUEST_ID_MAX} characters is needed`);
288
+ }
289
+ const result = await this.companyCall(company, 'POST', `/${entity.toLowerCase()}`, { requestid: id }, body);
290
+ if (result.didFail()) {
291
+ return result;
292
+ }
293
+ const record = result.getDataFirst()?.body?.[entity] ?? null;
294
+ return record?.Id
295
+ ? api_helpers_1.OpResult.ok([record])
296
+ : api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, null, `QuickBooks answered without the ${entity}`);
297
+ }
298
+ /** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
299
+ createItem(company, item, requestId) {
300
+ const name = (0, exports.quickBooksNameOf)(item?.name);
301
+ if (!name || !text(item?.incomeAccountId)) {
302
+ return Promise.resolve(api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'An item needs a name and an income account'));
303
+ }
304
+ return this.create(company, 'Item', {
305
+ Name: name,
306
+ Type: 'Service',
307
+ IncomeAccountRef: { value: text(item.incomeAccountId) },
308
+ ...(text(item.description) ? { Description: text(item.description).slice(0, 4000) } : {}),
309
+ }, requestId);
310
+ }
311
+ /** A customer by display name (unique in the company across customers, vendors and employees). */
312
+ createCustomer(company, customer, requestId) {
313
+ const displayName = (0, exports.quickBooksNameOf)(customer?.displayName);
314
+ if (!displayName) {
315
+ return Promise.resolve(api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A customer needs a name'));
316
+ }
317
+ return this.create(company, 'Customer', {
318
+ DisplayName: displayName,
319
+ ...(text(customer.email).includes('@') ? { PrimaryEmailAddr: { Address: text(customer.email) } } : {}),
320
+ }, requestId);
321
+ }
322
+ /** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
323
+ createSalesReceipt(company, receipt, requestId) {
324
+ return this.create(company, 'SalesReceipt', receipt, requestId);
325
+ }
326
+ /** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
327
+ createRefundReceipt(company, receipt, requestId) {
328
+ return this.create(company, 'RefundReceipt', receipt, requestId);
329
+ }
330
+ /** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
331
+ createPurchase(company, purchase, requestId) {
332
+ return this.create(company, 'Purchase', purchase, requestId);
333
+ }
334
+ /**
335
+ * A journal entry (the body as Intuit takes it — `Line` of `JournalEntryLineDetail` debits and credits, which must
336
+ * balance). Unlike a Purchase it may draw on any account type: a fee kept out of an Undeposited Funds deposit, say.
337
+ */
338
+ createJournalEntry(company, entry, requestId) {
339
+ return this.create(company, 'JournalEntry', entry, requestId);
340
+ }
341
+ }
342
+ exports.QuickBooksGw = QuickBooksGw;
@@ -7,5 +7,6 @@ export * from './SlackWebhookGw';
7
7
  export * from './DiscordWebhookGw';
8
8
  export * from './HubSpotGw';
9
9
  export * from './MailchimpGw';
10
+ export * from './QuickBooksGw';
10
11
  export * from './HttpWebhookGw';
11
12
  export * from './guardedFetch';
@@ -23,5 +23,6 @@ __exportStar(require("./SlackWebhookGw"), exports);
23
23
  __exportStar(require("./DiscordWebhookGw"), exports);
24
24
  __exportStar(require("./HubSpotGw"), exports);
25
25
  __exportStar(require("./MailchimpGw"), exports);
26
+ __exportStar(require("./QuickBooksGw"), exports);
26
27
  __exportStar(require("./HttpWebhookGw"), exports);
27
28
  __exportStar(require("./guardedFetch"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.145",
3
+ "version": "1.0.147",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {