feat: Feature 2.1 — Parlay Scan with correlation detection + monetization

POST /api/scan/parlay — authenticated parlay analysis:
- Supabase JWT auth middleware (auth.getUser verification)
- 5 correlation types detected between legs (same_game, same_team,
  same_player_conflicting, positive_correlation, blowout_cascade)
- Overall parlay grading (A/B/C/D) with correlation penalty adjustments
- Free tier: 5 scans/month, atomic scan count increment
- Scan 5: full analysis + personalized upgrade pitch
- Scan 6+: 403 block with upgrade pitch
- Pitch personalization from scan history (top stats, grades, tier rec)
- DB writes: picks + scan_sessions per scan

30 new tests, 158 total (131 Node.js + 27 Python), all passing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kev
2026-03-21 12:45:15 -04:00
parent c8c0962e56
commit 411cb6f196
14 changed files with 1539 additions and 48 deletions
+126
View File
@@ -0,0 +1,126 @@
function detectCorrelations(analyzedLegs, spreads) {
const flags = [];
for (let i = 0; i < analyzedLegs.length; i++) {
for (let j = i + 1; j < analyzedLegs.length; j++) {
const a = analyzedLegs[i];
const b = analyzedLegs[j];
const aGame = a.reasoning?.steps?.season_avg ? getGameKey(a) : null;
const bGame = b.reasoning?.steps?.season_avg ? getGameKey(b) : null;
const sameGame = aGame && bGame && aGame === bGame;
const aTeam = a._team;
const bTeam = b._team;
// 1. same_player_conflicting
if (a.player.toLowerCase() === b.player.toLowerCase()) {
if (isConflicting(a, b)) {
flags.push({
type: 'same_player_conflicting',
legs: [i, j],
detail: `${a.player}: ${a.stat_type} ${a.direction} conflicts with ${b.stat_type} ${b.direction}`,
impact: 'major_negative',
});
} else {
// 4. positive_correlation (same player, complementary)
flags.push({
type: 'positive_correlation',
legs: [i, j],
detail: `${a.player}: ${a.stat_type} ${a.direction} + ${b.stat_type} ${b.direction} are correlated`,
impact: 'positive',
});
}
continue;
}
if (!sameGame) continue;
// 2. same_game_same_team
if (aTeam && bTeam && aTeam === bTeam) {
flags.push({
type: 'same_game_same_team',
legs: [i, j],
detail: `${a.player} and ${b.player} are both ${aTeam} — usage overlap possible`,
impact: 'minor_negative',
});
continue;
}
// 3. same_game_opposing_players
if (a.stat_type === b.stat_type && a.direction === 'over' && b.direction === 'over') {
flags.push({
type: 'same_game_opposing_players',
legs: [i, j],
detail: `${a.player} and ${b.player} in same game, both ${a.stat_type} overs`,
impact: 'minor_negative',
});
}
}
}
// 5. blowout_cascade — 2+ legs from a high-spread game
const gameLegs = groupByGame(analyzedLegs);
for (const [gameKey, indices] of Object.entries(gameLegs)) {
if (indices.length < 2) continue;
const gameSpread = findSpreadForGame(analyzedLegs[indices[0]], spreads);
if (gameSpread != null && Math.abs(gameSpread) > 8) {
flags.push({
type: 'blowout_cascade',
legs: indices,
detail: `${indices.length} legs from a game with ${gameSpread > 0 ? '+' : ''}${gameSpread} spread — blowout risk compounds`,
impact: 'major_negative',
});
}
}
return flags;
}
function getGameKey(leg) {
// Use home_team + away_team from reasoning to identify the game
const sit = leg.reasoning?.steps?.situational;
const lineCmp = leg.reasoning?.steps?.line_comparison;
// Fallback: use the first line's game context
// We'll use _gameTime attached by the scan service
return leg._gameTime || null;
}
function isConflicting(a, b) {
// Same player, opposite directions on related stats
if (a.direction !== b.direction) return true;
// Over points + under PRA (points is component of PRA)
const complementary = [
['points', 'pra'], ['rebounds', 'pra'], ['assists', 'pra'],
];
for (const [s1, s2] of complementary) {
if ((a.stat_type === s1 && b.stat_type === s2) || (a.stat_type === s2 && b.stat_type === s1)) {
if (a.direction !== b.direction) return true;
}
}
return false;
}
function groupByGame(legs) {
const groups = {};
for (let i = 0; i < legs.length; i++) {
const key = legs[i]._gameTime;
if (!key) continue;
if (!groups[key]) groups[key] = [];
groups[key].push(i);
}
return groups;
}
function findSpreadForGame(leg, spreads) {
if (!spreads || !leg._team) return null;
const spread = spreads.find((s) =>
s.home_team === leg._team || s.away_team === leg._team
);
if (!spread) return null;
return spread.home_spread;
}
module.exports = { detectCorrelations };
+63
View File
@@ -0,0 +1,63 @@
function gradeParlayFromLegs(legResults, correlationFlags) {
if (legResults.length === 0) {
return { grade: 'D', confidence: 30, composite: 0 };
}
// Extract leg composites and grades
const legComposites = legResults.map((l) => l._composite || 0);
const legGrades = legResults.map((l) => l.grade);
const legConfidences = legResults.map((l) => l.confidence);
const dCount = legGrades.filter((g) => g === 'D').length;
// Average of leg composites
const legAvg = legComposites.reduce((a, b) => a + b, 0) / legComposites.length;
// Correlation penalties
let correlationPenalty = 0;
let hasMajorNegative = false;
for (const flag of correlationFlags) {
if (flag.impact === 'minor_negative') correlationPenalty -= 0.3;
if (flag.impact === 'major_negative') {
correlationPenalty -= 1.0;
hasMajorNegative = true;
}
}
const parlayComposite = legAvg + correlationPenalty;
// Grade assignment
let grade;
if (parlayComposite >= 2.5 && dCount === 0 && !hasMajorNegative) {
grade = 'A';
} else if (parlayComposite >= 1.5 && dCount <= 1) {
grade = 'B';
} else if (parlayComposite >= 0.5) {
grade = 'C';
} else {
grade = 'D';
}
// 2+ D legs forces grade D
if (dCount >= 2) grade = 'D';
// Major negative caps at B
if (hasMajorNegative && (grade === 'A')) {
grade = 'B';
}
// Confidence: average of legs, adjusted for correlations
let confidence = legConfidences.reduce((a, b) => a + b, 0) / legConfidences.length;
for (const flag of correlationFlags) {
if (flag.impact === 'minor_negative') confidence -= 5;
if (flag.impact === 'major_negative') confidence -= 15;
}
confidence = Math.max(30, Math.min(95, Math.round(confidence)));
return {
grade,
confidence,
composite: Math.round(parlayComposite * 100) / 100,
};
}
module.exports = { gradeParlayFromLegs };
+173
View File
@@ -0,0 +1,173 @@
const { analyzeProp } = require('./propAnalyzer');
const { getOdds } = require('./oddsService');
const { detectCorrelations } = require('./correlationEngine');
const { gradeParlayFromLegs } = require('./parlayGrader');
const { generateUpgradePitch } = require('./upgradePitch');
const { getSupabaseServiceClient } = require('../utils/supabase');
async function scanParlay(user, legs) {
const supabase = getSupabaseServiceClient();
const isFree = user.tier === 'free';
// Scan count check (atomic for free tier)
if (isFree) {
if (user.scan_count >= 5) {
// Already exhausted — return 403 with pitch
const pitch = await generateUpgradePitch(supabase, user.id, null);
return {
blocked: true,
scan_count: user.scan_count,
scans_remaining: 0,
upgrade_pitch: pitch,
};
}
}
// Analyze all legs
const legResults = [];
for (const leg of legs) {
const result = await analyzeProp(leg);
legResults.push(result);
}
// Fetch odds data for correlation detection (spreads, game context)
let spreads = [];
try {
const oddsData = await getOdds('nba');
spreads = oddsData.spreads || [];
// Attach game context to leg results for correlation detection
for (const leg of legResults) {
const matchingProps = (oddsData.props || []).filter(
(p) => p.player.toLowerCase().includes(leg.player.toLowerCase())
);
if (matchingProps.length > 0) {
const prop = matchingProps[0];
leg._gameTime = prop.game_time;
// Resolve team from season avg
const seasonStep = leg.reasoning?.steps?.season_avg;
const team = leg._resolvedTeam || null;
// Use the team from the analysis context
if (leg.reasoning?.steps?.situational?.home_away?.context === 'home') {
leg._team = prop.home_team;
} else if (leg.reasoning?.steps?.situational?.home_away?.context === 'away') {
leg._team = prop.away_team;
}
}
}
} catch (_) {
// Correlation detection is best-effort
}
// Detect correlations
const correlationFlags = detectCorrelations(legResults, spreads);
// Grade the parlay
// Attach composite scores from individual analyses for parlay grading
for (const leg of legResults) {
// Reconstruct composite from the reasoning steps
const steps = leg.reasoning?.steps;
if (steps) {
const seasonDelta = steps.season_avg?.vs_line || 0;
const recentDelta = steps.recent_form?.vs_line || 0;
leg._composite = (Math.abs(seasonDelta) + Math.abs(recentDelta)) / 2;
} else {
leg._composite = 0;
}
}
const { grade: parlayGrade, confidence: parlayConfidence } = gradeParlayFromLegs(
legResults,
correlationFlags
);
// Write to database
const pickIds = [];
for (const leg of legResults) {
const { data: pick, error } = await supabase
.from('picks')
.insert({
user_id: user.id,
player: leg.player,
stat_type: leg.stat_type,
line: leg.line,
book: leg.book || 'unknown',
direction: leg.direction,
grade: leg.grade,
edge_pct: leg.edge_pct,
reasoning: leg.reasoning?.summary || '',
kill_conditions: (leg.kill_conditions_triggered || []).map((k) => k.code),
confidence: leg.confidence,
})
.select('id')
.single();
if (pick) pickIds.push(pick.id);
}
// Write scan session
const { data: session } = await supabase
.from('scan_sessions')
.insert({
user_id: user.id,
legs: pickIds,
final_grade: parlayGrade,
kill_conditions: correlationFlags
.filter((f) => f.impact !== 'positive')
.map((f) => f.type),
correlation_notes: JSON.stringify(correlationFlags),
})
.select('id')
.single();
// Atomic scan count increment for free tier
let newScanCount = user.scan_count;
if (isFree) {
const { data: updated } = await supabase
.from('users')
.update({ scan_count: user.scan_count + 1 })
.eq('id', user.id)
.eq('scan_count', user.scan_count)
.select('scan_count')
.single();
newScanCount = updated?.scan_count ?? user.scan_count + 1;
}
// Build response legs (stripped of internal fields)
const responseLegs = legResults.map((leg, i) => ({
index: i,
player: leg.player,
stat_type: leg.stat_type,
line: leg.line,
direction: leg.direction,
grade: leg.grade,
confidence: leg.confidence,
edge_pct: leg.edge_pct,
kill_conditions: leg.kill_conditions_triggered || [],
reasoning_summary: leg.reasoning?.summary || '',
}));
// Generate upgrade pitch at scan 5
let upgradePitch = null;
if (isFree && newScanCount >= 5) {
upgradePitch = await generateUpgradePitch(supabase, user.id, {
grade: parlayGrade,
legs: responseLegs,
});
}
return {
blocked: false,
scan_id: session?.id || null,
parlay_grade: parlayGrade,
parlay_confidence: parlayConfidence,
correlation_flags: correlationFlags,
legs: responseLegs,
scan_count: newScanCount,
scans_remaining: isFree ? Math.max(0, 5 - newScanCount) : null,
upgrade_pitch: upgradePitch,
};
}
module.exports = { scanParlay };
+86
View File
@@ -0,0 +1,86 @@
async function generateUpgradePitch(supabase, userId, currentScanResults) {
// Fetch prior scan sessions + picks
const { data: sessions } = await supabase
.from('scan_sessions')
.select('id, final_grade, legs, created_at')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.limit(10);
const { data: picks } = await supabase
.from('picks')
.select('stat_type, direction, grade, player')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.limit(50);
const allPicks = picks || [];
const allSessions = sessions || [];
const totalScans = allSessions.length + 1; // +1 for current
// Count good grades (A or B)
const priorGrades = allSessions.map((s) => s.final_grade).filter(Boolean);
if (currentScanResults?.grade) priorGrades.push(currentScanResults.grade);
const goodCount = priorGrades.filter((g) => g === 'A' || g === 'B').length;
// Most common stat type
const statCounts = {};
for (const pick of allPicks) {
statCounts[pick.stat_type] = (statCounts[pick.stat_type] || 0) + 1;
}
// Include current scan legs
if (currentScanResults?.legs) {
for (const leg of currentScanResults.legs) {
const st = leg.stat_type;
statCounts[st] = (statCounts[st] || 0) + 1;
}
}
const topStatType = Object.entries(statCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'props';
// Most common direction for top stat
const dirCounts = { over: 0, under: 0 };
for (const pick of allPicks) {
if (pick.stat_type === topStatType) {
dirCounts[pick.direction] = (dirCounts[pick.direction] || 0) + 1;
}
}
const topDirection = dirCounts.over >= dirCounts.under ? 'over' : 'under';
// Average leg count
const legCounts = allSessions.map((s) => (s.legs || []).length);
if (currentScanResults?.legs) legCounts.push(currentScanResults.legs.length);
const avgLegs = legCounts.length > 0
? legCounts.reduce((a, b) => a + b, 0) / legCounts.length
: 3;
// Unique players scanned
const uniquePlayers = new Set(allPicks.map((p) => p.player));
// Compliment
let compliment;
if (goodCount >= 3) compliment = "you've got a good eye";
else if (goodCount >= 2) compliment = "you're getting sharper";
else if (goodCount >= 1) compliment = "BetonBLK is helping you filter";
else compliment = "let's find better edges together";
// Tier recommendation
const tierRecommended = (avgLegs > 4 || uniquePlayers.size >= 5) ? 'desk' : 'analyst';
const tierBenefit = tierRecommended === 'desk'
? 'Desk tier adds full bet tracking, ROI analytics, and priority cascade alerts.'
: 'Analyst tier gives you unlimited scans plus line movement alerts so you never miss a soft number.';
const founderPrice = tierRecommended === 'desk' ? '$34.99/mo' : '$14.99/mo';
const standardPrice = tierRecommended === 'desk' ? '$49.99/mo' : '$19.99/mo';
return {
hook: `You've scanned ${totalScans} parlays this month. ${goodCount} graded B or higher — ${compliment}.`,
insight: `Your best edge has been ${topStatType} ${topDirection}s. ${tierBenefit}`,
cta: `Unlock unlimited scans for ${founderPrice} (founder rate)`,
tier_recommended: tierRecommended,
founder_price: founderPrice,
standard_price: standardPrice,
};
}
module.exports = { generateUpgradePitch };