thumbgate 1.40.10 → 1.40.13
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/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +46 -40
- 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/bin/cli.js +9 -8
- package/bin/postinstall.js +2 -2
- package/config/unit-costs.json +47 -0
- package/package.json +16 -5
- package/public/admin.html +284 -29
- package/public/agent-manager.html +2 -2
- package/public/agents-cost-savings.html +1 -1
- package/public/codex-enterprise.html +2 -2
- package/public/compare.html +3 -3
- package/public/dashboard.html +28 -9
- package/public/diagnostic.html +1 -1
- package/public/founders.html +1 -1
- package/public/guide.html +4 -4
- package/public/index.html +80 -116
- package/public/install.html +19 -19
- package/public/js/connect-panel.js +21 -7
- package/public/learn.html +8 -0
- package/public/lessons.html +1 -1
- package/public/numbers.html +2 -2
- package/public/pricing.html +12 -9
- package/public/pro.html +96 -137
- package/public/project-switcher.js +50 -19
- package/scripts/auto-wire-hooks.js +36 -2
- package/scripts/billing.js +3 -1
- package/scripts/cli-schema.js +2 -3
- package/scripts/commercial-offer.js +1 -1
- package/scripts/cost-meter.js +161 -0
- package/scripts/gates-engine.js +26 -8
- package/scripts/hook-runtime.js +18 -1
- package/scripts/mailer/resend-mailer.js +2 -0
- package/scripts/owner-admin.js +338 -16
- package/scripts/owner-alerts.js +79 -0
- package/scripts/owner-telemetry.js +113 -3
- package/scripts/pr-manager.js +156 -41
- package/scripts/project-catalog.js +3 -1
- package/scripts/project-identity.js +10 -2
- package/scripts/seo-gsd.js +1 -1
- package/scripts/telemetry-analytics.js +7 -1
- package/scripts/unit-economics.js +138 -0
- package/server.json +2 -2
- package/src/api/server.js +62 -4
- package/src/mcp-writeguard.js +2 -2
package/scripts/owner-admin.js
CHANGED
|
@@ -8,12 +8,15 @@ const billing = require('./billing');
|
|
|
8
8
|
const ownerTelemetry = require('./owner-telemetry');
|
|
9
9
|
const opsLog = require('./ops-log');
|
|
10
10
|
const opsReport = require('./ops-report');
|
|
11
|
+
const ownerAlerts = require('./owner-alerts');
|
|
12
|
+
const costMeter = require('./cost-meter');
|
|
13
|
+
const unitEconomics = require('./unit-economics');
|
|
11
14
|
|
|
12
15
|
const JSON_LIMIT = 8 * 1024 * 1024;
|
|
13
16
|
const LOG_LIMIT = 16 * 1024 * 1024;
|
|
14
17
|
const RESPONSE_LIMIT = 1024 * 1024;
|
|
15
18
|
const RESOURCES = Object.freeze({ customers: 'cus', subscriptions: 'sub', payments: 'ch', refunds: 're', products: 'prod', prices: 'price', 'subscription-items': 'si' });
|
|
16
|
-
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary']);
|
|
19
|
+
const SECTIONS = new Set(['overview', 'money', 'data', 'analytics', 'observability', 'summary', 'alerts', 'economics']);
|
|
17
20
|
const MONEY_CACHE_MS = 60000;
|
|
18
21
|
let moneyCache = null;
|
|
19
22
|
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' });
|
|
@@ -49,7 +52,10 @@ function parseAdminRoute(pathname, params) {
|
|
|
49
52
|
if (limitRaw !== null && (!/^[1-9][0-9]*$/.test(limitRaw) || Number(limitRaw) > max)) throw failure('invalid_query');
|
|
50
53
|
const limit = limitRaw === null ? 25 : Number(limitRaw);
|
|
51
54
|
const cursor = params.get(section === 'data' ? 'cursor' : 'starting_after') || '';
|
|
52
|
-
|
|
55
|
+
// Stripe charge lists can return ch_ or py_ identifiers. Accept both only
|
|
56
|
+
// for payments, so the nextCursor we return is valid for the next request.
|
|
57
|
+
const cursorPrefix = resource === 'payments' ? '(?:ch|py)' : RESOURCES[resource];
|
|
58
|
+
if (section === 'stripe' && cursor && !new RegExp(`^${cursorPrefix}_[A-Za-z0-9]{1,120}$`).test(cursor)) throw failure('invalid_query');
|
|
53
59
|
let offset = 0;
|
|
54
60
|
if (section === 'data' && cursor) {
|
|
55
61
|
if (!/^[A-Za-z0-9_-]{1,32}$/.test(cursor)) throw failure('invalid_query');
|
|
@@ -296,6 +302,7 @@ function projectAnalytics(summary) {
|
|
|
296
302
|
return {
|
|
297
303
|
funnel: { ...numericFields(summary.funnel, ['totalEvents', 'uniqueAcquisitionLeads', 'uniquePaidCustomers', 'excludedSyntheticCheckoutSessions']), stageCounts: numericFields(summary.funnel?.stageCounts, ['acquisition', 'activation', 'paid']), conversionRates: numericFields(summary.funnel?.conversionRates, ['acquisitionToActivation', 'activationToPaid', 'acquisitionToPaid']) },
|
|
298
304
|
signups: numericFields(summary.signups, ['total', 'uniqueLeads', 'emailSignups', 'emailRecords', 'checkoutSessionsCreated']),
|
|
305
|
+
checkoutSessionDepth: { ...numericFields(summary.checkoutSessionDepth, ['sessionsCreated', 'raw', 'identified', 'paymentAttempt', 'paid', 'unresolved', 'qualifiedCheckoutStarts']), basis: summary.checkoutSessionDepth?.basis === 'stripe_session_lookup' ? 'stripe_session_lookup' : 'telemetry_heuristic', lookupStatus: ['ok', 'partial', 'unconfigured', 'unavailable', 'not_requested'].includes(summary.checkoutSessionDepth?.lookupStatus) ? summary.checkoutSessionDepth.lookupStatus : 'unavailable' },
|
|
299
306
|
revenue: { external: { ...numericFields(external, ['paidOrders', 'amountUnknownOrders', 'duplicates']), bookedRevenueByCurrency: currencies(external?.bookedRevenueByCurrency), refundedByCurrency: currencies(external?.refundedByCurrency), excluded: numericFields(external?.excluded, ['internal', 'test', 'unknown']) }, broadAccounting: { ...numericFields(summary.revenue, ['paidOrders', 'paidCustomers', 'amountKnownOrders', 'amountUnknownOrders']), bookedRevenueByCurrency: currencies(summary.revenue?.bookedRevenueByCurrency) } },
|
|
300
307
|
trafficMetrics: numericFields(summary.trafficMetrics, ['visitors', 'sessions', 'pageViews', 'ctaClicks', 'checkoutStarts', 'checkoutPaidConfirmations']),
|
|
301
308
|
attribution: { coverageRate: number(summary.dataQuality?.attributionCoverage) },
|
|
@@ -441,6 +448,17 @@ async function readTraffic(deps, signal) {
|
|
|
441
448
|
return value;
|
|
442
449
|
}
|
|
443
450
|
|
|
451
|
+
const cohortCache = new Map();
|
|
452
|
+
async function readCohorts(deps, signal) {
|
|
453
|
+
const ttl = deps.telemetryCacheMs ?? TELEMETRY_CACHE_MS;
|
|
454
|
+
const key = String(deps.feedbackDir);
|
|
455
|
+
const hit = cohortCache.get(key);
|
|
456
|
+
if (ttl > 0 && hit && Date.now() - hit.at < ttl) return hit.value;
|
|
457
|
+
const value = await ownerTelemetry.readInstallCohorts({ feedbackDir: guardPath(deps.feedbackDir, deps.feedbackDir), weeks: 8, signal, maxBytes: deps.telemetryMaxBytes });
|
|
458
|
+
if (ttl > 0) cohortCache.set(key, { at: Date.now(), value });
|
|
459
|
+
return value;
|
|
460
|
+
}
|
|
461
|
+
|
|
444
462
|
// 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
463
|
// (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
464
|
// running and kept its slot. Now each page waits for a slot until one shared deadline, a stopped list stops between pages,
|
|
@@ -480,12 +498,43 @@ async function listAll({ list, params, keep = () => true, maxPages = 40, signal,
|
|
|
480
498
|
}
|
|
481
499
|
}
|
|
482
500
|
|
|
501
|
+
// Monthly recurring revenue by currency from active subscriptions: each item's price times quantity, scaled to one month.
|
|
502
|
+
// Discounts and coupons are not applied, so this is list-price MRR. `cancelling` counts subscriptions set to end at period end.
|
|
503
|
+
const MONTHS_PER = { day: 12 / 365, week: 12 / 52, month: 1, year: 12 };
|
|
504
|
+
function monthlyRecurring(subscriptions) {
|
|
505
|
+
const mrr = {};
|
|
506
|
+
let cancelling = 0;
|
|
507
|
+
let unpriced = 0;
|
|
508
|
+
for (const row of subscriptions) {
|
|
509
|
+
if (row.cancel_at_period_end === true) cancelling += 1;
|
|
510
|
+
for (const item of row.items?.data || []) {
|
|
511
|
+
const price = item.price || {};
|
|
512
|
+
const every = MONTHS_PER[price.recurring?.interval];
|
|
513
|
+
const count = Number.isInteger(price.recurring?.interval_count) && price.recurring.interval_count > 0 ? price.recurring.interval_count : 1;
|
|
514
|
+
if (!every || !Number.isSafeInteger(price.unit_amount) || !/^[a-z]{3}$/i.test(price.currency || '')) { unpriced += 1; continue; }
|
|
515
|
+
const code = price.currency.toUpperCase();
|
|
516
|
+
const quantity = Number.isInteger(item.quantity) && item.quantity > 0 ? item.quantity : 1;
|
|
517
|
+
mrr[code] = (mrr[code] || 0) + (price.unit_amount * quantity) / (every * count);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
for (const code of Object.keys(mrr)) mrr[code] = Math.round(mrr[code]);
|
|
521
|
+
return { mrr, cancelling, unpriced };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// The acquisition channel a checkout carried in its metadata (utm source, else source), in one plain lower-case word.
|
|
525
|
+
function channelOf(row) {
|
|
526
|
+
const raw = String(row?.metadata?.utmSource || row?.metadata?.source || '').trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, '_').slice(0, 40);
|
|
527
|
+
return raw && raw !== 'unknown' ? raw : 'direct';
|
|
528
|
+
}
|
|
529
|
+
|
|
483
530
|
const thumbgateSession = (row) => /thumbgate/i.test(String(row.success_url || ''));
|
|
484
531
|
|
|
485
532
|
// Why a Stripe source failed, in words a person can act on. Never a bare "Unknown".
|
|
486
533
|
function stripeReason(error) {
|
|
487
534
|
if (/STRIPE_SECRET_KEY is missing/i.test(String(error?.message || ''))) return 'Stripe key missing';
|
|
488
|
-
|
|
535
|
+
// The request's own timeout is set to the time left before the shared deadline, so it can fire first: that is the
|
|
536
|
+
// same "no answer in time", not an outage.
|
|
537
|
+
if (error?.code === 'collection_timeout' || error?.code === 'ETIMEDOUT' || /timed? ?out/i.test(String(error?.message || ''))) return 'Stripe did not answer in time';
|
|
489
538
|
if (error?.code === 'provider_busy') return 'Stripe is busy, refresh in a moment';
|
|
490
539
|
return 'Stripe unavailable';
|
|
491
540
|
}
|
|
@@ -497,6 +546,53 @@ const telemetryReason = (error) => (error?.code === 'collection_timeout' ? 'tele
|
|
|
497
546
|
|
|
498
547
|
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
548
|
|
|
549
|
+
const attemptSync = (work) => { try { return work(); } catch { return { status: 'unavailable', reason: 'The key store could not be read.' }; } };
|
|
550
|
+
|
|
551
|
+
// Payment to access: every purchase that still grants access should have a ThumbGate key that works, and every working paid
|
|
552
|
+
// key should trace to a payment. Counts only; no customer id or address leaves this function.
|
|
553
|
+
// - `entitled` is who should hold access now: credit-pack buyers (one year) and active subscribers. Service orders and
|
|
554
|
+
// canceled subscriptions grant no key, so they are not expected to have one.
|
|
555
|
+
// - A key works the way billing.validateApiKey() decides: active, and not a credit pack with no credits left. A used-up
|
|
556
|
+
// credit pack was provisioned, so it is counted apart (`exhaustedCreditKeys`), never as a provisioning failure.
|
|
557
|
+
// - A working paid key with no Stripe match is listed for review, not called wrong: GitHub Marketplace, PayPal and manual
|
|
558
|
+
// grants also make keys.
|
|
559
|
+
const isTrialOrFree = (meta) => /free|trial/i.test(String(meta.plan || '') + ' ' + String(meta.tier || '') + ' ' + String(meta.source || ''));
|
|
560
|
+
const creditsExhausted = (meta) => meta.remainingCredits !== undefined && meta.remainingCredits !== null && meta.remainingCredits <= 0;
|
|
561
|
+
function paymentAccessCheck({ entitled, failing, store, complete = true }) {
|
|
562
|
+
const active = Object.values(store?.keys || {}).filter((meta) => meta && meta.active === true);
|
|
563
|
+
const working = active.filter((meta) => !creditsExhausted(meta));
|
|
564
|
+
const owners = (list) => {
|
|
565
|
+
const out = new Set();
|
|
566
|
+
for (const meta of list) {
|
|
567
|
+
if (meta.customerId) out.add(String(meta.customerId));
|
|
568
|
+
if (meta.customerEmail) out.add(String(meta.customerEmail).toLowerCase());
|
|
569
|
+
}
|
|
570
|
+
return out;
|
|
571
|
+
};
|
|
572
|
+
const provisioned = owners(active);
|
|
573
|
+
const withAccess = owners(working);
|
|
574
|
+
const has = (set, who) => set.has(String(who)) || set.has(String(who).toLowerCase());
|
|
575
|
+
const paidKeys = working.filter((meta) => !isTrialOrFree(meta));
|
|
576
|
+
const paidWithoutAccess = [...entitled].filter((who) => !has(provisioned, who)).length;
|
|
577
|
+
const accessWithoutStripePayment = paidKeys.filter((meta) => !entitled.has(String(meta.customerId || '')) && !entitled.has(String(meta.customerEmail || '').toLowerCase())).length;
|
|
578
|
+
const failingIds = Array.isArray(failing) ? failing.map((row) => row.customer).filter(Boolean) : null;
|
|
579
|
+
const failedPaymentWithAccess = failingIds ? failingIds.filter((who) => has(withAccess, who)).length : null;
|
|
580
|
+
const problems = paidWithoutAccess + (failedPaymentWithAccess || 0);
|
|
581
|
+
return {
|
|
582
|
+
status: problems ? 'needs_review' : accessWithoutStripePayment ? 'review' : 'ok',
|
|
583
|
+
complete: complete && failingIds !== null,
|
|
584
|
+
entitledCustomers: entitled.size,
|
|
585
|
+
activeKeys: working.length,
|
|
586
|
+
activePaidKeys: paidKeys.length,
|
|
587
|
+
activeTrialOrFreeKeys: working.length - paidKeys.length,
|
|
588
|
+
exhaustedCreditKeys: active.length - working.length,
|
|
589
|
+
paidWithoutAccess,
|
|
590
|
+
accessWithoutStripePayment,
|
|
591
|
+
failedPaymentSubscriptions: failingIds ? failingIds.length : null,
|
|
592
|
+
failedPaymentWithAccess,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
500
596
|
// Money board. Each block fails alone: its fields are null and a plain-words reason is returned beside them.
|
|
501
597
|
// Stripe answers paying customers, revenue and checkouts; our own page-view telemetry answers visitors.
|
|
502
598
|
async function collectMoney(deps, signal) {
|
|
@@ -534,20 +630,42 @@ async function collectMoney(deps, signal) {
|
|
|
534
630
|
const paidAndProLane = (async () => {
|
|
535
631
|
const paidResult = await withLastGood('paid', async () => {
|
|
536
632
|
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'] },
|
|
633
|
+
{ status: 'complete', created: { gte: nowSeconds - 365 * 86400 }, expand: ['data.payment_intent.latest_charge.balance_transaction'] },
|
|
538
634
|
(row) => row.status === 'complete' && thumbgateSession(row), 10);
|
|
539
635
|
// Paid and not refunded in full, owner and test purchases excluded. A partial refund comes off the revenue.
|
|
540
636
|
const charge = (row) => (object(row.payment_intent) && object(row.payment_intent.latest_charge) ? row.payment_intent.latest_charge : null);
|
|
541
637
|
const paid = result.rows.filter((row) => row.payment_status === 'paid' && classifySession(row, { ownerEmails }) !== 'internal' && charge(row)?.refunded !== true);
|
|
542
638
|
const customers = new Set(paid.map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
|
|
543
639
|
const revenue = {};
|
|
640
|
+
const channels = {};
|
|
641
|
+
const counted = new Set();
|
|
642
|
+
const channel = (name) => (channels[name] ||= { paidCustomers: 0, revenue30d: {} });
|
|
643
|
+
// Oldest first, so a customer is credited to the channel of their first paid checkout.
|
|
644
|
+
for (const row of [...paid].sort((a, b) => (a.created || 0) - (b.created || 0))) {
|
|
645
|
+
const who = id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase();
|
|
646
|
+
if (!counted.has(who)) { counted.add(who); channel(channelOf(row)).paidCustomers += 1; }
|
|
647
|
+
}
|
|
648
|
+
// Stripe's own fee on each 30-day checkout, read from the charge's balance transaction when Stripe returns it.
|
|
649
|
+
const fees = { reportedFees: {}, unreportedCharges: 0, unreportedAmount: {}, subscriptionFirstCharges: {} };
|
|
544
650
|
for (const row of paid) {
|
|
545
651
|
if (!(row.created >= nowSeconds - 30 * 86400) || !Number.isSafeInteger(row.amount_total) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
|
|
546
652
|
const code = row.currency.toUpperCase();
|
|
547
653
|
const refunded = Number.isSafeInteger(charge(row)?.amount_refunded) ? charge(row).amount_refunded : 0;
|
|
548
654
|
revenue[code] = (revenue[code] || 0) + row.amount_total - refunded;
|
|
655
|
+
const fee = charge(row)?.balance_transaction?.fee;
|
|
656
|
+
if (Number.isSafeInteger(fee)) {
|
|
657
|
+
const feeCode = String(charge(row).balance_transaction.currency || row.currency).toUpperCase();
|
|
658
|
+
fees.reportedFees[feeCode] = (fees.reportedFees[feeCode] || 0) + fee;
|
|
659
|
+
} else { fees.unreportedCharges += 1; fees.unreportedAmount[code] = (fees.unreportedAmount[code] || 0) + row.amount_total; }
|
|
660
|
+
if (row.mode === 'subscription') fees.subscriptionFirstCharges[code] = (fees.subscriptionFirstCharges[code] || 0) + row.amount_total;
|
|
661
|
+
const byChannel = channel(channelOf(row)).revenue30d;
|
|
662
|
+
byChannel[code] = (byChannel[code] || 0) + row.amount_total - refunded;
|
|
549
663
|
}
|
|
550
|
-
|
|
664
|
+
// Credit-pack buyers keep access for the pack's life; a subscription checkout's access is checked against active
|
|
665
|
+
// subscriptions instead, and a service order grants no key.
|
|
666
|
+
const grant = deps.resolveCheckoutProvisioningGrant || billing._resolveCheckoutProvisioningGrant;
|
|
667
|
+
const creditPackCustomers = new Set(paid.filter((row) => grant(row).kind === 'credit_pack').map((row) => id(row.customer) || String(row.customer_details?.email || row.customer_email || row.id).toLowerCase()));
|
|
668
|
+
return { customers, creditPackCustomers, revenue, channels, fees, complete: result.complete };
|
|
551
669
|
});
|
|
552
670
|
const proResult = await withLastGood('subscriptions', async () => {
|
|
553
671
|
const result = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'active', expand: ['data.customer'] }, () => true, 5);
|
|
@@ -556,13 +674,38 @@ async function collectMoney(deps, signal) {
|
|
|
556
674
|
return !(email && ownerEmails.some((owner) => email === String(owner).toLowerCase()));
|
|
557
675
|
});
|
|
558
676
|
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 };
|
|
677
|
+
return { count: external.length, customers, complete: result.complete, ...monthlyRecurring(external) };
|
|
560
678
|
});
|
|
561
679
|
return [paidResult, proResult];
|
|
562
680
|
})();
|
|
563
|
-
|
|
681
|
+
const isOwnerEmail = (email) => Boolean(email) && ownerEmails.some((owner) => String(email).toLowerCase() === String(owner).toLowerCase());
|
|
682
|
+
// Third lane: what subscriptions actually brought in and lost in 30 days. Renewal invoices are the recurring cash the
|
|
683
|
+
// checkout list never sees; cancelled subscriptions are churn.
|
|
684
|
+
const recurringLane = withLastGood('recurring', async () => {
|
|
685
|
+
const since30 = nowSeconds - 30 * 86400;
|
|
686
|
+
const invoices = await listIt((params, options) => stripe().invoices.list(params, options), { status: 'paid', created: { gte: since30 } },
|
|
687
|
+
(row) => row.billing_reason === 'subscription_cycle' && !isOwnerEmail(row.customer_email), 10);
|
|
688
|
+
const renewals = {};
|
|
689
|
+
for (const row of invoices.rows) {
|
|
690
|
+
if (!Number.isSafeInteger(row.amount_paid) || !/^[a-z]{3}$/i.test(row.currency || '')) continue;
|
|
691
|
+
const code = row.currency.toUpperCase();
|
|
692
|
+
renewals[code] = (renewals[code] || 0) + row.amount_paid;
|
|
693
|
+
}
|
|
694
|
+
const cancelled = await listIt((params, options) => stripe().subscriptions.list(params, options), { status: 'canceled', expand: ['data.customer'] },
|
|
695
|
+
(row) => Number(row.canceled_at || row.ended_at) >= since30 && !isOwnerEmail(row.customer?.email), 5);
|
|
696
|
+
// Failed payments: subscriptions Stripe could not charge. Their customer ids feed the payment-to-access check.
|
|
697
|
+
const failing = [];
|
|
698
|
+
let failingComplete = true;
|
|
699
|
+
for (const status of ['past_due', 'unpaid']) {
|
|
700
|
+
const listed = await listIt((params, options) => stripe().subscriptions.list(params, options), { status }, (row) => row.status === status, 2);
|
|
701
|
+
failingComplete &&= listed.complete;
|
|
702
|
+
for (const row of listed.rows) failing.push({ status, customer: id(row.customer) });
|
|
703
|
+
}
|
|
704
|
+
return { renewals, renewalCount: invoices.rows.length, churned: cancelled.rows.length, churnedMrr: monthlyRecurring(cancelled.rows).mrr, failing, complete: invoices.complete && cancelled.complete && failingComplete };
|
|
705
|
+
});
|
|
706
|
+
let paidAndPro; let sessionRun; let trafficRun; let summaryRun; let recurringRun;
|
|
564
707
|
try {
|
|
565
|
-
[paidAndPro, sessionRun, trafficRun, summaryRun] = await Promise.all([
|
|
708
|
+
[paidAndPro, sessionRun, trafficRun, summaryRun, recurringRun] = await Promise.all([
|
|
566
709
|
paidAndProLane,
|
|
567
710
|
withLastGood('checkouts', async () => {
|
|
568
711
|
const result = await listIt((params, options) => stripe().checkout.sessions.list(params, options), { created: { gte: nowSeconds - 30 * 86400 } }, thumbgateSession, 40);
|
|
@@ -571,7 +714,13 @@ async function collectMoney(deps, signal) {
|
|
|
571
714
|
const botCheckSeconds = Date.parse(botCheckBeganAt) / 1000;
|
|
572
715
|
const beforeBotCheck = (row) => Boolean(row.created) && row.created < botCheckSeconds;
|
|
573
716
|
const classified = result.rows.filter((row) => row.metadata?.uaClass && row.created).map((row) => row.created);
|
|
717
|
+
const startsByChannel = {};
|
|
718
|
+
for (const row of result.rows) {
|
|
719
|
+
if (['bot', 'internal'].includes(classifySession(row, { ownerEmails }))) continue;
|
|
720
|
+
startsByChannel[channelOf(row)] = (startsByChannel[channelOf(row)] || 0) + 1;
|
|
721
|
+
}
|
|
574
722
|
return {
|
|
723
|
+
startsByChannel,
|
|
575
724
|
d30: countSessions(result.rows, { ownerEmails }),
|
|
576
725
|
d7: countSessions(result.rows.filter((row) => !row.created || row.created >= since7), { ownerEmails }),
|
|
577
726
|
before: countSessions(result.rows.filter(beforeBotCheck), { ownerEmails }),
|
|
@@ -582,6 +731,7 @@ async function collectMoney(deps, signal) {
|
|
|
582
731
|
}),
|
|
583
732
|
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
584
733
|
attempt(() => readSummary(deps, signal), () => 'lead ledgers failed'),
|
|
734
|
+
recurringLane,
|
|
585
735
|
]);
|
|
586
736
|
} finally {
|
|
587
737
|
clearTimeout(sharedTimer);
|
|
@@ -606,6 +756,12 @@ async function collectMoney(deps, signal) {
|
|
|
606
756
|
internal: counts.excluded.internal,
|
|
607
757
|
} : null);
|
|
608
758
|
const bothStripe = paid && proRun.value;
|
|
759
|
+
const access = bothStripe ? attemptSync(() => paymentAccessCheck({
|
|
760
|
+
entitled: new Set([...(paid.creditPackCustomers || []), ...proRun.value.customers]),
|
|
761
|
+
failing: recurringRun.ok ? recurringRun.value.failing : null,
|
|
762
|
+
store: (deps.loadKeyStore || billing.loadKeyStore)(),
|
|
763
|
+
complete: paid.complete && proRun.value.complete,
|
|
764
|
+
})) : null;
|
|
609
765
|
// The checkout panel: sessions with no bot check on record come first, then people, bots and owner only for sessions
|
|
610
766
|
// created after the bot check began, then the gap between the site's own start events and Stripe's sessions.
|
|
611
767
|
const checkoutBotCheck = (counts, traffic) => {
|
|
@@ -638,6 +794,7 @@ async function collectMoney(deps, signal) {
|
|
|
638
794
|
paid: blockTime('paid'),
|
|
639
795
|
subscriptions: blockTime('subscriptions'),
|
|
640
796
|
checkouts: blockTime('checkouts'),
|
|
797
|
+
recurring: blockTime('recurring'),
|
|
641
798
|
traffic: { collectedAt: trafficRead?.collectedAt || null, stale: false },
|
|
642
799
|
leads: { collectedAt: summaryRun.value?.collectedAt || null, stale: summaryRun.value?.state === 'stale' },
|
|
643
800
|
displayRefreshedAt: new Date().toISOString(),
|
|
@@ -652,8 +809,31 @@ async function collectMoney(deps, signal) {
|
|
|
652
809
|
payingCustomersSource: 'stripe',
|
|
653
810
|
payingCustomersBasis: bothStripe ? (paid.complete && proRun.value.complete ? 'stripe_paid_and_active' : 'stripe_paid_and_active_partial') : 'unavailable',
|
|
654
811
|
activePro: proRun.value ? proRun.value.count : null,
|
|
812
|
+
mrr: proRun.value ? proRun.value.mrr : null,
|
|
813
|
+
mrrBasis: proRun.value ? (proRun.value.complete && !proRun.value.unpriced ? 'stripe_active_subscription_list_prices' : 'stripe_active_subscription_list_prices_partial') : 'unavailable',
|
|
814
|
+
cancellingAtPeriodEnd: proRun.value ? proRun.value.cancelling : null,
|
|
815
|
+
// Churn: subscriptions cancelled in 30 days against those plus the ones still active.
|
|
816
|
+
recurring30d: recurringRun.ok ? {
|
|
817
|
+
renewalRevenue: recurringRun.value.renewals,
|
|
818
|
+
renewalInvoices: recurringRun.value.renewalCount,
|
|
819
|
+
churnedSubscriptions: recurringRun.value.churned,
|
|
820
|
+
churnedMrr: recurringRun.value.churnedMrr,
|
|
821
|
+
failedPaymentSubscriptions: recurringRun.value.failing.length,
|
|
822
|
+
churnRate: proRun.value && proRun.value.count + recurringRun.value.churned > 0 ? Math.round((recurringRun.value.churned / (proRun.value.count + recurringRun.value.churned)) * 1000) / 1000 : null,
|
|
823
|
+
complete: recurringRun.value.complete,
|
|
824
|
+
} : null,
|
|
825
|
+
// One row per channel: checkout sessions started in 30 days (bots and owner left out), paying customers credited to
|
|
826
|
+
// the channel of their first paid checkout in the past year, and 30-day checkout revenue.
|
|
827
|
+
channels: paid || sessions ? Object.entries([...new Set([...Object.keys(paid?.channels || {}), ...Object.keys(sessions?.startsByChannel || {})])].reduce((out, name) => {
|
|
828
|
+
out[name] = { checkoutStarts30d: sessions ? sessions.startsByChannel[name] || 0 : null, paidCustomers: paid ? paid.channels[name]?.paidCustomers || 0 : null, revenue30d: paid ? paid.channels[name]?.revenue30d || {} : null };
|
|
829
|
+
return out;
|
|
830
|
+
}, {})).map(([channel, row]) => ({ channel, ...row })).sort((a, b) => (b.paidCustomers || 0) - (a.paidCustomers || 0) || (b.checkoutStarts30d || 0) - (a.checkoutStarts30d || 0)).slice(0, 25) : null,
|
|
831
|
+
usage30d: trafficReason ? null : (trafficRead.usage || null),
|
|
832
|
+
weekOverWeek: trafficReason ? null : (trafficRead.weeks || null),
|
|
655
833
|
activeProBasis: proRun.value ? (proRun.value.complete ? 'stripe_active_subscriptions_excluding_owner' : 'stripe_active_subscriptions_first_100_only') : 'unavailable',
|
|
656
834
|
revenueLast30Days: paid ? paid.revenue : null,
|
|
835
|
+
paymentFees30d: paid ? paid.fees : null,
|
|
836
|
+
paymentAccess: access,
|
|
657
837
|
revenueBasis: 'stripe_paid_checkouts_after_refunds',
|
|
658
838
|
checkouts7d: sessionBuckets(sessions?.d7),
|
|
659
839
|
checkouts30d: sessionBuckets(sessions?.d30),
|
|
@@ -663,6 +843,8 @@ async function collectMoney(deps, signal) {
|
|
|
663
843
|
reasons: {
|
|
664
844
|
payingCustomers: bothStripe ? null : (paidRun.reason || proRun.reason),
|
|
665
845
|
activePro: proRun.value ? null : proRun.reason,
|
|
846
|
+
mrr: proRun.value ? null : proRun.reason,
|
|
847
|
+
recurring: recurringRun.ok ? null : recurringRun.reason,
|
|
666
848
|
revenue: paid ? null : paidRun.reason,
|
|
667
849
|
checkouts: sessions ? null : sessionRun.reason,
|
|
668
850
|
visitors: trafficReason,
|
|
@@ -670,7 +852,7 @@ async function collectMoney(deps, signal) {
|
|
|
670
852
|
},
|
|
671
853
|
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
854
|
};
|
|
673
|
-
const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts' };
|
|
855
|
+
const staleLabel = { paid: 'paying customers and revenue', subscriptions: 'active subscriptions', checkouts: 'checkout counts', recurring: 'renewals and churn' };
|
|
674
856
|
for (const [key, at] of Object.entries(staleBlocks)) {
|
|
675
857
|
const minutes = Math.max(1, Math.round((Date.now() - at) / 60000));
|
|
676
858
|
data.notes.push(`Showing the last good ${staleLabel[key]} from ${minutes} minute${minutes === 1 ? '' : 's'} ago, because Stripe did not answer this time.`);
|
|
@@ -682,6 +864,7 @@ async function collectMoney(deps, signal) {
|
|
|
682
864
|
if (!paidRun.ok) warnings.push('paid_checkout_list_unavailable');
|
|
683
865
|
if (!sessionRun.ok) warnings.push('checkout_list_unavailable');
|
|
684
866
|
if (!proRun.ok) warnings.push('subscription_list_unavailable');
|
|
867
|
+
if (!recurringRun.ok) warnings.push('renewal_and_churn_unavailable');
|
|
685
868
|
if (trafficReason) warnings.push('telemetry_unavailable');
|
|
686
869
|
if (leadsReason) warnings.push('leads_unavailable');
|
|
687
870
|
const failed = [paidRun, sessionRun, proRun].filter((run) => !run.ok).length;
|
|
@@ -693,9 +876,10 @@ async function collectMoney(deps, signal) {
|
|
|
693
876
|
// Analytics: 30 days of traffic streamed from the telemetry tail (never refused for size), a daily series, and the
|
|
694
877
|
// billing totals from the cached child-process summary when it is ready.
|
|
695
878
|
async function collectAnalytics(deps, signal) {
|
|
696
|
-
const [trafficRun, summaryRun] = await Promise.all([
|
|
879
|
+
const [trafficRun, summaryRun, cohortRun] = await Promise.all([
|
|
697
880
|
attempt(() => readTraffic(deps, signal), telemetryReason),
|
|
698
881
|
attempt(() => readSummary(deps, signal), () => 'billing totals failed'),
|
|
882
|
+
attempt(() => readCohorts(deps, signal), telemetryReason),
|
|
699
883
|
]);
|
|
700
884
|
const parts = summaryRun.value?.value || null;
|
|
701
885
|
const trafficRead = trafficRun.value;
|
|
@@ -704,6 +888,9 @@ async function collectAnalytics(deps, signal) {
|
|
|
704
888
|
const hasTraffic = trafficRun.ok && !trafficRead.empty;
|
|
705
889
|
data.trafficMetrics = hasTraffic ? trafficFields(trafficRead) : (data.trafficMetrics || null);
|
|
706
890
|
data.daily = hasTraffic ? trafficRead.daily : [];
|
|
891
|
+
data.usage = hasTraffic ? (trafficRead.usage || null) : null;
|
|
892
|
+
data.weekOverWeek = hasTraffic ? (trafficRead.weeks || null) : null;
|
|
893
|
+
data.cohorts = cohortRun.ok ? cohortRun.value : null;
|
|
707
894
|
data.dataQuality = { ...(data.dataQuality || {}), telemetryWindowComplete: hasTraffic ? !trafficRead.partial : false, telemetryBytesRead: trafficRead ? trafficRead.bytesRead : 0, telemetrySizeBytes: trafficRead ? trafficRead.size : 0 };
|
|
708
895
|
const warnings = [];
|
|
709
896
|
if (data.reconciliation && (data.reconciliation.status !== 'ok' || !data.reconciliation.complete)) warnings.push('stripe_reconciliation_' + data.reconciliation.status);
|
|
@@ -713,6 +900,24 @@ async function collectAnalytics(deps, signal) {
|
|
|
713
900
|
return envelope('telemetry_tail_and_billing_summary_30d', data, warnings);
|
|
714
901
|
}
|
|
715
902
|
|
|
903
|
+
// Unit economics: delivery cost per active install and per paying customer, contribution per plan, payment-to-access.
|
|
904
|
+
function economicsFrom(money, deps) {
|
|
905
|
+
const meter = (deps.readCostMeter || ((options) => costMeter.readWindow(options)))({ feedbackDir: deps.feedbackDir, days: 30 });
|
|
906
|
+
return unitEconomics.computeUnitEconomics({ money, usage: money?.usage30d || null, meter, costs: deps.unitCosts || unitEconomics.loadUnitCosts() });
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function collectEconomics(deps, signal) {
|
|
910
|
+
const moneyRun = await attempt(() => collectMoney(deps, signal), () => 'Money collection failed');
|
|
911
|
+
const money = moneyRun.ok ? moneyRun.value.data : null;
|
|
912
|
+
const data = economicsFrom(money, deps);
|
|
913
|
+
data.paymentAccess = money?.paymentAccess || null;
|
|
914
|
+
data.firstValue = money?.usage30d ? { activeInstalls30d: money.usage30d.activeInstalls30d, initsInWindow: money.usage30d.initsInWindow, firstValueInstalls: money.usage30d.firstValueInstalls ?? null, timeToFirstValue: money.usage30d.timeToFirstValue || null } : null;
|
|
915
|
+
const warnings = [];
|
|
916
|
+
if (!money) warnings.push('money_unavailable');
|
|
917
|
+
if (data.status !== 'ok') warnings.push('costs_partial');
|
|
918
|
+
return envelope('unit_economics_30d', data, warnings);
|
|
919
|
+
}
|
|
920
|
+
|
|
716
921
|
// One metric of the read-only summary: its value, where it came from, when that source was read, and one of these states:
|
|
717
922
|
// ok a number from a source that answered in full
|
|
718
923
|
// verified_zero a zero from a source that answered in full
|
|
@@ -757,8 +962,15 @@ async function collectSummary(deps, signal) {
|
|
|
757
962
|
add('money.paying_customers', 'Paying customers', money.payingCustomers, { ...stripeOpts('paid', why.payingCustomers), partial: money.payingCustomersBasis === 'stripe_paid_and_active_partial' });
|
|
758
963
|
add('money.active_pro', 'Active Pro subscriptions', money.activePro, { ...stripeOpts('subscriptions', why.activePro), partial: money.activeProBasis === 'stripe_active_subscriptions_first_100_only' });
|
|
759
964
|
// collectMoney reads completed Checkout Sessions only, so this is first-charge revenue; renewal invoices never appear in it.
|
|
965
|
+
add('money.mrr', 'Monthly recurring revenue at list price, by currency (active Stripe subscriptions)', money.mrr, { ...stripeOpts('subscriptions', why.mrr), partial: money.mrrBasis === 'stripe_active_subscription_list_prices_partial' });
|
|
966
|
+
add('money.cancelling_at_period_end', 'Active subscriptions set to cancel at period end', money.cancellingAtPeriodEnd, stripeOpts('subscriptions', why.mrr));
|
|
760
967
|
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
|
-
|
|
968
|
+
const recurring = money.recurring30d;
|
|
969
|
+
const recurringOpts = { ...stripeOpts('recurring', why.recurring), partial: recurring ? recurring.complete === false : false };
|
|
970
|
+
add('money.subscription_invoices_30d', 'Subscription renewal revenue, past 30 days, by currency (paid renewal invoices)', recurring ? recurring.renewalRevenue : null, recurringOpts);
|
|
971
|
+
add('money.churned_subscriptions_30d', 'Subscriptions cancelled in the past 30 days', recurring ? recurring.churnedSubscriptions : null, recurringOpts);
|
|
972
|
+
const noSubscriptions = recurring && recurring.churnRate === null;
|
|
973
|
+
add('money.churn_rate_30d', 'Subscription churn, past 30 days (cancelled ÷ cancelled plus active)', recurring ? recurring.churnRate : null, noSubscriptions ? { ...recurringOpts, unresolved: true, reason: 'No active or cancelled subscriptions, so there is no rate' } : recurringOpts);
|
|
762
974
|
buckets('money.checkouts_7d', '7 days', money.checkouts7d);
|
|
763
975
|
buckets('money.checkouts_30d', '30 days', money.checkouts30d);
|
|
764
976
|
const panel = money.checkoutBotCheck;
|
|
@@ -766,6 +978,14 @@ async function collectSummary(deps, signal) {
|
|
|
766
978
|
add('money.signups_by_source', 'Signups by source', money.leadsBySource?.signups ?? null, leadOpts);
|
|
767
979
|
add('money.workflow_sprint_leads', 'Setup Sprint leads', money.leadsBySource?.workflowSprint ?? null, leadOpts);
|
|
768
980
|
add('money.newsletter', 'Newsletter signups', money.leadsBySource?.newsletter ?? null, leadOpts);
|
|
981
|
+
add('money.payment_access', 'Payment to access check: entitled customers (active subscription or credit pack) without a key, working paid keys without a Stripe payment, failed payments still holding a working key', money.paymentAccess || null, stripeOpts('paid', why.payingCustomers));
|
|
982
|
+
const econ = economicsFrom(money, deps);
|
|
983
|
+
const econOpts = { source: 'cost_meter_and_stripe', collectedAt: refreshed, partial: econ.status !== 'ok', reason: econ.reasons?.hosting || null };
|
|
984
|
+
add('economics.delivery_cost_30d_usd', 'Cost to deliver the service, past 30 days, US dollars (hosting, email, payment fees, fixed)', econ.delivery?.totalUsd ?? null, econOpts);
|
|
985
|
+
add('economics.cost_per_active_install_usd', 'Hosting, email and fixed cost per active CLI install, past 30 days, US dollars', econ.perActiveInstallUsd ?? null, { ...econOpts, reason: econ.reasons?.activeInstalls || econOpts.reason });
|
|
986
|
+
add('economics.cost_per_paying_customer_usd', 'Delivery cost per paying customer, past 30 days, US dollars', econ.perPayingCustomerUsd ?? null, { ...econOpts, reason: econ.reasons?.payingCustomers || econOpts.reason });
|
|
987
|
+
add('economics.contribution_30d', 'Revenue minus delivery cost, past 30 days, US dollars', econ.contribution || null, econOpts);
|
|
988
|
+
add('economics.plans', 'Contribution per sale for each plan, US dollars', econ.plans || null, econOpts);
|
|
769
989
|
}
|
|
770
990
|
const traffic = analytics?.trafficMetrics || money?.traffic30d || null;
|
|
771
991
|
const trafficField = (key, label, name) => add(key, label, traffic ? traffic[name] ?? null : null, trafficOpts);
|
|
@@ -775,20 +995,120 @@ async function collectSummary(deps, signal) {
|
|
|
775
995
|
trafficField('traffic.cta_clicks_30d', 'Call to action clicks (30 days)', 'ctaClicks');
|
|
776
996
|
trafficField('traffic.checkout_starts_30d', 'Checkout starts seen on the site (30 days)', 'checkoutStarts');
|
|
777
997
|
trafficField('traffic.paid_confirmations_30d', 'Paid confirmations (30 days)', 'checkoutPaidConfirmations');
|
|
998
|
+
const usage = analytics?.usage || money?.usage30d || null;
|
|
999
|
+
const usageField = (key, label, name) => add(key, label, usage ? usage[name] ?? null : null, trafficOpts);
|
|
1000
|
+
usageField('usage.active_installs_7d', 'CLI installs active in the past 7 days (owner and CI excluded)', 'activeInstalls7d');
|
|
1001
|
+
usageField('usage.active_installs_30d', 'CLI installs active in the past 30 days (owner and CI excluded)', 'activeInstalls30d');
|
|
1002
|
+
usageField('usage.activated_installs_30d', 'Active installs that captured feedback (30 days)', 'activatedInstalls');
|
|
1003
|
+
usageField('usage.returning_installs_30d', 'Active installs seen on 2 or more days (30 days)', 'returningInstalls');
|
|
1004
|
+
usageField('usage.first_value_installs_30d', 'Installs whose first real gate block arrived in the past 30 days', 'firstValueInstalls');
|
|
1005
|
+
usageField('usage.time_to_first_value', 'Minutes from install to first real gate block (median and 75th percentile)', 'timeToFirstValue');
|
|
1006
|
+
add('usage.install_cohorts_8w', 'Weekly CLI install cohorts and how many came back each later week (8 weeks)', analytics?.cohorts?.cohorts ?? null, { ...trafficOpts, partial: analytics?.cohorts?.partial === true });
|
|
1007
|
+
if (money) add('money.channels', 'Checkout starts (30 days), paying customers (first paid checkout, 1 year) and revenue (30 days) by channel', money.channels, stripeOpts('paid', why.revenue));
|
|
1008
|
+
add('traffic.week_over_week', 'Past 7 days against the 7 days before', analytics?.weekOverWeek || money?.weekOverWeek || null, trafficOpts);
|
|
778
1009
|
add('traffic.daily_30d', 'Daily traffic, past 30 days', analytics ? analytics.daily : null, trafficOpts);
|
|
779
1010
|
const billingOpts = { source: 'billing_summary', collectedAt: fresh.leads?.collectedAt || null, reason: analyticsRun.ok ? null : analyticsRun.reason, unresolved: !analytics?.signups };
|
|
780
1011
|
add('analytics.email_signups', 'Email signups', analytics?.signups?.emailSignups ?? null, billingOpts);
|
|
781
|
-
|
|
782
|
-
|
|
1012
|
+
// Ledger totals remain useful evidence when the provider reconciliation is
|
|
1013
|
+
// incomplete, but a zero must not be promoted to a verified provider zero.
|
|
1014
|
+
const reconciliationComplete = analytics?.reconciliation?.status === 'ok' && analytics.reconciliation.complete === true;
|
|
1015
|
+
const revenueOpts = { ...billingOpts, partial: Boolean(analytics) && !reconciliationComplete,
|
|
1016
|
+
reason: reconciliationComplete || !analytics ? billingOpts.reason : 'Provider reconciliation is incomplete (' + (analytics?.reconciliation?.status || 'not reported') + '); these are partial ledger totals, not a verified payment outcome' };
|
|
1017
|
+
add('analytics.external_paid_orders', 'External paid orders', analytics?.revenue?.external?.paidOrders ?? null, revenueOpts);
|
|
1018
|
+
add('analytics.external_booked_revenue_30d', 'External booked revenue, past 30 days, by currency', analytics?.revenue?.external?.bookedRevenueByCurrency ?? null, revenueOpts);
|
|
783
1019
|
|
|
784
1020
|
// A permanent, stated gap is listed apart so the overall state reflects sources that failed, not a feature not built yet.
|
|
785
|
-
const knownGaps = [
|
|
786
|
-
|
|
1021
|
+
const knownGaps = [];
|
|
1022
|
+
// Unit economics are estimates at list rates and start empty until the cost meter has samples, so they never decide the
|
|
1023
|
+
// summary's overall state; each one carries its own status.
|
|
1024
|
+
const states = Object.entries(fields).filter(([key]) => !knownGaps.includes(key) && !key.startsWith('economics.')).map(([, entry]) => entry.status);
|
|
787
1025
|
const bad = states.filter((state) => state === 'unavailable').length;
|
|
788
1026
|
const overall = !money && !analytics ? 'unavailable' : states.every((state) => state === 'ok' || state === 'verified_zero') ? 'ok' : 'partial';
|
|
789
1027
|
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
1028
|
}
|
|
791
1029
|
|
|
1030
|
+
// GET /v1/admin/alerts: what needs the owner now, from the Money board and the Health report.
|
|
1031
|
+
async function collectAlerts(deps, signal) {
|
|
1032
|
+
const [moneyRun, healthRun] = await Promise.all([
|
|
1033
|
+
attempt(() => collectMoney(deps, signal), () => 'money unavailable'),
|
|
1034
|
+
attempt(() => collectObservability(deps, signal), () => 'health unavailable'),
|
|
1035
|
+
]);
|
|
1036
|
+
const money = moneyRun.ok ? moneyRun.value.data : null;
|
|
1037
|
+
const report = healthRun.ok ? healthRun.value.data?.report || null : null;
|
|
1038
|
+
const alerts = ownerAlerts.evaluateAlerts({ money, report });
|
|
1039
|
+
if (!money) alerts.push({ id: 'money_unchecked', level: 'amber', text: 'The money checks could not run this time.', action: 'Refresh in a minute.', tab: 'money' });
|
|
1040
|
+
if (!report) alerts.push({ id: 'health_unchecked', level: 'amber', text: 'The health checks could not run this time.', action: 'Refresh in a minute.', tab: 'observability' });
|
|
1041
|
+
const delivery = alertChannels().length ? alertChannels().join('_and_') + '_on_new_alert' : 'off';
|
|
1042
|
+
return envelope('owner_alerts', { alerts, checked: { money: Boolean(money), health: Boolean(report) }, delivery }, [], money && report ? 'ok' : 'partial');
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// Where new alerts go: the owner's own incoming webhook (Slack, Discord or Teams) and/or an email to the owner addresses
|
|
1046
|
+
// through the app's existing mail provider. Both are off unless their variable is set.
|
|
1047
|
+
function alertChannels() {
|
|
1048
|
+
const out = [];
|
|
1049
|
+
if (/^https:\/\//.test(String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim())) out.push('webhook');
|
|
1050
|
+
if (String(process.env.THUMBGATE_OWNER_ALERT_EMAIL || '').trim().toLowerCase() === 'on') out.push('email');
|
|
1051
|
+
return out;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// One-shot webhook post for owner alerts. Kept local because scripts/webhook-delivery.js is a dev-only file the npm package must not ship.
|
|
1055
|
+
function postOwnerWebhook(platform, webhookUrl, title, message) {
|
|
1056
|
+
const payload = platform === 'teams' ? { '@type': 'MessageCard', '@context': 'http://schema.org/extensions', summary: title, themeColor: '0076D7', title, text: message }
|
|
1057
|
+
: platform === 'discord' ? { embeds: [{ title, description: String(message).substring(0, 4096), color: 0x0076D7 }] }
|
|
1058
|
+
: { text: `*${title}*\n${message}` };
|
|
1059
|
+
const target = new URL(webhookUrl);
|
|
1060
|
+
const body = JSON.stringify(payload);
|
|
1061
|
+
return new Promise((resolve, reject) => {
|
|
1062
|
+
const req = (target.protocol === 'https:' ? require('https') : require('http')).request(target, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, (res) => {
|
|
1063
|
+
res.resume();
|
|
1064
|
+
res.on('end', () => (res.statusCode >= 200 && res.statusCode < 300 ? resolve(res.statusCode) : reject(new Error(`Webhook HTTP ${res.statusCode}`))));
|
|
1065
|
+
});
|
|
1066
|
+
req.on('error', reject);
|
|
1067
|
+
req.on('timeout', () => req.destroy(new Error('Webhook timeout')));
|
|
1068
|
+
req.end(body);
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// Checks the alerts every 15 minutes and sends the new ones to the channels above. Does nothing when none is set.
|
|
1073
|
+
function startAlertDelivery(makeDeps, { intervalMs = 15 * 60 * 1000, firstCheckMs = 60000, send } = {}) {
|
|
1074
|
+
const channels = alertChannels();
|
|
1075
|
+
if (!channels.length && !send) return null;
|
|
1076
|
+
const url = String(process.env.THUMBGATE_OWNER_ALERT_WEBHOOK || '').trim();
|
|
1077
|
+
const platform = /discord/i.test(url) ? 'discord' : /office|teams|logic\.azure/i.test(url) ? 'teams' : 'slack';
|
|
1078
|
+
const deliver = send || (async ({ title, message }) => {
|
|
1079
|
+
if (channels.includes('webhook')) await postOwnerWebhook(platform, url, title, message).catch(() => null);
|
|
1080
|
+
if (channels.includes('email')) {
|
|
1081
|
+
const to = require('./bot-detection').getOwnerEmails();
|
|
1082
|
+
const sent = to.length ? await require('./mailer/resend-mailer').sendEmail({ to: String(to[0]), subject: title, text: message }).catch(() => null) : null;
|
|
1083
|
+
console.log('[owner-alerts] email ' + (sent && sent.sent !== false ? 'sent' : 'not sent (' + (sent?.reason || (to.length ? 'error' : 'no_owner_address')) + ')'));
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
console.log('[owner-alerts] delivery on: ' + (channels.join(', ') || 'custom'));
|
|
1087
|
+
// State lives on the volume (owner-alert-delivery.json), so a deploy or restart never re-sends an alert that is
|
|
1088
|
+
// still firing. The first check ever also sends one confirmation, so the channel is proven before a real alert needs it.
|
|
1089
|
+
const readState = (deps) => { const read = readObject(deps.feedbackDir, 'owner-alert-delivery.json'); return read.state === 'ok' ? read.value : null; };
|
|
1090
|
+
const writeState = (deps, state) => fs.writeFileSync(path.join(deps.feedbackDir, 'owner-alert-delivery.json'), JSON.stringify(state));
|
|
1091
|
+
const run = async () => {
|
|
1092
|
+
try {
|
|
1093
|
+
const deps = makeDeps();
|
|
1094
|
+
const result = await collectAlerts(deps, AbortSignal.timeout(30000));
|
|
1095
|
+
const firing = result.data.alerts.filter((alert) => alert.level !== 'info');
|
|
1096
|
+
const state = readState(deps);
|
|
1097
|
+
const before = new Set(Array.isArray(state?.firing) ? state.firing : []);
|
|
1098
|
+
const added = firing.filter((alert) => !before.has(alert.id));
|
|
1099
|
+
writeState(deps, { confirmedAt: state?.confirmedAt || new Date().toISOString(), channels, firing: firing.map((alert) => alert.id), checkedAt: new Date().toISOString() });
|
|
1100
|
+
if (!state?.confirmedAt) await deliver({ title: 'ThumbGate: alert delivery is on', message: 'This is the one-time test that owner alerts reach you. New alerts from thumbgate.ai/admin will arrive here, each once, checked every 15 minutes. Firing right now: ' + firing.length + '.\nhttps://thumbgate.ai/admin' });
|
|
1101
|
+
console.log('[owner-alerts] checked: ' + firing.length + ' firing, ' + added.length + ' new');
|
|
1102
|
+
if (!added.length) return;
|
|
1103
|
+
await deliver(ownerAlerts.formatAlertMessage(added));
|
|
1104
|
+
} catch { /* an alert check never takes the server down */ }
|
|
1105
|
+
};
|
|
1106
|
+
const timer = setInterval(run, intervalMs);
|
|
1107
|
+
timer.unref?.();
|
|
1108
|
+
setTimeout(run, firstCheckMs).unref?.();
|
|
1109
|
+
return timer;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
792
1112
|
async function collectAdminSection(route, deps, externalSignal) {
|
|
793
1113
|
if (activeCollections >= 2) throw failure('collection_busy');
|
|
794
1114
|
activeCollections += 1;
|
|
@@ -803,6 +1123,8 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
803
1123
|
if (route.section === 'overview') return envelope('current_process', { health: deps.health(), sections: ['stripe', 'data', 'analytics', 'observability'] });
|
|
804
1124
|
if (route.section === 'money') return collectMoney(deps, controller.signal);
|
|
805
1125
|
if (route.section === 'summary') return collectSummary(deps, controller.signal);
|
|
1126
|
+
if (route.section === 'alerts') return collectAlerts(deps, controller.signal);
|
|
1127
|
+
if (route.section === 'economics') return collectEconomics(deps, controller.signal);
|
|
806
1128
|
if (route.section === 'stripe') return collectStripe(route, deps, controller.signal);
|
|
807
1129
|
if (route.section === 'data') return collectData(route, deps, controller.signal);
|
|
808
1130
|
if (route.section === 'observability') return collectObservability(deps, controller.signal);
|
|
@@ -816,4 +1138,4 @@ async function collectAdminSection(route, deps, externalSignal) {
|
|
|
816
1138
|
}
|
|
817
1139
|
}
|
|
818
1140
|
|
|
819
|
-
module.exports = { PRIVATE_HEADERS, RESPONSE_LIMIT, adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|
|
1141
|
+
module.exports = { paymentAccessCheck, PRIVATE_HEADERS, RESPONSE_LIMIT, monthlyRecurring, collectAlerts, startAlertDelivery,adminPath, parseAdminRoute, readOwnerIdentity, readSessionState, collectMoney, collectAnalytics, collectSummary, summaryParts, collectAdminSection, createRuntimeObservations, githubCommitTitle, collectObservability, projectAnalytics, projectStripe, readObject, countRecords, guardPath };
|