@company-six/qbosync 0.10.0 → 0.11.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,8 @@ 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
+
141
143
  ### Bills and vendor credits (0.5.0)
142
144
 
143
145
  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.
@@ -187,6 +189,7 @@ The SDK sends each file to QBO Sync first, adds it to the document's `attachment
187
189
  - **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
190
  - **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
191
  - **A file that could not be sent** (the file store was down) leaves its document unsent with `failure`: send both again later.
192
+ - **A QBO Sync older than files** (it answers 404 where files are sent) is the same: `failure`, never `parked`, so nothing is refused for good while QBO Sync waits to be updated (0.10.1). Any other refusal there is still `parked`.
190
193
 
191
194
  To do the two steps yourself, `uploadAttachment` sends one file and answers what to put in the document:
192
195
 
package/dist/client.js CHANGED
@@ -314,6 +314,17 @@ export class QbosyncClient {
314
314
  return called;
315
315
  const { res } = called;
316
316
  const body = (await res.json().catch(() => null));
317
+ // QBO Sync's upload route never answers 404 itself, so a 404 means this QBO Sync is older than files (0.9.0) and has
318
+ // no such route yet. Nothing is wrong with the file or its document: a refusal would park it for good, when it only
319
+ // needs QBO Sync to be updated. Try again later instead (0.10.1).
320
+ if (res.status === 404) {
321
+ return {
322
+ ok: false,
323
+ reason: "unavailable",
324
+ status: 404,
325
+ error: "QBO Sync cannot take files yet: it answered 404 where files are sent, so it runs an older version than this SDK. Nothing was refused; send again once QBO Sync is updated.",
326
+ };
327
+ }
317
328
  if (!res.ok)
318
329
  return failureOf(res, body);
319
330
  if (body?.held === true)
@@ -32,6 +32,24 @@ 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
+ /** At most this many `extra_order_refs` on one document. */
36
+ export declare const MAX_EXTRA_ORDER_REFS = 10;
37
+ /**
38
+ * `extra_order_refs` (0.11.0): other ids the same order has, each in `order_ref`'s form, so a payment
39
+ * QBO Sync reads from a connector finds this document through any of them. A marketplace order that
40
+ * reaches the app as a shop order is the case: the invoice's `order_ref` is the shop's
41
+ * ("shopify:5551234567"), and the marketplace's payment knows only its own id ("faire:bo_kt2semdnvy").
42
+ * At most 10, no repeats, none equal to the document's `order_ref` (`extraOrderRefIssues`).
43
+ */
44
+ export declare const extraOrderRefs: z.ZodArray<z.ZodString>;
45
+ /** What is wrong with a document's `extra_order_refs` beyond each id's form: a repeat, or its own `order_ref`. */
46
+ export declare function extraOrderRefIssues(doc: {
47
+ order_ref?: string;
48
+ extra_order_refs?: string[];
49
+ }): Array<{
50
+ index: number;
51
+ message: string;
52
+ }>;
35
53
  /** A document's number as QuickBooks holds it: at most 21 characters (QuickBooks' DocNumber limit). */
36
54
  export declare const docNumber: z.ZodPipe<z.ZodString, z.ZodString>;
37
55
  /** Written into the memo in this order. */
@@ -38,6 +38,29 @@ export const currency = z.string().regex(/^[A-Z]{3}$/, "must be a three-letter c
38
38
  export const orderRef = z
39
39
  .string()
40
40
  .regex(/^[a-z][a-z0-9_-]*:\S+$/, 'must be "<system>:<id>", e.g. "shopify:5551234567"');
41
+ /** At most this many `extra_order_refs` on one document. */
42
+ export const MAX_EXTRA_ORDER_REFS = 10;
43
+ /**
44
+ * `extra_order_refs` (0.11.0): other ids the same order has, each in `order_ref`'s form, so a payment
45
+ * QBO Sync reads from a connector finds this document through any of them. A marketplace order that
46
+ * reaches the app as a shop order is the case: the invoice's `order_ref` is the shop's
47
+ * ("shopify:5551234567"), and the marketplace's payment knows only its own id ("faire:bo_kt2semdnvy").
48
+ * At most 10, no repeats, none equal to the document's `order_ref` (`extraOrderRefIssues`).
49
+ */
50
+ export const extraOrderRefs = z.array(orderRef).max(MAX_EXTRA_ORDER_REFS, `must list at most ${MAX_EXTRA_ORDER_REFS} order ids`);
51
+ /** What is wrong with a document's `extra_order_refs` beyond each id's form: a repeat, or its own `order_ref`. */
52
+ export function extraOrderRefIssues(doc) {
53
+ const issues = [];
54
+ const seen = new Set();
55
+ (doc.extra_order_refs ?? []).forEach((ref, index) => {
56
+ if (ref === doc.order_ref)
57
+ issues.push({ index, message: `"${ref}" is already the order_ref` });
58
+ else if (seen.has(ref))
59
+ issues.push({ index, message: `"${ref}" is listed twice` });
60
+ seen.add(ref);
61
+ });
62
+ return issues;
63
+ }
41
64
  /** A document's number as QuickBooks holds it: at most 21 characters (QuickBooks' DocNumber limit). */
42
65
  export const docNumber = text.pipe(z.string().max(21, "must be at most 21 characters"));
43
66
  /** Written into the memo in this order. */
@@ -26,6 +26,7 @@ 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>>;
29
30
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
31
  label: z.ZodString;
31
32
  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, 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,7 @@ 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(),
32
33
  references: references.optional(),
33
34
  class_key: z.string().optional(),
34
35
  customer,
@@ -58,6 +59,9 @@ export const creditMemoSchema = z
58
59
  });
59
60
  }
60
61
  });
62
+ for (const issue of extraOrderRefIssues(doc)) {
63
+ ctx.addIssue({ code: "custom", path: ["extra_order_refs", issue.index], message: issue.message });
64
+ }
61
65
  const expected = sum(doc.lines.map((l) => l.amount_cents)) + doc.shipping_cents + doc.tax_cents;
62
66
  if (doc.total_cents !== expected) {
63
67
  ctx.addIssue({ code: "custom", path: ["total_cents"], message: `must equal lines + shipping + tax (${expected})` });
@@ -26,6 +26,7 @@ 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>>;
29
30
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
31
  label: z.ZodString;
31
32
  value: z.ZodString;
@@ -91,6 +92,7 @@ export declare const appDocumentSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
91
92
  currency: z.ZodString;
92
93
  applies_to_invoice_ref: z.ZodString;
93
94
  order_ref: z.ZodOptional<z.ZodString>;
95
+ extra_order_refs: z.ZodOptional<z.ZodArray<z.ZodString>>;
94
96
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
95
97
  label: z.ZodString;
96
98
  value: z.ZodString;
@@ -31,6 +31,7 @@ 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>>;
34
35
  references: z.ZodOptional<z.ZodArray<z.ZodObject<{
35
36
  label: z.ZodString;
36
37
  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, 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,7 @@ 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(),
39
40
  references: references.optional(),
40
41
  class_key: z.string().optional(),
41
42
  customer,
@@ -56,6 +57,9 @@ export const invoiceSchema = z
56
57
  });
57
58
  }
58
59
  });
60
+ for (const issue of extraOrderRefIssues(doc)) {
61
+ ctx.addIssue({ code: "custom", path: ["extra_order_refs", issue.index], message: issue.message });
62
+ }
59
63
  const seen = new Set();
60
64
  doc.lines.forEach((line, i) => {
61
65
  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.0",
3
+ "version": "0.11.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;