@mccaskie-labs/workbench-quotes 0.0.0-stage → 0.2.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/CHANGELOG.md +16 -0
- package/README.md +92 -2
- package/dist/cli.d.ts +12 -0
- package/dist/cli.js +188 -0
- package/dist/document.d.ts +83 -0
- package/dist/document.js +67 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +10 -0
- package/dist/handover.d.ts +25 -0
- package/dist/handover.js +24 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +20 -0
- package/dist/kinds.d.ts +114 -0
- package/dist/kinds.js +231 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +335 -0
- package/dist/money.d.ts +21 -0
- package/dist/money.js +68 -0
- package/dist/page.d.ts +31 -0
- package/dist/page.js +87 -0
- package/dist/quotes.d.ts +121 -0
- package/dist/quotes.js +313 -0
- package/dist/starters.d.ts +3 -0
- package/dist/starters.js +23 -0
- package/dist/styles.d.ts +34 -0
- package/dist/styles.js +83 -0
- package/dist/types.d.ts +53 -0
- package/dist/types.js +4 -0
- package/dist/words.d.ts +9 -0
- package/dist/words.js +189 -0
- package/package.json +52 -4
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// The app's own quotes tables, copied into the project's supabase/migrations
|
|
2
|
+
// as one file and its down file (`npx workbench-quotes migration`).
|
|
3
|
+
//
|
|
4
|
+
// Only the service role reaches them: the app's own pages create, send and
|
|
5
|
+
// list quotes server side behind its sign-in, checking the account
|
|
6
|
+
// themselves, and the accept page is served by the app's Worker with the
|
|
7
|
+
// service client. So the tables have RLS on with no policies and the
|
|
8
|
+
// functions are granted to service_role only.
|
|
9
|
+
//
|
|
10
|
+
// - A quote's number is one sequence per account (Q-0001), taken under a
|
|
11
|
+
// row lock on quote_counters, so two quotes made at once never share one.
|
|
12
|
+
// - A quote is frozen once sent: its lines, totals and terms can't change.
|
|
13
|
+
// A change is a new quote that `replaces` it; sending that withdraws the
|
|
14
|
+
// old one in the same transaction.
|
|
15
|
+
// - The link carries a random token; only its SHA-256 is stored. Sending
|
|
16
|
+
// again makes a new token, and the old link stops.
|
|
17
|
+
// - Accepting and declining are one locked update each: a quote is accepted
|
|
18
|
+
// once, never after its valid-until time, and never once withdrawn.
|
|
19
|
+
// - The customer's typed name is kept with an accepted quote (it's the
|
|
20
|
+
// record of acceptance). A decline keeps a reason picked from a list, never
|
|
21
|
+
// typed words. No IP address or browser is stored.
|
|
22
|
+
// - The daily clean-up deletes a quote that wasn't accepted (declined,
|
|
23
|
+
// withdrawn, expired, or a draft) retention_days after it ended. Accepted
|
|
24
|
+
// quotes stay until the app deletes them: they back an invoice.
|
|
25
|
+
//
|
|
26
|
+
// It creates functions, so Control asks for approval to apply it even on
|
|
27
|
+
// staging. The down file drops everything the up file made.
|
|
28
|
+
export const quotesMigration = {
|
|
29
|
+
up: `create table public.quote_counters (
|
|
30
|
+
account text primary key check (char_length(account) between 1 and 200),
|
|
31
|
+
last integer not null default 0 check (last >= 0)
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
comment on table public.quote_counters is 'The last quote number used per account (workbench-quotes). Service role only.';
|
|
35
|
+
|
|
36
|
+
create table public.quotes (
|
|
37
|
+
id uuid primary key default gen_random_uuid(),
|
|
38
|
+
account text not null check (char_length(account) between 1 and 200),
|
|
39
|
+
kind text not null check (kind ~ '^[a-z][a-z0-9-]{0,39}$'),
|
|
40
|
+
number text not null check (char_length(number) between 1 and 40),
|
|
41
|
+
document text not null check (document in ('quote', 'estimate')),
|
|
42
|
+
status text not null default 'draft' check (status in ('draft', 'sent', 'accepted', 'declined', 'withdrawn')),
|
|
43
|
+
customer_type text check (char_length(customer_type) between 1 and 60),
|
|
44
|
+
customer_id text check (char_length(customer_id) between 1 and 200),
|
|
45
|
+
customer_name text check (char_length(customer_name) between 1 and 120),
|
|
46
|
+
customer_email text check (char_length(customer_email) between 3 and 254),
|
|
47
|
+
currency text not null check (currency ~ '^[A-Z]{3}$'),
|
|
48
|
+
lines jsonb not null check (jsonb_typeof(lines) = 'array' and jsonb_array_length(lines) between 1 and 200 and octet_length(lines::text) <= 60000),
|
|
49
|
+
tax jsonb check (tax is null or (jsonb_typeof(tax) = 'object' and octet_length(tax::text) <= 200)),
|
|
50
|
+
subtotal_cents bigint not null check (subtotal_cents between 0 and 10000000000),
|
|
51
|
+
tax_cents bigint not null check (tax_cents between 0 and 10000000000),
|
|
52
|
+
total_cents bigint not null check (total_cents between 0 and 20000000000),
|
|
53
|
+
deposit_cents bigint not null check (deposit_cents between 0 and total_cents),
|
|
54
|
+
note text check (char_length(note) <= 2000),
|
|
55
|
+
terms text not null default '' check (char_length(terms) <= 4000),
|
|
56
|
+
valid_days smallint not null check (valid_days between 1 and 365),
|
|
57
|
+
name_required boolean not null default true,
|
|
58
|
+
retention_days smallint not null check (retention_days between 30 and 3650),
|
|
59
|
+
replaces uuid references public.quotes (id) on delete set null,
|
|
60
|
+
token_hash text unique check (token_hash ~ '^[0-9a-f]{64}$'),
|
|
61
|
+
created_at timestamptz not null default now(),
|
|
62
|
+
updated_at timestamptz not null default now(),
|
|
63
|
+
sent_at timestamptz,
|
|
64
|
+
valid_until timestamptz,
|
|
65
|
+
viewed_at timestamptz,
|
|
66
|
+
views integer not null default 0 check (views >= 0),
|
|
67
|
+
accepted_at timestamptz,
|
|
68
|
+
accepted_name text check (char_length(accepted_name) between 1 and 120),
|
|
69
|
+
declined_at timestamptz,
|
|
70
|
+
decline_reason text check (decline_reason in ('price', 'timing', 'elsewhere', 'not_needed', 'other')),
|
|
71
|
+
withdrawn_at timestamptz,
|
|
72
|
+
unique (account, number),
|
|
73
|
+
check ((customer_type is null) = (customer_id is null)),
|
|
74
|
+
check (status in ('draft', 'withdrawn') or (sent_at is not null and valid_until is not null)),
|
|
75
|
+
check ((status = 'accepted') = (accepted_at is not null)),
|
|
76
|
+
check ((status = 'declined') = (declined_at is not null)),
|
|
77
|
+
check ((status = 'withdrawn') = (withdrawn_at is not null))
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
comment on table public.quotes is 'Quotes and estimates the business sent (workbench-quotes): lines, totals, the customer''s name and email, and, once accepted, the name they typed. A declined, withdrawn or expired quote is deleted retention_days after it ended; an accepted one stays. No IP address. Service role only.';
|
|
81
|
+
|
|
82
|
+
create index quotes_account on public.quotes (account, created_at desc);
|
|
83
|
+
create index quotes_customer on public.quotes (customer_type, customer_id) where customer_id is not null;
|
|
84
|
+
create index quotes_cleanup on public.quotes (updated_at) where status <> 'accepted';
|
|
85
|
+
|
|
86
|
+
alter table public.quote_counters enable row level security;
|
|
87
|
+
alter table public.quotes enable row level security;
|
|
88
|
+
revoke all on public.quote_counters, public.quotes from anon, authenticated;
|
|
89
|
+
|
|
90
|
+
-- A quote as the package reads it. expired is worked out here.
|
|
91
|
+
create function public.quotes_row(q public.quotes, p_now timestamptz)
|
|
92
|
+
returns jsonb
|
|
93
|
+
language sql
|
|
94
|
+
stable
|
|
95
|
+
security invoker
|
|
96
|
+
set search_path = ''
|
|
97
|
+
as $$
|
|
98
|
+
select jsonb_build_object('id', q.id, 'account', q.account, 'kind', q.kind, 'number', q.number, 'document', q.document,
|
|
99
|
+
'status', case when q.status = 'sent' and q.valid_until < p_now then 'expired' else q.status end,
|
|
100
|
+
'customer', jsonb_build_object('subject', case when q.customer_id is null then null else jsonb_build_object('type', q.customer_type, 'id', q.customer_id) end,
|
|
101
|
+
'name', q.customer_name, 'email', q.customer_email),
|
|
102
|
+
'currency', q.currency, 'lines', q.lines, 'tax', q.tax, 'subtotal_cents', q.subtotal_cents, 'tax_cents', q.tax_cents, 'total_cents', q.total_cents,
|
|
103
|
+
'deposit_cents', q.deposit_cents, 'note', q.note, 'terms', q.terms, 'valid_days', q.valid_days, 'name_required', q.name_required, 'replaces', q.replaces,
|
|
104
|
+
'created_at', q.created_at, 'sent_at', q.sent_at, 'valid_until', q.valid_until, 'viewed_at', q.viewed_at, 'views', q.views,
|
|
105
|
+
'accepted_at', q.accepted_at, 'accepted_name', q.accepted_name, 'declined_at', q.declined_at, 'decline_reason', q.decline_reason, 'withdrawn_at', q.withdrawn_at);
|
|
106
|
+
$$;
|
|
107
|
+
|
|
108
|
+
-- A new draft, with the account's next number.
|
|
109
|
+
create function public.quotes_create(p_quote jsonb, p_prefix text, p_now timestamptz)
|
|
110
|
+
returns jsonb
|
|
111
|
+
language plpgsql
|
|
112
|
+
security invoker
|
|
113
|
+
set search_path = ''
|
|
114
|
+
as $$
|
|
115
|
+
declare
|
|
116
|
+
n integer;
|
|
117
|
+
q public.quotes;
|
|
118
|
+
begin
|
|
119
|
+
if p_prefix !~ '^[A-Za-z0-9-]{0,8}$' then
|
|
120
|
+
raise exception 'bad prefix' using errcode = '22023';
|
|
121
|
+
end if;
|
|
122
|
+
insert into public.quote_counters as c (account, last) values (p_quote->>'account', 1)
|
|
123
|
+
on conflict (account) do update set last = c.last + 1
|
|
124
|
+
returning last into n;
|
|
125
|
+
insert into public.quotes (account, kind, number, document, customer_type, customer_id, customer_name, customer_email, currency, lines, tax,
|
|
126
|
+
subtotal_cents, tax_cents, total_cents, deposit_cents, note, terms, valid_days, name_required, retention_days, replaces, created_at, updated_at)
|
|
127
|
+
values (p_quote->>'account', p_quote->>'kind', p_prefix || lpad(n::text, 4, '0'), p_quote->>'document',
|
|
128
|
+
p_quote->'customer'->'subject'->>'type', p_quote->'customer'->'subject'->>'id', p_quote->'customer'->>'name', p_quote->'customer'->>'email',
|
|
129
|
+
p_quote->>'currency', p_quote->'lines', case when jsonb_typeof(p_quote->'tax') = 'object' then p_quote->'tax' end,
|
|
130
|
+
(p_quote->>'subtotal_cents')::bigint, (p_quote->>'tax_cents')::bigint, (p_quote->>'total_cents')::bigint, (p_quote->>'deposit_cents')::bigint,
|
|
131
|
+
p_quote->>'note', coalesce(p_quote->>'terms', ''), (p_quote->>'valid_days')::smallint, (p_quote->>'name_required')::boolean,
|
|
132
|
+
(p_quote->>'retention_days')::smallint, (p_quote->>'replaces')::uuid, p_now, p_now)
|
|
133
|
+
returning * into q;
|
|
134
|
+
return public.quotes_row(q, p_now);
|
|
135
|
+
end;
|
|
136
|
+
$$;
|
|
137
|
+
|
|
138
|
+
-- Changes a draft's lines, totals, note or customer. Only a draft.
|
|
139
|
+
create function public.quotes_update(p_id uuid, p_quote jsonb, p_now timestamptz)
|
|
140
|
+
returns jsonb
|
|
141
|
+
language plpgsql
|
|
142
|
+
security invoker
|
|
143
|
+
set search_path = ''
|
|
144
|
+
as $$
|
|
145
|
+
declare
|
|
146
|
+
q public.quotes;
|
|
147
|
+
begin
|
|
148
|
+
select * into q from public.quotes where id = p_id for update;
|
|
149
|
+
if not found then return jsonb_build_object('error', 'unknown_quote'); end if;
|
|
150
|
+
if q.status <> 'draft' then return jsonb_build_object('error', 'wrong_status'); end if;
|
|
151
|
+
update public.quotes set
|
|
152
|
+
customer_type = p_quote->'customer'->'subject'->>'type', customer_id = p_quote->'customer'->'subject'->>'id',
|
|
153
|
+
customer_name = p_quote->'customer'->>'name', customer_email = p_quote->'customer'->>'email',
|
|
154
|
+
lines = p_quote->'lines', subtotal_cents = (p_quote->>'subtotal_cents')::bigint, tax_cents = (p_quote->>'tax_cents')::bigint,
|
|
155
|
+
total_cents = (p_quote->>'total_cents')::bigint, deposit_cents = (p_quote->>'deposit_cents')::bigint, note = p_quote->>'note', updated_at = p_now
|
|
156
|
+
where id = p_id
|
|
157
|
+
returning * into q;
|
|
158
|
+
return public.quotes_row(q, p_now);
|
|
159
|
+
end;
|
|
160
|
+
$$;
|
|
161
|
+
|
|
162
|
+
-- Sends a draft, or sends a sent quote again with a new link. Withdraws the quote it replaces.
|
|
163
|
+
create function public.quotes_send(p_id uuid, p_token_hash text, p_now timestamptz)
|
|
164
|
+
returns jsonb
|
|
165
|
+
language plpgsql
|
|
166
|
+
security invoker
|
|
167
|
+
set search_path = ''
|
|
168
|
+
as $$
|
|
169
|
+
declare
|
|
170
|
+
q public.quotes;
|
|
171
|
+
begin
|
|
172
|
+
select * into q from public.quotes where id = p_id for update;
|
|
173
|
+
if not found then return jsonb_build_object('error', 'unknown_quote'); end if;
|
|
174
|
+
if q.status not in ('draft', 'sent') then return jsonb_build_object('error', 'wrong_status'); end if;
|
|
175
|
+
if q.status = 'sent' and q.valid_until < p_now then return jsonb_build_object('error', 'expired'); end if;
|
|
176
|
+
update public.quotes set status = 'sent', token_hash = p_token_hash, sent_at = coalesce(sent_at, p_now),
|
|
177
|
+
valid_until = coalesce(valid_until, p_now + make_interval(days => valid_days)), updated_at = p_now
|
|
178
|
+
where id = p_id
|
|
179
|
+
returning * into q;
|
|
180
|
+
if q.replaces is not null then
|
|
181
|
+
update public.quotes set status = 'withdrawn', withdrawn_at = p_now, updated_at = p_now
|
|
182
|
+
where id = q.replaces and status in ('draft', 'sent');
|
|
183
|
+
end if;
|
|
184
|
+
return public.quotes_row(q, p_now);
|
|
185
|
+
end;
|
|
186
|
+
$$;
|
|
187
|
+
|
|
188
|
+
-- The quote behind a link, counting a view of a sent one.
|
|
189
|
+
create function public.quotes_open(p_token_hash text, p_count boolean, p_now timestamptz)
|
|
190
|
+
returns jsonb
|
|
191
|
+
language plpgsql
|
|
192
|
+
security invoker
|
|
193
|
+
set search_path = ''
|
|
194
|
+
as $$
|
|
195
|
+
declare
|
|
196
|
+
q public.quotes;
|
|
197
|
+
begin
|
|
198
|
+
if p_count then
|
|
199
|
+
update public.quotes set views = views + 1, viewed_at = coalesce(viewed_at, p_now)
|
|
200
|
+
where token_hash = p_token_hash and status = 'sent'
|
|
201
|
+
returning * into q;
|
|
202
|
+
if found then return public.quotes_row(q, p_now); end if;
|
|
203
|
+
end if;
|
|
204
|
+
select * into q from public.quotes where token_hash = p_token_hash;
|
|
205
|
+
if not found then return null; end if;
|
|
206
|
+
return public.quotes_row(q, p_now);
|
|
207
|
+
end;
|
|
208
|
+
$$;
|
|
209
|
+
|
|
210
|
+
-- The customer accepts (p_name, when the quote asks for one) or declines (p_reason). Once only.
|
|
211
|
+
create function public.quotes_answer(p_token_hash text, p_answer text, p_name text, p_reason text, p_now timestamptz)
|
|
212
|
+
returns jsonb
|
|
213
|
+
language plpgsql
|
|
214
|
+
security invoker
|
|
215
|
+
set search_path = ''
|
|
216
|
+
as $$
|
|
217
|
+
declare
|
|
218
|
+
q public.quotes;
|
|
219
|
+
begin
|
|
220
|
+
if p_answer not in ('accept', 'decline') then raise exception 'bad answer' using errcode = '22023'; end if;
|
|
221
|
+
select * into q from public.quotes where token_hash = p_token_hash for update;
|
|
222
|
+
if not found then return jsonb_build_object('error', 'unknown_quote'); end if;
|
|
223
|
+
if q.status = 'accepted' and p_answer = 'accept' then return jsonb_build_object('quote', public.quotes_row(q, p_now), 'changed', false); end if;
|
|
224
|
+
if q.status = 'declined' and p_answer = 'decline' then return jsonb_build_object('quote', public.quotes_row(q, p_now), 'changed', false); end if;
|
|
225
|
+
if q.status <> 'sent' then return jsonb_build_object('error', 'wrong_status', 'quote', public.quotes_row(q, p_now)); end if;
|
|
226
|
+
if q.valid_until < p_now then return jsonb_build_object('error', 'expired', 'quote', public.quotes_row(q, p_now)); end if;
|
|
227
|
+
if p_answer = 'accept' then
|
|
228
|
+
if q.name_required and p_name is null then raise exception 'name required' using errcode = '22023'; end if;
|
|
229
|
+
update public.quotes set status = 'accepted', accepted_at = p_now, accepted_name = p_name, updated_at = p_now where id = q.id returning * into q;
|
|
230
|
+
else
|
|
231
|
+
update public.quotes set status = 'declined', declined_at = p_now, decline_reason = p_reason, updated_at = p_now where id = q.id returning * into q;
|
|
232
|
+
end if;
|
|
233
|
+
return jsonb_build_object('quote', public.quotes_row(q, p_now), 'changed', true);
|
|
234
|
+
end;
|
|
235
|
+
$$;
|
|
236
|
+
|
|
237
|
+
-- The business takes back a draft or a sent quote; its link then says it's no longer current.
|
|
238
|
+
create function public.quotes_withdraw(p_id uuid, p_now timestamptz)
|
|
239
|
+
returns jsonb
|
|
240
|
+
language plpgsql
|
|
241
|
+
security invoker
|
|
242
|
+
set search_path = ''
|
|
243
|
+
as $$
|
|
244
|
+
declare
|
|
245
|
+
q public.quotes;
|
|
246
|
+
begin
|
|
247
|
+
update public.quotes set status = 'withdrawn', withdrawn_at = p_now, updated_at = p_now
|
|
248
|
+
where id = p_id and status in ('draft', 'sent')
|
|
249
|
+
returning * into q;
|
|
250
|
+
if found then return public.quotes_row(q, p_now); end if;
|
|
251
|
+
select * into q from public.quotes where id = p_id;
|
|
252
|
+
if not found then return jsonb_build_object('error', 'unknown_quote'); end if;
|
|
253
|
+
return jsonb_build_object('error', 'wrong_status');
|
|
254
|
+
end;
|
|
255
|
+
$$;
|
|
256
|
+
|
|
257
|
+
create function public.quotes_get(p_id uuid, p_now timestamptz)
|
|
258
|
+
returns jsonb
|
|
259
|
+
language sql
|
|
260
|
+
stable
|
|
261
|
+
security invoker
|
|
262
|
+
set search_path = ''
|
|
263
|
+
as $$
|
|
264
|
+
select public.quotes_row(q, p_now) from public.quotes q where q.id = p_id;
|
|
265
|
+
$$;
|
|
266
|
+
|
|
267
|
+
-- An account's quotes, newest first; p_status filters (expired is a sent quote past its date).
|
|
268
|
+
create function public.quotes_list(p_account text, p_status text, p_limit integer, p_now timestamptz)
|
|
269
|
+
returns jsonb
|
|
270
|
+
language sql
|
|
271
|
+
stable
|
|
272
|
+
security invoker
|
|
273
|
+
set search_path = ''
|
|
274
|
+
as $$
|
|
275
|
+
select coalesce(jsonb_agg(r.j order by r.created_at desc), '[]'::jsonb)
|
|
276
|
+
from (
|
|
277
|
+
select public.quotes_row(q, p_now) as j, q.created_at
|
|
278
|
+
from public.quotes q
|
|
279
|
+
where q.account = p_account
|
|
280
|
+
and (p_status is null
|
|
281
|
+
or (p_status = 'expired' and q.status = 'sent' and q.valid_until < p_now)
|
|
282
|
+
or (p_status = 'sent' and q.status = 'sent' and q.valid_until >= p_now)
|
|
283
|
+
or (p_status not in ('sent', 'expired') and q.status = p_status))
|
|
284
|
+
order by q.created_at desc
|
|
285
|
+
limit least(greatest(p_limit, 1), 500)
|
|
286
|
+
) r;
|
|
287
|
+
$$;
|
|
288
|
+
|
|
289
|
+
-- The daily clean-up: quotes that weren't accepted, retention_days after they ended.
|
|
290
|
+
create function public.quotes_cleanup(p_now timestamptz)
|
|
291
|
+
returns integer
|
|
292
|
+
language plpgsql
|
|
293
|
+
security invoker
|
|
294
|
+
set search_path = ''
|
|
295
|
+
as $$
|
|
296
|
+
declare
|
|
297
|
+
n integer;
|
|
298
|
+
begin
|
|
299
|
+
delete from public.quotes q
|
|
300
|
+
where q.status <> 'accepted'
|
|
301
|
+
and case q.status
|
|
302
|
+
when 'sent' then q.valid_until
|
|
303
|
+
when 'draft' then q.updated_at
|
|
304
|
+
when 'declined' then q.declined_at
|
|
305
|
+
else q.withdrawn_at
|
|
306
|
+
end + make_interval(days => q.retention_days) < p_now;
|
|
307
|
+
get diagnostics n = row_count;
|
|
308
|
+
return n;
|
|
309
|
+
end;
|
|
310
|
+
$$;
|
|
311
|
+
|
|
312
|
+
revoke all on function public.quotes_row(public.quotes, timestamptz), public.quotes_create(jsonb, text, timestamptz), public.quotes_update(uuid, jsonb, timestamptz),
|
|
313
|
+
public.quotes_send(uuid, text, timestamptz), public.quotes_open(text, boolean, timestamptz), public.quotes_answer(text, text, text, text, timestamptz),
|
|
314
|
+
public.quotes_withdraw(uuid, timestamptz), public.quotes_get(uuid, timestamptz), public.quotes_list(text, text, integer, timestamptz),
|
|
315
|
+
public.quotes_cleanup(timestamptz) from public, anon, authenticated;
|
|
316
|
+
grant all on table public.quotes, public.quote_counters to service_role;
|
|
317
|
+
grant execute on function public.quotes_row(public.quotes, timestamptz), public.quotes_create(jsonb, text, timestamptz), public.quotes_update(uuid, jsonb, timestamptz),
|
|
318
|
+
public.quotes_send(uuid, text, timestamptz), public.quotes_open(text, boolean, timestamptz), public.quotes_answer(text, text, text, text, timestamptz),
|
|
319
|
+
public.quotes_withdraw(uuid, timestamptz), public.quotes_get(uuid, timestamptz), public.quotes_list(text, text, integer, timestamptz),
|
|
320
|
+
public.quotes_cleanup(timestamptz) to service_role;
|
|
321
|
+
`,
|
|
322
|
+
down: `drop function if exists public.quotes_cleanup(timestamptz);
|
|
323
|
+
drop function if exists public.quotes_list(text, text, integer, timestamptz);
|
|
324
|
+
drop function if exists public.quotes_get(uuid, timestamptz);
|
|
325
|
+
drop function if exists public.quotes_withdraw(uuid, timestamptz);
|
|
326
|
+
drop function if exists public.quotes_answer(text, text, text, text, timestamptz);
|
|
327
|
+
drop function if exists public.quotes_open(text, boolean, timestamptz);
|
|
328
|
+
drop function if exists public.quotes_send(uuid, text, timestamptz);
|
|
329
|
+
drop function if exists public.quotes_update(uuid, jsonb, timestamptz);
|
|
330
|
+
drop function if exists public.quotes_create(jsonb, text, timestamptz);
|
|
331
|
+
drop function if exists public.quotes_row(public.quotes, timestamptz);
|
|
332
|
+
drop table if exists public.quotes;
|
|
333
|
+
drop table if exists public.quote_counters;
|
|
334
|
+
`,
|
|
335
|
+
};
|
package/dist/money.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type CountryPack } from "@mccaskie-labs/workbench-country";
|
|
2
|
+
/** The largest amount in one line, subtotal or total: 100,000,000.00. */
|
|
3
|
+
export declare const MAX_CENTS = 10000000000;
|
|
4
|
+
/** The largest quantity on one line. */
|
|
5
|
+
export declare const MAX_QUANTITY = 100000;
|
|
6
|
+
/** "95", "95.5" or "95.50" as cents (9550). Throws bad_input naming `what`. */
|
|
7
|
+
export declare function toCents(price: unknown, what?: string): number;
|
|
8
|
+
/** Cents as plain decimal text with two places: 9550 → "95.50". For files and inputs, not for people. */
|
|
9
|
+
export declare function centsText(cents: number): string;
|
|
10
|
+
/** A quantity: a whole number or up to three decimal places, more than 0 and at most MAX_QUANTITY. */
|
|
11
|
+
export declare function checkQuantity(q: unknown, what?: string): number;
|
|
12
|
+
/** a × b ÷ c rounded half away from zero, exactly (BigInt), for cents. */
|
|
13
|
+
export declare function mulDiv(a: number, b: number, c: number): number;
|
|
14
|
+
/** One line's amount: quantity × unit price, rounded to whole cents. */
|
|
15
|
+
export declare function lineCents(quantity: number, unitCents: number): number;
|
|
16
|
+
/** The pack quotes are shown with by default: Australian. */
|
|
17
|
+
export declare const DEFAULT_COUNTRY = "AU";
|
|
18
|
+
/** The country pack for an app, Australian when none is given. */
|
|
19
|
+
export declare function packFor(country?: string | CountryPack): CountryPack;
|
|
20
|
+
/** Cents for people: "A$1,234.50", always two decimal places. A currency the pack doesn't use is shown by its code ("USD 12.00"). */
|
|
21
|
+
export declare function money(cents: number, currency: string, pack: CountryPack): string;
|
package/dist/money.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Money as whole cents, never floating point: prices are written as decimal
|
|
2
|
+
// text ("95.00"), quantities as up to three decimal places, and every
|
|
3
|
+
// rounding is half away from zero on whole cents. Shown to two decimal
|
|
4
|
+
// places always (Robert's rule), with the country pack's symbol.
|
|
5
|
+
import { countryPackFor, formatMoney } from "@mccaskie-labs/workbench-country";
|
|
6
|
+
import { QuotesError } from "./errors.js";
|
|
7
|
+
/** The largest amount in one line, subtotal or total: 100,000,000.00. */
|
|
8
|
+
export const MAX_CENTS = 10_000_000_000;
|
|
9
|
+
/** The largest quantity on one line. */
|
|
10
|
+
export const MAX_QUANTITY = 100_000;
|
|
11
|
+
const PRICE = /^-?\d{1,9}(\.\d{1,2})?$/;
|
|
12
|
+
/** "95", "95.5" or "95.50" as cents (9550). Throws bad_input naming `what`. */
|
|
13
|
+
export function toCents(price, what = "price") {
|
|
14
|
+
const text = typeof price === "number" && Number.isFinite(price) ? price.toFixed(2) : price;
|
|
15
|
+
if (typeof text !== "string" || !PRICE.test(text.trim()))
|
|
16
|
+
throw new QuotesError("bad_input", `${what} must be an amount such as 95.00`);
|
|
17
|
+
const t = text.trim();
|
|
18
|
+
const negative = t.startsWith("-");
|
|
19
|
+
const [whole, frac = ""] = t.replace("-", "").split(".");
|
|
20
|
+
const cents = Number(whole) * 100 + Number(frac.padEnd(2, "0"));
|
|
21
|
+
return negative && cents !== 0 ? -cents : cents;
|
|
22
|
+
}
|
|
23
|
+
/** Cents as plain decimal text with two places: 9550 → "95.50". For files and inputs, not for people. */
|
|
24
|
+
export function centsText(cents) {
|
|
25
|
+
const sign = cents < 0 ? "-" : "";
|
|
26
|
+
const abs = Math.abs(cents);
|
|
27
|
+
return `${sign}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
|
|
28
|
+
}
|
|
29
|
+
/** A quantity: a whole number or up to three decimal places, more than 0 and at most MAX_QUANTITY. */
|
|
30
|
+
export function checkQuantity(q, what = "quantity") {
|
|
31
|
+
const n = typeof q === "string" && /^\d{1,6}(\.\d{1,3})?$/.test(q.trim()) ? Number(q.trim()) : q;
|
|
32
|
+
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0 || n > MAX_QUANTITY || Math.round(n * 1000) !== Number((n * 1000).toFixed(6))) {
|
|
33
|
+
throw new QuotesError("bad_input", `${what} must be more than 0 and at most ${MAX_QUANTITY}, with at most three decimal places`);
|
|
34
|
+
}
|
|
35
|
+
return Math.round(n * 1000) / 1000;
|
|
36
|
+
}
|
|
37
|
+
/** a × b ÷ c rounded half away from zero, exactly (BigInt), for cents. */
|
|
38
|
+
export function mulDiv(a, b, c) {
|
|
39
|
+
const n = BigInt(a) * BigInt(b);
|
|
40
|
+
const d = BigInt(c);
|
|
41
|
+
const neg = n < 0n !== d < 0n;
|
|
42
|
+
const an = n < 0n ? -n : n;
|
|
43
|
+
const ad = d < 0n ? -d : d;
|
|
44
|
+
const q = (an * 2n + ad) / (ad * 2n);
|
|
45
|
+
return Number(neg ? -q : q);
|
|
46
|
+
}
|
|
47
|
+
/** One line's amount: quantity × unit price, rounded to whole cents. */
|
|
48
|
+
export function lineCents(quantity, unitCents) {
|
|
49
|
+
return mulDiv(Math.round(quantity * 1000), unitCents, 1000);
|
|
50
|
+
}
|
|
51
|
+
/** The pack quotes are shown with by default: Australian. */
|
|
52
|
+
export const DEFAULT_COUNTRY = "AU";
|
|
53
|
+
/** The country pack for an app, Australian when none is given. */
|
|
54
|
+
export function packFor(country) {
|
|
55
|
+
if (typeof country === "object")
|
|
56
|
+
return country;
|
|
57
|
+
const pack = countryPackFor(country ?? DEFAULT_COUNTRY);
|
|
58
|
+
if (!pack)
|
|
59
|
+
throw new QuotesError("bad_input", `no country pack for ${country}`);
|
|
60
|
+
return pack;
|
|
61
|
+
}
|
|
62
|
+
/** Cents for people: "A$1,234.50", always two decimal places. A currency the pack doesn't use is shown by its code ("USD 12.00"). */
|
|
63
|
+
export function money(cents, currency, pack) {
|
|
64
|
+
const amount = cents / 100;
|
|
65
|
+
if (currency === pack.currency.code)
|
|
66
|
+
return formatMoney(amount, pack, { decimals: 2 });
|
|
67
|
+
return formatMoney(amount, `${currency} `, { decimals: 2 });
|
|
68
|
+
}
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type PresentOptions } from "./document.ts";
|
|
2
|
+
import { type Quote } from "./types.ts";
|
|
3
|
+
import { type QuoteLang, type QuoteStrings } from "./words.ts";
|
|
4
|
+
/** The project's generated Workbench styles, then its own. */
|
|
5
|
+
export declare const DEFAULT_STYLESHEETS: readonly string[];
|
|
6
|
+
export interface QuotePageOptions extends PresentOptions {
|
|
7
|
+
/** The page's own address (path only is fine): forms post to <path>/accept and <path>/decline. */
|
|
8
|
+
path: string;
|
|
9
|
+
/** Show the Download PDF link (to <path>/pdf). */
|
|
10
|
+
pdf?: boolean;
|
|
11
|
+
/** Just accepted on this visit: say thank you. */
|
|
12
|
+
justAccepted?: boolean;
|
|
13
|
+
/** What was wrong with the accept form, to show above it. */
|
|
14
|
+
errors?: readonly ("name" | "agree")[];
|
|
15
|
+
/** What the customer typed, put back after a problem. */
|
|
16
|
+
typedName?: string;
|
|
17
|
+
/** Stylesheets, in order. Default the project's /styles/workbench.css then /styles/project.css. */
|
|
18
|
+
styles?: readonly string[];
|
|
19
|
+
/** The clock, for the expired check. */
|
|
20
|
+
now?: Date;
|
|
21
|
+
}
|
|
22
|
+
/** The quote page's full HTML. */
|
|
23
|
+
export declare function renderQuotePage(quote: Quote, o: QuotePageOptions): string;
|
|
24
|
+
/** The page for a link that opens no quote. */
|
|
25
|
+
export declare function renderNotFoundPage(o?: {
|
|
26
|
+
language?: QuoteLang;
|
|
27
|
+
t?: QuoteStrings;
|
|
28
|
+
styles?: readonly string[];
|
|
29
|
+
}): string;
|
|
30
|
+
/** Where a quote stands for its customer at `now`. */
|
|
31
|
+
export declare function quoteState(quote: Quote, now: Date): "open" | "accepted" | "declined" | "withdrawn" | "expired" | "draft";
|
package/dist/page.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// The page a customer opens from the quote's link: the quote, then Accept
|
|
2
|
+
// (their full name and a tick) and a folded Decline with reasons to pick
|
|
3
|
+
// from. Plain HTML forms that post back to the same address, so it works with
|
|
4
|
+
// no script at all. Every element carries a wb-quote-* class (QUOTE_STYLES).
|
|
5
|
+
import { formatDate } from "@mccaskie-labs/workbench-country";
|
|
6
|
+
import { presentQuote } from "./document.js";
|
|
7
|
+
import { packFor } from "./money.js";
|
|
8
|
+
import { DECLINE_REASONS } from "./types.js";
|
|
9
|
+
import { quoteWord } from "./words.js";
|
|
10
|
+
/** The project's generated Workbench styles, then its own. */
|
|
11
|
+
export const DEFAULT_STYLESHEETS = ["/styles/workbench.css", "/styles/project.css"];
|
|
12
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
13
|
+
const htmlLang = (l) => (l === "en" ? "en" : "fil");
|
|
14
|
+
function head(lang, title, styles) {
|
|
15
|
+
return [
|
|
16
|
+
`<!doctype html><html lang="${htmlLang(lang)}"><head><meta charset="utf-8">`,
|
|
17
|
+
'<meta name="viewport" content="width=device-width,initial-scale=1">',
|
|
18
|
+
'<meta name="robots" content="noindex,nofollow">',
|
|
19
|
+
`<title>${esc(title)}</title>`,
|
|
20
|
+
...styles.map((s) => `<link rel="stylesheet" href="${esc(s)}">`),
|
|
21
|
+
"</head>",
|
|
22
|
+
].join("\n");
|
|
23
|
+
}
|
|
24
|
+
/** The quote page's full HTML. */
|
|
25
|
+
export function renderQuotePage(quote, o) {
|
|
26
|
+
const p = presentQuote(quote, o);
|
|
27
|
+
const lang = p.lang;
|
|
28
|
+
const w = (key, values = {}) => quoteWord(key, lang, { document: p.document.toLowerCase(), business: o.business.name, ...values }, o.t);
|
|
29
|
+
const pack = packFor(o.country);
|
|
30
|
+
const date = (iso) => formatDate(iso, { pack });
|
|
31
|
+
const out = ['<body><main class="wb-quote-page">', '<article class="wb-quote">'];
|
|
32
|
+
out.push(`<header class="wb-quote-header"><p class="wb-quote-business">${esc(o.business.name)}</p><h1 class="wb-quote-title">${esc(p.title)}</h1></header>`);
|
|
33
|
+
const state = quoteState(quote, o.now ?? new Date());
|
|
34
|
+
if (state === "accepted") {
|
|
35
|
+
const text = o.justAccepted ? w("state.accepted_you") : w("state.accepted", { name: quote.accepted_name ?? "", date: date(quote.accepted_at) });
|
|
36
|
+
out.push(`<p class="wb-quote-state wb-quote-state-good" role="status">${esc(text)}</p>`);
|
|
37
|
+
}
|
|
38
|
+
else if (state !== "open") {
|
|
39
|
+
const when = state === "expired" ? date(quote.valid_until) : "";
|
|
40
|
+
out.push(`<p class="wb-quote-state wb-quote-state-ended" role="status">${esc(w(`state.${state}`, { date: when }))}</p>`);
|
|
41
|
+
}
|
|
42
|
+
out.push(`<dl class="wb-quote-facts">${p.facts.map((f) => `<dt class="wb-quote-label">${esc(f.label)}</dt><dd class="wb-quote-value">${esc(f.value)}</dd>`).join("")}</dl>`);
|
|
43
|
+
if (p.estimateNote)
|
|
44
|
+
out.push(`<p class="wb-quote-estimate">${esc(p.estimateNote)}</p>`);
|
|
45
|
+
if (p.note)
|
|
46
|
+
out.push(`<p class="wb-quote-note">${esc(p.note)}</p>`);
|
|
47
|
+
const [ci, cq, cu, ca] = p.columns;
|
|
48
|
+
out.push('<table class="wb-quote-lines"><thead><tr class="wb-quote-line">', `<th class="wb-quote-head" scope="col">${esc(ci)}</th><th class="wb-quote-head wb-quote-num" scope="col">${esc(cq)}</th><th class="wb-quote-head wb-quote-num" scope="col">${esc(cu)}</th><th class="wb-quote-head wb-quote-num" scope="col">${esc(ca)}</th>`, "</tr></thead><tbody>", ...p.lines.map((l) => `<tr class="wb-quote-line"><td class="wb-quote-item">${esc(l.label)}</td><td class="wb-quote-num">${esc(l.quantity)}</td><td class="wb-quote-num">${esc(l.unit)}</td><td class="wb-quote-num">${esc(l.amount)}</td></tr>`), "</tbody></table>");
|
|
49
|
+
out.push(`<dl class="wb-quote-totals">${p.totals
|
|
50
|
+
.map((t) => `<dt class="wb-quote-sum-label${t.grand ? " wb-quote-grand" : ""}">${esc(t.label)}</dt><dd class="wb-quote-sum${t.grand ? " wb-quote-grand" : ""}">${esc(t.value)}</dd>`)
|
|
51
|
+
.join("")}</dl>`);
|
|
52
|
+
if (p.terms)
|
|
53
|
+
out.push(`<section class="wb-quote-terms"><h2 class="wb-quote-terms-title">${esc(p.terms.title)}</h2><p class="wb-quote-terms-text">${esc(p.terms.text)}</p></section>`);
|
|
54
|
+
if (o.pdf)
|
|
55
|
+
out.push(`<p class="wb-quote-value"><a class="wb-quote-pdf" href="${esc(o.path)}/pdf">${esc(w("pdf"))}</a></p>`);
|
|
56
|
+
out.push("</article>");
|
|
57
|
+
if (state === "open") {
|
|
58
|
+
const errors = o.errors ?? [];
|
|
59
|
+
const nameBad = errors.includes("name");
|
|
60
|
+
const form = [`<form class="wb-quote-accept" method="post" action="${esc(o.path)}/accept">`, `<h2 class="wb-quote-form-title">${esc(w("accept.heading"))}</h2>`];
|
|
61
|
+
for (const e of errors)
|
|
62
|
+
form.push(`<p class="wb-quote-error" id="wb-quote-error-${e}" role="alert">${esc(w(`accept.error.${e}`))}</p>`);
|
|
63
|
+
if (quote.name_required) {
|
|
64
|
+
form.push(`<label class="wb-quote-field">${esc(w("accept.name"))}<input class="wb-quote-input" type="text" name="name" autocomplete="name" required maxlength="120" value="${esc(o.typedName ?? "")}"${nameBad ? ' aria-invalid="true" aria-describedby="wb-quote-error-name"' : ""}></label>`);
|
|
65
|
+
}
|
|
66
|
+
form.push(`<label class="wb-quote-check"><input class="wb-quote-box" type="checkbox" name="agree" value="yes" required> ${esc(w("accept.agree"))}</label>`);
|
|
67
|
+
form.push(`<button class="wb-quote-accept-button" type="submit">${esc(w("accept.button"))}</button>`, "</form>");
|
|
68
|
+
out.push(form.join("\n"));
|
|
69
|
+
out.push('<details class="wb-quote-decline">', `<summary class="wb-quote-decline-title">${esc(w("decline.heading"))}</summary>`, `<form class="wb-quote-decline-form" method="post" action="${esc(o.path)}/decline">`, `<fieldset class="wb-quote-reasons"><legend class="wb-quote-reasons-title">${esc(w("decline.reason"))}</legend>`, ...DECLINE_REASONS.map((r) => `<label class="wb-quote-reason"><input class="wb-quote-box" type="radio" name="reason" value="${r}" required> ${esc(w(`reason.${r}`))}</label>`), "</fieldset>", `<button class="wb-quote-decline-button" type="submit">${esc(w("decline.button"))}</button>`, "</form></details>");
|
|
70
|
+
}
|
|
71
|
+
out.push("</main></body></html>");
|
|
72
|
+
return `${head(lang, w("title", { document: p.document, number: quote.number }), o.styles ?? DEFAULT_STYLESHEETS)}\n${out.join("\n")}\n`;
|
|
73
|
+
}
|
|
74
|
+
/** The page for a link that opens no quote. */
|
|
75
|
+
export function renderNotFoundPage(o = {}) {
|
|
76
|
+
const lang = o.language ?? "en";
|
|
77
|
+
const text = quoteWord("state.not_found", lang, {}, o.t);
|
|
78
|
+
return `${head(lang, text, o.styles ?? DEFAULT_STYLESHEETS)}\n<body><main class="wb-quote-page"><p class="wb-quote-state wb-quote-state-ended" role="status">${esc(text)}</p></main></body></html>\n`;
|
|
79
|
+
}
|
|
80
|
+
/** Where a quote stands for its customer at `now`. */
|
|
81
|
+
export function quoteState(quote, now) {
|
|
82
|
+
if (quote.status === "accepted" || quote.status === "declined" || quote.status === "withdrawn" || quote.status === "draft")
|
|
83
|
+
return quote.status;
|
|
84
|
+
if (quote.status === "expired" || (quote.valid_until && Date.parse(quote.valid_until) < now.valueOf()))
|
|
85
|
+
return "expired";
|
|
86
|
+
return "open";
|
|
87
|
+
}
|