@company-six/qbosync 0.7.0 → 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 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:
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
- documents.forEach((document, index) => {
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: refOf(document), outcome: { kind: "parked", status: "refused", error: checked.reasons.join("; ") } });
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 = sendable.slice(i, i + MAX_DOCUMENTS_PER_REQUEST);
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 {
@@ -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
+ });
@@ -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
@@ -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>;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A document's error as a sentence for the people who read it.
3
+ *
4
+ * Most errors QBO Sync keeps are already sentences it wrote ("Waiting: …"), and pass through unchanged. The
5
+ * exception is a refusal from QuickBooks itself, kept as it arrived:
6
+ *
7
+ * QuickBooks API POST /v3/company/9130…/vendorcredit failed: 400 - {"Fault":{"Error":[{"Message":"Invalid
8
+ * Reference Id","Detail":"…","code":"2500"}],"type":"ValidationFault"},"time":"…"}
9
+ *
10
+ * That text stays in QBO Sync's records, where it helps whoever investigates. Screens, and the reports QBO Sync
11
+ * sends to apps, show `text` instead; `technical` holds the original for a "Technical details" line.
12
+ *
13
+ * ## One place for every refusal
14
+ *
15
+ * `RULES` is the whole list: each entry recognises one kind of refusal and says it in words, the first match wins,
16
+ * and a refusal no entry knows still reads as QuickBooks' own sentence without the wrapper. A new kind is one new
17
+ * entry here (and a test): nothing else changes, in QBO Sync or in any app.
18
+ *
19
+ * QBO Sync rewords before it reports to an app, so an app shows `error` as it arrives. An app holding text stored
20
+ * before that can pass it through this function; text already in words comes back as it is. Safe in a browser.
21
+ */
22
+ export interface ErrorInWords {
23
+ /** What to show a person. */
24
+ text: string;
25
+ /** The original, when `text` reworded any of it; null when the error was already in words. */
26
+ technical: string | null;
27
+ }
28
+ /** A refusal from QuickBooks, as a rule reads it. */
29
+ export interface QuickBooksRefusal {
30
+ /** The HTTP status QuickBooks answered with. */
31
+ status: number;
32
+ /** QuickBooks' own number for the fault ("2500"); "" when it sent none. */
33
+ code: string;
34
+ /** QuickBooks' short name for the fault ("Invalid Reference Id"); "" when it sent none. */
35
+ message: string;
36
+ /** QuickBooks' sentence about it; "" when it sent none. */
37
+ detail: string;
38
+ /** What was being saved, in words ("vendor credit"); "" when not known. */
39
+ thing: string;
40
+ /** True when QBO Sync was only reading from QuickBooks. */
41
+ reading: boolean;
42
+ /** True when the refused call was the renewal of QBO Sync's access to the company's QuickBooks. */
43
+ renewal: boolean;
44
+ }
45
+ /** `error` for a person to read, and the original when any of it was reworded. */
46
+ export declare function errorInWords(error: string | null | undefined): ErrorInWords;
@@ -0,0 +1,193 @@
1
+ /**
2
+ * A document's error as a sentence for the people who read it.
3
+ *
4
+ * Most errors QBO Sync keeps are already sentences it wrote ("Waiting: …"), and pass through unchanged. The
5
+ * exception is a refusal from QuickBooks itself, kept as it arrived:
6
+ *
7
+ * QuickBooks API POST /v3/company/9130…/vendorcredit failed: 400 - {"Fault":{"Error":[{"Message":"Invalid
8
+ * Reference Id","Detail":"…","code":"2500"}],"type":"ValidationFault"},"time":"…"}
9
+ *
10
+ * That text stays in QBO Sync's records, where it helps whoever investigates. Screens, and the reports QBO Sync
11
+ * sends to apps, show `text` instead; `technical` holds the original for a "Technical details" line.
12
+ *
13
+ * ## One place for every refusal
14
+ *
15
+ * `RULES` is the whole list: each entry recognises one kind of refusal and says it in words, the first match wins,
16
+ * and a refusal no entry knows still reads as QuickBooks' own sentence without the wrapper. A new kind is one new
17
+ * entry here (and a test): nothing else changes, in QBO Sync or in any app.
18
+ *
19
+ * QBO Sync rewords before it reports to an app, so an app shows `error` as it arrives. An app holding text stored
20
+ * before that can pass it through this function; text already in words comes back as it is. Safe in a browser.
21
+ */
22
+ /** QuickBooks' record names, as they appear in the address called, in words. */
23
+ const THINGS = {
24
+ invoice: "invoice",
25
+ creditmemo: "credit memo",
26
+ bill: "bill",
27
+ vendorcredit: "vendor credit",
28
+ payment: "payment",
29
+ refundreceipt: "refund",
30
+ billpayment: "bill payment",
31
+ purchase: "expense",
32
+ transfer: "transfer",
33
+ deposit: "deposit",
34
+ journalentry: "journal entry",
35
+ vendor: "vendor",
36
+ customer: "customer",
37
+ item: "product",
38
+ account: "account",
39
+ attachable: "attachment",
40
+ // A file being sent to, or read back from, a record (QBO Sync migration 069).
41
+ upload: "file",
42
+ download: "file",
43
+ };
44
+ const AGAIN = "then try again";
45
+ const the = (r) => (r.thing ? `the ${r.thing}` : "this");
46
+ const a = (r) => (r.thing ? `${/^[aeiou]/.test(r.thing) ? "an" : "a"} ${r.thing}` : "a record");
47
+ const says = (r) => `${r.message} ${r.detail}`;
48
+ /**
49
+ * Every refusal QBO Sync says in its own words, most specific first. What the connection or QuickBooks itself is
50
+ * doing (the first three) outranks what the fault says, because then the fault is not about the document.
51
+ */
52
+ const RULES = [
53
+ {
54
+ // QBO Sync's access ran out or was taken away: nothing about the document.
55
+ when: (r) => r.renewal || r.status === 401 || r.code === "3200" || /AuthenticationFailed|invalid_grant/i.test(says(r)),
56
+ say: () => `QBO Sync's connection to this company's QuickBooks has expired or was removed. Reconnect QuickBooks in QBO Sync, ${AGAIN}.`,
57
+ },
58
+ {
59
+ when: (r) => r.status === 429,
60
+ say: () => "QuickBooks is handling too many requests right now. Try again in a few minutes.",
61
+ },
62
+ {
63
+ when: (r) => r.status >= 500,
64
+ say: () => "QuickBooks had a problem on its side and could not complete this. Try again in a few minutes.",
65
+ },
66
+ {
67
+ // "Vendor assigned to this transaction has been deleted. Before you can modify this transaction, you must
68
+ // restore S&S (deleted)." Merging two records deletes one of them, which is how this usually happens.
69
+ when: (r) => /has been deleted/i.test(r.detail),
70
+ say: (r) => {
71
+ const kind = (r.detail.match(/([A-Za-z]+) assigned to this transaction has been deleted/)?.[1] ?? "").toLowerCase();
72
+ const name = r.detail.match(/you must restore (.+?) \(deleted\)/i)?.[1]?.trim();
73
+ const what = kind ? `The ${kind}${name ? ` "${name}"` : ""}` : "A record";
74
+ const kept = kind ? `the ${kind} you kept` : "the one you kept";
75
+ return (`${what} that ${the(r)} uses was deleted in QuickBooks (merging two records deletes one of them). ` +
76
+ `Restore it in QuickBooks, or ask QBO Sync staff to use ${kept}, ${AGAIN}.`);
77
+ },
78
+ },
79
+ {
80
+ when: (r) => /made inactive/i.test(r.detail),
81
+ say: (r) => `Something ${the(r)} uses (a customer, vendor, product, account or class) has been made inactive in QuickBooks. ` +
82
+ `Make it active again in QuickBooks, ${AGAIN}.`,
83
+ },
84
+ {
85
+ when: (r) => r.code === "6140" || /Duplicate Document Number/i.test(says(r)),
86
+ say: (r) => `QuickBooks already has ${a(r)} with this number.`,
87
+ },
88
+ {
89
+ when: (r) => r.code === "6240" || /Duplicate Name Exists/i.test(says(r)),
90
+ say: () => "QuickBooks already uses this name. It keeps one list of names across customers, vendors and employees, so a name " +
91
+ `cannot be used twice. Rename one of them in QuickBooks, ${AGAIN}.`,
92
+ },
93
+ {
94
+ when: (r) => r.code === "5010" || /Stale Object/i.test(says(r)),
95
+ say: () => "Someone changed this in QuickBooks at the same moment. Try again.",
96
+ },
97
+ {
98
+ when: (r) => /Account Period Closed|closing date|books (are|were|have been) closed/i.test(says(r)),
99
+ say: (r) => `The date of ${the(r)} falls in a period this company's books are closed for in QuickBooks. ` +
100
+ `Reopen the period in QuickBooks (or ask whoever closed it), ${AGAIN}.`,
101
+ },
102
+ {
103
+ when: (r) => r.code === "610" || /Object Not Found/i.test(says(r)),
104
+ say: (r) => `QuickBooks could not find a record ${the(r)} needs: it may have been deleted there.`,
105
+ },
106
+ ];
107
+ /** A refusal no rule knows: QuickBooks' own sentence, without the wrapper. */
108
+ function inQuickBooksWords(r) {
109
+ const lead = r.reading ? "QuickBooks could not be read" : `QuickBooks refused ${the(r)}`;
110
+ // QuickBooks often opens its sentence with the fault's name again ("Invalid Reference Id : …").
111
+ const opener = r.message ? new RegExp(`^${r.message.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*:\\s*`, "i") : null;
112
+ let said = (r.detail || r.message).replace(/\s+/g, " ").trim();
113
+ if (opener && r.detail)
114
+ said = said.replace(opener, "").trim() || said;
115
+ if (!said)
116
+ return `${lead} without giving a reason (status ${r.status}).`;
117
+ if (said.length > 300)
118
+ said = `${said.slice(0, 299).trimEnd()}…`;
119
+ return `${lead}: ${said}${/[.!?…]$/.test(said) ? "" : "."}`;
120
+ }
121
+ /** Where QuickBooks' own text starts inside an error, and what the call was. */
122
+ const RAW = /QuickBooks (?:API ([A-Z]+)(?: (\/\S*))?|(token request)) failed: (\d{3}) - /;
123
+ /** The JSON object `text` opens with, and what follows it; null when it does not open with one. */
124
+ function leadingJson(text) {
125
+ if (!text.startsWith("{"))
126
+ return null;
127
+ let depth = 0;
128
+ let inString = false;
129
+ for (let i = 0; i < text.length; i++) {
130
+ const ch = text[i];
131
+ if (inString) {
132
+ if (ch === "\\")
133
+ i++;
134
+ else if (ch === '"')
135
+ inString = false;
136
+ }
137
+ else if (ch === '"')
138
+ inString = true;
139
+ else if (ch === "{")
140
+ depth++;
141
+ else if (ch === "}" && --depth === 0)
142
+ return { json: text.slice(0, i + 1), rest: text.slice(i + 1) };
143
+ }
144
+ return null;
145
+ }
146
+ const str = (v) => (typeof v === "string" ? v : typeof v === "number" ? String(v) : "");
147
+ /** QuickBooks' fault out of the body it answered with: its JSON when it is JSON, else the body as its message. */
148
+ function faultOf(body) {
149
+ try {
150
+ const parsed = JSON.parse(body);
151
+ // QuickBooks writes "Fault"/"Error" for a refused document and "fault"/"error" for a refused sign-in.
152
+ const fault = (parsed.Fault ?? parsed.fault);
153
+ const first = (fault?.Error ?? fault?.error)?.[0];
154
+ if (first)
155
+ return { code: str(first.code), message: str(first.Message ?? first.message), detail: str(first.Detail ?? first.detail) };
156
+ // The renewal endpoint's shape: { error: "invalid_grant", error_description: "…" }.
157
+ if (typeof parsed.error === "string")
158
+ return { code: "", message: parsed.error, detail: str(parsed.error_description) };
159
+ }
160
+ catch {
161
+ // Not JSON: a page, or a bare line.
162
+ }
163
+ return { code: "", message: body.replace(/\s+/g, " ").trim().slice(0, 300), detail: "" };
164
+ }
165
+ /** `error` for a person to read, and the original when any of it was reworded. */
166
+ export function errorInWords(error) {
167
+ const original = (error ?? "").trim();
168
+ const text = reword(original);
169
+ return { text, technical: text === original ? null : original };
170
+ }
171
+ function reword(error) {
172
+ const found = RAW.exec(error);
173
+ if (!found)
174
+ return error;
175
+ const [whole, method, path, renewal, status] = found;
176
+ const after = error.slice(found.index + whole.length);
177
+ // QuickBooks' answer runs to the end of the text unless it is JSON, which says where it ends.
178
+ const { json: body, rest } = leadingJson(after) ?? { json: after, rest: "" };
179
+ // The record's name follows the company in the address: /v3/company/<id>/vendorcredit[/<id>].
180
+ const record = path?.match(/\/company\/[^/]+\/([a-z]+)/i)?.[1]?.toLowerCase() ?? "";
181
+ const refusal = {
182
+ status: Number(status),
183
+ ...faultOf(body.trim()),
184
+ thing: THINGS[record] ?? "",
185
+ reading: method === "GET",
186
+ renewal: Boolean(renewal),
187
+ };
188
+ const rule = RULES.find((r) => r.when(refusal));
189
+ const sentence = rule ? rule.say(refusal) : inQuickBooksWords(refusal);
190
+ // Whatever QBO Sync wrote around it stays ("Could not link to an existing bill: …"), and a second refusal
191
+ // further on is reworded the same way.
192
+ return `${error.slice(0, found.index)}${sentence}${reword(rest)}`;
193
+ }
@@ -8,6 +8,7 @@ import { type InvoiceDTO } from "./invoice.ts";
8
8
  * QBO Sync checks every document with this same code.
9
9
  */
10
10
  export * from "./common.ts";
11
+ export * from "./attachments.ts";
11
12
  export * from "./invoice.ts";
12
13
  export * from "./creditMemo.ts";
13
14
  export * from "./bill.ts";
@@ -15,6 +16,7 @@ export * from "./codes.ts";
15
16
  export * from "./statusReport.ts";
16
17
  export * from "./protocol.ts";
17
18
  export * from "./answers.ts";
19
+ export * from "./errorInWords.ts";
18
20
  /** An invoice, a credit memo, a bill or a vendor credit: what an app may send. */
19
21
  export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
20
22
  type: z.ZodLiteral<"invoice">;
@@ -76,6 +78,12 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
76
78
  active: "active";
77
79
  voided: "voided";
78
80
  }>;
81
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
82
+ file_name: z.ZodString;
83
+ content_type: z.ZodString;
84
+ size_bytes: z.ZodInt;
85
+ sha256: z.ZodString;
86
+ }, z.core.$strict>>>;
79
87
  }, z.core.$strict>, z.ZodObject<{
80
88
  type: z.ZodLiteral<"credit_memo">;
81
89
  number: z.ZodPipe<z.ZodString, z.ZodString>;
@@ -129,6 +137,12 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
129
137
  active: "active";
130
138
  voided: "voided";
131
139
  }>;
140
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
141
+ file_name: z.ZodString;
142
+ content_type: z.ZodString;
143
+ size_bytes: z.ZodInt;
144
+ sha256: z.ZodString;
145
+ }, z.core.$strict>>>;
132
146
  }, z.core.$strict>, z.ZodObject<{
133
147
  type: z.ZodLiteral<"bill">;
134
148
  due_date: z.ZodOptional<z.ZodString>;
@@ -218,6 +232,12 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
218
232
  active: "active";
219
233
  voided: "voided";
220
234
  }>;
235
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
236
+ file_name: z.ZodString;
237
+ content_type: z.ZodString;
238
+ size_bytes: z.ZodInt;
239
+ sha256: z.ZodString;
240
+ }, z.core.$strict>>>;
221
241
  }, z.core.$strict>, z.ZodObject<{
222
242
  type: z.ZodLiteral<"vendor_credit">;
223
243
  applies_to_bill_ref: z.ZodOptional<z.ZodString>;
@@ -306,6 +326,12 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
306
326
  active: "active";
307
327
  voided: "voided";
308
328
  }>;
329
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
330
+ file_name: z.ZodString;
331
+ content_type: z.ZodString;
332
+ size_bytes: z.ZodInt;
333
+ sha256: z.ZodString;
334
+ }, z.core.$strict>>>;
309
335
  }, z.core.$strict>], "type">;
310
336
  export type AppDocument = InvoiceDTO | CreditMemoDTO | BillDTO | VendorCreditDTO;
311
337
  export type CheckedDocument = {
@@ -9,6 +9,7 @@ import { APP_DOCUMENT_TYPES } from "./protocol.js";
9
9
  * QBO Sync checks every document with this same code.
10
10
  */
11
11
  export * from "./common.js";
12
+ export * from "./attachments.js";
12
13
  export * from "./invoice.js";
13
14
  export * from "./creditMemo.js";
14
15
  export * from "./bill.js";
@@ -16,6 +17,7 @@ export * from "./codes.js";
16
17
  export * from "./statusReport.js";
17
18
  export * from "./protocol.js";
18
19
  export * from "./answers.js";
20
+ export * from "./errorInWords.js";
19
21
  /** An invoice, a credit memo, a bill or a vendor credit: what an app may send. */
20
22
  export const appDocumentSchema = z.discriminatedUnion("type", [invoiceSchema, creditMemoSchema, billSchema, vendorCreditSchema], {
21
23
  error: `type must be one of ${APP_DOCUMENT_TYPES.join(", ")}`,
@@ -83,6 +83,12 @@ export declare const invoiceSchema: z.ZodObject<{
83
83
  active: "active";
84
84
  voided: "voided";
85
85
  }>;
86
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
87
+ file_name: z.ZodString;
88
+ content_type: z.ZodString;
89
+ size_bytes: z.ZodInt;
90
+ sha256: z.ZodString;
91
+ }, z.core.$strict>>>;
86
92
  }, z.core.$strict>;
87
93
  export type InvoiceDTO = z.infer<typeof invoiceSchema>;
88
94
  export type InvoiceLine = z.infer<typeof invoiceLine>;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** The QBO Sync SDK for an app's server. See README.md. */
2
2
  export * from "./contract/index.ts";
3
- export { QbosyncClient, SIGN_IN_PAGE_PATH, type ConnectionState, type DocumentResult, type Failure, type FailureReason, type QbosyncClientConfig, type SendResult, } from "./client.ts";
3
+ export { QbosyncClient, SIGN_IN_PAGE_PATH, type ConnectionState, type DocumentResult, type Failure, type FailureReason, type QbosyncClientConfig, type AttachmentFile, type SendOptions, type SendResult, type UploadResult, } from "./client.ts";
4
4
  export type { CollectResult, ConnectRequestRow, ConnectRequestStore, NewConnectRequest, OpenResult, RequestRefusal } from "./connectRequest.ts";
5
5
  export type { ConnectionRow, ConnectionStore, Log, TokenAnswer } from "./connection.ts";
6
6
  export { isNewerReport, verifySignature, type CheckedStatusReports, type InvalidReport, type PublicSigningKey, type StatusReportEntry, type StatusReportResult, } from "./statusReports.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@company-six/qbosync",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Connect an app to QBO Sync: send invoices, credit memos, bills and vendor credits to QuickBooks, and hear back what happened to them.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",