@company-six/qbosync 0.7.0 → 0.10.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 +34 -0
- package/dist/client.d.ts +41 -2
- package/dist/client.js +159 -8
- package/dist/contract/answers.d.ts +15 -0
- package/dist/contract/attachments.d.ts +98 -0
- package/dist/contract/attachments.js +112 -0
- package/dist/contract/bill.d.ts +12 -0
- package/dist/contract/common.d.ts +7 -0
- package/dist/contract/common.js +3 -0
- package/dist/contract/creditMemo.d.ts +6 -0
- package/dist/contract/errorInWords.d.ts +46 -0
- package/dist/contract/errorInWords.js +193 -0
- package/dist/contract/index.d.ts +26 -0
- package/dist/contract/index.js +2 -0
- package/dist/contract/invoice.d.ts +6 -0
- package/dist/index.d.ts +1 -1
- package/package.json +1 -1
- package/sql/002_daily_report.sql +258 -258
- package/sql/003_daily_report_bills.sql +25 -25
package/README.md
CHANGED
|
@@ -168,6 +168,37 @@ const bill: BillDTO = {
|
|
|
168
168
|
- `number` is unique per vendor among your bills. When QuickBooks already holds a bill from that vendor with that number, the bill waits for a person in QBO Sync to link it or post it anyway.
|
|
169
169
|
- Like an invoice, a bill is kept as first received. Once it is in QuickBooks, correct it with a vendor credit; one QuickBooks refused, or a person rolled back, goes again as its next version (see "Correcting one that failed or was rolled back" above).
|
|
170
170
|
|
|
171
|
+
### Files with a document (0.9.0)
|
|
172
|
+
|
|
173
|
+
A document can carry files (a vendor's PDF on a bill, a signed order on an invoice), and each one shows on its record in QuickBooks. Give `sendDocuments` the files by the document's `source_ref`:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
const sent = await qbosync.sendDocuments([bill], {
|
|
177
|
+
files: {
|
|
178
|
+
[bill.source_ref]: [{ fileName: "vendor-invoice-2207.pdf", data: pdfBytes }], // a Uint8Array (a Buffer is one) or a Blob
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
The SDK sends each file to QBO Sync first, adds it to the document's `attachments`, then sends the document. That is all your app does. What happens underneath:
|
|
184
|
+
|
|
185
|
+
- **A document never holds a file.** It names each one by the SHA-256 of its bytes, so the same file always has the same name and a retry changes nothing. The same bytes are never sent twice for a company.
|
|
186
|
+
- **The file does not pass through QBO Sync's routes.** QBO Sync answers an address, and the bytes go straight there, without your token. So a file may be up to 20 MB, whatever limit your own host puts on a request.
|
|
187
|
+
- **The files follow the document.** QBO Sync attaches them once the document is in QuickBooks. A problem with a file never holds the document back or fails it.
|
|
188
|
+
- **What is accepted:** up to 10 files a document, 20 MB each, of the types QuickBooks takes (pdf, png, jpg, jpeg, gif, tif, tiff, csv, txt, rtf, xml, doc, docx, xls, xlsx, ods, ai, eps). Two files on the same document cannot share a name; any other document may reuse it. A file that fails these is not sent, nor is its document, and the result says why (`parked`).
|
|
189
|
+
- **A file that could not be sent** (the file store was down) leaves its document unsent with `failure`: send both again later.
|
|
190
|
+
|
|
191
|
+
To do the two steps yourself, `uploadAttachment` sends one file and answers what to put in the document:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const up = await qbosync.uploadAttachment({ companyKey: bill.company_key, fileName: "vendor-invoice-2207.pdf", data: pdfBytes });
|
|
195
|
+
if (up.ok) await qbosync.sendDocuments([{ ...bill, attachments: [up.attachment] }]);
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Each file's state comes back in the document report (`documentReport`), under `attachments`: `waiting` (not in QuickBooks yet), `attached`, `failed` (it is tried again), `refused` (QuickBooks, or QBO Sync's own check of the bytes, would not take the file; it is not tried again) and `not_held` (the document was rolled back and the file could not be kept: send it again with the next version). A document's files are part of its content: they change only in a new version, as the document does. Status reports do not carry files.
|
|
199
|
+
|
|
200
|
+
An app that does not use this SDK does the same with three requests: `POST /api/v1/attachments` with `{ company_key, content_type, size_bytes, sha256 }`; when the answer is `{ held: false, upload }`, one request to `upload.url` with `upload.method`, exactly `upload.headers` and the bytes as the body; then the document, naming the file in `attachments`.
|
|
201
|
+
|
|
171
202
|
## 6. Receive status reports
|
|
172
203
|
|
|
173
204
|
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:
|
|
@@ -203,6 +234,8 @@ export async function POST(req: Request) {
|
|
|
203
234
|
|
|
204
235
|
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.)
|
|
205
236
|
|
|
237
|
+
**`error` is written for people (0.8.0).** When QuickBooks refuses a document, QBO Sync says why in a sentence before it reports to you ("The vendor "Acme" that the vendor credit uses was deleted in QuickBooks…"), so show a report's `error`, and a daily report's, as it arrives: your app needs no wording of its own. QuickBooks' technical answer stays in QBO Sync. For text you stored before this, `errorInWords(stored).text` (from `@company-six/qbosync/contract`, safe in a browser) says it the same way, and gives text that is already in words back unchanged; `.technical` holds the original when it reworded anything.
|
|
238
|
+
|
|
206
239
|
### Testing your status report route
|
|
207
240
|
|
|
208
241
|
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:
|
|
@@ -307,6 +340,7 @@ What to check for `differs`:
|
|
|
307
340
|
- **Amounts**: your totals against `posted`. `total_cents`, `shipping_cents`, `tax_cents` and, on an invoice, `discount_cents`. Then each line by its `line_ref` (on a credit memo, `applies_to_line_ref`): its `quantity` and `amount_cents`, and any line only one side has. `posted` is in your own terms, in cents, and a credit memo's amounts are positive.
|
|
308
341
|
- **Voided**: a document you voided should read `sync_status: "voided"`, and the other way round. When both are voided, there are no amounts to compare.
|
|
309
342
|
- **QuickBooks**: `check.result` is QBO Sync's nightly read-back. `differs` means someone changed the document in QuickBooks; `check.differences` says how, in sentences you can show. `missing` means it was deleted there. Either one makes the result `differs`. `not_checked` (the check has not reached it yet) does not keep a document from matching.
|
|
343
|
+
- **Accepted in QBO Sync (0.10.0)**: when someone in QBO Sync acknowledged the difference because QuickBooks is right, `check.accepted` says who, when and what they accepted. While `check.accepted.current` is true, treat the document as settled: count it as `matches`, or show it solved with that reason. An older report that flagged it can show it solved too: ask QBO Sync about the row again and read `check.accepted`. Once QuickBooks changes again, `current` is false and the difference counts again.
|
|
310
344
|
|
|
311
345
|
Copy `qbo_number`, `sync_status`, `synced_at` and `check.result` (as `qbo_check`) into every row QBO Sync knows, so the row stands on its own later. For totals, count rows by result and add `documents`: `{ "documents": 12, "matches": 11, "failed": 1 }`.
|
|
312
346
|
|
package/dist/client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type CollectResult, type ConnectRequestStore, type OpenResult } from "./connectRequest.ts";
|
|
2
2
|
import { type ConnectionStore, type Log } from "./connection.ts";
|
|
3
|
-
import { type CodesDeclaration, type DeclaredCodes } from "./contract/index.ts";
|
|
3
|
+
import { type Attachment, type CodesDeclaration, type DeclaredCodes } from "./contract/index.ts";
|
|
4
4
|
import { type SignInRole } from "./contract/protocol.ts";
|
|
5
5
|
import { type AppCompanyStatus, type ReceiveResult, type ReportEntry, type SendOutcome } from "./contract/answers.ts";
|
|
6
6
|
import { type CheckedStatusReports } from "./statusReports.ts";
|
|
@@ -92,6 +92,28 @@ export type SendResult = {
|
|
|
92
92
|
} | (Failure & {
|
|
93
93
|
results: DocumentResult[];
|
|
94
94
|
});
|
|
95
|
+
/** A file to send with a document (0.9.0). */
|
|
96
|
+
export interface AttachmentFile {
|
|
97
|
+
/** The name QuickBooks shows. Its extension says the type, and must be one QuickBooks accepts. */
|
|
98
|
+
fileName: string;
|
|
99
|
+
/** The file's bytes: a `Uint8Array` (Node's `Buffer` is one) or a `Blob`. */
|
|
100
|
+
data: Uint8Array | Blob;
|
|
101
|
+
/** Left out, it is the content type of the file name's extension. */
|
|
102
|
+
contentType?: string;
|
|
103
|
+
}
|
|
104
|
+
/** `attachment` is what a document's `attachments` list names the file by. `alreadyHeld`: QBO Sync had these bytes, so none were sent. */
|
|
105
|
+
export type UploadResult = {
|
|
106
|
+
ok: true;
|
|
107
|
+
attachment: Attachment;
|
|
108
|
+
alreadyHeld: boolean;
|
|
109
|
+
} | Failure;
|
|
110
|
+
export interface SendOptions {
|
|
111
|
+
/**
|
|
112
|
+
* Files to send with the documents, by each document's `source_ref`. The SDK sends the files first, adds them to
|
|
113
|
+
* the document's `attachments` (after any it already names) and then sends the document.
|
|
114
|
+
*/
|
|
115
|
+
files?: Readonly<Record<string, readonly AttachmentFile[]>>;
|
|
116
|
+
}
|
|
95
117
|
export declare class QbosyncClient {
|
|
96
118
|
private readonly config;
|
|
97
119
|
private readonly baseUrl;
|
|
@@ -126,14 +148,31 @@ export declare class QbosyncClient {
|
|
|
126
148
|
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
127
149
|
* contract first; one that fails is not sent, and does not stop the others.
|
|
128
150
|
*
|
|
151
|
+
* `options.files` sends files with documents (0.9.0): each document's files go to QBO Sync first, then the
|
|
152
|
+
* document, which names them. QuickBooks shows them on the record once it has posted. A document whose file
|
|
153
|
+
* could not be sent is not sent either, and its result says why.
|
|
154
|
+
*
|
|
129
155
|
* Send each document once, as version 1: QBO Sync keeps it exactly as first received while it waits to
|
|
130
156
|
* post and once it is in QuickBooks, and sending the same version again is always safe (`unchanged`). A
|
|
131
157
|
* document QuickBooks refused (status `failed`), or a person rolled back (status `deleted`), is corrected
|
|
132
158
|
* by sending it again under the same `source_ref` as the next version (2, then 3). One in QuickBooks is
|
|
133
159
|
* corrected by a credit memo or vendor credit, or rolled back first.
|
|
134
160
|
*/
|
|
135
|
-
sendDocuments(documents: readonly unknown[]): Promise<SendResult>;
|
|
161
|
+
sendDocuments(documents: readonly unknown[], options?: SendOptions): Promise<SendResult>;
|
|
136
162
|
private sendBatch;
|
|
163
|
+
/**
|
|
164
|
+
* Sends one file to QBO Sync for a company, so a document can name it (0.9.0). Answers the `attachment` to put in
|
|
165
|
+
* the document's `attachments` list. The same bytes sent again for the same company are recognised and not sent
|
|
166
|
+
* twice, so this is safe to repeat. `sendDocuments` does this for you when given `files`.
|
|
167
|
+
*/
|
|
168
|
+
uploadAttachment(input: {
|
|
169
|
+
companyKey: string;
|
|
170
|
+
} & AttachmentFile): Promise<UploadResult>;
|
|
171
|
+
/** Every file of one document, in order; the first failure, or null when all are with QBO Sync. */
|
|
172
|
+
private uploadFiles;
|
|
173
|
+
private uploadPrepared;
|
|
174
|
+
/** An address the file's bytes may go to: https, or plain http only when QBO Sync itself is reached that way (a local stack). */
|
|
175
|
+
private isUploadAddress;
|
|
137
176
|
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
138
177
|
documentReport(refs: readonly string[]): Promise<{
|
|
139
178
|
ok: true;
|
package/dist/client.js
CHANGED
|
@@ -1,11 +1,41 @@
|
|
|
1
1
|
import { collectConnectRequest, openConnectRequest } from "./connectRequest.js";
|
|
2
2
|
import { currentCredential, sendRenewingOn401 } from "./connection.js";
|
|
3
|
-
import { checkDocument, codesDeclarationSchema, formatIssue } from "./contract/index.js";
|
|
3
|
+
import { ATTACHMENTS_PATH, attachment as attachmentSchema, attachmentContentType, attachmentUploadSchema, checkDocument, codesDeclarationSchema, formatIssue, } from "./contract/index.js";
|
|
4
4
|
import { MAX_DOCUMENTS_PER_REQUEST, MAX_REPORT_REFS } from "./contract/protocol.js";
|
|
5
5
|
import { endedReasonInWords, outcomeOf } from "./contract/answers.js";
|
|
6
6
|
import { checkStatusReports, SigningKeys } from "./statusReports.js";
|
|
7
7
|
/** QBO Sync's sign-in page: the only page `createSignInLink` sends a browser to. */
|
|
8
8
|
export const SIGN_IN_PAGE_PATH = "/auth/link";
|
|
9
|
+
const rejected = (error, detail) => ({ ok: false, reason: "rejected", error, ...(detail ? { detail } : {}) });
|
|
10
|
+
const hex = (buffer) => [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
11
|
+
/** Reads a file's bytes, takes their SHA-256 and checks the result as QBO Sync will. Sends nothing. */
|
|
12
|
+
async function prepareFile(file) {
|
|
13
|
+
const name = typeof file?.fileName === "string" ? file.fileName : "";
|
|
14
|
+
let bytes;
|
|
15
|
+
try {
|
|
16
|
+
if (file.data instanceof Uint8Array)
|
|
17
|
+
bytes = file.data;
|
|
18
|
+
else if (file.data && typeof file.data.arrayBuffer === "function")
|
|
19
|
+
bytes = new Uint8Array(await file.data.arrayBuffer());
|
|
20
|
+
else
|
|
21
|
+
return rejected(`"${name}" was not sent: its data must be a Uint8Array or a Blob`);
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
return rejected(`"${name}" was not sent: its bytes could not be read (${err instanceof Error ? err.message : String(err)})`);
|
|
25
|
+
}
|
|
26
|
+
const candidate = {
|
|
27
|
+
file_name: name,
|
|
28
|
+
content_type: file.contentType ?? attachmentContentType(name) ?? "",
|
|
29
|
+
size_bytes: bytes.byteLength,
|
|
30
|
+
sha256: hex(await crypto.subtle.digest("SHA-256", bytes)),
|
|
31
|
+
};
|
|
32
|
+
const checked = attachmentSchema.safeParse(candidate);
|
|
33
|
+
if (!checked.success) {
|
|
34
|
+
const reasons = checked.error.issues.map(formatIssue).join("; ");
|
|
35
|
+
return rejected(`"${name}" was not sent: ${reasons}`, reasons);
|
|
36
|
+
}
|
|
37
|
+
return { ok: true, file: { attachment: checked.data, bytes } };
|
|
38
|
+
}
|
|
9
39
|
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
10
40
|
const DEFAULT_MAX_RETRY_AFTER_MS = 5_000;
|
|
11
41
|
const refOf = (document) => {
|
|
@@ -148,25 +178,68 @@ export class QbosyncClient {
|
|
|
148
178
|
* Sends invoices and credit memos, any number, in batches of 100. Each is checked against the
|
|
149
179
|
* contract first; one that fails is not sent, and does not stop the others.
|
|
150
180
|
*
|
|
181
|
+
* `options.files` sends files with documents (0.9.0): each document's files go to QBO Sync first, then the
|
|
182
|
+
* document, which names them. QuickBooks shows them on the record once it has posted. A document whose file
|
|
183
|
+
* could not be sent is not sent either, and its result says why.
|
|
184
|
+
*
|
|
151
185
|
* Send each document once, as version 1: QBO Sync keeps it exactly as first received while it waits to
|
|
152
186
|
* post and once it is in QuickBooks, and sending the same version again is always safe (`unchanged`). A
|
|
153
187
|
* document QuickBooks refused (status `failed`), or a person rolled back (status `deleted`), is corrected
|
|
154
188
|
* by sending it again under the same `source_ref` as the next version (2, then 3). One in QuickBooks is
|
|
155
189
|
* corrected by a credit memo or vendor credit, or rolled back first.
|
|
156
190
|
*/
|
|
157
|
-
async sendDocuments(documents) {
|
|
191
|
+
async sendDocuments(documents, options = {}) {
|
|
158
192
|
const results = [];
|
|
159
193
|
const sendable = [];
|
|
160
|
-
|
|
194
|
+
const inOrder = () => [...results].sort((a, b) => a.index - b.index);
|
|
195
|
+
const filesBy = options.files ?? {};
|
|
196
|
+
const stray = Object.keys(filesBy).find((ref) => !documents.some((d) => refOf(d) === ref));
|
|
197
|
+
// A mistyped ref would otherwise send its document without its files, and say nothing.
|
|
198
|
+
if (stray !== undefined)
|
|
199
|
+
return { ...rejected(`Nothing was sent: files are given for "${stray}", which is none of the documents' source_ref`), results: [] };
|
|
200
|
+
for (const [index, original] of documents.entries()) {
|
|
201
|
+
const ref = refOf(original);
|
|
202
|
+
const given = ref !== null ? (filesBy[ref] ?? []) : [];
|
|
203
|
+
const prepared = [];
|
|
204
|
+
let unread = null;
|
|
205
|
+
for (const file of given) {
|
|
206
|
+
const one = await prepareFile(file);
|
|
207
|
+
if (!one.ok) {
|
|
208
|
+
unread = one;
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
prepared.push(one.file);
|
|
212
|
+
}
|
|
213
|
+
if (unread) {
|
|
214
|
+
results.push({ index, source_ref: ref, outcome: { kind: "parked", status: "refused", error: unread.error } });
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const named = original?.attachments;
|
|
218
|
+
const document = prepared.length
|
|
219
|
+
? { ...original, attachments: [...(Array.isArray(named) ? named : []), ...prepared.map((p) => p.attachment)] }
|
|
220
|
+
: original;
|
|
161
221
|
const checked = checkDocument(document);
|
|
162
222
|
if (checked.ok)
|
|
163
|
-
sendable.push({ index, document: checked.document });
|
|
223
|
+
sendable.push({ index, document: checked.document, files: prepared });
|
|
164
224
|
else
|
|
165
|
-
results.push({ index, source_ref:
|
|
166
|
-
}
|
|
167
|
-
const inOrder = () => [...results].sort((a, b) => a.index - b.index);
|
|
225
|
+
results.push({ index, source_ref: ref, outcome: { kind: "parked", status: "refused", error: checked.reasons.join("; ") } });
|
|
226
|
+
}
|
|
168
227
|
for (let i = 0; i < sendable.length; i += MAX_DOCUMENTS_PER_REQUEST) {
|
|
169
|
-
const batch =
|
|
228
|
+
const batch = [];
|
|
229
|
+
// The files first: QBO Sync accepts a document only once every file it names has arrived.
|
|
230
|
+
for (const one of sendable.slice(i, i + MAX_DOCUMENTS_PER_REQUEST)) {
|
|
231
|
+
const failed = await this.uploadFiles(one.document, one.files);
|
|
232
|
+
if (!failed)
|
|
233
|
+
batch.push(one);
|
|
234
|
+
else if (failed.reason === "not_connected" || failed.reason === "ended")
|
|
235
|
+
return { ...failed, results: inOrder() };
|
|
236
|
+
else if (failed.reason === "rejected")
|
|
237
|
+
results.push({ index: one.index, source_ref: refOf(one.document), outcome: { kind: "parked", status: "refused", error: failed.error } });
|
|
238
|
+
else
|
|
239
|
+
results.push({ index: one.index, source_ref: refOf(one.document), outcome: { kind: "failure", error: failed.error } });
|
|
240
|
+
}
|
|
241
|
+
if (!batch.length)
|
|
242
|
+
continue;
|
|
170
243
|
const answered = await this.sendBatch(batch.map((b) => b.document));
|
|
171
244
|
if (!answered.ok)
|
|
172
245
|
return { ...answered, results: inOrder() };
|
|
@@ -202,6 +275,84 @@ export class QbosyncClient {
|
|
|
202
275
|
}
|
|
203
276
|
return { ok: true, answers: results };
|
|
204
277
|
}
|
|
278
|
+
// ---- attachments
|
|
279
|
+
/**
|
|
280
|
+
* Sends one file to QBO Sync for a company, so a document can name it (0.9.0). Answers the `attachment` to put in
|
|
281
|
+
* the document's `attachments` list. The same bytes sent again for the same company are recognised and not sent
|
|
282
|
+
* twice, so this is safe to repeat. `sendDocuments` does this for you when given `files`.
|
|
283
|
+
*/
|
|
284
|
+
async uploadAttachment(input) {
|
|
285
|
+
const prepared = await prepareFile(input);
|
|
286
|
+
if (!prepared.ok)
|
|
287
|
+
return prepared;
|
|
288
|
+
const sent = await this.uploadPrepared(input.companyKey, prepared.file);
|
|
289
|
+
return sent.ok ? { ok: true, attachment: prepared.file.attachment, alreadyHeld: sent.alreadyHeld } : sent;
|
|
290
|
+
}
|
|
291
|
+
/** Every file of one document, in order; the first failure, or null when all are with QBO Sync. */
|
|
292
|
+
async uploadFiles(document, files) {
|
|
293
|
+
const companyKey = document?.company_key;
|
|
294
|
+
for (const file of files) {
|
|
295
|
+
const sent = await this.uploadPrepared(typeof companyKey === "string" ? companyKey : "", file);
|
|
296
|
+
if (!sent.ok)
|
|
297
|
+
return { ...sent, error: `"${file.attachment.file_name}" was not sent: ${sent.error}` };
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
async uploadPrepared(companyKey, file) {
|
|
302
|
+
const { content_type, size_bytes, sha256 } = file.attachment;
|
|
303
|
+
const request = attachmentUploadSchema.safeParse({ company_key: companyKey, content_type, size_bytes, sha256 });
|
|
304
|
+
if (!request.success) {
|
|
305
|
+
const reasons = request.error.issues.map(formatIssue).join("; ");
|
|
306
|
+
return rejected(reasons, reasons);
|
|
307
|
+
}
|
|
308
|
+
const called = await this.call(ATTACHMENTS_PATH, {
|
|
309
|
+
method: "POST",
|
|
310
|
+
headers: { "Content-Type": "application/json" },
|
|
311
|
+
body: JSON.stringify(request.data),
|
|
312
|
+
});
|
|
313
|
+
if (!called.ok)
|
|
314
|
+
return called;
|
|
315
|
+
const { res } = called;
|
|
316
|
+
const body = (await res.json().catch(() => null));
|
|
317
|
+
if (!res.ok)
|
|
318
|
+
return failureOf(res, body);
|
|
319
|
+
if (body?.held === true)
|
|
320
|
+
return { ok: true, alreadyHeld: true };
|
|
321
|
+
const upload = body?.upload;
|
|
322
|
+
const headers = upload?.headers;
|
|
323
|
+
const plainHeaders = !!headers && typeof headers === "object" && Object.values(headers).every((v) => typeof v === "string");
|
|
324
|
+
if (body?.held !== false || typeof upload?.url !== "string" || upload.method !== "PUT" || !plainHeaders || !this.isUploadAddress(upload.url)) {
|
|
325
|
+
return unexpected(res.status, "QBO Sync's answer says neither that it holds the file nor where to send it");
|
|
326
|
+
}
|
|
327
|
+
try {
|
|
328
|
+
// The app's token never goes here: this address is somewhere to send bytes, not QBO Sync.
|
|
329
|
+
const sent = await this.fetchImpl(upload.url, {
|
|
330
|
+
method: "PUT",
|
|
331
|
+
headers: headers,
|
|
332
|
+
body: file.bytes,
|
|
333
|
+
signal: AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS),
|
|
334
|
+
cache: "no-store",
|
|
335
|
+
});
|
|
336
|
+
await sent.body?.cancel().catch(() => undefined);
|
|
337
|
+
if (sent.ok)
|
|
338
|
+
return { ok: true, alreadyHeld: false };
|
|
339
|
+
const error = `the file store answered ${sent.status}`;
|
|
340
|
+
return sent.status >= 500 || sent.status === 429 ? { ok: false, reason: "unavailable", status: sent.status, error } : { ...rejected(error), status: sent.status };
|
|
341
|
+
}
|
|
342
|
+
catch (err) {
|
|
343
|
+
return { ok: false, reason: "unavailable", error: `the file store could not be reached: ${err instanceof Error ? err.message : String(err)}` };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/** An address the file's bytes may go to: https, or plain http only when QBO Sync itself is reached that way (a local stack). */
|
|
347
|
+
isUploadAddress(url) {
|
|
348
|
+
try {
|
|
349
|
+
const protocol = new URL(url).protocol;
|
|
350
|
+
return protocol === "https:" || (protocol === "http:" && new URL(this.baseUrl).protocol === "http:");
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
205
356
|
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
206
357
|
async documentReport(refs) {
|
|
207
358
|
const documents = [];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* What QBO Sync answers an app. qbosync's own routes build these same types.
|
|
3
3
|
*/
|
|
4
|
+
import type { ReportAttachment } from "./attachments.ts";
|
|
4
5
|
export type ReceiveResultCode = "accepted" | "unchanged" | "stale" | "version_conflict" | "refused" | "ignored" | "error";
|
|
5
6
|
/** One document's result, in the order sent. */
|
|
6
7
|
export interface ReceiveResult {
|
|
@@ -64,6 +65,18 @@ export interface PostedCheck {
|
|
|
64
65
|
checked_at: string | null;
|
|
65
66
|
/** What differs, as sentences; empty unless `differs` or `missing`. */
|
|
66
67
|
differences: string[];
|
|
68
|
+
/**
|
|
69
|
+
* Someone in QBO Sync accepted QuickBooks as right on what the check found (0.10.0): who (their name, else their
|
|
70
|
+
* email), when, and exactly the differences they accepted. `current` is true while QuickBooks still shows exactly
|
|
71
|
+
* those: the document is settled, and its status reports carry no warning. False once QuickBooks changed again. Absent
|
|
72
|
+
* when no one has accepted anything.
|
|
73
|
+
*/
|
|
74
|
+
accepted?: {
|
|
75
|
+
by: string;
|
|
76
|
+
at: string;
|
|
77
|
+
differences: string[];
|
|
78
|
+
current: boolean;
|
|
79
|
+
};
|
|
67
80
|
}
|
|
68
81
|
export interface UnknownEntry {
|
|
69
82
|
source_ref: string;
|
|
@@ -82,6 +95,8 @@ export interface KnownEntry {
|
|
|
82
95
|
error: string | null;
|
|
83
96
|
posted: PostedAmounts | null;
|
|
84
97
|
check: PostedCheck | null;
|
|
98
|
+
/** The files the latest version names, in its order, each with where it stands (0.9.0). Absent when it names none. */
|
|
99
|
+
attachments?: ReportAttachment[];
|
|
85
100
|
}
|
|
86
101
|
/** QBO Sync's answer about one document; `sync_status: "unknown"` means it never received it. */
|
|
87
102
|
export type ReportEntry = UnknownEntry | KnownEntry;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Files attached to a document (0.9.0). A document never carries a file: the app uploads it to QBO Sync first, and
|
|
4
|
+
* the document names it by its SHA-256, the file's fingerprint. A fingerprint and not an id QBO Sync hands out,
|
|
5
|
+
* because the same version sent twice must be the same content: an id made at upload time would change on a retry
|
|
6
|
+
* and turn a safe re-send into a `version_conflict`.
|
|
7
|
+
*
|
|
8
|
+
* Once the document is in QuickBooks, QBO Sync attaches each file to the record there.
|
|
9
|
+
*/
|
|
10
|
+
/** The most files one document may name. */
|
|
11
|
+
export declare const MAX_ATTACHMENTS_PER_DOCUMENT = 10;
|
|
12
|
+
/** The largest file, in bytes: 20 MB. */
|
|
13
|
+
export declare const MAX_ATTACHMENT_BYTES: number;
|
|
14
|
+
/** The longest file name. */
|
|
15
|
+
export declare const MAX_ATTACHMENT_NAME_LENGTH = 200;
|
|
16
|
+
/**
|
|
17
|
+
* The file types QuickBooks accepts as attachments, by extension, each with the content type it is sent as
|
|
18
|
+
* (Intuit, "Attach images and notes", approved file types). QuickBooks refuses anything else, so QBO Sync does too.
|
|
19
|
+
*/
|
|
20
|
+
export declare const ATTACHMENT_CONTENT_TYPES: Readonly<Record<string, string>>;
|
|
21
|
+
/** Every content type a file may be uploaded as. */
|
|
22
|
+
export declare const ATTACHMENT_ALLOWED_CONTENT_TYPES: readonly string[];
|
|
23
|
+
/** A file name's extension, lower case, or null when it has none. */
|
|
24
|
+
export declare function attachmentExtension(fileName: string): string | null;
|
|
25
|
+
/** The content type a file of this name is sent as, or null when its type is not accepted. */
|
|
26
|
+
export declare function attachmentContentType(fileName: string): string | null;
|
|
27
|
+
/** A file's SHA-256, as 64 lower-case hex characters. */
|
|
28
|
+
export declare const sha256Hex: z.ZodString;
|
|
29
|
+
/** A file's size: more than nothing, at most 20 MB. */
|
|
30
|
+
export declare const attachmentSize: z.ZodInt;
|
|
31
|
+
/** The name QuickBooks shows: no folders, no control characters, not padded, with an accepted extension. */
|
|
32
|
+
export declare const attachmentFileName: z.ZodString;
|
|
33
|
+
/** One file a document names. */
|
|
34
|
+
export declare const attachment: z.ZodObject<{
|
|
35
|
+
file_name: z.ZodString;
|
|
36
|
+
content_type: z.ZodString;
|
|
37
|
+
size_bytes: z.ZodInt;
|
|
38
|
+
sha256: z.ZodString;
|
|
39
|
+
}, z.core.$strict>;
|
|
40
|
+
/**
|
|
41
|
+
* A document's files. Two files on the same document cannot share a name (compared without regard to case): before
|
|
42
|
+
* a retry QBO Sync asks QuickBooks which files the record already holds, and QuickBooks answers with names. Any
|
|
43
|
+
* other document may reuse a name.
|
|
44
|
+
*/
|
|
45
|
+
export declare const attachments: z.ZodArray<z.ZodObject<{
|
|
46
|
+
file_name: z.ZodString;
|
|
47
|
+
content_type: z.ZodString;
|
|
48
|
+
size_bytes: z.ZodInt;
|
|
49
|
+
sha256: z.ZodString;
|
|
50
|
+
}, z.core.$strict>>;
|
|
51
|
+
export type Attachment = z.infer<typeof attachment>;
|
|
52
|
+
/** Where an app asks for somewhere to send a file's bytes. */
|
|
53
|
+
export declare const ATTACHMENTS_PATH = "/api/v1/attachments";
|
|
54
|
+
/**
|
|
55
|
+
* Asking where to send a file. Not its name: a file is known by its bytes, and each document that names it gives it
|
|
56
|
+
* a name of its own.
|
|
57
|
+
*/
|
|
58
|
+
export declare const attachmentUploadSchema: z.ZodObject<{
|
|
59
|
+
/** The company as the app's documents name it. */
|
|
60
|
+
company_key: z.ZodString;
|
|
61
|
+
content_type: z.ZodString;
|
|
62
|
+
size_bytes: z.ZodInt;
|
|
63
|
+
sha256: z.ZodString;
|
|
64
|
+
}, z.core.$strict>;
|
|
65
|
+
export type AttachmentUploadRequest = z.infer<typeof attachmentUploadSchema>;
|
|
66
|
+
/**
|
|
67
|
+
* QBO Sync's answer. `held: true`: it already holds these bytes for this company, and there is nothing to send.
|
|
68
|
+
* Otherwise `upload` says where to send them: one request, the bytes as the body, with exactly these headers. The
|
|
69
|
+
* address is only somewhere to send bytes; what stands behind it is QBO Sync's business and may change.
|
|
70
|
+
*/
|
|
71
|
+
export type AttachmentUploadAnswer = {
|
|
72
|
+
held: true;
|
|
73
|
+
} | {
|
|
74
|
+
held: false;
|
|
75
|
+
upload: {
|
|
76
|
+
url: string;
|
|
77
|
+
method: "PUT";
|
|
78
|
+
headers: Record<string, string>;
|
|
79
|
+
expires_at: string | null;
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
/** What QBO Sync holds for one of a document's files, in the document report. */
|
|
83
|
+
export interface ReportAttachment {
|
|
84
|
+
file_name: string;
|
|
85
|
+
sha256: string;
|
|
86
|
+
/**
|
|
87
|
+
* `waiting`: not in QuickBooks yet. `attached`: on the record. `failed`: an attempt failed and is retried.
|
|
88
|
+
* `refused`: QuickBooks, or QBO Sync's own check of the bytes, refused the file; it is not retried.
|
|
89
|
+
* `not_held`: the document was rolled back and the file could not be kept; send it again with the next version.
|
|
90
|
+
* `needs_upload`: QBO Sync's copy was missing or not this file; send the file and the document again (the same
|
|
91
|
+
* version: `sendDocuments` with `files` does both), and it is sent.
|
|
92
|
+
*/
|
|
93
|
+
status: string;
|
|
94
|
+
error?: string;
|
|
95
|
+
/** QuickBooks' id of the attachment, once attached. */
|
|
96
|
+
qbo_id?: string;
|
|
97
|
+
attached_at?: string;
|
|
98
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Files attached to a document (0.9.0). A document never carries a file: the app uploads it to QBO Sync first, and
|
|
4
|
+
* the document names it by its SHA-256, the file's fingerprint. A fingerprint and not an id QBO Sync hands out,
|
|
5
|
+
* because the same version sent twice must be the same content: an id made at upload time would change on a retry
|
|
6
|
+
* and turn a safe re-send into a `version_conflict`.
|
|
7
|
+
*
|
|
8
|
+
* Once the document is in QuickBooks, QBO Sync attaches each file to the record there.
|
|
9
|
+
*/
|
|
10
|
+
/** The most files one document may name. */
|
|
11
|
+
export const MAX_ATTACHMENTS_PER_DOCUMENT = 10;
|
|
12
|
+
/** The largest file, in bytes: 20 MB. */
|
|
13
|
+
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
14
|
+
/** The longest file name. */
|
|
15
|
+
export const MAX_ATTACHMENT_NAME_LENGTH = 200;
|
|
16
|
+
/**
|
|
17
|
+
* The file types QuickBooks accepts as attachments, by extension, each with the content type it is sent as
|
|
18
|
+
* (Intuit, "Attach images and notes", approved file types). QuickBooks refuses anything else, so QBO Sync does too.
|
|
19
|
+
*/
|
|
20
|
+
export const ATTACHMENT_CONTENT_TYPES = {
|
|
21
|
+
pdf: "application/pdf",
|
|
22
|
+
png: "image/png",
|
|
23
|
+
jpg: "image/jpeg",
|
|
24
|
+
jpeg: "image/jpeg",
|
|
25
|
+
gif: "image/gif",
|
|
26
|
+
tif: "image/tiff",
|
|
27
|
+
tiff: "image/tiff",
|
|
28
|
+
csv: "text/csv",
|
|
29
|
+
txt: "text/plain",
|
|
30
|
+
rtf: "text/rtf",
|
|
31
|
+
xml: "text/xml",
|
|
32
|
+
doc: "application/msword",
|
|
33
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
34
|
+
xls: "application/vnd.ms-excel",
|
|
35
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
36
|
+
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
37
|
+
ai: "application/postscript",
|
|
38
|
+
eps: "application/postscript",
|
|
39
|
+
};
|
|
40
|
+
/** Every content type a file may be uploaded as. */
|
|
41
|
+
export const ATTACHMENT_ALLOWED_CONTENT_TYPES = [...new Set(Object.values(ATTACHMENT_CONTENT_TYPES))];
|
|
42
|
+
/** A file name's extension, lower case, or null when it has none. */
|
|
43
|
+
export function attachmentExtension(fileName) {
|
|
44
|
+
const match = /\.([A-Za-z0-9]+)$/.exec(fileName);
|
|
45
|
+
return match ? match[1].toLowerCase() : null;
|
|
46
|
+
}
|
|
47
|
+
/** The content type a file of this name is sent as, or null when its type is not accepted. */
|
|
48
|
+
export function attachmentContentType(fileName) {
|
|
49
|
+
const extension = attachmentExtension(fileName);
|
|
50
|
+
return extension ? (ATTACHMENT_CONTENT_TYPES[extension] ?? null) : null;
|
|
51
|
+
}
|
|
52
|
+
const acceptedTypes = Object.keys(ATTACHMENT_CONTENT_TYPES).join(", ");
|
|
53
|
+
/** A file's SHA-256, as 64 lower-case hex characters. */
|
|
54
|
+
export const sha256Hex = z.string().regex(/^[0-9a-f]{64}$/, "must be the file's SHA-256 as 64 lower-case hex characters");
|
|
55
|
+
/** A file's size: more than nothing, at most 20 MB. */
|
|
56
|
+
export const attachmentSize = z
|
|
57
|
+
.int("must be a whole number of bytes")
|
|
58
|
+
.positive("must be more than zero")
|
|
59
|
+
.max(MAX_ATTACHMENT_BYTES, "must be at most 20 MB (20971520 bytes)");
|
|
60
|
+
/** The name QuickBooks shows: no folders, no control characters, not padded, with an accepted extension. */
|
|
61
|
+
export const attachmentFileName = z
|
|
62
|
+
.string()
|
|
63
|
+
.max(MAX_ATTACHMENT_NAME_LENGTH, `must be at most ${MAX_ATTACHMENT_NAME_LENGTH} characters`)
|
|
64
|
+
.refine((s) => s.length > 0 && s.trim() === s, "must not be empty or start or end with a space")
|
|
65
|
+
.refine((s) => !/[\\/\u0000-\u001f\u007f]/.test(s), "must be a plain file name: no folders and no control characters")
|
|
66
|
+
.refine((s) => attachmentContentType(s) !== null, `must end in a file type QuickBooks accepts (${acceptedTypes})`);
|
|
67
|
+
/** One file a document names. */
|
|
68
|
+
export const attachment = z
|
|
69
|
+
.strictObject({
|
|
70
|
+
file_name: attachmentFileName,
|
|
71
|
+
content_type: z.string(),
|
|
72
|
+
size_bytes: attachmentSize,
|
|
73
|
+
sha256: sha256Hex,
|
|
74
|
+
})
|
|
75
|
+
.superRefine((file, ctx) => {
|
|
76
|
+
const expected = attachmentContentType(file.file_name);
|
|
77
|
+
// A name that is not accepted is already reported on `file_name`.
|
|
78
|
+
if (expected !== null && file.content_type !== expected) {
|
|
79
|
+
ctx.addIssue({ code: "custom", path: ["content_type"], message: `must be "${expected}" for a .${attachmentExtension(file.file_name)} file` });
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
/**
|
|
83
|
+
* A document's files. Two files on the same document cannot share a name (compared without regard to case): before
|
|
84
|
+
* a retry QBO Sync asks QuickBooks which files the record already holds, and QuickBooks answers with names. Any
|
|
85
|
+
* other document may reuse a name.
|
|
86
|
+
*/
|
|
87
|
+
export const attachments = z
|
|
88
|
+
.array(attachment)
|
|
89
|
+
.max(MAX_ATTACHMENTS_PER_DOCUMENT, `a document names at most ${MAX_ATTACHMENTS_PER_DOCUMENT} files`)
|
|
90
|
+
.superRefine((files, ctx) => {
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
files.forEach((file, i) => {
|
|
93
|
+
const name = typeof file.file_name === "string" ? file.file_name.toLowerCase() : "";
|
|
94
|
+
if (seen.has(name))
|
|
95
|
+
ctx.addIssue({ code: "custom", path: [i, "file_name"], message: `"${file.file_name}" is used by another file on this document` });
|
|
96
|
+
seen.add(name);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
// ---- POST /api/v1/attachments
|
|
100
|
+
/** Where an app asks for somewhere to send a file's bytes. */
|
|
101
|
+
export const ATTACHMENTS_PATH = "/api/v1/attachments";
|
|
102
|
+
/**
|
|
103
|
+
* Asking where to send a file. Not its name: a file is known by its bytes, and each document that names it gives it
|
|
104
|
+
* a name of its own.
|
|
105
|
+
*/
|
|
106
|
+
export const attachmentUploadSchema = z.strictObject({
|
|
107
|
+
/** The company as the app's documents name it. */
|
|
108
|
+
company_key: z.string().refine((s) => s.trim().length > 0, "must not be empty"),
|
|
109
|
+
content_type: z.string().refine((s) => ATTACHMENT_ALLOWED_CONTENT_TYPES.includes(s), "must be the content type of a file type QuickBooks accepts"),
|
|
110
|
+
size_bytes: attachmentSize,
|
|
111
|
+
sha256: sha256Hex,
|
|
112
|
+
});
|
package/dist/contract/bill.d.ts
CHANGED
|
@@ -169,6 +169,12 @@ export declare const billSchema: z.ZodObject<{
|
|
|
169
169
|
active: "active";
|
|
170
170
|
voided: "voided";
|
|
171
171
|
}>;
|
|
172
|
+
attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
173
|
+
file_name: z.ZodString;
|
|
174
|
+
content_type: z.ZodString;
|
|
175
|
+
size_bytes: z.ZodInt;
|
|
176
|
+
sha256: z.ZodString;
|
|
177
|
+
}, z.core.$strict>>>;
|
|
172
178
|
}, z.core.$strict>;
|
|
173
179
|
/**
|
|
174
180
|
* What a vendor gave back: posted as a Vendor Credit, which lowers what the company owes that vendor.
|
|
@@ -264,6 +270,12 @@ export declare const vendorCreditSchema: z.ZodObject<{
|
|
|
264
270
|
active: "active";
|
|
265
271
|
voided: "voided";
|
|
266
272
|
}>;
|
|
273
|
+
attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
274
|
+
file_name: z.ZodString;
|
|
275
|
+
content_type: z.ZodString;
|
|
276
|
+
size_bytes: z.ZodInt;
|
|
277
|
+
sha256: z.ZodString;
|
|
278
|
+
}, z.core.$strict>>>;
|
|
267
279
|
}, z.core.$strict>;
|
|
268
280
|
export type BillLine = z.infer<typeof billLine>;
|
|
269
281
|
export type Vendor = z.infer<typeof vendor>;
|
|
@@ -92,6 +92,13 @@ export declare const envelope: {
|
|
|
92
92
|
active: "active";
|
|
93
93
|
voided: "voided";
|
|
94
94
|
}>;
|
|
95
|
+
/** The document's files, each uploaded to QBO Sync first and named here by its SHA-256 (0.9.0, `attachments.ts`). */
|
|
96
|
+
attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
97
|
+
file_name: z.ZodString;
|
|
98
|
+
content_type: z.ZodString;
|
|
99
|
+
size_bytes: z.ZodInt;
|
|
100
|
+
sha256: z.ZodString;
|
|
101
|
+
}, z.core.$strict>>>;
|
|
95
102
|
};
|
|
96
103
|
/**
|
|
97
104
|
* A line's `amount_cents` must be exactly `quantity × unit_price_cents`. Compared with a
|
package/dist/contract/common.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { attachments } from "./attachments.js";
|
|
2
3
|
/**
|
|
3
4
|
* The pieces every v1 document shares. These schemas ARE the contract: QBO Sync checks
|
|
4
5
|
* every document it receives with this same code.
|
|
@@ -73,6 +74,8 @@ export const envelope = {
|
|
|
73
74
|
company_key: text,
|
|
74
75
|
version: z.int("must be a whole number").min(1, "must be 1 or more"),
|
|
75
76
|
status: z.enum(["active", "voided"], 'must be "active" or "voided"'),
|
|
77
|
+
/** The document's files, each uploaded to QBO Sync first and named here by its SHA-256 (0.9.0, `attachments.ts`). */
|
|
78
|
+
attachments: attachments.optional(),
|
|
76
79
|
};
|
|
77
80
|
/**
|
|
78
81
|
* A line's `amount_cents` must be exactly `quantity × unit_price_cents`. Compared with a
|
|
@@ -72,6 +72,12 @@ export declare const creditMemoSchema: z.ZodObject<{
|
|
|
72
72
|
active: "active";
|
|
73
73
|
voided: "voided";
|
|
74
74
|
}>;
|
|
75
|
+
attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
76
|
+
file_name: z.ZodString;
|
|
77
|
+
content_type: z.ZodString;
|
|
78
|
+
size_bytes: z.ZodInt;
|
|
79
|
+
sha256: z.ZodString;
|
|
80
|
+
}, z.core.$strict>>>;
|
|
75
81
|
}, z.core.$strict>;
|
|
76
82
|
export type CreditMemoDTO = z.infer<typeof creditMemoSchema>;
|
|
77
83
|
export type CreditMemoLine = z.infer<typeof creditMemoLine>;
|