@joelincc/mailroom 0.1.0 → 0.3.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/README.md +47 -5
- package/SECURITY.md +1 -1
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +4 -4
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/package.json +19 -3
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +177 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +42 -1
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +120 -31
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/wrangler.example.jsonc +16 -2
package/src/alert.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// 告警出口:讀者要求退訂卻沒退成時,把「誰、哪張券」送給人工。通用 webhook(POST JSON),不綁任何服務;網址與口令由設定注入。
|
|
2
|
+
// 不 import cloudflare:*。沒設網址時照樣把內容寫進 log(Worker 的 log 只有帳號擁有者看得到;完整券不進 log),並在啟動時警告。
|
|
3
|
+
|
|
4
|
+
export type AlertEvent = 'unsub_mail_no_token' | 'unsub_token_invalid' | 'unsub_write_failed' | 'unsub_alerts_suppressed';
|
|
5
|
+
|
|
6
|
+
export interface AlertConfig {
|
|
7
|
+
/** 收告警的 webhook 網址(https)。沒設=只寫 log。 */
|
|
8
|
+
url?: string;
|
|
9
|
+
/** 選填:以 `Authorization: Bearer …` 帶上,給需要口令的接收端。 */
|
|
10
|
+
token?: string;
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 收件端(人、聊天頻道)看到的欄位:去掉控制字元(含換行)、截長,免得外人寄來的字串在告警裡搞出假內容。 */
|
|
15
|
+
const clean = (v: unknown, max: number): string | undefined =>
|
|
16
|
+
typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, ' ').trim().slice(0, max) : undefined;
|
|
17
|
+
|
|
18
|
+
/** 同一個 isolate 一分鐘最多送幾則告警(超過只寫 log):沒有人能靠亂打網址把告警頻道灌爆。 */
|
|
19
|
+
const MAX_ALERTS_PER_MIN = 20;
|
|
20
|
+
/** 網頁亂打(任何人都能送)與信件(要寄信、較難灌)各有自己的額度,網頁灌爆不會擠掉真正的退訂信告警。 */
|
|
21
|
+
/** suppressed=這個時間窗被額度壓掉幾則(窗結束時補送一則彙總,人才知道中間漏看了多少)。 */
|
|
22
|
+
const budgets: Record<'page' | 'mail', { start: number; count: number; max: number; suppressed: number }> = {
|
|
23
|
+
page: { start: 0, count: 0, max: MAX_ALERTS_PER_MIN, suppressed: 0 },
|
|
24
|
+
mail: { start: 0, count: 0, max: 60, suppressed: 0 },
|
|
25
|
+
};
|
|
26
|
+
/** 寫入失敗=有人退訂卻沒退成,不受額度限制(漏掉一則就可能寄信給已經要求退訂的人)。 */
|
|
27
|
+
const UNLIMITED: ReadonlySet<AlertEvent> = new Set(['unsub_write_failed']);
|
|
28
|
+
|
|
29
|
+
export interface AlertPayload {
|
|
30
|
+
event: AlertEvent;
|
|
31
|
+
/** 信封寄件人(收信退訂時才有)。 */
|
|
32
|
+
from?: string;
|
|
33
|
+
subject?: string | null;
|
|
34
|
+
/** 完整退訂券(驗不過或寫入失敗時);有了它人工才能判斷是誰。 */
|
|
35
|
+
token?: string;
|
|
36
|
+
/** 券裡讀得出的名單與聯絡人編號(形狀對才有);不用完整券也足以人工處理。 */
|
|
37
|
+
claims?: { list: string; contactId: number; campaign?: string | null };
|
|
38
|
+
via?: 'page' | 'mailto';
|
|
39
|
+
/** 彙總告警用:壓掉幾則。 */
|
|
40
|
+
suppressed?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const SUMMARY: Record<AlertEvent, string> = {
|
|
44
|
+
unsub_mail_no_token: 'Unsubscribe email without a token: a person must handle it',
|
|
45
|
+
unsub_token_invalid: 'Unsubscribe token failed verification: the reader may still be subscribed',
|
|
46
|
+
unsub_write_failed: 'Unsubscribe email received but the database write failed: apply it by hand',
|
|
47
|
+
unsub_alerts_suppressed: 'Some unsubscribe alerts were dropped by the rate limit; check the logs',
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** 送告警。永遠不丟錯;回傳有沒有送出。 */
|
|
51
|
+
export async function sendAlert(cfg: AlertConfig, payload: AlertPayload, now: () => Date = () => new Date()): Promise<boolean> {
|
|
52
|
+
const at = now();
|
|
53
|
+
const from = clean(payload.from, 320);
|
|
54
|
+
const body = {
|
|
55
|
+
event: payload.event, at: at.toISOString(), suppressed: payload.suppressed, via: payload.via, from, subject: payload.subject === null ? null : clean(payload.subject, 200),
|
|
56
|
+
token: clean(payload.token, 200), claims: payload.claims, text: `${SUMMARY[payload.event]}${from ? ` (from ${from})` : ''}`, content: '',
|
|
57
|
+
};
|
|
58
|
+
body.content = body.text;
|
|
59
|
+
// log 不放完整券(它能替那個人退訂):只放券前 8 字與讀得出的名單/聯絡人編號,足夠人工處理;完整券只走有口令的 webhook。
|
|
60
|
+
// 主旨裡通常就是那張券(有時還被編碼過),有券時 log 不放主旨。
|
|
61
|
+
const short = body.token ? `${body.token.slice(0, 8)}…` : undefined;
|
|
62
|
+
const redacted = { ...body, token: short, subject: body.token && body.subject ? '[subject carries the token]' : body.subject };
|
|
63
|
+
console.error('unsub alert', JSON.stringify(redacted));
|
|
64
|
+
if (!cfg.url) return false;
|
|
65
|
+
const budget = budgets[payload.via === 'page' ? 'page' : 'mail'];
|
|
66
|
+
if (at.getTime() - budget.start >= 60_000) {
|
|
67
|
+
// 新的時間窗開始:上一窗有被壓掉的,先補送一則彙總。
|
|
68
|
+
await flushSuppressedAlerts(cfg, () => at);
|
|
69
|
+
budget.start = at.getTime();
|
|
70
|
+
budget.count = 0;
|
|
71
|
+
}
|
|
72
|
+
if (!UNLIMITED.has(payload.event) && ++budget.count > budget.max) {
|
|
73
|
+
budget.suppressed++;
|
|
74
|
+
console.error('unsub alert rate limited', payload.via ?? 'mail');
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
if (!/^https:\/\/[^\s]+$/i.test(cfg.url)) {
|
|
78
|
+
console.error('unsub alert webhook must be https');
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const res = await (cfg.fetch ?? fetch)(cfg.url, {
|
|
83
|
+
method: 'POST',
|
|
84
|
+
headers: { 'content-type': 'application/json', ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}) },
|
|
85
|
+
body: JSON.stringify(body),
|
|
86
|
+
signal: AbortSignal.timeout(5000),
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) console.error('unsub alert webhook status', res.status);
|
|
89
|
+
return res.ok;
|
|
90
|
+
} catch (e) {
|
|
91
|
+
console.error('unsub alert webhook failed', e instanceof Error ? e.message : 'unknown');
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 時間窗已過、而且上一窗有告警被額度壓掉:補送一則「壓掉 N 則」。沒有被壓掉的就什麼都不做。
|
|
98
|
+
* 排程每分鐘也可以呼叫(沒有後續告警進來時,彙總才不會一直等不到下一則)。回傳補送了幾則彙總。
|
|
99
|
+
*/
|
|
100
|
+
export async function flushSuppressedAlerts(cfg: AlertConfig, now: () => Date = () => new Date()): Promise<number> {
|
|
101
|
+
const at = now().getTime();
|
|
102
|
+
let sent = 0;
|
|
103
|
+
for (const [name, b] of Object.entries(budgets) as ['page' | 'mail', (typeof budgets)['page']][]) {
|
|
104
|
+
if (b.suppressed === 0 || at - b.start < 60_000) continue;
|
|
105
|
+
const n = b.suppressed;
|
|
106
|
+
b.suppressed = 0;
|
|
107
|
+
if (await sendAlert(cfg, { event: 'unsub_alerts_suppressed', via: name === 'page' ? 'page' : 'mailto', suppressed: n }, now)) sent++;
|
|
108
|
+
}
|
|
109
|
+
return sent;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let warned = false;
|
|
113
|
+
/** 沒設告警網址時警告一次(每個 isolate 一次);回傳是否有設。 */
|
|
114
|
+
export function warnIfNoAlert(url: string | undefined): boolean {
|
|
115
|
+
if (url) return true;
|
|
116
|
+
if (!warned) {
|
|
117
|
+
warned = true;
|
|
118
|
+
console.warn('UNSUB_ALERT_WEBHOOK is not set: unsubscribe requests that fail will only appear in the logs');
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
/** 測試用:重置一次性警告。 */
|
|
123
|
+
export function resetAlertWarning(): void { warned = false; for (const b of Object.values(budgets)) { b.start = 0; b.count = 0; b.suppressed = 0; } }
|
package/src/aws-sigv4.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// AWS Signature Version 4(只用 WebCrypto,不裝 AWS SDK、不加相依套件)。
|
|
2
|
+
// 只做郵務室用得到的那一小塊:一個 HTTPS 請求、標頭簽章(Authorization 標頭)、內文整段雜湊。
|
|
3
|
+
// 規格:https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
|
|
4
|
+
// 測試用 AWS 官方 SigV4 測試向量(tests/aws-sigv4.test.ts)。
|
|
5
|
+
// 不 import cloudflare:*;鑰匙不進 log、不進錯誤訊息。
|
|
6
|
+
|
|
7
|
+
export interface AwsCredentials {
|
|
8
|
+
accessKeyId: string;
|
|
9
|
+
secretAccessKey: string;
|
|
10
|
+
/** 臨時憑證才有。 */
|
|
11
|
+
sessionToken?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SignInput {
|
|
15
|
+
method: string;
|
|
16
|
+
url: string;
|
|
17
|
+
/** 要一起簽的標頭(host 與 x-amz-date 會自動補上)。 */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
region: string;
|
|
21
|
+
service: string;
|
|
22
|
+
credentials: AwsCredentials;
|
|
23
|
+
now?: Date;
|
|
24
|
+
/** 測試向量不簽 x-amz-content-sha256;正式送 AWS 也不需要(S3 才要)。 */
|
|
25
|
+
contentSha256Header?: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const enc = new TextEncoder();
|
|
29
|
+
|
|
30
|
+
function hex(buf: ArrayBuffer | Uint8Array): string {
|
|
31
|
+
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function sha256Hex(data: string): Promise<string> {
|
|
35
|
+
return hex(await crypto.subtle.digest('SHA-256', enc.encode(data)));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function hmac(key: Uint8Array | string, data: string): Promise<Uint8Array> {
|
|
39
|
+
const raw = typeof key === 'string' ? enc.encode(key) : key;
|
|
40
|
+
const k = await crypto.subtle.importKey('raw', Uint8Array.from(raw), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
41
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode(data)));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** RFC 3986 編碼(AWS 版本:保留 A-Z a-z 0-9 - _ . ~,其他一律 %XX 大寫)。 */
|
|
45
|
+
export function uriEncode(s: string, keepSlash = false): string {
|
|
46
|
+
let out = '';
|
|
47
|
+
for (const b of enc.encode(s)) {
|
|
48
|
+
const c = String.fromCharCode(b);
|
|
49
|
+
if (/[A-Za-z0-9\-_.~]/.test(c) || (keepSlash && c === '/')) out += c;
|
|
50
|
+
else out += `%${b.toString(16).toUpperCase().padStart(2, '0')}`;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function canonicalQuery(url: URL): string {
|
|
56
|
+
const pairs: [string, string][] = [];
|
|
57
|
+
for (const [k, v] of url.searchParams) pairs.push([uriEncode(k), uriEncode(v)]);
|
|
58
|
+
pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));
|
|
59
|
+
return pairs.map(([k, v]) => `${k}=${v}`).join('&');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function canonicalPath(url: URL): string {
|
|
63
|
+
// 非 S3 服務:路徑每一段各自再編碼一次(URL 物件給的已經是編碼過一次的樣子)。
|
|
64
|
+
const path = url.pathname || '/';
|
|
65
|
+
return path.split('/').map((seg) => uriEncode(decodeURIComponent(seg))).join('/') || '/';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function amzDate(now: Date): string {
|
|
69
|
+
return now.toISOString().replace(/[:-]/g, '').replace(/\.\d{3}/, '');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 簽好的標頭(含 authorization、x-amz-date、host)。呼叫端把它們原樣放進 fetch。 */
|
|
73
|
+
export async function signRequest(input: SignInput): Promise<Record<string, string>> {
|
|
74
|
+
const url = new URL(input.url);
|
|
75
|
+
const date = amzDate(input.now ?? new Date());
|
|
76
|
+
const day = date.slice(0, 8);
|
|
77
|
+
const body = input.body ?? '';
|
|
78
|
+
const payloadHash = await sha256Hex(body);
|
|
79
|
+
const headers: Record<string, string> = {};
|
|
80
|
+
for (const [k, v] of Object.entries(input.headers ?? {})) headers[k.toLowerCase()] = v;
|
|
81
|
+
headers.host = url.host;
|
|
82
|
+
headers['x-amz-date'] = date;
|
|
83
|
+
if (input.credentials.sessionToken) headers['x-amz-security-token'] = input.credentials.sessionToken;
|
|
84
|
+
if (input.contentSha256Header) headers['x-amz-content-sha256'] = payloadHash;
|
|
85
|
+
const names = Object.keys(headers).sort();
|
|
86
|
+
const canonicalHeaders = names.map((n) => `${n}:${headers[n].trim().replace(/\s+/g, ' ')}\n`).join('');
|
|
87
|
+
const signedHeaders = names.join(';');
|
|
88
|
+
const canonicalRequest = [input.method.toUpperCase(), canonicalPath(url), canonicalQuery(url), canonicalHeaders, signedHeaders, payloadHash].join('\n');
|
|
89
|
+
const scope = `${day}/${input.region}/${input.service}/aws4_request`;
|
|
90
|
+
const stringToSign = ['AWS4-HMAC-SHA256', date, scope, await sha256Hex(canonicalRequest)].join('\n');
|
|
91
|
+
let key = await hmac(`AWS4${input.credentials.secretAccessKey}`, day);
|
|
92
|
+
key = await hmac(key, input.region);
|
|
93
|
+
key = await hmac(key, input.service);
|
|
94
|
+
key = await hmac(key, 'aws4_request');
|
|
95
|
+
const signature = hex(await hmac(key, stringToSign));
|
|
96
|
+
return {
|
|
97
|
+
...headers,
|
|
98
|
+
authorization: `AWS4-HMAC-SHA256 Credential=${input.credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// 「這期現在開寄會寄給誰」的預估(唯讀,不凍結、不寫任何東西):依收件群與暖機梯子,列出每波每群多少人、被擋多少。
|
|
2
|
+
// 算法與 freeze.ts 一致:訂閱中的人 → 全域拒收的擋下 → 不在收件群的記「暖機沒輪到」→ 超過 maxCount 的(後面的波先)記「暖機沒輪到」。
|
|
3
|
+
|
|
4
|
+
import type { ListDb } from '../lists.ts';
|
|
5
|
+
import { checkAudience, getCampaign } from './campaigns.ts';
|
|
6
|
+
import { currentStep, planBlocked } from './warmup.ts';
|
|
7
|
+
|
|
8
|
+
export interface AudiencePlan {
|
|
9
|
+
plan: string | null;
|
|
10
|
+
step: number | null;
|
|
11
|
+
/** 暖機梯子被鎖住或收件群設定有問題時的原因(這期現在開不了寄)。 */
|
|
12
|
+
blocked: string | null;
|
|
13
|
+
subscribed: number;
|
|
14
|
+
willSend: number;
|
|
15
|
+
skipped: { suppressed: number; warmup: number };
|
|
16
|
+
waves: { wave: number; count: number; segments: { name: string; count: number }[] }[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function audiencePlan(db: ListDb, campaignId: string): Promise<AudiencePlan | null> {
|
|
20
|
+
const c = await getCampaign(db, campaignId);
|
|
21
|
+
if (!c) return null;
|
|
22
|
+
let a = null;
|
|
23
|
+
try {
|
|
24
|
+
a = checkAudience(JSON.parse(c.audience));
|
|
25
|
+
} catch {
|
|
26
|
+
/* 下面當設定有問題 */
|
|
27
|
+
}
|
|
28
|
+
const empty = (blocked: string): AudiencePlan => ({ plan: null, step: null, blocked, subscribed: 0, willSend: 0, skipped: { suppressed: 0, warmup: 0 }, waves: [] });
|
|
29
|
+
if (!a) return empty('bad_audience');
|
|
30
|
+
let waves: string[][];
|
|
31
|
+
let maxCount: number | null;
|
|
32
|
+
let plan: string | null = null;
|
|
33
|
+
let step: number | null = null;
|
|
34
|
+
let blocked: string | null = null;
|
|
35
|
+
if ('plan' in a) {
|
|
36
|
+
const b = await planBlocked(db, a.plan);
|
|
37
|
+
const s = await currentStep(db, a.plan);
|
|
38
|
+
if (!s) return empty('unknown_plan');
|
|
39
|
+
if (b) blocked = `warmup_blocked: ${b}`;
|
|
40
|
+
waves = JSON.parse(s.segments);
|
|
41
|
+
maxCount = s.max_count;
|
|
42
|
+
plan = a.plan;
|
|
43
|
+
step = s.step;
|
|
44
|
+
} else {
|
|
45
|
+
waves = a.waves;
|
|
46
|
+
maxCount = a.maxCount ?? null;
|
|
47
|
+
}
|
|
48
|
+
const rows = (
|
|
49
|
+
await db
|
|
50
|
+
.prepare(
|
|
51
|
+
`SELECT m.segment AS seg, CASE WHEN c.email IN (SELECT email FROM suppressions WHERE reason IN ('hard_bounce', 'complaint', 'unsubscribe')) THEN 1 ELSE 0 END AS sup, COUNT(*) AS n
|
|
52
|
+
FROM list_members m JOIN contacts c ON c.id = m.contact_id WHERE m.list_id = ? AND m.status = 'subscribed' GROUP BY seg, sup`,
|
|
53
|
+
)
|
|
54
|
+
.bind(c.list_id)
|
|
55
|
+
.all<{ seg: string | null; sup: number; n: number }>()
|
|
56
|
+
).results;
|
|
57
|
+
// 群 → (第幾波、波內順位);「*」=其他所有人。
|
|
58
|
+
const slot = new Map<string, { wave: number; rank: number }>();
|
|
59
|
+
let star: { wave: number; rank: number } | null = null;
|
|
60
|
+
waves.forEach((segs, wi) => segs.forEach((s, si) => (s === '*' ? (star = { wave: wi + 1, rank: si }) : slot.set(s, { wave: wi + 1, rank: si }))));
|
|
61
|
+
const perSeg = new Map<string, { wave: number; rank: number; count: number }>();
|
|
62
|
+
let subscribed = 0;
|
|
63
|
+
let suppressed = 0;
|
|
64
|
+
let warmup = 0;
|
|
65
|
+
for (const r of rows) {
|
|
66
|
+
const n = Number(r.n);
|
|
67
|
+
subscribed += n;
|
|
68
|
+
const sl = (r.seg !== null ? slot.get(r.seg) : undefined) ?? star;
|
|
69
|
+
if (r.sup) suppressed += n;
|
|
70
|
+
else if (!sl) warmup += n;
|
|
71
|
+
else {
|
|
72
|
+
const key = r.seg ?? '';
|
|
73
|
+
const cur = perSeg.get(key) ?? { wave: sl.wave, rank: sl.rank, count: 0 };
|
|
74
|
+
cur.count += n;
|
|
75
|
+
perSeg.set(key, cur);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// 依波次、順位排好;超過 maxCount 的記成暖機沒輪到。
|
|
79
|
+
const ordered = [...perSeg.entries()].sort((x, y) => x[1].wave - y[1].wave || x[1].rank - y[1].rank);
|
|
80
|
+
let left = maxCount ?? Number.POSITIVE_INFINITY;
|
|
81
|
+
const byWave = new Map<number, { name: string; count: number }[]>();
|
|
82
|
+
let willSend = 0;
|
|
83
|
+
for (const [name, v] of ordered) {
|
|
84
|
+
const take = Math.min(v.count, left);
|
|
85
|
+
left -= take;
|
|
86
|
+
warmup += v.count - take;
|
|
87
|
+
if (take > 0) {
|
|
88
|
+
willSend += take;
|
|
89
|
+
byWave.set(v.wave, [...(byWave.get(v.wave) ?? []), { name: name || '(none)', count: take }]);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
plan, step, blocked, subscribed, willSend, skipped: { suppressed, warmup },
|
|
94
|
+
waves: [...byWave.entries()].sort((x, y) => x[0] - y[0]).map(([wave, segments]) => ({ wave, count: segments.reduce((s, x) => s + x.count, 0), segments })),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// 一期信:存草稿、記寄前檢查、核准、排程、暫停、續寄、取消。狀態只能照下表走,其他一律擋。
|
|
2
|
+
//
|
|
3
|
+
// draft → approved → scheduled → sending ⇄ paused → done
|
|
4
|
+
// draft/approved/scheduled/paused → cancelled
|
|
5
|
+
// approved → draft(內容改了)、scheduled → approved(取消排程)、scheduled → draft(內容改了)
|
|
6
|
+
//
|
|
7
|
+
// sending/done 只有派送程式(dispatch.ts)能進;人能做的是 pause/resume/cancel。
|
|
8
|
+
// 內容(讀者看得到的一切)算一個雜湊:核准與寄前檢查都綁在那個雜湊上,內容一改就退回 draft、要重新核准。
|
|
9
|
+
|
|
10
|
+
import { parseAddress, type Db } from '../core.ts';
|
|
11
|
+
|
|
12
|
+
export type CampaignStatus = 'draft' | 'approved' | 'scheduled' | 'sending' | 'paused' | 'done' | 'cancelled';
|
|
13
|
+
export const CAMPAIGN_STATUSES: readonly CampaignStatus[] = ['draft', 'approved', 'scheduled', 'sending', 'paused', 'done', 'cancelled'];
|
|
14
|
+
|
|
15
|
+
/** 合法轉換(from → 可去的狀態)。 */
|
|
16
|
+
export const TRANSITIONS: Readonly<Record<CampaignStatus, readonly CampaignStatus[]>> = {
|
|
17
|
+
draft: ['approved', 'cancelled'],
|
|
18
|
+
approved: ['draft', 'scheduled', 'cancelled'],
|
|
19
|
+
scheduled: ['draft', 'approved', 'sending', 'cancelled'],
|
|
20
|
+
sending: ['paused', 'done'],
|
|
21
|
+
paused: ['sending', 'cancelled'],
|
|
22
|
+
done: [],
|
|
23
|
+
cancelled: [],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export function canTransition(from: CampaignStatus, to: CampaignStatus): boolean {
|
|
27
|
+
return TRANSITIONS[from]?.includes(to) ?? false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type Audience = { plan: string } | { waves: string[][]; maxCount?: number };
|
|
31
|
+
|
|
32
|
+
export interface CampaignInput {
|
|
33
|
+
id: string;
|
|
34
|
+
list: string;
|
|
35
|
+
subject: string;
|
|
36
|
+
preheader?: string;
|
|
37
|
+
from: string;
|
|
38
|
+
replyTo?: string;
|
|
39
|
+
html: string;
|
|
40
|
+
text: string;
|
|
41
|
+
headers?: Record<string, string>;
|
|
42
|
+
/** 這期的網頁版網址(https;信裡的 {{web_url}})。排程前一定要有。 */
|
|
43
|
+
webUrl?: string;
|
|
44
|
+
sourceRef?: string;
|
|
45
|
+
audience: Audience;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface CampaignRow {
|
|
49
|
+
id: string; list_id: string; subject: string; preheader: string | null; from_addr: string; reply_to: string | null;
|
|
50
|
+
html: string; text: string; headers: string | null; web_url: string | null; source_ref: string | null; status: CampaignStatus;
|
|
51
|
+
audience: string; audience_resolved: string | null; content_hash: string; approved_hash: string | null;
|
|
52
|
+
approved_at: string | null; approved_note: string | null; preflight: string | null; scheduled_at: string | null;
|
|
53
|
+
started_at: string | null; frozen_at: string | null; last_release_at: string | null; waiting_since: string | null; last_progress_at: string | null;
|
|
54
|
+
finished_at: string | null; pause_reason: string | null; counts: string | null; created_at: string; updated_at: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type Fail = { ok: false; reason: string; status?: CampaignStatus; twin?: string; twinStatus?: CampaignStatus; twinBy?: 'web_url' | 'content' | 'source_ref' };
|
|
58
|
+
export type Ok<T = object> = { ok: true } & T;
|
|
59
|
+
|
|
60
|
+
export const CAMPAIGN_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
61
|
+
const LIST_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
62
|
+
const SEGMENT = /^[^\u0000-\u001f\u007f]{1,64}$/;
|
|
63
|
+
/** 一期信能自帶的標頭:只收退訂兩個標頭、List-Id 與 X- 開頭的(寄件人、收件人、主旨等一律由引擎自己組,不准從這裡帶)。 */
|
|
64
|
+
export const EXTRA_HEADER = /^(?:list-unsubscribe|list-unsubscribe-post|list-id|x-[a-z0-9-]{1,60})$/i;
|
|
65
|
+
const LIMITS = { subject: 300, preheader: 300, html: 400_000, text: 200_000, note: 300, reason: 200, sourceRef: 300 };
|
|
66
|
+
const nowIso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString();
|
|
67
|
+
const ctl = (s: string) => /[\u0000-\u001f\u007f]/.test(s);
|
|
68
|
+
|
|
69
|
+
/** 讀者看得到的一切(含名單與寄件人)算一個雜湊。 */
|
|
70
|
+
export async function contentHash(c: { list: string; subject: string; preheader?: string | null; from: string; replyTo?: string | null; html: string; text: string; headers?: Record<string, string> | null; webUrl?: string | null }): Promise<string> {
|
|
71
|
+
const raw = JSON.stringify([c.list, c.subject, c.preheader ?? '', c.from, c.replyTo ?? '', c.html, c.text, Object.entries(c.headers ?? {}).sort(), c.webUrl ?? '']);
|
|
72
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw));
|
|
73
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 收件群設定檢查:plan 要有名字;waves 要是非空的二維字串陣列、同一個群不能出現兩次。 */
|
|
77
|
+
export function checkAudience(a: unknown): Audience | null {
|
|
78
|
+
if (!a || typeof a !== 'object' || Array.isArray(a)) return null;
|
|
79
|
+
const o = a as Record<string, unknown>;
|
|
80
|
+
if ('plan' in o) return typeof o.plan === 'string' && CAMPAIGN_ID.test(o.plan) && Object.keys(o).length === 1 ? { plan: o.plan } : null;
|
|
81
|
+
const waves = checkWaves(o.waves);
|
|
82
|
+
if (!waves) return null;
|
|
83
|
+
if (o.maxCount !== undefined && !(Number.isInteger(o.maxCount) && (o.maxCount as number) > 0)) return null;
|
|
84
|
+
return o.maxCount === undefined ? { waves } : { waves, maxCount: o.maxCount as number };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function checkWaves(w: unknown): string[][] | null {
|
|
88
|
+
if (!Array.isArray(w) || w.length === 0 || w.length > 20) return null;
|
|
89
|
+
const seen = new Set<string>();
|
|
90
|
+
const out: string[][] = [];
|
|
91
|
+
for (const wave of w) {
|
|
92
|
+
if (!Array.isArray(wave) || wave.length === 0 || wave.length > 50) return null;
|
|
93
|
+
const segs: string[] = [];
|
|
94
|
+
for (const s of wave) {
|
|
95
|
+
if (typeof s !== 'string' || !SEGMENT.test(s) || seen.has(s)) return null;
|
|
96
|
+
seen.add(s);
|
|
97
|
+
segs.push(s);
|
|
98
|
+
}
|
|
99
|
+
out.push(segs);
|
|
100
|
+
}
|
|
101
|
+
// 「*」(其他所有人)只能放在最後一波的最後一個。群總數上限 20(凍結那條 SQL 的綁定值才不會超過 D1 上限)。
|
|
102
|
+
const flat = out.flat();
|
|
103
|
+
if (flat.length > 20) return null;
|
|
104
|
+
if (flat.includes('*') && flat.indexOf('*') !== flat.length - 1) return null;
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 網頁版網址比對用:主機小寫、去掉 utm 參數與 #片段、路徑結尾斜線、預設埠。 */
|
|
109
|
+
export function normalizeWebUrl(u: string): string {
|
|
110
|
+
try {
|
|
111
|
+
const x = new URL(u);
|
|
112
|
+
x.hash = '';
|
|
113
|
+
for (const k of [...x.searchParams.keys()]) if (/^utm_/i.test(k)) x.searchParams.delete(k);
|
|
114
|
+
x.searchParams.sort();
|
|
115
|
+
const path = x.pathname.replace(/\/+$/, '') || '/';
|
|
116
|
+
return `${x.protocol}//${x.host.toLowerCase()}${path}${x.search}`;
|
|
117
|
+
} catch {
|
|
118
|
+
return u.trim().toLowerCase();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function findTwin(db: Db, input: CampaignInput, _hash: string): Promise<{ id: string; status: CampaignStatus; by: 'web_url' | 'content' | 'source_ref' } | null> {
|
|
123
|
+
const rows = (
|
|
124
|
+
await db
|
|
125
|
+
.prepare("SELECT id, status, web_url, source_ref, (list_id = ? AND html = ? AND text = ?) AS same_body FROM campaigns WHERE id <> ? AND status <> 'cancelled'")
|
|
126
|
+
.bind(input.list, input.html, input.text, input.id)
|
|
127
|
+
.all<{ id: string; status: CampaignStatus; web_url: string | null; source_ref: string | null; same_body: number }>()
|
|
128
|
+
).results;
|
|
129
|
+
const mine = input.webUrl ? normalizeWebUrl(input.webUrl) : null;
|
|
130
|
+
for (const r of rows) {
|
|
131
|
+
if (mine && r.web_url && normalizeWebUrl(r.web_url) === mine) return { id: r.id, status: r.status, by: 'web_url' };
|
|
132
|
+
if (Number(r.same_body) === 1) return { id: r.id, status: r.status, by: 'content' };
|
|
133
|
+
if (input.sourceRef && r.source_ref === input.sourceRef && r.status !== 'done') return { id: r.id, status: r.status, by: 'source_ref' };
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function checkInput(input: CampaignInput, marketingDomain: string): string | null {
|
|
139
|
+
if (!input || typeof input !== 'object') return 'bad_request';
|
|
140
|
+
if (typeof input.id !== 'string' || !CAMPAIGN_ID.test(input.id)) return 'bad_id';
|
|
141
|
+
if (typeof input.list !== 'string' || !LIST_ID.test(input.list)) return 'bad_list';
|
|
142
|
+
if (typeof input.subject !== 'string' || !input.subject.trim() || input.subject.length > LIMITS.subject || ctl(input.subject)) return 'bad_subject';
|
|
143
|
+
if (input.preheader !== undefined && (typeof input.preheader !== 'string' || input.preheader.length > LIMITS.preheader || ctl(input.preheader))) return 'bad_preheader';
|
|
144
|
+
const from = parseAddress(String(input.from ?? ''));
|
|
145
|
+
if (!from || !marketingDomain || !from.addr.endsWith(`@${marketingDomain.toLowerCase()}`)) return 'bad_from';
|
|
146
|
+
if (input.replyTo !== undefined && !parseAddress(input.replyTo)) return 'bad_reply_to';
|
|
147
|
+
if (typeof input.html !== 'string' || !input.html || input.html.length > LIMITS.html) return 'bad_html';
|
|
148
|
+
if (typeof input.text !== 'string' || !input.text || input.text.length > LIMITS.text) return 'bad_text';
|
|
149
|
+
if (input.headers !== undefined) {
|
|
150
|
+
if (!input.headers || typeof input.headers !== 'object' || Array.isArray(input.headers)) return 'bad_headers';
|
|
151
|
+
for (const [k, v] of Object.entries(input.headers)) if (!EXTRA_HEADER.test(k) || typeof v !== 'string' || v.length > 2000 || /[\r\n]/.test(v)) return 'bad_headers';
|
|
152
|
+
}
|
|
153
|
+
if (input.webUrl !== undefined && (typeof input.webUrl !== 'string' || input.webUrl.length > 2000 || !/^https:\/\/[^\s<>"]+$/i.test(input.webUrl))) return 'bad_web_url';
|
|
154
|
+
if (input.sourceRef !== undefined && (typeof input.sourceRef !== 'string' || input.sourceRef.length > LIMITS.sourceRef || ctl(input.sourceRef))) return 'bad_source_ref';
|
|
155
|
+
if (!checkAudience(input.audience)) return 'bad_audience';
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function getCampaign(db: Db, id: string): Promise<CampaignRow | null> {
|
|
160
|
+
if (typeof id !== 'string' || !CAMPAIGN_ID.test(id)) return null;
|
|
161
|
+
return db.prepare('SELECT * FROM campaigns WHERE id = ?').bind(id).first<CampaignRow>();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 存草稿:新的一期建成 draft;已存在的只有 draft/approved/scheduled 能改,改了一律退回 draft
|
|
166
|
+
* (清掉核准與寄前檢查)。sending 之後不能改內容。
|
|
167
|
+
*/
|
|
168
|
+
export async function saveDraft(db: Db, input: CampaignInput, opts: { marketingDomain: string; now?: () => Date }): Promise<Ok<{ status: CampaignStatus; changed: boolean }> | Fail> {
|
|
169
|
+
const bad = checkInput(input, opts.marketingDomain);
|
|
170
|
+
if (bad) return { ok: false, reason: bad };
|
|
171
|
+
if (!(await db.prepare('SELECT id FROM lists WHERE id = ?').bind(input.list).first())) return { ok: false, reason: 'unknown_list' };
|
|
172
|
+
const hash = await contentHash(input);
|
|
173
|
+
const audience = JSON.stringify(checkAudience(input.audience));
|
|
174
|
+
const headers = input.headers ? JSON.stringify(input.headers) : null;
|
|
175
|
+
const t = nowIso(opts.now);
|
|
176
|
+
const existing = await getCampaign(db, input.id);
|
|
177
|
+
// 同一份內容不能用不同期號建兩次(會寄兩封):網頁版網址(正規化後)、同名單同內文、原稿位置任一相同,且對方沒被取消,就擋。
|
|
178
|
+
// 原稿位置只跟「還沒寄完」的期比(同一個原稿路徑每期都會重用,寄完的舊期不該擋新的一期);網址與內文跟寄完的也比。
|
|
179
|
+
const twin = await findTwin(db, input, hash);
|
|
180
|
+
if (twin) return { ok: false, reason: 'duplicate_content', twin: twin.id, twinStatus: twin.status, twinBy: twin.by };
|
|
181
|
+
if (!existing) {
|
|
182
|
+
const r = await db
|
|
183
|
+
.prepare(
|
|
184
|
+
`INSERT INTO campaigns (id, list_id, subject, preheader, from_addr, reply_to, html, text, headers, web_url, source_ref, status, audience, content_hash, created_at, updated_at)
|
|
185
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING`,
|
|
186
|
+
)
|
|
187
|
+
.bind(input.id, input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, t, t)
|
|
188
|
+
.run();
|
|
189
|
+
if ((r.meta.changes ?? 0) === 1) return { ok: true, status: 'draft', changed: true };
|
|
190
|
+
return { ok: false, reason: 'conflict' };
|
|
191
|
+
}
|
|
192
|
+
if (!['draft', 'approved', 'scheduled'].includes(existing.status)) return { ok: false, reason: 'locked', status: existing.status };
|
|
193
|
+
if (existing.content_hash === hash && existing.audience === audience && existing.list_id === input.list && (existing.source_ref ?? null) === (input.sourceRef ?? null)) {
|
|
194
|
+
return { ok: true, status: existing.status, changed: false };
|
|
195
|
+
}
|
|
196
|
+
const r = await db
|
|
197
|
+
.prepare(
|
|
198
|
+
`UPDATE campaigns SET list_id = ?, subject = ?, preheader = ?, from_addr = ?, reply_to = ?, html = ?, text = ?, headers = ?, web_url = ?, source_ref = ?, audience = ?,
|
|
199
|
+
content_hash = ?, status = 'draft', approved_hash = NULL, approved_at = NULL, approved_note = NULL, preflight = NULL, scheduled_at = NULL, updated_at = ?
|
|
200
|
+
WHERE id = ? AND status IN ('draft', 'approved', 'scheduled')`,
|
|
201
|
+
)
|
|
202
|
+
.bind(input.list, input.subject, input.preheader ?? null, input.from, input.replyTo ?? null, input.html, input.text, headers, input.webUrl ?? null, input.sourceRef ?? null, audience, hash, t, input.id)
|
|
203
|
+
.run();
|
|
204
|
+
if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'locked' };
|
|
205
|
+
return { ok: true, status: 'draft', changed: true };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 寄前檢查結果(compose 的 preflight 產生)的最小形狀。 */
|
|
209
|
+
export interface PreflightRecord { ok: boolean; issues?: { severity?: string; code?: string; message?: string }[] }
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 記下寄前檢查結果,綁在目前的內容雜湊上。檢查是在呼叫端跑的(要打網路查連結),
|
|
213
|
+
* 引擎只認「ok 而且雜湊對得上」才准排程。
|
|
214
|
+
*/
|
|
215
|
+
export async function recordPreflight(db: Db, id: string, result: PreflightRecord, now?: () => Date): Promise<Ok<{ preflightOk: boolean }> | Fail> {
|
|
216
|
+
const c = await getCampaign(db, id);
|
|
217
|
+
if (!c) return { ok: false, reason: 'not_found' };
|
|
218
|
+
if (!['draft', 'approved', 'scheduled'].includes(c.status)) return { ok: false, reason: 'locked', status: c.status };
|
|
219
|
+
if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') return { ok: false, reason: 'bad_preflight' };
|
|
220
|
+
const errors = Array.isArray(result.issues) ? result.issues.filter((i) => i && i.severity === 'error').slice(0, 50).map((i) => String(i.code ?? i.message ?? 'error').slice(0, 100)) : [];
|
|
221
|
+
// 回報 ok 但列了 error=自相矛盾,當沒過。
|
|
222
|
+
const ok = result.ok && errors.length === 0;
|
|
223
|
+
// 給預覽頁看的明細(只留嚴重度、代碼、說明,截長;不放收件人資料)。
|
|
224
|
+
const issues = Array.isArray(result.issues)
|
|
225
|
+
? result.issues.filter((i) => i && typeof i === 'object').slice(0, 50).map((i) => ({ severity: String(i.severity ?? '').slice(0, 10), code: String(i.code ?? '').slice(0, 60), message: String(i.message ?? '').slice(0, 300) }))
|
|
226
|
+
: [];
|
|
227
|
+
const record = JSON.stringify({ ok, hash: c.content_hash, at: nowIso(now), errors, issues });
|
|
228
|
+
const r = await db.prepare('UPDATE campaigns SET preflight = ?, updated_at = ? WHERE id = ? AND content_hash = ?').bind(record, nowIso(now), id, c.content_hash).run();
|
|
229
|
+
if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'changed_meanwhile' };
|
|
230
|
+
// 檢查沒過:已排程的退回 approved(不准留在 scheduled)。
|
|
231
|
+
if (!ok && c.status === 'scheduled') await db.prepare("UPDATE campaigns SET status = 'approved', scheduled_at = NULL WHERE id = ? AND status = 'scheduled'").bind(id).run();
|
|
232
|
+
return { ok: true, preflightOk: ok };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function preflightPasses(c: CampaignRow): boolean {
|
|
236
|
+
if (!c.preflight) return false;
|
|
237
|
+
try {
|
|
238
|
+
const p = JSON.parse(c.preflight) as { ok?: unknown; hash?: unknown };
|
|
239
|
+
return p.ok === true && p.hash === c.content_hash;
|
|
240
|
+
} catch {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function move(db: Db, id: string, from: CampaignStatus[], to: CampaignStatus, sets: string, binds: unknown[], now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
|
|
246
|
+
for (const f of from) if (!canTransition(f, to)) throw new Error(`transition table forbids ${f} -> ${to}`);
|
|
247
|
+
const c = await getCampaign(db, id);
|
|
248
|
+
if (!c) return { ok: false, reason: 'not_found' };
|
|
249
|
+
if (!from.includes(c.status)) return { ok: false, reason: 'illegal_transition', status: c.status };
|
|
250
|
+
const r = await db
|
|
251
|
+
.prepare(`UPDATE campaigns SET status = ?, ${sets ? `${sets}, ` : ''}updated_at = ? WHERE id = ? AND status = ? AND content_hash = ?`)
|
|
252
|
+
.bind(to, ...binds, nowIso(now), id, c.status, c.content_hash)
|
|
253
|
+
.run();
|
|
254
|
+
if ((r.meta.changes ?? 0) !== 1) return { ok: false, reason: 'changed_meanwhile' };
|
|
255
|
+
return { ok: true, status: to };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function cleanText(v: unknown, max: number): string | null {
|
|
259
|
+
return typeof v === 'string' && v.trim() && !ctl(v) ? v.trim().slice(0, max) : null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 核准:只在本人看過預覽、明確說好之後執行;note 要寫「誰、什麼時候、在哪說的」。 */
|
|
263
|
+
export async function approveCampaign(db: Db, id: string, note: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
|
|
264
|
+
const n = cleanText(note, LIMITS.note);
|
|
265
|
+
if (!n) return { ok: false, reason: 'note_required' };
|
|
266
|
+
const c = await getCampaign(db, id);
|
|
267
|
+
if (!c) return { ok: false, reason: 'not_found' };
|
|
268
|
+
return move(db, id, ['draft'], 'approved', 'approved_hash = content_hash, approved_at = ?, approved_note = ?', [nowIso(now), n], now);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 排程(at=ISO 時間):要已核准、核准的就是現在這份內容、寄前檢查過了、收件群有效。 */
|
|
272
|
+
export async function scheduleCampaign(db: Db, id: string, at: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus; scheduledAt: string }> | Fail> {
|
|
273
|
+
const c = await getCampaign(db, id);
|
|
274
|
+
if (!c) return { ok: false, reason: 'not_found' };
|
|
275
|
+
if (c.status !== 'approved') return { ok: false, reason: 'illegal_transition', status: c.status };
|
|
276
|
+
if (c.approved_hash !== c.content_hash) return { ok: false, reason: 'not_approved' };
|
|
277
|
+
if (!preflightPasses(c)) return { ok: false, reason: 'preflight_not_passed' };
|
|
278
|
+
if (!c.web_url) return { ok: false, reason: 'web_url_required' };
|
|
279
|
+
if (typeof at !== 'string' || Number.isNaN(Date.parse(at))) return { ok: false, reason: 'bad_time' };
|
|
280
|
+
let audience: Audience | null = null;
|
|
281
|
+
try {
|
|
282
|
+
audience = checkAudience(JSON.parse(c.audience));
|
|
283
|
+
} catch {
|
|
284
|
+
/* 下面擋 */
|
|
285
|
+
}
|
|
286
|
+
if (!audience) return { ok: false, reason: 'bad_audience' };
|
|
287
|
+
if ('plan' in audience && !(await db.prepare('SELECT 1 AS x FROM warmup_steps WHERE plan_id = ? LIMIT 1').bind(audience.plan).first())) return { ok: false, reason: 'unknown_plan' };
|
|
288
|
+
const iso = new Date(at).toISOString();
|
|
289
|
+
const r = await move(db, id, ['approved'], 'scheduled', 'scheduled_at = ?', [iso], now);
|
|
290
|
+
return r.ok ? { ok: true, status: r.status, scheduledAt: iso } : r;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 取消排程(退回 approved)。 */
|
|
294
|
+
export function unscheduleCampaign(db: Db, id: string, now?: () => Date) {
|
|
295
|
+
return move(db, id, ['scheduled'], 'approved', 'scheduled_at = NULL', [], now);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** 人工暫停(寄送中)。 */
|
|
299
|
+
export function pauseCampaign(db: Db, id: string, reason: string, now?: () => Date) {
|
|
300
|
+
const r = cleanText(reason, LIMITS.reason);
|
|
301
|
+
if (!r) return Promise.resolve<Fail>({ ok: false, reason: 'reason_required' });
|
|
302
|
+
return move(db, id, ['sending'], 'paused', 'pause_reason = ?', [`manual: ${r}`], now);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* 續寄:只有 paused 能續;note 必填(寫查過什麼、為什麼可以繼續)。
|
|
307
|
+
* 寄件網域被整個停掉時不能續(要先解除網域停寄)。
|
|
308
|
+
*/
|
|
309
|
+
export async function resumeCampaign(db: Db, id: string, note: string, opts: { marketingDomain: string; now?: () => Date }): Promise<Ok<{ status: CampaignStatus }> | Fail> {
|
|
310
|
+
const n = cleanText(note, LIMITS.note);
|
|
311
|
+
if (!n) return { ok: false, reason: 'note_required' };
|
|
312
|
+
const hold = await db.prepare('SELECT reason FROM domain_holds WHERE domain = ? AND released_at IS NULL LIMIT 1').bind(opts.marketingDomain).first<{ reason: string }>();
|
|
313
|
+
if (hold) return { ok: false, reason: 'domain_held' };
|
|
314
|
+
// 「最後進度」順便更新:不然暫停很久之後一續寄,就被當成 Queue 卡住。
|
|
315
|
+
// 只有「讓這期停下來的那一道煞車」從續寄這一刻重新起算(ackBrake+brakeSince):人查過的就是那一項。
|
|
316
|
+
// 為了別的原因暫停(人工、Queue 卡住、對帳…)再續寄,比率照舊全部算,不會被清零。
|
|
317
|
+
const c = await getCampaign(db, id);
|
|
318
|
+
const m = /^brake:(hard_bounce_rate|complaint_rate|wave_gate)\b/.exec(c?.pause_reason ?? '');
|
|
319
|
+
const t = nowIso(opts.now);
|
|
320
|
+
return move(
|
|
321
|
+
db, id, ['paused'], 'sending',
|
|
322
|
+
"pause_reason = NULL, last_progress_at = ?, waiting_since = NULL, counts = json_set(COALESCE(counts, '{}'), '$.lastResumeNote', ?, '$.ackBrake', ?, '$.brakeSince', ?)",
|
|
323
|
+
[t, n, m ? m[1] : null, m ? t : null], opts.now,
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 取消:開寄前(draft/approved/scheduled)或暫停中才能取消;寄送中要先暫停。
|
|
329
|
+
* 暫停中取消:還沒寄的人記成 skipped/cancelled(已經交出去的那幾封由派送端看到 cancelled 後跳過)。
|
|
330
|
+
*/
|
|
331
|
+
export async function cancelCampaign(db: Db, id: string, reason: string, now?: () => Date): Promise<Ok<{ status: CampaignStatus }> | Fail> {
|
|
332
|
+
const r = cleanText(reason, LIMITS.reason);
|
|
333
|
+
if (!r) return { ok: false, reason: 'reason_required' };
|
|
334
|
+
const out = await move(db, id, ['draft', 'approved', 'scheduled', 'paused'], 'cancelled', 'pause_reason = ?, finished_at = ?', [`cancelled: ${r}`, nowIso(now)], now);
|
|
335
|
+
if (out.ok) {
|
|
336
|
+
await db.prepare("UPDATE campaign_recipients SET state = 'skipped', skip_reason = 'cancelled' WHERE campaign_id = ? AND state IN ('planned', 'enqueued')").bind(id).run();
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
}
|