thumbgate 1.40.3 → 1.40.6
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/.agents/skills/comet-session-logger/SKILL.md +8 -5
- package/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +7 -2
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/config/github-about.json +1 -1
- package/config/post-deploy-marketing-pages.json +1 -1
- package/package.json +35 -7
- package/public/about.html +2 -2
- package/public/admin.html +546 -50
- package/public/case-studies.html +1 -0
- package/public/dashboard.html +7 -6
- package/public/diagnostic.html +15 -12
- package/public/index.html +210 -88
- package/public/install.html +9 -8
- package/public/js/connect-panel.js +437 -0
- package/public/learn.html +8 -0
- package/public/numbers.html +2 -2
- package/public/preview.html +42 -0
- package/public/pricing.html +55 -10
- package/public/support.html +1 -1
- package/public/terms.html +1 -1
- package/scripts/auto-promote-gates.js +29 -4
- package/scripts/billing.js +189 -4
- package/scripts/cap-hit-counter.js +47 -0
- package/scripts/checkout-human-gate.js +248 -0
- package/scripts/checkout-session-count.js +119 -0
- package/scripts/claude-feedback-sync.js +4 -2
- package/scripts/feedback-loop.js +41 -5
- package/scripts/first-block-upsell.js +187 -0
- package/scripts/gates-engine.js +37 -108
- package/scripts/human-feedback.js +20 -1
- package/scripts/ops-log.js +91 -0
- package/scripts/ops-report.js +174 -0
- package/scripts/owner-admin.js +508 -27
- package/scripts/owner-telemetry.js +151 -0
- package/scripts/rate-limiter.js +8 -2
- package/scripts/statusline-human-counts.js +71 -8
- package/scripts/statusline.sh +15 -2
- package/scripts/telemetry-analytics.js +4 -0
- package/scripts/tool-contract-validator.js +13 -3
- package/scripts/tool-registry.js +1 -1
- package/scripts/utm-source-summary.js +88 -0
- package/server.json +2 -2
- package/skills/comet-session-logger/SKILL.md +8 -5
- package/src/api/server.js +649 -107
- package/src/mcp/email-triage-server/index.js +92 -14
package/scripts/owner-admin.js
CHANGED
|
@@ -5,12 +5,17 @@ const path = require('node:path');
|
|
|
5
5
|
const crypto = require('node:crypto');
|
|
6
6
|
const readline = require('node:readline');
|
|
7
7
|
const billing = require('./billing');
|
|
8
|
+
const ownerTelemetry = require('./owner-telemetry');
|
|
9
|
+
const opsLog = require('./ops-log');
|
|
10
|
+
const opsReport = require('./ops-report');
|
|
8
11
|
|
|
9
12
|
const JSON_LIMIT = 8 * 1024 * 1024;
|
|
10
13
|
const LOG_LIMIT = 16 * 1024 * 1024;
|
|
11
14
|
const RESPONSE_LIMIT = 1024 * 1024;
|
|
12
15
|
const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
|
|
13
|
-
const SECTIONS = new Set(['overview', 'data', 'analytics', 'observability']);
|
|
16
|
+
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary']);
|
|
17
|
+
const MONEY_CACHE_MS = 60000;
|
|
18
|
+
let moneyCache = null;
|
|
14
19
|
const PRIVATE_HEADERS = Object.freeze({ 'Cache-Control': 'private, no-store', Vary: 'Cookie', 'X-Robots-Tag': 'noindex, nofollow', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff' });
|
|
15
20
|
let activeCollections = 0;
|
|
16
21
|
const text = (value, max = 256) => typeof value === 'string' ? value.slice(0, max) : null;
|
|
@@ -29,7 +34,7 @@ function adminPath(raw) {
|
|
|
29
34
|
|
|
30
35
|
function parseAdminRoute(pathname, params) {
|
|
31
36
|
if (pathname === '/admin' || pathname === '/admin/' || pathname === '/admin.html') {
|
|
32
|
-
|
|
37
|
+
// The page takes no options: any query string (for example ?product=dayglass) is ignored and the ThumbGate board is served.
|
|
33
38
|
return { page: true };
|
|
34
39
|
}
|
|
35
40
|
const match = /^\/v1\/admin\/([^/]+)(?:\/([^/]+))?$/.exec(pathname || '');
|
|
@@ -97,6 +102,18 @@ function readOwnerIdentity({ feedbackDir, token, isOwner, now = Date.now() }) {
|
|
|
97
102
|
return { provider: entry.ssoProvider };
|
|
98
103
|
}
|
|
99
104
|
|
|
105
|
+
// Three states: no usable session, a valid session that is not the owner (any provider, API-key sessions included), or the owner.
|
|
106
|
+
function readSessionState({ feedbackDir, token, isOwner, now = Date.now() }) {
|
|
107
|
+
if (typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)) return { state: 'none' };
|
|
108
|
+
const store = readObject(feedbackDir, 'auth-sessions.json');
|
|
109
|
+
if (store.state !== 'ok') return { state: 'none' };
|
|
110
|
+
const entry = store.value[crypto.createHash('sha256').update(token).digest('hex')];
|
|
111
|
+
if (!object(entry) || !Number.isFinite(entry.expiresAt) || entry.expiresAt <= now) return { state: 'none' };
|
|
112
|
+
const provider = ['apple', 'google'].includes(entry.ssoProvider) ? entry.ssoProvider : 'key';
|
|
113
|
+
if (provider !== 'key' && isOwner(entry.ssoEmail)) return { state: 'owner', provider };
|
|
114
|
+
return { state: 'non_owner', provider };
|
|
115
|
+
}
|
|
116
|
+
|
|
100
117
|
function envelope(source, data, warnings = [], status = warnings.length ? 'partial' : 'ok') {
|
|
101
118
|
return { status, generatedAt: new Date().toISOString(), source, data, warnings };
|
|
102
119
|
}
|
|
@@ -105,7 +122,25 @@ function createRuntimeObservations(now = Date.now()) {
|
|
|
105
122
|
const errors = [];
|
|
106
123
|
const buckets = new Map();
|
|
107
124
|
const trim = (stamp) => { for (const key of buckets.keys()) if (key < Math.floor(stamp / 1000) - 59) buckets.delete(key); };
|
|
125
|
+
const timings = new Map();
|
|
126
|
+
const percentile = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
|
|
108
127
|
return {
|
|
128
|
+
// Response time per route category, kept for the newest 1,000 requests of each. Resets when the server restarts.
|
|
129
|
+
recordTiming(route, ms) {
|
|
130
|
+
if (!Number.isFinite(ms) || ms < 0) return;
|
|
131
|
+
const list = timings.get(route) || [];
|
|
132
|
+
list.push(ms);
|
|
133
|
+
if (list.length > 1000) list.shift();
|
|
134
|
+
timings.set(route, list);
|
|
135
|
+
},
|
|
136
|
+
speed() {
|
|
137
|
+
const out = {};
|
|
138
|
+
for (const [route, list] of timings) {
|
|
139
|
+
const sorted = list.slice().sort((a, b) => a - b);
|
|
140
|
+
out[route] = { samples: sorted.length, p50: Math.round(percentile(sorted, 0.5)), p95: Math.round(percentile(sorted, 0.95)) };
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
},
|
|
109
144
|
recordResponse(status, route, stamp = Date.now()) {
|
|
110
145
|
if (status < 500 || status > 599) return;
|
|
111
146
|
errors.push({ timestamp: new Date(stamp).toISOString(), status, route: ['admin', 'telemetry', 'health', 'api', 'page'].includes(route) ? route : 'other' });
|
|
@@ -229,6 +264,8 @@ async function collectData(route, deps, signal) {
|
|
|
229
264
|
const key = joined || 'sso:' + email;
|
|
230
265
|
if (!accounts.has(key)) accounts.set(key, { customerId: null, email, createdAt: Number.isFinite(session.createdAt) ? new Date(session.createdAt).toISOString() : null, hasActiveKey: false, hasCurrentSession: true, possibleDuplicate: Boolean(matches?.size > 1), freeEmails: new Set() });
|
|
231
266
|
accounts.get(key).hasCurrentSession = true;
|
|
267
|
+
// A paid key can carry no email of its own; the signed-in session's email is the identity that joined it.
|
|
268
|
+
(accounts.get(key).sessionEmails ||= new Set()).add(email);
|
|
232
269
|
if (!session.customerId || session.subjectType === 'sso_free') accounts.get(key).freeEmails.add(email);
|
|
233
270
|
}
|
|
234
271
|
const ordered = [...accounts.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
@@ -243,7 +280,7 @@ async function collectData(route, deps, signal) {
|
|
|
243
280
|
const counts = [];
|
|
244
281
|
for (const partition of partitions) counts.push(await countPartition(root, partition, signal));
|
|
245
282
|
if (counts.some((row) => row.state === 'partial')) warnings.push('account_counts_partial');
|
|
246
|
-
records.push({ accountId: account.customerId ? text(account.customerId, 128) : [...partitions][0], email: text(account.email, 320), createdAt: account.createdAt, hasActiveKey: account.hasActiveKey, hasCurrentSession: account.hasCurrentSession, possibleDuplicate: account.possibleDuplicate === true, classification: billing.classifyRevenueRecord({ email: account.email }), partitions: counts });
|
|
283
|
+
records.push({ accountId: account.customerId ? text(account.customerId, 128) : [...partitions][0], email: text(account.email, 320), createdAt: account.createdAt, hasActiveKey: account.hasActiveKey, hasCurrentSession: account.hasCurrentSession, possibleDuplicate: account.possibleDuplicate === true, classification: billing.classifyRevenueRecord({ email: account.email, identityEmails: [...(account.sessionEmails || [])] }), partitions: counts });
|
|
247
284
|
}
|
|
248
285
|
stopped(signal);
|
|
249
286
|
const feedback = await countRecords(root, path.join(root, 'feedback-log.jsonl'), signal);
|
|
@@ -268,17 +305,6 @@ function projectAnalytics(summary) {
|
|
|
268
305
|
};
|
|
269
306
|
}
|
|
270
307
|
|
|
271
|
-
async function preflightAnalytics(root) {
|
|
272
|
-
let total = 0;
|
|
273
|
-
for (const source of billing.getBillingAnalyticsReadPaths()) {
|
|
274
|
-
try {
|
|
275
|
-
const stat = await fs.promises.stat(guardPath(root, source));
|
|
276
|
-
total += stat.size;
|
|
277
|
-
if (!stat.isFile() || total > JSON_LIMIT) throw failure('analytics_source_budget');
|
|
278
|
-
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
308
|
async function collectObservability(deps, signal) {
|
|
283
309
|
stopped(signal);
|
|
284
310
|
let disk = null;
|
|
@@ -287,7 +313,51 @@ async function collectObservability(deps, signal) {
|
|
|
287
313
|
const stats = await fs.promises.statfs(guardPath(deps.feedbackDir, deps.feedbackDir));
|
|
288
314
|
disk = { capacityBytes: stats.blocks * stats.bsize, freeBytes: stats.bavail * stats.bsize, usedBytes: (stats.blocks - stats.bfree) * stats.bsize, scope: 'volume_filesystem' };
|
|
289
315
|
} catch { warnings.push('disk_unavailable'); }
|
|
290
|
-
|
|
316
|
+
const health = deps.health();
|
|
317
|
+
const snapshot = deps.runtime.snapshot();
|
|
318
|
+
const now = Date.now();
|
|
319
|
+
let events = [];
|
|
320
|
+
let beats = [];
|
|
321
|
+
try {
|
|
322
|
+
events = (await opsLog.readLog(deps.feedbackDir, opsLog.EVENTS_FILE, { now, days: 30, signal })).rows;
|
|
323
|
+
beats = (await opsLog.readLog(deps.feedbackDir, opsLog.HEARTBEAT_FILE, { now, days: 30, signal })).rows.map((row) => row.time);
|
|
324
|
+
} catch (error) { if (error.code === 'collection_timeout') throw error; warnings.push('ops_log_unavailable'); }
|
|
325
|
+
const sha = text(deps.buildMetadata?.buildSha, 64) || text(health.buildSha, 64);
|
|
326
|
+
let commitTitle = null;
|
|
327
|
+
let commitTitleReason = null;
|
|
328
|
+
if (sha && typeof deps.lookupCommitTitle === 'function') {
|
|
329
|
+
try { commitTitle = (await deps.lookupCommitTitle(sha, signal)) || null; } catch { commitTitle = null; }
|
|
330
|
+
if (!commitTitle) commitTitleReason = 'GitHub did not return the commit title.';
|
|
331
|
+
} else if (sha) commitTitleReason = 'The commit title lookup is not set up on this server.';
|
|
332
|
+
const report = opsReport.buildReport({
|
|
333
|
+
now, events, beats, disk,
|
|
334
|
+
speed: typeof deps.runtime.speed === 'function' ? deps.runtime.speed() : null,
|
|
335
|
+
startedAt: snapshot.processStartedAt,
|
|
336
|
+
uptimeSeconds: health.uptime,
|
|
337
|
+
sha, commitTitle, commitTitleReason,
|
|
338
|
+
repo: deps.githubRepo === undefined ? 'IgorGanapolsky/ThumbGate' : deps.githubRepo,
|
|
339
|
+
});
|
|
340
|
+
return envelope('current_process', { ...health, ...snapshot, deployment: { id: text(process.env.RAILWAY_DEPLOYMENT_ID, 128), commit: text(process.env.RAILWAY_GIT_COMMIT_SHA, 64), deployedAt: null, deploymentTimeStatus: 'unavailable', buildGeneratedAt: text(deps.buildMetadata?.generatedAt, 64) }, disk, report }, warnings);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const commitTitleCache = new Map();
|
|
344
|
+
// The first line of a commit message from GitHub's public API, cached an hour. Returns null on any failure.
|
|
345
|
+
async function githubCommitTitle(sha, signal, repo = 'IgorGanapolsky/ThumbGate') {
|
|
346
|
+
if (!/^[0-9a-f]{7,64}$/i.test(sha)) return null;
|
|
347
|
+
const cached = commitTitleCache.get(sha);
|
|
348
|
+
if (cached && Date.now() - cached.at < 3600000) return cached.title;
|
|
349
|
+
try {
|
|
350
|
+
const controller = new AbortController();
|
|
351
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
352
|
+
signal?.addEventListener?.('abort', () => controller.abort(), { once: true });
|
|
353
|
+
const response = await fetch('https://api.github.com/repos/' + repo + '/commits/' + sha, { headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'thumbgate-owner-console' }, signal: controller.signal });
|
|
354
|
+
clearTimeout(timer);
|
|
355
|
+
if (!response.ok) return null;
|
|
356
|
+
const body = await response.json();
|
|
357
|
+
const title = text(String(body?.commit?.message || '').split('\n')[0], 200);
|
|
358
|
+
if (title) commitTitleCache.set(sha, { at: Date.now(), title });
|
|
359
|
+
return title;
|
|
360
|
+
} catch { return null; }
|
|
291
361
|
}
|
|
292
362
|
|
|
293
363
|
function deadline(promise, ms, signal) {
|
|
@@ -301,6 +371,424 @@ function deadline(promise, ms, signal) {
|
|
|
301
371
|
});
|
|
302
372
|
}
|
|
303
373
|
|
|
374
|
+
const countMap = (value) => Object.fromEntries(Object.entries(object(value) ? value : {}).filter(([, n]) => Number.isFinite(n)).slice(0, 50).map(([key, n]) => [String(key).slice(0, 64), n]));
|
|
375
|
+
|
|
376
|
+
// The shared billing summary reads about 97 MB of ledgers on the hosted volume, so it never runs in the request:
|
|
377
|
+
// a child process computes it, the result is cached, and tabs that need it say "refreshing" until it lands.
|
|
378
|
+
// Telemetry (visitors, page views, clicks, checkouts) never waits for it: it is streamed from the log tail.
|
|
379
|
+
const SUMMARY_TTL_MS = 10 * 60 * 1000;
|
|
380
|
+
const TELEMETRY_CACHE_MS = 60000;
|
|
381
|
+
const SUMMARY_WORKER = `
|
|
382
|
+
const admin = require(process.argv[1]);
|
|
383
|
+
const billing = require(process.argv[2]);
|
|
384
|
+
billing.getBillingSummaryLive({ window: '30d', stripeReconciliationTimeoutMs: 3000 }, { signal: AbortSignal.timeout(60000) }).then((s) => {
|
|
385
|
+
if (!s || s.error) process.exit(2);
|
|
386
|
+
process.stdout.write(JSON.stringify(admin.summaryParts(s)));
|
|
387
|
+
process.exit(0);
|
|
388
|
+
}).catch(() => process.exit(3));
|
|
389
|
+
`;
|
|
390
|
+
let summarySnapshot = { at: 0, value: null, inflight: null, failed: false };
|
|
391
|
+
const trafficCache = new Map();
|
|
392
|
+
|
|
393
|
+
function summaryParts(summary) {
|
|
394
|
+
return {
|
|
395
|
+
analytics: projectAnalytics(summary),
|
|
396
|
+
leads: {
|
|
397
|
+
signups: countMap(summary.signups?.bySource),
|
|
398
|
+
workflowSprint: { total: number(summary.pipeline?.workflowSprintLeads?.total), bySource: countMap(summary.pipeline?.workflowSprintLeads?.bySource) },
|
|
399
|
+
newsletter: { total: number(summary.newsletter?.total), bySource: countMap(summary.newsletter?.bySource) },
|
|
400
|
+
emailSignups: number(summary.signups?.emailSignups),
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function startSummaryWorker() {
|
|
406
|
+
if (summarySnapshot.inflight) return;
|
|
407
|
+
summarySnapshot.inflight = new Promise((resolve) => {
|
|
408
|
+
require('node:child_process').execFile(process.execPath, ['-e', SUMMARY_WORKER, require.resolve('./owner-admin'), require.resolve('./billing')], { timeout: 90000, maxBuffer: 4 * 1024 * 1024, env: process.env }, (error, stdout) => {
|
|
409
|
+
summarySnapshot.failed = Boolean(error);
|
|
410
|
+
if (!error) { try { summarySnapshot.value = JSON.parse(stdout); summarySnapshot.at = Date.now(); } catch { summarySnapshot.failed = true; } }
|
|
411
|
+
resolve();
|
|
412
|
+
});
|
|
413
|
+
}).finally(() => { summarySnapshot.inflight = null; });
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async function readSummary(deps, signal) {
|
|
417
|
+
if (deps.getBillingSummaryLive) {
|
|
418
|
+
const injected = await deps.getBillingSummaryLive({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal });
|
|
419
|
+
if (!injected || injected.error) throw failure('analytics_unavailable');
|
|
420
|
+
return { value: summaryParts(injected), state: 'ok', collectedAt: new Date().toISOString() };
|
|
421
|
+
}
|
|
422
|
+
const fresh = summarySnapshot.value && Date.now() - summarySnapshot.at < SUMMARY_TTL_MS;
|
|
423
|
+
if (!fresh) startSummaryWorker();
|
|
424
|
+
// First visit after a restart: wait for the worker a few seconds instead of answering "not ready".
|
|
425
|
+
if (!summarySnapshot.value && summarySnapshot.inflight) {
|
|
426
|
+
await Promise.race([summarySnapshot.inflight, new Promise((resolve) => { const timer = setTimeout(resolve, 7000); timer.unref?.(); })]);
|
|
427
|
+
}
|
|
428
|
+
const state = summarySnapshot.value ? (fresh ? 'ok' : 'stale') : (summarySnapshot.failed ? 'failed' : 'refreshing');
|
|
429
|
+
return { value: summarySnapshot.value, state, collectedAt: summarySnapshot.at ? new Date(summarySnapshot.at).toISOString() : null };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// 30 days of site traffic, streamed from the newest end of the telemetry log. Cached for a minute.
|
|
433
|
+
async function readTraffic(deps, signal) {
|
|
434
|
+
const ttl = deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS;
|
|
435
|
+
const key = String(deps.feedbackDir);
|
|
436
|
+
const hit = trafficCache.get(key);
|
|
437
|
+
if (ttl > 0 && hit && Date.now() - hit.at < ttl) return hit.value;
|
|
438
|
+
const value = await ownerTelemetry.readTrafficWindow({ feedbackDir: guardPath(deps.feedbackDir, deps.feedbackDir), days: 30, signal, maxBytes: deps.telemetryMaxBytes });
|
|
439
|
+
value.collectedAt = new Date().toISOString();
|
|
440
|
+
if (ttl > 0) trafficCache.set(key, { at: Date.now(), value });
|
|
441
|
+
return value;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Why the Money board used to say "Stripe is busy": every list held one of the account's two read slots for its whole run
|
|
445
|
+
// (a 30-day checkout list is about six pages), a read that found both taken failed at once, and a read that timed out kept
|
|
446
|
+
// running and kept its slot. Now each page waits for a slot until one shared deadline, a stopped list stops between pages,
|
|
447
|
+
// and a block that still fails shows its last good result for five minutes.
|
|
448
|
+
const STRIPE_DEADLINE_MS = 8500;
|
|
449
|
+
const LAST_GOOD_MS = 5 * 60 * 1000;
|
|
450
|
+
const lastGood = new Map();
|
|
451
|
+
const pause = (ms, signal) => new Promise((resolve) => {
|
|
452
|
+
const timer = setTimeout(resolve, ms);
|
|
453
|
+
timer.unref?.();
|
|
454
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
async function withSlot(work, signal) {
|
|
458
|
+
for (;;) {
|
|
459
|
+
stopped(signal);
|
|
460
|
+
try { return await billing.withStripeReadSlot(work, { signal }); } catch (error) {
|
|
461
|
+
if (error?.code !== 'provider_busy') throw error;
|
|
462
|
+
await pause(100, signal);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Pages a Stripe list with starting_after, 100 rows at a time, newest first. `complete` is false when the page cap was hit.
|
|
468
|
+
async function listAll({ list, params, keep = () => true, maxPages = 40, signal, until }) {
|
|
469
|
+
const rows = [];
|
|
470
|
+
let after = null;
|
|
471
|
+
for (let page = 0; ; page += 1) {
|
|
472
|
+
stopped(signal);
|
|
473
|
+
if (page >= maxPages) return { rows, complete: false };
|
|
474
|
+
const left = Math.max(1, until - Date.now());
|
|
475
|
+
const result = await deadline(withSlot(() => list({ ...params, limit: 100, ...(after ? { starting_after: after } : {}) }, { timeout: Math.min(8000, left), maxNetworkRetries: 0 }), signal), left, signal);
|
|
476
|
+
if (!Array.isArray(result?.data)) throw failure('provider_unavailable');
|
|
477
|
+
for (const row of result.data) if (keep(row)) rows.push(row);
|
|
478
|
+
if (result.has_more !== true || !result.data.length) return { rows, complete: true };
|
|
479
|
+
after = result.data.at(-1).id;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''));
|
|
484
|
+
|
|
485
|
+
// Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
|
|
486
|
+
function stripeReason(error) {
|
|
487
|
+
if (/STRIPE_SECRET_KEY is missing/i.test(String(error?.message || ''))) return 'Stripe key missing';
|
|
488
|
+
if (error?.code === 'collection_timeout') return 'Stripe did not answer in time';
|
|
489
|
+
if (error?.code === 'provider_busy') return 'Stripe is busy, refresh in a moment';
|
|
490
|
+
return 'Stripe unavailable';
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const attempt = async (work, reasonOf) => {
|
|
494
|
+
try { return { ok: true, value: await work(), reason: null }; } catch (error) { return { ok: false, value: null, reason: reasonOf(error) }; }
|
|
495
|
+
};
|
|
496
|
+
const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'telemetry read timed out' : 'telemetry read failed');
|
|
497
|
+
|
|
498
|
+
const trafficFields = (read) => ({ visitors: read.traffic.visitors, realVisitors: read.traffic.realVisitors, botOrInternalVisitors: read.traffic.botOrInternalVisitors, pageViewers: read.traffic.pageViewers, checkoutStartsByType: read.traffic.checkoutStartsByType, sessions: read.traffic.sessions, pageViews: read.traffic.pageViews, ctaClicks: read.traffic.ctaClicks, checkoutStarts: read.traffic.checkoutStarts, checkoutPaidConfirmations: read.traffic.checkoutPaidConfirmations });
|
|
499
|
+
|
|
500
|
+
// Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
|
|
501
|
+
// Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
|
|
502
|
+
async function collectMoney(deps, signal) {
|
|
503
|
+
const ttl = deps.moneyCacheMs ?? MONEY_CACHE_MS;
|
|
504
|
+
if (ttl > 0 && moneyCache && Date.now() - moneyCache.at < ttl) return moneyCache.value;
|
|
505
|
+
const ownerEmails = (deps.getOwnerEmails || require('./bot-detection').getOwnerEmails)();
|
|
506
|
+
const stripe = () => (deps.getStripeClient || billing.getStripeClient)();
|
|
507
|
+
const { countSessions, classifySession, BOT_CHECK_BEGAN_AT, BOT_CHECK_BEGAN_LABEL } = require('./checkout-session-count');
|
|
508
|
+
// A test may move the date; production always uses the date the human-click gate went live.
|
|
509
|
+
const botCheckBeganAt = deps.botCheckBeganAt || BOT_CHECK_BEGAN_AT;
|
|
510
|
+
const botCheckBeganLabel = deps.botCheckBeganAt ? deps.botCheckBeganAt : BOT_CHECK_BEGAN_LABEL;
|
|
511
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
512
|
+
|
|
513
|
+
// One deadline for all of Stripe's reads, shared by every block below.
|
|
514
|
+
const stripeMs = deps.stripeDeadlineMs ?? STRIPE_DEADLINE_MS;
|
|
515
|
+
const until = Date.now() + stripeMs;
|
|
516
|
+
const shared = new AbortController();
|
|
517
|
+
const stopShared = () => shared.abort();
|
|
518
|
+
signal?.addEventListener('abort', stopShared, { once: true });
|
|
519
|
+
const sharedTimer = setTimeout(stopShared, stripeMs);
|
|
520
|
+
if (signal?.aborted) stopShared();
|
|
521
|
+
const keepMs = deps.lastGoodMs ?? LAST_GOOD_MS;
|
|
522
|
+
const staleBlocks = {};
|
|
523
|
+
// A block that fails shows its last good result when that is under five minutes old, and says so.
|
|
524
|
+
const withLastGood = async (key, work) => {
|
|
525
|
+
const run = await attempt(work, stripeReason);
|
|
526
|
+
if (run.ok) { if (keepMs > 0) lastGood.set(key, { at: Date.now(), value: run.value }); return run; }
|
|
527
|
+
const kept = keepMs > 0 ? lastGood.get(key) : null;
|
|
528
|
+
if (kept && Date.now() - kept.at < keepMs) { staleBlocks[key] = kept.at; return { ok: true, value: kept.value, reason: null }; }
|
|
529
|
+
return run;
|
|
530
|
+
};
|
|
531
|
+
const listIt = (list, params, keep, maxPages) => listAll({ list, params, keep, maxPages, signal: shared.signal, until });
|
|
532
|
+
|
|
533
|
+
// Two lanes: one lists paid checkouts then subscriptions, the other lists checkout sessions. Each page waits for a free slot.
|
|
534
|
+
const paidAndProLane = (async () => {
|
|
535
|
+
const paidResult = await withLastGood('paid', async () => {
|
|
536
|
+
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options),
|
|
537
|
+
{ status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge'] },
|
|
538
|
+
(row) => row.status === 'complete' && thumbgateSession(row), 10);
|
|
539
|
+
// Paid and not refunded in full, owner and test purchases excluded. A partial refund comes off the revenue.
|
|
540
|
+
const charge = (row) => (object(row.payment_intent) && object(row.payment_intent.latest_charge) ? row.payment_intent.latest_charge : null);
|
|
541
|
+
const paid = result.rows.filter((row) => row.payment_status === 'paid' && classifySession(row, { ownerEmails }) !== 'internal' && charge(row)?.refunded !== true);
|
|
542
|
+
const customers = new Set(paid.map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
|
|
543
|
+
const revenue = {};
|
|
544
|
+
for (const row of paid) {
|
|
545
|
+
if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
|
|
546
|
+
const code = row.currency.toUpperCase();
|
|
547
|
+
const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
|
|
548
|
+
revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
|
|
549
|
+
}
|
|
550
|
+
return { customers, revenue, complete: result.complete };
|
|
551
|
+
});
|
|
552
|
+
const proResult = await withLastGood('subscriptions', async () => {
|
|
553
|
+
const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
|
|
554
|
+
const external = result.rows.filter((row) => {
|
|
555
|
+
const email = String(row.customer?.email || '').toLowerCase();
|
|
556
|
+
return !(email && ownerEmails.some((owner) => email === String(owner).toLowerCase()));
|
|
557
|
+
});
|
|
558
|
+
const customers = new Set(external.map((row) => id(row.customer) || String(row.customer?.email || row.id).toLowerCase()));
|
|
559
|
+
return { count: external.length, customers, complete: result.complete };
|
|
560
|
+
});
|
|
561
|
+
return [paidResult, proResult];
|
|
562
|
+
})();
|
|
563
|
+
let paidAndPro; let sessionRun; let trafficRun; let summaryRun;
|
|
564
|
+
try {
|
|
565
|
+
[paidAndPro, sessionRun, trafficRun, summaryRun] = await Promise.all([
|
|
566
|
+
paidAndProLane,
|
|
567
|
+
withLastGood('checkouts', async () => {
|
|
568
|
+
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options), { created: { gte: nowSeconds - 30 * 86400 } }, thumbgateSession, 40);
|
|
569
|
+
const since7 = nowSeconds - 7 * 86400;
|
|
570
|
+
// Sessions made before the bot check carry no user-agent class, so they are reported apart from the ones after it.
|
|
571
|
+
const botCheckSeconds = Date.parse(botCheckBeganAt) / 1000;
|
|
572
|
+
const beforeBotCheck = (row) => Boolean(row.created) && row.created < botCheckSeconds;
|
|
573
|
+
const classified = result.rows.filter((row) => row.metadata?.uaClass && row.created).map((row) => row.created);
|
|
574
|
+
return {
|
|
575
|
+
d30: countSessions(result.rows, { ownerEmails }),
|
|
576
|
+
d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }),
|
|
577
|
+
before: countSessions(result.rows.filter(beforeBotCheck), { ownerEmails }),
|
|
578
|
+
since: countSessions(result.rows.filter((row) => !beforeBotCheck(row)), { ownerEmails }),
|
|
579
|
+
firstClassifiedAt: classified.length ? new Date(Math.min(...classified) * 1000).toISOString() : null,
|
|
580
|
+
complete: result.complete,
|
|
581
|
+
};
|
|
582
|
+
}),
|
|
583
|
+
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
584
|
+
attempt(() => readSummary(deps, signal), () => 'lead ledgers failed'),
|
|
585
|
+
]);
|
|
586
|
+
} finally {
|
|
587
|
+
clearTimeout(sharedTimer);
|
|
588
|
+
signal?.removeEventListener('abort', stopShared);
|
|
589
|
+
stopShared();
|
|
590
|
+
}
|
|
591
|
+
const [paidRun, proRun] = paidAndPro;
|
|
592
|
+
|
|
593
|
+
const parts = summaryRun.value?.value || null;
|
|
594
|
+
const leadsReason = parts ? null : summaryRun.ok && summaryRun.value.state === 'refreshing' ? 'lead ledgers still calculating, refresh in a minute' : 'lead ledgers failed';
|
|
595
|
+
const trafficRead = trafficRun.value;
|
|
596
|
+
const trafficReason = !trafficRun.ok ? trafficRun.reason : trafficRead.empty ? 'telemetry store empty' : null;
|
|
597
|
+
const paid = paidRun.value;
|
|
598
|
+
const sessions = sessionRun.value;
|
|
599
|
+
const sessionBuckets = (counts) => (counts ? {
|
|
600
|
+
started: counts.started,
|
|
601
|
+
human: counts.nonCrawlerStarted,
|
|
602
|
+
completedHuman: counts.nonCrawlerCompleted,
|
|
603
|
+
paidHuman: counts.nonCrawlerPaid,
|
|
604
|
+
bot: counts.excluded.bot,
|
|
605
|
+
notClassified: counts.excluded.unclassified + counts.excluded.unknownUa,
|
|
606
|
+
internal: counts.excluded.internal,
|
|
607
|
+
} : null);
|
|
608
|
+
const bothStripe = paid && proRun.value;
|
|
609
|
+
// The checkout panel: sessions with no bot check on record come first, then people, bots and owner only for sessions
|
|
610
|
+
// created after the bot check began, then the gap between the site's own start events and Stripe's sessions.
|
|
611
|
+
const checkoutBotCheck = (counts, traffic) => {
|
|
612
|
+
if (!counts) return null;
|
|
613
|
+
const stripeSessions = counts.d30.started;
|
|
614
|
+
const siteStarts = traffic ? traffic.traffic.checkoutStarts : null;
|
|
615
|
+
const difference = siteStarts === null ? null : siteStarts - stripeSessions;
|
|
616
|
+
return {
|
|
617
|
+
window: '30d',
|
|
618
|
+
botCheckBeganAt,
|
|
619
|
+
botCheckBeganLabel,
|
|
620
|
+
firstClassifiedAt: counts.firstClassifiedAt,
|
|
621
|
+
notClassified: sessionBuckets(counts.d30).notClassified,
|
|
622
|
+
beforeBotCheck: sessionBuckets(counts.before),
|
|
623
|
+
sinceBotCheck: sessionBuckets(counts.since),
|
|
624
|
+
siteVersusStripe: siteStarts === null ? null : {
|
|
625
|
+
siteStarts,
|
|
626
|
+
siteStartsByType: traffic.traffic.checkoutStartsByType || {},
|
|
627
|
+
stripeSessions,
|
|
628
|
+
difference,
|
|
629
|
+
status: difference === 0 ? 'match' : 'unexplained',
|
|
630
|
+
reason: difference === 0 ? 'The two counts match.'
|
|
631
|
+
: 'Unexplained. The site count adds up four kinds of start events (listed here); Stripe counts the sessions it created. They are not matched one to one, so the gap is not itemised.',
|
|
632
|
+
},
|
|
633
|
+
};
|
|
634
|
+
};
|
|
635
|
+
// When each source was last read. A block showing its last good value reports that older time and `stale: true`.
|
|
636
|
+
const blockTime = (key) => ({ collectedAt: new Date(staleBlocks[key] || Date.now()).toISOString(), stale: Object.hasOwn(staleBlocks, key) });
|
|
637
|
+
const freshness = {
|
|
638
|
+
paid: blockTime('paid'),
|
|
639
|
+
subscriptions: blockTime('subscriptions'),
|
|
640
|
+
checkouts: blockTime('checkouts'),
|
|
641
|
+
traffic: { collectedAt: trafficRead?.collectedAt || null, stale: false },
|
|
642
|
+
leads: { collectedAt: summaryRun.value?.collectedAt || null, stale: summaryRun.value?.state === 'stale' },
|
|
643
|
+
displayRefreshedAt: new Date().toISOString(),
|
|
644
|
+
telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000),
|
|
645
|
+
billingSummaryCacheSeconds: SUMMARY_TTL_MS / 1000,
|
|
646
|
+
};
|
|
647
|
+
const data = {
|
|
648
|
+
windows: { revenue: '30d', checkouts: '7d', traffic: '30d', leads: '30d' },
|
|
649
|
+
freshness,
|
|
650
|
+
// Counted straight from Stripe: people with a paid, unrefunded checkout in the past year plus active subscribers, once each.
|
|
651
|
+
payingCustomers: bothStripe ? new Set([...paid.customers, ...proRun.value.customers]).size : null,
|
|
652
|
+
payingCustomersSource: 'stripe',
|
|
653
|
+
payingCustomersBasis: bothStripe ? (paid.complete && proRun.value.complete ? 'stripe_paid_and_active' : 'stripe_paid_and_active_partial') : 'unavailable',
|
|
654
|
+
activePro: proRun.value ? proRun.value.count : null,
|
|
655
|
+
activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
|
|
656
|
+
revenueLast30Days: paid ? paid.revenue : null,
|
|
657
|
+
revenueBasis: 'stripe_paid_checkouts_after_refunds',
|
|
658
|
+
checkouts7d: sessionBuckets(sessions?.d7),
|
|
659
|
+
checkouts30d: sessionBuckets(sessions?.d30),
|
|
660
|
+
checkoutBotCheck: checkoutBotCheck(sessions, trafficReason ? null : trafficRead),
|
|
661
|
+
traffic30d: trafficReason ? null : { ...trafficFields(trafficRead), partial: trafficRead.partial },
|
|
662
|
+
leadsBySource: parts ? parts.leads : null,
|
|
663
|
+
reasons: {
|
|
664
|
+
payingCustomers: bothStripe ? null : (paidRun.reason || proRun.reason),
|
|
665
|
+
activePro: proRun.value ? null : proRun.reason,
|
|
666
|
+
revenue: paid ? null : paidRun.reason,
|
|
667
|
+
checkouts: sessions ? null : sessionRun.reason,
|
|
668
|
+
visitors: trafficReason,
|
|
669
|
+
leads: leadsReason,
|
|
670
|
+
},
|
|
671
|
+
notes: ['Every started checkout is counted once: real people, bots, not classified, or owner and test.', 'Sessions created before the bot check carry no browser class, so they are counted as not classified.'],
|
|
672
|
+
};
|
|
673
|
+
const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts' };
|
|
674
|
+
for (const [key, at] of Object.entries(staleBlocks)) {
|
|
675
|
+
const minutes = Math.max(1, Math.round((Date.now() - at) / 60000));
|
|
676
|
+
data.notes.push(`Showing the last good ${staleLabel[key]} from ${minutes} minute${minutes === 1 ? '' : 's'} ago, because Stripe did not answer this time.`);
|
|
677
|
+
}
|
|
678
|
+
if (sessions && sessions.complete === false) data.notes.push('The 30-day checkout list was cut short at 4,000 sessions, so the 30-day counts are a lower bound.');
|
|
679
|
+
const warnings = [];
|
|
680
|
+
if (Object.keys(staleBlocks).length) warnings.push('showing_last_good_stripe_numbers');
|
|
681
|
+
if (sessions && sessions.complete === false) warnings.push('checkout_list_partial');
|
|
682
|
+
if (!paidRun.ok) warnings.push('paid_checkout_list_unavailable');
|
|
683
|
+
if (!sessionRun.ok) warnings.push('checkout_list_unavailable');
|
|
684
|
+
if (!proRun.ok) warnings.push('subscription_list_unavailable');
|
|
685
|
+
if (trafficReason) warnings.push('telemetry_unavailable');
|
|
686
|
+
if (leadsReason) warnings.push('leads_unavailable');
|
|
687
|
+
const failed = [paidRun, sessionRun, proRun].filter((run) => !run.ok).length;
|
|
688
|
+
const value = envelope('stripe_and_telemetry', data, warnings, failed === 3 && trafficReason ? 'unavailable' : warnings.length ? 'partial' : 'ok');
|
|
689
|
+
if (ttl > 0 && warnings.length === 0) moneyCache = { at: Date.now(), value };
|
|
690
|
+
return value;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// Analytics: 30 days of traffic streamed from the telemetry tail (never refused for size), a daily series, and the
|
|
694
|
+
// billing totals from the cached child-process summary when it is ready.
|
|
695
|
+
async function collectAnalytics(deps, signal) {
|
|
696
|
+
const [trafficRun, summaryRun] = await Promise.all([
|
|
697
|
+
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
698
|
+
attempt(() => readSummary(deps, signal), () => 'billing totals failed'),
|
|
699
|
+
]);
|
|
700
|
+
const parts = summaryRun.value?.value || null;
|
|
701
|
+
const trafficRead = trafficRun.value;
|
|
702
|
+
if (!trafficRun.ok && !parts) throw Object.assign(new Error('analytics_unavailable'), { code: trafficRun.reason === 'telemetry read timed out' ? 'collection_timeout' : 'analytics_unavailable' });
|
|
703
|
+
const data = parts?.analytics ? { ...parts.analytics } : { window: '30d' };
|
|
704
|
+
const hasTraffic = trafficRun.ok && !trafficRead.empty;
|
|
705
|
+
data.trafficMetrics = hasTraffic ? trafficFields(trafficRead) : (data.trafficMetrics || null);
|
|
706
|
+
data.daily = hasTraffic ? trafficRead.daily : [];
|
|
707
|
+
data.dataQuality = { ...(data.dataQuality || {}), telemetryWindowComplete: hasTraffic ? !trafficRead.partial : false, telemetryBytesRead: trafficRead ? trafficRead.bytesRead : 0, telemetrySizeBytes: trafficRead ? trafficRead.size : 0 };
|
|
708
|
+
const warnings = [];
|
|
709
|
+
if (data.reconciliation && (data.reconciliation.status !== 'ok' || !data.reconciliation.complete)) warnings.push('stripe_reconciliation_' + data.reconciliation.status);
|
|
710
|
+
if (!parts) warnings.push(summaryRun.ok && summaryRun.value.state === 'refreshing' ? 'billing_totals_refreshing' : 'billing_totals_unavailable');
|
|
711
|
+
if (!hasTraffic) warnings.push(trafficRun.ok ? 'telemetry_store_empty' : 'telemetry_unavailable');
|
|
712
|
+
else if (trafficRead.partial) warnings.push('telemetry_incomplete');
|
|
713
|
+
return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// One metric of the read-only summary: its value, where it came from, when that source was read, and one of these states:
|
|
717
|
+
// ok a number from a source that answered in full
|
|
718
|
+
// verified_zero a zero from a source that answered in full
|
|
719
|
+
// partial a number from a source that answered only in part (a lower bound)
|
|
720
|
+
// stale the last good value, with lastVerifiedAt; the source failed this time
|
|
721
|
+
// unavailable the source failed and there is no earlier value
|
|
722
|
+
// unresolved the source answered but the metric cannot be settled yet (still calculating)
|
|
723
|
+
function metric(label, value, { source, collectedAt = null, reason = null, partial = false, stale = false, unresolved = false }) {
|
|
724
|
+
const missing = value === null || value === undefined;
|
|
725
|
+
let status = 'ok';
|
|
726
|
+
if (missing) status = unresolved ? 'unresolved' : 'unavailable';
|
|
727
|
+
else if (stale) status = 'stale';
|
|
728
|
+
else if (partial) status = 'partial';
|
|
729
|
+
else if (value === 0) status = 'verified_zero';
|
|
730
|
+
const out = { label, value: missing ? null : value, source, collectedAt, status };
|
|
731
|
+
if (reason && (missing || stale || partial)) out.reason = reason;
|
|
732
|
+
if (stale && !missing) out.lastVerifiedAt = collectedAt;
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// GET /v1/admin/summary: the numbers the Money and Analytics tabs show, as JSON an agent can read instead of scraping HTML.
|
|
737
|
+
async function collectSummary(deps, signal) {
|
|
738
|
+
const [moneyRun, analyticsRun] = await Promise.all([
|
|
739
|
+
attempt(() => collectMoney(deps, signal), () => 'Money collection failed'),
|
|
740
|
+
attempt(() => collectAnalytics(deps, signal), () => 'Analytics collection failed'),
|
|
741
|
+
]);
|
|
742
|
+
const money = moneyRun.ok ? moneyRun.value.data : null;
|
|
743
|
+
const analytics = analyticsRun.ok ? analyticsRun.value.data : null;
|
|
744
|
+
const why = money?.reasons || {};
|
|
745
|
+
const fresh = money?.freshness || {};
|
|
746
|
+
const refreshed = money?.freshness?.displayRefreshedAt || new Date().toISOString();
|
|
747
|
+
const stripeOpts = (key, reason) => ({ source: 'stripe', collectedAt: fresh[key]?.collectedAt || null, stale: Boolean(fresh[key]?.stale), reason });
|
|
748
|
+
const trafficOpts = { source: 'site_telemetry', collectedAt: fresh.traffic?.collectedAt || null, reason: why.visitors, partial: money?.traffic30d?.partial === true };
|
|
749
|
+
const leadOpts = { source: 'lead_ledgers', collectedAt: fresh.leads?.collectedAt || null, reason: why.leads, stale: Boolean(fresh.leads?.stale), unresolved: /still calculating/i.test(why.leads || '') };
|
|
750
|
+
const fields = {};
|
|
751
|
+
const add = (key, label, value, options) => { fields[key] = metric(label, value, options); };
|
|
752
|
+
const buckets = (prefix, label, block, reason) => {
|
|
753
|
+
for (const [name, words] of [['started', 'started'], ['human', 'browser-classified'], ['bot', 'bot-classified'], ['notClassified', 'with insufficient classification evidence'], ['internal', 'owner and test']]) add(`${prefix}.${name}`, `Checkout sessions ${words} (${label})`, block ? block[name] : null, stripeOpts('checkouts', why.checkouts));
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
if (money) {
|
|
757
|
+
add('money.paying_customers', 'Paying customers', money.payingCustomers, { ...stripeOpts('paid', why.payingCustomers), partial: money.payingCustomersBasis === 'stripe_paid_and_active_partial' });
|
|
758
|
+
add('money.active_pro', 'Active Pro subscriptions', money.activePro, { ...stripeOpts('subscriptions', why.activePro), partial: money.activeProBasis === 'stripe_active_subscriptions_first_100_only' });
|
|
759
|
+
// collectMoney reads completed Checkout Sessions only, so this is first-charge revenue; renewal invoices never appear in it.
|
|
760
|
+
add('money.revenue_30d', 'One-time checkout revenue, past 30 days, by currency (completed Checkout Sessions after refunds)', money.revenueLast30Days, stripeOpts('paid', why.revenue));
|
|
761
|
+
add('money.subscription_invoices_30d', 'Subscription invoices, past 30 days', null, { source: 'stripe', unresolved: true, reason: 'Not collected yet: renewal invoices are not read, so recurring revenue is not in any revenue number here' });
|
|
762
|
+
buckets('money.checkouts_7d', '7 days', money.checkouts7d);
|
|
763
|
+
buckets('money.checkouts_30d', '30 days', money.checkouts30d);
|
|
764
|
+
const panel = money.checkoutBotCheck;
|
|
765
|
+
add('money.checkout_bot_check', 'Checkout sessions split at the bot check (30 days)', panel, stripeOpts('checkouts', why.checkouts));
|
|
766
|
+
add('money.signups_by_source', 'Signups by source', money.leadsBySource?.signups ?? null, leadOpts);
|
|
767
|
+
add('money.workflow_sprint_leads', 'Setup Sprint leads', money.leadsBySource?.workflowSprint ?? null, leadOpts);
|
|
768
|
+
add('money.newsletter', 'Newsletter signups', money.leadsBySource?.newsletter ?? null, leadOpts);
|
|
769
|
+
}
|
|
770
|
+
const traffic = analytics?.trafficMetrics || money?.traffic30d || null;
|
|
771
|
+
const trafficField = (key, label, name) => add(key, label, traffic ? traffic[name] ?? null : null, trafficOpts);
|
|
772
|
+
trafficField('traffic.visitor_identifiers_all_30d', 'All observed visitor identifiers (30 days)', 'visitors');
|
|
773
|
+
if (money?.traffic30d) add('traffic.visitor_identifiers_excluding_flagged_30d', 'Observed visitor identifiers, excluding bot, internal and test (30 days)', money.traffic30d.realVisitors, trafficOpts);
|
|
774
|
+
trafficField('traffic.landing_page_views_30d', 'Landing page views (30 days)', 'pageViews');
|
|
775
|
+
trafficField('traffic.cta_clicks_30d', 'Call to action clicks (30 days)', 'ctaClicks');
|
|
776
|
+
trafficField('traffic.checkout_starts_30d', 'Checkout starts seen on the site (30 days)', 'checkoutStarts');
|
|
777
|
+
trafficField('traffic.paid_confirmations_30d', 'Paid confirmations (30 days)', 'checkoutPaidConfirmations');
|
|
778
|
+
add('traffic.daily_30d', 'Daily traffic, past 30 days', analytics ? analytics.daily : null, trafficOpts);
|
|
779
|
+
const billingOpts = { source: 'billing_summary', collectedAt: fresh.leads?.collectedAt || null, reason: analyticsRun.ok ? null : analyticsRun.reason, unresolved: !analytics?.signups };
|
|
780
|
+
add('analytics.email_signups', 'Email signups', analytics?.signups?.emailSignups ?? null, billingOpts);
|
|
781
|
+
add('analytics.external_paid_orders', 'External paid orders', analytics?.revenue?.external?.paidOrders ?? null, billingOpts);
|
|
782
|
+
add('analytics.external_booked_revenue_30d', 'External booked revenue, past 30 days, by currency', analytics?.revenue?.external?.bookedRevenueByCurrency ?? null, billingOpts);
|
|
783
|
+
|
|
784
|
+
// A permanent, stated gap is listed apart so the overall state reflects sources that failed, not a feature not built yet.
|
|
785
|
+
const knownGaps = ['money.subscription_invoices_30d'];
|
|
786
|
+
const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key)).map(([, entry]) => entry.status);
|
|
787
|
+
const bad = states.filter((state) => state === 'unavailable').length;
|
|
788
|
+
const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
|
|
789
|
+
return envelope('owner_console_summary', { generatedAt: refreshed, readOnly: true, windows: { checkouts: '7d and 30d', traffic: '30d', revenue: '30d' }, freshness: { displayRefreshedAt: refreshed, stripeCollectedAt: fresh.checkouts?.collectedAt || null, telemetryCollectedAt: fresh.traffic?.collectedAt || null, leadsCollectedAt: fresh.leads?.collectedAt || null, telemetryCacheSeconds: Math.round((deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS) / 1000), billingSummaryCacheSeconds: Math.round(SUMMARY_TTL_MS / 1000) }, fields, knownGaps, unavailableFields: bad }, [], overall);
|
|
790
|
+
}
|
|
791
|
+
|
|
304
792
|
async function collectAdminSection(route, deps, externalSignal) {
|
|
305
793
|
if (activeCollections >= 2) throw failure('collection_busy');
|
|
306
794
|
activeCollections += 1;
|
|
@@ -313,26 +801,19 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
313
801
|
const operation = async () => {
|
|
314
802
|
stopped(controller.signal);
|
|
315
803
|
if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
|
|
804
|
+
if (route.section === 'money') return collectMoney(deps, controller.signal);
|
|
805
|
+
if (route.section === 'summary') return collectSummary(deps, controller.signal);
|
|
316
806
|
if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
|
|
317
807
|
if (route.section === 'data') return collectData(route, deps, controller.signal);
|
|
318
808
|
if (route.section === 'observability') return collectObservability(deps, controller.signal);
|
|
319
|
-
|
|
320
|
-
stopped(controller.signal);
|
|
321
|
-
const summary = await (deps.getBillingSummaryLive || billing.getBillingSummaryLive)({ window: '30d', stripeReconciliationTimeoutMs: 8000 }, { signal: controller.signal });
|
|
322
|
-
stopped(controller.signal);
|
|
323
|
-
if (summary.error) throw failure('analytics_unavailable');
|
|
324
|
-
const data = projectAnalytics(summary);
|
|
325
|
-
const warnings = data.reconciliation.status !== 'ok' || !data.reconciliation.complete ? ['stripe_reconciliation_' + data.reconciliation.status] : [];
|
|
326
|
-
if (summary.sourceDiagnostics?.warnings?.length) warnings.push('source_quality_warning');
|
|
327
|
-
if (!data.dataQuality.telemetryWindowComplete) warnings.push('telemetry_incomplete');
|
|
328
|
-
return envelope('shared_billing_summary_30d', data, warnings);
|
|
809
|
+
return collectAnalytics(deps, controller.signal);
|
|
329
810
|
};
|
|
330
811
|
return await deadline(operation(), deps.sectionTimeoutMs || 10000, controller.signal);
|
|
331
812
|
} catch (error) {
|
|
332
|
-
return envelope(route.section, null, [error.code === 'collection_timeout' ? 'collection_timeout' :
|
|
813
|
+
return envelope(route.section, null, [error.code === 'collection_timeout' ? 'collection_timeout' : 'source_unavailable'], 'unavailable');
|
|
333
814
|
} finally {
|
|
334
815
|
abort(); clearTimeout(timer); externalSignal?.removeEventListener('abort', abort); activeCollections -= 1;
|
|
335
816
|
}
|
|
336
817
|
}
|
|
337
818
|
|
|
338
|
-
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, collectAdminSection, createRuntimeObservations, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
|
819
|
+
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|