feat(admin): make the token lifetimes, cart hold and greeting configurable (#136)
Giving the customer emails a tab of their own (#135) made a family of related holes visible: an admin could edit the wording of every customer email, but not the facts that wording asserted, and two templates could not address the customer at all. Both token lifetimes were hardcoded twice. VERIFY_TOKEN_TTL_MS sat in routes/customers.ts while the verification body separately said "This link expires in 24 hours", and RESET_TOKEN_TTL_MS sat beside a body separately saying "one hour". The prose was not derived from the constant, it was a second hand-written copy of the same fact — so making the constants configurable without addressing that would have made things worse, not better: the setting moves to two hours and the email keeps confidently promising one. Both are now settings, and both templates state their lifetime through an {{expiresIn}} placeholder rendered from the setting. The cart reminder gains {{holdDuration}} for the same reason. Per-item deadlines were already inside {{itemList}}, but there was no way to write a sentence about the hold itself without hardcoding a number the cart expiry setting could change underneath the author. All three durations render through one formatDuration(), so the reset email and the cart reminder say "one hour" the same way rather than in two authors' phrasing. A fractional hour drops to minutes, because "0.5 hours" reads badly and "1.5 hours" reads worse in a sentence a customer is meant to act on. Every template now offers greeting, firstName and lastName. favoriteSold and favoriteWithdrawn previously offered only itemName and siteUrl and could not address anyone — the query behind them never selected a name, so it does now. The greeting itself is two settings, a format and a fallback, rather than the wording baked into greeting(). The fallback is separate rather than the format with the name edited out: that editing is guesswork that has to be right every time, and getting it wrong ships "Hi ," to everyone who registered while first names were still optional (#106). Those customers exist, which is why greeting() guarded the case in the first place. The admin preview renders the durations and the greeting from the live settings rather than from a static sample. The preview exists so an admin sees the email that will be sent, and a sample reading "one hour" while the setting says two is the precise failure these placeholders were added to remove. Settings are read through a new adminSettings accessor. cart_expiry_hours was previously read by an inline query in two places, each with its own `|| '24'`; with five settings and read sites across three routes and the cron job, a default written twice is a default that will eventually disagree with itself. Values are stored as text, so each definition declares how to read it back — numbers were the only kind until the greeting format arrived. The new placeholders are available but never required, so every template an admin has already saved keeps rendering and keeps sending. Also fixes updateAdminSettings announcing success for a save the server refused: it returned the 400 body as though it were the saved settings, so the form reported "Settings saved" either way. Closes #136
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { pool } from './db';
|
||||
|
||||
/**
|
||||
* Every admin-configurable setting, in one table.
|
||||
*
|
||||
* `cart_expiry_hours` used to be read by an inline query in two places, each
|
||||
* with its own `|| '24'`. With several settings and read sites scattered across
|
||||
* routes and the cron job that stops being tenable: a default written twice is
|
||||
* a default that will eventually disagree with itself. Adding a setting means
|
||||
* adding a row here and nothing else.
|
||||
*
|
||||
* Values are stored as text, so each row declares how to read it back. Numbers
|
||||
* were the only kind until the greeting format arrived; typing it per setting
|
||||
* rather than assuming means the next string one costs nothing.
|
||||
*/
|
||||
const DEFINITIONS = [
|
||||
{ key: 'cart_expiry_hours', name: 'cartExpiryHours', type: 'hours', fallback: 24 },
|
||||
{ key: 'verify_token_hours', name: 'verifyTokenHours', type: 'hours', fallback: 24 },
|
||||
{ key: 'password_reset_hours', name: 'passwordResetHours', type: 'hours', fallback: 1 },
|
||||
{ key: 'greeting_format', name: 'greetingFormat', type: 'text', fallback: 'Hi {{firstName}},' },
|
||||
{ key: 'greeting_fallback', name: 'greetingFallback', type: 'text', fallback: 'Hi,' }
|
||||
] as const;
|
||||
|
||||
type Definition = (typeof DEFINITIONS)[number];
|
||||
|
||||
export type SettingName = Definition['name'];
|
||||
|
||||
export type HoursSettingName = Extract<Definition, { type: 'hours' }>['name'];
|
||||
export type TextSettingName = Extract<Definition, { type: 'text' }>['name'];
|
||||
|
||||
export type AdminSettings = Record<HoursSettingName, number> & Record<TextSettingName, string>;
|
||||
|
||||
export const HOURS_SETTINGS: readonly HoursSettingName[] = DEFINITIONS.filter(
|
||||
(d): d is Extract<Definition, { type: 'hours' }> => d.type === 'hours'
|
||||
).map(d => d.name);
|
||||
|
||||
export const TEXT_SETTINGS: readonly TextSettingName[] = DEFINITIONS.filter(
|
||||
(d): d is Extract<Definition, { type: 'text' }> => d.type === 'text'
|
||||
).map(d => d.name);
|
||||
|
||||
export async function getSettings(): Promise<AdminSettings> {
|
||||
const { rows } = await pool.query(`SELECT key, value FROM admin_settings`);
|
||||
const stored = new Map<string, string>(rows.map(r => [r.key, r.value]));
|
||||
|
||||
const settings = {} as Record<SettingName, number | string>;
|
||||
for (const { key, name, type, fallback } of DEFINITIONS) {
|
||||
const raw = stored.get(key);
|
||||
if (type === 'text') {
|
||||
// An empty format would render every greeting as nothing at all, which
|
||||
// reads as a bug in the email rather than a setting someone cleared.
|
||||
settings[name] = raw !== undefined && raw.trim() !== '' ? raw : fallback;
|
||||
continue;
|
||||
}
|
||||
const parsed = parseFloat(raw ?? '');
|
||||
// A row that is present but unparseable falls back rather than yielding
|
||||
// NaN, which would otherwise reach Date arithmetic and mint a token with an
|
||||
// Invalid Date expiry that no query could ever match.
|
||||
settings[name] = Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
return settings as AdminSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the supplied settings, ignoring names that were not sent.
|
||||
*
|
||||
* Partial rather than whole-object so a caller updating one field does not have
|
||||
* to know the current value of the others to avoid clobbering them.
|
||||
*/
|
||||
export async function updateSettings(
|
||||
values: Partial<Record<SettingName, number | string>>
|
||||
): Promise<void> {
|
||||
for (const { key, name } of DEFINITIONS) {
|
||||
const value = values[name];
|
||||
if (value === undefined) continue;
|
||||
await pool.query(
|
||||
`INSERT INTO admin_settings (key, value, updated_at) VALUES ($1, $2, now())
|
||||
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = now()`,
|
||||
[key, String(value)]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user