@mccaskie-labs/workbench-agreements 0.3.0 → 0.3.2

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.
@@ -0,0 +1,594 @@
1
+ // Open documents (workbench-agreements 0.3.2): saved wording plus a form's
2
+ // questions, signed by anyone from a link or a QR code, for themselves or for
3
+ // a child, valid for one event or a number of months. A second migration,
4
+ // beside agreementsMigration, so a project that already has agreements adds
5
+ // it without touching them (`npx workbench-agreements migration` writes it
6
+ // when it is missing). Additive only.
7
+ //
8
+ // - agreement_documents: each version of a document. Changing the wording
9
+ // saves a new version; signatures stay with the version they signed. One
10
+ // version per slug is current (retired_at is null).
11
+ // - agreement_requests: a link the app asked for, for one place on a booking
12
+ // (its subject). Each is used by one signature.
13
+ // - document_signatures: one person's signing, from "started" (pending: they
14
+ // gave their name and email) to signed. Answers are split: `answers` the
15
+ // ordinary ones, `sensitive` the ones the form marks sensitive (deleted
16
+ // sooner, by retention.sensitive_days_after), `files` the uploads' keys in
17
+ // the app's R2 bucket (deleted with the sensitive answers).
18
+ // - document_events: the audit trail, rows only ever added.
19
+ //
20
+ // Service role only, as agreementsMigration: RLS on with no policies, every
21
+ // function granted to service_role only. Signing locks the signature's row and
22
+ // its request's, so a request link signs once. The down file drops
23
+ // everything the up file made.
24
+ const FUNCTIONS = [
25
+ ["documents_save", "jsonb"],
26
+ ["documents_current", "text"],
27
+ ["documents_get", "uuid"],
28
+ ["documents_list", "text, integer"],
29
+ ["documents_retire", "text, text, timestamptz"],
30
+ ["documents_request", "jsonb"],
31
+ ["documents_request_open", "text"],
32
+ ["documents_start", "jsonb"],
33
+ ["documents_open", "text"],
34
+ ["documents_event", "uuid, text, timestamptz, text, text, jsonb"],
35
+ ["documents_code_sent", "uuid, text, timestamptz, timestamptz, text, text"],
36
+ ["documents_code_try", "uuid, text, timestamptz, text, text"],
37
+ ["documents_sign", "jsonb"],
38
+ ["documents_complete", "uuid, text, text, timestamptz"],
39
+ ["documents_copies_sent", "uuid, timestamptz, integer"],
40
+ ["documents_valid", "text, text, text, text, text, timestamptz"],
41
+ ["documents_signatures", "text, text, integer"],
42
+ ["documents_signature", "uuid"],
43
+ ["documents_scan", "timestamptz, timestamptz, integer"],
44
+ ["documents_renewal_sent", "uuid, timestamptz"],
45
+ ["documents_old", "timestamptz, timestamptz, timestamptz, timestamptz, integer"],
46
+ ["documents_scrub", "uuid[], timestamptz"],
47
+ ["documents_delete", "uuid[], uuid[], timestamptz"],
48
+ ];
49
+ const grants = FUNCTIONS.map(([f, args]) => `revoke execute on function public.${f}(${args}) from public, anon, authenticated;\ngrant execute on function public.${f}(${args}) to service_role;`).join("\n");
50
+ const drops = [...FUNCTIONS].reverse().map(([f, args]) => `drop function public.${f}(${args});`).join("\n");
51
+ export const documentsMigration = {
52
+ up: `create table public.agreement_documents (
53
+ id uuid primary key,
54
+ account text not null check (char_length(account) between 1 and 200),
55
+ slug text not null check (slug ~ '^[a-z0-9][a-z0-9-]{2,59}$'),
56
+ version integer not null check (version >= 1),
57
+ title text not null check (char_length(title) between 1 and 200),
58
+ business text not null check (char_length(business) between 1 and 200),
59
+ language text not null default 'en' check (language in ('en', 'tl', 'taglish')),
60
+ document_key text not null check (char_length(document_key) between 1 and 300),
61
+ document_sha256 text not null check (document_sha256 ~ '^[0-9a-f]{64}$'),
62
+ pages integer not null check (pages between 1 and 2000),
63
+ form text check (form ~ '^[a-z][a-z0-9_]{0,62}$'),
64
+ for_child text not null default 'never' check (for_child in ('never', 'allowed', 'always')),
65
+ validity_months smallint check (validity_months between 1 and 120),
66
+ copy_to text[] not null default '{}' check (cardinality(copy_to) <= 5),
67
+ created_at timestamptz not null,
68
+ retired_at timestamptz,
69
+ unique (slug, version)
70
+ );
71
+
72
+ comment on table public.agreement_documents is 'Open documents (workbench-agreements): each version of saved wording, its PDF''s key in the app''s R2 bucket and SHA-256, the form it asks, who may sign for a child and how long a signature lasts (validity_months; null is one event). Service role only.';
73
+
74
+ create unique index agreement_documents_current on public.agreement_documents (slug) where retired_at is null;
75
+ create index agreement_documents_account on public.agreement_documents (account, created_at desc);
76
+
77
+ create table public.agreement_requests (
78
+ id uuid primary key default gen_random_uuid(),
79
+ document_id uuid not null references public.agreement_documents (id) on delete cascade,
80
+ token text not null unique check (token ~ '^[A-Za-z0-9_-]{43}$'),
81
+ subject_type text not null check (char_length(subject_type) between 1 and 60),
82
+ subject_id text not null check (char_length(subject_id) between 1 and 200),
83
+ valid_until timestamptz,
84
+ created_at timestamptz not null,
85
+ expires_at timestamptz not null,
86
+ signature_id uuid,
87
+ check (expires_at > created_at)
88
+ );
89
+
90
+ comment on table public.agreement_requests is 'Signing links the app asked for, one per place on a booking (workbench-agreements): the document, the app''s own row it is for, and the signature that used it. Service role only.';
91
+
92
+ create index agreement_requests_document on public.agreement_requests (document_id);
93
+ create index agreement_requests_subject on public.agreement_requests (subject_type, subject_id);
94
+
95
+ create table public.document_signatures (
96
+ id uuid primary key,
97
+ document_id uuid not null references public.agreement_documents (id) on delete cascade,
98
+ request_id uuid references public.agreement_requests (id) on delete set null,
99
+ token text not null unique check (token ~ '^[A-Za-z0-9_-]{43}$'),
100
+ status text not null default 'pending' check (status in ('pending', 'signed')),
101
+ subject_type text check (char_length(subject_type) between 1 and 60),
102
+ subject_id text check (char_length(subject_id) between 1 and 200),
103
+ name text not null check (char_length(name) between 2 and 120),
104
+ email text not null check (char_length(email) between 3 and 254 and email ~ '^[^@\\s]+@[^@\\s]+$'),
105
+ created_at timestamptz not null,
106
+ verified_at timestamptz,
107
+ code_hash text check (code_hash ~ '^[0-9a-f]{64}$'),
108
+ code_sent_at timestamptz,
109
+ code_expires_at timestamptz,
110
+ code_tries smallint not null default 0,
111
+ for_child boolean not null default false,
112
+ child_name text check (char_length(child_name) between 2 and 120),
113
+ relationship text check (relationship in ('parent', 'guardian')),
114
+ answers jsonb check (answers is null or (jsonb_typeof(answers) = 'object' and octet_length(answers::text) <= 100000)),
115
+ sensitive jsonb check (sensitive is null or (jsonb_typeof(sensitive) = 'object' and octet_length(sensitive::text) <= 50000)),
116
+ sensitive_deleted_at timestamptz,
117
+ files jsonb not null default '[]' check (jsonb_typeof(files) = 'array' and jsonb_array_length(files) <= 20),
118
+ answers_sha256 text check (answers_sha256 ~ '^[0-9a-f]{64}$'),
119
+ signed_at timestamptz,
120
+ method text check (method in ('typed', 'drawn')),
121
+ typed_name text check (char_length(typed_name) between 2 and 120),
122
+ signature_key text check (char_length(signature_key) between 1 and 300),
123
+ consent text check (char_length(consent) between 1 and 2000),
124
+ sign_ip text check (char_length(sign_ip) <= 64),
125
+ sign_user_agent text check (char_length(sign_user_agent) <= 400),
126
+ valid_until timestamptz,
127
+ signed_key text check (char_length(signed_key) between 1 and 300),
128
+ signed_sha256 text check (signed_sha256 ~ '^[0-9a-f]{64}$'),
129
+ copies_sent_at timestamptz,
130
+ renewal_sent_at timestamptz,
131
+ check ((subject_type is null) = (subject_id is null)),
132
+ check ((status = 'signed') = (signed_at is not null) and (signed_at is null) = (method is null) and (method is null) = (typed_name is null) and (typed_name is null) = (consent is null)),
133
+ check ((status = 'signed') = (answers_sha256 is not null)),
134
+ check ((method = 'drawn') = (signature_key is not null)),
135
+ check (for_child = (child_name is not null) and (child_name is null) = (relationship is null)),
136
+ check ((signed_sha256 is null) = (signed_key is null))
137
+ );
138
+
139
+ comment on table public.document_signatures is 'Who signed an open document and how (workbench-agreements). Name, email, a child''s name, the answers and, when the project keeps them, IP address and browser are personal details, kept for retention.signed_years; sensitive answers and uploaded files (keys in the app''s R2 bucket) are deleted retention.sensitive_days_after days after the signature stops being valid. Service role only.';
140
+
141
+ create index document_signatures_person on public.document_signatures (document_id, lower(email)) where status = 'signed';
142
+ create index document_signatures_pending on public.document_signatures (document_id, created_at) where status = 'pending';
143
+ create index document_signatures_valid on public.document_signatures (valid_until) where status = 'signed';
144
+ create index document_signatures_subject on public.document_signatures (subject_type, subject_id) where subject_id is not null;
145
+
146
+ create table public.document_events (
147
+ id bigint generated always as identity primary key,
148
+ signature_id uuid not null references public.document_signatures (id) on delete cascade,
149
+ kind text not null check (kind in ('started', 'code_sent', 'code_failed', 'verified', 'opened', 'document_viewed', 'signed', 'completed', 'copy_sent', 'copy_downloaded', 'renewal_sent', 'sensitive_deleted')),
150
+ at timestamptz not null,
151
+ ip text check (char_length(ip) <= 64),
152
+ user_agent text check (char_length(user_agent) <= 400),
153
+ detail jsonb check (detail is null or (jsonb_typeof(detail) = 'object' and octet_length(detail::text) <= 2000))
154
+ );
155
+
156
+ comment on table public.document_events is 'The audit trail of each open document signature (workbench-agreements): what happened, when, and the IP address and browser when the project keeps them. Rows are only added. Service role only.';
157
+
158
+ create index document_events_signature on public.document_events (signature_id, at, id);
159
+
160
+ alter table public.agreement_documents enable row level security;
161
+ alter table public.agreement_requests enable row level security;
162
+ alter table public.document_signatures enable row level security;
163
+ alter table public.document_events enable row level security;
164
+
165
+ revoke all on public.agreement_documents, public.agreement_requests, public.document_signatures, public.document_events from anon, authenticated;
166
+
167
+ -- p: { id, account, slug, title, business, language, document_key, document_sha256, pages, form?, for_child, validity_months?, copy_to, created_at }.
168
+ -- Retires the current version and saves the next. { ok, version } or { ok: false, reason: taken } when another account has the slug.
169
+ create function public.documents_save(p jsonb)
170
+ returns jsonb
171
+ language plpgsql
172
+ security invoker
173
+ set search_path = ''
174
+ as $$
175
+ declare
176
+ cur public.agreement_documents;
177
+ v integer;
178
+ begin
179
+ perform pg_advisory_xact_lock(hashtextextended('workbench-agreements:' || (p->>'slug'), 0));
180
+ select * into cur from public.agreement_documents where slug = p->>'slug' order by version desc limit 1;
181
+ if found and cur.account <> p->>'account' then return jsonb_build_object('ok', false, 'reason', 'taken'); end if;
182
+ v := coalesce(cur.version, 0) + 1;
183
+ update public.agreement_documents set retired_at = (p->>'created_at')::timestamptz where slug = p->>'slug' and retired_at is null;
184
+ insert into public.agreement_documents (id, account, slug, version, title, business, language, document_key, document_sha256, pages, form, for_child, validity_months, copy_to, created_at)
185
+ values ((p->>'id')::uuid, p->>'account', p->>'slug', v, p->>'title', p->>'business', p->>'language', p->>'document_key', p->>'document_sha256', (p->>'pages')::integer,
186
+ p->>'form', p->>'for_child', (p->>'validity_months')::smallint, coalesce((select array_agg(x) from jsonb_array_elements_text(p->'copy_to') x), '{}'), (p->>'created_at')::timestamptz);
187
+ return jsonb_build_object('ok', true, 'version', v);
188
+ end;
189
+ $$;
190
+
191
+ -- The current version of a slug, or null.
192
+ create function public.documents_current(p_slug text)
193
+ returns jsonb
194
+ language sql
195
+ stable
196
+ security invoker
197
+ set search_path = ''
198
+ as $$
199
+ select to_jsonb(d) from public.agreement_documents d where d.slug = p_slug and d.retired_at is null;
200
+ $$;
201
+
202
+ create function public.documents_get(p_id uuid)
203
+ returns jsonb
204
+ language sql
205
+ stable
206
+ security invoker
207
+ set search_path = ''
208
+ as $$
209
+ select to_jsonb(d) from public.agreement_documents d where d.id = p_id;
210
+ $$;
211
+
212
+ -- An account's current documents, newest first, with how many have signed each version.
213
+ create function public.documents_list(p_account text, p_limit integer)
214
+ returns jsonb
215
+ language sql
216
+ stable
217
+ security invoker
218
+ set search_path = ''
219
+ as $$
220
+ select coalesce(jsonb_agg(to_jsonb(d) || jsonb_build_object('signed', (select count(*) from public.document_signatures s where s.document_id = d.id and s.status = 'signed')) order by d.created_at desc), '[]'::jsonb)
221
+ from (select * from public.agreement_documents where account = p_account and retired_at is null order by created_at desc limit p_limit) d;
222
+ $$;
223
+
224
+ create function public.documents_retire(p_slug text, p_account text, p_at timestamptz)
225
+ returns boolean
226
+ language plpgsql
227
+ security invoker
228
+ set search_path = ''
229
+ as $$
230
+ begin
231
+ update public.agreement_documents set retired_at = p_at where slug = p_slug and account = p_account and retired_at is null;
232
+ return found;
233
+ end;
234
+ $$;
235
+
236
+ -- p: { document_id, subject_type, subject_id, valid_until?, created_at, expires_at, tokens: [..] }. Returns how many links were made.
237
+ create function public.documents_request(p jsonb)
238
+ returns integer
239
+ language plpgsql
240
+ security invoker
241
+ set search_path = ''
242
+ as $$
243
+ declare
244
+ n integer;
245
+ begin
246
+ insert into public.agreement_requests (document_id, token, subject_type, subject_id, valid_until, created_at, expires_at)
247
+ select (p->>'document_id')::uuid, t, p->>'subject_type', p->>'subject_id', (p->>'valid_until')::timestamptz, (p->>'created_at')::timestamptz, (p->>'expires_at')::timestamptz
248
+ from jsonb_array_elements_text(p->'tokens') t;
249
+ get diagnostics n = row_count;
250
+ return n;
251
+ end;
252
+ $$;
253
+
254
+ -- What a request link opens: the request (with whether it is used) and the document version it is for. Null for an unknown token.
255
+ create function public.documents_request_open(p_token text)
256
+ returns jsonb
257
+ language sql
258
+ stable
259
+ security invoker
260
+ set search_path = ''
261
+ as $$
262
+ select jsonb_build_object('request', to_jsonb(r) - 'token', 'document', to_jsonb(d))
263
+ from public.agreement_requests r join public.agreement_documents d on d.id = r.document_id
264
+ where r.token = p_token;
265
+ $$;
266
+
267
+ -- p: { id, document_id, request_id?, token, name, email, created_at }. Starts a signing.
268
+ -- { ok, reason? }: reason used or expired (the request), retired (the document), busy (too many unfinished starts for this email or this document in the last hour).
269
+ create function public.documents_start(p jsonb)
270
+ returns jsonb
271
+ language plpgsql
272
+ security invoker
273
+ set search_path = ''
274
+ as $$
275
+ declare
276
+ r public.agreement_requests;
277
+ d public.agreement_documents;
278
+ at timestamptz := (p->>'created_at')::timestamptz;
279
+ begin
280
+ select * into d from public.agreement_documents where id = (p->>'document_id')::uuid;
281
+ if not found then return jsonb_build_object('ok', false, 'reason', 'retired'); end if;
282
+ if p->>'request_id' is not null then
283
+ select * into r from public.agreement_requests where id = (p->>'request_id')::uuid for update;
284
+ if not found or r.document_id <> d.id then return jsonb_build_object('ok', false, 'reason', 'used'); end if;
285
+ if r.signature_id is not null then return jsonb_build_object('ok', false, 'reason', 'used'); end if;
286
+ if r.expires_at <= at then return jsonb_build_object('ok', false, 'reason', 'expired'); end if;
287
+ elsif d.retired_at is not null then
288
+ return jsonb_build_object('ok', false, 'reason', 'retired');
289
+ end if;
290
+ if (select count(*) from public.document_signatures where document_id = d.id and status = 'pending' and lower(email) = lower(p->>'email') and created_at > at - interval '1 hour') >= 5
291
+ or (select count(*) from public.document_signatures where document_id = d.id and status = 'pending' and created_at > at - interval '1 hour') >= 500 then
292
+ return jsonb_build_object('ok', false, 'reason', 'busy');
293
+ end if;
294
+ insert into public.document_signatures (id, document_id, request_id, token, subject_type, subject_id, name, email, created_at)
295
+ values ((p->>'id')::uuid, d.id, r.id, p->>'token', r.subject_type, r.subject_id, p->>'name', p->>'email', at);
296
+ insert into public.document_events (signature_id, kind, at, ip, user_agent, detail)
297
+ values ((p->>'id')::uuid, 'started', at, p->>'ip', p->>'ua', jsonb_build_object('version', d.version, 'sha256', d.document_sha256) || case when r.id is null then '{}'::jsonb else jsonb_build_object('request', r.id) end);
298
+ return jsonb_build_object('ok', true);
299
+ end;
300
+ $$;
301
+
302
+ -- A signing session: the signature (no token or code hash) and its document. Null for an unknown token.
303
+ create function public.documents_open(p_token text)
304
+ returns jsonb
305
+ language sql
306
+ stable
307
+ security invoker
308
+ set search_path = ''
309
+ as $$
310
+ select jsonb_build_object('signature', to_jsonb(s) - 'token' - 'code_hash', 'document', to_jsonb(d))
311
+ from public.document_signatures s join public.agreement_documents d on d.id = s.document_id
312
+ where s.token = p_token;
313
+ $$;
314
+
315
+ create function public.documents_event(p_signature uuid, p_kind text, p_at timestamptz, p_ip text, p_ua text, p_detail jsonb)
316
+ returns void
317
+ language sql
318
+ security invoker
319
+ set search_path = ''
320
+ as $$
321
+ insert into public.document_events (signature_id, kind, at, ip, user_agent, detail) values (p_signature, p_kind, p_at, p_ip, p_ua, p_detail);
322
+ $$;
323
+
324
+ create function public.documents_code_sent(p_signature uuid, p_code_hash text, p_at timestamptz, p_expires timestamptz, p_ip text, p_ua text)
325
+ returns jsonb
326
+ language plpgsql
327
+ security invoker
328
+ set search_path = ''
329
+ as $$
330
+ declare
331
+ s public.document_signatures;
332
+ begin
333
+ select * into s from public.document_signatures where id = p_signature for update;
334
+ if not found then return jsonb_build_object('ok', false, 'reason', 'not_found'); end if;
335
+ if s.code_sent_at is not null and s.code_sent_at > p_at - interval '60 seconds' then return jsonb_build_object('ok', false, 'reason', 'wait'); end if;
336
+ update public.document_signatures set code_hash = p_code_hash, code_sent_at = p_at, code_expires_at = p_expires, code_tries = 0 where id = p_signature;
337
+ insert into public.document_events (signature_id, kind, at, ip, user_agent) values (p_signature, 'code_sent', p_at, p_ip, p_ua);
338
+ return jsonb_build_object('ok', true);
339
+ end;
340
+ $$;
341
+
342
+ -- ok, wrong, expired, locked (5 wrong tries) or none (no code sent).
343
+ create function public.documents_code_try(p_signature uuid, p_code_hash text, p_at timestamptz, p_ip text, p_ua text)
344
+ returns text
345
+ language plpgsql
346
+ security invoker
347
+ set search_path = ''
348
+ as $$
349
+ declare
350
+ s public.document_signatures;
351
+ begin
352
+ select * into s from public.document_signatures where id = p_signature for update;
353
+ if not found or s.code_hash is null then return 'none'; end if;
354
+ if s.code_tries >= 5 then return 'locked'; end if;
355
+ if s.code_expires_at <= p_at then return 'expired'; end if;
356
+ if s.code_hash <> p_code_hash then
357
+ update public.document_signatures set code_tries = code_tries + 1 where id = p_signature;
358
+ insert into public.document_events (signature_id, kind, at, ip, user_agent) values (p_signature, 'code_failed', p_at, p_ip, p_ua);
359
+ return case when s.code_tries + 1 >= 5 then 'locked' else 'wrong' end;
360
+ end if;
361
+ update public.document_signatures set verified_at = p_at, code_hash = null, code_expires_at = null, code_tries = 0 where id = p_signature;
362
+ insert into public.document_events (signature_id, kind, at, ip, user_agent) values (p_signature, 'verified', p_at, p_ip, p_ua);
363
+ return 'ok';
364
+ end;
365
+ $$;
366
+
367
+ -- p: { id, at, name, for_child, child_name?, relationship?, answers, sensitive?, files, answers_sha256, method, typed_name, signature_key?, consent, ip?, ua?, valid_until?, require_verified, started_after }.
368
+ -- A request link's own valid_until applies when p has none.
369
+ -- { ok, reason? }: reason not_found, done, stale (started before started_after), not_verified, retired, used.
370
+ create function public.documents_sign(p jsonb)
371
+ returns jsonb
372
+ language plpgsql
373
+ security invoker
374
+ set search_path = ''
375
+ as $$
376
+ declare
377
+ s public.document_signatures;
378
+ d public.agreement_documents;
379
+ r public.agreement_requests;
380
+ at timestamptz := (p->>'at')::timestamptz;
381
+ begin
382
+ select * into s from public.document_signatures where id = (p->>'id')::uuid for update;
383
+ if not found then return jsonb_build_object('ok', false, 'reason', 'not_found'); end if;
384
+ if s.status <> 'pending' then return jsonb_build_object('ok', false, 'reason', 'done'); end if;
385
+ if s.created_at <= (p->>'started_after')::timestamptz then return jsonb_build_object('ok', false, 'reason', 'stale'); end if;
386
+ if (p->>'require_verified')::boolean and s.verified_at is null then return jsonb_build_object('ok', false, 'reason', 'not_verified'); end if;
387
+ select * into d from public.agreement_documents where id = s.document_id;
388
+ if s.request_id is not null then
389
+ select * into r from public.agreement_requests where id = s.request_id for update;
390
+ if not found or r.signature_id is not null then return jsonb_build_object('ok', false, 'reason', 'used'); end if;
391
+ update public.agreement_requests set signature_id = s.id where id = r.id;
392
+ elsif d.retired_at is not null then
393
+ return jsonb_build_object('ok', false, 'reason', 'retired');
394
+ end if;
395
+ update public.document_signatures
396
+ set status = 'signed', signed_at = at, name = p->>'name', for_child = (p->>'for_child')::boolean, child_name = p->>'child_name', relationship = p->>'relationship',
397
+ answers = p->'answers', sensitive = nullif(p->'sensitive', 'null'::jsonb), files = coalesce(p->'files', '[]'::jsonb), answers_sha256 = p->>'answers_sha256',
398
+ method = p->>'method', typed_name = p->>'typed_name', signature_key = p->>'signature_key', consent = p->>'consent',
399
+ sign_ip = p->>'ip', sign_user_agent = p->>'ua', valid_until = coalesce((p->>'valid_until')::timestamptz, r.valid_until)
400
+ where id = s.id;
401
+ insert into public.document_events (signature_id, kind, at, ip, user_agent, detail)
402
+ values (s.id, 'signed', at, p->>'ip', p->>'ua', jsonb_build_object('method', p->>'method', 'for_child', (p->>'for_child')::boolean, 'answers_sha256', p->>'answers_sha256'));
403
+ return jsonb_build_object('ok', true);
404
+ end;
405
+ $$;
406
+
407
+ create function public.documents_complete(p_id uuid, p_signed_key text, p_signed_sha256 text, p_at timestamptz)
408
+ returns boolean
409
+ language plpgsql
410
+ security invoker
411
+ set search_path = ''
412
+ as $$
413
+ begin
414
+ update public.document_signatures set signed_key = p_signed_key, signed_sha256 = p_signed_sha256 where id = p_id and status = 'signed' and signed_key is null;
415
+ if not found then return false; end if;
416
+ insert into public.document_events (signature_id, kind, at, detail) values (p_id, 'completed', p_at, jsonb_build_object('sha256', p_signed_sha256));
417
+ return true;
418
+ end;
419
+ $$;
420
+
421
+ create function public.documents_copies_sent(p_id uuid, p_at timestamptz, p_count integer)
422
+ returns void
423
+ language plpgsql
424
+ security invoker
425
+ set search_path = ''
426
+ as $$
427
+ begin
428
+ update public.document_signatures set copies_sent_at = p_at where id = p_id and signed_key is not null and copies_sent_at is null;
429
+ if found then insert into public.document_events (signature_id, kind, at, detail) values (p_id, 'copy_sent', p_at, jsonb_build_object('emails', p_count)); end if;
430
+ end;
431
+ $$;
432
+
433
+ -- The person's latest signature of any version of the slug that is valid now: for themselves (p_child null) or for that child,
434
+ -- and, for a document that lasts one event, on that subject. Null when there is none.
435
+ create function public.documents_valid(p_slug text, p_email text, p_child text, p_subject_type text, p_subject_id text, p_at timestamptz)
436
+ returns jsonb
437
+ language sql
438
+ stable
439
+ security invoker
440
+ set search_path = ''
441
+ as $$
442
+ select jsonb_build_object('id', s.id, 'version', d.version, 'signed_at', s.signed_at, 'valid_until', s.valid_until, 'name', s.name, 'child_name', s.child_name)
443
+ from public.document_signatures s join public.agreement_documents d on d.id = s.document_id
444
+ where d.slug = p_slug and s.status = 'signed' and lower(s.email) = lower(p_email)
445
+ and (case when p_child is null then not s.for_child else s.for_child and lower(s.child_name) = lower(p_child) end)
446
+ and (s.valid_until is null or s.valid_until > p_at)
447
+ and (d.validity_months is not null or (s.subject_type = p_subject_type and s.subject_id = p_subject_id))
448
+ order by s.signed_at desc limit 1;
449
+ $$;
450
+
451
+ -- An account's signatures (or one slug's), newest first: everything the owner's pages show, sensitive answers included.
452
+ create function public.documents_signatures(p_account text, p_slug text, p_limit integer)
453
+ returns jsonb
454
+ language sql
455
+ stable
456
+ security invoker
457
+ set search_path = ''
458
+ as $$
459
+ select coalesce(jsonb_agg(x.j order by x.signed_at desc), '[]'::jsonb) from (
460
+ select to_jsonb(s) - 'token' - 'code_hash' || jsonb_build_object('slug', d.slug, 'version', d.version, 'title', d.title) as j, s.signed_at
461
+ from public.document_signatures s join public.agreement_documents d on d.id = s.document_id
462
+ where d.account = p_account and (p_slug is null or d.slug = p_slug) and s.status = 'signed'
463
+ order by s.signed_at desc limit p_limit
464
+ ) x;
465
+ $$;
466
+
467
+ -- One signature with its document and audit trail, or null.
468
+ create function public.documents_signature(p_id uuid)
469
+ returns jsonb
470
+ language sql
471
+ stable
472
+ security invoker
473
+ set search_path = ''
474
+ as $$
475
+ select jsonb_build_object('signature', to_jsonb(s) - 'token' - 'code_hash', 'document', to_jsonb(d), 'events', coalesce((
476
+ select jsonb_agg(to_jsonb(e) order by e.at, e.id) from public.document_events e where e.signature_id = s.id), '[]'::jsonb))
477
+ from public.document_signatures s join public.agreement_documents d on d.id = s.document_id where s.id = p_id;
478
+ $$;
479
+
480
+ -- The cron's view: signatures whose signed copy wasn't made, or wasn't emailed, and those to remind before they lapse
481
+ -- (valid_until before p_renew_by, not reminded, with no newer valid signature by the same person for the same child).
482
+ create function public.documents_scan(p_at timestamptz, p_renew_by timestamptz, p_limit integer)
483
+ returns jsonb
484
+ language sql
485
+ stable
486
+ security invoker
487
+ set search_path = ''
488
+ as $$
489
+ select jsonb_build_object(
490
+ 'finish', coalesce((select jsonb_agg(id) from (select id from public.document_signatures where status = 'signed' and signed_key is null limit p_limit) a), '[]'::jsonb),
491
+ 'copies', coalesce((select jsonb_agg(id) from (select id from public.document_signatures where signed_key is not null and copies_sent_at is null limit p_limit) a), '[]'::jsonb),
492
+ 'renew', coalesce((select jsonb_agg(id) from (
493
+ select s.id from public.document_signatures s join public.agreement_documents d on d.id = s.document_id
494
+ where s.status = 'signed' and s.renewal_sent_at is null and d.validity_months is not null
495
+ and s.valid_until > p_at and s.valid_until <= p_renew_by
496
+ and not exists (select 1 from public.document_signatures n join public.agreement_documents nd on nd.id = n.document_id
497
+ where nd.slug = d.slug and n.status = 'signed' and lower(n.email) = lower(s.email) and n.for_child = s.for_child
498
+ and coalesce(lower(n.child_name), '') = coalesce(lower(s.child_name), '') and n.valid_until > s.valid_until)
499
+ limit p_limit) a), '[]'::jsonb)
500
+ );
501
+ $$;
502
+
503
+ create function public.documents_renewal_sent(p_id uuid, p_at timestamptz)
504
+ returns boolean
505
+ language plpgsql
506
+ security invoker
507
+ set search_path = ''
508
+ as $$
509
+ begin
510
+ update public.document_signatures set renewal_sent_at = p_at where id = p_id and renewal_sent_at is null;
511
+ if not found then return false; end if;
512
+ insert into public.document_events (signature_id, kind, at) values (p_id, 'renewal_sent', p_at);
513
+ return true;
514
+ end;
515
+ $$;
516
+
517
+ -- Past their retention: signatures to delete (signed before p_signed_before, or never finished and started before p_pending_before),
518
+ -- signatures whose sensitive answers and files to delete (no longer valid before p_sensitive_before), and retired versions
519
+ -- nothing has signed that were retired before p_pending_before. Each with the file keys to delete first.
520
+ create function public.documents_old(p_signed_before timestamptz, p_sensitive_before timestamptz, p_pending_before timestamptz, p_at timestamptz, p_limit integer)
521
+ returns jsonb
522
+ language sql
523
+ stable
524
+ security invoker
525
+ set search_path = ''
526
+ as $$
527
+ select jsonb_build_object(
528
+ 'delete', coalesce((select jsonb_agg(jsonb_build_object('id', s.id, 'keys',
529
+ to_jsonb(array_remove(array[s.signed_key, s.signature_key], null) || coalesce((select array_agg(f->>'key') from jsonb_array_elements(s.files) f), '{}'))))
530
+ from (select * from public.document_signatures
531
+ where (status = 'signed' and signed_at < p_signed_before) or (status = 'pending' and created_at < p_pending_before) limit p_limit) s), '[]'::jsonb),
532
+ 'scrub', coalesce((select jsonb_agg(jsonb_build_object('id', s.id, 'keys', coalesce((select jsonb_agg(f->'key') from jsonb_array_elements(s.files) f), '[]'::jsonb)))
533
+ from (select * from public.document_signatures
534
+ where status = 'signed' and sensitive_deleted_at is null and (sensitive is not null or jsonb_array_length(files) > 0)
535
+ and coalesce(valid_until, signed_at) < p_sensitive_before and coalesce(valid_until, signed_at) < p_at limit p_limit) s), '[]'::jsonb),
536
+ 'documents', coalesce((select jsonb_agg(jsonb_build_object('id', d.id, 'keys', jsonb_build_array(d.document_key)))
537
+ from (select * from public.agreement_documents d where d.retired_at < p_pending_before
538
+ and not exists (select 1 from public.document_signatures s where s.document_id = d.id)
539
+ and not exists (select 1 from public.agreement_requests r where r.document_id = d.id and r.expires_at > p_at) limit p_limit) d), '[]'::jsonb)
540
+ );
541
+ $$;
542
+
543
+ -- Deletes the sensitive answers and the files' records of these signatures (their files are deleted first).
544
+ create function public.documents_scrub(p_ids uuid[], p_at timestamptz)
545
+ returns integer
546
+ language plpgsql
547
+ security invoker
548
+ set search_path = ''
549
+ as $$
550
+ declare
551
+ n integer;
552
+ begin
553
+ with u as (
554
+ update public.document_signatures set sensitive = null, files = '[]'::jsonb, sensitive_deleted_at = p_at
555
+ where id = any (p_ids) and sensitive_deleted_at is null returning id
556
+ ), e as (
557
+ insert into public.document_events (signature_id, kind, at) select id, 'sensitive_deleted', p_at from u returning 1
558
+ )
559
+ select count(*) into n from e;
560
+ return n;
561
+ end;
562
+ $$;
563
+
564
+ -- Deletes signatures and retired, unsigned document versions (their files are deleted first), and request links that expired before p_requests_before.
565
+ create function public.documents_delete(p_signatures uuid[], p_documents uuid[], p_requests_before timestamptz)
566
+ returns integer
567
+ language plpgsql
568
+ security invoker
569
+ set search_path = ''
570
+ as $$
571
+ declare
572
+ n integer;
573
+ m integer;
574
+ begin
575
+ delete from public.document_signatures where id = any (p_signatures);
576
+ get diagnostics n = row_count;
577
+ delete from public.agreement_requests where expires_at < p_requests_before and signature_id is null;
578
+ delete from public.agreement_documents d where d.id = any (p_documents) and d.retired_at is not null
579
+ and not exists (select 1 from public.document_signatures s where s.document_id = d.id);
580
+ get diagnostics m = row_count;
581
+ return n + m;
582
+ end;
583
+ $$;
584
+
585
+ ${grants}
586
+ grant select, insert, update, delete on public.agreement_documents, public.agreement_requests, public.document_signatures, public.document_events to service_role;
587
+ `,
588
+ down: `${drops}
589
+ drop table public.document_events;
590
+ drop table public.document_signatures;
591
+ drop table public.agreement_requests;
592
+ drop table public.agreement_documents;
593
+ `,
594
+ };