164 lines
6.0 KiB
JavaScript
164 lines
6.0 KiB
JavaScript
"use strict";
|
|
|
|
/**
|
|
* Turns normalized payment-event rows into a recovery-rate report.
|
|
*
|
|
* A raw CSV export from Stripe, Dodo Payments or Paddle lists one row per
|
|
* *attempt*, so a single customer retried four times by automatic dunning
|
|
* shows up as four rows for one real failure. Counting raw rows inflates
|
|
* both the failure count and (if you are not careful) the recovery rate.
|
|
* This groups rows by customer first, so the rate is calculated over real
|
|
* failure events, not retry noise.
|
|
*/
|
|
|
|
/**
|
|
* Published, vendor-sourced recovery-rate bands used only for comparison —
|
|
* never asserted as this report's own claim. See README "Sources".
|
|
*/
|
|
const BENCHMARK_BANDS = [
|
|
{ max: 30, label: "below the no-recovery-program baseline (~20-31%)" },
|
|
{ max: 45, label: "roughly in line with Stripe/processor-default recovery (~35-40%)" },
|
|
{ max: 60, label: "roughly in line with the reported SaaS median (~47-55%) with a dunning program" },
|
|
{ max: 100, label: "in the reported top-quartile range (70%+) for dedicated recovery programs" },
|
|
];
|
|
|
|
/**
|
|
* @param {ReturnType<import("./normalize").normalizeRecords>} events
|
|
*/
|
|
function buildReport(events) {
|
|
const hasCustomerIds = events.some((e) => e.customer !== "");
|
|
const groups = groupByCustomer(events, hasCustomerIds);
|
|
const unrecognizedStatusCount = events.filter((e) => e.status === "unknown").length;
|
|
|
|
let recoveredEvents = 0;
|
|
let unrecoveredEvents = 0;
|
|
let recoveredAmount = 0;
|
|
let unrecoveredAmount = 0;
|
|
const currencyCounts = {};
|
|
|
|
for (const group of groups) {
|
|
const hasFailed = group.some((e) => e.status === "failed");
|
|
if (!hasFailed) continue; // a customer who only ever succeeded never had a failure to recover
|
|
|
|
const hasRecovered = group.some((e) => e.status === "recovered");
|
|
const representative = group.find((e) => e.status === "failed") || group[0];
|
|
const amount = representative ? representative.amount : 0;
|
|
|
|
if (representative && representative.currency) {
|
|
currencyCounts[representative.currency] = (currencyCounts[representative.currency] || 0) + 1;
|
|
}
|
|
|
|
if (hasRecovered) {
|
|
recoveredEvents += 1;
|
|
recoveredAmount += amount;
|
|
} else {
|
|
unrecoveredEvents += 1;
|
|
unrecoveredAmount += amount;
|
|
}
|
|
}
|
|
|
|
const totalFailureEvents = recoveredEvents + unrecoveredEvents;
|
|
const recoveryRatePct = totalFailureEvents > 0 ? (recoveredEvents / totalFailureEvents) * 100 : null;
|
|
const totalAtRisk = recoveredAmount + unrecoveredAmount;
|
|
const currency = topCurrency(currencyCounts);
|
|
|
|
return {
|
|
rawRowCount: events.length,
|
|
dedupedCustomerCount: hasCustomerIds ? groups.length : null,
|
|
deduped: hasCustomerIds,
|
|
totalFailureEvents,
|
|
recoveredEvents,
|
|
unrecoveredEvents,
|
|
unrecognizedStatusCount,
|
|
recoveryRatePct,
|
|
recoveredAmount,
|
|
unrecoveredAmount,
|
|
totalAtRisk,
|
|
currency,
|
|
benchmark: recoveryRatePct === null ? null : benchmarkFor(recoveryRatePct),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @param {ReturnType<import("./normalize").normalizeRecords>} events
|
|
* @param {boolean} hasCustomerIds
|
|
*/
|
|
function groupByCustomer(events, hasCustomerIds) {
|
|
const relevant = events.filter((e) => e.status === "failed" || e.status === "recovered");
|
|
if (!hasCustomerIds) {
|
|
// No customer column detected: cannot safely dedupe retries, so every
|
|
// row is its own event. The report flags this with `deduped: false`.
|
|
return relevant.map((e) => [e]);
|
|
}
|
|
|
|
/** @type {Map<string, typeof relevant>} */
|
|
const map = new Map();
|
|
for (const event of relevant) {
|
|
const key = event.customer || `__row_${map.size}`;
|
|
const bucket = map.get(key) || [];
|
|
bucket.push(event);
|
|
map.set(key, bucket);
|
|
}
|
|
return Array.from(map.values());
|
|
}
|
|
|
|
function topCurrency(counts) {
|
|
const entries = Object.entries(counts);
|
|
if (entries.length === 0) return null;
|
|
entries.sort((a, b) => b[1] - a[1]);
|
|
return entries[0][0];
|
|
}
|
|
|
|
function benchmarkFor(ratePct) {
|
|
const band = BENCHMARK_BANDS.find((b) => ratePct <= b.max) || BENCHMARK_BANDS[BENCHMARK_BANDS.length - 1];
|
|
return band.label;
|
|
}
|
|
|
|
function formatMoney(amount, currency) {
|
|
const rounded = Math.round(amount * 100) / 100;
|
|
return currency ? `${rounded.toFixed(2)} ${currency}` : rounded.toFixed(2);
|
|
}
|
|
|
|
/**
|
|
* @param {ReturnType<typeof buildReport>} report
|
|
*/
|
|
function formatReportText(report) {
|
|
const lines = [];
|
|
lines.push("recovery-rate-calc report");
|
|
lines.push("");
|
|
lines.push(`rows read: ${report.rawRowCount}`);
|
|
if (report.deduped) {
|
|
lines.push(`distinct customers: ${report.dedupedCustomerCount} (retry rows collapsed per customer)`);
|
|
} else {
|
|
lines.push("distinct customers: not detected — no customer/email column found, counting rows as-is");
|
|
}
|
|
lines.push(`failure events: ${report.totalFailureEvents}`);
|
|
lines.push(` recovered: ${report.recoveredEvents}`);
|
|
lines.push(` still unrecovered: ${report.unrecoveredEvents}`);
|
|
if (report.unrecognizedStatusCount > 0) {
|
|
lines.push(` unrecognized status: ${report.unrecognizedStatusCount} row(s) with a status this tool didn't recognize (not counted either way)`);
|
|
}
|
|
lines.push("");
|
|
|
|
if (report.recoveryRatePct === null) {
|
|
lines.push("recovery rate: n/a (no failed or recovered rows detected in this file)");
|
|
} else {
|
|
lines.push(`recovery rate: ${report.recoveryRatePct.toFixed(1)}%`);
|
|
lines.push(` ${report.benchmark}`);
|
|
}
|
|
|
|
lines.push("");
|
|
lines.push(`money recovered: ${formatMoney(report.recoveredAmount, report.currency)}`);
|
|
lines.push(`money left on table: ${formatMoney(report.unrecoveredAmount, report.currency)}`);
|
|
lines.push(`total at risk: ${formatMoney(report.totalAtRisk, report.currency)}`);
|
|
lines.push("");
|
|
lines.push("benchmarks are vendor-published industry bands for comparison only, not a guarantee.");
|
|
lines.push("sources: see README.md");
|
|
lines.push("");
|
|
lines.push("built by RetryBolt (retrybolt.com) — dunning + recovery for Dodo/Stripe/Paddle. this tool works with any provider, no RetryBolt account needed.");
|
|
|
|
return lines.join("\n");
|
|
}
|
|
|
|
module.exports = { buildReport, formatReportText, BENCHMARK_BANDS };
|