@company-six/qbosync 0.6.1 → 0.9.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 +40 -3
- package/dist/client.d.ts +46 -5
- package/dist/client.js +164 -11
- package/dist/contract/answers.d.ts +3 -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
|
@@ -103,7 +103,7 @@ The first time, the link makes that person a QBO Sync user who sees only your co
|
|
|
103
103
|
const sent = await qbosync.sendDocuments([invoice, creditMemo]);
|
|
104
104
|
|
|
105
105
|
for (const { source_ref, outcome } of sent.results) {
|
|
106
|
-
if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it.
|
|
106
|
+
if (outcome.kind === "sent") markSent(source_ref); // QBO Sync holds it. Send it again only to correct it (below).
|
|
107
107
|
if (outcome.kind === "parked") needsAPerson(source_ref, outcome.error); // sending again changes nothing
|
|
108
108
|
if (outcome.kind === "failure") retryLater(source_ref); // not the document's fault
|
|
109
109
|
}
|
|
@@ -112,7 +112,11 @@ if (!sent.ok) console.error(sent.error); // a batch failed; what has no result h
|
|
|
112
112
|
|
|
113
113
|
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`.
|
|
114
114
|
|
|
115
|
-
**A document is sent once
|
|
115
|
+
**A document is sent once, unless it fails.** Start at `version` 1. QBO Sync keeps a document exactly as first received while it waits to post and once it is in QuickBooks. Sending the same version again is always safe (QBO Sync answers `unchanged`); different content under the same version is a `version_conflict`.
|
|
116
|
+
|
|
117
|
+
**Correcting one that failed or was rolled back.** When QuickBooks refused a document (its status report says `failed`, with QuickBooks' reason, for example a bill number that vendor already has), or a person rolled it back in QBO Sync (status `deleted`), send the corrected document under the **same `source_ref`** as the **next `version`**: 2, then 3. QBO Sync replaces its copy and posts it like a new arrival; the report route then answers the new `latest_version`, and `posted_version` once it posts. Send `status: "voided"` as the next version instead to withdraw it: it never posts. A new version keeps the company; an invoice's keeps every line a credit memo applies to, and a bill's the vendor its vendor credits are from.
|
|
118
|
+
|
|
119
|
+
In every other state a higher version is `refused`, and the reason says what to do: while it waits to post, wait for it to post or fail; once it is in QuickBooks, send a credit memo (for a bill, a vendor credit), or have a person roll it back in QBO Sync and then send the next version. A version that skips ahead (3 after 1) is refused too. This needs no particular SDK version: it is how QBO Sync answers.
|
|
116
120
|
|
|
117
121
|
**Item codes and products.** QuickBooks puts every invoice and credit memo line on a product, and QBO Sync picks it by the line's `item_code`: the product the company chose for your code in QBO Sync's Setup → Products, else the QuickBooks product with that SKU, else (by default) a new product named after the line. Send real SKUs if you have a catalogue, or a few fixed category codes (`SALES`, `SHIPPING`) if you don't, the same code for the same thing every time. A company can set your app to never create products; then a line whose code has no product waits in QBO Sync until the company chooses one, and its status report says so. Nothing changes in what you send.
|
|
118
122
|
|
|
@@ -162,7 +166,38 @@ const bill: BillDTO = {
|
|
|
162
166
|
- `customer` (on the bill, or on one line) puts the cost on that customer for job costing; it is not billed to them again.
|
|
163
167
|
- A vendor credit has the same fields, no terms, and may name its bill with `applies_to_bill_ref`. QuickBooks offers the credit when the company next pays that vendor.
|
|
164
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.
|
|
165
|
-
- Like an invoice, a bill is kept as first received
|
|
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
|
+
|
|
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`.
|
|
166
201
|
|
|
167
202
|
## 6. Receive status reports
|
|
168
203
|
|
|
@@ -199,6 +234,8 @@ export async function POST(req: Request) {
|
|
|
199
234
|
|
|
200
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.)
|
|
201
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
|
+
|
|
202
239
|
### Testing your status report route
|
|
203
240
|
|
|
204
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:
|
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,12 +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
|
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
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
|
+
*
|
|
155
|
+
* Send each document once, as version 1: QBO Sync keeps it exactly as first received while it waits to
|
|
156
|
+
* post and once it is in QuickBooks, and sending the same version again is always safe (`unchanged`). A
|
|
157
|
+
* document QuickBooks refused (status `failed`), or a person rolled back (status `deleted`), is corrected
|
|
158
|
+
* by sending it again under the same `source_ref` as the next version (2, then 3). One in QuickBooks is
|
|
159
|
+
* corrected by a credit memo or vendor credit, or rolled back first.
|
|
132
160
|
*/
|
|
133
|
-
sendDocuments(documents: readonly unknown[]): Promise<SendResult>;
|
|
161
|
+
sendDocuments(documents: readonly unknown[], options?: SendOptions): Promise<SendResult>;
|
|
134
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;
|
|
135
176
|
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
136
177
|
documentReport(refs: readonly string[]): Promise<{
|
|
137
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,23 +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
|
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
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
|
+
*
|
|
185
|
+
* Send each document once, as version 1: QBO Sync keeps it exactly as first received while it waits to
|
|
186
|
+
* post and once it is in QuickBooks, and sending the same version again is always safe (`unchanged`). A
|
|
187
|
+
* document QuickBooks refused (status `failed`), or a person rolled back (status `deleted`), is corrected
|
|
188
|
+
* by sending it again under the same `source_ref` as the next version (2, then 3). One in QuickBooks is
|
|
189
|
+
* corrected by a credit memo or vendor credit, or rolled back first.
|
|
154
190
|
*/
|
|
155
|
-
async sendDocuments(documents) {
|
|
191
|
+
async sendDocuments(documents, options = {}) {
|
|
156
192
|
const results = [];
|
|
157
193
|
const sendable = [];
|
|
158
|
-
|
|
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;
|
|
159
221
|
const checked = checkDocument(document);
|
|
160
222
|
if (checked.ok)
|
|
161
|
-
sendable.push({ index, document: checked.document });
|
|
223
|
+
sendable.push({ index, document: checked.document, files: prepared });
|
|
162
224
|
else
|
|
163
|
-
results.push({ index, source_ref:
|
|
164
|
-
}
|
|
165
|
-
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
|
+
}
|
|
166
227
|
for (let i = 0; i < sendable.length; i += MAX_DOCUMENTS_PER_REQUEST) {
|
|
167
|
-
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;
|
|
168
243
|
const answered = await this.sendBatch(batch.map((b) => b.document));
|
|
169
244
|
if (!answered.ok)
|
|
170
245
|
return { ...answered, results: inOrder() };
|
|
@@ -200,6 +275,84 @@ export class QbosyncClient {
|
|
|
200
275
|
}
|
|
201
276
|
return { ok: true, answers: results };
|
|
202
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
|
+
}
|
|
203
356
|
/** What QBO Sync holds for these documents, in the order asked, any number of refs: for an app's daily report. */
|
|
204
357
|
async documentReport(refs) {
|
|
205
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 {
|
|
@@ -82,6 +83,8 @@ export interface KnownEntry {
|
|
|
82
83
|
error: string | null;
|
|
83
84
|
posted: PostedAmounts | null;
|
|
84
85
|
check: PostedCheck | null;
|
|
86
|
+
/** The files the latest version names, in its order, each with where it stands (0.9.0). Absent when it names none. */
|
|
87
|
+
attachments?: ReportAttachment[];
|
|
85
88
|
}
|
|
86
89
|
/** QBO Sync's answer about one document; `sync_status: "unknown"` means it never received it. */
|
|
87
90
|
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
|