@company-six/qbosync 0.3.0 → 0.3.1

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
@@ -158,15 +158,103 @@ const checked = await client.checkStatusReports(body, headers[SIGNATURE_HEADER])
158
158
 
159
159
  Never use these outside tests: anyone can make such a key.
160
160
 
161
- ## 7. Compare
161
+ ## 7. A daily report (optional)
162
162
 
163
- For a daily report, name the documents your app created that day:
163
+ Each morning, set the invoices and credit memos your app created the day before beside what QBO Sync did with them: posted with the same amounts, posted but different, waiting, failed, or never received. QBO Sync answers for each document; your app picks the documents, compares, keeps the report and shows it. Fixing anything (a resync, a rollback) is done in QBO Sync.
164
+
165
+ To ask about any number of your documents (in batches of 100, answered in the order asked):
164
166
 
165
167
  ```ts
166
- const report = await qbosync.documentReport(refs);
168
+ const asked = await qbosync.documentReport(refs);
167
169
  // each entry: its status, QuickBooks number, what was posted and the nightly check, or sync_status "unknown" if never received
168
170
  ```
169
171
 
172
+ The rest of this section builds the report around that call. Your app does all of it; only the tables come with the SDK.
173
+
174
+ ### Add the report tables
175
+
176
+ Run [`sql/002_daily_report.sql`](sql/002_daily_report.sql) once, as you ran the first file (it is in `node_modules/@company-six/qbosync/sql/`). It adds:
177
+
178
+ - **`qbosync_report_runs`**: one row per run. It holds the day, its window in UTC, whether it is running, done or failed, and a finished day's totals.
179
+ - **`qbosync_report_rows`**: one row per document per run. It holds what was true that morning, so a past report shows what it showed then.
180
+ - **`qbosync_report_start(day, time_zone)`**, **`qbosync_report_finish(run_id, counts)`** and **`qbosync_report_fail(run_id, error)`**.
181
+
182
+ The database keeps the rules for you. Only one run runs at a time, and a day has one finished report: finishing a rerun replaces the earlier report. A failed run keeps no rows and leaves the earlier report in place. A run left running for 30 minutes (its server died) is marked failed by the next start.
183
+
184
+ ### Run it each morning
185
+
186
+ Run a scheduled job after QBO Sync's nightly QuickBooks check, which starts at 08:00 UTC (11:00 UTC leaves room). Report **yesterday in your own time zone**. Then make up any earlier day that has no finished report, counting from the first day that has one, oldest first and a few days at most per run. That way a morning that failed fills itself in.
187
+
188
+ ```ts
189
+ import type { ReportEntry } from "@company-six/qbosync/contract";
190
+
191
+ const TIME_ZONE = "America/Chicago"; // your app's day
192
+
193
+ async function reportDay(day: string) { // "2026-11-08"
194
+ const { data: run, error } = await supabase.rpc("qbosync_report_start", { p_report_date: day, p_time_zone: TIME_ZONE });
195
+ if (error) throw new Error(error.message); // another run is running: stop, the next one makes the day up
196
+
197
+ try {
198
+ // From YOUR records: the documents you created in [window_start, window_end), each with the ref you sent it under.
199
+ const docs = await documentsCreated(run.window_start, run.window_end);
200
+ const asked = await qbosync.documentReport(docs.map((d) => d.source_ref));
201
+ if (!asked.ok) throw new Error(asked.error);
202
+
203
+ const rows = docs.map((doc, i) => ({
204
+ run_id: run.id,
205
+ document_type: doc.document_type, // "invoice" | "credit_memo"
206
+ source_ref: doc.source_ref,
207
+ company_key: doc.company_key,
208
+ document_id: doc.id,
209
+ label: doc.order_number,
210
+ ...compare(doc, asked.documents[i]),
211
+ }));
212
+ if (rows.length) {
213
+ const inserted = await supabase.from("qbosync_report_rows").insert(rows);
214
+ if (inserted.error) throw new Error(inserted.error.message);
215
+ }
216
+ const finished = await supabase.rpc("qbosync_report_finish", { p_run_id: run.id, p_counts: countByResult(rows) });
217
+ if (finished.error) throw new Error(finished.error.message);
218
+ } catch (err) {
219
+ await supabase.rpc("qbosync_report_fail", { p_run_id: run.id, p_error: err instanceof Error ? err.message : String(err) });
220
+ throw err; // stop: the next morning makes this day up
221
+ }
222
+ }
223
+ ```
224
+
225
+ Pick the documents **by when your app created them**, not by their issue date or by when QBO Sync received them. QBO Sync may receive a document hours later (a retry, a company with syncing off), and only your app knows when it made it. Leave out what your app never meant to send, such as a company that has not connected. Otherwise every one of its documents reads as never received.
226
+
227
+ Insert in pages of a few hundred rows on a busy day.
228
+
229
+ ### Compare
230
+
231
+ Give each document **one** result, checked in this order:
232
+
233
+ | Result | When |
234
+ |---|---|
235
+ | `not_received` | `sync_status` is `"unknown"`: QBO Sync never received it. Keep your own record of the send beside it (`send_status`, `error`). |
236
+ | `failed` | `sync_status` is `"failed"`. Keep QBO Sync's `error`. |
237
+ | `not_posted` | `posted` is null, or `sync_status` is `"deleted"` or `"excluded"`. It is waiting, syncing is off, or it was excluded or rolled back. |
238
+ | `changed_since_posted` | `posted_version` is not `latest_version`, or your document changed after QBO Sync accepted it. A newer version has not been posted. |
239
+ | `differs` | Something below does not match. Say what in `differences` (a JSON array, never empty, in whatever shape your page shows). |
240
+ | `matches` | Everything below matches. |
241
+
242
+ What to check for `differs`:
243
+
244
+ - **Amounts**: your totals against `posted`. `total_cents`, `shipping_cents`, `tax_cents` and, on an invoice, `discount_cents`. Then each line by its `line_ref` (on a credit memo, `applies_to_line_ref`): its `quantity` and `amount_cents`, and any line only one side has. `posted` is in your own terms, in cents, and a credit memo's amounts are positive.
245
+ - **Voided**: a document you voided should read `sync_status: "voided"`, and the other way round. When both are voided, there are no amounts to compare.
246
+ - **QuickBooks**: `check.result` is QBO Sync's nightly read-back. `differs` means someone changed the document in QuickBooks; `check.differences` says how, in sentences you can show. `missing` means it was deleted there. Either one makes the result `differs`. `not_checked` (the check has not reached it yet) does not keep a document from matching.
247
+
248
+ Copy `qbo_number`, `sync_status`, `synced_at` and `check.result` (as `qbo_check`) into every row QBO Sync knows, so the row stands on its own later. For totals, count rows by result and add `documents`: `{ "documents": 12, "matches": 11, "failed": 1 }`.
249
+
250
+ ### Show it
251
+
252
+ - **The list of days**: one line per `report_date`, newest first. Show the day's `done` run with its `counts`. A day with no finished run shows its latest failed run with its `error`, so a gap is visible until a later run makes it up.
253
+ - **One day**: its rows, by `company_key`.
254
+ - **Who sees what**: the tables are for your server only. Show each person only the rows of the companies they belong to, through your own route.
255
+
256
+ Keep the report read-only, and send people to QBO Sync to fix a document.
257
+
170
258
  ## When a call fails
171
259
 
172
260
  Nothing here throws for something QBO Sync or the network did. Every call answers `{ ok: true, ... }` or a failure with an `error` you can show a person, and a `reason`:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@company-six/qbosync",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Connect an app to QBO Sync: send invoices and credit memos to QuickBooks, and hear back what happened to them.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -0,0 +1,260 @@
1
+ -- An app's daily report: each morning, the invoices and credit memos the app created the day before, set beside what
2
+ -- QBO Sync did with them. Optional; run this once in the app's own Postgres database (the Supabase SQL editor, for
3
+ -- 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')),
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;