@company-six/qbosync 0.10.1 → 0.12.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
@@ -138,6 +138,16 @@ A list is that company's alone: no other company sees it, even one your app also
138
138
 
139
139
  Apps send invoices, credit memos, bills and vendor credits. Payments, refunds and payouts reach QBO Sync through its own connectors, matched to your invoices by `order_ref`, so give every invoice the `order_ref` of its order. Paying a bill is a money movement too: apps never send one.
140
140
 
141
+ **Other ids of the same order (0.11.0).** When an order's payment comes from somewhere that knows the order by another id, list that id in `extra_order_refs`, in `order_ref`'s `"<system>:<id>"` form. A Faire order your app received as a Shopify order is the case: `order_ref: "shopify:5551234567"`, `extra_order_refs: ["faire:bo_kt2semdnvy"]` (Faire's own order id, lower case, as its API gives it). A payment or refund QBO Sync reads matches the invoice or credit memo by any of them, as by `order_ref`. At most 10, no repeats, none the same as `order_ref`; the contract refuses anything else. Two orders' invoices may list the same id (two shop orders made from one marketplace order): that payment then pays all of them, oldest first. A QBO Sync older than 0.11.0's contract refuses the field, so update the SDK only once QBO Sync has it.
142
+
143
+ **The sale a document belongs to (0.12.0).** `sale_group` says which sale a document is part of: `sale_group: { ref: "myapp:project:2207" }`. Documents your app sends for one company that name the same `ref` belong together (a sale is matched within one app and one company, never across apps): the sale's invoices, and the bills and vendor credits that are its costs. That is what lets a company record a bill's cost with its sale, when it pays for an order weeks before it invoices the customer. `ref` is whatever id your app has for the whole sale (a project, a sales order), in `order_ref`'s `"<system>:<id>"` form; it is compared whole and exactly, so send the same text on every document of the sale.
144
+
145
+ - **It is optional, on every document.** One without it is accepted and handled exactly as before; send it only if your app knows which sale a document belongs to.
146
+ - **It is not `order_ref`.** `order_ref` is how a payment finds its invoice; `sale_group` is how a bill finds its sale's invoice. A document may carry both, either or neither, with the same id or different ones, and neither is used in the other's place.
147
+ - **Send it on invoices, bills and vendor credits.** A credit memo may carry it, but nothing reads it there: a credit memo keeps applying to its invoice as before.
148
+ - **It is an object** so later versions can add facts about the sale beside `ref`. Today `ref` is its only key and any other is refused. It carries no instructions: what a company does with a sale's costs is its own setting in QBO Sync.
149
+ - Since 0.12.0 QBO Sync stores the field and changes nothing else for a document that carries it. A QBO Sync that does not know the field yet refuses a document that carries it, so start sending it only once QBO Sync has been updated.
150
+
141
151
  ### Bills and vendor credits (0.5.0)
142
152
 
143
153
  A bill is what the company owes a vendor; a vendor credit is what a vendor gave back. QBO Sync posts them as QuickBooks Bills and Vendor Credits.
@@ -164,6 +174,7 @@ const bill: BillDTO = {
164
174
 
165
175
  - A line is an **account line** (`cost_code`: your word for what was paid for) or an **item line** (`item_code`, `quantity`, `unit_cost_cents`: a product bought, by SKU). Each company maps your cost codes to its accounts once, in QBO Sync's Setup; a bill whose code is not mapped waits, and its status report says so. An item line posts on the product the company chose for its `item_code` in Setup → Products (the same choice your invoices use), else the QuickBooks product with that SKU; a bill never creates a product, so with neither it fails, or waits until the company chooses one if it has set your app to never create products.
166
176
  - `customer` (on the bill, or on one line) puts the cost on that customer for job costing; it is not billed to them again.
177
+ - `sale_group` (optional, 0.12.0) names the sale the cost belongs to, with the same `ref` as on that sale's invoice (see "The sale a document belongs to" above).
167
178
  - 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.
168
179
  - `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
180
  - 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).
@@ -56,7 +56,6 @@ export declare const ATTACHMENTS_PATH = "/api/v1/attachments";
56
56
  * a name of its own.
57
57
  */
58
58
  export declare const attachmentUploadSchema: z.ZodObject<{
59
- /** The company as the app's documents name it. */
60
59
  company_key: z.ZodString;
61
60
  content_type: z.ZodString;
62
61
  size_bytes: z.ZodInt;
@@ -124,6 +124,9 @@ export declare const billSchema: z.ZodObject<{
124
124
  }, z.core.$strict>>;
125
125
  }, z.core.$strict>>;
126
126
  order_ref: z.ZodOptional<z.ZodString>;
127
+ sale_group: z.ZodOptional<z.ZodObject<{
128
+ ref: z.ZodString;
129
+ }, z.core.$strict>>;
127
130
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
128
131
  label: z.ZodString;
129
132
  value: z.ZodString;
@@ -225,6 +228,9 @@ export declare const vendorCreditSchema: z.ZodObject<{
225
228
  }, z.core.$strict>>;
226
229
  }, z.core.$strict>>;
227
230
  order_ref: z.ZodOptional<z.ZodString>;
231
+ sale_group: z.ZodOptional<z.ZodObject<{
232
+ ref: z.ZodString;
233
+ }, z.core.$strict>>;
228
234
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
229
235
  label: z.ZodString;
230
236
  value: z.ZodString;
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { termsCode } from "./invoice.js";
3
- import { address, cents, currency, customer, docNumber, envelope, isoDate, orderRef, references, sum, text } from "./common.js";
3
+ import { address, cents, currency, customer, docNumber, envelope, isoDate, orderRef, references, saleGroup, sum, text } from "./common.js";
4
4
  /**
5
5
  * What a company owes its vendors: bills, and the vendor credits that reduce them. QBO Sync posts them as
6
6
  * QuickBooks Bills and Vendor Credits. Paying a bill is a money movement, and apps send none.
@@ -49,6 +49,8 @@ const vendorDocument = {
49
49
  vendor,
50
50
  customer: customer.optional(),
51
51
  order_ref: orderRef.optional(),
52
+ /** The sale this cost belongs to (0.12.0, `saleGroup` in `common.ts`): the same `ref` as on the sale's invoice. */
53
+ sale_group: saleGroup.optional(),
52
54
  references: references.optional(),
53
55
  class_key: z.string().optional(),
54
56
  lines: z.array(billLine).min(1, "needs at least one line"),
@@ -19,15 +19,11 @@ export declare const MAX_DECLARED_CODES = 200;
19
19
  /** An item code as invoice, credit memo and bill item lines send it: kept exactly, with nothing around it. */
20
20
  export declare const declaredItemCode: z.ZodString;
21
21
  export declare const declaredItemCodeSchema: z.ZodObject<{
22
- /** Exactly as the app puts it on a line's `item_code`. */
23
22
  code: z.ZodString;
24
- /** What the code stands for, in the words the company's bookkeeper reads: "Shipping and freight". */
25
23
  label: z.ZodString;
26
- /** A longer note, when the label is not enough: "Every line added with + Shipping". */
27
24
  description: z.ZodOptional<z.ZodString>;
28
25
  }, z.core.$strict>;
29
26
  export declare const declaredCostCodeSchema: z.ZodObject<{
30
- /** Exactly as the app puts it on a bill line's `cost_code`. */
31
27
  code: z.ZodString;
32
28
  label: z.ZodString;
33
29
  description: z.ZodOptional<z.ZodString>;
@@ -36,21 +32,13 @@ export type DeclaredItemCode = z.infer<typeof declaredItemCodeSchema>;
36
32
  export type DeclaredCostCode = z.infer<typeof declaredCostCodeSchema>;
37
33
  /** What `PUT /api/v1/codes` takes. At least one kind; each kind sent replaces that company's list of that kind. */
38
34
  export declare const codesDeclarationSchema: z.ZodObject<{
39
- /**
40
- * The company the lists are for, as the app's documents name it. Needed when the app sends for several
41
- * companies; with one, it may be left out (0.6.0).
42
- */
43
35
  company_key: z.ZodOptional<z.ZodString>;
44
36
  item_codes: z.ZodOptional<z.ZodArray<z.ZodObject<{
45
- /** Exactly as the app puts it on a line's `item_code`. */
46
37
  code: z.ZodString;
47
- /** What the code stands for, in the words the company's bookkeeper reads: "Shipping and freight". */
48
38
  label: z.ZodString;
49
- /** A longer note, when the label is not enough: "Every line added with + Shipping". */
50
39
  description: z.ZodOptional<z.ZodString>;
51
40
  }, z.core.$strict>>>;
52
41
  cost_codes: z.ZodOptional<z.ZodArray<z.ZodObject<{
53
- /** Exactly as the app puts it on a bill line's `cost_code`. */
54
42
  code: z.ZodString;
55
43
  label: z.ZodString;
56
44
  description: z.ZodOptional<z.ZodString>;
@@ -32,6 +32,53 @@ export declare const currency: z.ZodString;
32
32
  * collide; the system prefix is what keeps them apart, so it is required.
33
33
  */
34
34
  export declare const orderRef: z.ZodString;
35
+ /**
36
+ * `sale_group` (0.12.0): the sale this document belongs to. OPTIONAL on every document: one without it is
37
+ * accepted and handled exactly as before.
38
+ *
39
+ * Documents one app sends for one company that name the same `ref` belong to the same sale (never across apps): the sale's invoices, and the bills
40
+ * and vendor credits that are its costs. That is what lets a bill's cost be recorded with its sale, for a company
41
+ * that pays for an order weeks before it invoices the customer.
42
+ *
43
+ * `ref` is whatever id your app has for the whole sale (a project, a sales order), in `order_ref`'s form,
44
+ * "<system>:<id>": "myapp:project:2207". It is compared whole and exactly, so send the same text on every
45
+ * document of the sale.
46
+ *
47
+ * How it differs from `order_ref`: `order_ref` is how a PAYMENT finds its invoice; `sale_group` is how a BILL
48
+ * finds its sale's invoice. They are independent. A document may carry both, either or neither, they may hold the
49
+ * same id or different ones, and neither is used in the other's place: a document with no `sale_group` belongs to
50
+ * no sale group, whatever its `order_ref` says.
51
+ *
52
+ * An object, not a plain string, so that later versions can add facts about the sale beside `ref`. It carries no
53
+ * instructions: what a company does with a sale's costs is that company's own setting in QBO Sync. Any other key
54
+ * is refused today.
55
+ *
56
+ * Meant for invoices, bills and vendor credits. A credit memo may carry it, but nothing reads it there: a credit
57
+ * memo keeps applying to its invoice as before. Since 0.12.0 QBO Sync stores the field; nothing else changes for
58
+ * a document that carries it.
59
+ */
60
+ export declare const saleGroup: z.ZodObject<{
61
+ ref: z.ZodString;
62
+ }, z.core.$strict>;
63
+ export type SaleGroup = z.infer<typeof saleGroup>;
64
+ /** At most this many `extra_order_refs` on one document. */
65
+ export declare const MAX_EXTRA_ORDER_REFS = 10;
66
+ /**
67
+ * `extra_order_refs` (0.11.0): other ids the same order has, each in `order_ref`'s form, so a payment
68
+ * QBO Sync reads from a connector finds this document through any of them. A marketplace order that
69
+ * reaches the app as a shop order is the case: the invoice's `order_ref` is the shop's
70
+ * ("shopify:5551234567"), and the marketplace's payment knows only its own id ("faire:bo_kt2semdnvy").
71
+ * At most 10, no repeats, none equal to the document's `order_ref` (`extraOrderRefIssues`).
72
+ */
73
+ export declare const extraOrderRefs: z.ZodArray<z.ZodString>;
74
+ /** What is wrong with a document's `extra_order_refs` beyond each id's form: a repeat, or its own `order_ref`. */
75
+ export declare function extraOrderRefIssues(doc: {
76
+ order_ref?: string;
77
+ extra_order_refs?: string[];
78
+ }): Array<{
79
+ index: number;
80
+ message: string;
81
+ }>;
35
82
  /** A document's number as QuickBooks holds it: at most 21 characters (QuickBooks' DocNumber limit). */
36
83
  export declare const docNumber: z.ZodPipe<z.ZodString, z.ZodString>;
37
84
  /** Written into the memo in this order. */
@@ -31,13 +31,64 @@ export const isoDate = z.string().refine((s) => {
31
31
  }, "must be a date as YYYY-MM-DD");
32
32
  /** An ISO 4217 currency code, upper case: "USD". */
33
33
  export const currency = z.string().regex(/^[A-Z]{3}$/, "must be a three-letter currency code such as USD");
34
+ /** The form `order_ref` and `sale_group.ref` share: a lower-case system name, a colon, an id with no spaces. */
35
+ const SYSTEM_AND_ID = /^[a-z][a-z0-9_-]*:\S+$/;
34
36
  /**
35
37
  * `order_ref`: "<system>:<id>", e.g. "shopify:5551234567". Two apps' order ids can
36
38
  * collide; the system prefix is what keeps them apart, so it is required.
37
39
  */
38
- export const orderRef = z
39
- .string()
40
- .regex(/^[a-z][a-z0-9_-]*:\S+$/, 'must be "<system>:<id>", e.g. "shopify:5551234567"');
40
+ export const orderRef = z.string().regex(SYSTEM_AND_ID, 'must be "<system>:<id>", e.g. "shopify:5551234567"');
41
+ /**
42
+ * `sale_group` (0.12.0): the sale this document belongs to. OPTIONAL on every document: one without it is
43
+ * accepted and handled exactly as before.
44
+ *
45
+ * Documents one app sends for one company that name the same `ref` belong to the same sale (never across apps): the sale's invoices, and the bills
46
+ * and vendor credits that are its costs. That is what lets a bill's cost be recorded with its sale, for a company
47
+ * that pays for an order weeks before it invoices the customer.
48
+ *
49
+ * `ref` is whatever id your app has for the whole sale (a project, a sales order), in `order_ref`'s form,
50
+ * "<system>:<id>": "myapp:project:2207". It is compared whole and exactly, so send the same text on every
51
+ * document of the sale.
52
+ *
53
+ * How it differs from `order_ref`: `order_ref` is how a PAYMENT finds its invoice; `sale_group` is how a BILL
54
+ * finds its sale's invoice. They are independent. A document may carry both, either or neither, they may hold the
55
+ * same id or different ones, and neither is used in the other's place: a document with no `sale_group` belongs to
56
+ * no sale group, whatever its `order_ref` says.
57
+ *
58
+ * An object, not a plain string, so that later versions can add facts about the sale beside `ref`. It carries no
59
+ * instructions: what a company does with a sale's costs is that company's own setting in QBO Sync. Any other key
60
+ * is refused today.
61
+ *
62
+ * Meant for invoices, bills and vendor credits. A credit memo may carry it, but nothing reads it there: a credit
63
+ * memo keeps applying to its invoice as before. Since 0.12.0 QBO Sync stores the field; nothing else changes for
64
+ * a document that carries it.
65
+ */
66
+ export const saleGroup = z.strictObject({
67
+ ref: z.string().regex(SYSTEM_AND_ID, 'must be "<system>:<id>", e.g. "myapp:project:2207"'),
68
+ });
69
+ /** At most this many `extra_order_refs` on one document. */
70
+ export const MAX_EXTRA_ORDER_REFS = 10;
71
+ /**
72
+ * `extra_order_refs` (0.11.0): other ids the same order has, each in `order_ref`'s form, so a payment
73
+ * QBO Sync reads from a connector finds this document through any of them. A marketplace order that
74
+ * reaches the app as a shop order is the case: the invoice's `order_ref` is the shop's
75
+ * ("shopify:5551234567"), and the marketplace's payment knows only its own id ("faire:bo_kt2semdnvy").
76
+ * At most 10, no repeats, none equal to the document's `order_ref` (`extraOrderRefIssues`).
77
+ */
78
+ export const extraOrderRefs = z.array(orderRef).max(MAX_EXTRA_ORDER_REFS, `must list at most ${MAX_EXTRA_ORDER_REFS} order ids`);
79
+ /** What is wrong with a document's `extra_order_refs` beyond each id's form: a repeat, or its own `order_ref`. */
80
+ export function extraOrderRefIssues(doc) {
81
+ const issues = [];
82
+ const seen = new Set();
83
+ (doc.extra_order_refs ?? []).forEach((ref, index) => {
84
+ if (ref === doc.order_ref)
85
+ issues.push({ index, message: `"${ref}" is already the order_ref` });
86
+ else if (seen.has(ref))
87
+ issues.push({ index, message: `"${ref}" is listed twice` });
88
+ seen.add(ref);
89
+ });
90
+ return issues;
91
+ }
41
92
  /** A document's number as QuickBooks holds it: at most 21 characters (QuickBooks' DocNumber limit). */
42
93
  export const docNumber = text.pipe(z.string().max(21, "must be at most 21 characters"));
43
94
  /** Written into the memo in this order. */
@@ -26,6 +26,10 @@ export declare const creditMemoSchema: z.ZodObject<{
26
26
  currency: z.ZodString;
27
27
  applies_to_invoice_ref: z.ZodString;
28
28
  order_ref: z.ZodOptional<z.ZodString>;
29
+ extra_order_refs: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ sale_group: z.ZodOptional<z.ZodObject<{
31
+ ref: z.ZodString;
32
+ }, z.core.$strict>>;
29
33
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
34
  label: z.ZodString;
31
35
  value: z.ZodString;
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { cents, currency, customer, docNumber, envelope, isoDate, lineAmountMatches, orderRef, positiveCents, references, sum, text, } from "./common.js";
2
+ import { cents, currency, customer, docNumber, envelope, extraOrderRefIssues, extraOrderRefs, isoDate, lineAmountMatches, orderRef, positiveCents, references, saleGroup, sum, text, } from "./common.js";
3
3
  /** A credit memo line: reverses an invoice line (`applies_to_line_ref`), or is a money-only credit. */
4
4
  export const creditMemoLine = z.strictObject({
5
5
  applies_to_line_ref: z.string().optional(),
@@ -29,6 +29,9 @@ export const creditMemoSchema = z
29
29
  currency,
30
30
  applies_to_invoice_ref: text,
31
31
  order_ref: orderRef.optional(),
32
+ extra_order_refs: extraOrderRefs.optional(),
33
+ /** May be sent (0.12.0, `saleGroup` in `common.ts`), but nothing reads it on a credit memo: it applies to its invoice as before. */
34
+ sale_group: saleGroup.optional(),
32
35
  references: references.optional(),
33
36
  class_key: z.string().optional(),
34
37
  customer,
@@ -58,6 +61,9 @@ export const creditMemoSchema = z
58
61
  });
59
62
  }
60
63
  });
64
+ for (const issue of extraOrderRefIssues(doc)) {
65
+ ctx.addIssue({ code: "custom", path: ["extra_order_refs", issue.index], message: issue.message });
66
+ }
61
67
  const expected = sum(doc.lines.map((l) => l.amount_cents)) + doc.shipping_cents + doc.tax_cents;
62
68
  if (doc.total_cents !== expected) {
63
69
  ctx.addIssue({ code: "custom", path: ["total_cents"], message: `must equal lines + shipping + tax (${expected})` });
@@ -26,6 +26,10 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
26
26
  terms_code: z.ZodOptional<z.ZodString>;
27
27
  currency: z.ZodString;
28
28
  order_ref: z.ZodOptional<z.ZodString>;
29
+ extra_order_refs: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ sale_group: z.ZodOptional<z.ZodObject<{
31
+ ref: z.ZodString;
32
+ }, z.core.$strict>>;
29
33
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
34
  label: z.ZodString;
31
35
  value: z.ZodString;
@@ -91,6 +95,10 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
91
95
  currency: z.ZodString;
92
96
  applies_to_invoice_ref: z.ZodString;
93
97
  order_ref: z.ZodOptional<z.ZodString>;
98
+ extra_order_refs: z.ZodOptional<z.ZodArray<z.ZodString>>;
99
+ sale_group: z.ZodOptional<z.ZodObject<{
100
+ ref: z.ZodString;
101
+ }, z.core.$strict>>;
94
102
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
95
103
  label: z.ZodString;
96
104
  value: z.ZodString;
@@ -187,6 +195,9 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
187
195
  }, z.core.$strict>>;
188
196
  }, z.core.$strict>>;
189
197
  order_ref: z.ZodOptional<z.ZodString>;
198
+ sale_group: z.ZodOptional<z.ZodObject<{
199
+ ref: z.ZodString;
200
+ }, z.core.$strict>>;
190
201
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
191
202
  label: z.ZodString;
192
203
  value: z.ZodString;
@@ -281,6 +292,9 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
281
292
  }, z.core.$strict>>;
282
293
  }, z.core.$strict>>;
283
294
  order_ref: z.ZodOptional<z.ZodString>;
295
+ sale_group: z.ZodOptional<z.ZodObject<{
296
+ ref: z.ZodString;
297
+ }, z.core.$strict>>;
284
298
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
285
299
  label: z.ZodString;
286
300
  value: z.ZodString;
@@ -31,6 +31,10 @@ export declare const invoiceSchema: z.ZodObject<{
31
31
  terms_code: z.ZodOptional<z.ZodString>;
32
32
  currency: z.ZodString;
33
33
  order_ref: z.ZodOptional<z.ZodString>;
34
+ extra_order_refs: z.ZodOptional<z.ZodArray<z.ZodString>>;
35
+ sale_group: z.ZodOptional<z.ZodObject<{
36
+ ref: z.ZodString;
37
+ }, z.core.$strict>>;
34
38
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
35
39
  label: z.ZodString;
36
40
  value: z.ZodString;
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { cents, currency, customer, docNumber, envelope, fee, isoDate, lineAmountMatches, orderRef, references, sum, text, } from "./common.js";
2
+ import { cents, currency, customer, docNumber, envelope, extraOrderRefIssues, extraOrderRefs, fee, isoDate, lineAmountMatches, orderRef, references, saleGroup, sum, text, } from "./common.js";
3
3
  /** One invoice line. `line_ref` is stable (say, the shop's line item id); credit memos point at it. */
4
4
  export const invoiceLine = z.strictObject({
5
5
  line_ref: text,
@@ -36,6 +36,9 @@ export const invoiceSchema = z
36
36
  terms_code: termsCode.optional(),
37
37
  currency,
38
38
  order_ref: orderRef.optional(),
39
+ extra_order_refs: extraOrderRefs.optional(),
40
+ /** The sale this invoice belongs to (0.12.0, `saleGroup` in `common.ts`): bills that name the same sale are its costs. */
41
+ sale_group: saleGroup.optional(),
39
42
  references: references.optional(),
40
43
  class_key: z.string().optional(),
41
44
  customer,
@@ -56,6 +59,9 @@ export const invoiceSchema = z
56
59
  });
57
60
  }
58
61
  });
62
+ for (const issue of extraOrderRefIssues(doc)) {
63
+ ctx.addIssue({ code: "custom", path: ["extra_order_refs", issue.index], message: issue.message });
64
+ }
59
65
  const seen = new Set();
60
66
  doc.lines.forEach((line, i) => {
61
67
  if (seen.has(line.line_ref)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@company-six/qbosync",
3
- "version": "0.10.1",
3
+ "version": "0.12.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",
@@ -1,260 +1,260 @@
1
1
  -- An app's daily report: each morning, the invoices, credit memos, bills and vendor credits the app created the day
2
2
  -- before, set beside what QBO Sync did with them. Optional; run this once in the app's own Postgres database (the Supabase
3
- -- SQL editor, for instance) if the app keeps one. One transaction; re-running it is a no-op. It does not need 001_connection.sql.
4
- --
5
- -- qbosync_report_runs one row per run of the report: the day it covers, whether it is running, finished or failed,
6
- -- and a finished day's totals by result, for the page that lists the days.
7
- -- qbosync_report_rows one row per document per run, holding what was true THAT morning, so a past report can be
8
- -- opened again and still shows what it showed then.
9
- --
10
- -- The SDK's guide ("A daily report") says how a run fills them. In short:
11
- --
12
- -- select * from qbosync_report_start('2026-11-08', 'America/Chicago'); -- the run, with that day's window in UTC
13
- -- -- list the documents your app created in [window_start, window_end), ask QBO Sync, compare, then
14
- -- insert into qbosync_report_rows (run_id, ...) values (...); -- one per document
15
- -- select qbosync_report_finish(run_id, '{"documents": 12, "matches": 11, "failed": 1}');
16
- -- -- or, when the day cannot be built:
17
- -- select qbosync_report_fail(run_id, 'QBO Sync could not be reached');
18
- --
19
- -- Rules the database keeps:
20
- -- - ONE run is running at a time: two jobs, or a manual run during the scheduled one, never overlap;
21
- -- - ONE finished report per day: finishing a second report for a day replaces the first in the same transaction,
22
- -- so the day always has one, never none;
23
- -- - a run still running after 30 minutes (its server died) is marked failed by the next start;
24
- -- - rows go only into a running run, and a failed run keeps none.
25
- --
26
- -- The tables have row level security on and no policy, and every function is granted to service_role only: your server
27
- -- reads and writes them, and shows each person only their own companies' rows. Outside Supabase, grant the tables and
28
- -- functions to the role your server connects with.
29
- --
30
- -- Undo (nothing else depends on these):
31
- -- drop function public.qbosync_report_start(date, text);
32
- -- drop function public.qbosync_report_finish(uuid, jsonb);
33
- -- drop function public.qbosync_report_fail(uuid, text);
34
- -- drop table public.qbosync_report_rows;
35
- -- drop table public.qbosync_report_runs;
36
- -- drop function public.qbosync_report_rows_only_running();
37
-
38
- begin;
39
-
40
- -- ── 1. Runs ─────────────────────────────────────────────────────────────────────────
41
-
42
- create table if not exists public.qbosync_report_runs (
43
- id uuid primary key default gen_random_uuid(),
44
- -- The day reported, in the app's own time zone.
45
- report_date date not null,
46
- -- That zone (an IANA name, such as America/Chicago) and the day's midnight to midnight in it, in UTC. Worked out by
47
- -- qbosync_report_start, so daylight saving is the database's job, not the app's.
48
- time_zone text not null,
49
- window_start timestamptz not null,
50
- window_end timestamptz not null,
51
- status text not null default 'running',
52
- started_at timestamptz not null default now(),
53
- finished_at timestamptz,
54
- -- Why a failed run failed, for the page: a day that failed stays listed with this until a later run makes it up.
55
- error text,
56
- -- A finished run's totals: {"documents": 12, "matches": 11, "failed": 1, ...}.
57
- counts jsonb,
58
- constraint qbosync_report_runs_status_check check (status in ('running', 'done', 'failed')),
59
- constraint qbosync_report_runs_window_check check (window_start < window_end),
60
- constraint qbosync_report_runs_time_zone_check check (length(btrim(time_zone)) > 0),
61
- constraint qbosync_report_runs_shape_check check (
62
- (status = 'running' and finished_at is null and error is null and counts is null)
63
- or (status = 'done' and finished_at is not null and error is null
64
- and counts is not null and jsonb_typeof(counts) = 'object')
65
- or (status = 'failed' and finished_at is not null and counts is null
66
- and error is not null and length(btrim(error)) > 0))
67
- );
68
-
69
- -- One run at a time: every running run has the same key.
70
- create unique index if not exists qbosync_report_runs_one_running
71
- on public.qbosync_report_runs ((true)) where status = 'running';
72
- -- One finished report per day.
73
- create unique index if not exists qbosync_report_runs_one_done_per_day
74
- on public.qbosync_report_runs (report_date) where status = 'done';
75
- create index if not exists qbosync_report_runs_day_idx
76
- on public.qbosync_report_runs (report_date desc, started_at desc);
77
-
78
- -- ── 2. Rows ─────────────────────────────────────────────────────────────────────────
79
-
80
- create table if not exists public.qbosync_report_rows (
81
- id uuid primary key default gen_random_uuid(),
82
- run_id uuid not null references public.qbosync_report_runs (id) on delete cascade,
83
- document_type text not null,
84
- -- The ref your app sent the document under: what QBO Sync was asked about.
85
- source_ref text not null,
86
- -- The company, as your app names it (the document's company_key): for showing each company only its own rows.
87
- company_key text not null,
88
- -- Optional: your own id for the document (any id, as text), and what people know it by (an order number, say).
89
- document_id text,
90
- label text,
91
- -- The one result the document got. See the guide for when each applies:
92
- -- matches posted, and every amount is what your app holds
93
- -- differs posted, but an amount differs, or QuickBooks no longer holds what was posted
94
- -- changed_since_posted your document changed after the version QBO Sync posted
95
- -- not_posted QBO Sync has it and nothing is posted (waiting, syncing off, excluded, rolled back)
96
- -- failed QBO Sync tried and failed; its error is kept
97
- -- not_received QBO Sync never received it
98
- result text not null,
99
- -- As QBO Sync answered that morning.
100
- qbo_number text,
101
- sync_status text,
102
- synced_at timestamptz,
103
- -- The nightly QuickBooks check's result for what was posted; null while nothing is posted.
104
- qbo_check text,
105
- -- For "differs" only: each thing that did not match, as your app chooses to describe it (a JSON array, never empty).
106
- differences jsonb,
107
- -- QBO Sync's error for "failed"; for "not_received", your own record of why the send did not get through, if any.
108
- error text,
109
- -- Optional: your own record of sending it (shown beside "not_received").
110
- send_status text,
111
- created_at timestamptz not null default now(),
112
- constraint qbosync_report_rows_type_check check (document_type in ('invoice', 'credit_memo', 'bill', 'vendor_credit')),
113
- constraint qbosync_report_rows_ref_check check (length(btrim(source_ref)) > 0),
114
- constraint qbosync_report_rows_company_check check (length(btrim(company_key)) > 0),
115
- constraint qbosync_report_rows_result_check check (result in
116
- ('matches', 'differs', 'changed_since_posted', 'not_posted', 'failed', 'not_received')),
117
- constraint qbosync_report_rows_qbo_check_check check (
118
- qbo_check is null or qbo_check in ('matches', 'differs', 'missing', 'not_checked')),
119
- constraint qbosync_report_rows_differences_check check (
120
- (result = 'differs') = (differences is not null and jsonb_typeof(differences) = 'array' and jsonb_array_length(differences) > 0))
121
- );
122
-
123
- -- A document once per run.
124
- create unique index if not exists qbosync_report_rows_one_per_document
125
- on public.qbosync_report_rows (run_id, document_type, source_ref);
126
- create index if not exists qbosync_report_rows_company_idx
127
- on public.qbosync_report_rows (run_id, company_key);
128
-
129
- -- Rows go only into a running run: a finished report never changes, and a failed one stays empty.
130
- create or replace function public.qbosync_report_rows_only_running()
131
- returns trigger
132
- language plpgsql
133
- set search_path = public
134
- as $$
135
- begin
136
- if not exists (select 1 from public.qbosync_report_runs where id = new.run_id and status = 'running') then
137
- raise exception 'qbosync_report_rows: run % is not running', new.run_id;
138
- end if;
139
- return new;
140
- end;
141
- $$;
142
-
143
- drop trigger if exists qbosync_report_rows_only_running on public.qbosync_report_rows;
144
- create trigger qbosync_report_rows_only_running
145
- before insert or update on public.qbosync_report_rows
146
- for each row execute function public.qbosync_report_rows_only_running();
147
-
148
- alter table public.qbosync_report_runs enable row level security;
149
- alter table public.qbosync_report_rows enable row level security;
150
-
151
- -- ── 3. Starting, finishing, failing ─────────────────────────────────────────────────
152
-
153
- -- Starts a run for one day in the given time zone and answers it, with the day's window in UTC. A run still running after
154
- -- 30 minutes is marked failed first (its server died); one running for less makes this raise, so two runs never overlap.
155
- create or replace function public.qbosync_report_start(p_report_date date, p_time_zone text)
156
- returns public.qbosync_report_runs
157
- language plpgsql
158
- set search_path = public
159
- as $$
160
- declare
161
- run public.qbosync_report_runs;
162
- begin
163
- if p_report_date is null then
164
- raise exception 'qbosync_report_start: a day is required';
165
- end if;
166
- if p_time_zone is null or not exists (select 1 from pg_timezone_names where name = p_time_zone) then
167
- raise exception 'qbosync_report_start: % is not a time zone name (such as America/Chicago)', coalesce(p_time_zone, 'null');
168
- end if;
169
- update public.qbosync_report_runs
170
- set status = 'failed', finished_at = now(), error = 'abandoned: still running after 30 minutes'
171
- where status = 'running' and started_at < now() - interval '30 minutes';
172
- -- An abandoned run keeps no rows, like any failed run.
173
- delete from public.qbosync_report_rows r
174
- using public.qbosync_report_runs u
175
- where r.run_id = u.id and u.status = 'failed';
176
-
177
- insert into public.qbosync_report_runs (report_date, time_zone, window_start, window_end)
178
- values (p_report_date,
179
- p_time_zone,
180
- (p_report_date::timestamp) at time zone p_time_zone,
181
- ((p_report_date + 1)::timestamp) at time zone p_time_zone)
182
- returning * into run;
183
- return run;
184
- exception when unique_violation then
185
- raise exception 'qbosync_report_start: another report is running';
186
- end;
187
- $$;
188
-
189
- -- Finishes a running run with its totals. An earlier finished report for the same day is deleted in the same transaction
190
- -- (its rows with it), so the day always has exactly one, never none while a rerun is being finished.
191
- create or replace function public.qbosync_report_finish(p_run_id uuid, p_counts jsonb)
192
- returns void
193
- language plpgsql
194
- set search_path = public
195
- as $$
196
- declare
197
- day date;
198
- begin
199
- if p_counts is null or jsonb_typeof(p_counts) <> 'object' then
200
- raise exception 'qbosync_report_finish: counts must be a JSON object';
201
- end if;
202
- select report_date into day from public.qbosync_report_runs where id = p_run_id and status = 'running' for update;
203
- if not found then
204
- raise exception 'qbosync_report_finish: run % is not running', p_run_id;
205
- end if;
206
- delete from public.qbosync_report_runs where report_date = day and status = 'done';
207
- update public.qbosync_report_runs
208
- set status = 'done', finished_at = now(), counts = p_counts
209
- where id = p_run_id;
210
- end;
211
- $$;
212
-
213
- -- Marks a running run failed, keeping why, and drops the rows it had written. An earlier finished report for the day stays.
214
- create or replace function public.qbosync_report_fail(p_run_id uuid, p_error text)
215
- returns void
216
- language plpgsql
217
- set search_path = public
218
- as $$
219
- begin
220
- delete from public.qbosync_report_rows where run_id = p_run_id;
221
- update public.qbosync_report_runs
222
- set status = 'failed', finished_at = now(),
223
- error = coalesce(nullif(btrim(p_error), ''), 'the report could not be built')
224
- where id = p_run_id and status = 'running';
225
- end;
226
- $$;
227
-
228
- do $$
229
- declare
230
- fn text;
231
- tbl text;
232
- r text;
233
- begin
234
- foreach tbl in array array['public.qbosync_report_runs', 'public.qbosync_report_rows'] loop
235
- execute format('revoke all on table %s from public', tbl);
236
- foreach r in array array['anon', 'authenticated'] loop
237
- if exists (select 1 from pg_roles where rolname = r) then
238
- execute format('revoke all on table %s from %I', tbl, r);
239
- end if;
240
- end loop;
241
- end loop;
242
- foreach fn in array array[
243
- 'public.qbosync_report_start(date, text)',
244
- 'public.qbosync_report_finish(uuid, jsonb)',
245
- 'public.qbosync_report_fail(uuid, text)',
246
- 'public.qbosync_report_rows_only_running()'
247
- ] loop
248
- execute format('revoke all on function %s from public', fn);
249
- foreach r in array array['anon', 'authenticated'] loop
250
- if exists (select 1 from pg_roles where rolname = r) then
251
- execute format('revoke all on function %s from %I', fn, r);
252
- end if;
253
- end loop;
254
- if exists (select 1 from pg_roles where rolname = 'service_role') then
255
- execute format('grant execute on function %s to service_role', fn);
256
- end if;
257
- end loop;
258
- end $$;
259
-
260
- commit;
3
+ -- SQL editor, for instance) if the app keeps one. One transaction; re-running it is a no-op. It does not need 001_connection.sql.
4
+ --
5
+ -- qbosync_report_runs one row per run of the report: the day it covers, whether it is running, finished or failed,
6
+ -- and a finished day's totals by result, for the page that lists the days.
7
+ -- qbosync_report_rows one row per document per run, holding what was true THAT morning, so a past report can be
8
+ -- opened again and still shows what it showed then.
9
+ --
10
+ -- The SDK's guide ("A daily report") says how a run fills them. In short:
11
+ --
12
+ -- select * from qbosync_report_start('2026-11-08', 'America/Chicago'); -- the run, with that day's window in UTC
13
+ -- -- list the documents your app created in [window_start, window_end), ask QBO Sync, compare, then
14
+ -- insert into qbosync_report_rows (run_id, ...) values (...); -- one per document
15
+ -- select qbosync_report_finish(run_id, '{"documents": 12, "matches": 11, "failed": 1}');
16
+ -- -- or, when the day cannot be built:
17
+ -- select qbosync_report_fail(run_id, 'QBO Sync could not be reached');
18
+ --
19
+ -- Rules the database keeps:
20
+ -- - ONE run is running at a time: two jobs, or a manual run during the scheduled one, never overlap;
21
+ -- - ONE finished report per day: finishing a second report for a day replaces the first in the same transaction,
22
+ -- so the day always has one, never none;
23
+ -- - a run still running after 30 minutes (its server died) is marked failed by the next start;
24
+ -- - rows go only into a running run, and a failed run keeps none.
25
+ --
26
+ -- The tables have row level security on and no policy, and every function is granted to service_role only: your server
27
+ -- reads and writes them, and shows each person only their own companies' rows. Outside Supabase, grant the tables and
28
+ -- functions to the role your server connects with.
29
+ --
30
+ -- Undo (nothing else depends on these):
31
+ -- drop function public.qbosync_report_start(date, text);
32
+ -- drop function public.qbosync_report_finish(uuid, jsonb);
33
+ -- drop function public.qbosync_report_fail(uuid, text);
34
+ -- drop table public.qbosync_report_rows;
35
+ -- drop table public.qbosync_report_runs;
36
+ -- drop function public.qbosync_report_rows_only_running();
37
+
38
+ begin;
39
+
40
+ -- ── 1. Runs ─────────────────────────────────────────────────────────────────────────
41
+
42
+ create table if not exists public.qbosync_report_runs (
43
+ id uuid primary key default gen_random_uuid(),
44
+ -- The day reported, in the app's own time zone.
45
+ report_date date not null,
46
+ -- That zone (an IANA name, such as America/Chicago) and the day's midnight to midnight in it, in UTC. Worked out by
47
+ -- qbosync_report_start, so daylight saving is the database's job, not the app's.
48
+ time_zone text not null,
49
+ window_start timestamptz not null,
50
+ window_end timestamptz not null,
51
+ status text not null default 'running',
52
+ started_at timestamptz not null default now(),
53
+ finished_at timestamptz,
54
+ -- Why a failed run failed, for the page: a day that failed stays listed with this until a later run makes it up.
55
+ error text,
56
+ -- A finished run's totals: {"documents": 12, "matches": 11, "failed": 1, ...}.
57
+ counts jsonb,
58
+ constraint qbosync_report_runs_status_check check (status in ('running', 'done', 'failed')),
59
+ constraint qbosync_report_runs_window_check check (window_start < window_end),
60
+ constraint qbosync_report_runs_time_zone_check check (length(btrim(time_zone)) > 0),
61
+ constraint qbosync_report_runs_shape_check check (
62
+ (status = 'running' and finished_at is null and error is null and counts is null)
63
+ or (status = 'done' and finished_at is not null and error is null
64
+ and counts is not null and jsonb_typeof(counts) = 'object')
65
+ or (status = 'failed' and finished_at is not null and counts is null
66
+ and error is not null and length(btrim(error)) > 0))
67
+ );
68
+
69
+ -- One run at a time: every running run has the same key.
70
+ create unique index if not exists qbosync_report_runs_one_running
71
+ on public.qbosync_report_runs ((true)) where status = 'running';
72
+ -- One finished report per day.
73
+ create unique index if not exists qbosync_report_runs_one_done_per_day
74
+ on public.qbosync_report_runs (report_date) where status = 'done';
75
+ create index if not exists qbosync_report_runs_day_idx
76
+ on public.qbosync_report_runs (report_date desc, started_at desc);
77
+
78
+ -- ── 2. Rows ─────────────────────────────────────────────────────────────────────────
79
+
80
+ create table if not exists public.qbosync_report_rows (
81
+ id uuid primary key default gen_random_uuid(),
82
+ run_id uuid not null references public.qbosync_report_runs (id) on delete cascade,
83
+ document_type text not null,
84
+ -- The ref your app sent the document under: what QBO Sync was asked about.
85
+ source_ref text not null,
86
+ -- The company, as your app names it (the document's company_key): for showing each company only its own rows.
87
+ company_key text not null,
88
+ -- Optional: your own id for the document (any id, as text), and what people know it by (an order number, say).
89
+ document_id text,
90
+ label text,
91
+ -- The one result the document got. See the guide for when each applies:
92
+ -- matches posted, and every amount is what your app holds
93
+ -- differs posted, but an amount differs, or QuickBooks no longer holds what was posted
94
+ -- changed_since_posted your document changed after the version QBO Sync posted
95
+ -- not_posted QBO Sync has it and nothing is posted (waiting, syncing off, excluded, rolled back)
96
+ -- failed QBO Sync tried and failed; its error is kept
97
+ -- not_received QBO Sync never received it
98
+ result text not null,
99
+ -- As QBO Sync answered that morning.
100
+ qbo_number text,
101
+ sync_status text,
102
+ synced_at timestamptz,
103
+ -- The nightly QuickBooks check's result for what was posted; null while nothing is posted.
104
+ qbo_check text,
105
+ -- For "differs" only: each thing that did not match, as your app chooses to describe it (a JSON array, never empty).
106
+ differences jsonb,
107
+ -- QBO Sync's error for "failed"; for "not_received", your own record of why the send did not get through, if any.
108
+ error text,
109
+ -- Optional: your own record of sending it (shown beside "not_received").
110
+ send_status text,
111
+ created_at timestamptz not null default now(),
112
+ constraint qbosync_report_rows_type_check check (document_type in ('invoice', 'credit_memo', 'bill', 'vendor_credit')),
113
+ constraint qbosync_report_rows_ref_check check (length(btrim(source_ref)) > 0),
114
+ constraint qbosync_report_rows_company_check check (length(btrim(company_key)) > 0),
115
+ constraint qbosync_report_rows_result_check check (result in
116
+ ('matches', 'differs', 'changed_since_posted', 'not_posted', 'failed', 'not_received')),
117
+ constraint qbosync_report_rows_qbo_check_check check (
118
+ qbo_check is null or qbo_check in ('matches', 'differs', 'missing', 'not_checked')),
119
+ constraint qbosync_report_rows_differences_check check (
120
+ (result = 'differs') = (differences is not null and jsonb_typeof(differences) = 'array' and jsonb_array_length(differences) > 0))
121
+ );
122
+
123
+ -- A document once per run.
124
+ create unique index if not exists qbosync_report_rows_one_per_document
125
+ on public.qbosync_report_rows (run_id, document_type, source_ref);
126
+ create index if not exists qbosync_report_rows_company_idx
127
+ on public.qbosync_report_rows (run_id, company_key);
128
+
129
+ -- Rows go only into a running run: a finished report never changes, and a failed one stays empty.
130
+ create or replace function public.qbosync_report_rows_only_running()
131
+ returns trigger
132
+ language plpgsql
133
+ set search_path = public
134
+ as $$
135
+ begin
136
+ if not exists (select 1 from public.qbosync_report_runs where id = new.run_id and status = 'running') then
137
+ raise exception 'qbosync_report_rows: run % is not running', new.run_id;
138
+ end if;
139
+ return new;
140
+ end;
141
+ $$;
142
+
143
+ drop trigger if exists qbosync_report_rows_only_running on public.qbosync_report_rows;
144
+ create trigger qbosync_report_rows_only_running
145
+ before insert or update on public.qbosync_report_rows
146
+ for each row execute function public.qbosync_report_rows_only_running();
147
+
148
+ alter table public.qbosync_report_runs enable row level security;
149
+ alter table public.qbosync_report_rows enable row level security;
150
+
151
+ -- ── 3. Starting, finishing, failing ─────────────────────────────────────────────────
152
+
153
+ -- Starts a run for one day in the given time zone and answers it, with the day's window in UTC. A run still running after
154
+ -- 30 minutes is marked failed first (its server died); one running for less makes this raise, so two runs never overlap.
155
+ create or replace function public.qbosync_report_start(p_report_date date, p_time_zone text)
156
+ returns public.qbosync_report_runs
157
+ language plpgsql
158
+ set search_path = public
159
+ as $$
160
+ declare
161
+ run public.qbosync_report_runs;
162
+ begin
163
+ if p_report_date is null then
164
+ raise exception 'qbosync_report_start: a day is required';
165
+ end if;
166
+ if p_time_zone is null or not exists (select 1 from pg_timezone_names where name = p_time_zone) then
167
+ raise exception 'qbosync_report_start: % is not a time zone name (such as America/Chicago)', coalesce(p_time_zone, 'null');
168
+ end if;
169
+ update public.qbosync_report_runs
170
+ set status = 'failed', finished_at = now(), error = 'abandoned: still running after 30 minutes'
171
+ where status = 'running' and started_at < now() - interval '30 minutes';
172
+ -- An abandoned run keeps no rows, like any failed run.
173
+ delete from public.qbosync_report_rows r
174
+ using public.qbosync_report_runs u
175
+ where r.run_id = u.id and u.status = 'failed';
176
+
177
+ insert into public.qbosync_report_runs (report_date, time_zone, window_start, window_end)
178
+ values (p_report_date,
179
+ p_time_zone,
180
+ (p_report_date::timestamp) at time zone p_time_zone,
181
+ ((p_report_date + 1)::timestamp) at time zone p_time_zone)
182
+ returning * into run;
183
+ return run;
184
+ exception when unique_violation then
185
+ raise exception 'qbosync_report_start: another report is running';
186
+ end;
187
+ $$;
188
+
189
+ -- Finishes a running run with its totals. An earlier finished report for the same day is deleted in the same transaction
190
+ -- (its rows with it), so the day always has exactly one, never none while a rerun is being finished.
191
+ create or replace function public.qbosync_report_finish(p_run_id uuid, p_counts jsonb)
192
+ returns void
193
+ language plpgsql
194
+ set search_path = public
195
+ as $$
196
+ declare
197
+ day date;
198
+ begin
199
+ if p_counts is null or jsonb_typeof(p_counts) <> 'object' then
200
+ raise exception 'qbosync_report_finish: counts must be a JSON object';
201
+ end if;
202
+ select report_date into day from public.qbosync_report_runs where id = p_run_id and status = 'running' for update;
203
+ if not found then
204
+ raise exception 'qbosync_report_finish: run % is not running', p_run_id;
205
+ end if;
206
+ delete from public.qbosync_report_runs where report_date = day and status = 'done';
207
+ update public.qbosync_report_runs
208
+ set status = 'done', finished_at = now(), counts = p_counts
209
+ where id = p_run_id;
210
+ end;
211
+ $$;
212
+
213
+ -- Marks a running run failed, keeping why, and drops the rows it had written. An earlier finished report for the day stays.
214
+ create or replace function public.qbosync_report_fail(p_run_id uuid, p_error text)
215
+ returns void
216
+ language plpgsql
217
+ set search_path = public
218
+ as $$
219
+ begin
220
+ delete from public.qbosync_report_rows where run_id = p_run_id;
221
+ update public.qbosync_report_runs
222
+ set status = 'failed', finished_at = now(),
223
+ error = coalesce(nullif(btrim(p_error), ''), 'the report could not be built')
224
+ where id = p_run_id and status = 'running';
225
+ end;
226
+ $$;
227
+
228
+ do $$
229
+ declare
230
+ fn text;
231
+ tbl text;
232
+ r text;
233
+ begin
234
+ foreach tbl in array array['public.qbosync_report_runs', 'public.qbosync_report_rows'] loop
235
+ execute format('revoke all on table %s from public', tbl);
236
+ foreach r in array array['anon', 'authenticated'] loop
237
+ if exists (select 1 from pg_roles where rolname = r) then
238
+ execute format('revoke all on table %s from %I', tbl, r);
239
+ end if;
240
+ end loop;
241
+ end loop;
242
+ foreach fn in array array[
243
+ 'public.qbosync_report_start(date, text)',
244
+ 'public.qbosync_report_finish(uuid, jsonb)',
245
+ 'public.qbosync_report_fail(uuid, text)',
246
+ 'public.qbosync_report_rows_only_running()'
247
+ ] loop
248
+ execute format('revoke all on function %s from public', fn);
249
+ foreach r in array array['anon', 'authenticated'] loop
250
+ if exists (select 1 from pg_roles where rolname = r) then
251
+ execute format('revoke all on function %s from %I', fn, r);
252
+ end if;
253
+ end loop;
254
+ if exists (select 1 from pg_roles where rolname = 'service_role') then
255
+ execute format('grant execute on function %s to service_role', fn);
256
+ end if;
257
+ end loop;
258
+ end $$;
259
+
260
+ commit;
@@ -1,25 +1,25 @@
1
- -- The daily report keeps rows for bills and vendor credits too (SDK 0.5.1).
2
- --
3
- -- Run this once if your app ran sql/002_daily_report.sql before 0.5.1 and sends bills or vendor credits. Until then,
4
- -- 002's check allowed only 'invoice' and 'credit_memo', so the first morning with a bill failed whole ("new row for
5
- -- relation qbosync_report_rows violates check constraint qbosync_report_rows_type_check") and every later morning with
6
- -- one did too. 002 itself now allows all four types, so an app that runs 002 from 0.5.1 on does not need this file;
7
- -- running it anyway changes nothing. One transaction; re-running it is a no-op.
8
- --
9
- -- Found by Aztec's end-to-end run on 2026-11-16, the first app to send bills.
10
- --
11
- -- Undo (only while no bill or vendor credit row exists):
12
- -- alter table public.qbosync_report_rows drop constraint qbosync_report_rows_type_check;
13
- -- alter table public.qbosync_report_rows add constraint qbosync_report_rows_type_check
14
- -- check (document_type in ('invoice', 'credit_memo'));
15
-
16
- begin;
17
-
18
- alter table public.qbosync_report_rows
19
- drop constraint if exists qbosync_report_rows_type_check;
20
-
21
- alter table public.qbosync_report_rows
22
- add constraint qbosync_report_rows_type_check
23
- check (document_type in ('invoice', 'credit_memo', 'bill', 'vendor_credit'));
24
-
25
- commit;
1
+ -- The daily report keeps rows for bills and vendor credits too (SDK 0.5.1).
2
+ --
3
+ -- Run this once if your app ran sql/002_daily_report.sql before 0.5.1 and sends bills or vendor credits. Until then,
4
+ -- 002's check allowed only 'invoice' and 'credit_memo', so the first morning with a bill failed whole ("new row for
5
+ -- relation qbosync_report_rows violates check constraint qbosync_report_rows_type_check") and every later morning with
6
+ -- one did too. 002 itself now allows all four types, so an app that runs 002 from 0.5.1 on does not need this file;
7
+ -- running it anyway changes nothing. One transaction; re-running it is a no-op.
8
+ --
9
+ -- Found by Aztec's end-to-end run on 2026-11-16, the first app to send bills.
10
+ --
11
+ -- Undo (only while no bill or vendor credit row exists):
12
+ -- alter table public.qbosync_report_rows drop constraint qbosync_report_rows_type_check;
13
+ -- alter table public.qbosync_report_rows add constraint qbosync_report_rows_type_check
14
+ -- check (document_type in ('invoice', 'credit_memo'));
15
+
16
+ begin;
17
+
18
+ alter table public.qbosync_report_rows
19
+ drop constraint if exists qbosync_report_rows_type_check;
20
+
21
+ alter table public.qbosync_report_rows
22
+ add constraint qbosync_report_rows_type_check
23
+ check (document_type in ('invoice', 'credit_memo', 'bill', 'vendor_credit'));
24
+
25
+ commit;