@mccaskie-labs/workbench-contacts 0.0.0-stage → 0.1.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.
@@ -0,0 +1,269 @@
1
+ // createContacts: simple customer records in the app's own database. The
2
+ // app's tools call record() as they meet a person (a form sent, a booking
3
+ // made, a payment taken, a quote sent, a review left, a WhatsApp or Messenger
4
+ // message read), and the owner's pages search, edit, export and delete.
5
+ //
6
+ // The list keeps the least that does the job: the details workbench/
7
+ // contacts.json keeps, and the app's own row ids. Never a message, a review's
8
+ // words, an amount or a card. Marketing consent is unknown until the person
9
+ // says so themselves.
10
+ //
11
+ // Use it with the service client, server side: the functions are the service
12
+ // role's only (see migration.ts). Workbench itself never sees the list.
13
+ import { checkContactSettings } from "./config.js";
14
+ import { toCsv } from "./csv.js";
15
+ import { ContactsError } from "./errors.js";
16
+ import { tidyEmail, tidyMessenger, tidyName, tidyPhone } from "./tidy.js";
17
+ import { SOURCE_KINDS } from "./types.js";
18
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
+ const DAY = 86_400_000;
20
+ async function call(db, what, fn, args) {
21
+ const { data, error } = await db.rpc(fn, args);
22
+ if (error) {
23
+ if (error.code === "23505")
24
+ throw new ContactsError("taken", `${what}: that email, phone or Messenger id belongs to another contact in this account`);
25
+ if (error.code === "23514" || error.code === "22023")
26
+ throw new ContactsError("bad_input", `${what}: ${error.message || "refused"}`);
27
+ throw new ContactsError("store_failed", `${what}: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
28
+ }
29
+ return data;
30
+ }
31
+ function text(v, what, max) {
32
+ if (typeof v !== "string" || !v.trim() || v.trim().length > max)
33
+ throw new ContactsError("bad_input", `${what} must be text, 1 to ${max} characters`);
34
+ return v.trim();
35
+ }
36
+ function contactId(v) {
37
+ if (typeof v !== "string" || !UUID.test(v))
38
+ throw new ContactsError("bad_input", "id must be a contact's id");
39
+ return v.toLowerCase();
40
+ }
41
+ function when(v, now) {
42
+ if (v === undefined)
43
+ return now;
44
+ if (!(v instanceof Date) || Number.isNaN(v.getTime()))
45
+ throw new ContactsError("bad_input", "from.at must be a Date");
46
+ // A source dated in the future would keep the person past their time.
47
+ return v.getTime() > now.getTime() + DAY ? now : v;
48
+ }
49
+ const iso = (v) => (typeof v === "string" && v ? new Date(v).toISOString() : null);
50
+ /** A row with its times as ISO 8601 in UTC (Postgres writes +00:00). */
51
+ function norm(c) {
52
+ const out = { ...c, marketing_at: iso(c.marketing_at), first_seen_at: iso(c.first_seen_at), last_seen_at: iso(c.last_seen_at), counts: c.counts ?? {} };
53
+ if ("events" in out && Array.isArray(out.events))
54
+ out.events = out.events.map((e) => ({ ...e, at: iso(e.at) }));
55
+ return out;
56
+ }
57
+ /** An ILIKE pattern for part of a name or email, with its own wildcards escaped. */
58
+ export function likePattern(query) {
59
+ return `%${query.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
60
+ }
61
+ export function createContacts(opts) {
62
+ const settings = checkContactSettings(opts.settings);
63
+ const { db } = opts;
64
+ const now = opts.now ?? (() => new Date());
65
+ const keep = new Set(settings.keep);
66
+ const notes = settings.notes !== false;
67
+ /** The details this project keeps, tidied; what couldn't be read or isn't kept is named. */
68
+ function details(p) {
69
+ const dropped = [];
70
+ const one = (kind, raw, tidy) => {
71
+ const v = tidy(raw);
72
+ if (v === null)
73
+ return null;
74
+ if (v === undefined || !keep.has(kind)) {
75
+ dropped.push(kind);
76
+ return null;
77
+ }
78
+ return v;
79
+ };
80
+ const person = p && typeof p === "object" ? p : {};
81
+ return {
82
+ name: one("name", person.name, tidyName),
83
+ email: one("email", person.email, tidyEmail),
84
+ phone: one("phone", person.phone, (v) => tidyPhone(v, opts.phone)),
85
+ messenger: one("messenger", person.messenger, tidyMessenger),
86
+ dropped,
87
+ };
88
+ }
89
+ function sourceOf(v, at) {
90
+ const s = v;
91
+ if (!s || typeof s !== "object" || !SOURCE_KINDS.includes(s.kind))
92
+ throw new ContactsError("bad_input", `from.kind must be one of ${SOURCE_KINDS.join(", ")}`);
93
+ return { kind: s.kind, type: text(s.type, "from.type", 60), id: text(s.id, "from.id", 200), at: when(s.at, at) };
94
+ }
95
+ function consentOf(c) {
96
+ if (c === undefined)
97
+ return { value: null, wording: null };
98
+ if (!c || (c.marketing !== "yes" && c.marketing !== "no"))
99
+ throw new ContactsError("bad_input", 'consent.marketing must be "yes" or "no"');
100
+ // A project that sends no marketing keeps no yes; a no is still kept, so it holds if marketing is switched on later.
101
+ if (c.marketing === "yes" && settings.marketing === "off")
102
+ return { value: null, wording: null };
103
+ if (c.marketing === "yes")
104
+ return { value: "yes", wording: text(c.wording, "consent.wording (the words next to the box the person ticked)", 500) };
105
+ return { value: "no", wording: null };
106
+ }
107
+ async function record(req) {
108
+ if (!req || typeof req !== "object")
109
+ throw new ContactsError("bad_input", "record needs { account, person, from }");
110
+ const account = text(req.account, "account", 200);
111
+ const at = now();
112
+ const from = sourceOf(req.from, at);
113
+ const d = details(req.person);
114
+ const consent = consentOf(req.consent);
115
+ if (!settings.sources.includes(from.kind))
116
+ return { contact: null, created: false, dropped: d.dropped, skipped: "source_off" };
117
+ if (!d.email && !d.phone && !d.messenger)
118
+ return { contact: null, created: false, dropped: d.dropped, skipped: "no_detail" };
119
+ const r = await call(db, "record", "contacts_record", {
120
+ p_account: account,
121
+ p_name: d.name,
122
+ p_email: d.email,
123
+ p_phone: d.phone,
124
+ p_messenger: d.messenger,
125
+ p_kind: from.kind,
126
+ p_ref_type: from.type,
127
+ p_ref_id: from.id,
128
+ p_at: from.at.toISOString(),
129
+ p_marketing: consent.value,
130
+ p_wording: consent.wording,
131
+ p_now: at.toISOString(),
132
+ });
133
+ return { contact: norm(r.contact), created: r.created, dropped: d.dropped };
134
+ }
135
+ async function recordForm(req) {
136
+ if (!req || typeof req !== "object" || !req.fields || !req.values)
137
+ throw new ContactsError("bad_input", "recordForm needs { account, fields, values, from }");
138
+ const person = {};
139
+ const first = (kind, pick) => {
140
+ for (const [name, f] of Object.entries(req.fields)) {
141
+ if (f?.personal !== kind || (pick && !pick(name)))
142
+ continue;
143
+ const v = req.values[name];
144
+ if (typeof v === "string" && v.trim())
145
+ return v;
146
+ }
147
+ return undefined;
148
+ };
149
+ person.name = first("name");
150
+ person.email = first("email");
151
+ person.phone = first("phone");
152
+ if (req.messengerField)
153
+ person.messenger = first("handle", (n) => n === req.messengerField);
154
+ return record({ account: req.account, person, from: req.from, ...(req.consent ? { consent: req.consent } : {}) });
155
+ }
156
+ async function get(account, id) {
157
+ const c = await call(db, "get", "contacts_get", { p_account: text(account, "account", 200), p_id: contactId(id) });
158
+ return c ? norm(c) : null;
159
+ }
160
+ async function search(account, o = {}) {
161
+ const limit = o.limit ?? 50;
162
+ const offset = o.offset ?? 0;
163
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200)
164
+ throw new ContactsError("bad_input", "limit must be a whole number from 1 to 200");
165
+ if (!Number.isInteger(offset) || offset < 0)
166
+ throw new ContactsError("bad_input", "offset must be a whole number, 0 or more");
167
+ const q = typeof o.query === "string" ? o.query.replace(/\s+/g, " ").trim().slice(0, 100) : "";
168
+ const digits = q.replace(/\D/g, "");
169
+ const r = await call(db, "search", "contacts_search", {
170
+ p_account: text(account, "account", 200),
171
+ p_pattern: q ? likePattern(q) : null,
172
+ p_digits: digits.length >= 3 && /^[\d\s()+.-]+$/.test(q) ? digits : null,
173
+ p_marketing: o.marketing === true,
174
+ p_limit: limit,
175
+ p_offset: offset,
176
+ });
177
+ const contacts = r.contacts.map(norm);
178
+ return { total: r.total, contacts, ...(offset + contacts.length < r.total ? { next: offset + contacts.length } : {}) };
179
+ }
180
+ async function update(account, id, changes) {
181
+ if (!changes || typeof changes !== "object")
182
+ throw new ContactsError("bad_input", "changes must be an object");
183
+ const set = {};
184
+ const bad = [];
185
+ const tidyNote = (v) => (v === null || (typeof v === "string" && !v.trim()) ? null : typeof v === "string" && v.trim().length <= 1000 ? v.trim() : undefined);
186
+ const fields = [
187
+ ["name", tidyName],
188
+ ["email", tidyEmail],
189
+ ["phone", (v) => tidyPhone(v, opts.phone)],
190
+ ["messenger", tidyMessenger],
191
+ ["note", tidyNote],
192
+ ];
193
+ for (const [k, tidy] of fields) {
194
+ if (!Object.hasOwn(changes, k))
195
+ continue;
196
+ const v = tidy(changes[k]);
197
+ if (v === undefined)
198
+ bad.push(k);
199
+ else if (v !== null && k !== "note" && !keep.has(k))
200
+ bad.push(`${k} (this project doesn't keep it)`);
201
+ else if (v !== null && k === "note" && !notes)
202
+ bad.push("note (notes are off)");
203
+ else
204
+ set[k] = v;
205
+ }
206
+ if (bad.length)
207
+ throw new ContactsError("bad_input", `couldn't read ${bad.join(", ")}`);
208
+ const c = await call(db, "update", "contacts_update", { p_account: text(account, "account", 200), p_id: contactId(id), p_set: set, p_now: now().toISOString() });
209
+ if (!c)
210
+ throw new ContactsError("unknown_contact", "no such contact");
211
+ return norm(c);
212
+ }
213
+ async function setMarketing(account, id, consent) {
214
+ const c = consentOf(consent);
215
+ if (consent.marketing === "yes" && settings.marketing === "off")
216
+ throw new ContactsError("bad_input", 'contacts.json has marketing "off", so no yes is kept');
217
+ const at = now();
218
+ const source = consent.source ?? "owner";
219
+ if (![...SOURCE_KINDS, "owner", "unsubscribe"].includes(source))
220
+ throw new ContactsError("bad_input", "source must be a source kind, owner or unsubscribe");
221
+ const r = await call(db, "marketing", "contacts_marketing", {
222
+ p_account: text(account, "account", 200),
223
+ p_id: contactId(id),
224
+ p_value: c.value,
225
+ p_source: source,
226
+ p_wording: c.wording,
227
+ p_at: at.toISOString(),
228
+ p_now: at.toISOString(),
229
+ });
230
+ if (!r)
231
+ throw new ContactsError("unknown_contact", "no such contact");
232
+ return norm(r);
233
+ }
234
+ async function optOut(account, who) {
235
+ const p = who && typeof who === "object" ? who : {};
236
+ const email = tidyEmail(p.email) ?? null;
237
+ const phone = tidyPhone(p.phone, opts.phone) ?? null;
238
+ const messenger = tidyMessenger(p.messenger) ?? null;
239
+ if (!email && !phone && !messenger)
240
+ throw new ContactsError("bad_input", "optOut needs an email, phone or Messenger id");
241
+ const at = now().toISOString();
242
+ return call(db, "opt out", "contacts_opt_out", { p_account: text(account, "account", 200), p_email: email, p_phone: phone, p_messenger: messenger, p_source: "unsubscribe", p_at: at, p_now: at });
243
+ }
244
+ async function forget(account, id) {
245
+ return call(db, "forget", "contacts_forget", { p_account: text(account, "account", 200), p_id: contactId(id) });
246
+ }
247
+ async function exportCsv(account, o = {}) {
248
+ if (o.marketing && settings.marketing === "off")
249
+ throw new ContactsError("bad_input", 'contacts.json has marketing "off", so there is no mailing list to export');
250
+ const rows = await call(db, "export", "contacts_export", { p_account: text(account, "account", 200), p_marketing: o.marketing === true });
251
+ return toCsv(rows.map(norm), { lang: o.lang ?? "en", timeZone: settings.time_zone, keep, notes });
252
+ }
253
+ async function exportPerson(account, id) {
254
+ const c = await get(account, id);
255
+ if (!c)
256
+ return null;
257
+ return {
258
+ format: 1,
259
+ exported_at: now().toISOString(),
260
+ contact: c,
261
+ kept_because: `To deal with you about your ${[...new Set(c.events.map((e) => e.kind))].join(", ") || "dealings"} with this business. Deleted on request, or ${settings.retention_months ?? 24} months after you were last in touch.`,
262
+ };
263
+ }
264
+ async function cleanup() {
265
+ const n = await call(db, "cleanup", "contacts_cleanup", { p_now: now().toISOString(), p_months: settings.retention_months ?? 24 });
266
+ return { contacts: n };
267
+ }
268
+ return { record, recordForm, get, search, update, setMarketing, optOut, forget, exportCsv, exportPerson, cleanup, settings };
269
+ }
package/dist/csv.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { Contact, DetailKind, Lang } from "./types.ts";
2
+ /** One cell, quoted and defused. */
3
+ export declare function csvCell(v: unknown): string;
4
+ export declare function toCsv(rows: readonly Contact[], o: {
5
+ lang: Lang;
6
+ timeZone: string;
7
+ keep: ReadonlySet<DetailKind>;
8
+ notes: boolean;
9
+ }): string;
package/dist/csv.js ADDED
@@ -0,0 +1,42 @@
1
+ // The owner's spreadsheet: one row a person, UTF-8 with a byte order mark so
2
+ // Excel reads ñ and other letters, and every cell that a spreadsheet would
3
+ // run as a formula (=, +, -, @, tab, return) starts with an apostrophe. A
4
+ // phone (+639171234567) is only digits after its plus, so it is left as it is.
5
+ import { CONTACT_WORDS } from "./words.js";
6
+ const KINDS = ["form", "booking", "payment", "quote", "review", "message", "manual"];
7
+ /** One cell, quoted and defused. */
8
+ export function csvCell(v) {
9
+ let s = v === null || v === undefined ? "" : String(v);
10
+ if (/^[=+\-@\t\r]/.test(s) && !/^\+\d+$/.test(s))
11
+ s = `'${s}`;
12
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
13
+ }
14
+ /** A date in the project's time zone, YYYY-MM-DD, which every spreadsheet reads. */
15
+ function day(isoTime, timeZone) {
16
+ if (!isoTime)
17
+ return "";
18
+ const p = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(isoTime));
19
+ return p;
20
+ }
21
+ export function toCsv(rows, o) {
22
+ const w = CONTACT_WORDS[o.lang] ?? CONTACT_WORDS.en;
23
+ const cols = [];
24
+ const add = (key, cell) => cols.push({ head: w[key], cell });
25
+ if (o.keep.has("name"))
26
+ add("field.name", (c) => c.name);
27
+ if (o.keep.has("email"))
28
+ add("field.email", (c) => c.email);
29
+ if (o.keep.has("phone"))
30
+ add("field.phone", (c) => c.phone);
31
+ if (o.keep.has("messenger"))
32
+ add("field.messenger", (c) => c.messenger);
33
+ add("field.marketing", (c) => w[`marketing.${c.marketing}`]);
34
+ add("field.first_seen", (c) => day(c.first_seen_at, o.timeZone));
35
+ add("field.last_seen", (c) => day(c.last_seen_at, o.timeZone));
36
+ for (const k of KINDS)
37
+ add(`kind.${k}`, (c) => c.counts[k] ?? 0);
38
+ if (o.notes)
39
+ add("field.note", (c) => c.note);
40
+ const lines = [cols.map((c) => csvCell(c.head)).join(","), ...rows.map((r) => cols.map((c) => csvCell(c.cell(r))).join(","))];
41
+ return `${lines.join("\r\n")}\r\n`;
42
+ }
@@ -0,0 +1,15 @@
1
+ export type ContactsErrorCode =
2
+ /** workbench/contacts.json is out of shape. */
3
+ "bad_config"
4
+ /** A call's arguments are out of shape. */
5
+ | "bad_input"
6
+ /** No such contact in this account. */
7
+ | "unknown_contact"
8
+ /** The email, phone or Messenger id belongs to another contact in this account. Nothing was changed. */
9
+ | "taken"
10
+ /** The database refused or failed. */
11
+ | "store_failed";
12
+ export declare class ContactsError extends Error {
13
+ readonly code: ContactsErrorCode;
14
+ constructor(code: ContactsErrorCode, message: string);
15
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words.
3
+ export class ContactsError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "ContactsError";
8
+ this.code = code;
9
+ }
10
+ }
@@ -0,0 +1,12 @@
1
+ export { createContacts, likePattern, type ConsentGiven, type ContactChanges, type Contacts, type ContactsClient, type ContactsOptions, type ExportOptions, type FormFieldInfo, type FormRecordRequest, type PersonExport, type RecordRequest, type RecordResult, type SearchOptions } from "./contacts.ts";
2
+ export { checkContactSettings, contactProblems } from "./config.ts";
3
+ export { contactsMigration } from "./migration.ts";
4
+ export { STARTER_CONTACTS } from "./starters.ts";
5
+ export { contactAction, contactLabel, renderContact, renderContactList, type ActionResult, type ContactPageOptions, type ListOptions, type Words } from "./ui.ts";
6
+ export { CONTACT_WORDS, CONTACT_WORD_KEYS, type ContactWordKey } from "./words.ts";
7
+ export { CONTACT_STYLES } from "./styles.ts";
8
+ export { ContactsError, type ContactsErrorCode } from "./errors.ts";
9
+ export { csvCell } from "./csv.ts";
10
+ export { tidyEmail, tidyPhone, type PhoneCountry } from "./tidy.ts";
11
+ export { DETAIL_KINDS, SOURCE_KINDS } from "./types.ts";
12
+ export type { Contact, ContactDetail, ContactEvent, ContactSettings, DetailKind, Lang, Marketing, PersonDetails, SearchResult, Source, SourceKind } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ // @mccaskie-labs/workbench-contacts: simple customer records. One list of the
2
+ // people a business deals with, in the app's own database (contactsMigration),
3
+ // filled as the app's tools meet them (record), with search, a spreadsheet
4
+ // export, a person's own copy on request, opt-outs that stick, delete on
5
+ // request, and a daily clean-up of people who haven't been back.
6
+ export { createContacts, likePattern } from "./contacts.js";
7
+ export { checkContactSettings, contactProblems } from "./config.js";
8
+ export { contactsMigration } from "./migration.js";
9
+ export { STARTER_CONTACTS } from "./starters.js";
10
+ export { contactAction, contactLabel, renderContact, renderContactList } from "./ui.js";
11
+ export { CONTACT_WORDS, CONTACT_WORD_KEYS } from "./words.js";
12
+ export { CONTACT_STYLES } from "./styles.js";
13
+ export { ContactsError } from "./errors.js";
14
+ export { csvCell } from "./csv.js";
15
+ export { tidyEmail, tidyPhone } from "./tidy.js";
16
+ export { DETAIL_KINDS, SOURCE_KINDS } from "./types.js";
@@ -0,0 +1,4 @@
1
+ export declare const contactsMigration: {
2
+ up: string;
3
+ down: string;
4
+ };