@mccaskie-labs/workbench-plans 0.0.0-stage → 0.1.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.
@@ -0,0 +1,474 @@
1
+ // The app's own plans tables (docs/capabilities/06-plans-limits.md, "Data
2
+ // stored"), copied into the project's supabase/migrations as one file and its
3
+ // down file.
4
+ //
5
+ // Only the service role reaches them. The allowances come from the repo's
6
+ // workbench/plans.json and are passed in by the package, so a signed-in user
7
+ // who could call plans_use() directly could pass their own limits: the
8
+ // functions are granted to service_role only, and the tables have RLS on with
9
+ // no policies. The app calls createPlans with its service client, server side.
10
+ //
11
+ // plans_use() locks the account's row, so parallel calls for one account
12
+ // queue: ten calls with one left can't each see "1 left". The sign-up check
13
+ // takes a transaction lock, so two sign-ups with one Page address can't both
14
+ // pass as the first.
15
+ //
16
+ // No IP address is ever stored: the sign-up signals are keyed hashes made by
17
+ // the package (HMAC with the project's secret), and the network signal's key
18
+ // changes every day.
19
+ //
20
+ // It creates functions, so Control asks for approval to apply it even on
21
+ // staging. The down file drops everything the up file made.
22
+ export const plansMigration = {
23
+ up: `create table public.plan_accounts (
24
+ account_id text primary key check (char_length(account_id) between 1 and 100),
25
+ plan text not null check (plan ~ '^[a-z][a-z0-9_]{0,39}$'),
26
+ status text not null default 'active' check (status in ('active', 'held')),
27
+ switches jsonb not null default '{}'::jsonb check (jsonb_typeof(switches) = 'object'),
28
+ hold_matches jsonb not null default '[]'::jsonb check (jsonb_typeof(hold_matches) = 'array'),
29
+ set_by text check (char_length(set_by) <= 200),
30
+ reason text check (char_length(reason) <= 500),
31
+ created_at timestamptz not null default now(),
32
+ updated_at timestamptz not null default now()
33
+ );
34
+
35
+ comment on table public.plan_accounts is 'Each account''s plan, status (active or held for review) and feature switches (workbench-plans). Service role only.';
36
+
37
+ create table public.plan_uses (
38
+ id uuid primary key default gen_random_uuid(),
39
+ account_id text not null references public.plan_accounts (account_id) on delete cascade,
40
+ meter text not null check (meter ~ '^[a-z][a-z0-9_]{0,39}$'),
41
+ period text not null check (period ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'),
42
+ amount integer not null check (amount between 1 and 1000000),
43
+ subject text check (char_length(subject) between 1 and 200),
44
+ idempotency_key text check (char_length(idempotency_key) between 1 and 200),
45
+ created_at timestamptz not null default now(),
46
+ released_at timestamptz
47
+ );
48
+
49
+ comment on table public.plan_uses is 'Every counted use of a meter, per month; released_at gives one back (workbench-plans). Kept 13 months.';
50
+
51
+ create index plan_uses_count on public.plan_uses (account_id, meter, period) where released_at is null;
52
+ create unique index plan_uses_key on public.plan_uses (account_id, idempotency_key) where idempotency_key is not null;
53
+ create index plan_uses_created on public.plan_uses (created_at);
54
+
55
+ create table public.plan_grants (
56
+ id uuid primary key default gen_random_uuid(),
57
+ account_id text not null references public.plan_accounts (account_id) on delete cascade,
58
+ meter text not null check (meter ~ '^[a-z][a-z0-9_]{0,39}$'),
59
+ extra integer not null check (extra between 1 and 1000000),
60
+ until timestamptz not null,
61
+ granted_by text not null check (char_length(granted_by) between 1 and 200),
62
+ reason text not null check (char_length(reason) between 1 and 500),
63
+ created_at timestamptz not null default now()
64
+ );
65
+
66
+ comment on table public.plan_grants is 'One-off top-ups of a meter, in force until "until" (workbench-plans). Kept 13 months.';
67
+
68
+ create index plan_grants_account on public.plan_grants (account_id, meter, until);
69
+
70
+ create table public.signup_signals (
71
+ id bigint generated always as identity primary key,
72
+ account_id text not null references public.plan_accounts (account_id) on delete cascade,
73
+ kind text not null check (kind in ('email', 'page', 'name', 'phone', 'device', 'network')),
74
+ hash text not null check (hash ~ '^[0-9a-f]{64}$'),
75
+ created_at timestamptz not null default now()
76
+ );
77
+
78
+ comment on table public.signup_signals is 'Keyed hashes of what a sign-up gave (email, Page address, business name and city, phone, device cookie, daily network hash), never the values or an IP address (workbench-plans). Deleted after 12 months.';
79
+
80
+ create index signup_signals_match on public.signup_signals (kind, hash, created_at);
81
+ create index signup_signals_account on public.signup_signals (account_id);
82
+ create index signup_signals_created on public.signup_signals (created_at);
83
+
84
+ create table public.plan_changes (
85
+ id bigint generated always as identity primary key,
86
+ account_id text not null check (char_length(account_id) between 1 and 100),
87
+ kind text not null check (kind in ('plan', 'switch', 'grant', 'hold', 'clear')),
88
+ detail jsonb not null default '{}'::jsonb check (jsonb_typeof(detail) = 'object'),
89
+ changed_by text not null check (char_length(changed_by) between 1 and 200),
90
+ reason text not null check (char_length(reason) between 1 and 500),
91
+ created_at timestamptz not null default now()
92
+ );
93
+
94
+ comment on table public.plan_changes is 'Every plan, switch, top-up and hold change: who, when and why (workbench-plans). Kept.';
95
+
96
+ create index plan_changes_account on public.plan_changes (account_id, created_at);
97
+
98
+ alter table public.plan_accounts enable row level security;
99
+ alter table public.plan_uses enable row level security;
100
+ alter table public.plan_grants enable row level security;
101
+ alter table public.signup_signals enable row level security;
102
+ alter table public.plan_changes enable row level security;
103
+
104
+ revoke all on public.plan_accounts, public.plan_uses, public.plan_grants, public.signup_signals, public.plan_changes from anon, authenticated;
105
+
106
+ -- What one account has used of one meter this period, and its top-ups in force.
107
+ create function public.plans_counts(p_account text, p_meter text, p_period text, p_now timestamptz)
108
+ returns table (used integer, granted integer)
109
+ language sql
110
+ stable
111
+ security invoker
112
+ set search_path = ''
113
+ as $$
114
+ select
115
+ coalesce((select sum(u.amount) from public.plan_uses u
116
+ where u.account_id = p_account and u.meter = p_meter and u.period = p_period and u.released_at is null), 0)::integer,
117
+ coalesce((select sum(g.extra) from public.plan_grants g
118
+ where g.account_id = p_account and g.meter = p_meter and g.until > p_now), 0)::integer;
119
+ $$;
120
+
121
+ -- Checks and counts in one step. p_limits is the meter's allowance per plan
122
+ -- (from plans.json); p_switchable says a feature of the same name exists, so
123
+ -- switching it off for the account stops the meter too. A refusal counts
124
+ -- nothing. The same idempotency key again answers as the first call did.
125
+ create function public.plans_use(
126
+ p_account text,
127
+ p_meter text,
128
+ p_period text,
129
+ p_limits jsonb,
130
+ p_switchable boolean,
131
+ p_default_plan text,
132
+ p_create boolean,
133
+ p_amount integer,
134
+ p_subject text,
135
+ p_key text,
136
+ p_now timestamptz
137
+ )
138
+ returns jsonb
139
+ language plpgsql
140
+ security invoker
141
+ set search_path = ''
142
+ as $$
143
+ declare
144
+ a public.plan_accounts;
145
+ v_limit integer;
146
+ v_used integer;
147
+ v_granted integer;
148
+ v_id uuid;
149
+ begin
150
+ if p_amount is null or p_amount < 1 then
151
+ raise exception using errcode = '22023', message = 'plans: amount must be 1 or more';
152
+ end if;
153
+ if p_create then
154
+ insert into public.plan_accounts (account_id, plan) values (p_account, p_default_plan)
155
+ on conflict (account_id) do nothing;
156
+ end if;
157
+ select * into a from public.plan_accounts where account_id = p_account for update;
158
+ if not found then
159
+ raise exception using errcode = 'P0001', message = 'plans_unknown_account';
160
+ end if;
161
+ v_limit := coalesce((p_limits ->> a.plan)::integer, 0);
162
+ select c.used, c.granted into v_used, v_granted from public.plans_counts(p_account, p_meter, p_period, p_now) c;
163
+ if p_key is not null then
164
+ select u.id into v_id from public.plan_uses u where u.account_id = p_account and u.idempotency_key = p_key;
165
+ if found then
166
+ return jsonb_build_object('ok', true, 'use_id', v_id, 'left', greatest(v_limit + v_granted - v_used, 0), 'plan', a.plan, 'repeat', true);
167
+ end if;
168
+ end if;
169
+ if a.status = 'held' then
170
+ return jsonb_build_object('ok', false, 'reason', 'account_held', 'plan', a.plan);
171
+ end if;
172
+ if p_switchable and a.switches ->> p_meter = 'false' then
173
+ return jsonb_build_object('ok', false, 'reason', 'switched_off', 'plan', a.plan);
174
+ end if;
175
+ if v_limit + v_granted = 0 then
176
+ return jsonb_build_object('ok', false, 'reason', 'not_on_plan', 'plan', a.plan);
177
+ end if;
178
+ if v_used + p_amount > v_limit + v_granted then
179
+ return jsonb_build_object('ok', false, 'reason', 'allowance_used', 'plan', a.plan, 'limit', v_limit + v_granted);
180
+ end if;
181
+ insert into public.plan_uses (account_id, meter, period, amount, subject, idempotency_key, created_at)
182
+ values (p_account, p_meter, p_period, p_amount, p_subject, p_key, p_now)
183
+ returning id into v_id;
184
+ return jsonb_build_object('ok', true, 'use_id', v_id, 'left', v_limit + v_granted - v_used - p_amount, 'plan', a.plan);
185
+ end;
186
+ $$;
187
+
188
+ -- Gives a use back (its work failed). Twice is a no-op.
189
+ create function public.plans_release(p_use uuid, p_now timestamptz)
190
+ returns boolean
191
+ language sql
192
+ security invoker
193
+ set search_path = ''
194
+ as $$
195
+ with r as (
196
+ update public.plan_uses set released_at = p_now where id = p_use and released_at is null returning 1
197
+ )
198
+ select exists (select 1 from r);
199
+ $$;
200
+
201
+ -- The account, and this period's use and top-ups of each meter.
202
+ create function public.plans_status(p_account text, p_meters text[], p_period text, p_now timestamptz)
203
+ returns jsonb
204
+ language sql
205
+ stable
206
+ security invoker
207
+ set search_path = ''
208
+ as $$
209
+ select case when a.account_id is null then null else jsonb_build_object(
210
+ 'account', to_jsonb(a),
211
+ 'meters', coalesce((
212
+ select jsonb_object_agg(m, jsonb_build_object('used', c.used, 'granted', c.granted))
213
+ from unnest(p_meters) as m
214
+ cross join lateral public.plans_counts(p_account, m, p_period, p_now) c
215
+ ), '{}'::jsonb)
216
+ ) end
217
+ from (select 1) one
218
+ left join public.plan_accounts a on a.account_id = p_account;
219
+ $$;
220
+
221
+ create function public.plans_set_plan(p_account text, p_plan text, p_by text, p_reason text)
222
+ returns void
223
+ language plpgsql
224
+ security invoker
225
+ set search_path = ''
226
+ as $$
227
+ declare
228
+ v_from text;
229
+ begin
230
+ select plan into v_from from public.plan_accounts where account_id = p_account for update;
231
+ insert into public.plan_accounts (account_id, plan, set_by, reason) values (p_account, p_plan, p_by, p_reason)
232
+ on conflict (account_id) do update set plan = excluded.plan, set_by = excluded.set_by, reason = excluded.reason, updated_at = now();
233
+ insert into public.plan_changes (account_id, kind, detail, changed_by, reason)
234
+ values (p_account, 'plan', jsonb_build_object('from', v_from, 'to', p_plan), p_by, p_reason);
235
+ end;
236
+ $$;
237
+
238
+ -- Turns a feature off for one account, or back on. On is refused when the
239
+ -- account's plan lacks it (p_feature_plans: the plans that include it).
240
+ create function public.plans_set_switch(
241
+ p_account text,
242
+ p_feature text,
243
+ p_on boolean,
244
+ p_feature_plans text[],
245
+ p_default_plan text,
246
+ p_create boolean,
247
+ p_by text,
248
+ p_reason text
249
+ )
250
+ returns void
251
+ language plpgsql
252
+ security invoker
253
+ set search_path = ''
254
+ as $$
255
+ declare
256
+ a public.plan_accounts;
257
+ begin
258
+ if p_create then
259
+ insert into public.plan_accounts (account_id, plan) values (p_account, p_default_plan)
260
+ on conflict (account_id) do nothing;
261
+ end if;
262
+ select * into a from public.plan_accounts where account_id = p_account for update;
263
+ if not found then
264
+ raise exception using errcode = 'P0001', message = 'plans_unknown_account';
265
+ end if;
266
+ if p_on and not (a.plan = any (p_feature_plans)) then
267
+ raise exception using errcode = 'P0001', message = 'plans_not_on_plan', detail = a.plan;
268
+ end if;
269
+ update public.plan_accounts
270
+ set switches = case when p_on then switches - p_feature else switches || jsonb_build_object(p_feature, false) end,
271
+ set_by = p_by, reason = p_reason, updated_at = now()
272
+ where account_id = p_account;
273
+ insert into public.plan_changes (account_id, kind, detail, changed_by, reason)
274
+ values (p_account, 'switch', jsonb_build_object('feature', p_feature, 'on', p_on), p_by, p_reason);
275
+ end;
276
+ $$;
277
+
278
+ create function public.plans_grant(
279
+ p_account text,
280
+ p_meter text,
281
+ p_extra integer,
282
+ p_until timestamptz,
283
+ p_default_plan text,
284
+ p_create boolean,
285
+ p_by text,
286
+ p_reason text
287
+ )
288
+ returns uuid
289
+ language plpgsql
290
+ security invoker
291
+ set search_path = ''
292
+ as $$
293
+ declare
294
+ v_id uuid;
295
+ begin
296
+ if p_create then
297
+ insert into public.plan_accounts (account_id, plan) values (p_account, p_default_plan)
298
+ on conflict (account_id) do nothing;
299
+ end if;
300
+ if not exists (select 1 from public.plan_accounts where account_id = p_account) then
301
+ raise exception using errcode = 'P0001', message = 'plans_unknown_account';
302
+ end if;
303
+ insert into public.plan_grants (account_id, meter, extra, until, granted_by, reason)
304
+ values (p_account, p_meter, p_extra, p_until, p_by, p_reason)
305
+ returning id into v_id;
306
+ insert into public.plan_changes (account_id, kind, detail, changed_by, reason)
307
+ values (p_account, 'grant', jsonb_build_object('meter', p_meter, 'extra', p_extra, 'until', p_until), p_by, p_reason);
308
+ return v_id;
309
+ end;
310
+ $$;
311
+
312
+ -- A new account through the sign-up checks. p_signals is a list of
313
+ -- { kind, hash }. An identity signal (email, page, name, phone) matching
314
+ -- p_per_identity or more other accounts, or a device signal matching
315
+ -- p_device_max or more other accounts within p_window_days, is a repeat: the
316
+ -- account is created held (or, with p_refuse, not at all). Network signals
317
+ -- are kept but never matched (the device check is cookie only).
318
+ create function public.plans_signup(
319
+ p_account text,
320
+ p_plan text,
321
+ p_signals jsonb,
322
+ p_per_identity integer,
323
+ p_device_max integer,
324
+ p_window_days integer,
325
+ p_refuse boolean,
326
+ p_now timestamptz
327
+ )
328
+ returns jsonb
329
+ language plpgsql
330
+ security invoker
331
+ set search_path = ''
332
+ as $$
333
+ declare
334
+ s record;
335
+ v_others text[];
336
+ v_matches jsonb := '[]'::jsonb;
337
+ v_status text;
338
+ begin
339
+ if jsonb_typeof(p_signals) <> 'array' then
340
+ raise exception using errcode = '22023', message = 'plans: signals must be a list';
341
+ end if;
342
+ perform pg_advisory_xact_lock(hashtext('workbench-plans:signup'));
343
+ if exists (select 1 from public.plan_accounts where account_id = p_account) then
344
+ raise exception using errcode = 'P0001', message = 'plans_account_exists';
345
+ end if;
346
+ for s in select distinct e ->> 'kind' as kind, e ->> 'hash' as hash from jsonb_array_elements(p_signals) e loop
347
+ if s.kind in ('email', 'page', 'name', 'phone') then
348
+ select array_agg(distinct x.account_id order by x.account_id) into v_others
349
+ from public.signup_signals x where x.kind = s.kind and x.hash = s.hash;
350
+ if coalesce(cardinality(v_others), 0) >= p_per_identity then
351
+ v_matches := v_matches || jsonb_build_object('kind', s.kind, 'accounts', to_jsonb(v_others));
352
+ end if;
353
+ elsif s.kind = 'device' then
354
+ select array_agg(distinct x.account_id order by x.account_id) into v_others
355
+ from public.signup_signals x
356
+ where x.kind = 'device' and x.hash = s.hash and x.created_at > p_now - make_interval(days => p_window_days);
357
+ if coalesce(cardinality(v_others), 0) >= p_device_max then
358
+ v_matches := v_matches || jsonb_build_object('kind', 'device', 'accounts', to_jsonb(v_others));
359
+ end if;
360
+ elsif s.kind is distinct from 'network' then
361
+ raise exception using errcode = '22023', message = 'plans: unknown signal kind';
362
+ end if;
363
+ end loop;
364
+ v_status := case when jsonb_array_length(v_matches) = 0 then 'active' else 'held' end;
365
+ if v_status = 'held' and p_refuse then
366
+ return jsonb_build_object('status', 'refused', 'matches', v_matches);
367
+ end if;
368
+ insert into public.plan_accounts (account_id, plan, status, hold_matches, created_at, updated_at)
369
+ values (p_account, p_plan, v_status, v_matches, p_now, p_now);
370
+ insert into public.signup_signals (account_id, kind, hash, created_at)
371
+ select distinct p_account, e ->> 'kind', e ->> 'hash', p_now from jsonb_array_elements(p_signals) e;
372
+ if v_status = 'held' then
373
+ insert into public.plan_changes (account_id, kind, detail, changed_by, reason)
374
+ values (p_account, 'hold', jsonb_build_object('matches', v_matches), 'sign-up checks', 'Looks like a repeat free sign-up');
375
+ end if;
376
+ return jsonb_build_object('status', v_status, 'matches', v_matches);
377
+ end;
378
+ $$;
379
+
380
+ -- The admin clears a held account. Its hold_matches stay, as the record of why.
381
+ create function public.plans_clear_hold(p_account text, p_by text, p_reason text)
382
+ returns boolean
383
+ language plpgsql
384
+ security invoker
385
+ set search_path = ''
386
+ as $$
387
+ begin
388
+ update public.plan_accounts set status = 'active', set_by = p_by, reason = p_reason, updated_at = now()
389
+ where account_id = p_account and status = 'held';
390
+ if not found then
391
+ return false;
392
+ end if;
393
+ insert into public.plan_changes (account_id, kind, detail, changed_by, reason)
394
+ values (p_account, 'clear', '{}'::jsonb, p_by, p_reason);
395
+ return true;
396
+ end;
397
+ $$;
398
+
399
+ -- The held accounts, oldest first, for the admin page.
400
+ create function public.plans_held()
401
+ returns jsonb
402
+ language sql
403
+ stable
404
+ security invoker
405
+ set search_path = ''
406
+ as $$
407
+ select coalesce(jsonb_agg(jsonb_build_object('account', a.account_id, 'plan', a.plan, 'matches', a.hold_matches, 'created_at', a.created_at) order by a.created_at), '[]'::jsonb)
408
+ from public.plan_accounts a where a.status = 'held';
409
+ $$;
410
+
411
+ -- The daily clean-up: uses and top-ups after 13 months, sign-up signals after 12.
412
+ create function public.plans_cleanup(p_now timestamptz)
413
+ returns jsonb
414
+ language plpgsql
415
+ security invoker
416
+ set search_path = ''
417
+ as $$
418
+ declare
419
+ n_uses integer;
420
+ n_grants integer;
421
+ n_signals integer;
422
+ begin
423
+ delete from public.plan_uses where created_at < p_now - interval '13 months';
424
+ get diagnostics n_uses = row_count;
425
+ delete from public.plan_grants where until < p_now - interval '13 months';
426
+ get diagnostics n_grants = row_count;
427
+ delete from public.signup_signals where created_at < p_now - interval '12 months';
428
+ get diagnostics n_signals = row_count;
429
+ return jsonb_build_object('uses', n_uses, 'grants', n_grants, 'signals', n_signals);
430
+ end;
431
+ $$;
432
+
433
+ revoke execute on function public.plans_counts(text, text, text, timestamptz) from public, anon, authenticated;
434
+ revoke execute on function public.plans_use(text, text, text, jsonb, boolean, text, boolean, integer, text, text, timestamptz) from public, anon, authenticated;
435
+ revoke execute on function public.plans_release(uuid, timestamptz) from public, anon, authenticated;
436
+ revoke execute on function public.plans_status(text, text[], text, timestamptz) from public, anon, authenticated;
437
+ revoke execute on function public.plans_set_plan(text, text, text, text) from public, anon, authenticated;
438
+ revoke execute on function public.plans_set_switch(text, text, boolean, text[], text, boolean, text, text) from public, anon, authenticated;
439
+ revoke execute on function public.plans_grant(text, text, integer, timestamptz, text, boolean, text, text) from public, anon, authenticated;
440
+ revoke execute on function public.plans_signup(text, text, jsonb, integer, integer, integer, boolean, timestamptz) from public, anon, authenticated;
441
+ revoke execute on function public.plans_clear_hold(text, text, text) from public, anon, authenticated;
442
+ revoke execute on function public.plans_held() from public, anon, authenticated;
443
+ revoke execute on function public.plans_cleanup(timestamptz) from public, anon, authenticated;
444
+ grant execute on function public.plans_counts(text, text, text, timestamptz) to service_role;
445
+ grant execute on function public.plans_use(text, text, text, jsonb, boolean, text, boolean, integer, text, text, timestamptz) to service_role;
446
+ grant execute on function public.plans_release(uuid, timestamptz) to service_role;
447
+ grant execute on function public.plans_status(text, text[], text, timestamptz) to service_role;
448
+ grant execute on function public.plans_set_plan(text, text, text, text) to service_role;
449
+ grant execute on function public.plans_set_switch(text, text, boolean, text[], text, boolean, text, text) to service_role;
450
+ grant execute on function public.plans_grant(text, text, integer, timestamptz, text, boolean, text, text) to service_role;
451
+ grant execute on function public.plans_signup(text, text, jsonb, integer, integer, integer, boolean, timestamptz) to service_role;
452
+ grant execute on function public.plans_clear_hold(text, text, text) to service_role;
453
+ grant execute on function public.plans_held() to service_role;
454
+ grant execute on function public.plans_cleanup(timestamptz) to service_role;
455
+ grant select, insert, update, delete on public.plan_accounts, public.plan_uses, public.plan_grants, public.signup_signals, public.plan_changes to service_role;
456
+ `,
457
+ down: `drop function public.plans_cleanup(timestamptz);
458
+ drop function public.plans_held();
459
+ drop function public.plans_clear_hold(text, text, text);
460
+ drop function public.plans_signup(text, text, jsonb, integer, integer, integer, boolean, timestamptz);
461
+ drop function public.plans_grant(text, text, integer, timestamptz, text, boolean, text, text);
462
+ drop function public.plans_set_switch(text, text, boolean, text[], text, boolean, text, text);
463
+ drop function public.plans_set_plan(text, text, text, text);
464
+ drop function public.plans_status(text, text[], text, timestamptz);
465
+ drop function public.plans_release(uuid, timestamptz);
466
+ drop function public.plans_use(text, text, text, jsonb, boolean, text, boolean, integer, text, text, timestamptz);
467
+ drop function public.plans_counts(text, text, text, timestamptz);
468
+ drop table public.plan_changes;
469
+ drop table public.signup_signals;
470
+ drop table public.plan_grants;
471
+ drop table public.plan_uses;
472
+ drop table public.plan_accounts;
473
+ `,
474
+ };
@@ -0,0 +1,4 @@
1
+ /** The period an instant falls in: YYYY-MM in the time zone. */
2
+ export declare function periodOf(at: Date, timeZone: string): string;
3
+ /** Midnight at the start of the month after `period`, in the time zone, as ISO 8601 with the zone's offset. */
4
+ export declare function resetsAt(period: string, timeZone: string): string;
package/dist/period.js ADDED
@@ -0,0 +1,39 @@
1
+ // The month an allowance belongs to, in the project's time zone: a use at
2
+ // 23:30 on 30 November in Manila is November's, even though it is already
3
+ // December in some places, and the allowance comes back at midnight on the
4
+ // 1st, Manila time.
5
+ /** The wall-clock parts of an instant in a time zone. */
6
+ function parts(at, timeZone) {
7
+ const f = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hourCycle: "h23" });
8
+ const o = {};
9
+ for (const p of f.formatToParts(at))
10
+ if (p.type !== "literal")
11
+ o[p.type] = Number(p.value);
12
+ return { y: o.year, m: o.month, d: o.day, h: o.hour % 24, mi: o.minute, s: o.second };
13
+ }
14
+ /** The zone's offset from UTC at an instant, in minutes. */
15
+ function offsetMinutes(at, timeZone) {
16
+ const p = parts(at, timeZone);
17
+ const asUtc = Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s);
18
+ return Math.round((asUtc - Math.floor(at.getTime() / 1000) * 1000) / 60000);
19
+ }
20
+ const pad = (n, w = 2) => String(Math.abs(n)).padStart(w, "0");
21
+ /** The period an instant falls in: YYYY-MM in the time zone. */
22
+ export function periodOf(at, timeZone) {
23
+ const p = parts(at, timeZone);
24
+ return `${p.y}-${pad(p.m)}`;
25
+ }
26
+ /** Midnight at the start of the month after `period`, in the time zone, as ISO 8601 with the zone's offset. */
27
+ export function resetsAt(period, timeZone) {
28
+ const [y, m] = period.split("-").map(Number);
29
+ const ny = m === 12 ? y + 1 : y;
30
+ const nm = m === 12 ? 1 : m + 1;
31
+ // Midnight in the zone: start from midnight UTC, then correct by the offset there (twice, for a change of offset).
32
+ let t = Date.UTC(ny, nm - 1, 1);
33
+ let off = offsetMinutes(new Date(t), timeZone);
34
+ t = Date.UTC(ny, nm - 1, 1) - off * 60000;
35
+ off = offsetMinutes(new Date(t), timeZone);
36
+ t = Date.UTC(ny, nm - 1, 1) - off * 60000;
37
+ const sign = off < 0 ? "-" : "+";
38
+ return `${ny}-${pad(nm)}-01T00:00:00${sign}${pad(Math.trunc(off / 60))}:${pad(off % 60)}`;
39
+ }
@@ -0,0 +1,58 @@
1
+ import type { Allowed, FeatureKey, HoldMatch, MeterKey, PlanKey, PlansConfig, PlanStatus, UseRequest } from "./types.ts";
2
+ type DbError = {
3
+ message?: string;
4
+ code?: string;
5
+ details?: string;
6
+ } | null;
7
+ /** The part of a Supabase client the package needs. Any supabase-js client fits; use the service client. */
8
+ export interface PlansClient {
9
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
10
+ data: unknown;
11
+ error: DbError;
12
+ }>;
13
+ }
14
+ export interface PlansOptions<C extends PlansConfig> {
15
+ db: PlansClient;
16
+ /** PLANS from src/plans.generated.ts (`npx workbench-plans generate`). */
17
+ plans: C;
18
+ /** The clock, for tests. */
19
+ now?: () => Date;
20
+ }
21
+ export interface Plans<C extends PlansConfig = PlansConfig> {
22
+ /** Is the feature on the account's plan and switched on? No counting. */
23
+ can(account: string, feature: FeatureKey<C>): Promise<Allowed<PlanKey<C>>>;
24
+ /**
25
+ * Checks the allowance and counts the use in one step; a refusal counts
26
+ * nothing. The meter's allowance on the account's plan decides (0 is
27
+ * not_on_plan); a feature of the same name switched off for the account
28
+ * stops it too.
29
+ */
30
+ use(account: string, meter: MeterKey<C>, req?: UseRequest): Promise<Allowed<PlanKey<C>>>;
31
+ /** Gives back a use whose work failed (the AI call 502'd). Twice is a no-op. */
32
+ release(useId: string): Promise<void>;
33
+ /** The plan, switches and each meter's use this month. */
34
+ status(account: string): Promise<PlanStatus>;
35
+ setPlan(account: string, plan: PlanKey<C>, by: string, reason: string): Promise<void>;
36
+ /** Off works on any feature; on only where the plan has it (use setPlan or grant for more). */
37
+ setSwitch(account: string, feature: FeatureKey<C>, on: boolean, by: string, reason: string): Promise<void>;
38
+ /** A one-off top-up of a meter, in force until `until` (ISO 8601). */
39
+ grant(account: string, meter: MeterKey<C>, extra: number, until: string, by: string, reason: string): Promise<void>;
40
+ /** Clears a held account (the admin checked it): use() works again. */
41
+ clearHold(account: string, by: string, reason: string): Promise<boolean>;
42
+ /** The held accounts, oldest first, with what each matched. */
43
+ held(): Promise<{
44
+ account: string;
45
+ plan: string;
46
+ matches: HoldMatch[];
47
+ created_at: string;
48
+ }[]>;
49
+ /** The daily clean-up: uses and top-ups after 13 months, sign-up signals after 12. Run from the app's cron. */
50
+ cleanup(): Promise<{
51
+ uses: number;
52
+ grants: number;
53
+ signals: number;
54
+ }>;
55
+ }
56
+ export declare function call<T>(db: PlansClient, what: string, fn: string, args: Record<string, unknown>): Promise<T>;
57
+ export declare function createPlans<const C extends PlansConfig>(opts: PlansOptions<C>): Plans<C>;
58
+ export {};