@mccaskie-labs/workbench-nudges 0.5.0 → 0.6.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 CHANGED
@@ -1,5 +1,19 @@
1
1
  # @mccaskie-labs/workbench-nudges
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Undo for Not needed (docs/critical-actions-audit.md). `dismiss()` now keeps the follow-up's draft, and the new `undoDismiss(id)` brings a dismissed nudge back as it was: the same step, due time, draft and status (waiting, due or snoozed). It is refused with the new failure `started_again` (409) when the rule has started again for the subject since, and `unknown_nudge` for one that isn't dismissed. `nudgeAction` takes `undo` (one press, no question) and every success now answers the nudge's id (`body.nudge`); `renderNudgeList` takes `dismissed: [{ id, title }]` and shows "Stopped following up …" with an Undo button for each, and `renderUndo` draws that line alone. Not needed's question now says Undo brings it back instead of "This can't be undone".
8
+ - A second migration, `workbench_nudges_undo`: a new table `nudge_dismissals` (what a dismissed nudge was, and when) and two new functions, `nudges_dismiss` and `nudges_undismiss`, service role only. It adds only new objects, so Control applies it free on staging. `npx workbench-nudges migration` now writes whichever migrations a project doesn't have yet (`nudgesMigrations`, `nudgesUndoMigration`). Until it is applied, `dismiss()` works the old way (the draft deleted) and `undoDismiss()` answers `bad_config` naming the migration.
9
+ - New words `undo`, `undo.done`, `undo.done_untitled` and `error.started_again` (English, Tagalog, Taglish; also in `CATALOGUE_WORDS`), and `dismiss.consequence` reworded. New classes `wb-nudge-undone`, `wb-nudge-undone-text` and `wb-nudge-undo`.
10
+
11
+ ## 0.5.1
12
+
13
+ ### Patch Changes
14
+
15
+ - Short answers get sensible widths in every tool (Robert, 24 November 2026). A tool's own one-line fields for an email, a phone number, a date, a time, a small number, an amount or a postcode now carry workbench-ui's `wb-ui-size-<n>` class, so they are about as wide as what they hold instead of the full width, and never wider than their column. The "type this word to confirm" box in "Are you sure?" is as wide as its word. Names, addresses and other long text keep the full width. A project restyles the widths in project.css by the same class names. Needs workbench-ui 0.10.0 or later in the project, whose workbench.css carries the classes.
16
+
3
17
  ## 0.5.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -12,7 +12,7 @@ Nudges remind the **business**. They never message its customer: the owner copie
12
12
 
13
13
  1. `npx workbench-nudges init` writes `workbench/nudges.json` (quotes with no reply, and businesses that haven't answered a first message) and the `quote-follow-up` reply guide. Edit them; the client questions in `capabilities/nudges.json` say how.
14
14
  2. `npx workbench-ai replies generate`, then `npx workbench-nudges generate` checks the rules (no rule has more than three steps; every guide must exist) and writes `src/nudges.generated.ts` (`NUDGE_RULES`). Checks can run `npx workbench-nudges generate --check`.
15
- 3. `npx workbench-nudges migration` writes `nudgesMigration` and its down file. It creates functions, so Control asks for approval even on staging.
15
+ 3. `npx workbench-nudges migration` writes each migration the project doesn't have yet (`nudgesMigrations`: the tables, then `workbench_nudges_undo` for Undo) and their down files. The first creates functions that write rows, so Control asks for approval even on staging; the second adds only a new table and new functions granted to the service role, so staging applies it free. Without the second, Not needed deletes the draft and `undoDismiss()` answers `bad_config` naming it.
16
16
  4. Add `"*/15 * * * *"` to `triggers.crons` in `wrangler.jsonc`, and `nudges` to a plan's features in `workbench/plans.json`.
17
17
 
18
18
  ## Use
@@ -41,7 +41,8 @@ ctx.waitUntil(nudges.tick())
41
41
  - Quiet hours move a step that would fall in them to their end. `"3d"` is three days on the local clock.
42
42
  - After the last step, a nudge left alone ends `ends_after` (7 days) later. A rule never has more than three steps.
43
43
  - The digest: one email a day per account with something due, from `digest_at` (the end of the quiet hours, or 08:00), with a count and a link, never a customer's name. `email_owner: "each"` emails as each comes due; `"none"` uses only the list.
44
- - `cleanup()` once a day: ended nudges after 90 days, drafts after 30 at most (and as soon as their nudge moves on or ends).
44
+ - `cleanup()` once a day: ended nudges after 90 days, drafts after 30 at most (and as soon as their nudge moves on or ends, except a dismissed one's, kept for Undo).
45
+ - `dismiss()` (Not needed) ends a nudge and keeps its draft; `undoDismiss(id)` brings it back as it was: the same step, due time, draft and status. It answers `started_again` (409 from `nudgeAction`) when the rule has started again for the subject since, and `unknown_nudge` for one that isn't dismissed, was dismissed before the undo migration, or is gone.
45
46
 
46
47
  ## The Waiting for you list
47
48
 
@@ -51,15 +52,18 @@ import { renderReplyBox } from '@mccaskie-labs/workbench-ai/reply-ui'
51
52
 
52
53
  html = renderNudgeList(await nudges.due(account), { endpoint: '/app/waiting', replyBox: renderReplyBox, label: (n) => titleOf(n.subject) })
53
54
  // The buttons post here, behind the owner's sign-in:
54
- const r = await nudgeAction(nudges, fields, account) // sent, snooze (a day, out of quiet hours) or dismiss (needs confirm=yes)
55
+ const r = await nudgeAction(nudges, fields, account) // sent, snooze (a day, out of quiet hours), dismiss (needs confirm=yes) or undo
56
+ // After a dismiss, draw the list with its Undo line:
57
+ html = renderNudgeList(await nudges.due(account), { endpoint: '/app/waiting', dismissed: [{ id: r.body.nudge, title }] })
55
58
  ```
56
59
 
57
- Not needed asks "Are you sure?" first: the button opens a question that names the follow-up and says its draft is deleted, nobody is emailed and it can't be undone, with an optional reason. `nudgeAction` refuses a `dismiss` without `confirm=yes` (`confirm_needed`, 409), so a page that draws its own Not needed button must ask first too. Every element carries a `wb-nudge-*` class with a default style (`NUDGE_STYLES`, written by `npx workbench-ui styles`); the draft uses the reply drafter's `wb-reply-*` box. Words are in `NUDGE_WORDS` (English, Tagalog, Taglish) under `ui.wbnudge.*`.
60
+ Not needed asks "Are you sure?" first: the button opens a question that names the follow-up and says no more reminders come, nobody is emailed and Undo brings it back, with an optional reason. Once dismissed, pass it as `dismissed` and the list shows "Stopped following up …" with an Undo button at the top (`renderUndo` draws the line alone): one press, no question, since it only puts the follow-up back. `nudgeAction` refuses a `dismiss` without `confirm=yes` (`confirm_needed`, 409), so a page that draws its own Not needed button must ask first too. Every element carries a `wb-nudge-*` class with a default style (`NUDGE_STYLES`, written by `npx workbench-ui styles`); the draft uses the reply drafter's `wb-reply-*` box. Words are in `NUDGE_WORDS` (English, Tagalog, Taglish) under `ui.wbnudge.*`.
58
61
 
59
62
  ## Data
60
63
 
61
64
  | Table | Holds | Kept |
62
65
  | --- | --- | --- |
63
66
  | `nudges` | rule, account, subject (an id in the app's own tables), step, due time, status, why it stopped, start()'s facts (ids and dates) | 90 days after it ends |
64
- | `nudge_drafts` | the latest draft of a due nudge (may hold the customer's first name) | until the nudge moves on or ends; 30 days at most |
67
+ | `nudge_drafts` | the latest draft of a due nudge (may hold the customer's first name) | until the nudge moves on or ends (a dismissed one's is kept for Undo); 30 days at most |
65
68
  | `nudge_digests` | which accounts got the day's digest, and the count | 60 days |
69
+ | `nudge_dismissals` | what a dismissed nudge was (waiting, due or snoozed) and when, for Undo | with its nudge; gone once undone |
package/dist/cli.js CHANGED
@@ -10,14 +10,14 @@
10
10
  // src/nudges.generated.ts: NUDGE_RULES for createNudges. --check writes
11
11
  // nothing and fails when the file is out of date or wrong.
12
12
  //
13
- // `npx workbench-nudges migration [dir]` writes nudgesMigration into
14
- // supabase/migrations/<timestamp>_workbench_nudges.sql, and its down file into
15
- // supabase/rollback/, unless a nudges migration is already there.
13
+ // `npx workbench-nudges migration [dir]` writes each nudges migration into
14
+ // supabase/migrations/<timestamp>_<name>.sql, and its down file into
15
+ // supabase/rollback/, for each one the project doesn't have yet.
16
16
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
17
17
  import { dirname, join, resolve } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import { guidesOf, nudgeProblems } from "./config.js";
20
- import { nudgesMigration } from "./migration.js";
20
+ import { nudgesMigrations } from "./migration.js";
21
21
  import { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.js";
22
22
  const USAGE = "usage: workbench-nudges init [dir]\n workbench-nudges generate [--check] [dir]\n workbench-nudges migration [dir]";
23
23
  export const NUDGES_FILE = "workbench/nudges.json";
@@ -100,16 +100,22 @@ export function run(argv, log = console.log, err = console.error) {
100
100
  }
101
101
  if (command === "migration") {
102
102
  const folder = join(dir, "supabase/migrations");
103
- if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_nudges.sql"))) {
104
- log("supabase/migrations already has the nudges migration; nothing written");
103
+ const have = existsSync(folder) ? readdirSync(folder) : [];
104
+ const missing = nudgesMigrations.filter((m) => !have.some((f) => f.endsWith(`_${m.name}.sql`)));
105
+ if (!missing.length) {
106
+ log("supabase/migrations already has every nudges migration; nothing written");
105
107
  return 0;
106
108
  }
107
- const name = `${migrationStamp(new Date())}_workbench_nudges.sql`;
108
109
  mkdirSync(folder, { recursive: true });
109
110
  mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
110
- writeFileSync(join(folder, name), `-- workbench-nudges: follow-up nudges (docs/capabilities/09-follow-up-nudges.md)\n${nudgesMigration.up}`);
111
- writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${nudgesMigration.down}`);
112
- log(`wrote supabase/migrations/${name} and its down file`);
111
+ const at = Date.now();
112
+ missing.forEach((m, i) => {
113
+ // A second apart, so they apply in order.
114
+ const name = `${migrationStamp(new Date(at + i * 1000))}_${m.name}.sql`;
115
+ writeFileSync(join(folder, name), `-- workbench-nudges: ${m.about}\n${m.up}`);
116
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${m.down}`);
117
+ log(`wrote supabase/migrations/${name} and its down file`);
118
+ });
113
119
  return 0;
114
120
  }
115
121
  const config = readNudges(dir);
package/dist/confirm.js CHANGED
@@ -18,8 +18,10 @@ export function renderConfirm(o) {
18
18
  const reason = o.reason
19
19
  ? `<label class="${p}-confirm-field"><span class="${p}-confirm-label">${esc(o.reason.label)}</span><input class="${p}-confirm-input" type="text" name="${esc(o.reason.name ?? "reason")}" maxlength="${o.reason.maxlength ?? 200}"${o.reason.required ? " required" : ""}></label>`
20
20
  : "";
21
+ // The word box is as wide as the word (workbench-ui's wb-ui-size-<n>, in characters), not the width of the page.
22
+ const wordSize = o.type ? [5, 6, 8, 10, 12, 14, 16, 20, 24, 30, 40].find((n) => n > o.type.word.length) : undefined;
21
23
  const type = o.type
22
- ? `<label class="${p}-confirm-field"><span class="${p}-confirm-label">${esc(o.type.label)}</span><input class="${p}-confirm-input" type="text" name="confirm_word" required pattern="${esc(pattern(o.type.word))}" autocomplete="off" autocapitalize="off" spellcheck="false"></label>`
24
+ ? `<label class="${p}-confirm-field"><span class="${p}-confirm-label">${esc(o.type.label)}</span><input class="${p}-confirm-input${wordSize ? ` wb-ui-size-${wordSize}` : ""}" type="text" name="confirm_word" required pattern="${esc(pattern(o.type.word))}" autocomplete="off" autocapitalize="off" spellcheck="false"></label>`
23
25
  : "";
24
26
  return `<details class="${p}-confirm"${o.open ? " open" : ""}><summary class="${p}-confirm-open ${esc(o.askClass)}"><span class="${p}-confirm-ask">${esc(o.ask)}</span><span class="${p}-confirm-keep">${esc(o.no)}</span></summary><form class="${p}-confirm-form" method="post" action="${esc(o.endpoint)}">${hidden}<p class="${p}-confirm-question">${esc(o.question)}</p>${o.consequence ? `<p class="${p}-confirm-consequence">${esc(o.consequence)}</p>` : ""}${reason}${o.extra ?? ""}${type}<button class="${p}-confirm-yes" type="submit">${esc(o.yes)}</button></form></details>`;
25
27
  }
package/dist/errors.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type NudgesErrorCode =
2
- /** workbench/nudges.json is out of shape (or a rule has more steps than max_steps). */
2
+ /** workbench/nudges.json is out of shape (or a rule has more steps than max_steps), or Undo was asked for before the workbench_nudges_undo migration. */
3
3
  "bad_config"
4
4
  /** A call's arguments are out of shape. */
5
5
  | "bad_input"
@@ -11,6 +11,8 @@ export type NudgesErrorCode =
11
11
  | "not_allowed"
12
12
  /** Not needed arrived without the answer to "Are you sure?" (confirm=yes). Nothing was changed. */
13
13
  | "confirm_needed"
14
+ /** Undo refused: the same rule has started again for the subject since it was dismissed. Nothing was changed. */
15
+ | "started_again"
14
16
  /** The database refused or failed. */
15
17
  | "store_failed";
16
18
  export declare class NudgesError extends Error {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export { createNudges, type NudgeContext, type NudgeLink, type NudgeOwner, type NudgeRefresh, type Nudges, type NudgesAi, type NudgesClient, type NudgesMailer, type NudgesOptions, type NudgesPlans, type StartRequest, type TouchKind } from "./nudges.ts";
2
2
  export { checkNudgeConfig, MAX_STEPS, nudgeProblems } from "./config.ts";
3
- export { nudgesMigration } from "./migration.ts";
3
+ export { nudgesMigration, nudgesMigrations } from "./migration.ts";
4
+ export { nudgesUndoMigration } from "./migration-undo.ts";
4
5
  export { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.ts";
5
- export { nudgeAction, renderNudge, renderNudgeList, type ActionResult, type ListOptions, type Words } from "./ui.ts";
6
+ export { nudgeAction, renderNudge, renderNudgeList, renderUndo, type ActionResult, type ListOptions, type Words } from "./ui.ts";
6
7
  export { confirmed, renderConfirm, type ConfirmOptions } from "./confirm.ts";
7
8
  export { CATALOGUE_WORDS, NUDGE_WORDS, NUDGE_WORD_KEYS, type NudgeWordKey } from "./words.ts";
8
9
  export { NUDGE_STYLES } from "./styles.ts";
package/dist/index.js CHANGED
@@ -6,9 +6,10 @@
6
6
  // app's cron every 15 minutes. Nudges never message the business's customer.
7
7
  export { createNudges } from "./nudges.js";
8
8
  export { checkNudgeConfig, MAX_STEPS, nudgeProblems } from "./config.js";
9
- export { nudgesMigration } from "./migration.js";
9
+ export { nudgesMigration, nudgesMigrations } from "./migration.js";
10
+ export { nudgesUndoMigration } from "./migration-undo.js";
10
11
  export { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.js";
11
- export { nudgeAction, renderNudge, renderNudgeList } from "./ui.js";
12
+ export { nudgeAction, renderNudge, renderNudgeList, renderUndo } from "./ui.js";
12
13
  export { confirmed, renderConfirm } from "./confirm.js";
13
14
  export { CATALOGUE_WORDS, NUDGE_WORDS, NUDGE_WORD_KEYS } from "./words.js";
14
15
  export { NUDGE_STYLES } from "./styles.js";
@@ -0,0 +1,4 @@
1
+ export declare const nudgesUndoMigration: {
2
+ up: string;
3
+ down: string;
4
+ };
@@ -0,0 +1,104 @@
1
+ // Nudges' second migration: Undo for Not needed (docs/critical-actions-audit.md,
2
+ // nudges, "add Undo"). A dismissed nudge can be brought back as it was, with
3
+ // one press, straight after.
4
+ //
5
+ // - nudge_dismissals keeps what a dismissed nudge was (waiting, due or
6
+ // snoozed) and when it was dismissed, one row a nudge, deleted with it.
7
+ // - nudges_dismiss ends a nudge as dismissed like nudges_end, but keeps its
8
+ // draft and writes that row, so Undo has something to bring back.
9
+ // - nudges_undismiss puts it back: the same step, due time and draft, and the
10
+ // status it had. Refused when the rule has started again for the subject
11
+ // meanwhile (one active nudge a rule and subject).
12
+ //
13
+ // A kept draft still goes after draft_days (30) at most, and the nudge 90
14
+ // days after it ended, by the first migration's nudges_cleanup, so Undo works
15
+ // while they are there.
16
+ //
17
+ // Only a new table and new functions, with REVOKE and GRANT on them by exact
18
+ // name and argument types, to the service role only: it stays inside what
19
+ // Control applies free on staging (hard rule 6). Until it is applied the
20
+ // package dismisses the old way (the draft deleted) and Undo answers
21
+ // bad_config naming this migration. The down file drops what the up file made.
22
+ export const nudgesUndoMigration = {
23
+ up: `create table public.nudge_dismissals (
24
+ nudge_id uuid primary key references public.nudges (id) on delete cascade,
25
+ status text not null check (status in ('waiting', 'due', 'snoozed')),
26
+ dismissed_at timestamptz not null
27
+ );
28
+
29
+ comment on table public.nudge_dismissals is 'What a dismissed nudge was before Not needed (workbench-nudges), so Undo can bring it back. A status and a time only. Deleted with the nudge. Service role only.';
30
+
31
+ alter table public.nudge_dismissals enable row level security;
32
+
33
+ revoke all on public.nudge_dismissals from anon, authenticated;
34
+
35
+ -- Not needed: ends an active nudge as dismissed with why, keeping its draft
36
+ -- and what it was for Undo. False when it has already ended.
37
+ create function public.nudges_dismiss(p_nudge uuid, p_reason text, p_now timestamptz)
38
+ returns boolean
39
+ language plpgsql
40
+ security invoker
41
+ set search_path = ''
42
+ as $$
43
+ declare
44
+ n public.nudges;
45
+ begin
46
+ select * into n from public.nudges where id = p_nudge and status in ('waiting', 'due', 'snoozed') for update;
47
+ if not found then
48
+ return false;
49
+ end if;
50
+ update public.nudges
51
+ set status = 'dismissed', stop_reason = left(p_reason, 200), ended_at = p_now, claim = null, claimed_until = null, updated_at = p_now
52
+ where id = p_nudge;
53
+ insert into public.nudge_dismissals (nudge_id, status, dismissed_at) values (p_nudge, n.status, p_now)
54
+ on conflict (nudge_id) do update set status = excluded.status, dismissed_at = excluded.dismissed_at;
55
+ return true;
56
+ end;
57
+ $$;
58
+
59
+ -- Undo: brings a dismissed nudge back as it was. { ok, nudge } or
60
+ -- { ok: false, why }: not_dismissed (no such nudge, not dismissed, or
61
+ -- dismissed before this migration) or started_again (the rule is active for
62
+ -- the subject again).
63
+ create function public.nudges_undismiss(p_nudge uuid, p_now timestamptz)
64
+ returns jsonb
65
+ language plpgsql
66
+ security invoker
67
+ set search_path = ''
68
+ as $$
69
+ declare
70
+ n public.nudges;
71
+ d public.nudge_dismissals;
72
+ begin
73
+ select * into n from public.nudges where id = p_nudge and status = 'dismissed' for update;
74
+ if not found then
75
+ return jsonb_build_object('ok', false, 'why', 'not_dismissed');
76
+ end if;
77
+ select * into d from public.nudge_dismissals where nudge_id = p_nudge;
78
+ if not found then
79
+ return jsonb_build_object('ok', false, 'why', 'not_dismissed');
80
+ end if;
81
+ perform pg_advisory_xact_lock(hashtext('workbench-nudges:' || n.rule || ':' || n.subject_type || ':' || n.subject_id));
82
+ if exists (select 1 from public.nudges o where o.rule = n.rule and o.subject_type = n.subject_type and o.subject_id = n.subject_id and o.id <> n.id and o.status in ('waiting', 'due', 'snoozed')) then
83
+ return jsonb_build_object('ok', false, 'why', 'started_again');
84
+ end if;
85
+ update public.nudges
86
+ set status = d.status, stop_reason = null, ended_at = null, claim = null, claimed_until = null, updated_at = p_now
87
+ where id = p_nudge
88
+ returning * into n;
89
+ delete from public.nudge_dismissals where nudge_id = p_nudge;
90
+ return jsonb_build_object('ok', true, 'nudge', public.nudges_row(n));
91
+ end;
92
+ $$;
93
+
94
+ revoke execute on function public.nudges_dismiss(uuid, text, timestamptz) from public, anon, authenticated;
95
+ revoke execute on function public.nudges_undismiss(uuid, timestamptz) from public, anon, authenticated;
96
+ grant execute on function public.nudges_dismiss(uuid, text, timestamptz) to service_role;
97
+ grant execute on function public.nudges_undismiss(uuid, timestamptz) to service_role;
98
+ grant select, insert, update, delete on public.nudge_dismissals to service_role;
99
+ `,
100
+ down: `drop function public.nudges_undismiss(uuid, timestamptz);
101
+ drop function public.nudges_dismiss(uuid, text, timestamptz);
102
+ drop table public.nudge_dismissals;
103
+ `,
104
+ };
@@ -2,3 +2,10 @@ export declare const nudgesMigration: {
2
2
  up: string;
3
3
  down: string;
4
4
  };
5
+ /** Every nudges migration, in order. `npx workbench-nudges migration` writes the ones a project doesn't have yet. */
6
+ export declare const nudgesMigrations: readonly {
7
+ name: string;
8
+ about: string;
9
+ up: string;
10
+ down: string;
11
+ }[];
package/dist/migration.js CHANGED
@@ -23,6 +23,7 @@
23
23
  //
24
24
  // It creates functions, so Control asks for approval to apply it even on
25
25
  // staging. The down file drops everything the up file made.
26
+ import { nudgesUndoMigration } from "./migration-undo.js";
26
27
  export const nudgesMigration = {
27
28
  up: `create table public.nudges (
28
29
  id uuid primary key default gen_random_uuid(),
@@ -376,3 +377,8 @@ drop table public.nudge_drafts;
376
377
  drop table public.nudges;
377
378
  `,
378
379
  };
380
+ /** Every nudges migration, in order. `npx workbench-nudges migration` writes the ones a project doesn't have yet. */
381
+ export const nudgesMigrations = [
382
+ { name: "workbench_nudges", about: "follow-up nudges (docs/capabilities/09-follow-up-nudges.md)", ...nudgesMigration },
383
+ { name: "workbench_nudges_undo", about: "Undo for Not needed", ...nudgesUndoMigration },
384
+ ];
package/dist/nudges.d.ts CHANGED
@@ -135,8 +135,16 @@ export interface Nudges {
135
135
  touch(subject: Subject, kind: TouchKind | (string & {})): Promise<void>;
136
136
  /** Hides it until `until`; it comes due again then, with a fresh draft. */
137
137
  snooze(nudgeId: string, until: Date): Promise<void>;
138
- /** The owner doesn't want it: ended, its draft deleted. */
138
+ /** The owner doesn't want it (Not needed): ended, its draft kept for Undo. Without the workbench_nudges_undo migration, its draft is deleted and it can't be undone. */
139
139
  dismiss(nudgeId: string, reason?: string): Promise<void>;
140
+ /**
141
+ * Undo for Not needed: brings a dismissed nudge back as it was (its step,
142
+ * due time, draft and status). unknown_nudge when it isn't dismissed (or was
143
+ * dismissed before the migration, or the clean-up has deleted it);
144
+ * started_again when the rule has started again for the subject meanwhile;
145
+ * bad_config without the workbench_nudges_undo migration.
146
+ */
147
+ undoDismiss(nudgeId: string): Promise<Nudge>;
140
148
  /** The account's due nudges, the longest waiting first, each with its draft: for the app's Waiting for you list. */
141
149
  due(account: string): Promise<DueNudge[]>;
142
150
  /** One nudge, or null. */
package/dist/nudges.js CHANGED
@@ -19,6 +19,9 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
19
  const EVENT = /^[a-z][a-z0-9_]{0,39}$/;
20
20
  const LEASE_MS = 10 * 60_000;
21
21
  const NINETY_DAYS_MS = 90 * 86_400_000;
22
+ /** PostgREST's "no such function" (PGRST202), or Postgres's own (42883): a migration isn't applied yet. */
23
+ const missingFunction = (error) => error?.code === "PGRST202" || error?.code === "42883";
24
+ const UNDO_MIGRATION = "Undo needs the workbench_nudges_undo migration: run npx workbench-nudges migration and apply it";
22
25
  async function call(db, what, fn, args) {
23
26
  const { data, error } = await db.rpc(fn, args);
24
27
  if (error)
@@ -185,9 +188,34 @@ export function createNudges(opts) {
185
188
  async dismiss(id, reason) {
186
189
  const nid = nudgeId(id);
187
190
  const why = reason === undefined || reason === "" ? "dismissed" : text(reason, "reason", 200);
188
- if (!(await end(nid, "dismissed", why, null, now())))
191
+ const at = now();
192
+ const { data, error } = await db.rpc("nudges_dismiss", { p_nudge: nid, p_reason: why, p_now: at.toISOString() });
193
+ let ok;
194
+ if (!error)
195
+ ok = data === true;
196
+ // Before the undo migration: the old way, its draft deleted.
197
+ else if (missingFunction(error))
198
+ ok = await end(nid, "dismissed", why, null, at);
199
+ else
200
+ throw new NudgesError("store_failed", `dismiss: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
201
+ if (!ok)
189
202
  throw new NudgesError("unknown_nudge", "dismiss: no such nudge, or it has ended");
190
203
  },
204
+ async undoDismiss(id) {
205
+ const nid = nudgeId(id);
206
+ const { data, error } = await db.rpc("nudges_undismiss", { p_nudge: nid, p_now: now().toISOString() });
207
+ if (error) {
208
+ if (missingFunction(error))
209
+ throw new NudgesError("bad_config", UNDO_MIGRATION);
210
+ throw new NudgesError("store_failed", `undo: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
211
+ }
212
+ const r = data;
213
+ if (r?.ok && r.nudge)
214
+ return norm(r.nudge);
215
+ if (r?.why === "started_again")
216
+ throw new NudgesError("started_again", NUDGE_WORDS.en["error.started_again"]);
217
+ throw new NudgesError("unknown_nudge", "undo: no such nudge, or it can't be brought back");
218
+ },
191
219
  async due(account) {
192
220
  const rows = (await call(db, "due", "nudges_due", { p_account: text(account, "account", 200) })) ?? [];
193
221
  return rows.map((row) => {
package/dist/styles.js CHANGED
@@ -69,6 +69,9 @@ export const NUDGE_STYLES = {
69
69
  },
70
70
  { name: "wb-nudge-snooze", element: "button", about: "Remind me tomorrow", css: `${button};color:${v("text")};background:transparent;border:1px solid ${v("line")}`, states: [focus] },
71
71
  { name: "wb-nudge-dismiss", element: "summary", about: "Not needed: opens \"Are you sure?\"", css: `${button};color:${v("muted")};background:transparent;border:1px solid transparent`, states: [focus] },
72
+ { name: "wb-nudge-undone", element: "p", about: "A follow-up just stopped with Not needed, with Undo", css: `display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;justify-content:space-between;margin:0 0 .75rem;padding:.5rem .75rem;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
73
+ { name: "wb-nudge-undone-text", element: "span", about: "\"Stopped following up Maria · Sat 12 Dec.\"", css: "min-width:0;overflow-wrap:anywhere" },
74
+ { name: "wb-nudge-undo", element: "button", about: "Undo: brings the follow-up back as it was", css: `${button};color:${v("accent")};background:transparent;border:1px solid ${v("accent")}`, states: [focus] },
72
75
  ...confirmStyles("wb-nudge", v, { reason: true }),
73
76
  ],
74
77
  };
package/dist/ui.d.ts CHANGED
@@ -14,16 +14,28 @@ export interface ListOptions {
14
14
  replyBox?: (draft: NudgeDraft, opts: {
15
15
  hidden?: Readonly<Record<string, string>>;
16
16
  }) => string;
17
+ /** Follow-ups just stopped with Not needed (the nudge from nudgeAction's answer), each shown at the top with Undo. `title` is the app's label for it. */
18
+ dismissed?: readonly {
19
+ id: string;
20
+ title?: string;
21
+ }[];
17
22
  }
18
23
  /** One due nudge: what it's about, why, which step, the draft and its buttons. */
19
24
  export declare function renderNudge(n: DueNudge, o: ListOptions): string;
20
- /** The account's Waiting for you list (from due()), with its count. */
25
+ /** The line a follow-up just stopped with Not needed shows, with Undo: one press, which brings it back as it was. */
26
+ export declare function renderUndo(n: {
27
+ id: string;
28
+ title?: string;
29
+ }, o: Pick<ListOptions, "endpoint" | "t" | "lang">): string;
30
+ /** The account's Waiting for you list (from due()), with its count, and an Undo line for each follow-up just stopped (`dismissed`). */
21
31
  export declare function renderNudgeList(due: readonly DueNudge[], o: ListOptions): string;
22
32
  export interface ActionResult {
23
33
  status: number;
34
+ /** `nudge` is the nudge's id: after dismiss, pass it back as ListOptions.dismissed so the list shows its Undo. */
24
35
  body: {
25
36
  ok: true;
26
37
  action: string;
38
+ nudge: string;
27
39
  } | {
28
40
  ok: false;
29
41
  error: string;
@@ -35,7 +47,8 @@ export interface ActionResult {
35
47
  * fields here with the signed-in owner's account: `sent` (the follow-up went:
36
48
  * touch we_replied), `snooze` (back in a day, out of the quiet hours) or
37
49
  * `dismiss` (with an optional reason; needs confirm=yes, or it is refused
38
- * with `confirm_needed`, 409, and nothing changes). A nudge of another
50
+ * with `confirm_needed`, 409, and nothing changes) or `undo` (brings a
51
+ * dismissed nudge back as it was; one press, no question). A nudge of another
39
52
  * account is answered as unknown.
40
53
  */
41
54
  export declare function nudgeAction(nudges: Nudges, body: Record<string, unknown>, account: string, now?: Date): Promise<ActionResult>;
package/dist/ui.js CHANGED
@@ -7,7 +7,9 @@
7
7
  // REPLY_SCRIPT); otherwise a plain text box to copy from. Every element
8
8
  // carries a wb-nudge-* class (NUDGE_STYLES), and every button is at least
9
9
  // 44 px tall. Not needed asks "Are you sure?" first (renderConfirm), and
10
- // nudgeAction refuses a dismiss without confirm=yes.
10
+ // nudgeAction refuses a dismiss without confirm=yes. Once dismissed, the list
11
+ // shows a line for it with Undo (one press, no question: it only puts the
12
+ // follow-up back as it was).
11
13
  import { confirmed, renderConfirm } from "./confirm.js";
12
14
  import { NudgesError } from "./errors.js";
13
15
  import { addDuration, outOfQuiet } from "./time.js";
@@ -40,7 +42,7 @@ export function renderNudge(n, o) {
40
42
  ? o.replyBox(n.draft, { hidden: { nudge: n.id } })
41
43
  : `<textarea class="wb-nudge-text" readonly rows="5" lang="${n.draft.language === "en" ? "en" : "fil"}">${esc(n.draft.text)}</textarea>`
42
44
  : `<p class="wb-nudge-none">${esc(w("no_draft"))}</p>`;
43
- // Not needed ends the follow-up and deletes its draft for good, so it asks first.
45
+ // Not needed ends the follow-up (Undo brings it back), so it asks first.
44
46
  const dismiss = renderConfirm({
45
47
  prefix: "wb-nudge",
46
48
  endpoint: o.endpoint,
@@ -56,13 +58,20 @@ export function renderNudge(n, o) {
56
58
  const cls = ["wb-nudge", n.reason_code !== "no_reply" ? "wb-nudge-taken" : ""].filter(Boolean).join(" ");
57
59
  return `<article class="${cls}" id="wb-nudge-${esc(n.id)}">${title ? `<h3 class="wb-nudge-title">${esc(title)}</h3>` : ""}<p class="wb-nudge-reason">${esc(reason)}</p><p class="wb-nudge-step">${esc(w("step", { step: n.step, steps: n.steps }))}</p><div class="wb-nudge-draft">${draft}</div><div class="wb-nudge-actions">${form("sent", "wb-nudge-sent", w("sent"))}${form("snooze", "wb-nudge-snooze", w("snooze"))}${dismiss}</div></article>`;
58
60
  }
59
- /** The account's Waiting for you list (from due()), with its count. */
61
+ /** The line a follow-up just stopped with Not needed shows, with Undo: one press, which brings it back as it was. */
62
+ export function renderUndo(n, o) {
63
+ const w = words(o);
64
+ const said = n.title ? w("undo.done", { title: n.title }) : w("undo.done_untitled");
65
+ return `<p class="wb-nudge-undone" role="status"><span class="wb-nudge-undone-text">${esc(said)}</span><form class="wb-nudge-form" method="post" action="${esc(o.endpoint)}"><input type="hidden" name="nudge" value="${esc(n.id)}"><input type="hidden" name="action" value="undo"><button class="wb-nudge-undo" type="submit">${esc(w("undo"))}</button></form></p>`;
66
+ }
67
+ /** The account's Waiting for you list (from due()), with its count, and an Undo line for each follow-up just stopped (`dismissed`). */
60
68
  export function renderNudgeList(due, o) {
61
69
  const w = words(o);
70
+ const undo = (o.dismissed ?? []).map((n) => renderUndo(n, o)).join("");
62
71
  if (due.length === 0)
63
- return `<section class="wb-nudge-list"><h2 class="wb-nudge-list-title">${esc(w("list.title"))}</h2><p class="wb-nudge-empty">${esc(w("list.empty"))}</p></section>`;
72
+ return `<section class="wb-nudge-list"><h2 class="wb-nudge-list-title">${esc(w("list.title"))}</h2>${undo}<p class="wb-nudge-empty">${esc(w("list.empty"))}</p></section>`;
64
73
  const items = due.map((n) => `<li class="wb-nudge-item">${renderNudge(n, o)}</li>`).join("");
65
- return `<section class="wb-nudge-list"><h2 class="wb-nudge-list-title">${esc(w("list.title"))} <span class="wb-nudge-count">${due.length}</span></h2><ul class="wb-nudge-items">${items}</ul></section>`;
74
+ return `<section class="wb-nudge-list"><h2 class="wb-nudge-list-title">${esc(w("list.title"))} <span class="wb-nudge-count">${due.length}</span></h2>${undo}<ul class="wb-nudge-items">${items}</ul></section>`;
66
75
  }
67
76
  /** Not needed can't be undone, so the post must carry the answer to "Are you sure?" (confirm=yes, which renderConfirm's button sends). */
68
77
  function needConfirm(body) {
@@ -74,17 +83,24 @@ function needConfirm(body) {
74
83
  * fields here with the signed-in owner's account: `sent` (the follow-up went:
75
84
  * touch we_replied), `snooze` (back in a day, out of the quiet hours) or
76
85
  * `dismiss` (with an optional reason; needs confirm=yes, or it is refused
77
- * with `confirm_needed`, 409, and nothing changes). A nudge of another
86
+ * with `confirm_needed`, 409, and nothing changes) or `undo` (brings a
87
+ * dismissed nudge back as it was; one press, no question). A nudge of another
78
88
  * account is answered as unknown.
79
89
  */
80
90
  export async function nudgeAction(nudges, body, account, now = new Date()) {
81
91
  try {
82
92
  const action = String(body.action ?? "");
83
- if (!["sent", "snooze", "dismiss"].includes(action))
84
- throw new NudgesError("bad_input", "action must be sent, snooze or dismiss");
93
+ if (!["sent", "snooze", "dismiss", "undo"].includes(action))
94
+ throw new NudgesError("bad_input", "action must be sent, snooze, dismiss or undo");
85
95
  if (action === "dismiss")
86
96
  needConfirm(body);
87
97
  const n = await nudges.get(String(body.nudge ?? ""));
98
+ if (action === "undo") {
99
+ if (!n || n.account !== account || n.status !== "dismissed")
100
+ throw new NudgesError("unknown_nudge", "no such nudge, or it can't be brought back");
101
+ await nudges.undoDismiss(n.id);
102
+ return { status: 200, body: { ok: true, action, nudge: n.id } };
103
+ }
88
104
  if (!n || n.account !== account || !["waiting", "due", "snoozed"].includes(n.status))
89
105
  throw new NudgesError("unknown_nudge", "no such nudge, or it has ended");
90
106
  if (action === "sent")
@@ -95,11 +111,11 @@ export async function nudgeAction(nudges, body, account, now = new Date()) {
95
111
  }
96
112
  else
97
113
  await nudges.dismiss(n.id, typeof body.reason === "string" && body.reason.trim() ? body.reason.trim().slice(0, 200) : undefined);
98
- return { status: 200, body: { ok: true, action } };
114
+ return { status: 200, body: { ok: true, action, nudge: n.id } };
99
115
  }
100
116
  catch (e) {
101
117
  if (e instanceof NudgesError) {
102
- const status = e.code === "unknown_nudge" ? 404 : e.code === "store_failed" ? 502 : e.code === "bad_config" ? 500 : e.code === "not_allowed" ? 403 : e.code === "confirm_needed" ? 409 : 400;
118
+ const status = e.code === "unknown_nudge" ? 404 : e.code === "store_failed" ? 502 : e.code === "bad_config" ? 500 : e.code === "not_allowed" ? 403 : e.code === "confirm_needed" || e.code === "started_again" ? 409 : 400;
103
119
  return { status, body: { ok: false, error: e.code, message: e.message } };
104
120
  }
105
121
  throw e;
package/dist/words.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const NUDGE_WORD_KEYS: readonly ["list.title", "list.empty", "step", "reason.no_reply", "reason.date_unavailable", "reason.not_on_plan", "reason.draft_failed", "reason.no_ai", "no_draft", "sent", "snooze", "dismiss", "unit.minute", "unit.minutes", "unit.hour", "unit.hours", "unit.day", "unit.days", "email.digest.subject", "email.digest.subject_one", "email.due.subject", "email.due.subject_one", "email.body", "email.body_one", "email.open", "email.footer", "dismiss.question", "dismiss.question_untitled", "dismiss.consequence", "dismiss.reason", "dismiss.yes", "confirm.no", "error.confirm_needed"];
1
+ export declare const NUDGE_WORD_KEYS: readonly ["list.title", "list.empty", "step", "reason.no_reply", "reason.date_unavailable", "reason.not_on_plan", "reason.draft_failed", "reason.no_ai", "no_draft", "sent", "snooze", "dismiss", "unit.minute", "unit.minutes", "unit.hour", "unit.hours", "unit.day", "unit.days", "email.digest.subject", "email.digest.subject_one", "email.due.subject", "email.due.subject_one", "email.body", "email.body_one", "email.open", "email.footer", "dismiss.question", "dismiss.question_untitled", "dismiss.consequence", "dismiss.reason", "dismiss.yes", "confirm.no", "error.confirm_needed", "undo", "undo.done", "undo.done_untitled", "error.started_again"];
2
2
  export type NudgeWordKey = (typeof NUDGE_WORD_KEYS)[number];
3
3
  /** The words by language, as `ui.wbnudge.<key>` would hold them. */
4
4
  export declare const NUDGE_WORDS: Readonly<Record<"en" | "tl" | "taglish", Readonly<Record<NudgeWordKey, string>>>>;
package/dist/words.js CHANGED
@@ -39,6 +39,10 @@ export const NUDGE_WORD_KEYS = [
39
39
  "dismiss.yes",
40
40
  "confirm.no",
41
41
  "error.confirm_needed",
42
+ "undo",
43
+ "undo.done",
44
+ "undo.done_untitled",
45
+ "error.started_again",
42
46
  ];
43
47
  const en = {
44
48
  "list.title": "Waiting for you",
@@ -69,11 +73,15 @@ const en = {
69
73
  "email.footer": "This is a reminder for you. Nothing was sent to your customers.",
70
74
  "dismiss.question": "Stop following up {title}?",
71
75
  "dismiss.question_untitled": "Stop this follow-up?",
72
- "dismiss.consequence": "Its draft is deleted and no more reminders come for it. Nobody is emailed. This can't be undone.",
76
+ "dismiss.consequence": "No more reminders come for it. Nobody is emailed. You can bring it back with Undo straight after.",
73
77
  "dismiss.reason": "Why (optional, only you see it)",
74
78
  "dismiss.yes": "Yes, stop this follow-up",
75
79
  "confirm.no": "No, keep it",
76
80
  "error.confirm_needed": "Please confirm first. Nothing has changed.",
81
+ undo: "Undo",
82
+ "undo.done": "Stopped following up {title}.",
83
+ "undo.done_untitled": "Follow-up stopped.",
84
+ "error.started_again": "This follow-up has started again since, so there is nothing to bring back. Nothing has changed.",
77
85
  };
78
86
  const tl = {
79
87
  "list.title": "Naghihintay sa iyo",
@@ -104,11 +112,15 @@ const tl = {
104
112
  "email.footer": "Paalala lang ito para sa inyo. Walang naipadala sa inyong mga customer.",
105
113
  "dismiss.question": "Itigil ang pag-follow up sa {title}?",
106
114
  "dismiss.question_untitled": "Itigil ang follow-up na ito?",
107
- "dismiss.consequence": "Mabubura ang draft nito at wala nang paalala para dito. Walang ie-email. Hindi na ito maibabalik.",
115
+ "dismiss.consequence": "Wala nang paalala para dito. Walang ie-email. Maibabalik ninyo ito gamit ang Ibalik pagkatapos.",
108
116
  "dismiss.reason": "Bakit (hindi kailangan, kayo lang ang makakakita)",
109
117
  "dismiss.yes": "Oo, itigil ang follow-up na ito",
110
118
  "confirm.no": "Huwag, panatilihin",
111
119
  "error.confirm_needed": "Pakikumpirma muna. Walang nagbago.",
120
+ undo: "Ibalik",
121
+ "undo.done": "Itinigil ang pag-follow up sa {title}.",
122
+ "undo.done_untitled": "Itinigil ang follow-up.",
123
+ "error.started_again": "Nagsimula ulit ang follow-up na ito, kaya walang maibabalik. Walang nagbago.",
112
124
  };
113
125
  const taglish = {
114
126
  "list.title": "Waiting for you",
@@ -139,11 +151,15 @@ const taglish = {
139
151
  "email.footer": "Reminder lang ito para sa inyo. Walang na-send sa mga customer n'yo.",
140
152
  "dismiss.question": "I-stop ang pag-follow up sa {title}?",
141
153
  "dismiss.question_untitled": "I-stop ang follow-up na ito?",
142
- "dismiss.consequence": "Made-delete ang draft nito at wala nang reminders para dito. Walang ie-email. Hindi na ito maibabalik.",
154
+ "dismiss.consequence": "Wala nang reminders para dito. Walang ie-email. Pwede n'yo itong ibalik gamit ang Undo pagkatapos.",
143
155
  "dismiss.reason": "Bakit (optional, kayo lang ang makakakita)",
144
156
  "dismiss.yes": "Oo, i-stop ang follow-up",
145
157
  "confirm.no": "Hindi, i-keep",
146
158
  "error.confirm_needed": "Paki-confirm muna. Walang nagbago.",
159
+ undo: "Undo",
160
+ "undo.done": "Na-stop ang pag-follow up sa {title}.",
161
+ "undo.done_untitled": "Na-stop ang follow-up.",
162
+ "error.started_again": "Nag-start ulit ang follow-up na ito, kaya walang maibabalik. Walang nagbago.",
147
163
  };
148
164
  /** The words by language, as `ui.wbnudge.<key>` would hold them. */
149
165
  export const NUDGE_WORDS = { en, tl, taglish };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-nudges",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Follow-up nudges for Workbench apps: remind the business to follow up when a conversation goes quiet (\"no reply in 3 days\"), with the follow-up already drafted by the reply drafter when it comes due. One scan from the app's cron, quiet hours, at most three steps, and a daily email digest to the owner. Never messages the business's customer.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",