@dench.com/cli 2.8.8-staging.192 → 2.9.1-staging.200
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 +31 -0
- package/campaign.ts +2316 -0
- package/crm.ts +54 -12
- package/dench.ts +63 -1
- package/email.ts +6 -2
- package/lib/api-schemas.ts +655 -0
- package/lib/command-registry.ts +332 -0
- package/members.ts +274 -6
- package/package.json +2 -1
package/campaign.ts
ADDED
|
@@ -0,0 +1,2316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dench campaign <subcommand>` — outreach campaigns (email + LinkedIn steps
|
|
3
|
+
* on one schedule) from the terminal, and therefore from chat.
|
|
4
|
+
*
|
|
5
|
+
* Every subcommand talks straight to `functions/outreachSequences:*` over the
|
|
6
|
+
* Convex HTTP client; there is no campaign-specific HTTP route. `dench email
|
|
7
|
+
* multichannel` drives the same rows and keeps working — this namespace is
|
|
8
|
+
* the fuller surface (schedule, steps round-trip, fill from a CRM view, the
|
|
9
|
+
* Now/Next feed, per-person controls, the activity log).
|
|
10
|
+
*
|
|
11
|
+
* `<campaign>` is an id or an exact, case-insensitive name. A name shared by
|
|
12
|
+
* several live campaigns is an error that lists the ids.
|
|
13
|
+
*
|
|
14
|
+
* Auth: outreach functions need a workspace member's credentials (a saved
|
|
15
|
+
* `dench signin` session, a member-bound `DENCH_API_KEY`, or an agent session
|
|
16
|
+
* created by a member). An organization-only key is refused server-side.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { readFile } from "node:fs/promises";
|
|
20
|
+
import type { ConvexHttpClient } from "convex/browser";
|
|
21
|
+
import { makeFunctionReference } from "convex/server";
|
|
22
|
+
import { collectPaginated } from "./email";
|
|
23
|
+
import {
|
|
24
|
+
assertNoUnknownFlags,
|
|
25
|
+
CliArgError,
|
|
26
|
+
getFlag,
|
|
27
|
+
hasFlag,
|
|
28
|
+
shift as shiftRaw,
|
|
29
|
+
} from "./lib/cli-args";
|
|
30
|
+
|
|
31
|
+
export class CampaignCliError extends Error {}
|
|
32
|
+
|
|
33
|
+
type JsonRecord = Record<string, unknown>;
|
|
34
|
+
|
|
35
|
+
type CampaignCliContext = {
|
|
36
|
+
convex: ConvexHttpClient;
|
|
37
|
+
args: string[];
|
|
38
|
+
jsonOutput: boolean;
|
|
39
|
+
sessionToken?: string;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const OUTREACH = "functions/outreachSequences";
|
|
43
|
+
const MATERIALIZE_VIEW = "functions/crm/objects:materializeView";
|
|
44
|
+
|
|
45
|
+
/** Mirrors convex/lib/outreach/enrollBatch.ts; the CLI package cannot import from convex/. */
|
|
46
|
+
export const CRM_ENROLL_CHUNK_SIZE = 100;
|
|
47
|
+
/** How many people one campaign can hold (MAX_CAMPAIGN_PEOPLE on the server). */
|
|
48
|
+
export const MAX_CAMPAIGN_PEOPLE = 300;
|
|
49
|
+
/** Page size used when reading a CRM view; 100 keeps rows under the byte budget. */
|
|
50
|
+
export const VIEW_PAGE_SIZE = 100;
|
|
51
|
+
const MAX_VIEW_PAGES = 50;
|
|
52
|
+
const MAX_STEPS = 20;
|
|
53
|
+
const PEOPLE_PREVIEW_LIMIT = 50;
|
|
54
|
+
const DEFAULT_EVENTS_PAGE_SIZE = 50;
|
|
55
|
+
const MAX_EVENTS_PAGE_SIZE = 200;
|
|
56
|
+
|
|
57
|
+
// ─── Shapes (subset of the server's return values that the CLI reads) ─────
|
|
58
|
+
|
|
59
|
+
export type SendSchedule = {
|
|
60
|
+
name: string;
|
|
61
|
+
timezone: string;
|
|
62
|
+
startHour: number;
|
|
63
|
+
endHour: number;
|
|
64
|
+
weekdays: number[];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type CampaignRow = {
|
|
68
|
+
_id: string;
|
|
69
|
+
name: string;
|
|
70
|
+
status: string;
|
|
71
|
+
stopOnReply?: boolean;
|
|
72
|
+
timezone?: string;
|
|
73
|
+
startsAt?: number;
|
|
74
|
+
endsAt?: number;
|
|
75
|
+
sendSchedules?: SendSchedule[];
|
|
76
|
+
dailySendCap?: number;
|
|
77
|
+
stepCount?: number;
|
|
78
|
+
totalEnrolled?: number;
|
|
79
|
+
activeCount?: number;
|
|
80
|
+
pausedCount?: number;
|
|
81
|
+
finishedCount?: number;
|
|
82
|
+
repliedCount?: number;
|
|
83
|
+
failedCount?: number;
|
|
84
|
+
stoppedCount?: number;
|
|
85
|
+
launchedAt?: number;
|
|
86
|
+
completedAt?: number;
|
|
87
|
+
lastError?: string;
|
|
88
|
+
ownerName?: string;
|
|
89
|
+
isOwner?: boolean;
|
|
90
|
+
createdAt?: number;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
type Enrollment = {
|
|
94
|
+
_id: string;
|
|
95
|
+
displayName?: string;
|
|
96
|
+
status: string;
|
|
97
|
+
currentStepIndex?: number;
|
|
98
|
+
nextRunAt?: number;
|
|
99
|
+
lastError?: string;
|
|
100
|
+
repliedAt?: number;
|
|
101
|
+
linkedinProfileUrl?: string;
|
|
102
|
+
entryId?: string;
|
|
103
|
+
leadEntryId?: string;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
type LinkedinHold = { reason: string; until?: number };
|
|
107
|
+
|
|
108
|
+
type CurrentRun = {
|
|
109
|
+
status?: string;
|
|
110
|
+
type?: string;
|
|
111
|
+
stepIndex?: number;
|
|
112
|
+
waitUntil?: number;
|
|
113
|
+
retryAt?: number;
|
|
114
|
+
lastError?: string;
|
|
115
|
+
hold?: LinkedinHold;
|
|
116
|
+
linkedinAction?: { kind?: string; status?: string; lastError?: string };
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
type CampaignDetail = {
|
|
120
|
+
sequence: CampaignRow;
|
|
121
|
+
steps: Array<JsonRecord & { type: string; order?: number }>;
|
|
122
|
+
enrollments: Enrollment[];
|
|
123
|
+
currentRuns?: Record<string, CurrentRun>;
|
|
124
|
+
lastTouches?: Record<string, { type: string; at: number }>;
|
|
125
|
+
connectedEntries?: Record<
|
|
126
|
+
string,
|
|
127
|
+
{
|
|
128
|
+
entryId: string;
|
|
129
|
+
objectName: string;
|
|
130
|
+
label: string;
|
|
131
|
+
lead: { entryId: string; status: string | null } | null;
|
|
132
|
+
}
|
|
133
|
+
>;
|
|
134
|
+
isOwner?: boolean;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
type CampaignAnalytics = {
|
|
138
|
+
audience?: number;
|
|
139
|
+
contacted?: number;
|
|
140
|
+
linkedinInvited?: number;
|
|
141
|
+
linkedinConnected?: number;
|
|
142
|
+
linkedinMessaged?: number;
|
|
143
|
+
linkedinReplied?: number;
|
|
144
|
+
active?: number;
|
|
145
|
+
paused?: number;
|
|
146
|
+
finished?: number;
|
|
147
|
+
replied?: number;
|
|
148
|
+
failed?: number;
|
|
149
|
+
stopped?: number;
|
|
150
|
+
emailSent?: number;
|
|
151
|
+
opened?: number;
|
|
152
|
+
clicked?: number;
|
|
153
|
+
linkedinSent?: number;
|
|
154
|
+
replyRate?: number;
|
|
155
|
+
truncated?: boolean;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
type CampaignLive = {
|
|
159
|
+
status: string;
|
|
160
|
+
usesEmail: boolean;
|
|
161
|
+
usesLinkedin: boolean;
|
|
162
|
+
emailsToday: number;
|
|
163
|
+
dailySendCap: number | null;
|
|
164
|
+
nextEmailAt: number | null;
|
|
165
|
+
now: {
|
|
166
|
+
kind: string;
|
|
167
|
+
enrollmentId: string;
|
|
168
|
+
personName: string;
|
|
169
|
+
startedAt: number;
|
|
170
|
+
} | null;
|
|
171
|
+
next: {
|
|
172
|
+
kind: string;
|
|
173
|
+
enrollmentId: string | null;
|
|
174
|
+
personName: string | null;
|
|
175
|
+
at: number;
|
|
176
|
+
hold: LinkedinHold | null;
|
|
177
|
+
} | null;
|
|
178
|
+
paused: {
|
|
179
|
+
reason: string;
|
|
180
|
+
detail: string | null;
|
|
181
|
+
resumesAt: number | null;
|
|
182
|
+
} | null;
|
|
183
|
+
senders: Array<{
|
|
184
|
+
displayName: string;
|
|
185
|
+
ownerName: string | null;
|
|
186
|
+
status: string;
|
|
187
|
+
statusReason: string | null;
|
|
188
|
+
timezone: string;
|
|
189
|
+
windowStartMinutes: number;
|
|
190
|
+
windowEndMinutes: number;
|
|
191
|
+
dailyInviteLimit: number;
|
|
192
|
+
weeklyInviteLimit: number;
|
|
193
|
+
dailyMessageLimit: number;
|
|
194
|
+
usage: {
|
|
195
|
+
invitesToday: number;
|
|
196
|
+
messagesToday: number;
|
|
197
|
+
invitesThisWeek: number;
|
|
198
|
+
};
|
|
199
|
+
inWindow: boolean;
|
|
200
|
+
nextWindowOpenAt: number | null;
|
|
201
|
+
}>;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
type LaunchBlockerGroup = {
|
|
205
|
+
code: string;
|
|
206
|
+
title: string;
|
|
207
|
+
hint?: string;
|
|
208
|
+
stepIndex?: number;
|
|
209
|
+
people: Array<{ enrollmentId?: string; name: string }>;
|
|
210
|
+
count: number;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
type LaunchReadiness = {
|
|
214
|
+
ready: boolean;
|
|
215
|
+
fingerprint?: string;
|
|
216
|
+
blockingReasons?: string[];
|
|
217
|
+
blockers?: LaunchBlockerGroup[];
|
|
218
|
+
warnings?: string[];
|
|
219
|
+
stepCount?: number;
|
|
220
|
+
audienceCount?: number;
|
|
221
|
+
usesEmail?: boolean;
|
|
222
|
+
usesLinkedin?: boolean;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
export type EnrollFromCrmResult = {
|
|
226
|
+
added: number;
|
|
227
|
+
requested: number;
|
|
228
|
+
cappedAtLimit: number | null;
|
|
229
|
+
duplicates: number;
|
|
230
|
+
merged: number;
|
|
231
|
+
duplicatesElsewhere: number;
|
|
232
|
+
suppressed: number;
|
|
233
|
+
invalid: number;
|
|
234
|
+
skippedNoIdentity: number;
|
|
235
|
+
skippedSample: number;
|
|
236
|
+
skippedMissingInfo: number;
|
|
237
|
+
missingInfoSample?: { displayName?: string; missingKeys: string[] };
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// ─── Plumbing ─────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
function shift(args: string[], expected: string): string {
|
|
243
|
+
let value: string;
|
|
244
|
+
try {
|
|
245
|
+
value = shiftRaw(args, expected);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (error instanceof CliArgError) throw new CampaignCliError(error.message);
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
if (value.startsWith("--")) {
|
|
251
|
+
throw new CampaignCliError(
|
|
252
|
+
`Missing ${expected}: it is positional, so write it before or after the flags, e.g. dench campaign get "Founder outreach" --json`,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
return value;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function unknownFlags(args: readonly string[], command: string): void {
|
|
259
|
+
try {
|
|
260
|
+
assertNoUnknownFlags(args, command);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error instanceof CliArgError) throw new CampaignCliError(error.message);
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function callQuery(
|
|
268
|
+
ctx: CampaignCliContext,
|
|
269
|
+
name: string,
|
|
270
|
+
args: JsonRecord,
|
|
271
|
+
): Promise<unknown> {
|
|
272
|
+
const ref = makeFunctionReference<"query">(name);
|
|
273
|
+
return await ctx.convex.query(ref, {
|
|
274
|
+
...args,
|
|
275
|
+
sessionToken: ctx.sessionToken,
|
|
276
|
+
} as never);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async function callMutation(
|
|
280
|
+
ctx: CampaignCliContext,
|
|
281
|
+
name: string,
|
|
282
|
+
args: JsonRecord,
|
|
283
|
+
): Promise<unknown> {
|
|
284
|
+
const ref = makeFunctionReference<"mutation">(name);
|
|
285
|
+
return await ctx.convex.mutation(ref, {
|
|
286
|
+
...args,
|
|
287
|
+
sessionToken: ctx.sessionToken,
|
|
288
|
+
} as never);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function out(
|
|
292
|
+
ctx: CampaignCliContext,
|
|
293
|
+
payload: unknown,
|
|
294
|
+
text: string | string[],
|
|
295
|
+
): void {
|
|
296
|
+
if (ctx.jsonOutput) {
|
|
297
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
console.log(Array.isArray(text) ? text.join("\n") : text);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Warnings go to stderr so `--json` stdout stays parseable. */
|
|
304
|
+
function warn(ctx: CampaignCliContext, message: string): void {
|
|
305
|
+
if (!ctx.jsonOutput) console.error(`Warning: ${message}`);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function requiredFlag(args: string[], name: string): string {
|
|
309
|
+
const value = valueFlag(args, name)?.trim();
|
|
310
|
+
if (!value) throw new CampaignCliError(`Missing required ${name}`);
|
|
311
|
+
return value;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `getFlag` for a flag that carries a value. A flag left at the end of the
|
|
316
|
+
* line, or followed by another flag, is a mistake — dropping it silently
|
|
317
|
+
* would report success for a change that never happened.
|
|
318
|
+
*/
|
|
319
|
+
function valueFlag(args: string[], name: string): string | undefined {
|
|
320
|
+
if (!args.includes(name)) return undefined;
|
|
321
|
+
const value = getFlag(args, name);
|
|
322
|
+
if (value === undefined || value.startsWith("--")) {
|
|
323
|
+
throw new CampaignCliError(`${name} needs a value`);
|
|
324
|
+
}
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Every occurrence of a repeatable flag, in order. */
|
|
329
|
+
function getAllFlags(args: string[], name: string): string[] {
|
|
330
|
+
const values: string[] = [];
|
|
331
|
+
while (args.includes(name)) {
|
|
332
|
+
const value = valueFlag(args, name);
|
|
333
|
+
if (value !== undefined) values.push(value);
|
|
334
|
+
}
|
|
335
|
+
return values;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// ─── Pure parsers (exported for tests) ────────────────────────────────────
|
|
339
|
+
|
|
340
|
+
const DAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
341
|
+
|
|
342
|
+
const DAY_ALIASES: Record<string, number> = {
|
|
343
|
+
sun: 0,
|
|
344
|
+
sunday: 0,
|
|
345
|
+
mon: 1,
|
|
346
|
+
monday: 1,
|
|
347
|
+
tue: 2,
|
|
348
|
+
tues: 2,
|
|
349
|
+
tuesday: 2,
|
|
350
|
+
wed: 3,
|
|
351
|
+
weds: 3,
|
|
352
|
+
wednesday: 3,
|
|
353
|
+
thu: 4,
|
|
354
|
+
thur: 4,
|
|
355
|
+
thurs: 4,
|
|
356
|
+
thursday: 4,
|
|
357
|
+
fri: 5,
|
|
358
|
+
friday: 5,
|
|
359
|
+
sat: 6,
|
|
360
|
+
saturday: 6,
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
const DAY_GROUPS: Record<string, number[]> = {
|
|
364
|
+
weekdays: [1, 2, 3, 4, 5],
|
|
365
|
+
weekday: [1, 2, 3, 4, 5],
|
|
366
|
+
weekends: [0, 6],
|
|
367
|
+
weekend: [0, 6],
|
|
368
|
+
daily: [0, 1, 2, 3, 4, 5, 6],
|
|
369
|
+
everyday: [0, 1, 2, 3, 4, 5, 6],
|
|
370
|
+
"every-day": [0, 1, 2, 3, 4, 5, 6],
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
const WINDOW_HELP =
|
|
374
|
+
'Write a send window as "<days> <start>-<end>", e.g. "Mon-Fri 9-18", "Mon,Wed,Fri 10-16", "Weekdays 9am-5pm". Hours are whole hours, 0-24.';
|
|
375
|
+
|
|
376
|
+
function dayIndex(token: string): number {
|
|
377
|
+
const day = DAY_ALIASES[token.toLowerCase()];
|
|
378
|
+
if (day === undefined) {
|
|
379
|
+
throw new CampaignCliError(
|
|
380
|
+
`Unknown day "${token}" in --window. ${WINDOW_HELP}`,
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
return day;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function parseDays(part: string): number[] {
|
|
387
|
+
const days = new Set<number>();
|
|
388
|
+
for (const token of part.split(",")) {
|
|
389
|
+
const cleaned = token.trim();
|
|
390
|
+
if (!cleaned) continue;
|
|
391
|
+
const group = DAY_GROUPS[cleaned.toLowerCase()];
|
|
392
|
+
if (group) {
|
|
393
|
+
for (const day of group) days.add(day);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
const range = cleaned.match(/^([A-Za-z]+)\s*[-–]\s*([A-Za-z]+)$/);
|
|
397
|
+
if (range) {
|
|
398
|
+
const from = dayIndex(range[1]);
|
|
399
|
+
const to = dayIndex(range[2]);
|
|
400
|
+
let day = from;
|
|
401
|
+
days.add(day);
|
|
402
|
+
while (day !== to) {
|
|
403
|
+
day = (day + 1) % 7;
|
|
404
|
+
days.add(day);
|
|
405
|
+
}
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
days.add(dayIndex(cleaned));
|
|
409
|
+
}
|
|
410
|
+
if (days.size === 0) {
|
|
411
|
+
throw new CampaignCliError(
|
|
412
|
+
`--window needs at least one day. ${WINDOW_HELP}`,
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
return [...days].sort((a, b) => a - b);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function parseHour(token: string, edge: "start" | "end"): number {
|
|
419
|
+
const match = token
|
|
420
|
+
.trim()
|
|
421
|
+
.toLowerCase()
|
|
422
|
+
.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?$/);
|
|
423
|
+
if (!match) {
|
|
424
|
+
throw new CampaignCliError(
|
|
425
|
+
`Cannot read the ${edge} hour "${token}". ${WINDOW_HELP}`,
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
let hour = Number(match[1]);
|
|
429
|
+
const minutes = match[2] ? Number(match[2]) : 0;
|
|
430
|
+
if (minutes !== 0) {
|
|
431
|
+
throw new CampaignCliError(
|
|
432
|
+
`Send windows use whole hours; "${token}" has minutes. ${WINDOW_HELP}`,
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
const meridiem = match[3];
|
|
436
|
+
if (meridiem) {
|
|
437
|
+
if (hour < 1 || hour > 12) {
|
|
438
|
+
throw new CampaignCliError(
|
|
439
|
+
`"${token}" is not a valid clock hour. ${WINDOW_HELP}`,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
if (meridiem === "am") hour = hour === 12 ? 0 : hour;
|
|
443
|
+
else hour = hour === 12 ? 12 : hour + 12;
|
|
444
|
+
}
|
|
445
|
+
const max = edge === "start" ? 23 : 24;
|
|
446
|
+
if (hour < 0 || hour > max) {
|
|
447
|
+
throw new CampaignCliError(
|
|
448
|
+
`The ${edge} hour must be between 0 and ${max}, got "${token}". ${WINDOW_HELP}`,
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
return hour;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** "Mon-Fri" for a consecutive run, otherwise "Mon, Wed, Fri". */
|
|
455
|
+
export function formatWeekdays(weekdays: readonly number[]): string {
|
|
456
|
+
const days = [...new Set(weekdays)].sort((a, b) => a - b);
|
|
457
|
+
if (days.length === 0) return "no days";
|
|
458
|
+
if (days.length === 7) return "Every day";
|
|
459
|
+
const consecutive =
|
|
460
|
+
days.length > 2 &&
|
|
461
|
+
days.every((day, i) => i === 0 || day === days[i - 1] + 1);
|
|
462
|
+
if (consecutive) {
|
|
463
|
+
return `${DAY_LABELS[days[0]]}-${DAY_LABELS[days[days.length - 1]]}`;
|
|
464
|
+
}
|
|
465
|
+
return days.map((day) => DAY_LABELS[day]).join(", ");
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export type WindowSpec = {
|
|
469
|
+
name: string;
|
|
470
|
+
startHour: number;
|
|
471
|
+
endHour: number;
|
|
472
|
+
weekdays: number[];
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* `"Mon-Fri 9-18"`, `"Mon,Wed,Fri 10-16"`, `"Weekdays 9am-5pm"` →
|
|
477
|
+
* `{ name, startHour, endHour, weekdays }`. The timezone is added by the
|
|
478
|
+
* caller so several windows can share one `--timezone`.
|
|
479
|
+
*/
|
|
480
|
+
export function parseWindowSpec(spec: string): WindowSpec {
|
|
481
|
+
const trimmed = spec.trim().replace(/\s+/g, " ");
|
|
482
|
+
const split = trimmed.lastIndexOf(" ");
|
|
483
|
+
if (split === -1) {
|
|
484
|
+
throw new CampaignCliError(
|
|
485
|
+
`Cannot read the send window "${spec}". ${WINDOW_HELP}`,
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
const daysPart = trimmed.slice(0, split);
|
|
489
|
+
const hoursPart = trimmed.slice(split + 1);
|
|
490
|
+
const hours = hoursPart.split(/[-–]/).map((part) => part.trim());
|
|
491
|
+
if (hours.length !== 2) {
|
|
492
|
+
throw new CampaignCliError(
|
|
493
|
+
`The send window "${spec}" needs a start and an end hour. ${WINDOW_HELP}`,
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
const weekdays = parseDays(daysPart);
|
|
497
|
+
const startHour = parseHour(hours[0], "start");
|
|
498
|
+
const endHour = parseHour(hours[1], "end");
|
|
499
|
+
if (endHour <= startHour) {
|
|
500
|
+
throw new CampaignCliError(
|
|
501
|
+
`The send window "${spec}" must end after it starts. ${WINDOW_HELP}`,
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
return {
|
|
505
|
+
name: `${formatWeekdays(weekdays)} ${startHour}-${endHour}`,
|
|
506
|
+
startHour,
|
|
507
|
+
endHour,
|
|
508
|
+
weekdays,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
export function buildSendSchedules(
|
|
513
|
+
specs: readonly string[],
|
|
514
|
+
timezone: string,
|
|
515
|
+
): SendSchedule[] {
|
|
516
|
+
if (specs.length === 0) {
|
|
517
|
+
throw new CampaignCliError(`Pass at least one --window. ${WINDOW_HELP}`);
|
|
518
|
+
}
|
|
519
|
+
if (specs.length > 8) {
|
|
520
|
+
throw new CampaignCliError("Use at most eight --window values.");
|
|
521
|
+
}
|
|
522
|
+
const tz = assertIanaTimezone(timezone);
|
|
523
|
+
return specs.map((spec) => ({ ...parseWindowSpec(spec), timezone: tz }));
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export function assertIanaTimezone(timezone: string): string {
|
|
527
|
+
const tz = timezone.trim();
|
|
528
|
+
try {
|
|
529
|
+
new Intl.DateTimeFormat("en-US", { timeZone: tz }).format();
|
|
530
|
+
} catch {
|
|
531
|
+
throw new CampaignCliError(
|
|
532
|
+
`"${timezone}" is not an IANA timezone. Use one like America/Los_Angeles or Europe/London.`,
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
return tz;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function businessHoursSchedule(timezone: string): SendSchedule {
|
|
539
|
+
return {
|
|
540
|
+
name: "Business hours",
|
|
541
|
+
timezone,
|
|
542
|
+
startHour: 9,
|
|
543
|
+
endHour: 18,
|
|
544
|
+
weekdays: [1, 2, 3, 4, 5],
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export const STEP_TYPES = [
|
|
549
|
+
"wait",
|
|
550
|
+
"email",
|
|
551
|
+
"linkedin_connection",
|
|
552
|
+
"linkedin_message",
|
|
553
|
+
"linkedin_visit",
|
|
554
|
+
] as const;
|
|
555
|
+
|
|
556
|
+
const STEP_KEYS = new Set([
|
|
557
|
+
"type",
|
|
558
|
+
"waitHours",
|
|
559
|
+
"emailMailboxAccountId",
|
|
560
|
+
"emailSubject",
|
|
561
|
+
"emailHtmlBody",
|
|
562
|
+
"emailTextBody",
|
|
563
|
+
"emailReplyToPrevious",
|
|
564
|
+
"onlyIf",
|
|
565
|
+
"linkedinAccountId",
|
|
566
|
+
"linkedinMessageBody",
|
|
567
|
+
"linkedinMessageMode",
|
|
568
|
+
"connectionTimeoutHours",
|
|
569
|
+
]);
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Parse a steps file: a JSON array of step objects (or `{ "steps": [...] }`).
|
|
573
|
+
* Checks the shape the server validates so a typo is caught here with a
|
|
574
|
+
* step number instead of a Convex validator message.
|
|
575
|
+
*/
|
|
576
|
+
export function parseStepsJson(
|
|
577
|
+
raw: string,
|
|
578
|
+
source = "The steps file",
|
|
579
|
+
): JsonRecord[] {
|
|
580
|
+
let parsed: unknown;
|
|
581
|
+
try {
|
|
582
|
+
parsed = JSON.parse(raw);
|
|
583
|
+
} catch {
|
|
584
|
+
throw new CampaignCliError(`${source} is not valid JSON.`);
|
|
585
|
+
}
|
|
586
|
+
const steps = Array.isArray(parsed)
|
|
587
|
+
? parsed
|
|
588
|
+
: parsed &&
|
|
589
|
+
typeof parsed === "object" &&
|
|
590
|
+
Array.isArray((parsed as JsonRecord).steps)
|
|
591
|
+
? ((parsed as JsonRecord).steps as unknown[])
|
|
592
|
+
: null;
|
|
593
|
+
if (!steps) {
|
|
594
|
+
throw new CampaignCliError(
|
|
595
|
+
`${source} must be a JSON array of steps (or an object with a "steps" array).`,
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
if (steps.length === 0) {
|
|
599
|
+
throw new CampaignCliError(`${source} has no steps.`);
|
|
600
|
+
}
|
|
601
|
+
if (steps.length > MAX_STEPS) {
|
|
602
|
+
throw new CampaignCliError(
|
|
603
|
+
`A campaign can have at most ${MAX_STEPS} steps.`,
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
return steps.map((step, index) => {
|
|
607
|
+
const label = `Step ${index + 1}`;
|
|
608
|
+
if (!step || typeof step !== "object" || Array.isArray(step)) {
|
|
609
|
+
throw new CampaignCliError(`${label} must be an object with a "type".`);
|
|
610
|
+
}
|
|
611
|
+
const row = step as JsonRecord;
|
|
612
|
+
const type = row.type;
|
|
613
|
+
if (
|
|
614
|
+
typeof type !== "string" ||
|
|
615
|
+
!(STEP_TYPES as readonly string[]).includes(type)
|
|
616
|
+
) {
|
|
617
|
+
throw new CampaignCliError(
|
|
618
|
+
`${label} has type ${JSON.stringify(type)}. Use one of: ${STEP_TYPES.join(", ")}.`,
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
const unknown = Object.keys(row).filter((key) => !STEP_KEYS.has(key));
|
|
622
|
+
if (unknown.length > 0) {
|
|
623
|
+
throw new CampaignCliError(
|
|
624
|
+
`${label} has keys the engine does not know: ${unknown.join(", ")}. Allowed: ${[...STEP_KEYS].join(", ")}.`,
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
if (type === "wait") {
|
|
628
|
+
if (typeof row.waitHours !== "number" || !(row.waitHours > 0)) {
|
|
629
|
+
throw new CampaignCliError(
|
|
630
|
+
`${label} is a wait step and needs "waitHours" above 0.`,
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (row.waitHours !== undefined && typeof row.waitHours !== "number") {
|
|
635
|
+
throw new CampaignCliError(
|
|
636
|
+
`${label}: "waitHours" must be a number of hours.`,
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
if (
|
|
640
|
+
row.onlyIf !== undefined &&
|
|
641
|
+
!["always", "connected", "not_connected"].includes(String(row.onlyIf))
|
|
642
|
+
) {
|
|
643
|
+
throw new CampaignCliError(
|
|
644
|
+
`${label}: "onlyIf" must be always, connected or not_connected.`,
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
if (
|
|
648
|
+
row.linkedinMessageMode !== undefined &&
|
|
649
|
+
!["skip_if_not_connected", "wait_until_connected"].includes(
|
|
650
|
+
String(row.linkedinMessageMode),
|
|
651
|
+
)
|
|
652
|
+
) {
|
|
653
|
+
throw new CampaignCliError(
|
|
654
|
+
`${label}: "linkedinMessageMode" must be skip_if_not_connected or wait_until_connected.`,
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
return row;
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** The stored step reduced to the shape `steps set --file` accepts, so `steps get` round-trips. */
|
|
662
|
+
export function stepToInput(step: JsonRecord): JsonRecord {
|
|
663
|
+
const input: JsonRecord = {};
|
|
664
|
+
for (const key of STEP_KEYS) {
|
|
665
|
+
if (step[key] !== undefined && step[key] !== null) input[key] = step[key];
|
|
666
|
+
}
|
|
667
|
+
return input;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* A `--start`/`--end` value. A full timestamp is an instant already; a bare
|
|
672
|
+
* date (`2026-09-03`) stays a date until the campaign's timezone is known,
|
|
673
|
+
* because midnight in Los Angeles is not midnight in UTC.
|
|
674
|
+
*/
|
|
675
|
+
export type WhenFlag = number | { date: string };
|
|
676
|
+
|
|
677
|
+
export type ScheduleFlags = {
|
|
678
|
+
timezone?: string;
|
|
679
|
+
dailySendCap?: number;
|
|
680
|
+
stopOnReply?: boolean;
|
|
681
|
+
startsAt?: WhenFlag | null;
|
|
682
|
+
endsAt?: WhenFlag | null;
|
|
683
|
+
windows: string[];
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
687
|
+
|
|
688
|
+
function parseWhenFlag(value: string, flag: string): WhenFlag {
|
|
689
|
+
const trimmed = value.trim();
|
|
690
|
+
const dateOnly = trimmed.match(DATE_ONLY);
|
|
691
|
+
if (dateOnly) {
|
|
692
|
+
const [, year, month, day] = dateOnly.map(Number);
|
|
693
|
+
const utc = new Date(Date.UTC(year, month - 1, day));
|
|
694
|
+
if (
|
|
695
|
+
utc.getUTCFullYear() !== year ||
|
|
696
|
+
utc.getUTCMonth() !== month - 1 ||
|
|
697
|
+
utc.getUTCDate() !== day
|
|
698
|
+
) {
|
|
699
|
+
throw new CampaignCliError(`${flag}: "${value}" is not a calendar date.`);
|
|
700
|
+
}
|
|
701
|
+
return { date: trimmed };
|
|
702
|
+
}
|
|
703
|
+
const parsed = Date.parse(trimmed);
|
|
704
|
+
if (!Number.isFinite(parsed)) {
|
|
705
|
+
throw new CampaignCliError(
|
|
706
|
+
`${flag} must be an ISO 8601 date or date-time, e.g. 2026-09-03 or 2026-09-03T09:00:00-07:00 (got "${value}").`,
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
return parsed;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** The zone's UTC offset at `ms`, in milliseconds (positive east of UTC). */
|
|
713
|
+
function timezoneOffsetMs(ms: number, timeZone: string): number {
|
|
714
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
715
|
+
timeZone,
|
|
716
|
+
hourCycle: "h23",
|
|
717
|
+
year: "numeric",
|
|
718
|
+
month: "2-digit",
|
|
719
|
+
day: "2-digit",
|
|
720
|
+
hour: "2-digit",
|
|
721
|
+
minute: "2-digit",
|
|
722
|
+
second: "2-digit",
|
|
723
|
+
}).formatToParts(new Date(ms));
|
|
724
|
+
const read = (type: string) =>
|
|
725
|
+
Number(parts.find((part) => part.type === type)?.value ?? 0);
|
|
726
|
+
const wallClockAsUtc = Date.UTC(
|
|
727
|
+
read("year"),
|
|
728
|
+
read("month") - 1,
|
|
729
|
+
read("day"),
|
|
730
|
+
read("hour"),
|
|
731
|
+
read("minute"),
|
|
732
|
+
read("second"),
|
|
733
|
+
);
|
|
734
|
+
return wallClockAsUtc - (ms - (ms % 1000));
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Midnight at the start of `date` (YYYY-MM-DD) in `timezone`, as epoch ms. */
|
|
738
|
+
export function zonedMidnight(date: string, timezone: string): number {
|
|
739
|
+
const timeZone = assertIanaTimezone(timezone);
|
|
740
|
+
const [year, month, day] = date.split("-").map(Number);
|
|
741
|
+
const utcMidnight = Date.UTC(year, month - 1, day);
|
|
742
|
+
const offset = timezoneOffsetMs(utcMidnight, timeZone);
|
|
743
|
+
const guess = utcMidnight - offset;
|
|
744
|
+
// Around a DST change the offset in force at the guess differs from the
|
|
745
|
+
// one at UTC midnight; a second pass settles on the zone's own midnight.
|
|
746
|
+
const settled = timezoneOffsetMs(guess, timeZone);
|
|
747
|
+
return settled === offset ? guess : utcMidnight - settled;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function resolveWhen(when: WhenFlag | null, timezone: string): number | null {
|
|
751
|
+
if (when === null || typeof when === "number") return when;
|
|
752
|
+
return zonedMidnight(when.date, timezone);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function whenOrder(when: WhenFlag): number {
|
|
756
|
+
return typeof when === "number" ? when : Date.parse(when.date);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const END_BEFORE_START = "--end must be after --start.";
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Drain the schedule flags shared by `create` and `set`:
|
|
763
|
+
* `--timezone`, `--daily-cap`, `--stop-on-reply|--no-stop-on-reply`,
|
|
764
|
+
* `--start|--clear-start`, `--end|--clear-end`, repeatable `--window`.
|
|
765
|
+
*/
|
|
766
|
+
export function consumeScheduleFlags(args: string[]): ScheduleFlags {
|
|
767
|
+
const flags: ScheduleFlags = { windows: getAllFlags(args, "--window") };
|
|
768
|
+
const timezone = valueFlag(args, "--timezone");
|
|
769
|
+
if (timezone !== undefined) {
|
|
770
|
+
if (!timezone.trim()) {
|
|
771
|
+
throw new CampaignCliError(
|
|
772
|
+
"--timezone needs an IANA timezone like America/New_York",
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
flags.timezone = timezone.trim();
|
|
776
|
+
}
|
|
777
|
+
const cap = valueFlag(args, "--daily-cap");
|
|
778
|
+
if (cap !== undefined) {
|
|
779
|
+
const parsed = Number(cap);
|
|
780
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100) {
|
|
781
|
+
throw new CampaignCliError(
|
|
782
|
+
`--daily-cap must be a whole number from 1 to 100 (got "${cap}").`,
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
flags.dailySendCap = parsed;
|
|
786
|
+
}
|
|
787
|
+
const stopOn = hasFlag(args, "--stop-on-reply");
|
|
788
|
+
const stopOff = hasFlag(args, "--no-stop-on-reply");
|
|
789
|
+
if (stopOn && stopOff) {
|
|
790
|
+
throw new CampaignCliError(
|
|
791
|
+
"Pass either --stop-on-reply or --no-stop-on-reply, not both.",
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
if (stopOn) flags.stopOnReply = true;
|
|
795
|
+
if (stopOff) flags.stopOnReply = false;
|
|
796
|
+
const start = valueFlag(args, "--start");
|
|
797
|
+
const clearStart = hasFlag(args, "--clear-start");
|
|
798
|
+
if (start !== undefined && clearStart) {
|
|
799
|
+
throw new CampaignCliError(
|
|
800
|
+
"Pass either --start or --clear-start, not both.",
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
if (start !== undefined) flags.startsAt = parseWhenFlag(start, "--start");
|
|
804
|
+
if (clearStart) flags.startsAt = null;
|
|
805
|
+
const end = valueFlag(args, "--end");
|
|
806
|
+
const clearEnd = hasFlag(args, "--clear-end");
|
|
807
|
+
if (end !== undefined && clearEnd) {
|
|
808
|
+
throw new CampaignCliError("Pass either --end or --clear-end, not both.");
|
|
809
|
+
}
|
|
810
|
+
if (end !== undefined) flags.endsAt = parseWhenFlag(end, "--end");
|
|
811
|
+
if (clearEnd) flags.endsAt = null;
|
|
812
|
+
// A bare date and a full timestamp can only be compared once the timezone
|
|
813
|
+
// is known (schedulePatchFromFlags); two of the same kind fail fast here.
|
|
814
|
+
if (
|
|
815
|
+
flags.startsAt != null &&
|
|
816
|
+
flags.endsAt != null &&
|
|
817
|
+
typeof flags.startsAt === typeof flags.endsAt &&
|
|
818
|
+
whenOrder(flags.endsAt) <= whenOrder(flags.startsAt)
|
|
819
|
+
) {
|
|
820
|
+
throw new CampaignCliError(END_BEFORE_START);
|
|
821
|
+
}
|
|
822
|
+
return flags;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
export type SchedulePatch = {
|
|
826
|
+
stopOnReply?: boolean;
|
|
827
|
+
dailySendCap?: number;
|
|
828
|
+
startsAt?: number | null;
|
|
829
|
+
endsAt?: number | null;
|
|
830
|
+
sendSchedules?: SendSchedule[];
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Turn parsed flags into the `updateDraft` patch. `--window` values take the
|
|
835
|
+
* `--timezone` (or the campaign's current one). A bare `--timezone` moves the
|
|
836
|
+
* existing windows to that zone, or installs business hours when there are
|
|
837
|
+
* none yet.
|
|
838
|
+
*/
|
|
839
|
+
export function schedulePatchFromFlags(
|
|
840
|
+
flags: ScheduleFlags,
|
|
841
|
+
options: { fallbackTimezone: string; existingSchedules?: SendSchedule[] },
|
|
842
|
+
): SchedulePatch {
|
|
843
|
+
const patch: SchedulePatch = {};
|
|
844
|
+
if (flags.stopOnReply !== undefined) patch.stopOnReply = flags.stopOnReply;
|
|
845
|
+
if (flags.dailySendCap !== undefined) patch.dailySendCap = flags.dailySendCap;
|
|
846
|
+
const timezone = flags.timezone ?? options.fallbackTimezone;
|
|
847
|
+
if (flags.startsAt !== undefined) {
|
|
848
|
+
patch.startsAt = resolveWhen(flags.startsAt, timezone);
|
|
849
|
+
}
|
|
850
|
+
if (flags.endsAt !== undefined) {
|
|
851
|
+
patch.endsAt = resolveWhen(flags.endsAt, timezone);
|
|
852
|
+
}
|
|
853
|
+
if (
|
|
854
|
+
typeof patch.startsAt === "number" &&
|
|
855
|
+
typeof patch.endsAt === "number" &&
|
|
856
|
+
patch.endsAt <= patch.startsAt
|
|
857
|
+
) {
|
|
858
|
+
throw new CampaignCliError(END_BEFORE_START);
|
|
859
|
+
}
|
|
860
|
+
if (flags.windows.length > 0) {
|
|
861
|
+
patch.sendSchedules = buildSendSchedules(flags.windows, timezone);
|
|
862
|
+
} else if (flags.timezone !== undefined) {
|
|
863
|
+
const existing = options.existingSchedules ?? [];
|
|
864
|
+
patch.sendSchedules =
|
|
865
|
+
existing.length > 0
|
|
866
|
+
? existing.map((schedule) => ({ ...schedule, timezone }))
|
|
867
|
+
: [businessHoursSchedule(timezone)];
|
|
868
|
+
}
|
|
869
|
+
return patch;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
export function hasScheduleChanges(patch: SchedulePatch): boolean {
|
|
873
|
+
return Object.keys(patch).length > 0;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
function localTimezone(): string {
|
|
877
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// ─── Formatting ───────────────────────────────────────────────────────────
|
|
881
|
+
|
|
882
|
+
function fmtWhen(ms: number | null | undefined): string {
|
|
883
|
+
if (typeof ms !== "number" || !Number.isFinite(ms)) return "—";
|
|
884
|
+
return new Date(ms).toLocaleString("en-US", {
|
|
885
|
+
dateStyle: "medium",
|
|
886
|
+
timeStyle: "short",
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function fmtRelative(ms: number, now = Date.now()): string {
|
|
891
|
+
const delta = ms - now;
|
|
892
|
+
const abs = Math.abs(delta);
|
|
893
|
+
const unit =
|
|
894
|
+
abs < 60_000
|
|
895
|
+
? `${Math.max(1, Math.round(abs / 1000))}s`
|
|
896
|
+
: abs < 3_600_000
|
|
897
|
+
? `${Math.round(abs / 60_000)}m`
|
|
898
|
+
: abs < 86_400_000
|
|
899
|
+
? `${Math.round(abs / 3_600_000)}h`
|
|
900
|
+
: `${Math.round(abs / 86_400_000)}d`;
|
|
901
|
+
return delta >= 0 ? `in ${unit}` : `${unit} ago`;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
function fmtWhenRelative(ms: number | null | undefined): string {
|
|
905
|
+
if (typeof ms !== "number" || !Number.isFinite(ms)) return "—";
|
|
906
|
+
return `${fmtWhen(ms)} (${fmtRelative(ms)})`;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function fmtMinutes(minutes: number): string {
|
|
910
|
+
const h = Math.floor(minutes / 60);
|
|
911
|
+
const m = minutes % 60;
|
|
912
|
+
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function fmtHours(hours: number): string {
|
|
916
|
+
if (hours % 24 === 0 && hours >= 24) return `${hours / 24}d`;
|
|
917
|
+
return `${hours}h`;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function pct(value: number | undefined): string {
|
|
921
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return "0%";
|
|
922
|
+
return `${Math.round(value * 1000) / 10}%`;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
const STATUS_LABELS: Record<string, string> = {
|
|
926
|
+
draft: "draft",
|
|
927
|
+
active: "active",
|
|
928
|
+
paused: "paused",
|
|
929
|
+
completed: "completed",
|
|
930
|
+
archived: "archived",
|
|
931
|
+
};
|
|
932
|
+
|
|
933
|
+
const STEP_LABELS: Record<string, string> = {
|
|
934
|
+
email: "Email",
|
|
935
|
+
wait: "Wait",
|
|
936
|
+
linkedin_connection: "Connect on LinkedIn",
|
|
937
|
+
linkedin_message: "LinkedIn message",
|
|
938
|
+
linkedin_visit: "Visit profile",
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
function stepLabel(step: { type: string; waitHours?: unknown }): string {
|
|
942
|
+
if (step.type === "wait") {
|
|
943
|
+
const hours = typeof step.waitHours === "number" ? step.waitHours : 0;
|
|
944
|
+
return `Wait ${fmtHours(hours)}`;
|
|
945
|
+
}
|
|
946
|
+
return STEP_LABELS[step.type] ?? step.type;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const HOLD_TEXT: Record<string, string> = {
|
|
950
|
+
checking: "checking whether they are already connected",
|
|
951
|
+
spacing: "spacing out sends so they look human",
|
|
952
|
+
outside_window: "outside the sender's working hours",
|
|
953
|
+
campaign_schedule: "outside the campaign's send window",
|
|
954
|
+
daily_cap: "the sender's daily LinkedIn limit is reached",
|
|
955
|
+
weekly_cap: "the sender's weekly connection limit is reached",
|
|
956
|
+
circuit_break: "paused after LinkedIn errors",
|
|
957
|
+
account_paused: "the LinkedIn account is paused",
|
|
958
|
+
provider_retry: "LinkedIn asked us to retry later",
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
export function describeHold(
|
|
962
|
+
hold: LinkedinHold | null | undefined,
|
|
963
|
+
): string | null {
|
|
964
|
+
if (!hold) return null;
|
|
965
|
+
const text = HOLD_TEXT[hold.reason] ?? hold.reason.replace(/_/g, " ");
|
|
966
|
+
return hold.until ? `${text} (until ${fmtWhenRelative(hold.until)})` : text;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
const PAUSED_TEXT: Record<string, string> = {
|
|
970
|
+
campaign_paused: "the campaign is paused",
|
|
971
|
+
account_disconnected: "a sending account is disconnected",
|
|
972
|
+
email_daily_cap: "today's email cap is reached",
|
|
973
|
+
...HOLD_TEXT,
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
const NOW_VERBS: Record<string, string> = {
|
|
977
|
+
profile: "Visiting the LinkedIn profile of",
|
|
978
|
+
invite: "Sending a connection request to",
|
|
979
|
+
message: "Sending a LinkedIn message to",
|
|
980
|
+
email: "Sending an email to",
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
const NEXT_VERBS: Record<string, string> = {
|
|
984
|
+
profile: "Visit the LinkedIn profile of",
|
|
985
|
+
visit: "Visit the LinkedIn profile of",
|
|
986
|
+
invite: "Send a connection request to",
|
|
987
|
+
message: "Send a LinkedIn message to",
|
|
988
|
+
email: "Send an email to",
|
|
989
|
+
wait: "Wait for",
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
const TOUCH_LABELS: Record<string, string> = {
|
|
993
|
+
email: "email sent",
|
|
994
|
+
linkedin_connection: "invite sent",
|
|
995
|
+
linkedin_message: "LinkedIn message sent",
|
|
996
|
+
linkedin_visit: "profile visited",
|
|
997
|
+
wait: "wait finished",
|
|
998
|
+
};
|
|
999
|
+
|
|
1000
|
+
const RUN_STATUS_TEXT: Record<string, string> = {
|
|
1001
|
+
queued: "queued",
|
|
1002
|
+
running: "sending",
|
|
1003
|
+
waiting: "waiting",
|
|
1004
|
+
retry: "retrying",
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
function describeSchedule(row: CampaignRow): string {
|
|
1008
|
+
const schedules = row.sendSchedules ?? [];
|
|
1009
|
+
const windows =
|
|
1010
|
+
schedules.length > 0
|
|
1011
|
+
? schedules
|
|
1012
|
+
.map(
|
|
1013
|
+
(s) =>
|
|
1014
|
+
`${formatWeekdays(s.weekdays)} ${s.startHour}-${s.endHour} ${s.timezone}`,
|
|
1015
|
+
)
|
|
1016
|
+
.join("; ")
|
|
1017
|
+
: "no send window yet";
|
|
1018
|
+
const parts = [windows];
|
|
1019
|
+
if (typeof row.dailySendCap === "number") {
|
|
1020
|
+
parts.push(`up to ${row.dailySendCap} emails/day`);
|
|
1021
|
+
}
|
|
1022
|
+
parts.push(
|
|
1023
|
+
row.stopOnReply === false ? "keeps going after a reply" : "stops on reply",
|
|
1024
|
+
);
|
|
1025
|
+
if (row.startsAt) parts.push(`starts ${fmtWhen(row.startsAt)}`);
|
|
1026
|
+
if (row.endsAt) parts.push(`ends ${fmtWhen(row.endsAt)}`);
|
|
1027
|
+
return parts.join(" · ");
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function describePerson(
|
|
1031
|
+
enrollment: Enrollment,
|
|
1032
|
+
detail: CampaignDetail,
|
|
1033
|
+
): { line: string; json: JsonRecord } {
|
|
1034
|
+
const id = String(enrollment._id);
|
|
1035
|
+
const run = detail.currentRuns?.[id];
|
|
1036
|
+
const touch = detail.lastTouches?.[id];
|
|
1037
|
+
const connected = detail.connectedEntries?.[id];
|
|
1038
|
+
const name = enrollment.displayName?.trim() || connected?.label || "Someone";
|
|
1039
|
+
const hold = describeHold(run?.hold);
|
|
1040
|
+
const bits: string[] = [enrollment.status];
|
|
1041
|
+
if (run?.status && enrollment.status === "active") {
|
|
1042
|
+
const runText = RUN_STATUS_TEXT[run.status] ?? run.status;
|
|
1043
|
+
const stepText = run.type ? (STEP_LABELS[run.type] ?? run.type) : "step";
|
|
1044
|
+
bits.push(`${runText}: ${stepText.toLowerCase()}`);
|
|
1045
|
+
if (run.status === "waiting" && run.waitUntil) {
|
|
1046
|
+
bits.push(`until ${fmtWhenRelative(run.waitUntil)}`);
|
|
1047
|
+
} else if (run.status === "retry" && run.retryAt) {
|
|
1048
|
+
bits.push(`retry ${fmtRelative(run.retryAt)}`);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (touch) {
|
|
1052
|
+
bits.push(
|
|
1053
|
+
`last: ${TOUCH_LABELS[touch.type] ?? touch.type} ${fmtRelative(touch.at)}`,
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
if (hold) bits.push(`hold: ${hold}`);
|
|
1057
|
+
const lastError = run?.lastError ?? enrollment.lastError;
|
|
1058
|
+
if (lastError && !hold) bits.push(`note: ${lastError}`);
|
|
1059
|
+
if (connected?.lead?.status) bits.push(`lead: ${connected.lead.status}`);
|
|
1060
|
+
return {
|
|
1061
|
+
line: ` ${name} — ${bits.join(" · ")} [${id}]`,
|
|
1062
|
+
json: {
|
|
1063
|
+
enrollmentId: id,
|
|
1064
|
+
name,
|
|
1065
|
+
status: enrollment.status,
|
|
1066
|
+
currentStepIndex: enrollment.currentStepIndex,
|
|
1067
|
+
run: run
|
|
1068
|
+
? {
|
|
1069
|
+
status: run.status,
|
|
1070
|
+
type: run.type,
|
|
1071
|
+
waitUntil: run.waitUntil,
|
|
1072
|
+
retryAt: run.retryAt,
|
|
1073
|
+
lastError: run.lastError,
|
|
1074
|
+
}
|
|
1075
|
+
: null,
|
|
1076
|
+
hold: run?.hold ?? null,
|
|
1077
|
+
holdText: hold,
|
|
1078
|
+
lastTouch: touch ?? null,
|
|
1079
|
+
lastError: lastError ?? null,
|
|
1080
|
+
lead: connected?.lead ?? null,
|
|
1081
|
+
record: connected
|
|
1082
|
+
? {
|
|
1083
|
+
entryId: connected.entryId,
|
|
1084
|
+
objectName: connected.objectName,
|
|
1085
|
+
label: connected.label,
|
|
1086
|
+
}
|
|
1087
|
+
: null,
|
|
1088
|
+
linkedinProfileUrl: enrollment.linkedinProfileUrl,
|
|
1089
|
+
},
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// ─── Campaign resolution ──────────────────────────────────────────────────
|
|
1094
|
+
|
|
1095
|
+
async function listCampaigns(
|
|
1096
|
+
ctx: CampaignCliContext,
|
|
1097
|
+
includeArchived: boolean,
|
|
1098
|
+
): Promise<CampaignRow[]> {
|
|
1099
|
+
const rows = await callQuery(ctx, `${OUTREACH}:listSequences`, {
|
|
1100
|
+
includeArchived,
|
|
1101
|
+
});
|
|
1102
|
+
return Array.isArray(rows) ? (rows as CampaignRow[]) : [];
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* `<campaign>` → the campaign row. Exact id first, then an exact
|
|
1107
|
+
* case-insensitive name (live campaigns win over archived ones of the same
|
|
1108
|
+
* name), then a direct read for ids older than the 200 most recent rows.
|
|
1109
|
+
*/
|
|
1110
|
+
export async function resolveCampaign(
|
|
1111
|
+
ctx: CampaignCliContext,
|
|
1112
|
+
reference: string,
|
|
1113
|
+
): Promise<CampaignRow> {
|
|
1114
|
+
const needle = reference.trim();
|
|
1115
|
+
if (!needle) throw new CampaignCliError("Pass a campaign id or name.");
|
|
1116
|
+
const rows = await listCampaigns(ctx, true);
|
|
1117
|
+
const byId = rows.find((row) => String(row._id) === needle);
|
|
1118
|
+
if (byId) return byId;
|
|
1119
|
+
const lowered = needle.toLowerCase();
|
|
1120
|
+
const byName = rows.filter(
|
|
1121
|
+
(row) => row.name.trim().toLowerCase() === lowered,
|
|
1122
|
+
);
|
|
1123
|
+
const live = byName.filter((row) => row.status !== "archived");
|
|
1124
|
+
const candidates = live.length > 0 ? live : byName;
|
|
1125
|
+
if (candidates.length === 1) return candidates[0];
|
|
1126
|
+
if (candidates.length > 1) {
|
|
1127
|
+
const list = candidates
|
|
1128
|
+
.map(
|
|
1129
|
+
(row) =>
|
|
1130
|
+
` ${row._id} (${row.status}${row.ownerName ? `, ${row.ownerName}` : ""}${row.createdAt ? `, created ${fmtWhen(row.createdAt)}` : ""})`,
|
|
1131
|
+
)
|
|
1132
|
+
.join("\n");
|
|
1133
|
+
throw new CampaignCliError(
|
|
1134
|
+
`${candidates.length} campaigns are named "${needle}". Use the id instead:\n${list}`,
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
const detail = (await callQuery(ctx, `${OUTREACH}:getSequence`, {
|
|
1138
|
+
sequenceId: needle,
|
|
1139
|
+
})) as CampaignDetail | null;
|
|
1140
|
+
if (detail?.sequence) return detail.sequence;
|
|
1141
|
+
throw new CampaignCliError(
|
|
1142
|
+
`No campaign called "${needle}". Run \`dench campaign list --all\` to see every campaign.`,
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
async function loadDetail(
|
|
1147
|
+
ctx: CampaignCliContext,
|
|
1148
|
+
sequenceId: string,
|
|
1149
|
+
): Promise<CampaignDetail> {
|
|
1150
|
+
const detail = (await callQuery(ctx, `${OUTREACH}:getSequence`, {
|
|
1151
|
+
sequenceId,
|
|
1152
|
+
})) as CampaignDetail | null;
|
|
1153
|
+
if (!detail?.sequence) throw new CampaignCliError("Campaign not found");
|
|
1154
|
+
return detail;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// ─── Subcommands ──────────────────────────────────────────────────────────
|
|
1158
|
+
|
|
1159
|
+
async function runList(ctx: CampaignCliContext): Promise<void> {
|
|
1160
|
+
const includeArchived = hasFlag(ctx.args, "--all");
|
|
1161
|
+
unknownFlags(ctx.args, "campaign list");
|
|
1162
|
+
const rows = await listCampaigns(ctx, includeArchived);
|
|
1163
|
+
if (rows.length === 0) {
|
|
1164
|
+
out(
|
|
1165
|
+
ctx,
|
|
1166
|
+
rows,
|
|
1167
|
+
includeArchived
|
|
1168
|
+
? 'No campaigns yet. Create one with: dench campaign create --name "..."'
|
|
1169
|
+
: 'No live campaigns. Add --all to include archived ones, or create one with: dench campaign create --name "..."',
|
|
1170
|
+
);
|
|
1171
|
+
return;
|
|
1172
|
+
}
|
|
1173
|
+
const lines = rows.map((row) => {
|
|
1174
|
+
const status = (STATUS_LABELS[row.status] ?? row.status).padEnd(9);
|
|
1175
|
+
const people = `${row.totalEnrolled ?? 0} people`;
|
|
1176
|
+
const replied = `${row.repliedCount ?? 0} replied`;
|
|
1177
|
+
const owner = row.ownerName ? ` · ${row.ownerName}` : "";
|
|
1178
|
+
return `${status} ${row.name} — ${people}, ${replied}${owner} [${row._id}]`;
|
|
1179
|
+
});
|
|
1180
|
+
out(ctx, rows, lines);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
async function runCreate(ctx: CampaignCliContext): Promise<void> {
|
|
1184
|
+
const name = requiredFlag(ctx.args, "--name");
|
|
1185
|
+
const flags = consumeScheduleFlags(ctx.args);
|
|
1186
|
+
unknownFlags(ctx.args, "campaign create");
|
|
1187
|
+
const timezone = flags.timezone ?? localTimezone();
|
|
1188
|
+
// Every flag is parsed before the first write, so a bad --window cannot
|
|
1189
|
+
// leave a half-configured draft behind.
|
|
1190
|
+
const patch = schedulePatchFromFlags(flags, { fallbackTimezone: timezone });
|
|
1191
|
+
// createSequence already installs business hours in that timezone; only
|
|
1192
|
+
// explicit windows are worth a second write.
|
|
1193
|
+
if (flags.windows.length === 0) delete patch.sendSchedules;
|
|
1194
|
+
const created = (await callMutation(ctx, `${OUTREACH}:createSequence`, {
|
|
1195
|
+
name,
|
|
1196
|
+
timezone,
|
|
1197
|
+
})) as { sequenceId: string };
|
|
1198
|
+
if (hasScheduleChanges(patch)) {
|
|
1199
|
+
await callMutation(ctx, `${OUTREACH}:updateDraft`, {
|
|
1200
|
+
sequenceId: created.sequenceId,
|
|
1201
|
+
...patch,
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
const schedules = patch.sendSchedules ?? [businessHoursSchedule(timezone)];
|
|
1205
|
+
const payload = {
|
|
1206
|
+
sequenceId: created.sequenceId,
|
|
1207
|
+
name,
|
|
1208
|
+
status: "draft",
|
|
1209
|
+
timezone,
|
|
1210
|
+
sendSchedules: schedules,
|
|
1211
|
+
...(patch.dailySendCap !== undefined
|
|
1212
|
+
? { dailySendCap: patch.dailySendCap }
|
|
1213
|
+
: {}),
|
|
1214
|
+
...(patch.stopOnReply !== undefined
|
|
1215
|
+
? { stopOnReply: patch.stopOnReply }
|
|
1216
|
+
: {}),
|
|
1217
|
+
...(patch.startsAt !== undefined ? { startsAt: patch.startsAt } : {}),
|
|
1218
|
+
...(patch.endsAt !== undefined ? { endsAt: patch.endsAt } : {}),
|
|
1219
|
+
};
|
|
1220
|
+
out(ctx, payload, [
|
|
1221
|
+
`Created draft campaign "${name}" [${created.sequenceId}]`,
|
|
1222
|
+
`Send window: ${schedules
|
|
1223
|
+
.map(
|
|
1224
|
+
(s) =>
|
|
1225
|
+
`${formatWeekdays(s.weekdays)} ${s.startHour}-${s.endHour} ${s.timezone}`,
|
|
1226
|
+
)
|
|
1227
|
+
.join("; ")}`,
|
|
1228
|
+
'Next: dench campaign steps set <campaign> --file steps.json, then dench campaign add <campaign> --object lead --view "<view>", then dench campaign launch <campaign>',
|
|
1229
|
+
]);
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
async function runGet(ctx: CampaignCliContext): Promise<void> {
|
|
1233
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1234
|
+
unknownFlags(ctx.args, "campaign get");
|
|
1235
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1236
|
+
const sequenceId = String(row._id);
|
|
1237
|
+
const [detail, analytics, live] = await Promise.all([
|
|
1238
|
+
loadDetail(ctx, sequenceId),
|
|
1239
|
+
callQuery(ctx, `${OUTREACH}:getSequenceAnalytics`, {
|
|
1240
|
+
sequenceId,
|
|
1241
|
+
}) as Promise<CampaignAnalytics>,
|
|
1242
|
+
callQuery(ctx, `${OUTREACH}:getSequenceLive`, {
|
|
1243
|
+
sequenceId,
|
|
1244
|
+
}) as Promise<CampaignLive>,
|
|
1245
|
+
]);
|
|
1246
|
+
const sequence = detail.sequence;
|
|
1247
|
+
const lines: string[] = [];
|
|
1248
|
+
lines.push(
|
|
1249
|
+
`${sequence.name} — ${STATUS_LABELS[sequence.status] ?? sequence.status} [${sequence._id}]`,
|
|
1250
|
+
);
|
|
1251
|
+
lines.push(`Schedule: ${describeSchedule(sequence)}`);
|
|
1252
|
+
const steps = [...detail.steps].sort(
|
|
1253
|
+
(a, b) => (a.order ?? 0) - (b.order ?? 0),
|
|
1254
|
+
);
|
|
1255
|
+
lines.push(
|
|
1256
|
+
steps.length === 0
|
|
1257
|
+
? "Steps: none yet — dench campaign steps set <campaign> --file steps.json"
|
|
1258
|
+
: `Steps (${steps.length}): ${steps.map((step) => stepLabel(step)).join(" → ")}`,
|
|
1259
|
+
);
|
|
1260
|
+
if (sequence.lastError) lines.push(`Last error: ${sequence.lastError}`);
|
|
1261
|
+
|
|
1262
|
+
lines.push("", "Funnel");
|
|
1263
|
+
const a = analytics ?? {};
|
|
1264
|
+
const audience = a.audience ?? detail.enrollments.length;
|
|
1265
|
+
lines.push(` Enrolled ${audience}`);
|
|
1266
|
+
lines.push(
|
|
1267
|
+
` In flight ${(a.active ?? 0) + (a.paused ?? 0)} (active ${a.active ?? 0}, paused ${a.paused ?? 0})`,
|
|
1268
|
+
);
|
|
1269
|
+
lines.push(` Contacted ${a.contacted ?? 0}`);
|
|
1270
|
+
if (live?.usesLinkedin || (a.linkedinInvited ?? 0) > 0) {
|
|
1271
|
+
lines.push(
|
|
1272
|
+
` LinkedIn invited ${a.linkedinInvited ?? 0} · accepted ${a.linkedinConnected ?? 0} · messaged ${a.linkedinMessaged ?? 0}`,
|
|
1273
|
+
);
|
|
1274
|
+
}
|
|
1275
|
+
if (live?.usesEmail || (a.emailSent ?? 0) > 0) {
|
|
1276
|
+
lines.push(
|
|
1277
|
+
` Email sent ${a.emailSent ?? 0} · opened ${a.opened ?? 0} · clicked ${a.clicked ?? 0}`,
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
lines.push(
|
|
1281
|
+
` Replied ${a.replied ?? 0} (${pct(a.replyRate)} of enrolled)`,
|
|
1282
|
+
);
|
|
1283
|
+
lines.push(
|
|
1284
|
+
` Done finished ${a.finished ?? 0} · stopped ${a.stopped ?? 0} · failed ${a.failed ?? 0}`,
|
|
1285
|
+
);
|
|
1286
|
+
if (a.truncated) {
|
|
1287
|
+
lines.push(
|
|
1288
|
+
" (counts are approximate — this campaign has more history than one read can hold)",
|
|
1289
|
+
);
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
lines.push("", "Now / Next");
|
|
1293
|
+
if (live?.now) {
|
|
1294
|
+
lines.push(
|
|
1295
|
+
` Now: ${NOW_VERBS[live.now.kind] ?? live.now.kind} ${live.now.personName} (since ${fmtWhen(live.now.startedAt)})`,
|
|
1296
|
+
);
|
|
1297
|
+
} else if (sequence.status === "active") {
|
|
1298
|
+
lines.push(" Now: nothing is being sent right now");
|
|
1299
|
+
}
|
|
1300
|
+
if (live?.next) {
|
|
1301
|
+
const who = live.next.personName ? ` ${live.next.personName}` : "";
|
|
1302
|
+
const hold = describeHold(live.next.hold);
|
|
1303
|
+
lines.push(
|
|
1304
|
+
` Next: ${NEXT_VERBS[live.next.kind] ?? live.next.kind}${who} at ${fmtWhenRelative(live.next.at)}${hold ? ` — on hold: ${hold}` : ""}`,
|
|
1305
|
+
);
|
|
1306
|
+
} else if (sequence.status === "active") {
|
|
1307
|
+
lines.push(
|
|
1308
|
+
" Next: nothing scheduled — everyone is finished, waiting on a reply, or stopped",
|
|
1309
|
+
);
|
|
1310
|
+
} else if (sequence.status === "draft") {
|
|
1311
|
+
lines.push(" Next: launch it — dench campaign launch <campaign>");
|
|
1312
|
+
}
|
|
1313
|
+
if (live?.paused) {
|
|
1314
|
+
const reason =
|
|
1315
|
+
PAUSED_TEXT[live.paused.reason] ?? live.paused.reason.replace(/_/g, " ");
|
|
1316
|
+
const detailText = live.paused.detail ? ` (${live.paused.detail})` : "";
|
|
1317
|
+
const resumes = live.paused.resumesAt
|
|
1318
|
+
? ` · resumes ${fmtWhenRelative(live.paused.resumesAt)}`
|
|
1319
|
+
: "";
|
|
1320
|
+
lines.push(` Held: ${reason}${detailText}${resumes}`);
|
|
1321
|
+
}
|
|
1322
|
+
if (live?.usesEmail) {
|
|
1323
|
+
const cap = live.dailySendCap ?? "∞";
|
|
1324
|
+
const next = live.nextEmailAt
|
|
1325
|
+
? ` · next email ${fmtWhenRelative(live.nextEmailAt)}`
|
|
1326
|
+
: "";
|
|
1327
|
+
lines.push(` Emails today: ${live.emailsToday}/${cap}${next}`);
|
|
1328
|
+
}
|
|
1329
|
+
for (const sender of live?.senders ?? []) {
|
|
1330
|
+
const statusText = sender.statusReason
|
|
1331
|
+
? `${sender.status}: ${sender.statusReason}`
|
|
1332
|
+
: sender.status;
|
|
1333
|
+
const window = `${fmtMinutes(sender.windowStartMinutes)}-${fmtMinutes(sender.windowEndMinutes)} ${sender.timezone}`;
|
|
1334
|
+
const opens = sender.inWindow
|
|
1335
|
+
? "in window"
|
|
1336
|
+
: `opens ${fmtWhenRelative(sender.nextWindowOpenAt)}`;
|
|
1337
|
+
lines.push(
|
|
1338
|
+
` Sender ${sender.displayName}${sender.ownerName ? ` (${sender.ownerName})` : ""}: ${statusText} · invites ${sender.usage.invitesToday}/${sender.dailyInviteLimit} today, ${sender.usage.invitesThisWeek}/${sender.weeklyInviteLimit} this week · messages ${sender.usage.messagesToday}/${sender.dailyMessageLimit} today · ${window} (${opens})`,
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
const enrollments = detail.enrollments;
|
|
1343
|
+
const shown = enrollments.slice(0, PEOPLE_PREVIEW_LIMIT);
|
|
1344
|
+
lines.push("", `People (${shown.length} of ${enrollments.length})`);
|
|
1345
|
+
if (enrollments.length === 0) {
|
|
1346
|
+
lines.push(
|
|
1347
|
+
' nobody yet — dench campaign add <campaign> --object lead --view "<view>"',
|
|
1348
|
+
);
|
|
1349
|
+
}
|
|
1350
|
+
for (const enrollment of shown)
|
|
1351
|
+
lines.push(describePerson(enrollment, detail).line);
|
|
1352
|
+
if (enrollments.length > shown.length) {
|
|
1353
|
+
lines.push(
|
|
1354
|
+
` … ${enrollments.length - shown.length} more: dench campaign people <campaign>`,
|
|
1355
|
+
);
|
|
1356
|
+
}
|
|
1357
|
+
out(ctx, { detail, analytics, live }, lines);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
async function runSet(ctx: CampaignCliContext): Promise<void> {
|
|
1361
|
+
const name = valueFlag(ctx.args, "--name")?.trim();
|
|
1362
|
+
if (name === "") {
|
|
1363
|
+
throw new CampaignCliError("--name needs the new campaign name");
|
|
1364
|
+
}
|
|
1365
|
+
const flags = consumeScheduleFlags(ctx.args);
|
|
1366
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1367
|
+
unknownFlags(ctx.args, "campaign set");
|
|
1368
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1369
|
+
const patch = schedulePatchFromFlags(flags, {
|
|
1370
|
+
fallbackTimezone:
|
|
1371
|
+
row.timezone ?? row.sendSchedules?.[0]?.timezone ?? localTimezone(),
|
|
1372
|
+
existingSchedules: row.sendSchedules,
|
|
1373
|
+
});
|
|
1374
|
+
if (name === undefined && !hasScheduleChanges(patch)) {
|
|
1375
|
+
throw new CampaignCliError(
|
|
1376
|
+
"Nothing to change. Pass at least one of --name, --timezone, --window, --daily-cap, --stop-on-reply/--no-stop-on-reply, --start/--clear-start, --end/--clear-end.",
|
|
1377
|
+
);
|
|
1378
|
+
}
|
|
1379
|
+
if (row.status === "archived") {
|
|
1380
|
+
throw new CampaignCliError(
|
|
1381
|
+
"This campaign is archived and can't be changed. Duplicate it in the Dench app to start again.",
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
// One updateDraft carries the rename too, so the server accepts or rejects
|
|
1385
|
+
// the whole change set at once.
|
|
1386
|
+
const update = { ...(name !== undefined ? { name } : {}), ...patch };
|
|
1387
|
+
await callMutation(ctx, `${OUTREACH}:updateDraft`, {
|
|
1388
|
+
sequenceId: row._id,
|
|
1389
|
+
...update,
|
|
1390
|
+
});
|
|
1391
|
+
const changed = Object.keys(update);
|
|
1392
|
+
const payload = {
|
|
1393
|
+
ok: true,
|
|
1394
|
+
sequenceId: row._id,
|
|
1395
|
+
changed,
|
|
1396
|
+
patch,
|
|
1397
|
+
...(name !== undefined ? { name } : {}),
|
|
1398
|
+
};
|
|
1399
|
+
out(ctx, payload, [
|
|
1400
|
+
`Updated "${name ?? row.name}" (${changed.join(", ")}).`,
|
|
1401
|
+
...(patch.sendSchedules
|
|
1402
|
+
? [
|
|
1403
|
+
`Send window: ${patch.sendSchedules
|
|
1404
|
+
.map(
|
|
1405
|
+
(s) =>
|
|
1406
|
+
`${formatWeekdays(s.weekdays)} ${s.startHour}-${s.endHour} ${s.timezone}`,
|
|
1407
|
+
)
|
|
1408
|
+
.join("; ")}`,
|
|
1409
|
+
]
|
|
1410
|
+
: []),
|
|
1411
|
+
]);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
async function runSteps(ctx: CampaignCliContext): Promise<void> {
|
|
1415
|
+
const file = valueFlag(ctx.args, "--file");
|
|
1416
|
+
let action = ctx.args[0];
|
|
1417
|
+
if (
|
|
1418
|
+
action === "get" ||
|
|
1419
|
+
action === "set" ||
|
|
1420
|
+
action === "show" ||
|
|
1421
|
+
action === "replace"
|
|
1422
|
+
) {
|
|
1423
|
+
ctx.args.shift();
|
|
1424
|
+
action = action === "show" ? "get" : action === "replace" ? "set" : action;
|
|
1425
|
+
} else {
|
|
1426
|
+
action = file ? "set" : "get";
|
|
1427
|
+
}
|
|
1428
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1429
|
+
unknownFlags(ctx.args, `campaign steps ${action}`);
|
|
1430
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1431
|
+
if (action === "get") {
|
|
1432
|
+
const detail = await loadDetail(ctx, String(row._id));
|
|
1433
|
+
const steps = [...detail.steps]
|
|
1434
|
+
.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
|
1435
|
+
.map((step) => stepToInput(step));
|
|
1436
|
+
// Always JSON: the point of `steps get` is a file you can edit and feed
|
|
1437
|
+
// back to `steps set --file`.
|
|
1438
|
+
console.log(JSON.stringify(steps, null, 2));
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
if (!file) {
|
|
1442
|
+
throw new CampaignCliError(
|
|
1443
|
+
"Missing required --file steps.json (a JSON array of steps).",
|
|
1444
|
+
);
|
|
1445
|
+
}
|
|
1446
|
+
if (row.status !== "draft") {
|
|
1447
|
+
throw new CampaignCliError(
|
|
1448
|
+
"Steps can only change while a campaign is a draft. Duplicate it to edit steps.",
|
|
1449
|
+
);
|
|
1450
|
+
}
|
|
1451
|
+
const raw = await readFile(file, "utf8").catch(() => {
|
|
1452
|
+
throw new CampaignCliError(`Cannot read ${file}`);
|
|
1453
|
+
});
|
|
1454
|
+
const steps = parseStepsJson(raw, file);
|
|
1455
|
+
const result = (await callMutation(ctx, `${OUTREACH}:replaceSteps`, {
|
|
1456
|
+
sequenceId: row._id,
|
|
1457
|
+
steps,
|
|
1458
|
+
})) as { ok: true; stepCount: number };
|
|
1459
|
+
out(ctx, { ...result, sequenceId: row._id, steps }, [
|
|
1460
|
+
`Saved ${result.stepCount} steps on "${row.name}": ${steps
|
|
1461
|
+
.map((step) => stepLabel(step as { type: string; waitHours?: unknown }))
|
|
1462
|
+
.join(" → ")}`,
|
|
1463
|
+
]);
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
function emptyTotals(): EnrollFromCrmResult {
|
|
1467
|
+
return {
|
|
1468
|
+
added: 0,
|
|
1469
|
+
requested: 0,
|
|
1470
|
+
cappedAtLimit: null,
|
|
1471
|
+
duplicates: 0,
|
|
1472
|
+
merged: 0,
|
|
1473
|
+
duplicatesElsewhere: 0,
|
|
1474
|
+
suppressed: 0,
|
|
1475
|
+
invalid: 0,
|
|
1476
|
+
skippedNoIdentity: 0,
|
|
1477
|
+
skippedSample: 0,
|
|
1478
|
+
skippedMissingInfo: 0,
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
function addTotals(
|
|
1483
|
+
into: EnrollFromCrmResult,
|
|
1484
|
+
result: EnrollFromCrmResult,
|
|
1485
|
+
): void {
|
|
1486
|
+
into.added += result.added ?? 0;
|
|
1487
|
+
into.requested += result.requested ?? 0;
|
|
1488
|
+
into.duplicates += result.duplicates ?? 0;
|
|
1489
|
+
into.merged += result.merged ?? 0;
|
|
1490
|
+
into.duplicatesElsewhere += result.duplicatesElsewhere ?? 0;
|
|
1491
|
+
into.suppressed += result.suppressed ?? 0;
|
|
1492
|
+
into.invalid += result.invalid ?? 0;
|
|
1493
|
+
into.skippedNoIdentity += result.skippedNoIdentity ?? 0;
|
|
1494
|
+
into.skippedSample += result.skippedSample ?? 0;
|
|
1495
|
+
into.skippedMissingInfo += result.skippedMissingInfo ?? 0;
|
|
1496
|
+
if (result.cappedAtLimit != null) into.cappedAtLimit = result.cappedAtLimit;
|
|
1497
|
+
if (!into.missingInfoSample && result.missingInfoSample) {
|
|
1498
|
+
into.missingInfoSample = result.missingInfoSample;
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
/** Split ids into server-sized chunks, in order. */
|
|
1503
|
+
export function chunkIds<T>(
|
|
1504
|
+
items: readonly T[],
|
|
1505
|
+
size: number = CRM_ENROLL_CHUNK_SIZE,
|
|
1506
|
+
): T[][] {
|
|
1507
|
+
const chunks: T[][] = [];
|
|
1508
|
+
for (let start = 0; start < items.length; start += size) {
|
|
1509
|
+
chunks.push(items.slice(start, start + size));
|
|
1510
|
+
}
|
|
1511
|
+
return chunks;
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
type CrmEnrollOptions = {
|
|
1515
|
+
objectName: string;
|
|
1516
|
+
emailFieldName?: string;
|
|
1517
|
+
linkedinUrlFieldName?: string;
|
|
1518
|
+
nameFieldName?: string;
|
|
1519
|
+
relationFieldName?: string;
|
|
1520
|
+
relationDirection?: "reverse";
|
|
1521
|
+
checkDuplicatesAcrossWorkspace: boolean;
|
|
1522
|
+
};
|
|
1523
|
+
|
|
1524
|
+
async function enrollEntryIds(
|
|
1525
|
+
ctx: CampaignCliContext,
|
|
1526
|
+
sequenceId: string,
|
|
1527
|
+
entryIds: readonly string[],
|
|
1528
|
+
options: CrmEnrollOptions,
|
|
1529
|
+
): Promise<EnrollFromCrmResult & { chunks: number; notConsidered: number }> {
|
|
1530
|
+
const totals = emptyTotals();
|
|
1531
|
+
let chunks = 0;
|
|
1532
|
+
let considered = 0;
|
|
1533
|
+
for (const chunk of chunkIds(entryIds)) {
|
|
1534
|
+
const result = (await callMutation(ctx, `${OUTREACH}:enrollFromCrm`, {
|
|
1535
|
+
sequenceId,
|
|
1536
|
+
...options,
|
|
1537
|
+
entryIds: chunk,
|
|
1538
|
+
})) as EnrollFromCrmResult;
|
|
1539
|
+
chunks += 1;
|
|
1540
|
+
considered += chunk.length;
|
|
1541
|
+
addTotals(totals, result);
|
|
1542
|
+
if (result.cappedAtLimit != null) break;
|
|
1543
|
+
}
|
|
1544
|
+
return { ...totals, chunks, notConsidered: entryIds.length - considered };
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
type ViewSlice = {
|
|
1548
|
+
entries?: Array<{ id?: unknown; entry_id?: unknown }>;
|
|
1549
|
+
totalCount?: number;
|
|
1550
|
+
truncated?: boolean;
|
|
1551
|
+
pageByteTruncated?: boolean;
|
|
1552
|
+
};
|
|
1553
|
+
|
|
1554
|
+
/** Every entry id a saved view shows, paged at VIEW_PAGE_SIZE until totalCount. */
|
|
1555
|
+
export async function collectViewEntryIds(
|
|
1556
|
+
ctx: CampaignCliContext,
|
|
1557
|
+
objectName: string,
|
|
1558
|
+
viewName: string,
|
|
1559
|
+
): Promise<{ ids: string[]; totalCount: number; truncated: boolean }> {
|
|
1560
|
+
const ids: string[] = [];
|
|
1561
|
+
const seen = new Set<string>();
|
|
1562
|
+
let totalCount = 0;
|
|
1563
|
+
let truncated = false;
|
|
1564
|
+
for (let page = 1; page <= MAX_VIEW_PAGES; page += 1) {
|
|
1565
|
+
const slice = (await callQuery(ctx, MATERIALIZE_VIEW, {
|
|
1566
|
+
objectName,
|
|
1567
|
+
viewName,
|
|
1568
|
+
page,
|
|
1569
|
+
pageSize: VIEW_PAGE_SIZE,
|
|
1570
|
+
includeReverseRelations: false,
|
|
1571
|
+
omitHiddenFields: true,
|
|
1572
|
+
})) as ViewSlice | null;
|
|
1573
|
+
if (!slice) {
|
|
1574
|
+
throw new CampaignCliError(
|
|
1575
|
+
`CRM object "${objectName}" not found. Run dench crm objects list.`,
|
|
1576
|
+
);
|
|
1577
|
+
}
|
|
1578
|
+
const entries = Array.isArray(slice.entries) ? slice.entries : [];
|
|
1579
|
+
totalCount =
|
|
1580
|
+
typeof slice.totalCount === "number"
|
|
1581
|
+
? slice.totalCount
|
|
1582
|
+
: ids.length + entries.length;
|
|
1583
|
+
truncated =
|
|
1584
|
+
truncated || slice.truncated === true || slice.pageByteTruncated === true;
|
|
1585
|
+
for (const row of entries) {
|
|
1586
|
+
const id = typeof row.id === "string" ? row.id : row.entry_id;
|
|
1587
|
+
if (typeof id === "string" && id && !seen.has(id)) {
|
|
1588
|
+
seen.add(id);
|
|
1589
|
+
ids.push(id);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
if (entries.length === 0 || ids.length >= totalCount) break;
|
|
1593
|
+
}
|
|
1594
|
+
return { ids, totalCount, truncated };
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
function describeEnrollTotals(
|
|
1598
|
+
campaignName: string,
|
|
1599
|
+
totals: EnrollFromCrmResult & { notConsidered?: number },
|
|
1600
|
+
extra: { truncated?: boolean; viewCount?: number } = {},
|
|
1601
|
+
): string[] {
|
|
1602
|
+
const lines = [
|
|
1603
|
+
`Added ${totals.added} ${totals.added === 1 ? "person" : "people"} to "${campaignName}" (${totals.requested} requested).`,
|
|
1604
|
+
];
|
|
1605
|
+
const alreadyIn = totals.duplicates;
|
|
1606
|
+
if (alreadyIn > 0) {
|
|
1607
|
+
lines.push(
|
|
1608
|
+
` Already in this campaign: ${alreadyIn}${totals.merged > 0 ? ` (${totals.merged} gained a missing email or LinkedIn URL)` : ""}`,
|
|
1609
|
+
);
|
|
1610
|
+
}
|
|
1611
|
+
if (totals.duplicatesElsewhere > 0) {
|
|
1612
|
+
lines.push(
|
|
1613
|
+
` Active in another campaign, skipped: ${totals.duplicatesElsewhere} (pass --allow-duplicates to add anyway)`,
|
|
1614
|
+
);
|
|
1615
|
+
}
|
|
1616
|
+
if (totals.suppressed > 0)
|
|
1617
|
+
lines.push(
|
|
1618
|
+
` Unsubscribed or bounced before, skipped: ${totals.suppressed}`,
|
|
1619
|
+
);
|
|
1620
|
+
const missingContact = totals.skippedNoIdentity + totals.invalid;
|
|
1621
|
+
if (missingContact > 0) {
|
|
1622
|
+
lines.push(
|
|
1623
|
+
` Missing a usable email or LinkedIn URL, skipped: ${missingContact} (check --email-field / --linkedin-field)`,
|
|
1624
|
+
);
|
|
1625
|
+
}
|
|
1626
|
+
if (totals.skippedMissingInfo > 0) {
|
|
1627
|
+
const sample = totals.missingInfoSample
|
|
1628
|
+
? ` — e.g. ${totals.missingInfoSample.displayName ?? "one person"} lacks ${totals.missingInfoSample.missingKeys.join(", ")}`
|
|
1629
|
+
: "";
|
|
1630
|
+
lines.push(
|
|
1631
|
+
` Missing merge fields the steps use, skipped: ${totals.skippedMissingInfo}${sample}`,
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
if (totals.cappedAtLimit != null) {
|
|
1635
|
+
lines.push(
|
|
1636
|
+
` Campaign is full: stopped at ${totals.cappedAtLimit} people${totals.notConsidered ? ` (${totals.notConsidered} not considered)` : ""}.`,
|
|
1637
|
+
);
|
|
1638
|
+
}
|
|
1639
|
+
if (extra.truncated) {
|
|
1640
|
+
lines.push(
|
|
1641
|
+
` Warning: the view holds more rows than the CRM lists in one read (${extra.viewCount ?? "1000+"} rows); rows past that were not considered. Narrow the view and run add again.`,
|
|
1642
|
+
);
|
|
1643
|
+
}
|
|
1644
|
+
return lines;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
async function runAdd(ctx: CampaignCliContext): Promise<void> {
|
|
1648
|
+
const objectName = valueFlag(ctx.args, "--object");
|
|
1649
|
+
const viewName = valueFlag(ctx.args, "--view");
|
|
1650
|
+
const entriesRaw = valueFlag(ctx.args, "--entries");
|
|
1651
|
+
const displayName = valueFlag(ctx.args, "--name");
|
|
1652
|
+
const email = valueFlag(ctx.args, "--email");
|
|
1653
|
+
const linkedinProfileUrl = valueFlag(ctx.args, "--linkedin-url");
|
|
1654
|
+
const emailFieldName = valueFlag(ctx.args, "--email-field");
|
|
1655
|
+
const linkedinUrlFieldName = valueFlag(ctx.args, "--linkedin-field");
|
|
1656
|
+
const nameFieldName = valueFlag(ctx.args, "--name-field");
|
|
1657
|
+
const relationFieldName = valueFlag(ctx.args, "--relation-field");
|
|
1658
|
+
const reverse = hasFlag(ctx.args, "--reverse");
|
|
1659
|
+
const allowDuplicates = hasFlag(ctx.args, "--allow-duplicates");
|
|
1660
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1661
|
+
unknownFlags(ctx.args, "campaign add");
|
|
1662
|
+
|
|
1663
|
+
const usage =
|
|
1664
|
+
'Usage: dench campaign add <campaign> --object <name> --view "<view>" | --object <name> --entries id1,id2 | --name "Ada" [--email ada@x.com] [--linkedin-url https://linkedin.com/in/ada]';
|
|
1665
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1666
|
+
if (row.status === "archived") {
|
|
1667
|
+
throw new CampaignCliError(
|
|
1668
|
+
"People can't be added to an archived campaign.",
|
|
1669
|
+
);
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
if (objectName) {
|
|
1673
|
+
if (viewName && entriesRaw) {
|
|
1674
|
+
throw new CampaignCliError(
|
|
1675
|
+
`Pass either --view or --entries, not both. ${usage}`,
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
if (!viewName && !entriesRaw) {
|
|
1679
|
+
throw new CampaignCliError(
|
|
1680
|
+
`--object needs --view "<view name>" or --entries id1,id2. ${usage}`,
|
|
1681
|
+
);
|
|
1682
|
+
}
|
|
1683
|
+
const options: CrmEnrollOptions = {
|
|
1684
|
+
objectName,
|
|
1685
|
+
emailFieldName,
|
|
1686
|
+
linkedinUrlFieldName,
|
|
1687
|
+
nameFieldName,
|
|
1688
|
+
relationFieldName,
|
|
1689
|
+
relationDirection: reverse ? "reverse" : undefined,
|
|
1690
|
+
checkDuplicatesAcrossWorkspace: !allowDuplicates,
|
|
1691
|
+
};
|
|
1692
|
+
let entryIds: string[];
|
|
1693
|
+
let view: { totalCount: number; truncated: boolean } | undefined;
|
|
1694
|
+
if (viewName) {
|
|
1695
|
+
const collected = await collectViewEntryIds(ctx, objectName, viewName);
|
|
1696
|
+
entryIds = collected.ids;
|
|
1697
|
+
view = {
|
|
1698
|
+
totalCount: collected.totalCount,
|
|
1699
|
+
truncated: collected.truncated,
|
|
1700
|
+
};
|
|
1701
|
+
if (entryIds.length === 0) {
|
|
1702
|
+
out(
|
|
1703
|
+
ctx,
|
|
1704
|
+
{
|
|
1705
|
+
...emptyTotals(),
|
|
1706
|
+
chunks: 0,
|
|
1707
|
+
notConsidered: 0,
|
|
1708
|
+
view: { name: viewName, ...view },
|
|
1709
|
+
},
|
|
1710
|
+
`The view "${viewName}" on ${objectName} has no rows, so nobody was added.`,
|
|
1711
|
+
);
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
if (collected.truncated) {
|
|
1715
|
+
warn(
|
|
1716
|
+
ctx,
|
|
1717
|
+
`the view "${viewName}" has more rows than one read can list; only the first ${entryIds.length} were considered.`,
|
|
1718
|
+
);
|
|
1719
|
+
}
|
|
1720
|
+
} else {
|
|
1721
|
+
entryIds = (entriesRaw ?? "")
|
|
1722
|
+
.split(",")
|
|
1723
|
+
.map((id) => id.trim())
|
|
1724
|
+
.filter(Boolean);
|
|
1725
|
+
if (entryIds.length === 0) {
|
|
1726
|
+
throw new CampaignCliError(
|
|
1727
|
+
"Pass at least one CRM entry id in --entries",
|
|
1728
|
+
);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
const totals = await enrollEntryIds(
|
|
1732
|
+
ctx,
|
|
1733
|
+
String(row._id),
|
|
1734
|
+
entryIds,
|
|
1735
|
+
options,
|
|
1736
|
+
);
|
|
1737
|
+
const payload = {
|
|
1738
|
+
...totals,
|
|
1739
|
+
sequenceId: row._id,
|
|
1740
|
+
objectName,
|
|
1741
|
+
...(viewName ? { view: { name: viewName, ...view } } : {}),
|
|
1742
|
+
};
|
|
1743
|
+
out(
|
|
1744
|
+
ctx,
|
|
1745
|
+
payload,
|
|
1746
|
+
describeEnrollTotals(row.name, totals, {
|
|
1747
|
+
truncated: view?.truncated,
|
|
1748
|
+
viewCount: view?.totalCount,
|
|
1749
|
+
}),
|
|
1750
|
+
);
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
if (viewName || entriesRaw) {
|
|
1755
|
+
throw new CampaignCliError(
|
|
1756
|
+
`--view and --entries need --object <name>. ${usage}`,
|
|
1757
|
+
);
|
|
1758
|
+
}
|
|
1759
|
+
if (!email && !linkedinProfileUrl) {
|
|
1760
|
+
throw new CampaignCliError(
|
|
1761
|
+
`Pass --email and/or --linkedin-url for one person, or --object with --view/--entries for CRM records. ${usage}`,
|
|
1762
|
+
);
|
|
1763
|
+
}
|
|
1764
|
+
const result = (await callMutation(ctx, `${OUTREACH}:addEnrollment`, {
|
|
1765
|
+
sequenceId: row._id,
|
|
1766
|
+
displayName,
|
|
1767
|
+
email,
|
|
1768
|
+
linkedinProfileUrl,
|
|
1769
|
+
checkDuplicatesAcrossWorkspace: !allowDuplicates,
|
|
1770
|
+
})) as { enrollmentId: string };
|
|
1771
|
+
out(ctx, { ...result, sequenceId: row._id }, [
|
|
1772
|
+
`Added ${displayName ?? email ?? linkedinProfileUrl} to "${row.name}" [${result.enrollmentId}]`,
|
|
1773
|
+
]);
|
|
1774
|
+
}
|
|
1775
|
+
|
|
1776
|
+
function describeBlockers(readiness: LaunchReadiness): string[] {
|
|
1777
|
+
const lines: string[] = [];
|
|
1778
|
+
const groups = readiness.blockers ?? [];
|
|
1779
|
+
if (groups.length > 0) {
|
|
1780
|
+
for (const group of groups) {
|
|
1781
|
+
const step =
|
|
1782
|
+
typeof group.stepIndex === "number"
|
|
1783
|
+
? ` (step ${group.stepIndex + 1})`
|
|
1784
|
+
: "";
|
|
1785
|
+
const names = group.people.slice(0, 3).map((person) => person.name);
|
|
1786
|
+
const more =
|
|
1787
|
+
group.people.length > 3 ? `, +${group.people.length - 3} more` : "";
|
|
1788
|
+
const who = names.length > 0 ? ` — ${names.join(", ")}${more}` : "";
|
|
1789
|
+
lines.push(
|
|
1790
|
+
` - ${group.title}${step}${who}${group.hint ? ` ${group.hint}` : ""}`,
|
|
1791
|
+
);
|
|
1792
|
+
}
|
|
1793
|
+
} else {
|
|
1794
|
+
for (const reason of readiness.blockingReasons ?? [])
|
|
1795
|
+
lines.push(` - ${reason}`);
|
|
1796
|
+
}
|
|
1797
|
+
return lines;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
async function runLaunch(ctx: CampaignCliContext): Promise<void> {
|
|
1801
|
+
const ack = hasFlag(ctx.args, "--ack-linkedin-risk");
|
|
1802
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1803
|
+
unknownFlags(ctx.args, "campaign launch");
|
|
1804
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1805
|
+
if (row.status !== "draft") {
|
|
1806
|
+
throw new CampaignCliError(
|
|
1807
|
+
row.status === "paused"
|
|
1808
|
+
? `"${row.name}" is paused, not a draft. Use: dench campaign resume <campaign>`
|
|
1809
|
+
: `Only a draft can be launched. "${row.name}" is ${row.status}.`,
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
const readiness = (await callQuery(ctx, `${OUTREACH}:previewLaunch`, {
|
|
1813
|
+
sequenceId: row._id,
|
|
1814
|
+
})) as LaunchReadiness;
|
|
1815
|
+
if (readiness.ready !== true || typeof readiness.fingerprint !== "string") {
|
|
1816
|
+
const lines = [
|
|
1817
|
+
`"${row.name}" is not ready to launch:`,
|
|
1818
|
+
...describeBlockers(readiness),
|
|
1819
|
+
];
|
|
1820
|
+
if ((readiness.warnings ?? []).length > 0) {
|
|
1821
|
+
lines.push(
|
|
1822
|
+
"Warnings:",
|
|
1823
|
+
...(readiness.warnings ?? []).map((w) => ` - ${w}`),
|
|
1824
|
+
);
|
|
1825
|
+
}
|
|
1826
|
+
out(ctx, { ...readiness, sequenceId: row._id }, lines);
|
|
1827
|
+
throw new CampaignCliError(
|
|
1828
|
+
"Campaign is not ready to launch. Fix the items above, then run launch again.",
|
|
1829
|
+
);
|
|
1830
|
+
}
|
|
1831
|
+
if (readiness.usesLinkedin && !ack) {
|
|
1832
|
+
throw new CampaignCliError(
|
|
1833
|
+
"This campaign sends connection requests or messages through a connected LinkedIn account, which LinkedIn's terms discourage and can get the account restricted. Re-run with --ack-linkedin-risk once the account owner accepts that.",
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
const result = (await callMutation(ctx, `${OUTREACH}:launch`, {
|
|
1837
|
+
sequenceId: row._id,
|
|
1838
|
+
fingerprint: readiness.fingerprint,
|
|
1839
|
+
linkedinRiskAcknowledged: ack,
|
|
1840
|
+
})) as { ok: true; status: string };
|
|
1841
|
+
const payload = {
|
|
1842
|
+
...result,
|
|
1843
|
+
sequenceId: row._id,
|
|
1844
|
+
audienceCount: readiness.audienceCount,
|
|
1845
|
+
stepCount: readiness.stepCount,
|
|
1846
|
+
warnings: readiness.warnings ?? [],
|
|
1847
|
+
};
|
|
1848
|
+
const lines = [
|
|
1849
|
+
`Launched "${row.name}" — ${readiness.audienceCount ?? 0} people, ${readiness.stepCount ?? 0} steps.`,
|
|
1850
|
+
`Watch it: dench campaign get ${row._id}`,
|
|
1851
|
+
];
|
|
1852
|
+
if ((readiness.warnings ?? []).length > 0) {
|
|
1853
|
+
lines.push(
|
|
1854
|
+
"Warnings:",
|
|
1855
|
+
...(readiness.warnings ?? []).map((w) => ` - ${w}`),
|
|
1856
|
+
);
|
|
1857
|
+
}
|
|
1858
|
+
out(ctx, payload, lines);
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
async function runLifecycle(
|
|
1862
|
+
ctx: CampaignCliContext,
|
|
1863
|
+
action: "pause" | "resume" | "archive",
|
|
1864
|
+
): Promise<void> {
|
|
1865
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1866
|
+
unknownFlags(ctx.args, `campaign ${action}`);
|
|
1867
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1868
|
+
const already =
|
|
1869
|
+
action === "pause"
|
|
1870
|
+
? row.status === "paused"
|
|
1871
|
+
: action === "resume"
|
|
1872
|
+
? row.status === "active"
|
|
1873
|
+
: row.status === "archived";
|
|
1874
|
+
if (already) {
|
|
1875
|
+
out(
|
|
1876
|
+
ctx,
|
|
1877
|
+
{ ok: true, sequenceId: row._id, status: row.status, changed: false },
|
|
1878
|
+
[`"${row.name}" is already ${row.status}.`],
|
|
1879
|
+
);
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
if (action === "pause" && row.status !== "active") {
|
|
1883
|
+
throw new CampaignCliError(
|
|
1884
|
+
`Only an active campaign can be paused. "${row.name}" is ${row.status}.`,
|
|
1885
|
+
);
|
|
1886
|
+
}
|
|
1887
|
+
if (action === "resume" && row.status !== "paused") {
|
|
1888
|
+
throw new CampaignCliError(
|
|
1889
|
+
row.status === "draft"
|
|
1890
|
+
? `"${row.name}" is a draft. Launch it with: dench campaign launch <campaign>`
|
|
1891
|
+
: `Only a paused campaign can be resumed. "${row.name}" is ${row.status}.`,
|
|
1892
|
+
);
|
|
1893
|
+
}
|
|
1894
|
+
const fn =
|
|
1895
|
+
action === "pause"
|
|
1896
|
+
? "pauseSequence"
|
|
1897
|
+
: action === "resume"
|
|
1898
|
+
? "resumeSequence"
|
|
1899
|
+
: "archiveSequence";
|
|
1900
|
+
await callMutation(ctx, `${OUTREACH}:${fn}`, { sequenceId: row._id });
|
|
1901
|
+
const status =
|
|
1902
|
+
action === "pause" ? "paused" : action === "resume" ? "active" : "archived";
|
|
1903
|
+
const verb =
|
|
1904
|
+
action === "pause"
|
|
1905
|
+
? "Paused"
|
|
1906
|
+
: action === "resume"
|
|
1907
|
+
? "Resumed"
|
|
1908
|
+
: "Archived";
|
|
1909
|
+
out(ctx, { ok: true, sequenceId: row._id, status, changed: true }, [
|
|
1910
|
+
`${verb} "${row.name}".${action === "archive" ? " Everyone still in flight was stopped." : ""}`,
|
|
1911
|
+
]);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
async function runPeople(ctx: CampaignCliContext): Promise<void> {
|
|
1915
|
+
const status = valueFlag(ctx.args, "--status");
|
|
1916
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1917
|
+
unknownFlags(ctx.args, "campaign people");
|
|
1918
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1919
|
+
const detail = await loadDetail(ctx, String(row._id));
|
|
1920
|
+
const enrollments = status
|
|
1921
|
+
? detail.enrollments.filter((e) => e.status === status.trim().toLowerCase())
|
|
1922
|
+
: detail.enrollments;
|
|
1923
|
+
const people = enrollments.map((enrollment) =>
|
|
1924
|
+
describePerson(enrollment, detail),
|
|
1925
|
+
);
|
|
1926
|
+
const header = `${enrollments.length} ${enrollments.length === 1 ? "person" : "people"}${status ? ` with status ${status}` : ""} in "${row.name}"`;
|
|
1927
|
+
out(
|
|
1928
|
+
ctx,
|
|
1929
|
+
{
|
|
1930
|
+
sequenceId: row._id,
|
|
1931
|
+
count: enrollments.length,
|
|
1932
|
+
people: people.map((p) => p.json),
|
|
1933
|
+
},
|
|
1934
|
+
[header, ...people.map((p) => p.line)],
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
function resolvePerson(detail: CampaignDetail, reference: string): Enrollment {
|
|
1939
|
+
const needle = reference.trim();
|
|
1940
|
+
const byId = detail.enrollments.find((e) => String(e._id) === needle);
|
|
1941
|
+
if (byId) return byId;
|
|
1942
|
+
const lowered = needle.toLowerCase();
|
|
1943
|
+
const byName = detail.enrollments.filter(
|
|
1944
|
+
(e) => (e.displayName ?? "").trim().toLowerCase() === lowered,
|
|
1945
|
+
);
|
|
1946
|
+
if (byName.length === 1) return byName[0];
|
|
1947
|
+
if (byName.length > 1) {
|
|
1948
|
+
throw new CampaignCliError(
|
|
1949
|
+
`${byName.length} people in this campaign are called "${needle}". Use the enrollment id from dench campaign people:\n${byName
|
|
1950
|
+
.map((e) => ` ${e._id} (${e.status})`)
|
|
1951
|
+
.join("\n")}`,
|
|
1952
|
+
);
|
|
1953
|
+
}
|
|
1954
|
+
throw new CampaignCliError(
|
|
1955
|
+
`"${needle}" is not in this campaign. Run dench campaign people <campaign> for ids and names.`,
|
|
1956
|
+
);
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
async function runPerson(
|
|
1960
|
+
ctx: CampaignCliContext,
|
|
1961
|
+
action: "stop" | "resume-person",
|
|
1962
|
+
): Promise<void> {
|
|
1963
|
+
const person = requiredFlag(ctx.args, "--person");
|
|
1964
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
1965
|
+
unknownFlags(ctx.args, `campaign ${action}`);
|
|
1966
|
+
const row = await resolveCampaign(ctx, reference);
|
|
1967
|
+
const detail = await loadDetail(ctx, String(row._id));
|
|
1968
|
+
const enrollment = resolvePerson(detail, person);
|
|
1969
|
+
const name = enrollment.displayName?.trim() || enrollment._id;
|
|
1970
|
+
if (action === "stop") {
|
|
1971
|
+
if (
|
|
1972
|
+
[
|
|
1973
|
+
"finished",
|
|
1974
|
+
"stopped",
|
|
1975
|
+
"replied",
|
|
1976
|
+
"bounced",
|
|
1977
|
+
"complained",
|
|
1978
|
+
"unsubscribed",
|
|
1979
|
+
"failed",
|
|
1980
|
+
].includes(enrollment.status)
|
|
1981
|
+
) {
|
|
1982
|
+
out(
|
|
1983
|
+
ctx,
|
|
1984
|
+
{
|
|
1985
|
+
ok: true,
|
|
1986
|
+
enrollmentId: enrollment._id,
|
|
1987
|
+
status: enrollment.status,
|
|
1988
|
+
changed: false,
|
|
1989
|
+
},
|
|
1990
|
+
[`${name} is already ${enrollment.status}; nothing more will be sent.`],
|
|
1991
|
+
);
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
await callMutation(ctx, `${OUTREACH}:stopEnrollment`, {
|
|
1995
|
+
enrollmentId: enrollment._id,
|
|
1996
|
+
});
|
|
1997
|
+
out(
|
|
1998
|
+
ctx,
|
|
1999
|
+
{
|
|
2000
|
+
ok: true,
|
|
2001
|
+
enrollmentId: enrollment._id,
|
|
2002
|
+
status: "stopped",
|
|
2003
|
+
changed: true,
|
|
2004
|
+
},
|
|
2005
|
+
[
|
|
2006
|
+
`Stopped ${name} in "${row.name}". They will get nothing more from this campaign.`,
|
|
2007
|
+
],
|
|
2008
|
+
);
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
2011
|
+
if (enrollment.status !== "paused") {
|
|
2012
|
+
throw new CampaignCliError(
|
|
2013
|
+
`${name} is ${enrollment.status}, not paused. Only a paused person can be resumed.`,
|
|
2014
|
+
);
|
|
2015
|
+
}
|
|
2016
|
+
if (row.status !== "active") {
|
|
2017
|
+
throw new CampaignCliError(
|
|
2018
|
+
`Resume the campaign first: dench campaign resume ${row._id}`,
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
await callMutation(ctx, `${OUTREACH}:resumeEnrollment`, {
|
|
2022
|
+
enrollmentId: enrollment._id,
|
|
2023
|
+
});
|
|
2024
|
+
out(
|
|
2025
|
+
ctx,
|
|
2026
|
+
{ ok: true, enrollmentId: enrollment._id, status: "active", changed: true },
|
|
2027
|
+
[`Resumed ${name} in "${row.name}".`],
|
|
2028
|
+
);
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
const EVENT_LABELS: Record<string, string> = {
|
|
2032
|
+
enrolled: "added to the campaign",
|
|
2033
|
+
launched: "campaign launched",
|
|
2034
|
+
paused: "campaign paused",
|
|
2035
|
+
resumed: "campaign resumed",
|
|
2036
|
+
completed: "campaign completed",
|
|
2037
|
+
revived: "campaign picked back up",
|
|
2038
|
+
archived: "campaign archived",
|
|
2039
|
+
profile_visited: "profile visited",
|
|
2040
|
+
invite_sent: "connection request sent",
|
|
2041
|
+
message_sent: "LinkedIn message sent",
|
|
2042
|
+
email_sent: "email sent",
|
|
2043
|
+
connection_accepted: "accepted the connection",
|
|
2044
|
+
reply_received: "replied",
|
|
2045
|
+
step_skipped: "step skipped",
|
|
2046
|
+
step_failed: "step failed",
|
|
2047
|
+
person_paused: "paused",
|
|
2048
|
+
person_resumed: "resumed",
|
|
2049
|
+
person_stopped: "stopped",
|
|
2050
|
+
person_finished: "finished every step",
|
|
2051
|
+
bounced: "email bounced",
|
|
2052
|
+
unsubscribed: "unsubscribed",
|
|
2053
|
+
manual_review: "needs a look",
|
|
2054
|
+
};
|
|
2055
|
+
|
|
2056
|
+
type EventRow = {
|
|
2057
|
+
occurredAt: number;
|
|
2058
|
+
kind: string;
|
|
2059
|
+
channel?: string;
|
|
2060
|
+
personName?: string;
|
|
2061
|
+
detail?: string;
|
|
2062
|
+
actorName?: string;
|
|
2063
|
+
stepIndex?: number;
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
async function runEvents(ctx: CampaignCliContext): Promise<void> {
|
|
2067
|
+
const limitRaw = valueFlag(ctx.args, "--limit");
|
|
2068
|
+
const maxPagesRaw = valueFlag(ctx.args, "--max-pages");
|
|
2069
|
+
const reference = shift(ctx.args, "campaign id or name");
|
|
2070
|
+
unknownFlags(ctx.args, "campaign events");
|
|
2071
|
+
const limit =
|
|
2072
|
+
limitRaw === undefined ? DEFAULT_EVENTS_PAGE_SIZE : Number(limitRaw);
|
|
2073
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_EVENTS_PAGE_SIZE) {
|
|
2074
|
+
throw new CampaignCliError(
|
|
2075
|
+
`--limit must be a whole number from 1 to ${MAX_EVENTS_PAGE_SIZE}.`,
|
|
2076
|
+
);
|
|
2077
|
+
}
|
|
2078
|
+
const maxPages = maxPagesRaw === undefined ? 1 : Number(maxPagesRaw);
|
|
2079
|
+
if (!Number.isInteger(maxPages) || maxPages < 1) {
|
|
2080
|
+
throw new CampaignCliError("--max-pages must be a positive whole number.");
|
|
2081
|
+
}
|
|
2082
|
+
const row = await resolveCampaign(ctx, reference);
|
|
2083
|
+
const result = await collectPaginated(
|
|
2084
|
+
async (cursor) =>
|
|
2085
|
+
(await callQuery(ctx, `${OUTREACH}:listSequenceEvents`, {
|
|
2086
|
+
sequenceId: row._id,
|
|
2087
|
+
paginationOpts: { numItems: limit, cursor },
|
|
2088
|
+
})) as {
|
|
2089
|
+
page: unknown[];
|
|
2090
|
+
isDone: boolean;
|
|
2091
|
+
continueCursor: string | null;
|
|
2092
|
+
},
|
|
2093
|
+
{ maxPages },
|
|
2094
|
+
);
|
|
2095
|
+
const events = result.rows as EventRow[];
|
|
2096
|
+
const lines = events.map((event) => {
|
|
2097
|
+
const who = event.personName ? `${event.personName}: ` : "";
|
|
2098
|
+
const label = EVENT_LABELS[event.kind] ?? event.kind.replace(/_/g, " ");
|
|
2099
|
+
const step =
|
|
2100
|
+
typeof event.stepIndex === "number"
|
|
2101
|
+
? ` (step ${event.stepIndex + 1})`
|
|
2102
|
+
: "";
|
|
2103
|
+
const detail = event.detail ? ` — ${event.detail}` : "";
|
|
2104
|
+
const actor = event.actorName ? ` (by ${event.actorName})` : "";
|
|
2105
|
+
return `${fmtWhen(event.occurredAt)} ${who}${label}${step}${detail}${actor}`;
|
|
2106
|
+
});
|
|
2107
|
+
if (lines.length === 0) lines.push(`No activity yet on "${row.name}".`);
|
|
2108
|
+
if (!result.isDone) {
|
|
2109
|
+
lines.push(
|
|
2110
|
+
`… more: dench campaign events ${row._id} --max-pages ${maxPages + 1}`,
|
|
2111
|
+
);
|
|
2112
|
+
}
|
|
2113
|
+
out(
|
|
2114
|
+
ctx,
|
|
2115
|
+
{
|
|
2116
|
+
sequenceId: row._id,
|
|
2117
|
+
events,
|
|
2118
|
+
isDone: result.isDone,
|
|
2119
|
+
continueCursor: result.continueCursor,
|
|
2120
|
+
pagesFetched: result.pagesFetched,
|
|
2121
|
+
},
|
|
2122
|
+
lines,
|
|
2123
|
+
);
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
type MailboxRow = {
|
|
2127
|
+
_id: string;
|
|
2128
|
+
email?: string;
|
|
2129
|
+
provider?: string;
|
|
2130
|
+
status?: string;
|
|
2131
|
+
statusReason?: string | null;
|
|
2132
|
+
ownerName?: string;
|
|
2133
|
+
isOwner?: boolean;
|
|
2134
|
+
visibility?: string;
|
|
2135
|
+
};
|
|
2136
|
+
|
|
2137
|
+
/**
|
|
2138
|
+
* The sending accounts a step can name. Mailboxes come from
|
|
2139
|
+
* `emailMailboxAccounts:listAccounts`; LinkedIn accounts have no
|
|
2140
|
+
* token-authenticated list yet, so their ids come from the app or from an
|
|
2141
|
+
* existing campaign's steps.
|
|
2142
|
+
*/
|
|
2143
|
+
async function runAccounts(ctx: CampaignCliContext): Promise<void> {
|
|
2144
|
+
unknownFlags(ctx.args, "campaign accounts");
|
|
2145
|
+
const rows = await callQuery(
|
|
2146
|
+
ctx,
|
|
2147
|
+
"functions/emailMailboxAccounts:listAccounts",
|
|
2148
|
+
{},
|
|
2149
|
+
);
|
|
2150
|
+
const mailboxes = (Array.isArray(rows) ? (rows as MailboxRow[]) : []).map(
|
|
2151
|
+
(row) => ({
|
|
2152
|
+
emailMailboxAccountId: row._id,
|
|
2153
|
+
email: row.email ?? null,
|
|
2154
|
+
provider: row.provider ?? null,
|
|
2155
|
+
status: row.status ?? null,
|
|
2156
|
+
statusReason: row.statusReason ?? null,
|
|
2157
|
+
ownerName: row.ownerName ?? null,
|
|
2158
|
+
isOwner: row.isOwner === true,
|
|
2159
|
+
visibility: row.visibility ?? null,
|
|
2160
|
+
}),
|
|
2161
|
+
);
|
|
2162
|
+
const lines = [
|
|
2163
|
+
`Mailboxes (${mailboxes.length}) — use emailMailboxAccountId in email steps:`,
|
|
2164
|
+
...mailboxes.map(
|
|
2165
|
+
(m) =>
|
|
2166
|
+
` ${m.email ?? "(no address)"} — ${m.provider ?? "mailbox"} · ${m.status ?? "unknown"}${m.statusReason ? ` (${m.statusReason})` : ""}${m.ownerName && !m.isOwner ? ` · ${m.ownerName}` : ""}${m.visibility === "private" ? " · private" : ""} [${m.emailMailboxAccountId}]`,
|
|
2167
|
+
),
|
|
2168
|
+
];
|
|
2169
|
+
if (mailboxes.length === 0) {
|
|
2170
|
+
lines.push(
|
|
2171
|
+
" none — connect Gmail or Outlook under Outreach → Accounts in the Dench app",
|
|
2172
|
+
);
|
|
2173
|
+
}
|
|
2174
|
+
lines.push(
|
|
2175
|
+
"",
|
|
2176
|
+
"LinkedIn accounts can't be listed from the CLI yet. Take linkedinAccountId from an existing campaign (dench campaign steps get <campaign>) or ask the user to copy it from Outreach → Accounts.",
|
|
2177
|
+
);
|
|
2178
|
+
out(
|
|
2179
|
+
ctx,
|
|
2180
|
+
{
|
|
2181
|
+
mailboxes,
|
|
2182
|
+
linkedinAccounts: null,
|
|
2183
|
+
note: "LinkedIn accounts can't be listed from the CLI yet; take linkedinAccountId from an existing campaign's steps or from Outreach → Accounts in the app.",
|
|
2184
|
+
},
|
|
2185
|
+
lines,
|
|
2186
|
+
);
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
// ─── Help ─────────────────────────────────────────────────────────────────
|
|
2190
|
+
|
|
2191
|
+
export function campaignHelp(): void {
|
|
2192
|
+
console.log(`Usage: dench campaign <subcommand> [--json]
|
|
2193
|
+
|
|
2194
|
+
Outreach campaigns send email and LinkedIn steps to a list of people on one
|
|
2195
|
+
schedule. <campaign> is an id or an exact (case-insensitive) name.
|
|
2196
|
+
|
|
2197
|
+
Browse:
|
|
2198
|
+
dench campaign list [--all] # live campaigns; --all includes archived
|
|
2199
|
+
dench campaign get <campaign> # status, schedule, funnel, Now/Next, holds, people
|
|
2200
|
+
dench campaign people <campaign> [--status active|paused|finished|replied|stopped|bounced|failed]
|
|
2201
|
+
dench campaign events <campaign> [--limit 50] [--max-pages 1] # activity log, newest first
|
|
2202
|
+
dench campaign accounts # connected mailboxes and their ids for steps.json
|
|
2203
|
+
|
|
2204
|
+
Create and configure:
|
|
2205
|
+
dench campaign create --name "Founder outreach" [--timezone America/Los_Angeles] \\
|
|
2206
|
+
[--window "Mon-Fri 9-18"] [--window "Sat 10-12"] [--daily-cap 30] \\
|
|
2207
|
+
[--stop-on-reply|--no-stop-on-reply] [--start 2026-09-03T09:00:00-07:00] [--end 2026-10-01]
|
|
2208
|
+
dench campaign set <campaign> [--name "New name"] [--timezone <tz>] [--window "<spec>" ...] \\
|
|
2209
|
+
[--daily-cap 1-100] [--stop-on-reply|--no-stop-on-reply] [--start <ISO>|--clear-start] [--end <ISO>|--clear-end]
|
|
2210
|
+
dench campaign steps get <campaign> # prints steps as JSON you can edit
|
|
2211
|
+
dench campaign steps set <campaign> --file steps.json # replaces every step; drafts only
|
|
2212
|
+
|
|
2213
|
+
Fill it:
|
|
2214
|
+
dench campaign add <campaign> --object lead --view "Q3 targets" [--email-field Email] [--linkedin-field "POC LinkedIn URL"] [--allow-duplicates]
|
|
2215
|
+
dench campaign add <campaign> --object people --entries id1,id2 [--relation-field Contact] [--reverse]
|
|
2216
|
+
dench campaign add <campaign> --name "Ada Lovelace" [--email ada@x.com] [--linkedin-url https://linkedin.com/in/ada]
|
|
2217
|
+
|
|
2218
|
+
Run it:
|
|
2219
|
+
dench campaign launch <campaign> [--ack-linkedin-risk] # checks readiness first; prints blockers
|
|
2220
|
+
dench campaign pause <campaign>
|
|
2221
|
+
dench campaign resume <campaign>
|
|
2222
|
+
dench campaign archive <campaign> # stops everyone still in flight
|
|
2223
|
+
dench campaign stop <campaign> --person <enrollmentId|name>
|
|
2224
|
+
dench campaign resume-person <campaign> --person <enrollmentId|name>
|
|
2225
|
+
|
|
2226
|
+
Send window spec (--window, repeatable, all in --timezone):
|
|
2227
|
+
"Mon-Fri 9-18" "Mon,Wed,Fri 10-16" "Weekdays 9am-5pm" "Sat-Sun 10-14"
|
|
2228
|
+
|
|
2229
|
+
--start / --end take ISO 8601. A bare date (2026-10-01) is midnight at the start
|
|
2230
|
+
of that day in the campaign's timezone; add a time and offset to be exact.
|
|
2231
|
+
|
|
2232
|
+
steps.json: a JSON array of steps, in order. Types: email, wait, linkedin_visit,
|
|
2233
|
+
linkedin_connection, linkedin_message. See references/CAMPAIGNS.md for every field.
|
|
2234
|
+
|
|
2235
|
+
A campaign holds at most ${MAX_CAMPAIGN_PEOPLE} people. Steps lock at launch; the schedule,
|
|
2236
|
+
daily cap and stop-on-reply stay editable. Leads move New → Contacted → Replied
|
|
2237
|
+
on their own as steps go out.
|
|
2238
|
+
|
|
2239
|
+
Auth: a workspace member's credentials (dench signin, a member DENCH_API_KEY, or
|
|
2240
|
+
an agent session). An organization-only key cannot run outreach.
|
|
2241
|
+
`);
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2244
|
+
// ─── Entry point ──────────────────────────────────────────────────────────
|
|
2245
|
+
|
|
2246
|
+
export async function runCampaignCommand(opts: {
|
|
2247
|
+
convex: ConvexHttpClient;
|
|
2248
|
+
args: string[];
|
|
2249
|
+
sessionToken?: string;
|
|
2250
|
+
jsonOutput?: boolean;
|
|
2251
|
+
}): Promise<void> {
|
|
2252
|
+
const args = [...opts.args];
|
|
2253
|
+
const jsonOutput = hasFlag(args, "--json") || opts.jsonOutput === true;
|
|
2254
|
+
const ctx: CampaignCliContext = {
|
|
2255
|
+
convex: opts.convex,
|
|
2256
|
+
args,
|
|
2257
|
+
jsonOutput,
|
|
2258
|
+
sessionToken: opts.sessionToken,
|
|
2259
|
+
};
|
|
2260
|
+
const subcommand = args.shift();
|
|
2261
|
+
if (
|
|
2262
|
+
!subcommand ||
|
|
2263
|
+
subcommand === "help" ||
|
|
2264
|
+
subcommand === "--help" ||
|
|
2265
|
+
subcommand === "-h"
|
|
2266
|
+
) {
|
|
2267
|
+
campaignHelp();
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
switch (subcommand) {
|
|
2271
|
+
case "list":
|
|
2272
|
+
case "ls":
|
|
2273
|
+
return await runList(ctx);
|
|
2274
|
+
case "create":
|
|
2275
|
+
case "new":
|
|
2276
|
+
return await runCreate(ctx);
|
|
2277
|
+
case "get":
|
|
2278
|
+
case "status":
|
|
2279
|
+
case "show":
|
|
2280
|
+
return await runGet(ctx);
|
|
2281
|
+
case "set":
|
|
2282
|
+
case "update":
|
|
2283
|
+
case "configure":
|
|
2284
|
+
return await runSet(ctx);
|
|
2285
|
+
case "steps":
|
|
2286
|
+
return await runSteps(ctx);
|
|
2287
|
+
case "add":
|
|
2288
|
+
case "enroll":
|
|
2289
|
+
return await runAdd(ctx);
|
|
2290
|
+
case "launch":
|
|
2291
|
+
case "start":
|
|
2292
|
+
return await runLaunch(ctx);
|
|
2293
|
+
case "pause":
|
|
2294
|
+
return await runLifecycle(ctx, "pause");
|
|
2295
|
+
case "resume":
|
|
2296
|
+
return await runLifecycle(ctx, "resume");
|
|
2297
|
+
case "archive":
|
|
2298
|
+
return await runLifecycle(ctx, "archive");
|
|
2299
|
+
case "people":
|
|
2300
|
+
return await runPeople(ctx);
|
|
2301
|
+
case "stop":
|
|
2302
|
+
return await runPerson(ctx, "stop");
|
|
2303
|
+
case "resume-person":
|
|
2304
|
+
return await runPerson(ctx, "resume-person");
|
|
2305
|
+
case "events":
|
|
2306
|
+
case "activity":
|
|
2307
|
+
return await runEvents(ctx);
|
|
2308
|
+
case "accounts":
|
|
2309
|
+
case "senders":
|
|
2310
|
+
return await runAccounts(ctx);
|
|
2311
|
+
default:
|
|
2312
|
+
throw new CampaignCliError(
|
|
2313
|
+
`Unknown campaign subcommand: ${subcommand}. Run 'dench campaign help'.`,
|
|
2314
|
+
);
|
|
2315
|
+
}
|
|
2316
|
+
}
|