@metricraven/cli 0.4.5 → 0.5.1
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 +33 -7
- package/dist/api.js +1 -1
- package/dist/args.js +127 -6
- package/dist/commands.js +849 -22
- package/dist/completion.js +14 -8
- package/dist/format.js +14 -0
- package/dist/index.js +86 -12
- package/dist/range.js +15 -3
- package/package.json +1 -1
package/dist/commands.js
CHANGED
|
@@ -3,9 +3,17 @@ import { UsageError, buildFilters, positiveInt, rangeParams } from "./args.js";
|
|
|
3
3
|
import { customRange, validTimeZone } from "./range.js";
|
|
4
4
|
import { AD_PROVIDER_VALUES, completionScript } from "./completion.js";
|
|
5
5
|
import { configPath, deleteConfigToken, readConfig, resolveSettings, updateConfig } from "./config.js";
|
|
6
|
-
import { bold, change, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
|
|
6
|
+
import { bold, change, csvLine, date, dim, duration, money, num, pct, section, table, terminalSafe, truncate } from "./format.js";
|
|
7
7
|
import { interactive, prompt, promptHidden, readStdin } from "./prompt.js";
|
|
8
8
|
export const TOKENS_URL = "https://metricraven.com/app/api";
|
|
9
|
+
/** "2.4 s" (LCP) or "180 ms" (INP); "–" without a value. */
|
|
10
|
+
export function vitalText(metric, ms) {
|
|
11
|
+
if (ms === null || ms === undefined || !Number.isFinite(ms))
|
|
12
|
+
return "–";
|
|
13
|
+
return metric === "lcp" && ms >= 1000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms)} ms`;
|
|
14
|
+
}
|
|
15
|
+
const speedHead = ["LCP p75", "INP p75"];
|
|
16
|
+
const speedCells = (r) => [vitalText("lcp", r.speed?.lcp.p75), vitalText("inp", r.speed?.inp.p75)];
|
|
9
17
|
/** Every line the CLI prints; terminalSafe strips escape sequences that came from report data. */
|
|
10
18
|
const out = (s) => process.stdout.write(`${terminalSafe(s)}\n`);
|
|
11
19
|
const printJson = (data) => out(JSON.stringify(data));
|
|
@@ -56,6 +64,12 @@ export async function run(command, flags) {
|
|
|
56
64
|
case "payments":
|
|
57
65
|
if (sub === "delete")
|
|
58
66
|
return deletePayments(ctx);
|
|
67
|
+
if (!sub || sub === "list")
|
|
68
|
+
return listRaw(ctx, "payments");
|
|
69
|
+
break;
|
|
70
|
+
case "events":
|
|
71
|
+
if (!sub || sub === "list")
|
|
72
|
+
return listRaw(ctx, "events");
|
|
59
73
|
break;
|
|
60
74
|
case "use":
|
|
61
75
|
return useSite(ctx, sub);
|
|
@@ -84,11 +98,15 @@ export async function run(command, flags) {
|
|
|
84
98
|
return listVisitors(ctx);
|
|
85
99
|
if (sub === "get")
|
|
86
100
|
return getVisitor(ctx, rest[0]);
|
|
101
|
+
if (sub === "traits")
|
|
102
|
+
return visitorTraits(ctx);
|
|
87
103
|
break;
|
|
88
104
|
case "funnels":
|
|
89
|
-
if (
|
|
90
|
-
return
|
|
91
|
-
|
|
105
|
+
if (sub === "dropoff")
|
|
106
|
+
return funnelDropoff(ctx, rest[0]);
|
|
107
|
+
return funnels(ctx, sub, rest);
|
|
108
|
+
case "segments":
|
|
109
|
+
return segments(ctx, sub, rest);
|
|
92
110
|
case "goals":
|
|
93
111
|
if (sub === "delete-events")
|
|
94
112
|
return deleteGoalEvents(ctx);
|
|
@@ -220,17 +238,52 @@ async function useSite({ flags, client }, id) {
|
|
|
220
238
|
out(`Default website: ${bold(site.name)} (${id}).`);
|
|
221
239
|
return 0;
|
|
222
240
|
}
|
|
223
|
-
const REPORTS = ["traffic", "revenue", "mrr", "conversions", "insights", "search", "crawlers", "ads", "meta-ads"];
|
|
241
|
+
const REPORTS = ["traffic", "revenue", "mrr", "conversions", "paths", "insights", "speed", "search", "crawlers", "ai-companies", "ads", "meta-ads"];
|
|
224
242
|
async function analytics(ctx, sub, rest) {
|
|
225
243
|
const { flags, client } = ctx;
|
|
226
244
|
if (!sub)
|
|
227
|
-
throw new UsageError(`Use: metricraven analytics <${[...REPORTS, "breakdown", "goal"].join("|")}>`);
|
|
245
|
+
throw new UsageError(`Use: metricraven analytics <${[...REPORTS, "breakdown", "goal", "properties", "errors"].join("|")}>`);
|
|
228
246
|
const params = rangeParams(flags);
|
|
247
|
+
// A saved funnel (--funnel <id>, wins) or unsaved steps (--steps) for the conversions report
|
|
248
|
+
// (and, with --drop-step, the errors report). analytics paths takes --steps as a step count (handled below).
|
|
249
|
+
if (flags.funnel !== undefined || (flags.steps !== undefined && sub !== "paths")) {
|
|
250
|
+
if (sub !== "conversions" && sub !== "errors")
|
|
251
|
+
throw new UsageError("--funnel and --steps go with the conversions report: metricraven analytics conversions --funnel <funnel_id>.");
|
|
252
|
+
if (flags.funnel)
|
|
253
|
+
params.set("funnel", flags.funnel);
|
|
254
|
+
else if (flags.steps)
|
|
255
|
+
params.set("steps", flags.steps);
|
|
256
|
+
}
|
|
229
257
|
if (sub === "breakdown") {
|
|
230
258
|
const dimension = rest[0];
|
|
231
259
|
if (!dimension)
|
|
232
|
-
throw new UsageError("Use: metricraven analytics breakdown <dimension>, e.g. country, referrer, page, utmSource.");
|
|
260
|
+
throw new UsageError("Use: metricraven analytics breakdown <dimension>, e.g. country, referrer, page, utmSource, exitPage.");
|
|
233
261
|
params.set("dimension", dimension);
|
|
262
|
+
if (dimension === "urlParam") {
|
|
263
|
+
if (!flags.param)
|
|
264
|
+
throw new UsageError("Use: metricraven analytics breakdown urlParam --param <name>, e.g. --param plan (one of the site's kept URL parameters).");
|
|
265
|
+
params.set("param", flags.param.trim().toLowerCase());
|
|
266
|
+
}
|
|
267
|
+
else if (flags.param)
|
|
268
|
+
throw new UsageError("--param goes with the urlParam dimension only: metricraven analytics breakdown urlParam --param plan.");
|
|
269
|
+
// Pages only: --attribution viewed credits every page buyers viewed before paying; --group folder rolls pages up.
|
|
270
|
+
if ((flags.attribution || flags.group || flags.folder) && dimension !== "page")
|
|
271
|
+
throw new UsageError("--attribution, --group and --folder go with the page dimension only: metricraven analytics breakdown page --group folder.");
|
|
272
|
+
if (flags.attribution) {
|
|
273
|
+
if (flags.attribution !== "first_touch" && flags.attribution !== "viewed")
|
|
274
|
+
throw new UsageError("Use --attribution first_touch or viewed.");
|
|
275
|
+
params.set("attribution", flags.attribution);
|
|
276
|
+
}
|
|
277
|
+
if (flags.group) {
|
|
278
|
+
if (flags.group !== "page" && flags.group !== "folder")
|
|
279
|
+
throw new UsageError("Use --group page or folder.");
|
|
280
|
+
params.set("group", flags.group);
|
|
281
|
+
}
|
|
282
|
+
if (flags.folder) {
|
|
283
|
+
if (flags.group !== "folder")
|
|
284
|
+
throw new UsageError("--folder needs --group folder: metricraven analytics breakdown page --group folder --folder /blog/.");
|
|
285
|
+
params.set("folder", flags.folder.endsWith("/") ? flags.folder : `${flags.folder}/`);
|
|
286
|
+
}
|
|
234
287
|
if (flags.sort)
|
|
235
288
|
params.set("sort", flags.sort);
|
|
236
289
|
if (flags.order) {
|
|
@@ -240,6 +293,16 @@ async function analytics(ctx, sub, rest) {
|
|
|
240
293
|
}
|
|
241
294
|
if (flags.q)
|
|
242
295
|
params.set("q", flags.q);
|
|
296
|
+
// --include speed,errors: LCP and INP at the 75th percentile per page, and visitors who hit a
|
|
297
|
+
// JavaScript error there and didn't pay (page and entryPage).
|
|
298
|
+
if (flags.include) {
|
|
299
|
+
const include = [...new Set(flags.include.split(",").map((v) => v.trim()))];
|
|
300
|
+
if (!include.length || include.some((v) => v !== "speed" && v !== "errors"))
|
|
301
|
+
throw new UsageError("Use --include speed, errors or speed,errors.");
|
|
302
|
+
if (dimension !== "page" && dimension !== "entryPage")
|
|
303
|
+
throw new UsageError(`--include ${include.join(",")} goes with the page and entryPage dimensions: metricraven analytics breakdown page --include ${include.join(",")}.`);
|
|
304
|
+
params.set("include", include.join(","));
|
|
305
|
+
}
|
|
243
306
|
const limit = positiveInt(flags.limit, "limit", 100);
|
|
244
307
|
if (limit !== undefined)
|
|
245
308
|
params.set("limit", String(Math.max(1, limit)));
|
|
@@ -247,11 +310,54 @@ async function analytics(ctx, sub, rest) {
|
|
|
247
310
|
if (offset !== undefined)
|
|
248
311
|
params.set("offset", String(offset));
|
|
249
312
|
}
|
|
313
|
+
else if (sub === "errors") {
|
|
314
|
+
// JavaScript errors grouped by name and message (GET /stats/errors): one page, one funnel drop-off or one group.
|
|
315
|
+
if (flags.path) {
|
|
316
|
+
if (!flags.path.startsWith("/"))
|
|
317
|
+
throw new UsageError("--path is a page path starting with /, e.g. --path /checkout.");
|
|
318
|
+
params.set("path", flags.path);
|
|
319
|
+
}
|
|
320
|
+
if (flags.group) {
|
|
321
|
+
if (!/^[0-9a-f]{16}$/.test(flags.group))
|
|
322
|
+
throw new UsageError("--group is an error group's 16-character ID, from the list.");
|
|
323
|
+
params.set("group", flags.group);
|
|
324
|
+
}
|
|
325
|
+
if ((flags.funnel || flags.steps) && !flags["drop-step"])
|
|
326
|
+
throw new UsageError("--funnel and --steps need --drop-step <n>: metricraven analytics errors --funnel <id> --drop-step 2.");
|
|
327
|
+
if (flags["drop-step"]) {
|
|
328
|
+
if (flags.path)
|
|
329
|
+
throw new UsageError("Use --path or --drop-step, not both.");
|
|
330
|
+
const step = positiveInt(flags["drop-step"], "drop-step", 7);
|
|
331
|
+
if (!step)
|
|
332
|
+
throw new UsageError("--drop-step is the funnel step visitors didn't reach (1 or more; 0 is the first step).");
|
|
333
|
+
params.set("dropStep", String(step));
|
|
334
|
+
if (flags.funnel)
|
|
335
|
+
params.set("funnel", flags.funnel);
|
|
336
|
+
else if (flags.steps)
|
|
337
|
+
params.set("steps", flags.steps);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
250
340
|
else if (sub === "goal") {
|
|
251
341
|
if (!rest[0])
|
|
252
342
|
throw new UsageError("Use: metricraven analytics goal <name>");
|
|
253
343
|
params.set("name", rest[0]);
|
|
254
344
|
}
|
|
345
|
+
else if (sub === "properties") {
|
|
346
|
+
// Event property names (or one property's values) with people counts: GET /stats/filter-values?dimension=prop.
|
|
347
|
+
params.set("dimension", "prop");
|
|
348
|
+
if (rest[0])
|
|
349
|
+
params.set("key", rest[0]);
|
|
350
|
+
if (flags.goal)
|
|
351
|
+
params.set("goal", flags.goal);
|
|
352
|
+
if (flags.q)
|
|
353
|
+
params.set("q", flags.q);
|
|
354
|
+
const limit = positiveInt(flags.limit, "limit", 100);
|
|
355
|
+
if (limit !== undefined)
|
|
356
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
357
|
+
const offset = positiveInt(flags.offset, "offset", 1_000_000);
|
|
358
|
+
if (offset !== undefined)
|
|
359
|
+
params.set("offset", String(offset));
|
|
360
|
+
}
|
|
255
361
|
else if (sub === "meta-ads" && (rest[0] || flags.account)) {
|
|
256
362
|
if (rest[0] && !["campaign", "adset", "ad"].includes(rest[0]))
|
|
257
363
|
throw new UsageError("Use: metricraven analytics meta-ads [campaign|adset|ad] [--account <id>]");
|
|
@@ -260,6 +366,26 @@ async function analytics(ctx, sub, rest) {
|
|
|
260
366
|
if (flags.account)
|
|
261
367
|
params.set("account", adAccountId(flags.account));
|
|
262
368
|
}
|
|
369
|
+
else if (sub === "paths") {
|
|
370
|
+
// Page sequences of payers and non-payers: GET /stats/paths.
|
|
371
|
+
if (flags.steps) {
|
|
372
|
+
const steps = Number(flags.steps);
|
|
373
|
+
if (!Number.isInteger(steps) || steps < 2 || steps > 7)
|
|
374
|
+
throw new UsageError("Use --steps 2 to 7.");
|
|
375
|
+
params.set("steps", String(steps));
|
|
376
|
+
}
|
|
377
|
+
if (flags.group) {
|
|
378
|
+
if (flags.group !== "page" && flags.group !== "section")
|
|
379
|
+
throw new UsageError("Use --group page or section.");
|
|
380
|
+
params.set("group", flags.group);
|
|
381
|
+
}
|
|
382
|
+
if (flags.start)
|
|
383
|
+
params.set("start", flags.start);
|
|
384
|
+
if (flags.end)
|
|
385
|
+
params.set("end", flags.end);
|
|
386
|
+
if (flags.who && !["all", "paid", "unpaid"].includes(flags.who))
|
|
387
|
+
throw new UsageError("Use --who all, paid or unpaid.");
|
|
388
|
+
}
|
|
263
389
|
else if (sub === "mrr") {
|
|
264
390
|
if (rest[0] && !["day", "week", "month"].includes(rest[0]))
|
|
265
391
|
throw new UsageError("Use: metricraven analytics mrr [day|week|month]");
|
|
@@ -280,11 +406,23 @@ async function analytics(ctx, sub, rest) {
|
|
|
280
406
|
params.set("account", adAccountId(flags.account));
|
|
281
407
|
}
|
|
282
408
|
else if (!REPORTS.includes(sub)) {
|
|
283
|
-
throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal"].join(", ")}.`);
|
|
409
|
+
throw new UsageError(`Unknown report "${sub}". Use ${[...REPORTS, "breakdown", "goal", "properties", "errors"].join(", ")}.`);
|
|
284
410
|
}
|
|
285
411
|
params.set("site", await ctx.site());
|
|
286
412
|
const selected = selectFields(flags, params);
|
|
287
|
-
const path = sub === "breakdown"
|
|
413
|
+
const path = sub === "breakdown"
|
|
414
|
+
? "/stats/breakdown"
|
|
415
|
+
: sub === "goal"
|
|
416
|
+
? "/stats/goal"
|
|
417
|
+
: sub === "properties"
|
|
418
|
+
? "/stats/filter-values"
|
|
419
|
+
: sub === "errors"
|
|
420
|
+
? "/stats/errors"
|
|
421
|
+
: sub === "mrr"
|
|
422
|
+
? "/stats/mrr-history"
|
|
423
|
+
: sub === "speed"
|
|
424
|
+
? "/stats/page-speed"
|
|
425
|
+
: `/stats/${sub}`;
|
|
288
426
|
const fetched = await client.get(path, params);
|
|
289
427
|
const data = flags.compare === "off" ? withoutComparison(fetched) : fetched;
|
|
290
428
|
if (flags.json || selected)
|
|
@@ -293,6 +431,10 @@ async function analytics(ctx, sub, rest) {
|
|
|
293
431
|
out(`Ad account ${params.get("account")} is not one of this website's chosen ad accounts${params.get("provider") && params.get("provider") !== "all" ? ` on ${NETWORKS[params.get("provider")] ?? params.get("provider")}` : ""}. Run the report without --account to list them.`);
|
|
294
432
|
return 0;
|
|
295
433
|
}
|
|
434
|
+
if (sub === "paths") {
|
|
435
|
+
out(pathsText(data, flags.who ?? "all"));
|
|
436
|
+
return 0;
|
|
437
|
+
}
|
|
296
438
|
const render = RENDER[sub];
|
|
297
439
|
out(render ? render(data) : JSON.stringify(data, null, 2));
|
|
298
440
|
return 0;
|
|
@@ -398,6 +540,27 @@ export function withoutComparison(data) {
|
|
|
398
540
|
};
|
|
399
541
|
return out;
|
|
400
542
|
}
|
|
543
|
+
/** analytics paths: the totals line and one list (--who all, paid or unpaid). */
|
|
544
|
+
export function pathsText(d, who = "all") {
|
|
545
|
+
const currency = d.period?.currency ?? "USD";
|
|
546
|
+
const revenue = d.totals.revenue !== null;
|
|
547
|
+
const rows = who === "paid" ? d.paidPaths : who === "unpaid" ? d.unpaidPaths : d.paths;
|
|
548
|
+
const pathText = (r) => truncate(`${r.steps.join(" → ")}${r.more ? " → …" : ""}`, 70);
|
|
549
|
+
return [
|
|
550
|
+
periodLine(d.period),
|
|
551
|
+
revenue
|
|
552
|
+
? `${num(d.totals.visitors)} visitors · ${num(d.totals.payingVisitors)} paid (${pct(d.totals.purchaseRate)}) · ${money(d.totals.revenue, currency)}`
|
|
553
|
+
: `${num(d.totals.visitors)} visitors`,
|
|
554
|
+
section(who === "paid" ? "Paths of people who paid" : who === "unpaid" ? "Paths of people who didn’t pay" : "Paths", rows.length
|
|
555
|
+
? revenue
|
|
556
|
+
? table(["Path", "Visitors", "Paid", "% paid", "Revenue"], rows.map((r) => [pathText(r), num(r.visitors), num(r.payingVisitors), pct(r.purchaseRate), money(r.revenue, currency)]), ["left", "right", "right", "right", "right"])
|
|
557
|
+
: table(["Path", "Visitors"], rows.map((r) => [pathText(r), num(r.visitors)]), ["left", "right"])
|
|
558
|
+
: dim(who === "paid" ? "Nobody paid in this period." : "No pages viewed in this period.")),
|
|
559
|
+
d.sample ? dim(`Visitors who didn’t pay are estimated from a 1 in ${Math.round(1 / d.sample.rate)} sample.`) : "",
|
|
560
|
+
]
|
|
561
|
+
.filter(Boolean)
|
|
562
|
+
.join("\n");
|
|
563
|
+
}
|
|
401
564
|
const RENDER = {
|
|
402
565
|
traffic(d) {
|
|
403
566
|
const c = d.overview.current;
|
|
@@ -425,8 +588,52 @@ const RENDER = {
|
|
|
425
588
|
breakdown(d) {
|
|
426
589
|
if (!d.rows.length)
|
|
427
590
|
return dim("No data.");
|
|
591
|
+
const speed = d.rows.some((r) => r.speed != null);
|
|
592
|
+
const withSpeed = (head) => (speed ? [...head, ...speedHead] : head);
|
|
593
|
+
const speedRow = (r) => (speed ? speedCells(r) : []);
|
|
594
|
+
// Pages: average time and exit rate, and in viewed mode buyers and buyer rate (▸ marks folders).
|
|
595
|
+
if (d.rows.some((r) => typeof r.avgTime === "number")) {
|
|
596
|
+
const viewed = d.attribution === "viewed";
|
|
597
|
+
const name = (r) => truncate(`${r.kind === "folder" ? "▸ " : ""}${r.name}`, 60);
|
|
598
|
+
const header = withSpeed(viewed
|
|
599
|
+
? [d.dimension, "Visitors", "Pageviews", "Avg time", "Exit %", "Buyers", "Buyer %", "Revenue"]
|
|
600
|
+
: [d.dimension, "Visitors", "Pageviews", "Avg time", "Exit %", "Revenue"]);
|
|
601
|
+
// --include errors: visitors who hit a JavaScript error on the page and didn't pay.
|
|
602
|
+
const errors = d.rows.some((r) => r.errors);
|
|
603
|
+
if (errors)
|
|
604
|
+
header.push("Errors (didn't pay)");
|
|
605
|
+
return [
|
|
606
|
+
table(header, d.rows.map((r) => [
|
|
607
|
+
name(r),
|
|
608
|
+
num(r.visitors),
|
|
609
|
+
num(r.pageviews),
|
|
610
|
+
duration(r.avgTime),
|
|
611
|
+
pct(r.exitRate, 2),
|
|
612
|
+
...(viewed ? [num(r.buyers), pct(r.purchaseRate, 2)] : []),
|
|
613
|
+
money(r.revenue),
|
|
614
|
+
...speedRow(r),
|
|
615
|
+
...(errors ? [r.errors ? `${num(r.errors.nonBuyers)} of ${num(r.errors.visitors)}` : "–"] : []),
|
|
616
|
+
]), header.map((_, i) => (i ? "right" : "left"))),
|
|
617
|
+
...(viewed && d.totals
|
|
618
|
+
? [dim(`${num(d.totals.buyers)} buyers paid ${money(d.totals.revenue)} in this period; a buyer counts on every page they viewed.`)]
|
|
619
|
+
: []),
|
|
620
|
+
dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`),
|
|
621
|
+
].join("\n");
|
|
622
|
+
}
|
|
623
|
+
// Paying visitors and purchase rate come with revenue (absent for outbound links and hidden revenue).
|
|
624
|
+
const paying = d.rows.some((r) => typeof r.payingVisitors === "number");
|
|
428
625
|
return [
|
|
429
|
-
|
|
626
|
+
paying
|
|
627
|
+
? table(withSpeed([d.dimension, "Visitors", "Pageviews", "Revenue", "Paying", "Rate"]), d.rows.map((r) => [
|
|
628
|
+
truncate(r.name, 60),
|
|
629
|
+
num(r.visitors),
|
|
630
|
+
num(r.pageviews),
|
|
631
|
+
money(r.revenue),
|
|
632
|
+
num(r.payingVisitors),
|
|
633
|
+
pct(r.purchaseRate, 2),
|
|
634
|
+
...speedRow(r),
|
|
635
|
+
]), withSpeed([d.dimension, "", "", "", "", ""]).map((_, i) => (i ? "right" : "left")))
|
|
636
|
+
: table(withSpeed([d.dimension, "Visitors", "Pageviews", "Revenue"]), d.rows.map((r) => [truncate(r.name, 60), num(r.visitors), num(r.pageviews), money(r.revenue), ...speedRow(r)]), withSpeed([d.dimension, "", "", ""]).map((_, i) => (i ? "right" : "left"))),
|
|
430
637
|
dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`),
|
|
431
638
|
].join("\n");
|
|
432
639
|
},
|
|
@@ -481,23 +688,85 @@ const RENDER = {
|
|
|
481
688
|
.filter(Boolean)
|
|
482
689
|
.join("\n");
|
|
483
690
|
},
|
|
691
|
+
errors(d) {
|
|
692
|
+
const off = d.enabled ? [] : [dim("JavaScript errors are off for this website: turn them on in Settings → Tracking & install.")];
|
|
693
|
+
const label = (g) => `${g.name}${g.message ? `: ${g.message}` : ""}`;
|
|
694
|
+
if (d.group !== undefined) {
|
|
695
|
+
const g = d.group;
|
|
696
|
+
if (!g)
|
|
697
|
+
return [...off, dim("No errors in this group in this period.")].join("\n");
|
|
698
|
+
return [
|
|
699
|
+
...off,
|
|
700
|
+
periodLine(d.period),
|
|
701
|
+
bold(truncate(label(g), 200)),
|
|
702
|
+
`${num(g.occurrences)} times · ${num(g.visitors)} visitors · ${num(g.nonBuyers)} didn't pay · last seen ${date(g.lastSeen)}`,
|
|
703
|
+
...(g.topPaths.length ? [`Pages: ${g.topPaths.map((p) => `${p.path} (${num(p.visitors)})`).join(", ")}`] : []),
|
|
704
|
+
...(g.browsers.length ? [`Browsers: ${g.browsers.map((b) => `${b.name} (${num(b.visitors)})`).join(", ")}`] : []),
|
|
705
|
+
...(g.sample?.stack ? [section("Latest stack", g.sample.stack)] : []),
|
|
706
|
+
...(g.people.length
|
|
707
|
+
? [section("People", table(["Visitor", "Last hit", "Paid"], g.people.map((p) => [p.visitorId, date(p.at), p.paid ? "yes" : "no"]), ["left", "left", "left"]))]
|
|
708
|
+
: []),
|
|
709
|
+
].join("\n");
|
|
710
|
+
}
|
|
711
|
+
const groups = d.groups ?? [];
|
|
712
|
+
if (!groups.length)
|
|
713
|
+
return [...off, dim("No errors recorded in this period.")].join("\n");
|
|
714
|
+
return [
|
|
715
|
+
...off,
|
|
716
|
+
periodLine(d.period),
|
|
717
|
+
table(["Error", "Times", "Visitors", "Didn't pay", "Group"], groups.map((g) => [truncate(label(g), 70), num(g.occurrences), num(g.visitors), num(g.nonBuyers), g.fingerprint]), ["left", "right", "right", "right", "left"]),
|
|
718
|
+
dim("Details: metricraven analytics errors --group <Group>"),
|
|
719
|
+
].join("\n");
|
|
720
|
+
},
|
|
484
721
|
conversions(d) {
|
|
485
722
|
// Hidden goals (Settings → Goals) stay out of the table, like the dashboard; --json has them all.
|
|
486
723
|
const shown = d.goals.filter((g) => !g.hidden);
|
|
487
724
|
const hidden = d.goals.length - shown.length;
|
|
725
|
+
const auto = (d.automaticEvents ?? []).filter((g) => !g.hidden);
|
|
488
726
|
return [
|
|
489
727
|
periodLine(d.period),
|
|
490
728
|
section("Goals", shown.length
|
|
491
729
|
? table(["Goal", "Visitors", "Completions", "Rate"], shown.map((g) => [truncate(goalText(g)), num(g.visitors), num(g.events), pct(g.rate, 2)]), ["left", "right", "right", "right"])
|
|
492
730
|
: dim("No goals in this period.")),
|
|
493
731
|
hidden ? dim(`${num(hidden)} hidden goal${hidden === 1 ? "" : "s"} not shown (see --json or \`metricraven goals list\`).`) : "",
|
|
732
|
+
// Button clicks, form submissions and downloads: event counts here, people with `analytics goal <name>`.
|
|
733
|
+
auto.length
|
|
734
|
+
? section("Automatic events", [
|
|
735
|
+
table(["Event", "Completions"], auto.map((g) => [truncate(goalText(g)), num(g.events)]), ["left", "right"]),
|
|
736
|
+
dim(`Visitors and revenue: metricraven analytics goal ${auto[0].name}`),
|
|
737
|
+
].join("\n"))
|
|
738
|
+
: "",
|
|
494
739
|
d.funnel?.length
|
|
495
|
-
? section("Funnel", table(["Step", "Visitors", "From start"], d.funnel.map((s) => [s.displayName || s.step, num(s.visitors), pct(s.fromStart, 0)]), ["left", "right", "right"]))
|
|
740
|
+
? section("Funnel", table(["Step", "Visitors", "From start", "Median after previous"], d.funnel.map((s) => [s.displayName || s.step, num(s.visitors), pct(s.fromStart, 0), duration(s.medianSecondsFromPrevious)]), ["left", "right", "right", "right"]))
|
|
741
|
+
: "",
|
|
742
|
+
d.funnel?.length && d.timeToPayment?.payingVisitors
|
|
743
|
+
? dim(`${num(d.timeToPayment.payingVisitors)} of ${num(d.timeToPayment.visitors)} who finished paid · median ${duration(d.timeToPayment.medianSeconds)} to pay`)
|
|
496
744
|
: "",
|
|
497
745
|
]
|
|
498
746
|
.filter(Boolean)
|
|
499
747
|
.join("\n");
|
|
500
748
|
},
|
|
749
|
+
speed(d) {
|
|
750
|
+
if (!d.pages.length)
|
|
751
|
+
return dim(d.enabled
|
|
752
|
+
? "No page has enough slow and fast visitors to compare yet (each needs 30 of both)."
|
|
753
|
+
: "Page speed is off. Turn it on in Settings → Tracking & install → Page speed.");
|
|
754
|
+
const header = ["Page", "Slow visitors", "Paid (slow)", "Paid (fast)", "Buyers lost", "LCP p75", "INP p75"];
|
|
755
|
+
return [
|
|
756
|
+
bold("Slow pages that lose buyers"),
|
|
757
|
+
table(header, d.pages.map((p) => [
|
|
758
|
+
truncate(p.path, 50),
|
|
759
|
+
num(p.slowVisitors),
|
|
760
|
+
pct(p.slowConversion, 2),
|
|
761
|
+
pct(p.fastConversion, 2),
|
|
762
|
+
num(p.buyersLost),
|
|
763
|
+
vitalText("lcp", p.lcpP75),
|
|
764
|
+
vitalText("inp", p.inpP75),
|
|
765
|
+
]), header.map((_, i) => (i ? "right" : "left"))),
|
|
766
|
+
dim("Slow: main content after 4 s or a click answered after 500 ms. A lead, not proof: slow loads come with slower devices and networks."),
|
|
767
|
+
...(d.truncated ? [dim("Based on the most recent 200,000 page loads in this period.")] : []),
|
|
768
|
+
].join("\n");
|
|
769
|
+
},
|
|
501
770
|
insights(d) {
|
|
502
771
|
const o = d.overview;
|
|
503
772
|
const cur = d.period.currency ?? "USD";
|
|
@@ -507,6 +776,17 @@ const RENDER = {
|
|
|
507
776
|
d.timing
|
|
508
777
|
? `Time to first purchase: median ${num(d.timing.medianDays, 1)} days, ${num(d.timing.medianVisits)} visits · ${pct(d.timing.firstVisitPercent, 0)} buy on the first visit`
|
|
509
778
|
: "",
|
|
779
|
+
d.channels?.rows.length
|
|
780
|
+
? section("Channels", table(["Channel", "Visitors", "Revenue", "Days", "Visits", "Came back", "Then paid"], d.channels.rows.map((r) => [
|
|
781
|
+
r.name,
|
|
782
|
+
num(r.visitors),
|
|
783
|
+
money(r.revenue, cur),
|
|
784
|
+
num(r.medianDays, 1),
|
|
785
|
+
num(r.medianVisits, 1),
|
|
786
|
+
pct(r.returnRate, 1),
|
|
787
|
+
pct(r.returnBuyRate, 1),
|
|
788
|
+
]), ["left", "right", "right", "right", "right", "right", "right"]))
|
|
789
|
+
: "",
|
|
510
790
|
d.revenueMix?.sources?.length
|
|
511
791
|
? section("Revenue by source", table(["Source", "Revenue"], d.revenueMix.sources.slice(0, 6).map((s) => [s.name, money(s.revenue, cur)]), ["left", "right"]))
|
|
512
792
|
: "",
|
|
@@ -540,6 +820,35 @@ const RENDER = {
|
|
|
540
820
|
: dim("No crawler requests in this period."),
|
|
541
821
|
].join("\n");
|
|
542
822
|
},
|
|
823
|
+
/** Per AI company: pages its AI crawlers read, visits its assistants sent, customers and revenue. */
|
|
824
|
+
"ai-companies"(d) {
|
|
825
|
+
const cur = d.period.currency ?? "USD";
|
|
826
|
+
const showMoney = d.companies.some((c) => c.revenue !== null);
|
|
827
|
+
return [
|
|
828
|
+
periodLine(d.period),
|
|
829
|
+
`${num(d.totals.visits)} visits from AI assistants${d.totals.revenue === null ? "" : ` · ${money(d.totals.revenue, cur)} revenue`} · ${num(d.totals.crawlRequests)} AI crawler requests`,
|
|
830
|
+
d.companies.length
|
|
831
|
+
? section("AI companies", table(["Company", "Pages crawled", "Crawls", "Visits", ...(showMoney ? ["Customers", "Revenue"] : [])], d.companies.map((c) => [
|
|
832
|
+
c.company,
|
|
833
|
+
num(c.pagesCrawled),
|
|
834
|
+
num(c.crawlRequests),
|
|
835
|
+
num(c.visits),
|
|
836
|
+
...(showMoney ? [c.payingCustomers === null ? "–" : num(c.payingCustomers), money(c.revenue, cur)] : []),
|
|
837
|
+
]), ["left", "right", "right", "right", ...(showMoney ? ["right", "right"] : [])]))
|
|
838
|
+
: dim("No AI crawler requests or AI assistant visits in this period."),
|
|
839
|
+
].join("\n");
|
|
840
|
+
},
|
|
841
|
+
properties(d) {
|
|
842
|
+
if (!d.rows.length)
|
|
843
|
+
return dim(d.key ? `No values of ${d.key} in this period.` : "No goal in this period has properties.");
|
|
844
|
+
return [
|
|
845
|
+
table([d.key ? `Value of ${d.key}` : "Property", "People"], d.rows.map((r) => [truncate(r.value), num(r.visitors)]), ["left", "right"]),
|
|
846
|
+
d.nextOffset !== null ? dim(`${num(d.total - d.rows.length)} more: --offset ${d.nextOffset}`) : "",
|
|
847
|
+
d.key ? "" : dim("Values: metricraven analytics properties <name> [--goal <goal>]. Filter: -f prop.<name>[@goal]:is:<value>"),
|
|
848
|
+
]
|
|
849
|
+
.filter(Boolean)
|
|
850
|
+
.join("\n");
|
|
851
|
+
},
|
|
543
852
|
goal(d) {
|
|
544
853
|
const t = d.totals;
|
|
545
854
|
return [
|
|
@@ -549,7 +858,16 @@ const RENDER = {
|
|
|
549
858
|
d.sources.length
|
|
550
859
|
? section("Sources", table(["Source", "Visitors"], d.sources.slice(0, 10).map((s) => [s.name, num(s.visitors)]), ["left", "right"]))
|
|
551
860
|
: "",
|
|
552
|
-
...d.properties.slice(0, 5).map((p) =>
|
|
861
|
+
...d.properties.slice(0, 5).map((p) => {
|
|
862
|
+
// People who paid at or after completing it with the value; no money columns where revenue is hidden.
|
|
863
|
+
const withMoney = p.values.some((v) => typeof v.revenue === "number");
|
|
864
|
+
return section(`Property: ${p.key}`, table(["Value", "Completions", "People", ...(withMoney ? ["Bought", "Purchase %", "Revenue"] : [])], p.values.slice(0, 10).map((v) => [
|
|
865
|
+
truncate(v.value),
|
|
866
|
+
num(v.events),
|
|
867
|
+
num(v.people ?? null),
|
|
868
|
+
...(withMoney ? [num(v.payingPeople ?? null), pct(v.purchaseRate ?? null), money(v.revenue ?? null, d.period.currency)] : []),
|
|
869
|
+
]), ["left", "right", "right", ...(withMoney ? ["right", "right", "right"] : [])]));
|
|
870
|
+
}),
|
|
553
871
|
]
|
|
554
872
|
.filter(Boolean)
|
|
555
873
|
.join("\n");
|
|
@@ -597,14 +915,26 @@ async function listVisitors(ctx) {
|
|
|
597
915
|
if (!d.rows.length)
|
|
598
916
|
return out(dim("No visitors match.")), 0;
|
|
599
917
|
out(periodLine(d.period));
|
|
600
|
-
|
|
918
|
+
// With a "Same visit" condition, each row says when its matching visit started.
|
|
919
|
+
const matched = [...params.keys()].some((k) => /^visit[A-Z]/.test(k));
|
|
920
|
+
out(table(["Visitor", ...(matched ? ["Matched visit"] : []), "Paid", "Pageviews", "Source", "Country", "Last seen"], d.rows.map((r) => [
|
|
921
|
+
r.name ?? r.email ?? r.visitorId,
|
|
922
|
+
...(matched ? [r.matchedVisitAt ? date(r.matchedVisitAt) : "–"] : []),
|
|
923
|
+
r.paid ? "yes" : "",
|
|
924
|
+
num(r.pageviews),
|
|
925
|
+
r.source ?? "–",
|
|
926
|
+
r.country ?? "–",
|
|
927
|
+
date(r.lastPageviewAt),
|
|
928
|
+
]), ["left", ...(matched ? ["left"] : []), "left", "right", "left", "left", "left"]));
|
|
601
929
|
out(dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`));
|
|
602
930
|
return 0;
|
|
603
931
|
}
|
|
604
932
|
async function getVisitor(ctx, id) {
|
|
605
933
|
if (!id)
|
|
606
|
-
throw new UsageError("Use: metricraven visitors get <visitor_id>");
|
|
934
|
+
throw new UsageError("Use: metricraven visitors get <visitor_id> [--visit <ISO time>]");
|
|
607
935
|
const params = new URLSearchParams({ site: await ctx.site() });
|
|
936
|
+
if (ctx.flags.visit)
|
|
937
|
+
params.set("visitAt", ctx.flags.visit);
|
|
608
938
|
const d = await ctx.client.get(`/visitors/${encodeURIComponent(id)}`, params).catch((e) => needs("visitors", Promise.reject(e)));
|
|
609
939
|
if (ctx.flags.json)
|
|
610
940
|
return printJson(d), 0;
|
|
@@ -614,16 +944,185 @@ async function getVisitor(ctx, id) {
|
|
|
614
944
|
if (s.firstTouch)
|
|
615
945
|
out(`First touch: ${s.firstTouch.channel ?? "–"} / ${s.firstTouch.source ?? "–"} → ${s.firstTouch.landingPage ?? "–"}`);
|
|
616
946
|
out(dim(`${date(s.firstSeenAt)} → ${date(s.lastSeenAt)}`));
|
|
617
|
-
|
|
947
|
+
// Session recordings (Growth) are watched in the dashboard; the CLI only says they exist.
|
|
948
|
+
if (d.replays?.length)
|
|
949
|
+
out(`Recordings: ${num(d.replays.length)} (watch in the dashboard)`);
|
|
950
|
+
// --visit: the visit containing that time, and only its rows; otherwise the last 50 rows.
|
|
951
|
+
const v = d.visit;
|
|
952
|
+
if (v)
|
|
953
|
+
out(`Visit ${num(v.number)} · ${date(v.startedAt)} → ${date(v.endedAt)} · ${v.channel ?? "–"}/${v.source ?? "–"} → ${v.landingPage ?? "–"}`);
|
|
954
|
+
const rows = v ? d.timeline.filter((t) => t.visit === v.number) : d.timeline.slice(-50);
|
|
955
|
+
out(section("Timeline", table(["When", "Type", "Detail"], rows.map((t) => [
|
|
956
|
+
date(t.at),
|
|
957
|
+
t.type,
|
|
958
|
+
// JavaScript errors (L-2): "TypeError: message on /pricing".
|
|
959
|
+
truncate(t.type === "error"
|
|
960
|
+
? `${t.name}: ${t.message ?? ""}${t.path ? ` on ${t.path}` : ""}`
|
|
961
|
+
: (t.path ?? t.name ?? (t.amount !== undefined ? money(t.amount) : "")), 60),
|
|
962
|
+
]))));
|
|
618
963
|
return 0;
|
|
619
964
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
965
|
+
/** core/funnels.ts FUNNEL_STEPS_HELP (the CLI ships without core). */
|
|
966
|
+
export const FUNNEL_STEPS_HELP = "1–8 comma-separated steps, counted in order: visit, page:/path (path prefix), page:=/path (exact page), page:host/path (one hostname), event:goal_name, identify, payment. Example: visit,page:/pricing,event:signup,payment";
|
|
967
|
+
/** Saved funnels: list, create, update, delete (changes need write access). */
|
|
968
|
+
async function funnels(ctx, sub, rest) {
|
|
969
|
+
const { flags, client } = ctx;
|
|
970
|
+
const site = await ctx.site();
|
|
971
|
+
const params = () => new URLSearchParams({ site });
|
|
972
|
+
const funnelPath = (id) => {
|
|
973
|
+
if (!id)
|
|
974
|
+
throw new UsageError(`Use: metricraven funnels ${sub} <funnel_id> (IDs from \`metricraven funnels list\`).`);
|
|
975
|
+
return `/funnels/${encodeURIComponent(id)}`;
|
|
976
|
+
};
|
|
977
|
+
switch (sub ?? "list") {
|
|
978
|
+
case "list": {
|
|
979
|
+
const d = await client.get("/funnels", params());
|
|
980
|
+
if (flags.json)
|
|
981
|
+
return printJson(d), 0;
|
|
982
|
+
if (!d.funnels.length)
|
|
983
|
+
return out(dim("No saved funnels.")), 0;
|
|
984
|
+
out(table(["Funnel", "Steps", "ID"], d.funnels.map((f) => [f.name, truncate(f.steps, 70), f.id])));
|
|
985
|
+
return 0;
|
|
986
|
+
}
|
|
987
|
+
case "create": {
|
|
988
|
+
if (!flags.name?.trim() || !flags.steps?.trim())
|
|
989
|
+
throw new UsageError(`Use: metricraven funnels create --name <name> --steps <steps>. Steps: ${FUNNEL_STEPS_HELP}.`);
|
|
990
|
+
const f = await needs("write", client.post("/funnels", { name: flags.name, steps: flags.steps }, params()));
|
|
991
|
+
if (flags.json)
|
|
992
|
+
return printJson(f), 0;
|
|
993
|
+
const count = f.steps.split(",").filter((step) => step.trim()).length;
|
|
994
|
+
out(`Created funnel "${f.name}" (${count} step${count === 1 ? "" : "s"}). ID ${f.id}`);
|
|
995
|
+
out(dim(`Report it: metricraven analytics conversions --funnel ${f.id}`));
|
|
996
|
+
return 0;
|
|
997
|
+
}
|
|
998
|
+
case "update": {
|
|
999
|
+
const path = funnelPath(rest[0]);
|
|
1000
|
+
if (flags.name === undefined && flags.steps === undefined)
|
|
1001
|
+
throw new UsageError("Nothing to change. Use --name or --steps.");
|
|
1002
|
+
const f = await needs("write", client.put(path, { name: flags.name, steps: flags.steps }, params()));
|
|
1003
|
+
if (flags.json)
|
|
1004
|
+
return printJson(f), 0;
|
|
1005
|
+
out(`Updated funnel "${f.name}".`);
|
|
1006
|
+
return 0;
|
|
1007
|
+
}
|
|
1008
|
+
case "delete": {
|
|
1009
|
+
const path = funnelPath(rest[0]);
|
|
1010
|
+
if (!(await confirmOrStop(flags, `Delete funnel ${rest[0]}? Its data is kept.`)))
|
|
1011
|
+
return 0;
|
|
1012
|
+
const d = await needs("write", client.del(path, params()));
|
|
1013
|
+
if (flags.json)
|
|
1014
|
+
return printJson(d), 0;
|
|
1015
|
+
out(`Deleted funnel ${rest[0]}.`);
|
|
1016
|
+
return 0;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
throw new UsageError(`Unknown command "funnels ${sub}". Use list, create, update, delete or dropoff.`);
|
|
1020
|
+
}
|
|
1021
|
+
/** "country is US · urlParam.plan is pro · utmCampaign is empty", as --filter would write it. */
|
|
1022
|
+
export function filtersText(filters) {
|
|
1023
|
+
return filters
|
|
1024
|
+
.map((f) => {
|
|
1025
|
+
const slot = f.key ? `${f.dim}.${f.key}${f.goal ? `@${f.goal}` : ""}` : f.dim;
|
|
1026
|
+
return `${slot} ${f.op.replace(/_/g, " ")}${f.values.length ? ` ${f.values.join(", ")}` : ""}`;
|
|
1027
|
+
})
|
|
1028
|
+
.join(" · ");
|
|
1029
|
+
}
|
|
1030
|
+
/** Saved segments: listing needs visitor details access, changes need write access. */
|
|
1031
|
+
async function segments(ctx, sub, rest) {
|
|
1032
|
+
const { flags, client } = ctx;
|
|
1033
|
+
const site = await ctx.site();
|
|
1034
|
+
const params = () => new URLSearchParams({ site });
|
|
1035
|
+
const list = () => needs("visitors", client.get("/segments", params()));
|
|
1036
|
+
const current = async (id) => {
|
|
1037
|
+
if (!id)
|
|
1038
|
+
throw new UsageError(`Use: metricraven segments ${sub} <segment_id> (IDs from \`metricraven segments list\`).`);
|
|
1039
|
+
const segment = (await list()).segments.find((s) => s.id === id);
|
|
1040
|
+
if (!segment)
|
|
1041
|
+
throw new UsageError(`No segment "${id}". Run \`metricraven segments list\`.`);
|
|
1042
|
+
return segment;
|
|
1043
|
+
};
|
|
1044
|
+
const segmentPath = (id) => `/segments/${encodeURIComponent(id)}`;
|
|
1045
|
+
switch (sub ?? "list") {
|
|
1046
|
+
case "list": {
|
|
1047
|
+
const d = await list();
|
|
1048
|
+
if (flags.json)
|
|
1049
|
+
return printJson(d), 0;
|
|
1050
|
+
if (!d.segments.length)
|
|
1051
|
+
return out(dim("No saved segments.")), 0;
|
|
1052
|
+
out(table(["Segment", "Filters", "ID"], d.segments.map((s) => [s.name, truncate(filtersText(s.filters), 70), s.id])));
|
|
1053
|
+
return 0;
|
|
1054
|
+
}
|
|
1055
|
+
case "create": {
|
|
1056
|
+
if (!flags.name?.trim())
|
|
1057
|
+
throw new UsageError("Use: metricraven segments create --name <name> --filter dim:op:value (repeat --filter, up to six).");
|
|
1058
|
+
const filters = buildFilters(flags.filter);
|
|
1059
|
+
if (!filters.length)
|
|
1060
|
+
throw new UsageError("Add at least one --filter, e.g. --filter country:is:US.");
|
|
1061
|
+
const s = await needs("write", client.post("/segments", { name: flags.name, filters }, params()));
|
|
1062
|
+
if (flags.json)
|
|
1063
|
+
return printJson(s), 0;
|
|
1064
|
+
out(`Saved segment "${s.name}". ID ${s.id}`);
|
|
1065
|
+
return 0;
|
|
1066
|
+
}
|
|
1067
|
+
case "update": {
|
|
1068
|
+
if (flags.name === undefined && !flags.filter?.length)
|
|
1069
|
+
throw new UsageError("Nothing to change. Use --name or --filter (filters replace all).");
|
|
1070
|
+
const filters = flags.filter?.length ? buildFilters(flags.filter) : undefined;
|
|
1071
|
+
const seg = await current(rest[0]);
|
|
1072
|
+
const s = await needs("write", client.put(segmentPath(seg.id), { revision: seg.revision, name: flags.name ?? seg.name, filters: filters ?? seg.filters }, params()));
|
|
1073
|
+
if (flags.json)
|
|
1074
|
+
return printJson(s), 0;
|
|
1075
|
+
out(`Updated segment "${s.name}".`);
|
|
1076
|
+
return 0;
|
|
1077
|
+
}
|
|
1078
|
+
case "delete": {
|
|
1079
|
+
const seg = await current(rest[0]);
|
|
1080
|
+
if (!(await confirmOrStop(flags, `Delete segment "${seg.name}"?`)))
|
|
1081
|
+
return 0;
|
|
1082
|
+
const d = await needs("write", client.del(segmentPath(seg.id), params(), { revision: seg.revision }));
|
|
1083
|
+
if (flags.json)
|
|
1084
|
+
return printJson(d), 0;
|
|
1085
|
+
out(`Deleted segment "${seg.name}".`);
|
|
1086
|
+
return 0;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
throw new UsageError(`Unknown command "segments ${sub}". Use list, create, update or delete.`);
|
|
1090
|
+
}
|
|
1091
|
+
/** Who left a funnel after step N (1-based), or went on with --continued. Without an ID: the default funnel. */
|
|
1092
|
+
async function funnelDropoff(ctx, id) {
|
|
1093
|
+
const { flags } = ctx;
|
|
1094
|
+
const step = flags.step === undefined ? undefined : Number(flags.step);
|
|
1095
|
+
if (step === undefined || !Number.isInteger(step) || step < 1 || step > 7)
|
|
1096
|
+
throw new UsageError("Use: metricraven funnels dropoff <funnel_id> --step <n> (n from 1; the last step has no next step) [--continued]");
|
|
1097
|
+
const params = rangeParams(flags);
|
|
1098
|
+
if (id)
|
|
1099
|
+
params.set("funnel", id);
|
|
1100
|
+
else if (flags.steps)
|
|
1101
|
+
params.set("steps", flags.steps);
|
|
1102
|
+
params.set("step", String(step - 1));
|
|
1103
|
+
params.set("outcome", flags.continued ? "continued" : "dropped");
|
|
1104
|
+
if (flags.q)
|
|
1105
|
+
params.set("q", flags.q);
|
|
1106
|
+
const limit = positiveInt(flags.limit, "limit", 100);
|
|
1107
|
+
if (limit !== undefined)
|
|
1108
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
1109
|
+
const offset = positiveInt(flags.offset, "offset", 1_000_000);
|
|
1110
|
+
if (offset !== undefined)
|
|
1111
|
+
params.set("offset", String(offset));
|
|
1112
|
+
params.set("site", await ctx.site());
|
|
1113
|
+
const selected = selectFields(flags, params);
|
|
1114
|
+
const d = await ctx.client
|
|
1115
|
+
.get("/stats/conversions/people", params)
|
|
1116
|
+
.catch((e) => needs("visitors", Promise.reject(e)));
|
|
1117
|
+
if (flags.json || selected)
|
|
623
1118
|
return printJson(d), 0;
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
1119
|
+
out(bold(d.outcome === "dropped"
|
|
1120
|
+
? `Reached "${d.stepLabel}" but not "${d.nextLabel}"`
|
|
1121
|
+
: `Reached "${d.stepLabel}" and went on to "${d.nextLabel}"`));
|
|
1122
|
+
if (!d.rows.length)
|
|
1123
|
+
return out(dim(d.outcome === "dropped" ? "Nobody left at this step in this period." : "Nobody reached the next step in this period.")), 0;
|
|
1124
|
+
out(table(["Visitor", "Source", "Country", "Reached", "Spent"], d.rows.map((r) => [r.name ?? r.email ?? r.visitorId, r.source ?? r.channel, r.country ?? "–", date(r.reachedAt), r.spent ? money(r.spent, d.currency) : "–"]), ["left", "left", "left", "left", "right"]));
|
|
1125
|
+
out(dim(`${d.offset + 1}–${d.offset + d.rows.length} of ${num(d.total)}${d.nextOffset !== null ? ` · next: --offset ${d.nextOffset}` : ""}`));
|
|
627
1126
|
return 0;
|
|
628
1127
|
}
|
|
629
1128
|
/** Notes take calendar days; the period becomes from/to dates in the chosen zone. */
|
|
@@ -822,7 +1321,126 @@ async function goals(ctx, sub, rest) {
|
|
|
822
1321
|
return 0;
|
|
823
1322
|
}
|
|
824
1323
|
}
|
|
825
|
-
|
|
1324
|
+
if (sub === "definitions" || sub === "preview" || sub === "define" || sub === "undefine")
|
|
1325
|
+
return goalDefinitions(ctx, sub, rest);
|
|
1326
|
+
throw new UsageError(`Unknown command "goals ${sub}". Use list, set, reset, colors, definitions, preview, define or undefine.`);
|
|
1327
|
+
}
|
|
1328
|
+
const definitionPattern = (d) => d.kind === "outbound"
|
|
1329
|
+
? `${d.host ?? ""}${d.path ?? ""}`
|
|
1330
|
+
: d.kind === "click"
|
|
1331
|
+
? `“${d.text ?? ""}”`
|
|
1332
|
+
: d.kind === "form"
|
|
1333
|
+
? (d.form ?? "")
|
|
1334
|
+
: d.kind === "download"
|
|
1335
|
+
? (d.file ?? "")
|
|
1336
|
+
: (d.path ?? "");
|
|
1337
|
+
const KIND_LABEL = { page: "page", outbound: "link", click: "button", form: "form", download: "download" };
|
|
1338
|
+
/**
|
|
1339
|
+
* `--page /pricing`, `--link stripe.com [--link-path /checkout/**]`, `--click "Start free trial"`,
|
|
1340
|
+
* `--form signup` or `--download .pdf` as API fields.
|
|
1341
|
+
*/
|
|
1342
|
+
function definitionInput(flags) {
|
|
1343
|
+
const given = ["page", "link", "click", "form", "download"].filter((k) => flags[k] !== undefined);
|
|
1344
|
+
if (given.length > 1)
|
|
1345
|
+
throw new UsageError(`Use one of --page, --link, --click, --form or --download, not ${given.map((g) => `--${g}`).join(" and ")}.`);
|
|
1346
|
+
if (flags.page)
|
|
1347
|
+
return { kind: "page", path: flags.page };
|
|
1348
|
+
if (flags.link)
|
|
1349
|
+
return { kind: "outbound", host: flags.link, ...(flags["link-path"] ? { path: flags["link-path"] } : {}) };
|
|
1350
|
+
if (flags.click)
|
|
1351
|
+
return { kind: "click", text: flags.click };
|
|
1352
|
+
if (flags.form)
|
|
1353
|
+
return { kind: "form", form: flags.form };
|
|
1354
|
+
if (flags.download)
|
|
1355
|
+
return { kind: "download", file: flags.download };
|
|
1356
|
+
throw new UsageError("Add --page <path> (e.g. /pricing, /blog/*, /docs/**), --link <site> [--link-path <path>], or from automatic events --click <button text>, --form <id or name> or --download <file or .ext>.");
|
|
1357
|
+
}
|
|
1358
|
+
function previewLines(p) {
|
|
1359
|
+
if (!p.visitors)
|
|
1360
|
+
return ["No visitors matched in the last 30 days. The goal will still count future visits."];
|
|
1361
|
+
const lines = [`${num(p.visitors)} visitors would have converted in the last 30 days (${pct(p.rate)} of ${num(p.totalVisitors)}).`];
|
|
1362
|
+
if (p.payingVisitors !== undefined)
|
|
1363
|
+
lines[0] += ` ${num(p.payingVisitors)} of them paid ${money(p.revenue ?? 0, p.currency)}.`;
|
|
1364
|
+
if (p.matches.length)
|
|
1365
|
+
lines.push(dim(`Matches: ${p.matches.map((m) => `${m.value} (${num(m.visitors)})`).join(", ")}`));
|
|
1366
|
+
return lines;
|
|
1367
|
+
}
|
|
1368
|
+
/** `goals definitions | preview | define <name> | undefine <name>`: goals without code (page, link, button, form, download). */
|
|
1369
|
+
async function goalDefinitions(ctx, sub, rest) {
|
|
1370
|
+
const { flags, client } = ctx;
|
|
1371
|
+
const site = await ctx.site();
|
|
1372
|
+
const params = () => new URLSearchParams({ site });
|
|
1373
|
+
const preview = async () => {
|
|
1374
|
+
const input = definitionInput(flags);
|
|
1375
|
+
const p = params();
|
|
1376
|
+
for (const [k, v] of Object.entries(input))
|
|
1377
|
+
p.set(k, v);
|
|
1378
|
+
return client.get("/goals/definitions/preview", p);
|
|
1379
|
+
};
|
|
1380
|
+
switch (sub) {
|
|
1381
|
+
case "definitions": {
|
|
1382
|
+
const d = await client.get("/goals/definitions", params());
|
|
1383
|
+
if (flags.json)
|
|
1384
|
+
return printJson(d), 0;
|
|
1385
|
+
if (!d.definitions.length)
|
|
1386
|
+
return out(dim("No goals without code yet. Use `metricraven goals define <name> --page /pricing`.")), 0;
|
|
1387
|
+
out(table(["Name", "Type", "Pattern"], d.definitions.map((g) => [g.name, KIND_LABEL[g.kind] ?? g.kind, definitionPattern(g)])));
|
|
1388
|
+
return 0;
|
|
1389
|
+
}
|
|
1390
|
+
case "preview": {
|
|
1391
|
+
const d = await preview();
|
|
1392
|
+
if (flags.json)
|
|
1393
|
+
return printJson(d), 0;
|
|
1394
|
+
for (const line of previewLines(d))
|
|
1395
|
+
out(line);
|
|
1396
|
+
return 0;
|
|
1397
|
+
}
|
|
1398
|
+
case "define": {
|
|
1399
|
+
const name = rest[0];
|
|
1400
|
+
if (!name)
|
|
1401
|
+
throw new UsageError("Use: metricraven goals define <name> --page <path> | --link <site> [--link-path <path>] | --click <text> | --form <id> | --download <file>");
|
|
1402
|
+
const input = definitionInput(flags);
|
|
1403
|
+
if (!flags.json) {
|
|
1404
|
+
for (const line of previewLines(await preview()))
|
|
1405
|
+
out(line);
|
|
1406
|
+
if (!(await confirmOrStop(flags, `Create the goal ${name}? It counts past visits at once.`)))
|
|
1407
|
+
return 0;
|
|
1408
|
+
}
|
|
1409
|
+
else if (!flags.yes)
|
|
1410
|
+
throw new UsageError("Add --yes to do this without a prompt.");
|
|
1411
|
+
const d = await needs("write", client.post("/goals/definitions", { name, ...input }, params()));
|
|
1412
|
+
if (flags.json)
|
|
1413
|
+
return printJson(d), 0;
|
|
1414
|
+
out(`Created ${bold(d.definition.name)} (${KIND_LABEL[d.definition.kind] ?? d.definition.kind} ${definitionPattern(d.definition)}). It already counts past visits.`);
|
|
1415
|
+
return 0;
|
|
1416
|
+
}
|
|
1417
|
+
case "undefine": {
|
|
1418
|
+
const name = rest[0];
|
|
1419
|
+
if (!name)
|
|
1420
|
+
throw new UsageError("Use: metricraven goals undefine <name>");
|
|
1421
|
+
const { definitions } = await client.get("/goals/definitions", params());
|
|
1422
|
+
const def = definitions.find((g) => g.name === name);
|
|
1423
|
+
if (!def)
|
|
1424
|
+
throw new UsageError(`No goal without code named "${name}". See \`metricraven goals definitions\`.`);
|
|
1425
|
+
const path = `/goals/definitions/${encodeURIComponent(def.id)}`;
|
|
1426
|
+
const dry = await needs("write", client.del(path, new URLSearchParams([...params(), ["dryRun", "1"]])));
|
|
1427
|
+
const uses = [
|
|
1428
|
+
dry.usedBy.alerts ? `${num(dry.usedBy.alerts)} ${plural("alerts", dry.usedBy.alerts)}` : "",
|
|
1429
|
+
dry.usedBy.funnels ? `${num(dry.usedBy.funnels)} ${plural("funnels", dry.usedBy.funnels)}` : "",
|
|
1430
|
+
dry.usedBy.primaryGoal ? "the primary goal" : "",
|
|
1431
|
+
].filter(Boolean);
|
|
1432
|
+
if (uses.length && !flags.json)
|
|
1433
|
+
out(`Still used by ${uses.join(", ")}; they will count 0 until you change them.`);
|
|
1434
|
+
if (!(await confirmOrStop(flags, `Delete the goal ${name}? Reports stop counting it at once.`)))
|
|
1435
|
+
return 0;
|
|
1436
|
+
const d = await needs("write", client.del(path, params()));
|
|
1437
|
+
if (flags.json)
|
|
1438
|
+
return printJson(d), 0;
|
|
1439
|
+
out(`Deleted ${name}.`);
|
|
1440
|
+
return 0;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return 1;
|
|
826
1444
|
}
|
|
827
1445
|
/**
|
|
828
1446
|
* `--recipients a@x.com,b@x.com` (emails or user IDs), or `all` for every current member. The API
|
|
@@ -1391,6 +2009,160 @@ async function deleteWithCount(ctx, path, params, what) {
|
|
|
1391
2009
|
out(`Deleted ${num(d.deleted)} ${plural(what, d.deleted)}.`);
|
|
1392
2010
|
return 0;
|
|
1393
2011
|
}
|
|
2012
|
+
/** --all stops here (with a note on stderr); continue with --cursor. */
|
|
2013
|
+
export const RAW_ALL_CAP = 100_000;
|
|
2014
|
+
const EVENT_CSV = [
|
|
2015
|
+
["id", (e) => e.id],
|
|
2016
|
+
["created_at", (e) => e.createdAt],
|
|
2017
|
+
["type", (e) => e.type],
|
|
2018
|
+
["name", (e) => e.name],
|
|
2019
|
+
["hostname", (e) => e.hostname],
|
|
2020
|
+
["path", (e) => e.path],
|
|
2021
|
+
["referrer", (e) => e.referrer],
|
|
2022
|
+
["utm_source", (e) => e.utm?.source],
|
|
2023
|
+
["utm_medium", (e) => e.utm?.medium],
|
|
2024
|
+
["utm_campaign", (e) => e.utm?.campaign],
|
|
2025
|
+
["utm_term", (e) => e.utm?.term],
|
|
2026
|
+
["utm_content", (e) => e.utm?.content],
|
|
2027
|
+
["country", (e) => e.country],
|
|
2028
|
+
["region", (e) => e.region],
|
|
2029
|
+
["city", (e) => e.city],
|
|
2030
|
+
["browser", (e) => e.browser],
|
|
2031
|
+
["os", (e) => e.os],
|
|
2032
|
+
["device", (e) => e.device],
|
|
2033
|
+
["visitor_id", (e) => e.visitorId],
|
|
2034
|
+
["user_id", (e) => e.userId],
|
|
2035
|
+
["duration", (e) => e.duration],
|
|
2036
|
+
["props", (e) => (e.props == null ? null : JSON.stringify(e.props))],
|
|
2037
|
+
];
|
|
2038
|
+
const PAYMENT_CSV = [
|
|
2039
|
+
["id", (p) => p.id],
|
|
2040
|
+
["created_at", (p) => p.createdAt],
|
|
2041
|
+
["provider", (p) => p.provider],
|
|
2042
|
+
["amount", (p) => p.amount],
|
|
2043
|
+
["currency", (p) => p.currency],
|
|
2044
|
+
["refunded_amount", (p) => p.refundedAmount],
|
|
2045
|
+
["refunded", (p) => p.refunded],
|
|
2046
|
+
["free_trial", (p) => p.isFreeTrial],
|
|
2047
|
+
["renewal", (p) => p.renewal],
|
|
2048
|
+
["plan", (p) => p.plan],
|
|
2049
|
+
["subscription_id", (p) => p.subscriptionId],
|
|
2050
|
+
["customer_id", (p) => p.customerId],
|
|
2051
|
+
["user_id", (p) => p.userId],
|
|
2052
|
+
["visitor_id", (p) => p.visitorId],
|
|
2053
|
+
["customer_email", (p) => p.customer?.email],
|
|
2054
|
+
["customer_name", (p) => p.customer?.name],
|
|
2055
|
+
["channel", (p) => p.attribution?.channel],
|
|
2056
|
+
["source", (p) => p.attribution?.source],
|
|
2057
|
+
["landing_page", (p) => p.attribution?.landingPage],
|
|
2058
|
+
["first_referrer", (p) => p.attribution?.referrer],
|
|
2059
|
+
["first_utm_source", (p) => p.attribution?.utmSource],
|
|
2060
|
+
["first_utm_medium", (p) => p.attribution?.utmMedium],
|
|
2061
|
+
["first_utm_campaign", (p) => p.attribution?.utmCampaign],
|
|
2062
|
+
["first_country", (p) => p.attribution?.country],
|
|
2063
|
+
["first_seen_at", (p) => p.attribution?.firstSeenAt],
|
|
2064
|
+
];
|
|
2065
|
+
/** Query parameters of `events list` / `payments list` (GET /events, GET /payments). */
|
|
2066
|
+
export function rawListParams(kind, flags, now = new Date()) {
|
|
2067
|
+
if (!flags.from && !flags.to && flags.period === "all")
|
|
2068
|
+
throw new UsageError("Raw lists need a period: use --period with a preset or --from/--to, not all.");
|
|
2069
|
+
const range = rangeParams({ ...flags, compare: undefined }, now);
|
|
2070
|
+
const params = new URLSearchParams();
|
|
2071
|
+
for (const key of ["from", "to", "filters"]) {
|
|
2072
|
+
const value = range.get(key);
|
|
2073
|
+
if (value)
|
|
2074
|
+
params.set(key, value);
|
|
2075
|
+
}
|
|
2076
|
+
if (kind === "events") {
|
|
2077
|
+
if (flags.type)
|
|
2078
|
+
params.set("type", flags.type);
|
|
2079
|
+
if (flags.goal)
|
|
2080
|
+
params.set("name", flags.goal);
|
|
2081
|
+
}
|
|
2082
|
+
else if (flags.transaction)
|
|
2083
|
+
params.set("transaction_id", flags.transaction);
|
|
2084
|
+
if (flags.visitor)
|
|
2085
|
+
params.set("visitor_id", flags.visitor);
|
|
2086
|
+
if (flags.user)
|
|
2087
|
+
params.set("user_id", flags.user);
|
|
2088
|
+
const limit = positiveInt(flags.limit, "limit", 1000);
|
|
2089
|
+
if (limit !== undefined)
|
|
2090
|
+
params.set("limit", String(Math.max(1, limit)));
|
|
2091
|
+
else if (flags.all)
|
|
2092
|
+
params.set("limit", "1000");
|
|
2093
|
+
if (flags.cursor)
|
|
2094
|
+
params.set("cursor", flags.cursor);
|
|
2095
|
+
return params;
|
|
2096
|
+
}
|
|
2097
|
+
/**
|
|
2098
|
+
* events list / payments list: raw rows, newest first. --all follows nextCursor (up to
|
|
2099
|
+
* RAW_ALL_CAP rows); --csv prints CSV (header once), --json the API's JSON (one object; with
|
|
2100
|
+
* --all every row in it).
|
|
2101
|
+
*/
|
|
2102
|
+
async function listRaw(ctx, kind) {
|
|
2103
|
+
const { flags } = ctx;
|
|
2104
|
+
if (flags.csv && flags.json)
|
|
2105
|
+
throw new UsageError("Use --csv or --json, not both.");
|
|
2106
|
+
const params = rawListParams(kind, flags);
|
|
2107
|
+
params.set("site", await ctx.site());
|
|
2108
|
+
const rows = [];
|
|
2109
|
+
let page;
|
|
2110
|
+
let first = null;
|
|
2111
|
+
let capped = false;
|
|
2112
|
+
for (;;) {
|
|
2113
|
+
page = await needs("visitors", ctx.client.get(`/${kind}`, params));
|
|
2114
|
+
first ??= page;
|
|
2115
|
+
const items = (kind === "events" ? page.events : page.payments) ?? [];
|
|
2116
|
+
if (flags.csv) {
|
|
2117
|
+
const columns = (kind === "events" ? EVENT_CSV : PAYMENT_CSV);
|
|
2118
|
+
// CRLF line ends (RFC 4180); escape sequences from report data are still removed.
|
|
2119
|
+
const write = (cells) => process.stdout.write(`${terminalSafe(csvLine(cells))}\r\n`);
|
|
2120
|
+
if (first === page)
|
|
2121
|
+
write(columns.map(([name]) => name));
|
|
2122
|
+
for (const item of items)
|
|
2123
|
+
write(columns.map(([, get]) => get(item)));
|
|
2124
|
+
}
|
|
2125
|
+
rows.push(...items);
|
|
2126
|
+
if (!flags.all || !page.nextCursor)
|
|
2127
|
+
break;
|
|
2128
|
+
if (rows.length >= RAW_ALL_CAP) {
|
|
2129
|
+
capped = true;
|
|
2130
|
+
break;
|
|
2131
|
+
}
|
|
2132
|
+
params.set("cursor", page.nextCursor);
|
|
2133
|
+
}
|
|
2134
|
+
if (capped)
|
|
2135
|
+
process.stderr.write(`Stopped at ${num(rows.length)} rows. Continue with --cursor ${page.nextCursor}\n`);
|
|
2136
|
+
if (flags.csv)
|
|
2137
|
+
return 0;
|
|
2138
|
+
if (flags.json)
|
|
2139
|
+
return printJson({ [kind]: rows, nextCursor: page.nextCursor, from: first.from, to: first.to }), 0;
|
|
2140
|
+
if (!rows.length)
|
|
2141
|
+
return out(dim(kind === "events" ? "No events match." : "No payments match.")), 0;
|
|
2142
|
+
out(periodLine({ from: first.from, to: first.to }));
|
|
2143
|
+
if (kind === "events")
|
|
2144
|
+
out(table(["Time", "Type", "Name/Path", "Source", "Country", "Device", "Visitor"], rows.map((e) => [
|
|
2145
|
+
date(e.createdAt),
|
|
2146
|
+
e.type,
|
|
2147
|
+
truncate(e.name ?? e.path ?? "–", 40),
|
|
2148
|
+
truncate(e.utm?.source ?? e.referrer ?? "–", 28),
|
|
2149
|
+
e.country ?? "–",
|
|
2150
|
+
e.device ?? "–",
|
|
2151
|
+
e.userId ?? e.visitorId?.slice(0, 12) ?? "–",
|
|
2152
|
+
])));
|
|
2153
|
+
else
|
|
2154
|
+
out(table(["Time", "Amount", "Plan", "Channel", "Source", "Customer", "Status"], rows.map((p) => [
|
|
2155
|
+
date(p.createdAt),
|
|
2156
|
+
money(p.amount, p.currency),
|
|
2157
|
+
p.plan ?? "–",
|
|
2158
|
+
p.attribution?.channel ?? "–",
|
|
2159
|
+
truncate(p.attribution?.source ?? "–", 28),
|
|
2160
|
+
truncate(p.customer?.email ?? p.customer?.name ?? p.userId ?? p.customerId ?? "–", 32),
|
|
2161
|
+
p.refunded ? "refunded" : p.isFreeTrial ? "trial" : "",
|
|
2162
|
+
]), ["left", "right", "left", "left", "left", "left", "left"]));
|
|
2163
|
+
out(dim(`${num(rows.length)} ${rows.length === 1 ? "row" : "rows"}${page.nextCursor ? ` · next: --cursor ${page.nextCursor}` : ""}`));
|
|
2164
|
+
return 0;
|
|
2165
|
+
}
|
|
1394
2166
|
async function deletePayments(ctx) {
|
|
1395
2167
|
const { flags } = ctx;
|
|
1396
2168
|
const params = new URLSearchParams();
|
|
@@ -1436,6 +2208,14 @@ function visitorSearchParams(flags, params) {
|
|
|
1436
2208
|
["device", "device"],
|
|
1437
2209
|
["browser", "browser"],
|
|
1438
2210
|
["os", "os"],
|
|
2211
|
+
["visit-source", "visitSource"],
|
|
2212
|
+
["visit-channel", "visitChannel"],
|
|
2213
|
+
["visit-campaign", "visitCampaign"],
|
|
2214
|
+
["visit-referrer", "visitReferrer"],
|
|
2215
|
+
["visit-entry-page", "visitEntryPage"],
|
|
2216
|
+
["visit-page", "visitPage"],
|
|
2217
|
+
["visit-page-contains", "visitPageContains"],
|
|
2218
|
+
["visit-goal", "visitGoal"],
|
|
1439
2219
|
];
|
|
1440
2220
|
for (const [flag, param] of map) {
|
|
1441
2221
|
const value = flags[flag];
|
|
@@ -1448,6 +2228,53 @@ function visitorSearchParams(flags, params) {
|
|
|
1448
2228
|
const lt = positiveInt(flags["visits-lt"], "visits-lt", 100_000);
|
|
1449
2229
|
if (lt !== undefined)
|
|
1450
2230
|
params.set("visits_lt", String(lt));
|
|
2231
|
+
// --trait role=founder[,cto] → trait.role=founder,cto (people whose latest identify trait matches).
|
|
2232
|
+
for (const raw of flags.trait ?? []) {
|
|
2233
|
+
const eq = raw.indexOf("=");
|
|
2234
|
+
const key = eq < 0 ? "" : raw.slice(0, eq).trim();
|
|
2235
|
+
const value = eq < 0 ? "" : raw.slice(eq + 1).trim();
|
|
2236
|
+
if (!TRAIT_KEY.test(key) || !value)
|
|
2237
|
+
throw new UsageError("Use --trait key=value, e.g. --trait role=founder.");
|
|
2238
|
+
params.set(`trait.${key}`, value);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
/** core/traits.ts TRAIT_KEY_PATTERN. */
|
|
2242
|
+
const TRAIT_KEY = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
2243
|
+
/** `visitors traits [--key role]`: revenue, customers and purchase rate per value of one identify trait. */
|
|
2244
|
+
async function visitorTraits(ctx) {
|
|
2245
|
+
const { flags } = ctx;
|
|
2246
|
+
const params = rangeParams(flags);
|
|
2247
|
+
if (flags.key !== undefined) {
|
|
2248
|
+
if (!TRAIT_KEY.test(flags.key))
|
|
2249
|
+
throw new UsageError("Use --key <trait>, a lowercase trait name such as role.");
|
|
2250
|
+
params.set("key", flags.key);
|
|
2251
|
+
}
|
|
2252
|
+
visitorSearchParams(flags, params);
|
|
2253
|
+
params.set("site", await ctx.site());
|
|
2254
|
+
const selected = selectFields(flags, params);
|
|
2255
|
+
const d = await ctx.client
|
|
2256
|
+
.get("/stats/visitor-traits", params)
|
|
2257
|
+
.catch((e) => needs("visitors", Promise.reject(e)));
|
|
2258
|
+
if (flags.json || selected)
|
|
2259
|
+
return printJson(d), 0;
|
|
2260
|
+
if (!d.key)
|
|
2261
|
+
return out(dim("No custom traits yet. Send traits such as role or company_size with identify.")), 0;
|
|
2262
|
+
out(periodLine(d.period));
|
|
2263
|
+
const currency = d.period.currency;
|
|
2264
|
+
const label = (r) => r.label === "not_set" ? "Not set" : r.label === "other" ? "Other values" : r.label === "hidden_email" ? "Hidden (email addresses)" : (r.value ?? "–");
|
|
2265
|
+
const rows = [...d.rows, ...[d.other, d.notSet, d.hiddenEmail].filter((r) => !!r)];
|
|
2266
|
+
if (!d.people)
|
|
2267
|
+
out(dim("No identified people in this period and filters."));
|
|
2268
|
+
else
|
|
2269
|
+
out(table([d.key, "People", "Customers", "Purchase rate", "Revenue", "Revenue/person"], rows.map((r) => [label(r), num(r.people), num(r.customers), `${r.conversionRate}%`, money(r.revenue, currency), money(r.revenuePerPerson, currency)]), ["left", "right", "right", "right", "right", "right"]));
|
|
2270
|
+
const visible = d.keys.filter((k) => !k.hidden).map((k) => k.key);
|
|
2271
|
+
const hidden = d.keys.filter((k) => k.hidden).map((k) => k.key);
|
|
2272
|
+
out(dim(`Traits: ${visible.join(", ") || "–"}${hidden.length ? ` (hidden: ${hidden.join(", ")})` : ""}`));
|
|
2273
|
+
if (d.unidentified.payments)
|
|
2274
|
+
out(dim(`${money(d.unidentified.revenue, currency)} from ${num(d.unidentified.payments)} payments by people never identified`));
|
|
2275
|
+
if (d.truncated)
|
|
2276
|
+
out(dim("Based on the first 200,000 identified people."));
|
|
2277
|
+
return 0;
|
|
1451
2278
|
}
|
|
1452
2279
|
const GRACES = ["none", "24h", "7d"];
|
|
1453
2280
|
async function siteKeys(ctx, sub, rest) {
|