@sdflc/backend-helpers 1.0.144 → 1.0.146
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 +38 -3
- package/build/esm/gateways/HubSpotGw.d.ts +2 -0
- package/build/esm/gateways/HubSpotGw.js +2 -0
- package/build/esm/gateways/MailchimpGw.d.ts +21 -2
- package/build/esm/gateways/MailchimpGw.js +36 -1
- package/build/esm/gateways/QuickBooksGw.d.ts +100 -0
- package/build/esm/gateways/QuickBooksGw.js +322 -0
- package/build/esm/gateways/index.d.ts +1 -0
- package/build/esm/gateways/index.js +1 -0
- package/build/gateways/HubSpotGw.d.ts +2 -0
- package/build/gateways/HubSpotGw.js +2 -0
- package/build/gateways/MailchimpGw.d.ts +21 -2
- package/build/gateways/MailchimpGw.js +38 -2
- package/build/gateways/QuickBooksGw.d.ts +100 -0
- package/build/gateways/QuickBooksGw.js +327 -0
- package/build/gateways/index.d.ts +1 -0
- package/build/gateways/index.js +1 -0
- package/package.json +1 -1
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` … | 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:
|
|
@@ -1349,7 +1351,9 @@ await hubspot.addNote(contactId, '<p>Registered for …</p>', new Date());
|
|
|
1349
1351
|
const lists = await hubspot.listStaticLists(); // [{ id, name, processingType }] — the contact lists that take members
|
|
1350
1352
|
```
|
|
1351
1353
|
|
|
1352
|
-
- One upsert by email: only the values given are written — an empty one never blanks what HubSpot holds.
|
|
1354
|
+
- One upsert by email: only the values given are written — an empty one never blanks what HubSpot holds. Other
|
|
1355
|
+
properties by their internal names in `properties` (`address`, `city`, `state`, `zip`, `country`, a custom one) — never
|
|
1356
|
+
the email the contact is found by.
|
|
1353
1357
|
- Scopes the key needs: `crm.objects.contacts.read` / `.write`, `crm.lists.read` / `.write`.
|
|
1354
1358
|
- `verify()` reads one contact (nothing is written). The token is scrubbed out of everything returned.
|
|
1355
1359
|
|
|
@@ -1371,7 +1375,38 @@ const audiences = await mailchimp.listAudiences(); // [{ id, name, memberCount }
|
|
|
1371
1375
|
on the audience, not subscribed to marketing; `pending` sends a confirmation email; `subscribed` only with consent).
|
|
1372
1376
|
- Required merge fields the host added are not demanded (`skip_merge_validation`); an audience id that could leave the
|
|
1373
1377
|
path is refused before sending. The key (and the Basic header made of it) is scrubbed out of everything returned.
|
|
1374
|
-
-
|
|
1378
|
+
- `mergeFields.ADDRESS` takes an object (`addr1`, `addr2`, `city`, `state`, `zip`, `country`): sent only when addr1,
|
|
1379
|
+
city, state and zip are all there (Mailchimp refuses the member over a partial one), the country only as two letters.
|
|
1380
|
+
- Pure helpers: `mailchimpDataCenterOf(apiKey)`, `mailchimpSubscriberHash(email)`, `mailchimpAddressOf(address)`.
|
|
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).
|
|
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).
|
|
1375
1410
|
|
|
1376
1411
|
### HttpWebhookGw
|
|
1377
1412
|
|
|
@@ -2525,7 +2560,7 @@ START_READY_TIMEOUT_MS; // 60000: startService alerts when the server is not lis
|
|
|
2525
2560
|
| `SlackWebhookSettings` / `SlackMessage` | `SlackWebhookGw` settings and message |
|
|
2526
2561
|
| `DiscordWebhookSettings` / `DiscordMessage` / `DiscordEmbed` | `DiscordWebhookGw` settings, message and embed |
|
|
2527
2562
|
| `HubSpotSettings` / `HubSpotContact` / `HubSpotList` | `HubSpotGw` settings, a contact, a static list |
|
|
2528
|
-
| `MailchimpSettings` / `MailchimpMember` / `MailchimpAudience` / `MailchimpStatusIfNew` | `MailchimpGw` settings, a member, an audience, a new member's subscription |
|
|
2563
|
+
| `MailchimpSettings` / `MailchimpMember` / `MailchimpAudience` / `MailchimpStatusIfNew` / `MailchimpAddress` | `MailchimpGw` settings, a member, an audience, a new member's subscription |
|
|
2529
2564
|
| `HttpWebhookSettings` / `HttpWebhookSend` / `HttpWebhookGwProps` | `HttpWebhookGw` settings, one send, and its constructor props (`allowPrivateNetwork`, `lookup`, `dnsLookup`) |
|
|
2530
2565
|
| `ExternalUrlOptions` | Options for `checkExternalUrl()`: `{ protocols?, lookup?, field? }` |
|
|
2531
2566
|
| `GuardedFetchOptions` | Options for `createGuardedFetch()`: `{ dnsLookup?, isBlocked? }` |
|
|
@@ -12,6 +12,8 @@ export interface HubSpotContact {
|
|
|
12
12
|
lastName?: string | null;
|
|
13
13
|
phone?: string | null;
|
|
14
14
|
company?: string | null;
|
|
15
|
+
/** Any other contact properties by their internal names — `address`, `city`, `state`, `zip`, `country`, a custom one. */
|
|
16
|
+
properties?: Record<string, string | null | undefined>;
|
|
15
17
|
}
|
|
16
18
|
/** A static list as `listStaticLists` returns it. */
|
|
17
19
|
export interface HubSpotList {
|
|
@@ -70,6 +70,8 @@ class HubSpotGw extends BaseExternalApiGateway {
|
|
|
70
70
|
['lastname', contact.lastName],
|
|
71
71
|
['phone', contact.phone],
|
|
72
72
|
['company', contact.company],
|
|
73
|
+
// ⓘ After the named ones, so `properties` cannot replace the email the contact is found by.
|
|
74
|
+
...Object.entries(contact.properties ?? {}).filter(([name]) => /^[a-z0-9_]{1,100}$/.test(name) && name !== 'email'),
|
|
73
75
|
];
|
|
74
76
|
for (const [name, value] of given) {
|
|
75
77
|
if (text(value)) {
|
|
@@ -10,11 +10,25 @@ export type MailchimpStatusIfNew = 'transactional' | 'pending' | 'subscribed';
|
|
|
10
10
|
export declare const MAILCHIMP_STATUSES_IF_NEW: MailchimpStatusIfNew[];
|
|
11
11
|
export interface MailchimpMember {
|
|
12
12
|
email: string;
|
|
13
|
-
/**
|
|
14
|
-
|
|
13
|
+
/**
|
|
14
|
+
* By merge tag — FNAME, LNAME (every audience has them unless the host removed them), ADDRESS as an object (`addr1`,
|
|
15
|
+
* `addr2`, `city`, `state`, `zip`, `country` — Mailchimp refuses one without addr1, city, state and zip). Empty values
|
|
16
|
+
* are not sent.
|
|
17
|
+
*/
|
|
18
|
+
mergeFields?: Record<string, string | MailchimpAddress | null | undefined>;
|
|
15
19
|
/** Default `transactional`: on the audience, not subscribed to marketing. */
|
|
16
20
|
statusIfNew?: MailchimpStatusIfNew;
|
|
17
21
|
}
|
|
22
|
+
/** The ADDRESS merge field's value. */
|
|
23
|
+
export interface MailchimpAddress {
|
|
24
|
+
addr1: string;
|
|
25
|
+
addr2?: string | null;
|
|
26
|
+
city: string;
|
|
27
|
+
state: string;
|
|
28
|
+
zip: string;
|
|
29
|
+
/** Two letters (`CA`); left out, the audience's default country. */
|
|
30
|
+
country?: string | null;
|
|
31
|
+
}
|
|
18
32
|
/** An audience as `listAudiences` returns it. */
|
|
19
33
|
export interface MailchimpAudience {
|
|
20
34
|
id: string;
|
|
@@ -27,6 +41,11 @@ export declare const MAILCHIMP_NOTE_MAX = 1000;
|
|
|
27
41
|
export declare const MAILCHIMP_TAG_MAX = 100;
|
|
28
42
|
/** The data centre at the end of an API key (`us21`), or null. Pure. */
|
|
29
43
|
export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
|
|
44
|
+
/**
|
|
45
|
+
* An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
|
|
46
|
+
* only as two letters — or null. Pure.
|
|
47
|
+
*/
|
|
48
|
+
export declare const mailchimpAddressOf: (value: Partial<MailchimpAddress> | null | undefined) => Record<string, string> | null;
|
|
30
49
|
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
31
50
|
export declare const mailchimpSubscriberHash: (email: string) => string;
|
|
32
51
|
declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
|
|
@@ -29,6 +29,31 @@ export const mailchimpDataCenterOf = (apiKey) => {
|
|
|
29
29
|
const match = /^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/i.exec(text(apiKey));
|
|
30
30
|
return match ? match[1].toLowerCase() : null;
|
|
31
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
|
|
34
|
+
* only as two letters — or null. Pure.
|
|
35
|
+
*/
|
|
36
|
+
export const mailchimpAddressOf = (value) => {
|
|
37
|
+
const parts = {
|
|
38
|
+
addr1: text(value?.addr1),
|
|
39
|
+
addr2: text(value?.addr2),
|
|
40
|
+
city: text(value?.city),
|
|
41
|
+
state: text(value?.state),
|
|
42
|
+
zip: text(value?.zip),
|
|
43
|
+
};
|
|
44
|
+
if (!parts.addr1 || !parts.city || !parts.state || !parts.zip) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
const country = text(value?.country).toUpperCase();
|
|
48
|
+
const out = { addr1: parts.addr1, city: parts.city, state: parts.state, zip: parts.zip };
|
|
49
|
+
if (parts.addr2) {
|
|
50
|
+
out.addr2 = parts.addr2;
|
|
51
|
+
}
|
|
52
|
+
if (/^[A-Z]{2}$/.test(country)) {
|
|
53
|
+
out.country = country;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
};
|
|
32
57
|
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
33
58
|
export const mailchimpSubscriberHash = (email) => createHash('md5').update(text(email).toLowerCase()).digest('hex');
|
|
34
59
|
class MailchimpGw extends BaseExternalApiGateway {
|
|
@@ -96,7 +121,17 @@ class MailchimpGw extends BaseExternalApiGateway {
|
|
|
96
121
|
: 'transactional';
|
|
97
122
|
const mergeFields = {};
|
|
98
123
|
for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
|
|
99
|
-
if (
|
|
124
|
+
if (!/^[A-Z0-9_]{1,10}$/.test(tag)) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (value && typeof value === 'object') {
|
|
128
|
+
// An address goes whole or not at all: Mailchimp refuses the member over a partial one.
|
|
129
|
+
const address = mailchimpAddressOf(value);
|
|
130
|
+
if (address) {
|
|
131
|
+
mergeFields[tag] = address;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
else if (text(value)) {
|
|
100
135
|
mergeFields[tag] = text(value);
|
|
101
136
|
}
|
|
102
137
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
private tokensOf;
|
|
58
|
+
private tokenCall;
|
|
59
|
+
/** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
|
|
60
|
+
authorizeUrl(args: {
|
|
61
|
+
state: string;
|
|
62
|
+
redirectUri: string;
|
|
63
|
+
scope?: string;
|
|
64
|
+
}): string;
|
|
65
|
+
/** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
|
|
66
|
+
exchangeCode(code: string, redirectUri: string): Promise<OpResult>;
|
|
67
|
+
/** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
|
|
68
|
+
refreshTokens(refreshToken: string): Promise<OpResult>;
|
|
69
|
+
/** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
|
|
70
|
+
revoke(token: string): Promise<OpResult>;
|
|
71
|
+
/**
|
|
72
|
+
* A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
|
|
73
|
+
* OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
|
|
74
|
+
*/
|
|
75
|
+
query(company: QuickBooksCompany, sql: string): Promise<OpResult>;
|
|
76
|
+
/** The company's name and country. OK with `{ name, country, raw }`. */
|
|
77
|
+
companyInfo(company: QuickBooksCompany): Promise<OpResult>;
|
|
78
|
+
/** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
|
|
79
|
+
preferences(company: QuickBooksCompany): Promise<OpResult>;
|
|
80
|
+
/** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase). OK with the record. */
|
|
81
|
+
private create;
|
|
82
|
+
/** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
|
|
83
|
+
createItem(company: QuickBooksCompany, item: {
|
|
84
|
+
name: string;
|
|
85
|
+
incomeAccountId: string;
|
|
86
|
+
description?: string | null;
|
|
87
|
+
}, requestId: string): Promise<OpResult>;
|
|
88
|
+
/** A customer by display name (unique in the company across customers, vendors and employees). */
|
|
89
|
+
createCustomer(company: QuickBooksCompany, customer: {
|
|
90
|
+
displayName: string;
|
|
91
|
+
email?: string | null;
|
|
92
|
+
}, requestId: string): Promise<OpResult>;
|
|
93
|
+
/** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
|
|
94
|
+
createSalesReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
95
|
+
/** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
|
|
96
|
+
createRefundReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
97
|
+
/** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
|
|
98
|
+
createPurchase(company: QuickBooksCompany, purchase: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
99
|
+
}
|
|
100
|
+
export { QuickBooksGw };
|
|
@@ -0,0 +1,322 @@
|
|
|
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
|
+
tokensOf(body) {
|
|
122
|
+
const accessToken = text(body?.access_token);
|
|
123
|
+
const refreshToken = text(body?.refresh_token);
|
|
124
|
+
if (!accessToken || !refreshToken) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
const expiresIn = Number(body?.expires_in) || 3600;
|
|
129
|
+
const refreshIn = Number(body?.x_refresh_token_expires_in);
|
|
130
|
+
return {
|
|
131
|
+
accessToken,
|
|
132
|
+
refreshToken,
|
|
133
|
+
expiresAt: new Date(now + expiresIn * 1000).toISOString(),
|
|
134
|
+
refreshExpiresAt: Number.isFinite(refreshIn) && refreshIn > 0 ? new Date(now + refreshIn * 1000).toISOString() : null,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
async tokenCall(form, secrets) {
|
|
138
|
+
if (!this.isConfigured()) {
|
|
139
|
+
return this.notConfigured();
|
|
140
|
+
}
|
|
141
|
+
const result = await this.requestWithRetries({
|
|
142
|
+
url: QUICKBOOKS_TOKEN_URL,
|
|
143
|
+
method: 'POST',
|
|
144
|
+
headers: {
|
|
145
|
+
Authorization: this.basicAuth(),
|
|
146
|
+
Accept: 'application/json',
|
|
147
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
148
|
+
},
|
|
149
|
+
body: new URLSearchParams(form),
|
|
150
|
+
secrets,
|
|
151
|
+
});
|
|
152
|
+
if (result.didFail()) {
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
// ⓘ The reply is scrubbed of the values this call SENT (the code, the old refresh token) — the new tokens are not
|
|
156
|
+
// among them, so they arrive intact.
|
|
157
|
+
const tokens = this.tokensOf(result.getDataFirst()?.body);
|
|
158
|
+
return tokens
|
|
159
|
+
? OpResult.ok([tokens])
|
|
160
|
+
: OpResult.fail(OP_RESULT_CODES.FAILED, null, 'Intuit answered without the tokens');
|
|
161
|
+
}
|
|
162
|
+
/** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
|
|
163
|
+
authorizeUrl(args) {
|
|
164
|
+
if (!this.isConfigured()) {
|
|
165
|
+
return '';
|
|
166
|
+
}
|
|
167
|
+
const params = new URLSearchParams({
|
|
168
|
+
client_id: text(this.settings.clientId),
|
|
169
|
+
response_type: 'code',
|
|
170
|
+
scope: args.scope || QUICKBOOKS_ACCOUNTING_SCOPE,
|
|
171
|
+
redirect_uri: text(args.redirectUri),
|
|
172
|
+
state: text(args.state),
|
|
173
|
+
});
|
|
174
|
+
return `${QUICKBOOKS_AUTHORIZE_URL}?${params.toString()}`;
|
|
175
|
+
}
|
|
176
|
+
/** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
|
|
177
|
+
async exchangeCode(code, redirectUri) {
|
|
178
|
+
if (!text(code) || !text(redirectUri)) {
|
|
179
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The code and the redirect address are needed');
|
|
180
|
+
}
|
|
181
|
+
return this.tokenCall({ grant_type: 'authorization_code', code: text(code), redirect_uri: text(redirectUri) }, [
|
|
182
|
+
text(code),
|
|
183
|
+
]);
|
|
184
|
+
}
|
|
185
|
+
/** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
|
|
186
|
+
async refreshTokens(refreshToken) {
|
|
187
|
+
if (!text(refreshToken)) {
|
|
188
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The refresh token is needed');
|
|
189
|
+
}
|
|
190
|
+
return this.tokenCall({ grant_type: 'refresh_token', refresh_token: text(refreshToken) }, [text(refreshToken)]);
|
|
191
|
+
}
|
|
192
|
+
/** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
|
|
193
|
+
async revoke(token) {
|
|
194
|
+
if (!this.isConfigured()) {
|
|
195
|
+
return this.notConfigured();
|
|
196
|
+
}
|
|
197
|
+
if (!text(token)) {
|
|
198
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The token is needed');
|
|
199
|
+
}
|
|
200
|
+
const result = await this.requestWithRetries({
|
|
201
|
+
url: QUICKBOOKS_REVOKE_URL,
|
|
202
|
+
method: 'POST',
|
|
203
|
+
headers: { Authorization: this.basicAuth(), Accept: 'application/json' },
|
|
204
|
+
json: { token: text(token) },
|
|
205
|
+
secrets: [text(token)],
|
|
206
|
+
});
|
|
207
|
+
return result.didFail() ? result : OpResult.ok([{ revoked: true }]);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
|
|
211
|
+
* OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
|
|
212
|
+
*/
|
|
213
|
+
async query(company, sql) {
|
|
214
|
+
if (!this.isConfigured()) {
|
|
215
|
+
return this.notConfigured();
|
|
216
|
+
}
|
|
217
|
+
const bad = this.badCompany(company);
|
|
218
|
+
if (bad) {
|
|
219
|
+
return bad;
|
|
220
|
+
}
|
|
221
|
+
const result = await this.companyCall(company, 'GET', '/query', { query: text(sql) });
|
|
222
|
+
if (result.didFail()) {
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
const response = result.getDataFirst()?.body?.QueryResponse ?? {};
|
|
226
|
+
const rows = Object.values(response).find((v) => Array.isArray(v));
|
|
227
|
+
return OpResult.ok(Array.isArray(rows) ? rows : []);
|
|
228
|
+
}
|
|
229
|
+
/** The company's name and country. OK with `{ name, country, raw }`. */
|
|
230
|
+
async companyInfo(company) {
|
|
231
|
+
if (!this.isConfigured()) {
|
|
232
|
+
return this.notConfigured();
|
|
233
|
+
}
|
|
234
|
+
const bad = this.badCompany(company);
|
|
235
|
+
if (bad) {
|
|
236
|
+
return bad;
|
|
237
|
+
}
|
|
238
|
+
const result = await this.companyCall(company, 'GET', `/companyinfo/${text(company.realmId)}`, {});
|
|
239
|
+
if (result.didFail()) {
|
|
240
|
+
return result;
|
|
241
|
+
}
|
|
242
|
+
const info = result.getDataFirst()?.body?.CompanyInfo ?? {};
|
|
243
|
+
return OpResult.ok([
|
|
244
|
+
{
|
|
245
|
+
name: text(info.CompanyName) || text(info.LegalName) || null,
|
|
246
|
+
country: text(info.Country) || null,
|
|
247
|
+
raw: info,
|
|
248
|
+
},
|
|
249
|
+
]);
|
|
250
|
+
}
|
|
251
|
+
/** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
|
|
252
|
+
async preferences(company) {
|
|
253
|
+
if (!this.isConfigured()) {
|
|
254
|
+
return this.notConfigured();
|
|
255
|
+
}
|
|
256
|
+
const bad = this.badCompany(company);
|
|
257
|
+
if (bad) {
|
|
258
|
+
return bad;
|
|
259
|
+
}
|
|
260
|
+
const result = await this.companyCall(company, 'GET', '/preferences', {});
|
|
261
|
+
return result.didFail() ? result : OpResult.ok([result.getDataFirst()?.body?.Preferences ?? {}]);
|
|
262
|
+
}
|
|
263
|
+
/** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase). OK with the record. */
|
|
264
|
+
async create(company, entity, body, requestId) {
|
|
265
|
+
if (!this.isConfigured()) {
|
|
266
|
+
return this.notConfigured();
|
|
267
|
+
}
|
|
268
|
+
const bad = this.badCompany(company);
|
|
269
|
+
if (bad) {
|
|
270
|
+
return bad;
|
|
271
|
+
}
|
|
272
|
+
const id = text(requestId);
|
|
273
|
+
if (!id || id.length > QUICKBOOKS_REQUEST_ID_MAX) {
|
|
274
|
+
return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `A request id of 1 to ${QUICKBOOKS_REQUEST_ID_MAX} characters is needed`);
|
|
275
|
+
}
|
|
276
|
+
const result = await this.companyCall(company, 'POST', `/${entity.toLowerCase()}`, { requestid: id }, body);
|
|
277
|
+
if (result.didFail()) {
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
const record = result.getDataFirst()?.body?.[entity] ?? null;
|
|
281
|
+
return record?.Id
|
|
282
|
+
? OpResult.ok([record])
|
|
283
|
+
: OpResult.fail(OP_RESULT_CODES.FAILED, null, `QuickBooks answered without the ${entity}`);
|
|
284
|
+
}
|
|
285
|
+
/** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
|
|
286
|
+
createItem(company, item, requestId) {
|
|
287
|
+
const name = quickBooksNameOf(item?.name);
|
|
288
|
+
if (!name || !text(item?.incomeAccountId)) {
|
|
289
|
+
return Promise.resolve(OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'An item needs a name and an income account'));
|
|
290
|
+
}
|
|
291
|
+
return this.create(company, 'Item', {
|
|
292
|
+
Name: name,
|
|
293
|
+
Type: 'Service',
|
|
294
|
+
IncomeAccountRef: { value: text(item.incomeAccountId) },
|
|
295
|
+
...(text(item.description) ? { Description: text(item.description).slice(0, 4000) } : {}),
|
|
296
|
+
}, requestId);
|
|
297
|
+
}
|
|
298
|
+
/** A customer by display name (unique in the company across customers, vendors and employees). */
|
|
299
|
+
createCustomer(company, customer, requestId) {
|
|
300
|
+
const displayName = quickBooksNameOf(customer?.displayName);
|
|
301
|
+
if (!displayName) {
|
|
302
|
+
return Promise.resolve(OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A customer needs a name'));
|
|
303
|
+
}
|
|
304
|
+
return this.create(company, 'Customer', {
|
|
305
|
+
DisplayName: displayName,
|
|
306
|
+
...(text(customer.email).includes('@') ? { PrimaryEmailAddr: { Address: text(customer.email) } } : {}),
|
|
307
|
+
}, requestId);
|
|
308
|
+
}
|
|
309
|
+
/** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
|
|
310
|
+
createSalesReceipt(company, receipt, requestId) {
|
|
311
|
+
return this.create(company, 'SalesReceipt', receipt, requestId);
|
|
312
|
+
}
|
|
313
|
+
/** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
|
|
314
|
+
createRefundReceipt(company, receipt, requestId) {
|
|
315
|
+
return this.create(company, 'RefundReceipt', receipt, requestId);
|
|
316
|
+
}
|
|
317
|
+
/** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
|
|
318
|
+
createPurchase(company, purchase, requestId) {
|
|
319
|
+
return this.create(company, 'Purchase', purchase, requestId);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
export { QuickBooksGw };
|
|
@@ -12,6 +12,8 @@ export interface HubSpotContact {
|
|
|
12
12
|
lastName?: string | null;
|
|
13
13
|
phone?: string | null;
|
|
14
14
|
company?: string | null;
|
|
15
|
+
/** Any other contact properties by their internal names — `address`, `city`, `state`, `zip`, `country`, a custom one. */
|
|
16
|
+
properties?: Record<string, string | null | undefined>;
|
|
15
17
|
}
|
|
16
18
|
/** A static list as `listStaticLists` returns it. */
|
|
17
19
|
export interface HubSpotList {
|
|
@@ -73,6 +73,8 @@ class HubSpotGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
|
|
|
73
73
|
['lastname', contact.lastName],
|
|
74
74
|
['phone', contact.phone],
|
|
75
75
|
['company', contact.company],
|
|
76
|
+
// ⓘ After the named ones, so `properties` cannot replace the email the contact is found by.
|
|
77
|
+
...Object.entries(contact.properties ?? {}).filter(([name]) => /^[a-z0-9_]{1,100}$/.test(name) && name !== 'email'),
|
|
76
78
|
];
|
|
77
79
|
for (const [name, value] of given) {
|
|
78
80
|
if (text(value)) {
|
|
@@ -10,11 +10,25 @@ export type MailchimpStatusIfNew = 'transactional' | 'pending' | 'subscribed';
|
|
|
10
10
|
export declare const MAILCHIMP_STATUSES_IF_NEW: MailchimpStatusIfNew[];
|
|
11
11
|
export interface MailchimpMember {
|
|
12
12
|
email: string;
|
|
13
|
-
/**
|
|
14
|
-
|
|
13
|
+
/**
|
|
14
|
+
* By merge tag — FNAME, LNAME (every audience has them unless the host removed them), ADDRESS as an object (`addr1`,
|
|
15
|
+
* `addr2`, `city`, `state`, `zip`, `country` — Mailchimp refuses one without addr1, city, state and zip). Empty values
|
|
16
|
+
* are not sent.
|
|
17
|
+
*/
|
|
18
|
+
mergeFields?: Record<string, string | MailchimpAddress | null | undefined>;
|
|
15
19
|
/** Default `transactional`: on the audience, not subscribed to marketing. */
|
|
16
20
|
statusIfNew?: MailchimpStatusIfNew;
|
|
17
21
|
}
|
|
22
|
+
/** The ADDRESS merge field's value. */
|
|
23
|
+
export interface MailchimpAddress {
|
|
24
|
+
addr1: string;
|
|
25
|
+
addr2?: string | null;
|
|
26
|
+
city: string;
|
|
27
|
+
state: string;
|
|
28
|
+
zip: string;
|
|
29
|
+
/** Two letters (`CA`); left out, the audience's default country. */
|
|
30
|
+
country?: string | null;
|
|
31
|
+
}
|
|
18
32
|
/** An audience as `listAudiences` returns it. */
|
|
19
33
|
export interface MailchimpAudience {
|
|
20
34
|
id: string;
|
|
@@ -27,6 +41,11 @@ export declare const MAILCHIMP_NOTE_MAX = 1000;
|
|
|
27
41
|
export declare const MAILCHIMP_TAG_MAX = 100;
|
|
28
42
|
/** The data centre at the end of an API key (`us21`), or null. Pure. */
|
|
29
43
|
export declare const mailchimpDataCenterOf: (apiKey: unknown) => string | null;
|
|
44
|
+
/**
|
|
45
|
+
* An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
|
|
46
|
+
* only as two letters — or null. Pure.
|
|
47
|
+
*/
|
|
48
|
+
export declare const mailchimpAddressOf: (value: Partial<MailchimpAddress> | null | undefined) => Record<string, string> | null;
|
|
30
49
|
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
31
50
|
export declare const mailchimpSubscriberHash: (email: string) => string;
|
|
32
51
|
declare class MailchimpGw extends BaseExternalApiGateway<MailchimpSettings> {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MailchimpGw = exports.mailchimpSubscriberHash = exports.mailchimpDataCenterOf = exports.MAILCHIMP_TAG_MAX = exports.MAILCHIMP_NOTE_MAX = exports.MAILCHIMP_STATUSES_IF_NEW = void 0;
|
|
3
|
+
exports.MailchimpGw = exports.mailchimpSubscriberHash = exports.mailchimpAddressOf = exports.mailchimpDataCenterOf = exports.MAILCHIMP_TAG_MAX = exports.MAILCHIMP_NOTE_MAX = exports.MAILCHIMP_STATUSES_IF_NEW = void 0;
|
|
4
4
|
// ./src/gateways/MailchimpGw.ts
|
|
5
5
|
//
|
|
6
6
|
// Mailchimp's Marketing API (https://mailchimp.com/developer/marketing/api/) — the calls that put a person into a host's
|
|
@@ -33,6 +33,32 @@ const mailchimpDataCenterOf = (apiKey) => {
|
|
|
33
33
|
return match ? match[1].toLowerCase() : null;
|
|
34
34
|
};
|
|
35
35
|
exports.mailchimpDataCenterOf = mailchimpDataCenterOf;
|
|
36
|
+
/**
|
|
37
|
+
* An address as Mailchimp takes it — addr1, city, state and zip all there (it refuses the member otherwise), the country
|
|
38
|
+
* only as two letters — or null. Pure.
|
|
39
|
+
*/
|
|
40
|
+
const mailchimpAddressOf = (value) => {
|
|
41
|
+
const parts = {
|
|
42
|
+
addr1: text(value?.addr1),
|
|
43
|
+
addr2: text(value?.addr2),
|
|
44
|
+
city: text(value?.city),
|
|
45
|
+
state: text(value?.state),
|
|
46
|
+
zip: text(value?.zip),
|
|
47
|
+
};
|
|
48
|
+
if (!parts.addr1 || !parts.city || !parts.state || !parts.zip) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const country = text(value?.country).toUpperCase();
|
|
52
|
+
const out = { addr1: parts.addr1, city: parts.city, state: parts.state, zip: parts.zip };
|
|
53
|
+
if (parts.addr2) {
|
|
54
|
+
out.addr2 = parts.addr2;
|
|
55
|
+
}
|
|
56
|
+
if (/^[A-Z]{2}$/.test(country)) {
|
|
57
|
+
out.country = country;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
};
|
|
61
|
+
exports.mailchimpAddressOf = mailchimpAddressOf;
|
|
36
62
|
/** The member's id in Mailchimp's paths: the MD5 of the lowercase email. Pure. */
|
|
37
63
|
const mailchimpSubscriberHash = (email) => (0, crypto_1.createHash)('md5').update(text(email).toLowerCase()).digest('hex');
|
|
38
64
|
exports.mailchimpSubscriberHash = mailchimpSubscriberHash;
|
|
@@ -101,7 +127,17 @@ class MailchimpGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
|
|
|
101
127
|
: 'transactional';
|
|
102
128
|
const mergeFields = {};
|
|
103
129
|
for (const [tag, value] of Object.entries(member.mergeFields ?? {})) {
|
|
104
|
-
if (
|
|
130
|
+
if (!/^[A-Z0-9_]{1,10}$/.test(tag)) {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (value && typeof value === 'object') {
|
|
134
|
+
// An address goes whole or not at all: Mailchimp refuses the member over a partial one.
|
|
135
|
+
const address = (0, exports.mailchimpAddressOf)(value);
|
|
136
|
+
if (address) {
|
|
137
|
+
mergeFields[tag] = address;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
else if (text(value)) {
|
|
105
141
|
mergeFields[tag] = text(value);
|
|
106
142
|
}
|
|
107
143
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
private tokensOf;
|
|
58
|
+
private tokenCall;
|
|
59
|
+
/** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
|
|
60
|
+
authorizeUrl(args: {
|
|
61
|
+
state: string;
|
|
62
|
+
redirectUri: string;
|
|
63
|
+
scope?: string;
|
|
64
|
+
}): string;
|
|
65
|
+
/** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
|
|
66
|
+
exchangeCode(code: string, redirectUri: string): Promise<OpResult>;
|
|
67
|
+
/** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
|
|
68
|
+
refreshTokens(refreshToken: string): Promise<OpResult>;
|
|
69
|
+
/** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
|
|
70
|
+
revoke(token: string): Promise<OpResult>;
|
|
71
|
+
/**
|
|
72
|
+
* A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
|
|
73
|
+
* OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
|
|
74
|
+
*/
|
|
75
|
+
query(company: QuickBooksCompany, sql: string): Promise<OpResult>;
|
|
76
|
+
/** The company's name and country. OK with `{ name, country, raw }`. */
|
|
77
|
+
companyInfo(company: QuickBooksCompany): Promise<OpResult>;
|
|
78
|
+
/** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
|
|
79
|
+
preferences(company: QuickBooksCompany): Promise<OpResult>;
|
|
80
|
+
/** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase). OK with the record. */
|
|
81
|
+
private create;
|
|
82
|
+
/** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
|
|
83
|
+
createItem(company: QuickBooksCompany, item: {
|
|
84
|
+
name: string;
|
|
85
|
+
incomeAccountId: string;
|
|
86
|
+
description?: string | null;
|
|
87
|
+
}, requestId: string): Promise<OpResult>;
|
|
88
|
+
/** A customer by display name (unique in the company across customers, vendors and employees). */
|
|
89
|
+
createCustomer(company: QuickBooksCompany, customer: {
|
|
90
|
+
displayName: string;
|
|
91
|
+
email?: string | null;
|
|
92
|
+
}, requestId: string): Promise<OpResult>;
|
|
93
|
+
/** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
|
|
94
|
+
createSalesReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
95
|
+
/** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
|
|
96
|
+
createRefundReceipt(company: QuickBooksCompany, receipt: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
97
|
+
/** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
|
|
98
|
+
createPurchase(company: QuickBooksCompany, purchase: Record<string, unknown>, requestId: string): Promise<OpResult>;
|
|
99
|
+
}
|
|
100
|
+
export { QuickBooksGw };
|
|
@@ -0,0 +1,327 @@
|
|
|
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
|
+
tokensOf(body) {
|
|
127
|
+
const accessToken = text(body?.access_token);
|
|
128
|
+
const refreshToken = text(body?.refresh_token);
|
|
129
|
+
if (!accessToken || !refreshToken) {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
const now = Date.now();
|
|
133
|
+
const expiresIn = Number(body?.expires_in) || 3600;
|
|
134
|
+
const refreshIn = Number(body?.x_refresh_token_expires_in);
|
|
135
|
+
return {
|
|
136
|
+
accessToken,
|
|
137
|
+
refreshToken,
|
|
138
|
+
expiresAt: new Date(now + expiresIn * 1000).toISOString(),
|
|
139
|
+
refreshExpiresAt: Number.isFinite(refreshIn) && refreshIn > 0 ? new Date(now + refreshIn * 1000).toISOString() : null,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
async tokenCall(form, secrets) {
|
|
143
|
+
if (!this.isConfigured()) {
|
|
144
|
+
return this.notConfigured();
|
|
145
|
+
}
|
|
146
|
+
const result = await this.requestWithRetries({
|
|
147
|
+
url: exports.QUICKBOOKS_TOKEN_URL,
|
|
148
|
+
method: 'POST',
|
|
149
|
+
headers: {
|
|
150
|
+
Authorization: this.basicAuth(),
|
|
151
|
+
Accept: 'application/json',
|
|
152
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
153
|
+
},
|
|
154
|
+
body: new URLSearchParams(form),
|
|
155
|
+
secrets,
|
|
156
|
+
});
|
|
157
|
+
if (result.didFail()) {
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
// ⓘ The reply is scrubbed of the values this call SENT (the code, the old refresh token) — the new tokens are not
|
|
161
|
+
// among them, so they arrive intact.
|
|
162
|
+
const tokens = this.tokensOf(result.getDataFirst()?.body);
|
|
163
|
+
return tokens
|
|
164
|
+
? api_helpers_1.OpResult.ok([tokens])
|
|
165
|
+
: api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, null, 'Intuit answered without the tokens');
|
|
166
|
+
}
|
|
167
|
+
/** Where to send the host to connect a company (Intuit's consent screen). Pure; '' when the gateway is not configured. */
|
|
168
|
+
authorizeUrl(args) {
|
|
169
|
+
if (!this.isConfigured()) {
|
|
170
|
+
return '';
|
|
171
|
+
}
|
|
172
|
+
const params = new URLSearchParams({
|
|
173
|
+
client_id: text(this.settings.clientId),
|
|
174
|
+
response_type: 'code',
|
|
175
|
+
scope: args.scope || exports.QUICKBOOKS_ACCOUNTING_SCOPE,
|
|
176
|
+
redirect_uri: text(args.redirectUri),
|
|
177
|
+
state: text(args.state),
|
|
178
|
+
});
|
|
179
|
+
return `${exports.QUICKBOOKS_AUTHORIZE_URL}?${params.toString()}`;
|
|
180
|
+
}
|
|
181
|
+
/** The code Intuit sent back, exchanged for the company's tokens. OK with a `QuickBooksTokens`. Never throws. */
|
|
182
|
+
async exchangeCode(code, redirectUri) {
|
|
183
|
+
if (!text(code) || !text(redirectUri)) {
|
|
184
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The code and the redirect address are needed');
|
|
185
|
+
}
|
|
186
|
+
return this.tokenCall({ grant_type: 'authorization_code', code: text(code), redirect_uri: text(redirectUri) }, [
|
|
187
|
+
text(code),
|
|
188
|
+
]);
|
|
189
|
+
}
|
|
190
|
+
/** New tokens for a refresh token — ⚠ store the NEW refresh token it returns. OK with a `QuickBooksTokens`. */
|
|
191
|
+
async refreshTokens(refreshToken) {
|
|
192
|
+
if (!text(refreshToken)) {
|
|
193
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The refresh token is needed');
|
|
194
|
+
}
|
|
195
|
+
return this.tokenCall({ grant_type: 'refresh_token', refresh_token: text(refreshToken) }, [text(refreshToken)]);
|
|
196
|
+
}
|
|
197
|
+
/** Disconnects: the token (refresh or access) and everything issued with it stop working. OK with `{ revoked: true }`. */
|
|
198
|
+
async revoke(token) {
|
|
199
|
+
if (!this.isConfigured()) {
|
|
200
|
+
return this.notConfigured();
|
|
201
|
+
}
|
|
202
|
+
if (!text(token)) {
|
|
203
|
+
return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The token is needed');
|
|
204
|
+
}
|
|
205
|
+
const result = await this.requestWithRetries({
|
|
206
|
+
url: exports.QUICKBOOKS_REVOKE_URL,
|
|
207
|
+
method: 'POST',
|
|
208
|
+
headers: { Authorization: this.basicAuth(), Accept: 'application/json' },
|
|
209
|
+
json: { token: text(token) },
|
|
210
|
+
secrets: [text(token)],
|
|
211
|
+
});
|
|
212
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([{ revoked: true }]);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* A query in Intuit's SQL dialect ("select * from Account where Active = true") — values through `quickBooksQuoted`.
|
|
216
|
+
* OK with the rows of the entity asked for (`QueryResponse.<Entity>`, [] when none). Never throws.
|
|
217
|
+
*/
|
|
218
|
+
async query(company, sql) {
|
|
219
|
+
if (!this.isConfigured()) {
|
|
220
|
+
return this.notConfigured();
|
|
221
|
+
}
|
|
222
|
+
const bad = this.badCompany(company);
|
|
223
|
+
if (bad) {
|
|
224
|
+
return bad;
|
|
225
|
+
}
|
|
226
|
+
const result = await this.companyCall(company, 'GET', '/query', { query: text(sql) });
|
|
227
|
+
if (result.didFail()) {
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
const response = result.getDataFirst()?.body?.QueryResponse ?? {};
|
|
231
|
+
const rows = Object.values(response).find((v) => Array.isArray(v));
|
|
232
|
+
return api_helpers_1.OpResult.ok(Array.isArray(rows) ? rows : []);
|
|
233
|
+
}
|
|
234
|
+
/** The company's name and country. OK with `{ name, country, raw }`. */
|
|
235
|
+
async companyInfo(company) {
|
|
236
|
+
if (!this.isConfigured()) {
|
|
237
|
+
return this.notConfigured();
|
|
238
|
+
}
|
|
239
|
+
const bad = this.badCompany(company);
|
|
240
|
+
if (bad) {
|
|
241
|
+
return bad;
|
|
242
|
+
}
|
|
243
|
+
const result = await this.companyCall(company, 'GET', `/companyinfo/${text(company.realmId)}`, {});
|
|
244
|
+
if (result.didFail()) {
|
|
245
|
+
return result;
|
|
246
|
+
}
|
|
247
|
+
const info = result.getDataFirst()?.body?.CompanyInfo ?? {};
|
|
248
|
+
return api_helpers_1.OpResult.ok([
|
|
249
|
+
{
|
|
250
|
+
name: text(info.CompanyName) || text(info.LegalName) || null,
|
|
251
|
+
country: text(info.Country) || null,
|
|
252
|
+
raw: info,
|
|
253
|
+
},
|
|
254
|
+
]);
|
|
255
|
+
}
|
|
256
|
+
/** The company's preferences (sales tax on, multicurrency, home currency). OK with the raw `Preferences`. */
|
|
257
|
+
async preferences(company) {
|
|
258
|
+
if (!this.isConfigured()) {
|
|
259
|
+
return this.notConfigured();
|
|
260
|
+
}
|
|
261
|
+
const bad = this.badCompany(company);
|
|
262
|
+
if (bad) {
|
|
263
|
+
return bad;
|
|
264
|
+
}
|
|
265
|
+
const result = await this.companyCall(company, 'GET', '/preferences', {});
|
|
266
|
+
return result.didFail() ? result : api_helpers_1.OpResult.ok([result.getDataFirst()?.body?.Preferences ?? {}]);
|
|
267
|
+
}
|
|
268
|
+
/** Creates one record of `entity` (Item, Customer, SalesReceipt, RefundReceipt, Purchase). OK with the record. */
|
|
269
|
+
async create(company, entity, body, requestId) {
|
|
270
|
+
if (!this.isConfigured()) {
|
|
271
|
+
return this.notConfigured();
|
|
272
|
+
}
|
|
273
|
+
const bad = this.badCompany(company);
|
|
274
|
+
if (bad) {
|
|
275
|
+
return bad;
|
|
276
|
+
}
|
|
277
|
+
const id = text(requestId);
|
|
278
|
+
if (!id || id.length > exports.QUICKBOOKS_REQUEST_ID_MAX) {
|
|
279
|
+
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`);
|
|
280
|
+
}
|
|
281
|
+
const result = await this.companyCall(company, 'POST', `/${entity.toLowerCase()}`, { requestid: id }, body);
|
|
282
|
+
if (result.didFail()) {
|
|
283
|
+
return result;
|
|
284
|
+
}
|
|
285
|
+
const record = result.getDataFirst()?.body?.[entity] ?? null;
|
|
286
|
+
return record?.Id
|
|
287
|
+
? api_helpers_1.OpResult.ok([record])
|
|
288
|
+
: api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, null, `QuickBooks answered without the ${entity}`);
|
|
289
|
+
}
|
|
290
|
+
/** A Service item booked on an income account (`IncomeAccountRef`) — a sales line's account is its item's. */
|
|
291
|
+
createItem(company, item, requestId) {
|
|
292
|
+
const name = (0, exports.quickBooksNameOf)(item?.name);
|
|
293
|
+
if (!name || !text(item?.incomeAccountId)) {
|
|
294
|
+
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'));
|
|
295
|
+
}
|
|
296
|
+
return this.create(company, 'Item', {
|
|
297
|
+
Name: name,
|
|
298
|
+
Type: 'Service',
|
|
299
|
+
IncomeAccountRef: { value: text(item.incomeAccountId) },
|
|
300
|
+
...(text(item.description) ? { Description: text(item.description).slice(0, 4000) } : {}),
|
|
301
|
+
}, requestId);
|
|
302
|
+
}
|
|
303
|
+
/** A customer by display name (unique in the company across customers, vendors and employees). */
|
|
304
|
+
createCustomer(company, customer, requestId) {
|
|
305
|
+
const displayName = (0, exports.quickBooksNameOf)(customer?.displayName);
|
|
306
|
+
if (!displayName) {
|
|
307
|
+
return Promise.resolve(api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A customer needs a name'));
|
|
308
|
+
}
|
|
309
|
+
return this.create(company, 'Customer', {
|
|
310
|
+
DisplayName: displayName,
|
|
311
|
+
...(text(customer.email).includes('@') ? { PrimaryEmailAddr: { Address: text(customer.email) } } : {}),
|
|
312
|
+
}, requestId);
|
|
313
|
+
}
|
|
314
|
+
/** A sale paid at once (the body as Intuit takes it — `Line`, `DepositToAccountRef`, …). */
|
|
315
|
+
createSalesReceipt(company, receipt, requestId) {
|
|
316
|
+
return this.create(company, 'SalesReceipt', receipt, requestId);
|
|
317
|
+
}
|
|
318
|
+
/** Money given back on a sale (the body as Intuit takes it — `Line`, `DepositToAccountRef` it is paid from, …). */
|
|
319
|
+
createRefundReceipt(company, receipt, requestId) {
|
|
320
|
+
return this.create(company, 'RefundReceipt', receipt, requestId);
|
|
321
|
+
}
|
|
322
|
+
/** Money that went out of an account — a processor's or a platform's fee (`AccountRef` it left, expense lines). */
|
|
323
|
+
createPurchase(company, purchase, requestId) {
|
|
324
|
+
return this.create(company, 'Purchase', purchase, requestId);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
exports.QuickBooksGw = QuickBooksGw;
|
package/build/gateways/index.js
CHANGED
|
@@ -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);
|