@joelincc/mailroom 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +207 -2
- package/SECURITY.md +11 -0
- 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 +82 -0
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0001_init.sql +42 -0
- package/migrations/0002_tier.sql +4 -0
- package/migrations/0003_rate.sql +9 -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 +64 -4
- 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 +84 -0
- 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 +328 -0
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +378 -0
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/transport.ts +193 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +101 -0
- package/wrangler.example.jsonc +56 -0
package/src/lists.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
// 電子報名單:加入、退出、查狀態、分頁列出、批次匯入、分群欄位寫入。
|
|
2
|
+
// 單份退訂記在 list_members;全域拒收(suppressions)只放硬退信、檢舉、「全部都不要」。
|
|
3
|
+
// 不 import cloudflare:*,測試用 Node 內建 SQLite 跑同一份 SQL。
|
|
4
|
+
|
|
5
|
+
import { type Db, type Stmt } from './core.ts';
|
|
6
|
+
|
|
7
|
+
/** D1 的 batch(一次交多條、整批成功或整批失敗)是選配:沒有就逐條跑。D1Database 本身就符合。 */
|
|
8
|
+
export type ListDb = Db & { batch?(statements: Stmt[]): Promise<Array<{ meta: { changes?: number } }>> };
|
|
9
|
+
|
|
10
|
+
export const UNSUB_SOURCES = ['link', 'one_click', 'mailto', 'api', 'import', 'import-removed', 'complaint'] as const;
|
|
11
|
+
export type UnsubSource = (typeof UNSUB_SOURCES)[number];
|
|
12
|
+
/** 還沒有分群資料的新加入者。 */
|
|
13
|
+
export const NEW_SEGMENT = '新進觀察群';
|
|
14
|
+
|
|
15
|
+
const EMAIL = /^[^\s,;<>"'@]+@[^\s,;<>"'@]+\.[^\s,;<>"'@]+$/;
|
|
16
|
+
const LIST_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
17
|
+
const MAX_TEXT = 200;
|
|
18
|
+
/** D1 一條 SQL 最多 100 個綁定值;批次內每次查詢的信箱數留餘裕。 */
|
|
19
|
+
const CHUNK = 40;
|
|
20
|
+
const BATCH = 100;
|
|
21
|
+
export const MAX_IMPORT_ROWS = 2000;
|
|
22
|
+
export const MAX_SEGMENT_ROWS = 5000;
|
|
23
|
+
export const MEMBERS_PAGE = 1000;
|
|
24
|
+
|
|
25
|
+
export function normalizeEmail(raw: unknown): string | null {
|
|
26
|
+
if (typeof raw !== 'string') return null;
|
|
27
|
+
const e = raw.trim().toLowerCase();
|
|
28
|
+
return e.length <= 254 && !/[\u0000-\u001f\u007f]/.test(e) && EMAIL.test(e) ? e : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const text = (v: unknown, max = MAX_TEXT): string | null => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null);
|
|
32
|
+
const iso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString();
|
|
33
|
+
|
|
34
|
+
async function runAll(db: ListDb, stmts: Stmt[]): Promise<number[]> {
|
|
35
|
+
const out: number[] = [];
|
|
36
|
+
for (let i = 0; i < stmts.length; i += BATCH) {
|
|
37
|
+
const part = stmts.slice(i, i + BATCH);
|
|
38
|
+
if (db.batch) {
|
|
39
|
+
for (const r of await db.batch(part)) out.push(r.meta.changes ?? 0);
|
|
40
|
+
} else {
|
|
41
|
+
// 沒有 batch:照順序逐條跑(後面的條件依賴前面的列)。
|
|
42
|
+
for (const s of part) out.push((await s.run()).meta.changes ?? 0);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const marks = (n: number) => Array.from({ length: n }, () => '?').join(',');
|
|
49
|
+
|
|
50
|
+
// ---------- 名單本身 ----------
|
|
51
|
+
|
|
52
|
+
export interface ListInput { id: string; name: string; fromAddr?: string; replyTo?: string; welcomeTemplate?: string }
|
|
53
|
+
|
|
54
|
+
/** 建立或更新一份名單(同 id 再呼叫=改名稱與寄件資訊)。 */
|
|
55
|
+
export async function upsertList(db: ListDb, input: ListInput, now?: () => Date): Promise<{ ok: true } | { ok: false; reason: string }> {
|
|
56
|
+
if (!input || typeof input.id !== 'string' || !LIST_ID.test(input.id)) return { ok: false, reason: 'bad_list' };
|
|
57
|
+
const name = text(input.name);
|
|
58
|
+
if (!name) return { ok: false, reason: 'bad_name' };
|
|
59
|
+
await db
|
|
60
|
+
.prepare(
|
|
61
|
+
`INSERT INTO lists (id, name, from_addr, reply_to, welcome_template, created_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
62
|
+
ON CONFLICT (id) DO UPDATE SET name = excluded.name, from_addr = excluded.from_addr, reply_to = excluded.reply_to, welcome_template = excluded.welcome_template`,
|
|
63
|
+
)
|
|
64
|
+
.bind(input.id, name, text(input.fromAddr, 320), text(input.replyTo, 320), text(input.welcomeTemplate), iso(now))
|
|
65
|
+
.run();
|
|
66
|
+
return { ok: true };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function listExists(db: ListDb, id: unknown): Promise<boolean> {
|
|
70
|
+
if (typeof id !== 'string' || !LIST_ID.test(id)) return false;
|
|
71
|
+
return !!(await db.prepare('SELECT id FROM lists WHERE id = ?').bind(id).first());
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 這個信箱有沒有任何「電子報會擋」的全域拒收原因。 */
|
|
75
|
+
async function globalBlock(db: ListDb, email: string): Promise<boolean> {
|
|
76
|
+
return !!(await db.prepare("SELECT 1 AS x FROM suppressions WHERE email = ? AND reason IN ('hard_bounce', 'complaint', 'unsubscribe') LIMIT 1").bind(email).first());
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function contactId(db: ListDb, email: string, name: string | null, now: string): Promise<number> {
|
|
80
|
+
const row = await db
|
|
81
|
+
.prepare(
|
|
82
|
+
`INSERT INTO contacts (email, name, created_at, updated_at) VALUES (?, ?, ?, ?)
|
|
83
|
+
ON CONFLICT (email) DO UPDATE SET name = COALESCE(contacts.name, excluded.name), updated_at = excluded.updated_at
|
|
84
|
+
RETURNING id`,
|
|
85
|
+
)
|
|
86
|
+
.bind(email, name, now, now)
|
|
87
|
+
.first<{ id: number }>();
|
|
88
|
+
return Number(row!.id);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------- 加入、退出、查狀態 ----------
|
|
92
|
+
|
|
93
|
+
export interface SubscribeInput { list: string; email: string; source?: string; consentVersion?: string; name?: string }
|
|
94
|
+
export type SubscribeResult = { status: 'subscribed' | 'already' | 'blocked' } | { status: 'rejected'; reason: 'bad_list' | 'unknown_list' | 'bad_email' };
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 加入。回 subscribed(新加入或退訂後再訂回)、already(本來就在)、blocked(在全域拒收名單,不加)。
|
|
98
|
+
* 只有「讀者本人的加入動作」能把 unsubscribed 改回 subscribed;批次匯入與同步做不到(見 importMembers)。
|
|
99
|
+
*/
|
|
100
|
+
export async function listSubscribe(db: ListDb, input: SubscribeInput, now?: () => Date): Promise<SubscribeResult> {
|
|
101
|
+
const email = normalizeEmail(input?.email);
|
|
102
|
+
if (!email) return { status: 'rejected', reason: 'bad_email' };
|
|
103
|
+
if (typeof input.list !== 'string' || !LIST_ID.test(input.list)) return { status: 'rejected', reason: 'bad_list' };
|
|
104
|
+
if (!(await listExists(db, input.list))) return { status: 'rejected', reason: 'unknown_list' };
|
|
105
|
+
if (await globalBlock(db, email)) return { status: 'blocked' };
|
|
106
|
+
const t = iso(now);
|
|
107
|
+
const existing = await db
|
|
108
|
+
.prepare('SELECT m.status AS status FROM list_members m JOIN contacts c ON c.id = m.contact_id WHERE m.list_id = ? AND c.email = ?')
|
|
109
|
+
.bind(input.list, email)
|
|
110
|
+
.first<{ status: string }>();
|
|
111
|
+
if (existing?.status === 'subscribed') return { status: 'already' };
|
|
112
|
+
const id = await contactId(db, email, text(input.name), t);
|
|
113
|
+
// 新加入與退訂後再訂回走同一條:退訂欄位清空、來源記新入口。
|
|
114
|
+
await db
|
|
115
|
+
.prepare(
|
|
116
|
+
`INSERT INTO list_members (list_id, contact_id, status, subscribed_at, source, consent_version, segment, updated_at)
|
|
117
|
+
VALUES (?, ?, 'subscribed', ?, ?, ?, ?, ?)
|
|
118
|
+
ON CONFLICT (list_id, contact_id) DO UPDATE SET
|
|
119
|
+
status = 'subscribed', subscribed_at = excluded.subscribed_at, unsubscribed_at = NULL, unsub_source = NULL,
|
|
120
|
+
source = excluded.source, consent_version = excluded.consent_version, updated_at = excluded.updated_at`,
|
|
121
|
+
)
|
|
122
|
+
.bind(input.list, id, t, text(input.source), text(input.consentVersion), NEW_SEGMENT, t)
|
|
123
|
+
.run();
|
|
124
|
+
return { status: 'subscribed' };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface UnsubscribeInput { list: string; email: string; source?: UnsubSource }
|
|
128
|
+
export type UnsubscribeResult = { status: 'unsubscribed' | 'not_member' } | { status: 'rejected'; reason: 'bad_list' | 'unknown_list' | 'bad_email' | 'bad_source' };
|
|
129
|
+
|
|
130
|
+
/** 退出這一份名單(不碰別份、不碰全域拒收)。已經退訂=回 unsubscribed、不改原本的時間與來源(重複點擊安全)。 */
|
|
131
|
+
export async function listUnsubscribe(db: ListDb, input: UnsubscribeInput, now?: () => Date): Promise<UnsubscribeResult> {
|
|
132
|
+
const email = normalizeEmail(input?.email);
|
|
133
|
+
if (!email) return { status: 'rejected', reason: 'bad_email' };
|
|
134
|
+
if (typeof input.list !== 'string' || !LIST_ID.test(input.list)) return { status: 'rejected', reason: 'bad_list' };
|
|
135
|
+
const source = input.source ?? 'api';
|
|
136
|
+
if (!UNSUB_SOURCES.includes(source)) return { status: 'rejected', reason: 'bad_source' };
|
|
137
|
+
if (!(await listExists(db, input.list))) return { status: 'rejected', reason: 'unknown_list' };
|
|
138
|
+
const t = iso(now);
|
|
139
|
+
const row = await db
|
|
140
|
+
.prepare(
|
|
141
|
+
`UPDATE list_members SET
|
|
142
|
+
status = 'unsubscribed',
|
|
143
|
+
unsubscribed_at = CASE WHEN status = 'unsubscribed' THEN unsubscribed_at ELSE ? END,
|
|
144
|
+
unsub_source = CASE WHEN status = 'unsubscribed' THEN unsub_source ELSE ? END,
|
|
145
|
+
updated_at = CASE WHEN status = 'unsubscribed' THEN updated_at ELSE ? END
|
|
146
|
+
WHERE list_id = ? AND contact_id = (SELECT id FROM contacts WHERE email = ?)
|
|
147
|
+
RETURNING contact_id`,
|
|
148
|
+
)
|
|
149
|
+
.bind(t, source, t, input.list, email)
|
|
150
|
+
.first();
|
|
151
|
+
return { status: row ? 'unsubscribed' : 'not_member' };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type ListStatus = 'subscribed' | 'unsubscribed' | 'not_found' | 'blocked';
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 查狀態。已退訂=unsubscribed;訂閱中但在全域拒收=blocked(不寄);不是成員但在拒收名單=blocked;其他 not_found。
|
|
158
|
+
* 給會員中心對帳用:畫面上不要因為 blocked 就透露別人的狀態。
|
|
159
|
+
*/
|
|
160
|
+
export async function listStatus(db: ListDb, input: { list: string; email: string }): Promise<ListStatus | { status: 'rejected'; reason: 'bad_email' | 'bad_list' }> {
|
|
161
|
+
const email = normalizeEmail(input?.email);
|
|
162
|
+
if (!email) return { status: 'rejected', reason: 'bad_email' };
|
|
163
|
+
if (typeof input.list !== 'string' || !LIST_ID.test(input.list)) return { status: 'rejected', reason: 'bad_list' };
|
|
164
|
+
const m = await db
|
|
165
|
+
.prepare('SELECT m.status AS status FROM list_members m JOIN contacts c ON c.id = m.contact_id WHERE m.list_id = ? AND c.email = ?')
|
|
166
|
+
.bind(input.list, email)
|
|
167
|
+
.first<{ status: 'subscribed' | 'unsubscribed' }>();
|
|
168
|
+
if (m?.status === 'unsubscribed') return 'unsubscribed';
|
|
169
|
+
if (await globalBlock(db, email)) return 'blocked';
|
|
170
|
+
return m ? 'subscribed' : 'not_found';
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export interface MemberRow { email: string; status: 'subscribed' | 'unsubscribed'; subscribedAt: string | null; unsubscribedAt: string | null; unsubSource: string | null; unsubReason: string | null; source: string | null; segment: string | null; segmentLabel: string | null;
|
|
174
|
+
/** 這個信箱在全域拒收名單(硬退信、檢舉、「全部不要」)=不會寄;與 listStatus 的 blocked 同口徑。 */
|
|
175
|
+
suppressed: boolean }
|
|
176
|
+
export interface MembersPage { members: MemberRow[]; next: string | null }
|
|
177
|
+
|
|
178
|
+
/** 分頁列出(依 contact id 遞增,一頁最多 1,000)。cursor=上一頁回的 next;next 為 null=沒有下一頁。 */
|
|
179
|
+
export async function listMembers(db: ListDb, input: { list: string; status?: 'subscribed' | 'unsubscribed'; cursor?: string | null; limit?: number }): Promise<MembersPage | { status: 'rejected'; reason: 'bad_list' | 'bad_status' | 'bad_cursor' }> {
|
|
180
|
+
if (typeof input?.list !== 'string' || !LIST_ID.test(input.list)) return { status: 'rejected', reason: 'bad_list' };
|
|
181
|
+
if (input.status !== undefined && input.status !== 'subscribed' && input.status !== 'unsubscribed') return { status: 'rejected', reason: 'bad_status' };
|
|
182
|
+
let after = 0;
|
|
183
|
+
if (input.cursor !== undefined && input.cursor !== null && input.cursor !== '') {
|
|
184
|
+
if (!/^\d{1,15}$/.test(String(input.cursor))) return { status: 'rejected', reason: 'bad_cursor' };
|
|
185
|
+
after = Number(input.cursor);
|
|
186
|
+
}
|
|
187
|
+
const limit = Math.min(Math.max(Math.trunc(Number(input.limit)) || MEMBERS_PAGE, 1), MEMBERS_PAGE);
|
|
188
|
+
const rows = await db
|
|
189
|
+
.prepare(
|
|
190
|
+
`SELECT m.contact_id AS id, c.email AS email, m.status AS status, m.subscribed_at AS subscribedAt, m.unsubscribed_at AS unsubscribedAt,
|
|
191
|
+
m.unsub_source AS unsubSource, m.unsub_reason AS unsubReason, m.source AS source, m.segment AS segment, m.segment_label AS segmentLabel,
|
|
192
|
+
EXISTS (SELECT 1 FROM suppressions s WHERE s.email = c.email AND s.reason IN ('hard_bounce', 'complaint', 'unsubscribe')) AS suppressed
|
|
193
|
+
FROM list_members m JOIN contacts c ON c.id = m.contact_id
|
|
194
|
+
WHERE m.list_id = ? AND m.contact_id > ? ${input.status ? 'AND m.status = ?' : ''}
|
|
195
|
+
ORDER BY m.contact_id LIMIT ?`,
|
|
196
|
+
)
|
|
197
|
+
.bind(...[input.list, after, ...(input.status ? [input.status] : []), limit + 1])
|
|
198
|
+
.all<Omit<MemberRow, 'suppressed'> & { id: number; suppressed: number }>();
|
|
199
|
+
const more = rows.results.length > limit;
|
|
200
|
+
const page = rows.results.slice(0, limit);
|
|
201
|
+
const next = more ? String(page[page.length - 1].id) : null;
|
|
202
|
+
return { members: page.map(({ id: _id, suppressed, ...m }) => ({ ...m, suppressed: !!suppressed })), next };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---------- 分群欄位寫入 ----------
|
|
206
|
+
|
|
207
|
+
export interface SegmentInput { email: string; segment: string; segmentLabel?: string }
|
|
208
|
+
export type SegmentResult = { ok: true; updated: number; notMember: number; invalid: number } | { ok: false; reason: 'bad_list' | 'unknown_list' | 'too_many' | 'bad_body' };
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 寫入分群欄位(每週從分析那頭抄一份)。只更新已經在名單裡的人,不建立新成員;同一份再送一次結果一樣(冪等)。
|
|
212
|
+
* 一次最多 5,000 筆;無效的列(信箱或分群空白)略過並計數。
|
|
213
|
+
*/
|
|
214
|
+
export async function setSegments(db: ListDb, listId: string, items: SegmentInput[], now?: () => Date): Promise<SegmentResult> {
|
|
215
|
+
if (typeof listId !== 'string' || !LIST_ID.test(listId)) return { ok: false, reason: 'bad_list' };
|
|
216
|
+
if (!Array.isArray(items)) return { ok: false, reason: 'bad_body' };
|
|
217
|
+
if (items.length > MAX_SEGMENT_ROWS) return { ok: false, reason: 'too_many' };
|
|
218
|
+
if (!(await listExists(db, listId))) return { ok: false, reason: 'unknown_list' };
|
|
219
|
+
const t = iso(now);
|
|
220
|
+
const stmts: Stmt[] = [];
|
|
221
|
+
let invalid = 0;
|
|
222
|
+
for (const it of items) {
|
|
223
|
+
const email = normalizeEmail(it?.email);
|
|
224
|
+
const segment = text(it?.segment, 100);
|
|
225
|
+
if (!email || !segment) { invalid++; continue; }
|
|
226
|
+
stmts.push(
|
|
227
|
+
db
|
|
228
|
+
.prepare('UPDATE list_members SET segment = ?, segment_label = ?, segment_at = ? WHERE list_id = ? AND contact_id = (SELECT id FROM contacts WHERE email = ?)')
|
|
229
|
+
.bind(segment, text(it.segmentLabel, 100), t, listId, email),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
const changes = await runAll(db, stmts);
|
|
233
|
+
const updated = changes.filter((n) => n > 0).length;
|
|
234
|
+
return { ok: true, updated, notMember: changes.length - updated, invalid };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ---------- 批次匯入 ----------
|
|
238
|
+
|
|
239
|
+
export const IMPORT_STATUSES = ['subscribed', 'unsubscribed', 'bounced', 'removed', 'complained'] as const;
|
|
240
|
+
export type ImportStatus = (typeof IMPORT_STATUSES)[number];
|
|
241
|
+
/** 同一個信箱在同一批裡出現多次時,取限制最多的那一筆。 */
|
|
242
|
+
const RESTRICTIVENESS: Record<ImportStatus, number> = { subscribed: 1, unsubscribed: 2, removed: 3, bounced: 4, complained: 5 };
|
|
243
|
+
|
|
244
|
+
export interface ImportRow { email: string; status: ImportStatus; name?: string; subscribedAt?: string; unsubscribedAt?: string; source?: string; consentVersion?: string }
|
|
245
|
+
export interface ImportOptions {
|
|
246
|
+
/** 來源系統代號,寫進 imported_from。 */
|
|
247
|
+
importedFrom: string;
|
|
248
|
+
/** 只驗證與試算、不寫入。 */
|
|
249
|
+
dryRun?: boolean;
|
|
250
|
+
/** 對帳用:預期去重後各狀態的筆數。對不上就整批不寫。 */
|
|
251
|
+
expected?: Partial<Record<ImportStatus, number>>;
|
|
252
|
+
}
|
|
253
|
+
export type ImportOutcome = 'subscribed_new' | 'subscribed_unchanged' | 'kept_unsubscribed' | 'blocked' | 'unsubscribed' | 'unsubscribed_unchanged' | 'suppressed' | 'suppressed_unchanged';
|
|
254
|
+
export type ImportReport =
|
|
255
|
+
| { ok: true; dryRun: boolean; total: number; duplicates: number; received: Record<ImportStatus, number>; outcomes: Record<ImportOutcome, number> }
|
|
256
|
+
| { ok: false; reason: 'bad_list' | 'unknown_list' | 'bad_body' | 'too_many' | 'bad_source' | 'invalid_rows' | 'count_mismatch'; problems?: Array<{ index: number; reason: string }>; received?: Record<ImportStatus, number> };
|
|
257
|
+
|
|
258
|
+
const zero = <K extends string>(keys: readonly K[]) => Object.fromEntries(keys.map((k) => [k, 0])) as Record<K, number>;
|
|
259
|
+
const OUTCOMES: readonly ImportOutcome[] = ['subscribed_new', 'subscribed_unchanged', 'kept_unsubscribed', 'blocked', 'unsubscribed', 'unsubscribed_unchanged', 'suppressed', 'suppressed_unchanged'];
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 批次匯入(搬家用)。規則:
|
|
263
|
+
* - subscribed:進名單;但信箱在全域拒收名單 → blocked 不進;已經是 unsubscribed → 維持不變(匯入不准把退訂改回訂閱)。
|
|
264
|
+
* - unsubscribed/removed:記成這份名單的 unsubscribed(unsub_source=import/import-removed);已退訂的不動;不進全域拒收。
|
|
265
|
+
* - bounced/complained:進全域拒收(hard_bounce/complaint,source=import),不建立名單成員。
|
|
266
|
+
* - 先整批驗證(信箱格式、狀態、expected 筆數),任何一筆不合格就整批不寫;通過才寫,寫入冪等,重跑不會重複、不會多出成員。
|
|
267
|
+
*/
|
|
268
|
+
export async function importMembers(db: ListDb, listId: string, rows: ImportRow[], opts: ImportOptions, now?: () => Date): Promise<ImportReport> {
|
|
269
|
+
if (typeof listId !== 'string' || !LIST_ID.test(listId)) return { ok: false, reason: 'bad_list' };
|
|
270
|
+
if (!Array.isArray(rows)) return { ok: false, reason: 'bad_body' };
|
|
271
|
+
if (rows.length > MAX_IMPORT_ROWS) return { ok: false, reason: 'too_many' };
|
|
272
|
+
const importedFrom = text(opts?.importedFrom, 40);
|
|
273
|
+
if (!importedFrom) return { ok: false, reason: 'bad_source' };
|
|
274
|
+
if (!(await listExists(db, listId))) return { ok: false, reason: 'unknown_list' };
|
|
275
|
+
|
|
276
|
+
const problems: Array<{ index: number; reason: string }> = [];
|
|
277
|
+
const byEmail = new Map<string, ImportRow & { email: string }>();
|
|
278
|
+
let duplicates = 0;
|
|
279
|
+
rows.forEach((r, index) => {
|
|
280
|
+
const email = normalizeEmail(r?.email);
|
|
281
|
+
if (!email) return void problems.push({ index, reason: 'bad_email' });
|
|
282
|
+
if (!IMPORT_STATUSES.includes(r.status)) return void problems.push({ index, reason: 'bad_status' });
|
|
283
|
+
const prev = byEmail.get(email);
|
|
284
|
+
if (prev) {
|
|
285
|
+
duplicates++;
|
|
286
|
+
if (RESTRICTIVENESS[r.status] <= RESTRICTIVENESS[prev.status]) return;
|
|
287
|
+
}
|
|
288
|
+
byEmail.set(email, { ...r, email });
|
|
289
|
+
});
|
|
290
|
+
if (problems.length) return { ok: false, reason: 'invalid_rows', problems: problems.slice(0, 20) };
|
|
291
|
+
|
|
292
|
+
const received = zero(IMPORT_STATUSES);
|
|
293
|
+
for (const r of byEmail.values()) received[r.status]++;
|
|
294
|
+
for (const [k, n] of Object.entries(opts.expected ?? {})) {
|
|
295
|
+
if (IMPORT_STATUSES.includes(k as ImportStatus) && received[k as ImportStatus] !== n) return { ok: false, reason: 'count_mismatch', received };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const t = iso(now);
|
|
299
|
+
const outcomes = zero(OUTCOMES);
|
|
300
|
+
const all = [...byEmail.values()];
|
|
301
|
+
for (let i = 0; i < all.length; i += CHUNK) {
|
|
302
|
+
const chunk = all.slice(i, i + CHUNK);
|
|
303
|
+
const emails = chunk.map((r) => r.email);
|
|
304
|
+
const members = new Map(
|
|
305
|
+
(
|
|
306
|
+
await db
|
|
307
|
+
.prepare(`SELECT c.email AS email, m.status AS status FROM list_members m JOIN contacts c ON c.id = m.contact_id WHERE m.list_id = ? AND c.email IN (${marks(emails.length)})`)
|
|
308
|
+
.bind(listId, ...emails)
|
|
309
|
+
.all<{ email: string; status: string }>()
|
|
310
|
+
).results.map((x) => [x.email, x.status]),
|
|
311
|
+
);
|
|
312
|
+
const supp = new Map<string, Set<string>>();
|
|
313
|
+
for (const x of (await db.prepare(`SELECT email, reason FROM suppressions WHERE email IN (${marks(emails.length)})`).bind(...emails).all<{ email: string; reason: string }>()).results) {
|
|
314
|
+
(supp.get(x.email) ?? supp.set(x.email, new Set()).get(x.email)!).add(x.reason);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const stmts: Stmt[] = [];
|
|
318
|
+
const contactStmt = (r: ImportRow & { email: string }) =>
|
|
319
|
+
db
|
|
320
|
+
.prepare(`INSERT INTO contacts (email, name, created_at, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (email) DO UPDATE SET name = COALESCE(contacts.name, excluded.name), updated_at = excluded.updated_at`)
|
|
321
|
+
.bind(r.email, text(r.name), t, t);
|
|
322
|
+
const idOf = '(SELECT id FROM contacts WHERE email = ?)';
|
|
323
|
+
|
|
324
|
+
for (const r of chunk) {
|
|
325
|
+
const existing = members.get(r.email);
|
|
326
|
+
const reasons = supp.get(r.email);
|
|
327
|
+
if (r.status === 'subscribed') {
|
|
328
|
+
if (reasons && reasons.size) { outcomes.blocked++; continue; }
|
|
329
|
+
if (existing === 'unsubscribed') { outcomes.kept_unsubscribed++; continue; }
|
|
330
|
+
if (existing === 'subscribed') { outcomes.subscribed_unchanged++; continue; }
|
|
331
|
+
outcomes.subscribed_new++;
|
|
332
|
+
stmts.push(contactStmt(r));
|
|
333
|
+
stmts.push(
|
|
334
|
+
db
|
|
335
|
+
.prepare(
|
|
336
|
+
`INSERT INTO list_members (list_id, contact_id, status, subscribed_at, source, consent_version, segment, imported_from, updated_at)
|
|
337
|
+
VALUES (?, ${idOf}, 'subscribed', ?, ?, ?, ?, ?, ?) ON CONFLICT (list_id, contact_id) DO NOTHING`,
|
|
338
|
+
)
|
|
339
|
+
.bind(listId, r.email, text(r.subscribedAt, 40) ?? t, text(r.source), text(r.consentVersion), NEW_SEGMENT, importedFrom, t),
|
|
340
|
+
);
|
|
341
|
+
} else if (r.status === 'unsubscribed' || r.status === 'removed') {
|
|
342
|
+
if (existing === 'unsubscribed') { outcomes.unsubscribed_unchanged++; continue; }
|
|
343
|
+
outcomes.unsubscribed++;
|
|
344
|
+
stmts.push(contactStmt(r));
|
|
345
|
+
stmts.push(
|
|
346
|
+
db
|
|
347
|
+
.prepare(
|
|
348
|
+
`INSERT INTO list_members (list_id, contact_id, status, subscribed_at, unsubscribed_at, unsub_source, source, imported_from, updated_at)
|
|
349
|
+
VALUES (?, ${idOf}, 'unsubscribed', ?, ?, ?, ?, ?, ?)
|
|
350
|
+
ON CONFLICT (list_id, contact_id) DO UPDATE SET status = 'unsubscribed', unsubscribed_at = excluded.unsubscribed_at, unsub_source = excluded.unsub_source, updated_at = excluded.updated_at
|
|
351
|
+
WHERE list_members.status != 'unsubscribed'`,
|
|
352
|
+
)
|
|
353
|
+
.bind(listId, r.email, text(r.subscribedAt, 40), text(r.unsubscribedAt, 40) ?? t, r.status === 'removed' ? 'import-removed' : 'import', text(r.source), importedFrom, t),
|
|
354
|
+
);
|
|
355
|
+
} else {
|
|
356
|
+
const reason = r.status === 'bounced' ? 'hard_bounce' : 'complaint';
|
|
357
|
+
if (reasons?.has(reason)) { outcomes.suppressed_unchanged++; continue; }
|
|
358
|
+
outcomes.suppressed++;
|
|
359
|
+
stmts.push(contactStmt(r));
|
|
360
|
+
stmts.push(
|
|
361
|
+
db
|
|
362
|
+
.prepare('INSERT INTO suppressions (email, reason, source, detail, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (email, reason) DO NOTHING')
|
|
363
|
+
.bind(r.email, reason, 'import', importedFrom, t),
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (!opts.dryRun) await runAll(db, stmts);
|
|
368
|
+
}
|
|
369
|
+
return { ok: true, dryRun: !!opts.dryRun, total: all.length, duplicates, received, outcomes };
|
|
370
|
+
}
|