@company-six/qbosync 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -2
- package/dist/client.d.ts +163 -0
- package/dist/client.js +273 -0
- package/dist/connectRequest.d.ts +126 -0
- package/dist/connectRequest.js +188 -0
- package/dist/connection.d.ts +108 -0
- package/dist/connection.js +191 -0
- package/dist/contract/answers.d.ts +103 -0
- package/dist/contract/answers.js +47 -0
- package/dist/contract/common.d.ts +107 -0
- package/dist/contract/common.js +86 -0
- package/dist/contract/creditMemo.d.ts +77 -0
- package/dist/contract/creditMemo.js +65 -0
- package/dist/contract/index.d.ts +145 -0
- package/dist/contract/index.js +39 -0
- package/dist/contract/invoice.d.ts +88 -0
- package/dist/contract/invoice.js +74 -0
- package/dist/contract/protocol.d.ts +28 -0
- package/dist/contract/protocol.js +26 -0
- package/dist/contract/statusReport.d.ts +20 -0
- package/dist/contract/statusReport.js +17 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/statusReports.d.ts +82 -0
- package/dist/statusReports.js +129 -0
- package/dist/supabase.d.ts +38 -0
- package/dist/supabase.js +67 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +31 -0
- package/package.json +42 -4
- package/sql/001_connection.sql +368 -0
package/README.md
CHANGED
|
@@ -1,3 +1,179 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @company-six/qbosync
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Connect your app to QBO Sync, which posts your sales to each company's QuickBooks. Your app sends invoices and credit memos; QBO Sync checks them, posts them and tells your app what happened to each one.
|
|
4
|
+
|
|
5
|
+
Server-side only (Node 20 or later): it holds your app's tokens. TypeScript types are included (TypeScript 5 or later).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @company-six/qbosync zod
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Before you start, ask Company Six staff to set your app's **callback address**, the https address QBO Sync sends status reports to, and to turn on **Sign people in** if your app has a Connect button for its companies.
|
|
14
|
+
|
|
15
|
+
## 1. Add the two tables
|
|
16
|
+
|
|
17
|
+
Your app keeps its connection in its own database. Run [`sql/001_connection.sql`](sql/001_connection.sql) once (in the Supabase SQL editor, for instance). It adds two one-row tables that only your server can read, with the locks that keep two servers from spending the same renewal token.
|
|
18
|
+
|
|
19
|
+
Nothing else needs storing: status reports are checked with QBO Sync's public key, so your app keeps no signing secret.
|
|
20
|
+
|
|
21
|
+
**Coming from a hand-built client?** Compare your functions with `sql/001_connection.sql` before switching. Supabase finds a function by the names of its arguments, so one that takes an extra argument (an old `p_signing_secret`, say) or names one differently is not found, and every renewal save fails. A renewal that cannot be saved loses the new renewal token, and QBO Sync then ends the connection. Change the functions first, in a way the old code still works with (give the extra argument a default), switch, then drop what is left.
|
|
22
|
+
|
|
23
|
+
## 2. Create the client
|
|
24
|
+
|
|
25
|
+
On Supabase, with a **service-role** client:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { QbosyncClient } from "@company-six/qbosync";
|
|
29
|
+
import { createSupabaseStores } from "@company-six/qbosync/supabase";
|
|
30
|
+
|
|
31
|
+
export const qbosync = new QbosyncClient({
|
|
32
|
+
baseUrl: process.env.QBOSYNC_URL!,
|
|
33
|
+
appName: "my-app",
|
|
34
|
+
...createSupabaseStores(supabase),
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Make **one client per server** and reuse it, as above: it keeps QBO Sync's public keys once fetched, so a client made per request would fetch them again for every status report.
|
|
39
|
+
|
|
40
|
+
On another database, implement `ConnectionStore` and `ConnectRequestStore` (their comments say what each method must promise) and pass them as `connections` and `connectRequests`.
|
|
41
|
+
|
|
42
|
+
## 3. Connect
|
|
43
|
+
|
|
44
|
+
When an admin of your app presses Connect:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
const opened = await qbosync.openConnectRequest({
|
|
48
|
+
redirectUri: "https://my-app.com/qbosync/callback",
|
|
49
|
+
startedBy: admin.email,
|
|
50
|
+
});
|
|
51
|
+
if (opened.ok) redirect(opened.verificationUri);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
A QBO Sync administrator approves then, or later. Collect the connection from a job your app runs on a schedule, and from the page the admin comes back to. It is safe to call often: only one server collects.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const collected = await qbosync.collectConnectRequest();
|
|
58
|
+
// collected.state: "connected", "waiting", "denied", "expired", "failed", "none", "other" or "unavailable"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
From then on the client renews its tokens by itself. If QBO Sync ends the connection, calls answer `reason: "ended"` and an admin presses Connect again.
|
|
62
|
+
|
|
63
|
+
For a settings page, or to know whether there is anything to send with, read the connection without calling QBO Sync:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const now = await qbosync.connectionState();
|
|
67
|
+
// now.state: "connected" (who, when), "ended" (when, and why in words), "not_connected" or "unavailable"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## 4. Connect a company
|
|
71
|
+
|
|
72
|
+
A company comes to exist in QBO Sync when your app asks for a sign-in link for it. This is what a company's own Connect button calls:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
const link = await qbosync.createSignInLink({ email: user.email, company: "Acme", role: "company_user" });
|
|
76
|
+
if (link.ok) redirect(link.url); // works once, for five minutes
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The link is always QBO Sync's own sign-in page on the address the client calls; any other answer is refused as `unexpected_answer`. If QBO Sync refuses (the app may not sign people in yet, say), `link.detail` is its message, written for the person.
|
|
80
|
+
|
|
81
|
+
`company` is the name your documents carry as `company_key`. Ask which of your companies have connected with `qbosync.listCompanies()`, and send a company's documents only once it has: QBO Sync refuses the rest.
|
|
82
|
+
|
|
83
|
+
## 5. Send documents
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
const sent = await qbosync.sendDocuments([invoice, creditMemo]);
|
|
87
|
+
|
|
88
|
+
for (const { source_ref, outcome } of sent.results) {
|
|
89
|
+
if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it. Never send it again.
|
|
90
|
+
if (outcome.kind === "parked") needsAPerson(source_ref, outcome.error); // sending again changes nothing
|
|
91
|
+
if (outcome.kind === "failure") retryLater(source_ref); // not the document's fault
|
|
92
|
+
}
|
|
93
|
+
if (!sent.ok) console.error(sent.error); // a batch failed; what has no result here is safe to send again
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Each document is checked against the contract first; one that fails is not sent and does not stop the others. You can run the same check yourself, in the browser too, with `checkDocument` from `@company-six/qbosync/contract`.
|
|
97
|
+
|
|
98
|
+
**A document is sent once.** QBO Sync keeps it exactly as first received, so `version` is 1 and a later version is refused. To correct an invoice, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is always safe: QBO Sync answers `unchanged`.
|
|
99
|
+
|
|
100
|
+
Apps send invoices and credit memos only. Payments, refunds and payouts reach QBO Sync through its own connectors, matched to your invoices by `order_ref`, so give every invoice the `order_ref` of its order.
|
|
101
|
+
|
|
102
|
+
## 6. Receive status reports
|
|
103
|
+
|
|
104
|
+
QBO Sync posts what happened to your documents to your callback address + `STATUS_REPORT_PATH` (`/api/qbosync/status`). Pass the body **exactly as it arrived**, before any parsing:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { SIGNATURE_HEADER, isNewerReport } from "@company-six/qbosync";
|
|
108
|
+
|
|
109
|
+
export async function POST(req: Request) {
|
|
110
|
+
const checked = await qbosync.checkStatusReports(await req.text(), req.headers.get(SIGNATURE_HEADER));
|
|
111
|
+
if (!checked.ok) return Response.json({ error: checked.error }, { status: checked.status });
|
|
112
|
+
|
|
113
|
+
// Every report in the order it came: one that reads, or why it does not.
|
|
114
|
+
const results = [];
|
|
115
|
+
for (const entry of checked.entries) {
|
|
116
|
+
if ("invalid" in entry) {
|
|
117
|
+
const { source_ref = "", document_type = "", reasons } = entry.invalid;
|
|
118
|
+
results.push({ source_ref, document_type, result: "error", reason: reasons.join("; ") });
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const { report } = entry;
|
|
122
|
+
const id = { source_ref: report.source_ref, document_type: report.document_type };
|
|
123
|
+
const row = await findDocument(report.source_ref);
|
|
124
|
+
if (!row) results.push({ ...id, result: "unknown" });
|
|
125
|
+
else if (!isNewerReport(report, row.lastSequence)) results.push({ ...id, result: "stale" });
|
|
126
|
+
else {
|
|
127
|
+
await saveStatus(row, report);
|
|
128
|
+
results.push({ ...id, result: "applied" });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return Response.json({ results });
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Answer `error` for a report you could not apply, and for every invalid one: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one. (`checked.reports` and `checked.invalid` hold the same reports split in two, for an app that does not answer in order.)
|
|
136
|
+
|
|
137
|
+
### Testing your status report route
|
|
138
|
+
|
|
139
|
+
Only QBO Sync can sign a real report, so tests make their own key. `@company-six/qbosync/testing` signs a call the way QBO Sync does and answers the public half where the client looks for it:
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
import { SIGNATURE_HEADER } from "@company-six/qbosync";
|
|
143
|
+
import { createTestSigningKey, signStatusReports, testKeysFetch } from "@company-six/qbosync/testing";
|
|
144
|
+
|
|
145
|
+
const key = createTestSigningKey();
|
|
146
|
+
const client = new QbosyncClient({ baseUrl, appName: "my-app", ...stores, fetch: testKeysFetch(baseUrl, [key]) });
|
|
147
|
+
const { body, headers } = signStatusReports(key, { reports: [report] }); // a third argument makes an old signature
|
|
148
|
+
const checked = await client.checkStatusReports(body, headers[SIGNATURE_HEADER]);
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Never use these outside tests: anyone can make such a key.
|
|
152
|
+
|
|
153
|
+
## 7. Compare
|
|
154
|
+
|
|
155
|
+
For a daily report, name the documents your app created that day:
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
const report = await qbosync.documentReport(refs);
|
|
159
|
+
// each entry: its status, QuickBooks number, what was posted and the nightly check, or sync_status "unknown" if never received
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## When a call fails
|
|
163
|
+
|
|
164
|
+
Nothing here throws for something QBO Sync or the network did. Every call answers `{ ok: true, ... }` or a failure with an `error` you can show a person, and a `reason`:
|
|
165
|
+
|
|
166
|
+
| `reason` | Meaning | What to do |
|
|
167
|
+
|---|---|---|
|
|
168
|
+
| `not_connected` | Nobody has connected the app yet. | An admin presses Connect. |
|
|
169
|
+
| `ended` | QBO Sync ended the connection. | An admin presses Connect again. |
|
|
170
|
+
| `unavailable` | QBO Sync or your database could not answer. | Try again later. |
|
|
171
|
+
| `rate_limited` | Over your limit. `retryAfterSeconds` says how long to wait; a wait of five seconds or less is handled for you. | Try again after that. |
|
|
172
|
+
| `rejected` | QBO Sync refused the request. | Show `detail`, QBO Sync's own message, when there is one. |
|
|
173
|
+
| `unexpected_answer` | QBO Sync answered, but with something this version cannot use (a link to another address, a list that does not line up). Nothing was applied. | Try again later; if it keeps happening, update the package. |
|
|
174
|
+
|
|
175
|
+
`status` is set whenever QBO Sync answered. With `ended`, `error` says why in words and `endedReason` keeps QBO Sync's own reason for your logs; `endedReasonInWords(reason)` (also in `@company-six/qbosync/contract`, safe in a browser) says a stored reason the same way.
|
|
176
|
+
|
|
177
|
+
## Versions
|
|
178
|
+
|
|
179
|
+
Version 1 of the protocol only grows: new fields are optional, and none is removed or renamed. This package follows semver: a patch fixes something, a minor adds something, and a major may break your code.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { type CollectResult, type ConnectRequestStore, type OpenResult } from "./connectRequest.ts";
|
|
2
|
+
import { type ConnectionStore, type Log } from "./connection.ts";
|
|
3
|
+
import { type SignInRole } from "./contract/protocol.ts";
|
|
4
|
+
import { type AppCompanyStatus, type ReceiveResult, type ReportEntry, type SendOutcome } from "./contract/answers.ts";
|
|
5
|
+
import { type CheckedStatusReports } from "./statusReports.ts";
|
|
6
|
+
/**
|
|
7
|
+
* The client an app uses to talk to QBO Sync. Server-side only: it holds the app's tokens.
|
|
8
|
+
*
|
|
9
|
+
* It never throws for something QBO Sync or the network did: every call answers `{ ok: true, ... }` or
|
|
10
|
+
* `{ ok: false, error, reason }`, with a sentence fit to show a person.
|
|
11
|
+
*/
|
|
12
|
+
export interface QbosyncClientConfig {
|
|
13
|
+
/** QBO Sync's address. */
|
|
14
|
+
baseUrl: string;
|
|
15
|
+
/** The app's name, sent on its first Connect; a QBO Sync administrator matches it to the app. */
|
|
16
|
+
appName: string;
|
|
17
|
+
connections: ConnectionStore;
|
|
18
|
+
connectRequests: ConnectRequestStore;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
/** Where the SDK reports what it cannot return; `console.error` by default. */
|
|
21
|
+
log?: Log;
|
|
22
|
+
/** The longest a call waits for QBO Sync's rate limit before answering `rate_limited`. Default 5 seconds. */
|
|
23
|
+
maxRetryAfterMs?: number;
|
|
24
|
+
/** How long one call may take. Default 60 seconds. */
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Why a call failed. `not_connected` and `ended` need an admin to press Connect; `unavailable` and
|
|
29
|
+
* `rate_limited` are worth trying again; `rejected` is QBO Sync refusing the request (read `detail`);
|
|
30
|
+
* `unexpected_answer` is QBO Sync answering something this version cannot use, such as a link to another
|
|
31
|
+
* address or a list that does not line up with what was asked.
|
|
32
|
+
*/
|
|
33
|
+
export type FailureReason = "not_connected" | "ended" | "unavailable" | "rate_limited" | "rejected" | "unexpected_answer";
|
|
34
|
+
export interface Failure {
|
|
35
|
+
ok: false;
|
|
36
|
+
/** A sentence fit to show a person. */
|
|
37
|
+
error: string;
|
|
38
|
+
reason: FailureReason;
|
|
39
|
+
/** QBO Sync's status, when it answered. */
|
|
40
|
+
status?: number;
|
|
41
|
+
/** With `rate_limited`: how long QBO Sync asks to wait. */
|
|
42
|
+
retryAfterSeconds?: number;
|
|
43
|
+
/** With `rejected`: QBO Sync's own message, as it sent it. QBO Sync writes these for people. */
|
|
44
|
+
detail?: string;
|
|
45
|
+
/** With `ended`: QBO Sync's own reason, as stored (`invalid_grant: ...`), for logs; `error` says it in words. */
|
|
46
|
+
endedReason?: string;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The stored connection, without asking QBO Sync anything: for a settings page, or to decide whether an
|
|
50
|
+
* app has anything to send with. A connection made against another QBO Sync address counts as none.
|
|
51
|
+
*/
|
|
52
|
+
export type ConnectionState = {
|
|
53
|
+
state: "not_connected";
|
|
54
|
+
} | {
|
|
55
|
+
state: "connected";
|
|
56
|
+
connectedBy: string;
|
|
57
|
+
connectedAt: string;
|
|
58
|
+
renewedAt: string | null;
|
|
59
|
+
clientId: string;
|
|
60
|
+
redirectUri: string;
|
|
61
|
+
} | {
|
|
62
|
+
state: "ended";
|
|
63
|
+
connectedBy: string;
|
|
64
|
+
connectedAt: string;
|
|
65
|
+
endedAt: string;
|
|
66
|
+
/** Why, in words (`endedReasonInWords`). */
|
|
67
|
+
error: string;
|
|
68
|
+
/** QBO Sync's own reason, as stored. */
|
|
69
|
+
endedReason: string | null;
|
|
70
|
+
}
|
|
71
|
+
/** The store could not be read. */
|
|
72
|
+
| {
|
|
73
|
+
state: "unavailable";
|
|
74
|
+
error: string;
|
|
75
|
+
};
|
|
76
|
+
/** QBO Sync's sign-in page: the only page `createSignInLink` sends a browser to. */
|
|
77
|
+
export declare const SIGN_IN_PAGE_PATH = "/auth/link";
|
|
78
|
+
/** One document's result, in the order given. */
|
|
79
|
+
export interface DocumentResult {
|
|
80
|
+
index: number;
|
|
81
|
+
source_ref: string | null;
|
|
82
|
+
/** What to do about it. Not sent because it failed the contract: `parked`, without calling QBO Sync. */
|
|
83
|
+
outcome: SendOutcome;
|
|
84
|
+
/** QBO Sync's own answer; absent when it was not sent. */
|
|
85
|
+
answer?: ReceiveResult;
|
|
86
|
+
}
|
|
87
|
+
/** `Failure` with `results`: a batch failed, and the documents in it or after it have no result. They are safe to send again. */
|
|
88
|
+
export type SendResult = {
|
|
89
|
+
ok: true;
|
|
90
|
+
results: DocumentResult[];
|
|
91
|
+
} | (Failure & {
|
|
92
|
+
results: DocumentResult[];
|
|
93
|
+
});
|
|
94
|
+
export declare class QbosyncClient {
|
|
95
|
+
private readonly config;
|
|
96
|
+
private readonly baseUrl;
|
|
97
|
+
private readonly fetchImpl;
|
|
98
|
+
private readonly log;
|
|
99
|
+
private readonly keys;
|
|
100
|
+
constructor(config: QbosyncClientConfig);
|
|
101
|
+
/** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
|
|
102
|
+
openConnectRequest(input: {
|
|
103
|
+
redirectUri: string;
|
|
104
|
+
startedBy: string;
|
|
105
|
+
}): Promise<OpenResult>;
|
|
106
|
+
/**
|
|
107
|
+
* Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
|
|
108
|
+
* schedule, when a page opens, when QBO Sync sends the admin's tab back): only one server collects.
|
|
109
|
+
*/
|
|
110
|
+
collectConnectRequest(options?: {
|
|
111
|
+
requestId?: string;
|
|
112
|
+
waitMs?: number;
|
|
113
|
+
}): Promise<CollectResult>;
|
|
114
|
+
/** The stored connection, asking QBO Sync nothing. Never throws. */
|
|
115
|
+
connectionState(): Promise<ConnectionState>;
|
|
116
|
+
private credential;
|
|
117
|
+
private failed;
|
|
118
|
+
/** One authenticated call: renews on a 401, waits out a short rate limit once. */
|
|
119
|
+
private call;
|
|
120
|
+
/**
|
|
121
|
+
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
122
|
+
* contract first; one that fails is not sent, and does not stop the others.
|
|
123
|
+
*
|
|
124
|
+
* QBO Sync keeps a document exactly as first received, so send each one once, as version 1. To correct
|
|
125
|
+
* one, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is
|
|
126
|
+
* always safe: QBO Sync answers `unchanged` for what it holds.
|
|
127
|
+
*/
|
|
128
|
+
sendDocuments(documents: readonly unknown[]): Promise<SendResult>;
|
|
129
|
+
private sendBatch;
|
|
130
|
+
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
131
|
+
documentReport(refs: readonly string[]): Promise<{
|
|
132
|
+
ok: true;
|
|
133
|
+
documents: ReportEntry[];
|
|
134
|
+
} | Failure>;
|
|
135
|
+
/** Which of the app's companies are connected to QBO Sync, with their QuickBooks and syncing. */
|
|
136
|
+
listCompanies(): Promise<{
|
|
137
|
+
ok: true;
|
|
138
|
+
companies: AppCompanyStatus[];
|
|
139
|
+
} | Failure>;
|
|
140
|
+
/**
|
|
141
|
+
* A one-time link that signs a person in to QBO Sync for one company: send their browser to `url`.
|
|
142
|
+
* This is also how a company comes to exist in QBO Sync, so it is what an app's Connect button for a
|
|
143
|
+
* company calls. The app must be allowed to sign people in (a switch on QBO Sync's side).
|
|
144
|
+
*/
|
|
145
|
+
createSignInLink(input: {
|
|
146
|
+
email: string;
|
|
147
|
+
/** The company as the app names it: its documents' `company_key`. */
|
|
148
|
+
company: string;
|
|
149
|
+
role: SignInRole;
|
|
150
|
+
/** What the app asks its company users to see it called in QBO Sync. */
|
|
151
|
+
appDisplayName?: string;
|
|
152
|
+
}): Promise<{
|
|
153
|
+
ok: true;
|
|
154
|
+
url: string;
|
|
155
|
+
expiresAt: string | null;
|
|
156
|
+
} | Failure>;
|
|
157
|
+
private isSignInPage;
|
|
158
|
+
/**
|
|
159
|
+
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
|
160
|
+
* arrived, before any parsing, and the `X-QBOSync-Signature` header.
|
|
161
|
+
*/
|
|
162
|
+
checkStatusReports(rawBody: string, signature: string | null | undefined): Promise<CheckedStatusReports>;
|
|
163
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { collectConnectRequest, openConnectRequest } from "./connectRequest.js";
|
|
2
|
+
import { currentCredential, sendRenewingOn401 } from "./connection.js";
|
|
3
|
+
import { checkDocument } from "./contract/index.js";
|
|
4
|
+
import { MAX_DOCUMENTS_PER_REQUEST, MAX_REPORT_REFS } from "./contract/protocol.js";
|
|
5
|
+
import { endedReasonInWords, outcomeOf } from "./contract/answers.js";
|
|
6
|
+
import { checkStatusReports, SigningKeys } from "./statusReports.js";
|
|
7
|
+
/** QBO Sync's sign-in page: the only page `createSignInLink` sends a browser to. */
|
|
8
|
+
export const SIGN_IN_PAGE_PATH = "/auth/link";
|
|
9
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
10
|
+
const DEFAULT_MAX_RETRY_AFTER_MS = 5_000;
|
|
11
|
+
const refOf = (document) => {
|
|
12
|
+
const ref = document?.source_ref;
|
|
13
|
+
return typeof ref === "string" ? ref : null;
|
|
14
|
+
};
|
|
15
|
+
function failureOf(res, body) {
|
|
16
|
+
const said = body?.error;
|
|
17
|
+
const detail = typeof said === "string" && said.trim() ? said.trim() : undefined;
|
|
18
|
+
return { ok: false, reason: "rejected", status: res.status, error: `QBO Sync answered ${res.status}${detail ? `: ${detail}` : ""}`, ...(detail ? { detail } : {}) };
|
|
19
|
+
}
|
|
20
|
+
/** QBO Sync answered, but with something this version cannot use. */
|
|
21
|
+
function unexpected(status, error) {
|
|
22
|
+
return { ok: false, reason: "unexpected_answer", status, error };
|
|
23
|
+
}
|
|
24
|
+
function endedFailure(reason) {
|
|
25
|
+
return {
|
|
26
|
+
ok: false,
|
|
27
|
+
reason: "ended",
|
|
28
|
+
error: `The connection to QBO Sync has ended. ${endedReasonInWords(reason)} An admin must press Connect again.`,
|
|
29
|
+
...(reason ? { endedReason: reason } : {}),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
export class QbosyncClient {
|
|
33
|
+
config;
|
|
34
|
+
baseUrl;
|
|
35
|
+
fetchImpl;
|
|
36
|
+
log;
|
|
37
|
+
keys;
|
|
38
|
+
constructor(config) {
|
|
39
|
+
this.config = config;
|
|
40
|
+
this.baseUrl = config.baseUrl.trim().replace(/\/+$/, "");
|
|
41
|
+
// Through a function, so a fetch stubbed after this is built is the one used.
|
|
42
|
+
this.fetchImpl = config.fetch ?? ((...args) => fetch(...args));
|
|
43
|
+
this.log = config.log ?? console.error;
|
|
44
|
+
this.keys = new SigningKeys(this.baseUrl, this.fetchImpl);
|
|
45
|
+
}
|
|
46
|
+
// ---- connecting
|
|
47
|
+
/** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
|
|
48
|
+
async openConnectRequest(input) {
|
|
49
|
+
const { baseUrl, config, fetchImpl, log } = this;
|
|
50
|
+
let clientId = null;
|
|
51
|
+
try {
|
|
52
|
+
const row = await config.connections.read();
|
|
53
|
+
clientId = row && row.base_url === baseUrl ? row.client_id : null;
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
return { ok: false, error: `The connection could not be read: ${err instanceof Error ? err.message : String(err)}` };
|
|
57
|
+
}
|
|
58
|
+
return openConnectRequest({ baseUrl, appName: config.appName, clientId, ...input, store: config.connectRequests, fetchImpl, log });
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
|
|
62
|
+
* schedule, when a page opens, when QBO Sync sends the admin's tab back): only one server collects.
|
|
63
|
+
*/
|
|
64
|
+
collectConnectRequest(options = {}) {
|
|
65
|
+
return collectConnectRequest({ store: this.config.connectRequests, baseUrl: this.baseUrl, fetchImpl: this.fetchImpl, log: this.log, ...options });
|
|
66
|
+
}
|
|
67
|
+
/** The stored connection, asking QBO Sync nothing. Never throws. */
|
|
68
|
+
async connectionState() {
|
|
69
|
+
let row;
|
|
70
|
+
try {
|
|
71
|
+
row = await this.config.connections.read();
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
return { state: "unavailable", error: `The connection could not be read: ${err instanceof Error ? err.message : String(err)}` };
|
|
75
|
+
}
|
|
76
|
+
if (!row || row.base_url !== this.baseUrl)
|
|
77
|
+
return { state: "not_connected" };
|
|
78
|
+
if (row.ended_at) {
|
|
79
|
+
return {
|
|
80
|
+
state: "ended",
|
|
81
|
+
connectedBy: row.connected_by,
|
|
82
|
+
connectedAt: row.connected_at,
|
|
83
|
+
endedAt: row.ended_at,
|
|
84
|
+
error: endedReasonInWords(row.ended_reason),
|
|
85
|
+
endedReason: row.ended_reason,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return { state: "connected", connectedBy: row.connected_by, connectedAt: row.connected_at, renewedAt: row.renewed_at, clientId: row.client_id, redirectUri: row.redirect_uri };
|
|
89
|
+
}
|
|
90
|
+
// ---- calling
|
|
91
|
+
credential(refusedToken) {
|
|
92
|
+
return currentCredential({ store: this.config.connections, baseUrl: this.baseUrl, refusedToken, fetchImpl: this.fetchImpl, log: this.log });
|
|
93
|
+
}
|
|
94
|
+
failed(credential) {
|
|
95
|
+
switch (credential.kind) {
|
|
96
|
+
case "not_connected":
|
|
97
|
+
return { ok: false, reason: "not_connected", error: "This app is not connected to QBO Sync yet: an admin must press Connect" };
|
|
98
|
+
case "ended":
|
|
99
|
+
return endedFailure(credential.reason);
|
|
100
|
+
case "unavailable":
|
|
101
|
+
return { ok: false, reason: "unavailable", error: credential.error };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** One authenticated call: renews on a 401, waits out a short rate limit once. */
|
|
105
|
+
async call(path, init = {}) {
|
|
106
|
+
const first = await this.credential();
|
|
107
|
+
if (first.kind !== "token")
|
|
108
|
+
return this.failed(first);
|
|
109
|
+
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
110
|
+
const send = (accessToken) => this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
111
|
+
...init,
|
|
112
|
+
headers: { ...init.headers, Authorization: `Bearer ${accessToken}` },
|
|
113
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
114
|
+
cache: "no-store",
|
|
115
|
+
});
|
|
116
|
+
const sendRenewing = (accessToken) => sendRenewingOn401(accessToken, (refused) => this.credential(refused), send);
|
|
117
|
+
try {
|
|
118
|
+
let sent = await sendRenewing(first.accessToken);
|
|
119
|
+
if (sent.refused)
|
|
120
|
+
return this.failed(sent.refused);
|
|
121
|
+
if (sent.res.status === 429) {
|
|
122
|
+
const retryAfterSeconds = Number(sent.res.headers.get("Retry-After")) || 60;
|
|
123
|
+
if (retryAfterSeconds * 1000 > (this.config.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS)) {
|
|
124
|
+
return { ok: false, reason: "rate_limited", status: 429, retryAfterSeconds, error: `QBO Sync's rate limit: try again in ${retryAfterSeconds} seconds` };
|
|
125
|
+
}
|
|
126
|
+
await sent.res.body?.cancel().catch(() => undefined);
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterSeconds * 1000));
|
|
128
|
+
const again = await this.credential();
|
|
129
|
+
if (again.kind !== "token")
|
|
130
|
+
return this.failed(again);
|
|
131
|
+
sent = await sendRenewing(again.accessToken);
|
|
132
|
+
if (sent.refused)
|
|
133
|
+
return this.failed(sent.refused);
|
|
134
|
+
if (sent.res.status === 429)
|
|
135
|
+
return { ok: false, reason: "rate_limited", status: 429, retryAfterSeconds, error: `QBO Sync's rate limit: try again in ${retryAfterSeconds} seconds` };
|
|
136
|
+
}
|
|
137
|
+
return { ok: true, res: sent.res };
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
return { ok: false, reason: "unavailable", error: `QBO Sync could not be reached: ${err instanceof Error ? err.message : String(err)}` };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// ---- documents
|
|
144
|
+
/**
|
|
145
|
+
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
146
|
+
* contract first; one that fails is not sent, and does not stop the others.
|
|
147
|
+
*
|
|
148
|
+
* QBO Sync keeps a document exactly as first received, so send each one once, as version 1. To correct
|
|
149
|
+
* one, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is
|
|
150
|
+
* always safe: QBO Sync answers `unchanged` for what it holds.
|
|
151
|
+
*/
|
|
152
|
+
async sendDocuments(documents) {
|
|
153
|
+
const results = [];
|
|
154
|
+
const sendable = [];
|
|
155
|
+
documents.forEach((document, index) => {
|
|
156
|
+
const checked = checkDocument(document);
|
|
157
|
+
if (checked.ok)
|
|
158
|
+
sendable.push({ index, document: checked.document });
|
|
159
|
+
else
|
|
160
|
+
results.push({ index, source_ref: refOf(document), outcome: { kind: "parked", status: "refused", error: checked.reasons.join("; ") } });
|
|
161
|
+
});
|
|
162
|
+
const inOrder = () => [...results].sort((a, b) => a.index - b.index);
|
|
163
|
+
for (let i = 0; i < sendable.length; i += MAX_DOCUMENTS_PER_REQUEST) {
|
|
164
|
+
const batch = sendable.slice(i, i + MAX_DOCUMENTS_PER_REQUEST);
|
|
165
|
+
const answered = await this.sendBatch(batch.map((b) => b.document));
|
|
166
|
+
if (!answered.ok)
|
|
167
|
+
return { ...answered, results: inOrder() };
|
|
168
|
+
batch.forEach((b, j) => {
|
|
169
|
+
const answer = answered.answers[j];
|
|
170
|
+
results.push({ index: b.index, source_ref: refOf(b.document), outcome: outcomeOf(answer), answer });
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
return { ok: true, results: inOrder() };
|
|
174
|
+
}
|
|
175
|
+
async sendBatch(documents) {
|
|
176
|
+
const called = await this.call("/api/v1/documents", {
|
|
177
|
+
method: "POST",
|
|
178
|
+
headers: { "Content-Type": "application/json" },
|
|
179
|
+
body: JSON.stringify({ documents }),
|
|
180
|
+
});
|
|
181
|
+
if (!called.ok)
|
|
182
|
+
return called;
|
|
183
|
+
const { res } = called;
|
|
184
|
+
const body = (await res.json().catch(() => null));
|
|
185
|
+
if (!res.ok)
|
|
186
|
+
return failureOf(res, body);
|
|
187
|
+
const results = body?.results;
|
|
188
|
+
if (!Array.isArray(results) || results.length !== documents.length) {
|
|
189
|
+
return unexpected(res.status, `QBO Sync answered ${Array.isArray(results) ? results.length : "no"} results for ${documents.length} documents`);
|
|
190
|
+
}
|
|
191
|
+
// Answers are matched by position; when one names a source_ref it must be the one sent there.
|
|
192
|
+
for (let i = 0; i < documents.length; i++) {
|
|
193
|
+
const named = results[i]?.source_ref;
|
|
194
|
+
if (typeof named === "string" && named !== refOf(documents[i])) {
|
|
195
|
+
return unexpected(res.status, `QBO Sync's answer ${i} is for "${named}", not "${refOf(documents[i])}"`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { ok: true, answers: results };
|
|
199
|
+
}
|
|
200
|
+
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
201
|
+
async documentReport(refs) {
|
|
202
|
+
const documents = [];
|
|
203
|
+
for (let i = 0; i < refs.length; i += MAX_REPORT_REFS) {
|
|
204
|
+
const batch = refs.slice(i, i + MAX_REPORT_REFS);
|
|
205
|
+
const query = new URLSearchParams(batch.map((ref) => ["ref", ref]));
|
|
206
|
+
const called = await this.call(`/api/v1/reports/documents?${query}`);
|
|
207
|
+
if (!called.ok)
|
|
208
|
+
return called;
|
|
209
|
+
const body = (await called.res.json().catch(() => null));
|
|
210
|
+
if (!called.res.ok)
|
|
211
|
+
return failureOf(called.res, body);
|
|
212
|
+
if (!Array.isArray(body?.documents) || body.documents.length !== batch.length) {
|
|
213
|
+
return unexpected(called.res.status, `QBO Sync's report answered ${Array.isArray(body?.documents) ? body.documents.length : "no"} entries for ${batch.length} refs`);
|
|
214
|
+
}
|
|
215
|
+
documents.push(...body.documents);
|
|
216
|
+
}
|
|
217
|
+
return { ok: true, documents };
|
|
218
|
+
}
|
|
219
|
+
// ---- companies and people
|
|
220
|
+
/** Which of the app's companies are connected to QBO Sync, with their QuickBooks and syncing. */
|
|
221
|
+
async listCompanies() {
|
|
222
|
+
const called = await this.call("/api/v1/companies");
|
|
223
|
+
if (!called.ok)
|
|
224
|
+
return called;
|
|
225
|
+
const body = (await called.res.json().catch(() => null));
|
|
226
|
+
if (!called.res.ok)
|
|
227
|
+
return failureOf(called.res, body);
|
|
228
|
+
if (!Array.isArray(body?.companies))
|
|
229
|
+
return unexpected(called.res.status, "QBO Sync's answer has no companies list");
|
|
230
|
+
return { ok: true, companies: body.companies };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* A one-time link that signs a person in to QBO Sync for one company: send their browser to `url`.
|
|
234
|
+
* This is also how a company comes to exist in QBO Sync, so it is what an app's Connect button for a
|
|
235
|
+
* company calls. The app must be allowed to sign people in (a switch on QBO Sync's side).
|
|
236
|
+
*/
|
|
237
|
+
async createSignInLink(input) {
|
|
238
|
+
const { email, company, role, appDisplayName } = input;
|
|
239
|
+
const called = await this.call("/api/v1/auth/sign-in-link", {
|
|
240
|
+
method: "POST",
|
|
241
|
+
headers: { "Content-Type": "application/json" },
|
|
242
|
+
body: JSON.stringify({ email, company, role, ...(appDisplayName ? { app_display_name: appDisplayName } : {}) }),
|
|
243
|
+
});
|
|
244
|
+
if (!called.ok)
|
|
245
|
+
return called;
|
|
246
|
+
const body = (await called.res.json().catch(() => null));
|
|
247
|
+
if (!called.res.ok)
|
|
248
|
+
return failureOf(called.res, body);
|
|
249
|
+
if (typeof body?.url !== "string")
|
|
250
|
+
return unexpected(called.res.status, "QBO Sync's answer has no link");
|
|
251
|
+
// Apps send a signed-in person straight to it: only ever QBO Sync's own sign-in page, on the address called.
|
|
252
|
+
if (!this.isSignInPage(body.url))
|
|
253
|
+
return unexpected(called.res.status, "QBO Sync's answer links to a page other than its own sign-in page");
|
|
254
|
+
return { ok: true, url: body.url, expiresAt: typeof body.expires_at === "string" ? body.expires_at : null };
|
|
255
|
+
}
|
|
256
|
+
isSignInPage(url) {
|
|
257
|
+
try {
|
|
258
|
+
const link = new URL(url);
|
|
259
|
+
return link.origin === new URL(this.baseUrl).origin && link.pathname === SIGN_IN_PAGE_PATH;
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
// ---- status reports
|
|
266
|
+
/**
|
|
267
|
+
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
|
268
|
+
* arrived, before any parsing, and the `X-QBOSync-Signature` header.
|
|
269
|
+
*/
|
|
270
|
+
checkStatusReports(rawBody, signature) {
|
|
271
|
+
return checkStatusReports(this.keys, rawBody, signature);
|
|
272
|
+
}
|
|
273
|
+
}
|