@company-six/qbosync 0.0.0-stage → 0.1.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 +137 -2
- package/dist/client.d.ts +120 -0
- package/dist/client.js +223 -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 +97 -0
- package/dist/contract/answers.js +31 -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 +70 -0
- package/dist/statusReports.js +125 -0
- package/dist/supabase.d.ts +38 -0
- package/dist/supabase.js +67 -0
- package/package.json +38 -4
- package/sql/001_connection.sql +368 -0
package/README.md
CHANGED
|
@@ -1,3 +1,138 @@
|
|
|
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.
|
|
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
|
+
## 2. Create the client
|
|
22
|
+
|
|
23
|
+
On Supabase, with a **service-role** client:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { QbosyncClient } from "@company-six/qbosync";
|
|
27
|
+
import { createSupabaseStores } from "@company-six/qbosync/supabase";
|
|
28
|
+
|
|
29
|
+
export const qbosync = new QbosyncClient({
|
|
30
|
+
baseUrl: process.env.QBOSYNC_URL!,
|
|
31
|
+
appName: "my-app",
|
|
32
|
+
...createSupabaseStores(supabase),
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
On another database, implement `ConnectionStore` and `ConnectRequestStore` (their comments say what each method must promise) and pass them as `connections` and `connectRequests`.
|
|
37
|
+
|
|
38
|
+
## 3. Connect
|
|
39
|
+
|
|
40
|
+
When an admin of your app presses Connect:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const opened = await qbosync.openConnectRequest({
|
|
44
|
+
redirectUri: "https://my-app.com/qbosync/callback",
|
|
45
|
+
startedBy: admin.email,
|
|
46
|
+
});
|
|
47
|
+
if (opened.ok) redirect(opened.verificationUri);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
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.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const collected = await qbosync.collectConnectRequest();
|
|
54
|
+
// collected.state: "connected", "waiting", "denied", "expired", "failed", "none", "other" or "unavailable"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
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.
|
|
58
|
+
|
|
59
|
+
## 4. Connect a company
|
|
60
|
+
|
|
61
|
+
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:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const link = await qbosync.createSignInLink({ email: user.email, company: "Acme", role: "company_user" });
|
|
65
|
+
if (link.ok) redirect(link.url); // works once, for five minutes
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`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.
|
|
69
|
+
|
|
70
|
+
## 5. Send documents
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const sent = await qbosync.sendDocuments([invoice, creditMemo]);
|
|
74
|
+
|
|
75
|
+
for (const { source_ref, outcome } of sent.results) {
|
|
76
|
+
if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it. Never send it again.
|
|
77
|
+
if (outcome.kind === "parked") needsAPerson(source_ref, outcome.error); // sending again changes nothing
|
|
78
|
+
if (outcome.kind === "failure") retryLater(source_ref); // not the document's fault
|
|
79
|
+
}
|
|
80
|
+
if (!sent.ok) console.error(sent.error); // a batch failed; what has no result here is safe to send again
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
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`.
|
|
84
|
+
|
|
85
|
+
**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`.
|
|
86
|
+
|
|
87
|
+
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.
|
|
88
|
+
|
|
89
|
+
## 6. Receive status reports
|
|
90
|
+
|
|
91
|
+
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:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { SIGNATURE_HEADER, isNewerReport } from "@company-six/qbosync";
|
|
95
|
+
|
|
96
|
+
export async function POST(req: Request) {
|
|
97
|
+
const checked = await qbosync.checkStatusReports(await req.text(), req.headers.get(SIGNATURE_HEADER));
|
|
98
|
+
if (!checked.ok) return Response.json({ error: checked.error }, { status: checked.status });
|
|
99
|
+
|
|
100
|
+
const results = await Promise.all(
|
|
101
|
+
checked.reports.map(async (report) => {
|
|
102
|
+
const row = await findDocument(report.source_ref);
|
|
103
|
+
if (!row) return { source_ref: report.source_ref, document_type: report.document_type, result: "unknown" };
|
|
104
|
+
if (!isNewerReport(report, row.lastSequence)) return { source_ref: report.source_ref, document_type: report.document_type, result: "stale" };
|
|
105
|
+
await saveStatus(row, report);
|
|
106
|
+
return { source_ref: report.source_ref, document_type: report.document_type, result: "applied" };
|
|
107
|
+
})
|
|
108
|
+
);
|
|
109
|
+
return Response.json({ results });
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Answer `error` for a report you could not apply, and for anything in `checked.invalid`: QBO Sync sends those again later. Keep the sequence you applied for each document: a delayed report must not hide a newer one.
|
|
114
|
+
|
|
115
|
+
## 7. Compare
|
|
116
|
+
|
|
117
|
+
For a daily report, name the documents your app created that day:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const report = await qbosync.documentReport(refs);
|
|
121
|
+
// each entry: its status, QuickBooks number, what was posted and the nightly check, or sync_status "unknown" if never received
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## When a call fails
|
|
125
|
+
|
|
126
|
+
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`:
|
|
127
|
+
|
|
128
|
+
| `reason` | Meaning | What to do |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `not_connected` | Nobody has connected the app yet. | An admin presses Connect. |
|
|
131
|
+
| `ended` | QBO Sync ended the connection. | An admin presses Connect again. |
|
|
132
|
+
| `unavailable` | QBO Sync or your database could not answer. | Try again later. |
|
|
133
|
+
| `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. |
|
|
134
|
+
| `rejected` | QBO Sync refused the request. | Read `error`. |
|
|
135
|
+
|
|
136
|
+
## Versions
|
|
137
|
+
|
|
138
|
+
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,120 @@
|
|
|
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
|
+
/** Why a call failed. `not_connected` and `ended` need an admin to press Connect; the others are worth trying again. */
|
|
28
|
+
export type FailureReason = "not_connected" | "ended" | "unavailable" | "rate_limited" | "rejected";
|
|
29
|
+
export interface Failure {
|
|
30
|
+
ok: false;
|
|
31
|
+
error: string;
|
|
32
|
+
reason: FailureReason;
|
|
33
|
+
/** QBO Sync's status, when it answered. */
|
|
34
|
+
status?: number;
|
|
35
|
+
/** With `rate_limited`: how long QBO Sync asks to wait. */
|
|
36
|
+
retryAfterSeconds?: number;
|
|
37
|
+
}
|
|
38
|
+
/** One document's result, in the order given. */
|
|
39
|
+
export interface DocumentResult {
|
|
40
|
+
index: number;
|
|
41
|
+
source_ref: string | null;
|
|
42
|
+
/** What to do about it. Not sent because it failed the contract: `parked`, without calling QBO Sync. */
|
|
43
|
+
outcome: SendOutcome;
|
|
44
|
+
/** QBO Sync's own answer; absent when it was not sent. */
|
|
45
|
+
answer?: ReceiveResult;
|
|
46
|
+
}
|
|
47
|
+
/** `Failure` with `results`: a batch failed, and the documents in it or after it have no result. They are safe to send again. */
|
|
48
|
+
export type SendResult = {
|
|
49
|
+
ok: true;
|
|
50
|
+
results: DocumentResult[];
|
|
51
|
+
} | (Failure & {
|
|
52
|
+
results: DocumentResult[];
|
|
53
|
+
});
|
|
54
|
+
export declare class QbosyncClient {
|
|
55
|
+
private readonly config;
|
|
56
|
+
private readonly baseUrl;
|
|
57
|
+
private readonly fetchImpl;
|
|
58
|
+
private readonly log;
|
|
59
|
+
private readonly keys;
|
|
60
|
+
constructor(config: QbosyncClientConfig);
|
|
61
|
+
/** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
|
|
62
|
+
openConnectRequest(input: {
|
|
63
|
+
redirectUri: string;
|
|
64
|
+
startedBy: string;
|
|
65
|
+
}): Promise<OpenResult>;
|
|
66
|
+
/**
|
|
67
|
+
* Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
|
|
68
|
+
* schedule, when a page opens, when QBO Sync sends the admin's tab back): only one server collects.
|
|
69
|
+
*/
|
|
70
|
+
collectConnectRequest(options?: {
|
|
71
|
+
requestId?: string;
|
|
72
|
+
waitMs?: number;
|
|
73
|
+
}): Promise<CollectResult>;
|
|
74
|
+
private credential;
|
|
75
|
+
private failed;
|
|
76
|
+
/** One authenticated call: renews on a 401, waits out a short rate limit once. */
|
|
77
|
+
private call;
|
|
78
|
+
/**
|
|
79
|
+
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
80
|
+
* contract first; one that fails is not sent, and does not stop the others.
|
|
81
|
+
*
|
|
82
|
+
* QBO Sync keeps a document exactly as first received, so send each one once, as version 1. To correct
|
|
83
|
+
* one, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is
|
|
84
|
+
* always safe: QBO Sync answers `unchanged` for what it holds.
|
|
85
|
+
*/
|
|
86
|
+
sendDocuments(documents: readonly unknown[]): Promise<SendResult>;
|
|
87
|
+
private sendBatch;
|
|
88
|
+
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
89
|
+
documentReport(refs: readonly string[]): Promise<{
|
|
90
|
+
ok: true;
|
|
91
|
+
documents: ReportEntry[];
|
|
92
|
+
} | Failure>;
|
|
93
|
+
/** Which of the app's companies are connected to QBO Sync, with their QuickBooks and syncing. */
|
|
94
|
+
listCompanies(): Promise<{
|
|
95
|
+
ok: true;
|
|
96
|
+
companies: AppCompanyStatus[];
|
|
97
|
+
} | Failure>;
|
|
98
|
+
/**
|
|
99
|
+
* A one-time link that signs a person in to QBO Sync for one company: send their browser to `url`.
|
|
100
|
+
* This is also how a company comes to exist in QBO Sync, so it is what an app's Connect button for a
|
|
101
|
+
* company calls. The app must be allowed to sign people in (a switch on QBO Sync's side).
|
|
102
|
+
*/
|
|
103
|
+
createSignInLink(input: {
|
|
104
|
+
email: string;
|
|
105
|
+
/** The company as the app names it: its documents' `company_key`. */
|
|
106
|
+
company: string;
|
|
107
|
+
role: SignInRole;
|
|
108
|
+
/** What the app asks its company users to see it called in QBO Sync. */
|
|
109
|
+
appDisplayName?: string;
|
|
110
|
+
}): Promise<{
|
|
111
|
+
ok: true;
|
|
112
|
+
url: string;
|
|
113
|
+
expiresAt: string | null;
|
|
114
|
+
} | Failure>;
|
|
115
|
+
/**
|
|
116
|
+
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
|
117
|
+
* arrived, before any parsing, and the `X-QBOSync-Signature` header.
|
|
118
|
+
*/
|
|
119
|
+
checkStatusReports(rawBody: string, signature: string | null | undefined): Promise<CheckedStatusReports>;
|
|
120
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
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 { outcomeOf } from "./contract/answers.js";
|
|
6
|
+
import { checkStatusReports, SigningKeys } from "./statusReports.js";
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
8
|
+
const DEFAULT_MAX_RETRY_AFTER_MS = 5_000;
|
|
9
|
+
const refOf = (document) => {
|
|
10
|
+
const ref = document?.source_ref;
|
|
11
|
+
return typeof ref === "string" ? ref : null;
|
|
12
|
+
};
|
|
13
|
+
function failureOf(res, body) {
|
|
14
|
+
const detail = typeof body?.error === "string" ? `: ${body.error}` : "";
|
|
15
|
+
return { ok: false, reason: "rejected", status: res.status, error: `QBO Sync answered ${res.status}${detail}` };
|
|
16
|
+
}
|
|
17
|
+
export class QbosyncClient {
|
|
18
|
+
config;
|
|
19
|
+
baseUrl;
|
|
20
|
+
fetchImpl;
|
|
21
|
+
log;
|
|
22
|
+
keys;
|
|
23
|
+
constructor(config) {
|
|
24
|
+
this.config = config;
|
|
25
|
+
this.baseUrl = config.baseUrl.trim().replace(/\/+$/, "");
|
|
26
|
+
// Through a function, so a fetch stubbed after this is built is the one used.
|
|
27
|
+
this.fetchImpl = config.fetch ?? ((...args) => fetch(...args));
|
|
28
|
+
this.log = config.log ?? console.error;
|
|
29
|
+
this.keys = new SigningKeys(this.baseUrl, this.fetchImpl);
|
|
30
|
+
}
|
|
31
|
+
// ---- connecting
|
|
32
|
+
/** An admin pressed Connect: opens a connect request. Send their browser to `verificationUri`. */
|
|
33
|
+
async openConnectRequest(input) {
|
|
34
|
+
const { baseUrl, config, fetchImpl, log } = this;
|
|
35
|
+
let clientId = null;
|
|
36
|
+
try {
|
|
37
|
+
const row = await config.connections.read();
|
|
38
|
+
clientId = row && row.base_url === baseUrl ? row.client_id : null;
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
return { ok: false, error: `The connection could not be read: ${err instanceof Error ? err.message : String(err)}` };
|
|
42
|
+
}
|
|
43
|
+
return openConnectRequest({ baseUrl, appName: config.appName, clientId, ...input, store: config.connectRequests, fetchImpl, log });
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Collects the connection once a QBO Sync administrator has decided. Safe to call often (on a
|
|
47
|
+
* schedule, when a page opens, when QBO Sync sends the admin's tab back): only one server collects.
|
|
48
|
+
*/
|
|
49
|
+
collectConnectRequest(options = {}) {
|
|
50
|
+
return collectConnectRequest({ store: this.config.connectRequests, baseUrl: this.baseUrl, fetchImpl: this.fetchImpl, log: this.log, ...options });
|
|
51
|
+
}
|
|
52
|
+
// ---- calling
|
|
53
|
+
credential(refusedToken) {
|
|
54
|
+
return currentCredential({ store: this.config.connections, baseUrl: this.baseUrl, refusedToken, fetchImpl: this.fetchImpl, log: this.log });
|
|
55
|
+
}
|
|
56
|
+
failed(credential) {
|
|
57
|
+
switch (credential.kind) {
|
|
58
|
+
case "not_connected":
|
|
59
|
+
return { ok: false, reason: "not_connected", error: "This app is not connected to QBO Sync yet: an admin must press Connect" };
|
|
60
|
+
case "ended":
|
|
61
|
+
return { ok: false, reason: "ended", error: `The connection to QBO Sync has ended (${credential.reason}): an admin must press Connect again` };
|
|
62
|
+
case "unavailable":
|
|
63
|
+
return { ok: false, reason: "unavailable", error: credential.error };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** One authenticated call: renews on a 401, waits out a short rate limit once. */
|
|
67
|
+
async call(path, init = {}) {
|
|
68
|
+
const first = await this.credential();
|
|
69
|
+
if (first.kind !== "token")
|
|
70
|
+
return this.failed(first);
|
|
71
|
+
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
72
|
+
const send = (accessToken) => this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
73
|
+
...init,
|
|
74
|
+
headers: { ...init.headers, Authorization: `Bearer ${accessToken}` },
|
|
75
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
76
|
+
cache: "no-store",
|
|
77
|
+
});
|
|
78
|
+
const sendRenewing = (accessToken) => sendRenewingOn401(accessToken, (refused) => this.credential(refused), send);
|
|
79
|
+
try {
|
|
80
|
+
let sent = await sendRenewing(first.accessToken);
|
|
81
|
+
if (sent.refused)
|
|
82
|
+
return this.failed(sent.refused);
|
|
83
|
+
if (sent.res.status === 429) {
|
|
84
|
+
const retryAfterSeconds = Number(sent.res.headers.get("Retry-After")) || 60;
|
|
85
|
+
if (retryAfterSeconds * 1000 > (this.config.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS)) {
|
|
86
|
+
return { ok: false, reason: "rate_limited", status: 429, retryAfterSeconds, error: `QBO Sync's rate limit: try again in ${retryAfterSeconds} seconds` };
|
|
87
|
+
}
|
|
88
|
+
await sent.res.body?.cancel().catch(() => undefined);
|
|
89
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterSeconds * 1000));
|
|
90
|
+
const again = await this.credential();
|
|
91
|
+
if (again.kind !== "token")
|
|
92
|
+
return this.failed(again);
|
|
93
|
+
sent = await sendRenewing(again.accessToken);
|
|
94
|
+
if (sent.refused)
|
|
95
|
+
return this.failed(sent.refused);
|
|
96
|
+
if (sent.res.status === 429)
|
|
97
|
+
return { ok: false, reason: "rate_limited", status: 429, retryAfterSeconds, error: `QBO Sync's rate limit: try again in ${retryAfterSeconds} seconds` };
|
|
98
|
+
}
|
|
99
|
+
return { ok: true, res: sent.res };
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
return { ok: false, reason: "unavailable", error: `QBO Sync could not be reached: ${err instanceof Error ? err.message : String(err)}` };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// ---- documents
|
|
106
|
+
/**
|
|
107
|
+
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
108
|
+
* contract first; one that fails is not sent, and does not stop the others.
|
|
109
|
+
*
|
|
110
|
+
* QBO Sync keeps a document exactly as first received, so send each one once, as version 1. To correct
|
|
111
|
+
* one, send a credit memo, or have a person roll it back in QBO Sync. Sending again after a failure is
|
|
112
|
+
* always safe: QBO Sync answers `unchanged` for what it holds.
|
|
113
|
+
*/
|
|
114
|
+
async sendDocuments(documents) {
|
|
115
|
+
const results = [];
|
|
116
|
+
const sendable = [];
|
|
117
|
+
documents.forEach((document, index) => {
|
|
118
|
+
const checked = checkDocument(document);
|
|
119
|
+
if (checked.ok)
|
|
120
|
+
sendable.push({ index, document: checked.document });
|
|
121
|
+
else
|
|
122
|
+
results.push({ index, source_ref: refOf(document), outcome: { kind: "parked", status: "refused", error: checked.reasons.join("; ") } });
|
|
123
|
+
});
|
|
124
|
+
const inOrder = () => [...results].sort((a, b) => a.index - b.index);
|
|
125
|
+
for (let i = 0; i < sendable.length; i += MAX_DOCUMENTS_PER_REQUEST) {
|
|
126
|
+
const batch = sendable.slice(i, i + MAX_DOCUMENTS_PER_REQUEST);
|
|
127
|
+
const answered = await this.sendBatch(batch.map((b) => b.document));
|
|
128
|
+
if (!answered.ok)
|
|
129
|
+
return { ...answered, results: inOrder() };
|
|
130
|
+
batch.forEach((b, j) => {
|
|
131
|
+
const answer = answered.answers[j];
|
|
132
|
+
results.push({ index: b.index, source_ref: refOf(b.document), outcome: outcomeOf(answer), answer });
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return { ok: true, results: inOrder() };
|
|
136
|
+
}
|
|
137
|
+
async sendBatch(documents) {
|
|
138
|
+
const called = await this.call("/api/v1/documents", {
|
|
139
|
+
method: "POST",
|
|
140
|
+
headers: { "Content-Type": "application/json" },
|
|
141
|
+
body: JSON.stringify({ documents }),
|
|
142
|
+
});
|
|
143
|
+
if (!called.ok)
|
|
144
|
+
return called;
|
|
145
|
+
const { res } = called;
|
|
146
|
+
const body = (await res.json().catch(() => null));
|
|
147
|
+
if (!res.ok)
|
|
148
|
+
return failureOf(res, body);
|
|
149
|
+
const results = body?.results;
|
|
150
|
+
if (!Array.isArray(results) || results.length !== documents.length) {
|
|
151
|
+
return { ok: false, reason: "unavailable", status: res.status, error: `QBO Sync answered ${Array.isArray(results) ? results.length : "no"} results for ${documents.length} documents` };
|
|
152
|
+
}
|
|
153
|
+
// Answers are matched by position; when one names a source_ref it must be the one sent there.
|
|
154
|
+
for (let i = 0; i < documents.length; i++) {
|
|
155
|
+
const named = results[i]?.source_ref;
|
|
156
|
+
if (typeof named === "string" && named !== refOf(documents[i])) {
|
|
157
|
+
return { ok: false, reason: "unavailable", status: res.status, error: `QBO Sync's answer ${i} is for "${named}", not "${refOf(documents[i])}"` };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return { ok: true, answers: results };
|
|
161
|
+
}
|
|
162
|
+
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
163
|
+
async documentReport(refs) {
|
|
164
|
+
const documents = [];
|
|
165
|
+
for (let i = 0; i < refs.length; i += MAX_REPORT_REFS) {
|
|
166
|
+
const batch = refs.slice(i, i + MAX_REPORT_REFS);
|
|
167
|
+
const query = new URLSearchParams(batch.map((ref) => ["ref", ref]));
|
|
168
|
+
const called = await this.call(`/api/v1/reports/documents?${query}`);
|
|
169
|
+
if (!called.ok)
|
|
170
|
+
return called;
|
|
171
|
+
const body = (await called.res.json().catch(() => null));
|
|
172
|
+
if (!called.res.ok)
|
|
173
|
+
return failureOf(called.res, body);
|
|
174
|
+
if (!Array.isArray(body?.documents) || body.documents.length !== batch.length) {
|
|
175
|
+
return { ok: false, reason: "unavailable", status: called.res.status, error: `QBO Sync's report answered ${Array.isArray(body?.documents) ? body.documents.length : "no"} entries for ${batch.length} refs` };
|
|
176
|
+
}
|
|
177
|
+
documents.push(...body.documents);
|
|
178
|
+
}
|
|
179
|
+
return { ok: true, documents };
|
|
180
|
+
}
|
|
181
|
+
// ---- companies and people
|
|
182
|
+
/** Which of the app's companies are connected to QBO Sync, with their QuickBooks and syncing. */
|
|
183
|
+
async listCompanies() {
|
|
184
|
+
const called = await this.call("/api/v1/companies");
|
|
185
|
+
if (!called.ok)
|
|
186
|
+
return called;
|
|
187
|
+
const body = (await called.res.json().catch(() => null));
|
|
188
|
+
if (!called.res.ok)
|
|
189
|
+
return failureOf(called.res, body);
|
|
190
|
+
if (!Array.isArray(body?.companies))
|
|
191
|
+
return { ok: false, reason: "unavailable", status: called.res.status, error: "QBO Sync's answer has no companies list" };
|
|
192
|
+
return { ok: true, companies: body.companies };
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* A one-time link that signs a person in to QBO Sync for one company: send their browser to `url`.
|
|
196
|
+
* This is also how a company comes to exist in QBO Sync, so it is what an app's Connect button for a
|
|
197
|
+
* company calls. The app must be allowed to sign people in (a switch on QBO Sync's side).
|
|
198
|
+
*/
|
|
199
|
+
async createSignInLink(input) {
|
|
200
|
+
const { email, company, role, appDisplayName } = input;
|
|
201
|
+
const called = await this.call("/api/v1/auth/sign-in-link", {
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers: { "Content-Type": "application/json" },
|
|
204
|
+
body: JSON.stringify({ email, company, role, ...(appDisplayName ? { app_display_name: appDisplayName } : {}) }),
|
|
205
|
+
});
|
|
206
|
+
if (!called.ok)
|
|
207
|
+
return called;
|
|
208
|
+
const body = (await called.res.json().catch(() => null));
|
|
209
|
+
if (!called.res.ok)
|
|
210
|
+
return failureOf(called.res, body);
|
|
211
|
+
if (typeof body?.url !== "string")
|
|
212
|
+
return { ok: false, reason: "unavailable", status: called.res.status, error: "QBO Sync's answer has no link" };
|
|
213
|
+
return { ok: true, url: body.url, expiresAt: typeof body.expires_at === "string" ? body.expires_at : null };
|
|
214
|
+
}
|
|
215
|
+
// ---- status reports
|
|
216
|
+
/**
|
|
217
|
+
* Checks a call to the app's status report route (`STATUS_REPORT_PATH`). Pass the body EXACTLY as it
|
|
218
|
+
* arrived, before any parsing, and the `X-QBOSync-Signature` header.
|
|
219
|
+
*/
|
|
220
|
+
checkStatusReports(rawBody, signature) {
|
|
221
|
+
return checkStatusReports(this.keys, rawBody, signature);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type Log, type TokenAnswer } from "./connection.ts";
|
|
2
|
+
/** How a request ends, when it does not end connected. */
|
|
3
|
+
export type RequestRefusal = "denied" | "expired" | "failed";
|
|
4
|
+
/** The stored request. */
|
|
5
|
+
export interface ConnectRequestRow {
|
|
6
|
+
base_url: string;
|
|
7
|
+
request_id: string;
|
|
8
|
+
code_verifier: string | null;
|
|
9
|
+
client_id: string | null;
|
|
10
|
+
redirect_uri: string;
|
|
11
|
+
started_by: string;
|
|
12
|
+
started_at: string;
|
|
13
|
+
outcome: "connected" | RequestRefusal | null;
|
|
14
|
+
outcome_detail: string | null;
|
|
15
|
+
finished_at: string | null;
|
|
16
|
+
}
|
|
17
|
+
export interface NewConnectRequest {
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
requestId: string;
|
|
20
|
+
verifier: string;
|
|
21
|
+
clientId: string | null;
|
|
22
|
+
redirectUri: string;
|
|
23
|
+
startedBy: string;
|
|
24
|
+
}
|
|
25
|
+
/** Where an app keeps its request. `createSupabaseStores` gives one ready. */
|
|
26
|
+
export interface ConnectRequestStore {
|
|
27
|
+
/** The row, or null when there is none. Throws on a failure to read. */
|
|
28
|
+
read(): Promise<ConnectRequestRow | null>;
|
|
29
|
+
/** Keeps a new request, replacing any earlier one. */
|
|
30
|
+
open(request: NewConnectRequest): Promise<void>;
|
|
31
|
+
/** True for exactly one caller while the claim lasts, and only while it is this request and open. */
|
|
32
|
+
claim(requestId: string, seconds: number): Promise<boolean>;
|
|
33
|
+
release(requestId: string): Promise<void>;
|
|
34
|
+
finish(requestId: string, outcome: RequestRefusal, detail: string): Promise<boolean>;
|
|
35
|
+
/** Stores the connection AND closes the request, in one statement. False when it is no longer this request. */
|
|
36
|
+
saveCollected(requestId: string, clientId: string, answer: TokenAnswer): Promise<boolean>;
|
|
37
|
+
}
|
|
38
|
+
/** How long a server holds the collect. Far longer than TOKEN_TIMEOUT_MS plus saving. */
|
|
39
|
+
export declare const COLLECT_CLAIM_SECONDS = 60;
|
|
40
|
+
export declare const COLLECT_WAIT_STEP_MS = 500;
|
|
41
|
+
/** Reads the 201 to opening a request. The page must be on QBO Sync's own origin: an admin is never sent to an address the app was merely told about. */
|
|
42
|
+
export declare function readOpenAnswer(body: unknown, baseUrl: string): {
|
|
43
|
+
ok: true;
|
|
44
|
+
requestId: string;
|
|
45
|
+
verificationUri: string;
|
|
46
|
+
} | {
|
|
47
|
+
ok: false;
|
|
48
|
+
error: string;
|
|
49
|
+
};
|
|
50
|
+
export type CollectAnswer = {
|
|
51
|
+
kind: "connected";
|
|
52
|
+
clientId: string;
|
|
53
|
+
answer: TokenAnswer;
|
|
54
|
+
}
|
|
55
|
+
/** No decision yet (or QBO Sync asks the app to slow down): ask again later. */
|
|
56
|
+
| {
|
|
57
|
+
kind: "waiting";
|
|
58
|
+
}
|
|
59
|
+
/** Final: the request is over. */
|
|
60
|
+
| {
|
|
61
|
+
kind: "refused";
|
|
62
|
+
outcome: RequestRefusal;
|
|
63
|
+
detail: string;
|
|
64
|
+
}
|
|
65
|
+
/** Not an answer about the request: ask again later. */
|
|
66
|
+
| {
|
|
67
|
+
kind: "unavailable";
|
|
68
|
+
error: string;
|
|
69
|
+
};
|
|
70
|
+
/** What QBO Sync's answer to a collect means (RFC 8628's answers). */
|
|
71
|
+
export declare function readCollectAnswer(status: number, body: unknown): CollectAnswer;
|
|
72
|
+
export type OpenResult = {
|
|
73
|
+
ok: true;
|
|
74
|
+
requestId: string;
|
|
75
|
+
verificationUri: string;
|
|
76
|
+
} | {
|
|
77
|
+
ok: false;
|
|
78
|
+
error: string;
|
|
79
|
+
};
|
|
80
|
+
/** Opens a connect request and keeps it. `clientId`: the one from an earlier Connect; without one, `appName` is sent. Never throws. */
|
|
81
|
+
export declare function openConnectRequest(input: {
|
|
82
|
+
baseUrl: string;
|
|
83
|
+
appName: string;
|
|
84
|
+
clientId: string | null;
|
|
85
|
+
redirectUri: string;
|
|
86
|
+
/** Who pressed Connect, for the record. */
|
|
87
|
+
startedBy: string;
|
|
88
|
+
store: ConnectRequestStore;
|
|
89
|
+
fetchImpl?: typeof fetch;
|
|
90
|
+
log?: Log;
|
|
91
|
+
}): Promise<OpenResult>;
|
|
92
|
+
export type CollectResult =
|
|
93
|
+
/** No request for this QBO Sync (none yet, or one made against another address). */
|
|
94
|
+
{
|
|
95
|
+
state: "none";
|
|
96
|
+
}
|
|
97
|
+
/** The request named is not the current one (a newer Connect replaced it). */
|
|
98
|
+
| {
|
|
99
|
+
state: "other";
|
|
100
|
+
} | {
|
|
101
|
+
state: "waiting";
|
|
102
|
+
} | {
|
|
103
|
+
state: "connected";
|
|
104
|
+
} | {
|
|
105
|
+
state: RequestRefusal;
|
|
106
|
+
detail: string | null;
|
|
107
|
+
}
|
|
108
|
+
/** Not known now: QBO Sync or the database unavailable, or another server still collecting. Ask again later. */
|
|
109
|
+
| {
|
|
110
|
+
state: "unavailable";
|
|
111
|
+
error: string;
|
|
112
|
+
};
|
|
113
|
+
export interface CollectDeps {
|
|
114
|
+
store: ConnectRequestStore;
|
|
115
|
+
baseUrl: string;
|
|
116
|
+
/** Only this request; another current one answers `other`. */
|
|
117
|
+
requestId?: string;
|
|
118
|
+
/** How long to wait for another server's collect of the same request. 0: answer `unavailable` at once. */
|
|
119
|
+
waitMs?: number;
|
|
120
|
+
fetchImpl?: typeof fetch;
|
|
121
|
+
now?: () => number;
|
|
122
|
+
sleep?: (ms: number) => Promise<void>;
|
|
123
|
+
log?: Log;
|
|
124
|
+
}
|
|
125
|
+
/** Collects the current request, when there is one still open. Never throws. */
|
|
126
|
+
export declare function collectConnectRequest(deps: CollectDeps): Promise<CollectResult>;
|