| import { AttachmentBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, ActionRowBuilder } from 'discord.js'; |
| import { buildChartSummaryText, createProfitChartPng } from './chart.js'; |
| import { ALERT_ROLE_NAMES } from './constants.js'; |
|
|
| export const BRAND_COLORS = { |
| primary: 0x9d91fb, |
| secondary: 0xcf6bf3, |
| accent: 0x6f5af7, |
| success: 0x8b7bff, |
| info: 0xcf6bf3, |
| muted: 0x7f74c9, |
| error: 0xdc2626, |
| }; |
|
|
| const PALETTE = { |
| primary: BRAND_COLORS.primary, |
| secondary: BRAND_COLORS.secondary, |
| accent: BRAND_COLORS.accent, |
| success: BRAND_COLORS.success, |
| info: BRAND_COLORS.info, |
| muted: BRAND_COLORS.muted, |
| red: BRAND_COLORS.error, |
| }; |
|
|
| const CIRCA_PAGE_SIZE = 15; |
| const CIRCA_PAGE_DESCRIPTION_LIMIT = 3600; |
| const CIRCA_EMPTY_PAGE_TEXT = 'No parsed props were available for this market.'; |
| const EMBED_SIGNATURE_URL = 'http://kasper.streamlit.app/'; |
| const EMBED_SIGNATURE_LABEL = '[Click here for Kasper Web Tool](http://kasper.streamlit.app/)'; |
|
|
| function signEmbed(embed) { |
| const existingDescription = embed?.data?.description; |
| const nextDescription = existingDescription |
| ? `${existingDescription}\n\n${EMBED_SIGNATURE_LABEL}` |
| : EMBED_SIGNATURE_LABEL; |
| return embed.setDescription(nextDescription); |
| } |
|
|
| export function buildErrorEmbed(title, description) { |
| return signEmbed(new EmbedBuilder().setColor(PALETTE.red).setTitle(title).setDescription(description)); |
| } |
|
|
| export function buildBetSavedEmbed(bet) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(`Bet #${bet.betNumber} saved`) |
| .setDescription(`Added to **${bet.book}** under **${bet.sport}** and ready to grade later.`) |
| .addFields( |
| { name: 'Odds', value: bet.oddsInput, inline: true }, |
| { name: 'Stake', value: formatCurrency(bet.stake), inline: true }, |
| { name: 'Units', value: formatUnits(bet.unitsValue), inline: true }, |
| { name: 'Prop', value: truncate(bet.prop, 180) } |
| ) |
| .setFooter({ text: 'Use /resolve or /resolveall when the bet settles.' })); |
| } |
|
|
| export function buildBulkAddEmbed(book, sport, result) { |
| const embed = new EmbedBuilder() |
| .setColor(result.accepted.length > 0 ? PALETTE.primary : PALETTE.red) |
| .setTitle(`Bulk add complete`) |
| .setDescription(`Processed your **${book} / ${sport}** batch.`) |
| .addFields( |
| { |
| name: 'Saved', |
| value: result.accepted.length > 0 |
| ? result.accepted.map((entry) => `Line ${entry.lineNumber} -> #${entry.savedBet.betNumber}`).join('\n') |
| : 'None', |
| }, |
| { |
| name: 'Rejected', |
| value: result.rejected.length > 0 |
| ? result.rejected.map((entry) => `Line ${entry.lineNumber}: ${entry.reason}`).join('\n') |
| : 'None', |
| } |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildResolveEmbed(bet) { |
| const colorMap = { |
| win: PALETTE.success, |
| loss: PALETTE.red, |
| void: PALETTE.muted, |
| }; |
|
|
| return signEmbed(new EmbedBuilder() |
| .setColor(colorMap[bet.status] ?? PALETTE.muted) |
| .setTitle(`Bet #${bet.betNumber} graded ${bet.status.toUpperCase()}`) |
| .setDescription(`${statusBadge(bet.status)} ${truncate(bet.prop, 180)}`) |
| .addFields( |
| { name: 'Sportsbook', value: bet.book, inline: true }, |
| { name: 'Sport', value: bet.sport, inline: true }, |
| { name: 'P/L', value: formatSignedCurrency(bet.profitLoss ?? 0), inline: true } |
| )); |
| } |
|
|
| export function buildResolveAllEmbed(result, summary) { |
| const colorMap = { |
| win: PALETTE.success, |
| loss: PALETTE.red, |
| void: PALETTE.muted, |
| }; |
|
|
| return signEmbed(new EmbedBuilder() |
| .setColor(colorMap[result] ?? PALETTE.muted) |
| .setTitle('Bulk resolve complete') |
| .setDescription(`Applied **${result.toUpperCase()}** to the submitted bet IDs.`) |
| .addFields( |
| { name: 'Resolved', value: listOrNone(summary.resolved) }, |
| { name: 'Already settled', value: listOrNone(summary.alreadyResolved), inline: true }, |
| { name: 'Deleted', value: listOrNone(summary.deleted), inline: true }, |
| { name: 'Not found', value: listOrNone(summary.missing), inline: true } |
| )); |
| } |
|
|
| export function buildEditBetEmbed(result) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(`Bet #${result.bet.betNumber} updated`) |
| .setDescription(`${result.bet.book} | ${result.bet.sport}`) |
| .addFields( |
| { name: 'Odds', value: result.bet.oddsInput, inline: true }, |
| { name: 'Stake', value: formatCurrency(result.bet.stake), inline: true }, |
| { name: 'Units', value: formatUnits(result.bet.unitsValue), inline: true }, |
| { name: 'Prop', value: truncate(result.bet.prop, 180) } |
| )); |
| } |
|
|
| export function buildDeleteBetEmbed(result) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.muted) |
| .setTitle(`Bet #${result.bet.betNumber} deleted`) |
| .setDescription('This bet is now excluded from analytics and browsing, but remains in the audit trail.') |
| .addFields( |
| { name: 'Sportsbook', value: result.bet.book, inline: true }, |
| { name: 'Sport', value: result.bet.sport, inline: true }, |
| { name: 'Reason', value: result.bet.deletedReason ?? 'No reason provided', inline: false } |
| )); |
| } |
|
|
| export function buildBankrollEmbed(profile, summary) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Bankroll Settings') |
| .setDescription('Your bankroll and unit settings feed the analytics layer.') |
| .addFields( |
| { name: 'Starting Bankroll', value: profile.startingBankroll !== null ? formatCurrency(profile.startingBankroll) : 'Not set', inline: true }, |
| { name: 'Unit Size', value: profile.unitSize !== null ? formatCurrency(profile.unitSize) : 'Not set', inline: true }, |
| { name: 'Current Bankroll', value: summary.bankrollNow !== null ? formatSignedCurrency(summary.bankrollNow) : 'Not available', inline: true }, |
| { name: 'Total Units', value: formatUnits(summary.totalUnits), inline: true } |
| )); |
| } |
|
|
| export function buildRoiEmbed(summary, points, chartFileName, filters) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(summary.netProfit >= 0 ? PALETTE.primary : PALETTE.red) |
| .setTitle('ROI Overview') |
| .setDescription(buildFilterBanner(filters, `Total Bets: **${summary.totalBets}**`)) |
| .addFields( |
| { name: 'Net Profit', value: formatSignedCurrency(summary.netProfit), inline: true }, |
| { name: 'ROI', value: formatPercent(summary.roiPercent), inline: true }, |
| { name: 'Settled Stake', value: formatCurrency(summary.settledStake), inline: true }, |
| { name: 'Units', value: formatUnits(summary.totalUnits), inline: true }, |
| { name: 'Current Bankroll', value: summary.bankrollNow !== null ? formatCurrency(summary.bankrollNow) : 'Not set', inline: true }, |
| { name: 'Trend Read', value: buildTrendRead(summary, points), inline: false }, |
| { name: 'Best Snapshot', value: buildPeakSnapshot(points), inline: true }, |
| { name: 'Current Streak', value: formatStreak(summary.streak), inline: true }, |
| { name: 'Best Bet', value: summary.bestBet ? `#${summary.bestBet.betNumber} ${formatSignedCurrency(summary.bestBet.profitLoss ?? 0)}` : 'None', inline: true } |
| ) |
| .setFooter({ text: 'Trend-first view of profitability and staking efficiency' }) |
| .setImage(`attachment://${chartFileName}`)); |
| } |
|
|
| export function buildSummaryEmbed(summary, chartFileName, filters) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(summary.netProfit >= 0 ? PALETTE.secondary : PALETTE.red) |
| .setTitle('Betting Summary') |
| .setDescription(buildFilterBanner(filters, buildSummaryRead(summary))) |
| .addFields( |
| { name: 'Record', value: `${summary.wins}-${summary.losses}-${summary.voids}`, inline: true }, |
| { name: 'Win Rate', value: formatPercent(summary.winRatePercent), inline: true }, |
| { name: 'Open Bets', value: String(summary.openBets), inline: true }, |
| { name: 'Total Bets', value: String(summary.totalBets), inline: true }, |
| { name: 'Net Profit', value: formatSignedCurrency(summary.netProfit), inline: true }, |
| { name: 'Units', value: formatUnits(summary.totalUnits), inline: true }, |
| { name: 'Worst Bet', value: summary.worstBet ? `#${summary.worstBet.betNumber} ${formatSignedCurrency(summary.worstBet.profitLoss ?? 0)}` : 'None', inline: true }, |
| { name: 'Current Bankroll', value: summary.bankrollNow !== null ? formatCurrency(summary.bankrollNow) : 'Not set', inline: true } |
| ) |
| .setFooter({ text: 'Record-first snapshot of overall betting performance' }) |
| .setImage(`attachment://${chartFileName}`)); |
| } |
|
|
| export function buildBetsEmbed(summary, betsPage, filters) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Bet Ledger') |
| .setDescription(buildFilterBanner(filters, `Tracking **${betsPage.totalCount}** matching bets.`)) |
| .addFields( |
| { name: 'Open', value: String(summary.openBets), inline: true }, |
| { name: 'Settled', value: String(summary.wins + summary.losses + summary.voids), inline: true }, |
| { name: 'Net Profit', value: formatSignedCurrency(summary.netProfit), inline: true } |
| ) |
| .setFooter({ text: `Page ${betsPage.currentPage} of ${betsPage.totalPages}` }); |
|
|
| if (betsPage.bets.length === 0) { |
| embed.addFields({ name: 'Recent Bets', value: 'No bets matched these filters.' }); |
| } else { |
| embed.addFields( |
| betsPage.bets.map((bet) => ({ |
| name: `#${bet.betNumber} ${statusBadge(bet.deletedAt ? 'deleted' : bet.status)} ${bet.book} • ${bet.sport}`, |
| value: [ |
| truncate(bet.prop, 110), |
| `Odds: ${bet.oddsInput} | Stake: ${formatCurrency(bet.stake)} | Units: ${formatUnits(bet.unitsValue)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
| } |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildBetsPaginationRow(state) { |
| return new ActionRowBuilder().addComponents( |
| new ButtonBuilder() |
| .setCustomId(buildBetsPageId(state, Math.max(1, state.page - 1))) |
| .setLabel('Prev') |
| .setStyle(ButtonStyle.Primary) |
| .setDisabled(state.page <= 1), |
| new ButtonBuilder() |
| .setCustomId(buildBetsPageId(state, Math.min(state.totalPages, state.page + 1))) |
| .setLabel('Next') |
| .setStyle(ButtonStyle.Primary) |
| .setDisabled(state.page >= state.totalPages) |
| ); |
| } |
|
|
| export function buildBooksEmbed(bookRows, filters) { |
| const sortedRows = [...bookRows].sort((left, right) => right.roiPercent - left.roiPercent); |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Sportsbook Breakdown') |
| .setDescription(buildFilterBanner(filters, 'ROI and win rate ranked by highest ROI.')); |
|
|
| if (sortedRows.length === 0) { |
| return signEmbed(embed.setDescription(buildFilterBanner(filters, 'No bets tracked yet.'))); |
| } |
|
|
| embed.addFields( |
| sortedRows.map((row, index) => ({ |
| name: `${index + 1}. ${row.label}`, |
| value: [ |
| `ROI: ${formatPercent(row.roiPercent)} | Net: ${formatSignedCurrency(row.netProfit)}`, |
| `Win Rate: ${formatPercent(row.winRatePercent)} | Record: ${row.wins}-${row.losses}-${row.voids}`, |
| `Open: ${row.openBets} | Total: ${row.totalBets}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildSportsEmbed(sportRows, filters) { |
| const sortedRows = [...sportRows].sort((left, right) => right.roiPercent - left.roiPercent); |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle('Sport Breakdown') |
| .setDescription(buildFilterBanner(filters, 'ROI and win rate ranked by highest ROI.')); |
|
|
| if (sortedRows.length === 0) { |
| return signEmbed(embed.setDescription(buildFilterBanner(filters, 'No bets tracked yet.'))); |
| } |
|
|
| embed.addFields( |
| sortedRows.map((row, index) => ({ |
| name: `${index + 1}. ${row.label}`, |
| value: [ |
| `ROI: ${formatPercent(row.roiPercent)} | Net: ${formatSignedCurrency(row.netProfit)}`, |
| `Win Rate: ${formatPercent(row.winRatePercent)} | Record: ${row.wins}-${row.losses}-${row.voids}`, |
| `Open: ${row.openBets} | Total: ${row.totalBets}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export async function buildChartAttachment(points, fileName = 'roi-chart.png', options = {}) { |
| const png = await createProfitChartPng(points, options); |
| return new AttachmentBuilder(png, { name: fileName }); |
| } |
|
|
| export function buildBaseballChartAttachment(pngBuffer, fileName) { |
| return new AttachmentBuilder(pngBuffer, { name: fileName }); |
| } |
|
|
| export function buildCommandsEmbed() { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('ROI Bet Tracker Commands') |
| .setDescription('Manual bet logging, editing, grading, export, and analytics for each Discord user.') |
| .addFields( |
| { name: '/bet', value: 'Log one bet privately using sportsbook and sport dropdowns.' }, |
| { name: '/bulkadd', value: 'Log multiple bets privately for one sportsbook and one sport.' }, |
| { name: '/editbet', value: 'Edit one of your open bets privately.' }, |
| { name: '/deletebet', value: 'Soft delete one of your bets privately so it no longer counts.' }, |
| { name: '/resolve', value: 'Grade one of your bet IDs as win, loss, or void.' }, |
| { name: '/resolveall', value: 'Grade multiple bet IDs to the same result in one command.' }, |
| { name: '/bankroll', value: 'View or update your bankroll and unit settings privately.' }, |
| { name: '/roi', value: 'Post a public trend-first ROI view with filters and chart.' }, |
| { name: '/bets', value: 'Post a public filtered ledger with pagination controls.' }, |
| { name: '/summary', value: 'Post a public record-first summary with filters and chart.' }, |
| { name: '/books', value: 'Post public ROI and win-rate breakdowns by sportsbook.' }, |
| { name: '/sports', value: 'Post public ROI and win-rate breakdowns by sport.' }, |
| { name: '/export', value: 'Export your filtered bets to CSV privately.' }, |
| { name: '/commands', value: 'Post this public command reference embed.' }, |
| { name: '/scanstatus', value: 'Show the market scanner status and latest run info. Admin only.' }, |
| { name: '/oddsquota', value: 'Show live Odds API quota usage headers. Admin only.' }, |
| { name: '/scanrun', value: 'Run the market scanner manually. Admin only.' }, |
| { name: '/scanreport', value: 'Post the morning scan reports immediately. Admin only.' }, |
| { name: 'Sharp Market Commands', value: '`/edgeboard`, `/playeredge`, `/marketedge`, `/widthboard`, `/consensusvs`, `/steam`, `/sharpboard`, `/bookscoreboard`, `/markethealth` cover sportsbook comparisons. `/dfsedgeboard`, `/dfsplayeredge`, `/dfsmarketedge`, `/dfswidthboard`, `/dfsconsensusvs` and `/exchangeedgeboard`, `/exchangeplayeredge`, `/exchangemarketedge`, `/exchangewidthboard`, `/exchangeconsensusvs` mirror those views for DFS and exchange lanes.' }, |
| { name: '/hrodds', value: 'Show live Home Run odds for one player across the supported sportsbook books, including Circa, FanDuel, DraftKings, Caesars, Fanatics, Bally Bet, Hard Rock Bet, and BetMGM when available.' }, |
| { name: 'Other Odds Commands', value: '`/hitodds`, `/tbodds`, `/rbiodds`, `/runodds`, `/sbodds`, `/kodds` stay sportsbook-only. `/dfsodds` and `/exchangeodds` show direct prices inside the DFS or exchange lane. Pitcher charts now include `/ktrend`, `/kladder`, `/kprofile`, `/kmatchup`, `/kcount`, plus `/pitchertrend`, `/pitcherarsenal`, `/pitcherlocation`, `/pitcherapproach`, and `/pitchercompare` for deeper pitch-tracking analysis.' }, |
| { name: '/circatest', value: 'Run a Circa OCR diagnostic preview. Admin only.' }, |
| { name: 'Circa Market Commands', value: '`/circamarket`, `/circahr`, `/circahits`, `/circatb`, `/circarbis`, `/circaruns`, `/circasb`, `/circahrri`, `/circak` post the latest parsed Circa markets in the channel where you run them.' }, |
| { name: '/alerts', value: 'Post the public analyst alert-role panel to the welcome channel. Only for jew_olympics.' }, |
| { name: '/welcome', value: 'Post the public welcome embed and tag everyone. Only for Kenny F\'n Powers.' } |
| )); |
| } |
|
|
| export function buildPlayerOddsEmbed({ playerName, marketLabel, entries, bookFilter, lane }) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(buildLaneTitle(`${marketLabel} Odds`, lane)) |
| .setDescription(`${formatLaneLabel(lane)} prices from ${bookFilter ? `**${bookFilter}**` : 'the current lane'} for **${playerName}**.`); |
|
|
| if (!entries.length) { |
| return signEmbed(embed.setDescription(`No ${marketLabel.toLowerCase()} odds were found for **${playerName}**.`)); |
| } |
|
|
| const sortedEntries = [...entries].sort((left, right) => { |
| const circaBoost = left.book === 'Circa' ? -1 : right.book === 'Circa' ? 1 : 0; |
| if (circaBoost !== 0) { |
| return circaBoost; |
| } |
| return Number(left.oddsInput) - Number(right.oddsInput) || left.book.localeCompare(right.book); |
| }); |
|
|
| embed.addFields( |
| sortedEntries.map((entry) => ({ |
| name: entry.book, |
| value: [ |
| entry.selectionDisplay |
| ? `Selection: ${entry.selectionDisplay}` |
| : entry.side |
| ? `Selection: ${String(entry.side).toUpperCase()}${entry.lineValue !== null && entry.lineValue !== undefined ? ` ${entry.lineValue}` : ''}` |
| : null, |
| `Odds: ${entry.oddsInput}`, |
| entry.source === 'circa' ? 'Source: Circa snapshot' : 'Source: Odds API', |
| ].filter(Boolean).join('\n'), |
| inline: true, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildWelcomeEmbed() { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Welcome to ROI Bet Tracker') |
| .setDescription('Track bets manually, grade them later, and compare your ROI across sportsbooks and sports without mixing your stats with anyone else.') |
| .addFields( |
| { name: 'Start Here', value: 'Use `/bet` for one wager or `/bulkadd` to log a full batch.' }, |
| { name: 'Manage Bets', value: 'Use `/editbet`, `/deletebet`, `/resolve`, and `/resolveall` as your card evolves.' }, |
| { name: 'Track Performance', value: 'Use `/roi`, `/summary`, `/bets`, `/books`, `/sports`, and `/export` to review your edge.' } |
| ) |
| .setFooter({ text: 'Built for fast manual logging inside Discord.' })); |
| } |
|
|
| export function buildAlertsEmbed() { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle('Analyst Alert Roles') |
| .setDescription([ |
| "We are moving from @ everyone alerts to individualized alerts. We have 6 analysts who will be sharing plays. You can have as many or as few alerts as you'd like. Click the button of the analyst(s) whose alerts you would like to receive.", |
| '', |
| '@PhazzAlerts - MLB / NBA', |
| '@KennyAlerts - MLB', |
| '@GarAlerts - MLB', |
| '@RIIPAlerts - MLB / NBA / NFL', |
| '@ZylisAlerts - MLB / NBA', |
| '@JRAlerts - NBA / MLB', |
| ].join('\n')) |
| .setFooter({ text: 'Click again any time to remove an alert role.' })); |
| } |
|
|
| export function buildAlertsButtonRows() { |
| const rows = []; |
|
|
| for (let index = 0; index < ALERT_ROLE_NAMES.length; index += 3) { |
| rows.push( |
| new ActionRowBuilder().addComponents( |
| ...ALERT_ROLE_NAMES.slice(index, index + 3).map((roleName) => |
| new ButtonBuilder() |
| .setCustomId(buildAlertRoleButtonId(roleName)) |
| .setLabel(roleName) |
| .setStyle(ButtonStyle.Primary) |
| ) |
| ) |
| ); |
| } |
|
|
| return rows; |
| } |
|
|
| export function buildExportAttachment(rows) { |
| const header = [ |
| 'bet_number', |
| 'book', |
| 'sport', |
| 'status', |
| 'prop', |
| 'odds_input', |
| 'stake', |
| 'units_value', |
| 'profit_loss', |
| 'created_at', |
| 'resolved_at', |
| 'deleted_at', |
| 'deleted_reason', |
| ]; |
| const lines = rows.map((row) => |
| [ |
| row.betNumber, |
| row.book, |
| row.sport, |
| row.deletedAt ? 'deleted' : row.status, |
| escapeCsv(row.prop), |
| row.oddsInput, |
| row.stake.toFixed(2), |
| (row.unitsValue ?? 0).toFixed(4), |
| row.profitLoss ?? '', |
| row.createdAt, |
| row.resolvedAt ?? '', |
| row.deletedAt ?? '', |
| escapeCsv(row.deletedReason ?? ''), |
| ].join(',') |
| ); |
|
|
| return new AttachmentBuilder(Buffer.from([header.join(','), ...lines].join('\n'), 'utf8'), { |
| name: 'bets-export.csv', |
| }); |
| } |
|
|
| export function buildScanStatusEmbed(status) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(status.enabled ? PALETTE.primary : PALETTE.muted) |
| .setTitle('Market Scanner Status') |
| .setDescription(status.enabled |
| ? 'Scanner is configured and ready to run MLB Circa comparisons.' |
| : 'Scanner is disabled because one or more scan environment variables are missing.') |
| .addFields( |
| { name: 'Enabled', value: status.enabled ? 'Yes' : 'No', inline: true }, |
| { name: 'Odds / Circa', value: `${status.oddsWorkflowEnabled ? 'On' : 'Off'} / ${status.circaWorkflowEnabled ? 'On' : 'Off'}`, inline: true }, |
| { name: 'Frequency', value: `${status.frequencyMinutes} minutes`, inline: true }, |
| { name: 'Morning Time', value: `${status.morningTime} (${status.timeZone})`, inline: true }, |
| { name: 'Report Channel', value: status.reportChannelId ? `<#${status.reportChannelId}>` : 'Not set', inline: true }, |
| { name: 'Alert Channel', value: status.alertChannelId ? `<#${status.alertChannelId}>` : 'Not set', inline: true }, |
| { name: 'Min Books / Threshold', value: `${status.minBooks} / ${(status.disagreementThreshold * 100).toFixed(2)}%`, inline: true }, |
| { name: 'Last Scan', value: status.lastScanAt ?? 'Never', inline: true }, |
| { name: 'Last Report', value: status.lastReportAt ?? 'Never', inline: true }, |
| { name: 'Last Circa File', value: status.lastCircaFileName ?? 'None', inline: false }, |
| { name: 'Last Counts', value: `API: ${status.lastApiEntries ?? 0} | Circa: ${status.lastCircaEntries ?? 0} | Alerts: ${status.lastAlertCount ?? 0}`, inline: false }, |
| { name: 'Circa Channel', value: status.circaChannelId ? `<#${status.circaChannelId}>` : 'Not set', inline: true }, |
| { name: 'Circa Daily / Retry', value: `${status.circaDailyTime ?? '09:30'} (${status.circaTimeZone ?? 'America/Chicago'}) / ${status.circaRetryMinutes ?? 30}m`, inline: true }, |
| { name: 'Circa Move Frequency', value: `${status.circaMovementFrequencyMinutes ?? 5} minutes`, inline: true }, |
| { name: 'Odds API Quota', value: status.lastOddsApiRequestsRemaining !== null |
| ? `Remaining: ${status.lastOddsApiRequestsRemaining} | Used: ${status.lastOddsApiRequestsUsed ?? 'n/a'} | Last: ${status.lastOddsApiLastCost ?? 'n/a'}` |
| : 'Unknown', inline: false }, |
| { name: 'Quota Seen', value: status.lastOddsApiQuotaAt ?? 'Never', inline: true }, |
| { name: 'Quota Endpoint', value: status.lastOddsApiEndpoint ?? 'Unknown', inline: true }, |
| { name: 'Last Seen Fingerprint', value: status.lastCircaFingerprintAt ?? 'Never', inline: true }, |
| { name: 'Last Daily Board', value: status.lastCircaBoardAt ?? 'Never', inline: true }, |
| { name: 'Last Move Scan', value: status.lastCircaMovementScanAt ?? 'Never', inline: true }, |
| { name: 'Board Retry State', value: status.circaRetryState ?? 'Idle', inline: false }, |
| { name: 'Last Error', value: status.lastScanError ?? 'None', inline: false }, |
| )); |
| } |
|
|
| export function buildOddsApiQuotaEmbed(quota) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Odds API Quota Usage') |
| .setDescription('Latest live quota headers from The Odds API.') |
| .addFields( |
| { name: 'Remaining', value: quota.remaining !== null && quota.remaining !== undefined ? String(quota.remaining) : 'Unknown', inline: true }, |
| { name: 'Used', value: quota.used !== null && quota.used !== undefined ? String(quota.used) : 'Unknown', inline: true }, |
| { name: 'Last Cost', value: quota.last !== null && quota.last !== undefined ? String(quota.last) : 'Unknown', inline: true }, |
| { name: 'Sport', value: quota.sportKey ?? 'Unknown', inline: true }, |
| { name: 'Region', value: quota.regions ?? 'Unknown', inline: true }, |
| { name: 'Event Count', value: quota.eventCount !== null && quota.eventCount !== undefined ? String(quota.eventCount) : 'Unknown', inline: true }, |
| { name: 'Books', value: Array.isArray(quota.bookmakers) && quota.bookmakers.length > 0 ? quota.bookmakers.join(', ') : 'All returned books', inline: false }, |
| { name: 'Markets', value: Array.isArray(quota.markets) && quota.markets.length > 0 ? quota.markets.join(', ') : 'Unknown', inline: false }, |
| { name: 'Captured At', value: quota.capturedAt ?? 'Unknown', inline: true }, |
| { name: 'Endpoint', value: quota.endpoint ?? 'Unknown', inline: true }, |
| )); |
| } |
|
|
| export function buildMarketTopEmbed(title, rows, options = {}) { |
| const metricLabel = options.metricLabel ?? 'Edge'; |
| const metricFormatter = options.metricFormatter ?? ((row) => String(row.valueEdge ?? '0')); |
| const secondaryValue = options.secondaryValue ?? ((row) => row.oddsInput); |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(title) |
| .setDescription('MLB player props ranked from the latest market scan.'); |
|
|
| if (rows.length === 0) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No matching markets were found in the latest scan.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.playerName} - ${row.marketLabel}`, |
| value: [ |
| `Side: ${row.side.toUpperCase()}${row.lineValue !== null && row.lineValue !== undefined ? ` ${row.lineValue}` : ''}`, |
| `Book: ${row.book} | Odds: ${row.oddsInput}`, |
| `${metricLabel}: ${metricFormatter(row)} | Books: ${row.books}`, |
| `Detail: ${secondaryValue(row)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildSharpEdgeBoardEmbed(title, rows, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(buildLaneTitle(title, filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, `Best current prices versus the ${formatLaneLabel(filters.lane ?? rows[0]?.lane)} lane reference.`)); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No sharp-comparison rows matched the current filters.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.playerName} - ${row.marketLabel}`, |
| value: [ |
| `${getReferenceLabel(row)}: ${row.sharpBook} @ ${row.sharpOddsInput} | Best Price: ${row.bestSoftBook} @ ${row.bestSoftOddsInput}`, |
| `Edge: ${formatPercent(row.edgeImpliedPct * 100)} | Width: ${formatPercent(row.marketWidthPct * 100)}`, |
| `Books: ${row.booksCompared} | Status: ${describeSharpSource(row)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildPlayerEdgeEmbed({ playerName, rows }, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(buildLaneTitle('Player Edge', filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, `Current sharp comparisons for **${playerName}**.`)); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No sharp comparisons were found for that player.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row) => ({ |
| name: row.marketLabel, |
| value: [ |
| `${getReferenceLabel(row)}: ${row.sharpBook} @ ${row.sharpOddsInput} | Best Price: ${row.bestSoftBook} @ ${row.bestSoftOddsInput}`, |
| `Edge: ${formatPercent(row.edgeImpliedPct * 100)} | Width: ${formatPercent(row.marketWidthPct * 100)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildConsensusVsEmbed({ summary, rows }, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle(buildLaneTitle(`Consensus Vs ${summary.book}`, filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, `How this book compares to the current ${formatLaneLabel(filters.lane ?? rows[0]?.lane)} lane reference.`)); |
|
|
| embed.addFields( |
| { name: 'Compared Rows', value: String(summary.comparedRows), inline: true }, |
| { name: 'Positive Edges', value: String(summary.betterThanSharpCount), inline: true }, |
| { name: 'Average Edge', value: formatPercent(summary.averageEdgePct * 100), inline: true }, |
| ); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No sharp comparison rows matched this book and filter set.' })); |
| } |
|
|
| embed.addFields( |
| rows.slice(0, 10).map((row, index) => ({ |
| name: `${index + 1}. ${row.playerName} - ${row.marketLabel}`, |
| value: [ |
| `${getReferenceLabel(row)}: ${row.sharpBook} @ ${row.sharpOddsInput} | ${summary.book}: ${row.compareOddsInput}`, |
| `Edge: ${formatPercent(row.compareEdgePct * 100)} | Width: ${formatPercent(row.marketWidthPct * 100)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildBookScoreboardEmbed(title, rows, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle(buildLaneTitle(title, filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, 'Books ranked by how often and how far they differ from the current lane reference.')); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No book comparison rows matched the current filters.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.book}`, |
| value: [ |
| `Positive Edges: ${row.positiveEdges} / ${row.comparedRows}`, |
| `Avg Edge: ${formatPercent(row.averageEdgePct * 100)} | Max Edge: ${formatPercent(row.maxEdgePct * 100)}`, |
| `Avg Width: ${formatPercent(row.averageWidthPct * 100)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildMarketHealthEmbed(title, rows, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle(buildLaneTitle(title, filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, 'Coverage and quality snapshot across supported sharp markets.')); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No market health rows matched the current filters.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.marketLabel}`, |
| value: [ |
| `Rows: ${row.rows} | Avg Books: ${row.averageBooksCompared.toFixed(2)}`, |
| `Avg Width: ${formatPercent(row.averageWidthPct * 100)}`, |
| row.lane === 'sportsbook' |
| ? `Sharp Source: Circa ${row.circaRows} | FanDuel fallback ${row.fanduelFallbackRows ?? 0} | MGM fallback ${row.mgmFallbackRows}` |
| : `Reference: ${row.lane === 'dfs' ? 'DFS consensus baseline' : 'Exchange consensus baseline'} | Rows ${row.consensusRows}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildSteamEmbed(title, rows, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.info) |
| .setTitle(buildLaneTitle(title, filters.lane ?? rows[0]?.lane)) |
| .setDescription(buildFilterBanner(filters, 'Recent movement compared to the prior stored scan snapshot.')); |
|
|
| if (!rows.length) { |
| return signEmbed(embed.addFields({ name: 'No rows', value: 'No tracked price movement matched the current filters.' })); |
| } |
|
|
| embed.addFields( |
| rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.playerName} - ${row.marketLabel}`, |
| value: [ |
| `Selection: ${formatSelection(row.side, row.lineValue)}`, |
| `Moved Book: ${row.movedBook} | ${formatAmericanOdds(row.oldOddsInput)} -> ${formatAmericanOdds(row.newOddsInput)}`, |
| `${getReferenceLabel(row)}: ${row.sharpBook} @ ${formatAmericanOdds(row.sharpOddsInput)} | Delta: ${formatPercent(row.impliedDeltaPct * 100)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildSharpAlertEmbed(row) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.red) |
| .setTitle(row.lane === 'dfs' ? 'DFS Edge Alert' : row.lane === 'exchange' ? 'Exchange Edge Alert' : 'Sharp Edge Alert') |
| .setDescription(`${row.playerName} - ${row.marketLabel}`) |
| .addFields( |
| { name: 'Selection', value: formatSelection(row.side, row.lineValue), inline: true }, |
| { name: getReferenceLabel(row), value: `${row.sharpBook} @ ${formatAmericanOdds(row.sharpOddsInput)}`, inline: true }, |
| { name: 'Best Price', value: `${row.bestSoftBook} @ ${formatAmericanOdds(row.bestSoftOddsInput)}`, inline: true }, |
| { name: 'Edge', value: formatPercent(row.edgeImpliedPct * 100), inline: true }, |
| { name: 'Width', value: formatPercent(row.marketWidthPct * 100), inline: true }, |
| { name: 'Books Compared', value: String(row.booksCompared), inline: true }, |
| { name: 'Reference Source', value: describeSharpSource(row), inline: true }, |
| )); |
| } |
|
|
| export function buildStaleBookAlertEmbed(row, staleEntry) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.red) |
| .setTitle(row.lane === 'dfs' ? 'DFS Stale Alert' : row.lane === 'exchange' ? 'Exchange Stale Alert' : 'Stale Book Alert') |
| .setDescription(`${row.playerName} - ${row.marketLabel}`) |
| .addFields( |
| { name: 'Selection', value: formatSelection(row.side, row.lineValue), inline: true }, |
| { name: getReferenceLabel(row), value: `${row.sharpBook} @ ${formatAmericanOdds(row.sharpOddsInput)}`, inline: true }, |
| { name: 'Stale Book', value: `${staleEntry.book} @ ${formatAmericanOdds(staleEntry.oddsInput)}`, inline: true }, |
| { name: 'Current Edge', value: formatPercent(((row.sharpImpliedProbability ?? 0) - (staleEntry.impliedProbability ?? 0)) * 100), inline: true }, |
| { name: 'Books Compared', value: String(row.booksCompared), inline: true }, |
| ) |
| .setFooter({ text: 'The lane reference improved while this book stayed stale.' })); |
| } |
|
|
| export function buildReverseAlertEmbed(row, movement) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.muted) |
| .setTitle(row.lane === 'dfs' ? 'DFS Reverse Alert' : row.lane === 'exchange' ? 'Exchange Reverse Alert' : 'Reverse Alert') |
| .setDescription(`${row.playerName} - ${row.marketLabel}`) |
| .addFields( |
| { name: 'Selection', value: formatSelection(row.side, row.lineValue), inline: true }, |
| { name: getReferenceLabel(row), value: `${row.sharpBook} @ ${formatAmericanOdds(row.sharpOddsInput)}`, inline: true }, |
| { |
| name: 'Soft Move', |
| value: `${movement.book} ${formatSelection(movement.currentEntry.side, movement.currentEntry.lineValue)} ${formatAmericanOdds(movement.previousEntry.oddsInput)} -> ${formatAmericanOdds(movement.currentEntry.oddsInput)}`, |
| inline: true, |
| }, |
| { name: 'Move Size', value: formatPercent(movement.impliedDeltaPct * 100), inline: true }, |
| { name: 'Books Compared', value: String(row.booksCompared), inline: true }, |
| ) |
| .setFooter({ text: 'A soft book moved materially while the sharp book stayed flat.' })); |
| } |
|
|
| export function buildCircaAlertEmbed(alert) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.red) |
| .setTitle('Circa Disagreement Alert') |
| .setDescription(`${alert.playerName} - ${alert.marketLabel}`) |
| .addFields( |
| { name: 'Circa', value: `${alert.side.toUpperCase()}${alert.lineValue !== null && alert.lineValue !== undefined ? ` ${alert.lineValue}` : ''} @ ${alert.oddsInput}`, inline: true }, |
| { name: 'Furthest Book', value: `${alert.furthestBookName} @ ${alert.furthestBookOddsInput}`, inline: true }, |
| { name: 'Books Compared', value: String(alert.books), inline: true }, |
| { name: 'Max Deviation', value: `${(alert.maxDeviation * 100).toFixed(2)}%`, inline: true }, |
| { name: 'Market Avg', value: `${((alert.marketAverageImpliedProbability ?? 0) * 100).toFixed(2)}% implied`, inline: true }, |
| { name: 'Market Key', value: alert.marketKey, inline: false }, |
| ) |
| .setFooter({ text: 'Triggered because market books materially disagree with Circa.' })); |
| } |
|
|
| export function buildCircaDiagnosticEmbed(result) { |
| const preview = result.parsedEntries.length > 0 |
| ? result.parsedEntries.map((entry) => |
| `${entry.playerName} | ${entry.marketLabel} | ${entry.side} ${entry.lineValue ?? ''} | ${entry.oddsInput}`.trim() |
| ).join('\n') |
| : 'No Circa entries parsed.'; |
| const snippetFields = (result.marketSnippets ?? []) |
| .map((snippet) => ({ |
| name: snippet.label, |
| value: truncate(snippet.text || 'No text extracted.', 700), |
| inline: false, |
| })); |
|
|
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle('Circa OCR Diagnostic') |
| .setDescription(`Parsed **${result.totalEntries}** Circa entries from **${result.fileName ?? 'the latest Circa file'}**.`) |
| .addFields( |
| { name: 'Market Counts', value: truncate(result.marketCounts || 'No market counts available.', 1000), inline: false }, |
| { name: 'Parsed Preview', value: truncate(preview, 1000), inline: false }, |
| { name: 'OCR Text Sample', value: truncate(result.rawTextSample || 'No OCR text extracted.', 1000), inline: false }, |
| ...snippetFields, |
| )); |
| } |
|
|
| export function buildCircaFailureEmbed(details) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.red) |
| .setTitle('Circa Ingestion Failed') |
| .setDescription('The market scanner could not parse the current Circa file, so no Circa-based alerts were posted for this run.') |
| .addFields( |
| { name: 'File', value: details.fileName ?? 'Unknown', inline: true }, |
| { name: 'Reason', value: details.reason ?? 'Unknown error', inline: true }, |
| { name: 'Source', value: details.source ?? 'Dropbox API', inline: true }, |
| )); |
| } |
|
|
| function buildSafeDescriptionPages(lines, options = {}) { |
| const maxItemsPerPage = options.maxItemsPerPage ?? CIRCA_PAGE_SIZE; |
| const maxDescriptionLength = options.maxDescriptionLength ?? CIRCA_PAGE_DESCRIPTION_LIMIT; |
| const headerLines = options.headerLines ?? []; |
| const fallbackText = options.fallbackText ?? CIRCA_EMPTY_PAGE_TEXT; |
| const pageIntro = headerLines.join('\n'); |
| const introLength = pageIntro.length > 0 ? pageIntro.length + 2 : 0; |
| const pages = []; |
| let current = []; |
| let currentLength = introLength; |
|
|
| for (const rawLine of lines) { |
| const line = truncate(String(rawLine), 220); |
| const lineLength = line.length + (current.length > 0 ? 1 : 0); |
| const wouldExceedItems = current.length >= maxItemsPerPage; |
| const wouldExceedDescription = current.length > 0 && currentLength + lineLength > maxDescriptionLength; |
|
|
| if (wouldExceedItems || wouldExceedDescription) { |
| pages.push(current.join('\n')); |
| current = [line]; |
| currentLength = introLength + line.length; |
| continue; |
| } |
|
|
| current.push(line); |
| currentLength += lineLength; |
| } |
|
|
| if (current.length > 0) { |
| pages.push(current.join('\n')); |
| } |
|
|
| if (pages.length === 0) { |
| pages.push(fallbackText); |
| } |
|
|
| return pages; |
| } |
|
|
| export function buildCircaMarketEmbeds(snapshot, marketLabel, entries, options = {}) { |
| const displayEntries = [...entries] |
| .filter((entry) => entry.side !== 'no') |
| .sort((left, right) => { |
| const leftOdds = Number(left.oddsInput); |
| const rightOdds = Number(right.oddsInput); |
| const leftValue = Number.isFinite(leftOdds) ? leftOdds : Number.MAX_SAFE_INTEGER; |
| const rightValue = Number.isFinite(rightOdds) ? rightOdds : Number.MAX_SAFE_INTEGER; |
| return leftValue - rightValue || left.playerName.localeCompare(right.playerName); |
| }); |
| const lines = displayEntries.map((entry) => { |
| const team = entry.team ? ` (${entry.team})` : ''; |
| const side = `${String(entry.side ?? '').toUpperCase()}${entry.lineValue !== null && entry.lineValue !== undefined ? ` ${entry.lineValue}` : ''}`; |
| return `${entry.playerName}${team} | ${side} | ${entry.oddsInput}`; |
| }); |
|
|
| const footerBase = options.footerText ?? 'Latest parsed Circa market snapshot'; |
| const headerLines = [`Source file: **${snapshot.fileName ?? 'Unknown'}**`]; |
| const pages = buildSafeDescriptionPages(lines, { |
| maxItemsPerPage: options.pageSize ?? CIRCA_PAGE_SIZE, |
| maxDescriptionLength: options.maxDescriptionLength ?? CIRCA_PAGE_DESCRIPTION_LIMIT, |
| headerLines, |
| fallbackText: CIRCA_EMPTY_PAGE_TEXT, |
| }); |
|
|
| return pages.map((pageText, pageIndex) => |
| signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle(`Circa ${marketLabel}${pages.length > 1 ? ` (${pageIndex + 1}/${pages.length})` : ''}`) |
| .setDescription([ |
| ...headerLines, |
| '', |
| pageText, |
| ].join('\n')) |
| .setFooter({ text: `${footerBase}${pages.length > 1 ? ` | Page ${pageIndex + 1}/${pages.length}` : ''}` })) |
| ); |
| } |
|
|
| export function buildCircaPageId({ userId, marketType, totalPages }, page) { |
| return [ |
| 'circa-page', |
| userId, |
| marketType, |
| page, |
| totalPages, |
| ].join('|'); |
| } |
|
|
| export function parseCircaPageId(customId) { |
| const [prefix, userId, marketType, pageText, totalPagesText] = String(customId ?? '').split('|'); |
| if (prefix !== 'circa-page' || !userId || !marketType) { |
| return null; |
| } |
|
|
| const page = Number(pageText); |
| const totalPages = Number(totalPagesText); |
| if (!Number.isInteger(page) || !Number.isInteger(totalPages)) { |
| return null; |
| } |
|
|
| return { |
| userId, |
| marketType, |
| page, |
| totalPages, |
| }; |
| } |
|
|
| export function buildCircaPaginationRow(state) { |
| if (!state || state.totalPages <= 1) { |
| return null; |
| } |
|
|
| return new ActionRowBuilder().addComponents( |
| new ButtonBuilder() |
| .setCustomId(buildCircaPageId(state, Math.max(1, state.page - 1))) |
| .setLabel('Prev') |
| .setStyle(ButtonStyle.Primary) |
| .setDisabled(state.page <= 1), |
| new ButtonBuilder() |
| .setCustomId(buildCircaPageId(state, Math.min(state.totalPages, state.page + 1))) |
| .setLabel('Next') |
| .setStyle(ButtonStyle.Primary) |
| .setDisabled(state.page >= state.totalPages), |
| ); |
| } |
|
|
| export function buildCircaMovementEmbed(movement, snapshot) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Circa Movement') |
| .setDescription(`${movement.playerName} - ${movement.marketLabel}`) |
| .addFields( |
| { name: 'Side', value: `${String(movement.side).toUpperCase()}${movement.lineValue !== null && movement.lineValue !== undefined ? ` ${movement.lineValue}` : ''}`, inline: true }, |
| { name: 'Old Odds', value: movement.oldOddsInput, inline: true }, |
| { name: 'New Odds', value: movement.newOddsInput, inline: true }, |
| { name: 'Implied Change', value: `${movement.impliedChangePercent >= 0 ? '+' : ''}${movement.impliedChangePercent.toFixed(2)}%`, inline: true }, |
| { name: 'Percent Change', value: `${movement.relativePercentChange >= 0 ? '+' : ''}${movement.relativePercentChange.toFixed(2)}%`, inline: true }, |
| { name: 'Source File', value: snapshot.fileName ?? 'Unknown', inline: true }, |
| ) |
| .setFooter({ text: 'Posted only because this Circa prop moved from the prior seen snapshot.' })); |
| } |
|
|
| export function buildMatchupHittersEmbed(result, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.primary) |
| .setTitle('Matchup Hitters') |
| .setDescription( |
| buildFilterBanner( |
| filters, |
| `Top hitter matchups from **${String(result.source ?? 'unknown').toUpperCase()}** for **${result.resolvedDate ?? 'unknown slate'}**.` |
| ) |
| ); |
|
|
| if (result.warning) { |
| embed.addFields({ name: 'Source Note', value: truncate(result.warning, 256), inline: false }); |
| } |
|
|
| if (!result.rows?.length) { |
| return signEmbed(embed.addFields({ name: 'Board', value: 'No hitter matchup rows were available for that filter set.' })); |
| } |
|
|
| embed.addFields( |
| result.rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.hitter_name ?? 'Unknown Hitter'}${row.team ? ` (${row.team})` : ''}`, |
| value: [ |
| `Matchup: ${formatMetricNumber(row.matchup_score)} | Ceiling: ${formatMetricNumber(row.ceiling_score)} | Zone Fit: ${formatMetricNumber(row.zone_fit_score, 3)}`, |
| `xwOBA: ${formatMetricDecimal(row.xwoba)} | Likely: ${formatMetricNumber(row.likely_starter_score)} | HH%: ${formatMetricPercent(row.hard_hit_pct)}`, |
| `Opponent: ${row.opponent_team ?? 'N/A'}${row.opposing_pitcher_name ? ` vs ${row.opposing_pitcher_name}` : ''}${row.opposing_pitcher_hand ? ` (${row.opposing_pitcher_hand})` : ''}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildMatchupPitchersEmbed(result, filters = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.secondary) |
| .setTitle('Matchup Pitchers') |
| .setDescription( |
| buildFilterBanner( |
| filters, |
| `Top pitcher matchups from **${String(result.source ?? 'unknown').toUpperCase()}** for **${result.resolvedDate ?? 'unknown slate'}**.` |
| ) |
| ); |
|
|
| if (result.warning) { |
| embed.addFields({ name: 'Source Note', value: truncate(result.warning, 256), inline: false }); |
| } |
|
|
| if (!result.rows?.length) { |
| return signEmbed(embed.addFields({ name: 'Board', value: 'No pitcher matchup rows were available for that filter set.' })); |
| } |
|
|
| embed.addFields( |
| result.rows.map((row, index) => ({ |
| name: `${index + 1}. ${row.pitcher_name ?? 'Unknown Pitcher'}${row.team ? ` (${row.team})` : ''}`, |
| value: [ |
| `Pitch Score: ${formatMetricNumber(row.pitcher_score)} | Strikeout: ${formatMetricNumber(row.strikeout_score)} | Matchup Adj: ${formatMetricNumber(row.pitcher_matchup_adjustment)}`, |
| `xwOBA: ${formatMetricDecimal(row.xwoba)} | CSW%: ${formatMetricPercent(row.csw_pct)} | SwStr%: ${formatMetricPercent(row.swstr_pct)}`, |
| `Opponent: ${row.opponent_team ?? 'N/A'} | Lineup Quality: ${formatMetricNumber(row.opponent_lineup_quality)} | Lineup Count: ${formatMetricNumber(row.lineup_hitter_count, 0)}`, |
| ].join('\n'), |
| inline: false, |
| })) |
| ); |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildBestMatchupsEmbed(result, filters = {}, options = {}) { |
| const embed = new EmbedBuilder() |
| .setColor(PALETTE.accent) |
| .setTitle(options.title ?? 'Best Matchups') |
| .setDescription( |
| buildFilterBanner( |
| filters, |
| `Compact hitter board from **${String(result.source ?? 'unknown').toUpperCase()}** for **${result.resolvedDate ?? 'unknown slate'}**.` |
| ) |
| ); |
|
|
| if (!result.rows?.length) { |
| return signEmbed(embed.addFields({ name: 'Board', value: 'No matchup hitters were available for that slate.' })); |
| } |
|
|
| embed.addFields( |
| { |
| name: 'Top Board', |
| value: result.rows.map((row, index) => [ |
| `${index + 1}. **${row.hitter_name ?? 'Unknown'}**${row.team ? ` (${row.team})` : ''}`, |
| `Matchup ${formatMetricNumber(row.matchup_score)} | Ceiling ${formatMetricNumber(row.ceiling_score)} | Zone Fit ${formatMetricNumber(row.zone_fit_score, 3)}`, |
| `Barrel ${formatMetricPercent(row.barrel_bip_pct)} | PulledBarrel ${formatMetricPercent(row.pulled_barrel_pct)} | Flyball ${formatMetricPercent(row.fb_pct)}`, |
| `SweetSpot ${formatMetricPercent(row.sweet_spot_pct)} | Launch Angle ${formatMetricNumber(row.avg_launch_angle)} | xwOBA ${formatMetricDecimal(row.xwoba)}`, |
| ].join('\n')).join('\n\n'), |
| inline: false, |
| } |
| ); |
|
|
| if (result.warning) { |
| embed.addFields({ name: 'Source Note', value: truncate(result.warning, 256), inline: false }); |
| } |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildPlayerContextEmbed(result) { |
| const baseDescription = [ |
| `Source: **${String(result.source ?? 'unknown').toUpperCase()}**`, |
| `Slate: **${result.resolvedDate ?? 'unknown'}**`, |
| result.team ? `Team: **${result.team}**` : null, |
| result.opponentTeam ? `Opponent: **${result.opponentTeam}**` : null, |
| ].filter(Boolean).join(' | '); |
|
|
| const embed = new EmbedBuilder() |
| .setColor(result.playerType === 'pitcher' ? PALETTE.secondary : PALETTE.primary) |
| .setTitle(`${result.name ?? 'Player Context'}${result.playerType ? ` - ${capitalize(result.playerType)}` : ''}`) |
| .setDescription(baseDescription); |
|
|
| if (result.metrics?.length) { |
| embed.addFields({ |
| name: 'Overview', |
| value: result.metrics |
| .map((metric) => `${metric.label}: ${formatMetricAuto(metric.value, metric.label)}`) |
| .join(' | '), |
| inline: false, |
| }); |
| } |
|
|
| if (result.playerType === 'hitter') { |
| embed.addFields({ |
| name: 'Today', |
| value: [ |
| result.opposingPitcherName ? `Opposing Pitcher: ${result.opposingPitcherName}` : null, |
| result.hand ? `Pitcher Hand: ${result.hand}` : null, |
| ].filter(Boolean).join(' | ') || 'No same-day opponent context was available.', |
| inline: false, |
| }); |
| } |
|
|
| if (result.rolling?.length) { |
| embed.addFields({ |
| name: 'Rolling', |
| value: result.rolling |
| .map((row) => `${row.label}: ${formatMetricDecimal(row.value)}`) |
| .join('\n'), |
| inline: false, |
| }); |
| } |
|
|
| if (result.zones?.length) { |
| embed.addFields({ |
| name: result.playerType === 'pitcher' ? 'Zones To Watch' : 'Best Zones', |
| value: result.zones |
| .map((row) => `${row.label}: ${formatMetricAuto(row.value, row.metricKey)}${row.sample !== null ? ` | Sample ${formatMetricNumber(row.sample, 0)}` : ''}`) |
| .join('\n'), |
| inline: false, |
| }); |
| } |
|
|
| if (result.arsenal?.length) { |
| embed.addFields({ |
| name: 'Arsenal', |
| value: result.arsenal |
| .map((row) => `${row.pitchType}: Usage ${formatMetricPercent(row.usagePct)}${row.velocity !== null ? ` | Velo ${formatMetricNumber(row.velocity)}` : ''}${row.whiffRate !== null ? ` | Whiff ${formatMetricPercent(row.whiffRate)}` : ''}`) |
| .join('\n'), |
| inline: false, |
| }); |
| } |
|
|
| if (result.countUsage?.length) { |
| embed.addFields({ |
| name: 'Count Usage', |
| value: result.countUsage |
| .map((row) => `${row.countBucket} ${String(row.batterSide).toUpperCase()}: ${row.pitchType} ${formatMetricPercent(row.usagePct)}`) |
| .join('\n'), |
| inline: false, |
| }); |
| } |
|
|
| return signEmbed(embed); |
| } |
|
|
| export function buildMatchupHealthEmbed(result) { |
| return signEmbed(new EmbedBuilder() |
| .setColor(PALETTE.info) |
| .setTitle('Matchup Health') |
| .addFields( |
| { |
| name: 'Hosted Artifacts', |
| value: [ |
| `Configured: ${result.hosted?.configured ? 'Yes' : 'No'}`, |
| `Latest Date: ${result.hosted?.latestDate ?? 'Unavailable'}`, |
| `Cache Entries: ${result.hosted?.cacheEntries ?? 0}`, |
| `Cache TTL: ${formatMetricNumber((result.hosted?.cacheTtlMs ?? 0) / 1000, 0)}s`, |
| result.hosted?.error ? `Error: ${truncate(result.hosted.error, 180)}` : null, |
| ].filter(Boolean).join('\n'), |
| inline: false, |
| }, |
| { |
| name: 'Cockroach Fallback', |
| value: [ |
| `Configured: ${result.fallback?.configured ? 'Yes' : 'No'}`, |
| `Latest Date: ${result.fallback?.latestDate ?? 'Unavailable'}`, |
| result.fallback?.error ? `Error: ${truncate(result.fallback.error, 180)}` : null, |
| ].filter(Boolean).join('\n'), |
| inline: false, |
| } |
| )); |
| } |
|
|
| function buildBaseballChartEmbed({ title, description, fileName, color = PALETTE.primary, read, source, resolvedDate, player, team, opponent, book, view, window, split, pitchType, compareTo, countBucket }) { |
| const details = [ |
| description ?? null, |
| source ? `Source: **${String(source).toUpperCase()}**` : null, |
| resolvedDate ? `Slate: **${resolvedDate}**` : null, |
| player ? `Player: **${player}**` : null, |
| team ? `Team: **${team}**` : null, |
| opponent ? `Opponent: **${opponent}**` : null, |
| view ? `View: **${view}**` : null, |
| window ? `Window: **${window}**` : null, |
| split && split !== 'overall' ? `Split: **${split}**` : null, |
| pitchType ? `Pitch: **${pitchType}**` : null, |
| compareTo ? `Compare To: **${compareTo}**` : null, |
| countBucket && countBucket !== 'all' ? `Count Bucket: **${countBucket}**` : null, |
| book ? `Book: **${book}**` : null, |
| read ? `Read: ${read}` : null, |
| ].filter(Boolean); |
|
|
| return signEmbed(new EmbedBuilder() |
| .setColor(color) |
| .setTitle(title) |
| .setDescription(details.join('\n')) |
| .setImage(`attachment://${fileName}`)); |
| } |
|
|
| export function buildHrBoardChartEmbed(result, filters = {}, fileName = 'hr-board-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'HR Board Chart', |
| description: buildFilterBanner(filters, 'Top home run targets for the active slate.'), |
| fileName, |
| color: PALETTE.secondary, |
| read: 'Higher bars mean stronger HR matchup and ceiling combinations.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| team: filters.team ?? null, |
| }); |
| } |
|
|
| export function buildHrTrendEmbed(result, fileName = 'hr-trend-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'HR Trend', |
| description: 'Rolling slate-date trend for the selected hitter.', |
| fileName, |
| color: PALETTE.secondary, |
| read: 'The main line tracks matchup quality while overlays show shape support.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.playerName, |
| team: result.team, |
| opponent: result.opponentPitcherName ? `${result.opponentPitcherName}${result.opposingPitcherHand ? ` (${result.opposingPitcherHand})` : ''}` : null, |
| }); |
| } |
|
|
| export function buildHrProfileEmbed(result, fileName = 'hr-profile-radar.png') { |
| return buildBaseballChartEmbed({ |
| title: 'HR Profile Radar', |
| description: 'Normalized power profile for the selected hitter.', |
| fileName, |
| color: PALETTE.secondary, |
| read: `Zone Fit ${formatMetricNumber(result.zone_fit_score, 3)} | Matchup ${formatMetricNumber(result.matchup_score)} | Ceiling ${formatMetricNumber(result.ceiling_score)}`, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.playerName, |
| team: result.team, |
| opponent: result.opposingPitcherName ? `${result.opposingPitcherName}${result.opposingPitcherHand ? ` (${result.opposingPitcherHand})` : ''}` : null, |
| }); |
| } |
|
|
| export function buildHrValueChartEmbed(result, filters = {}, fileName = 'hr-value-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'HR Price vs Model', |
| description: buildFilterBanner(filters, 'Current home run prices plotted against model strength.'), |
| fileName, |
| color: PALETTE.secondary, |
| read: 'Points higher and further left are stronger model reads at cheaper implied prices.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| team: filters.team ?? null, |
| book: filters.book ?? null, |
| }); |
| } |
|
|
| export function buildHrZoneEmbed(result, fileName = 'hr-zone-card.png') { |
| return buildBaseballChartEmbed({ |
| title: 'HR Zone Overlay', |
| description: 'Batter damage zones overlaid against the probable pitcher attack map.', |
| fileName, |
| color: PALETTE.secondary, |
| read: `Zone Fit ${formatMetricNumber(result.zone_fit_score, 3)} | Best Overlay ${result.bestOverlay ?? 'N/A'}`, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.playerName, |
| team: result.team, |
| opponent: result.opposingPitcherName ? `${result.opposingPitcherName}${result.opposingPitcherHand ? ` (${result.opposingPitcherHand})` : ''}` : null, |
| }); |
| } |
|
|
| export function buildKTrendEmbed(result, fileName = 'k-trend-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher K Trend', |
| description: 'Rolling strikeout trend for the selected pitcher.', |
| fileName, |
| color: PALETTE.info, |
| read: 'The main line tracks strikeout score while overlays show whiff support.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| }); |
| } |
|
|
| export function buildKLadderEmbed(result, fileName = 'k-ladder-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher K Ladder', |
| description: 'Current strikeout ladder prices for the selected pitcher.', |
| fileName, |
| color: PALETTE.info, |
| read: `Best listed rung: ${result.bestLabel ?? 'N/A'} ${result.bestPrice ?? ''}`.trim(), |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| book: result.book, |
| }); |
| } |
|
|
| export function buildKProfileEmbed(result, fileName = 'k-profile-radar.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Strikeout Profile', |
| description: 'Normalized strikeout upside profile for the selected pitcher.', |
| fileName, |
| color: PALETTE.info, |
| read: `Pitch Score ${formatMetricNumber(result.pitcher_score)} | Strikeout ${formatMetricNumber(result.strikeout_score)} | K Adj ${formatMetricNumber(result.strikeout_matchup_adjustment)}`, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| }); |
| } |
|
|
| export function buildKMatchupEmbed(result, fileName = 'k-matchup-card.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher K Matchup', |
| description: 'Pitcher whiff traits versus opponent lineup pressure.', |
| fileName, |
| color: PALETTE.info, |
| read: result.read ?? 'Higher K scores mean the pitcher whiff profile is well aligned with the opposing lineup.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| }); |
| } |
|
|
| export function buildKCountEmbed(result, fileName = 'k-count-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Count Leverage', |
| description: 'Pitch usage distribution by count bucket for the selected pitcher.', |
| fileName, |
| color: PALETTE.info, |
| read: result.read ?? 'This chart highlights which pitch shapes drive putaway leverage.', |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| }); |
| } |
|
|
| export function buildPitcherTrendEmbed(result, fileName = 'pitcher-trend-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Trend Suite', |
| description: 'Time-based pitcher analysis using Cockroach pitch tracking.', |
| fileName, |
| color: PALETTE.success, |
| read: result.read, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| view: result.view, |
| window: result.window, |
| split: result.split, |
| pitchType: result.pitchType, |
| compareTo: result.compareTo, |
| }); |
| } |
|
|
| export function buildPitcherArsenalEmbed(result, fileName = 'pitcher-arsenal-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Arsenal Suite', |
| description: 'Pitch shape, movement, usage, and outcome view for the selected pitcher.', |
| fileName, |
| color: PALETTE.success, |
| read: result.read, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| view: result.view, |
| window: result.window, |
| split: result.split, |
| pitchType: result.pitchType, |
| }); |
| } |
|
|
| export function buildPitcherLocationEmbed(result, fileName = 'pitcher-location-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Location Suite', |
| description: 'Attack pattern and zone distribution for the selected pitcher.', |
| fileName, |
| color: PALETTE.success, |
| read: result.read, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| view: result.view, |
| split: result.split, |
| pitchType: result.pitchType, |
| countBucket: result.countBucket, |
| }); |
| } |
|
|
| export function buildPitcherApproachEmbed(result, fileName = 'pitcher-approach-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Approach Suite', |
| description: 'Count-state and sequencing view for the selected pitcher.', |
| fileName, |
| color: PALETTE.success, |
| read: result.read, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| view: result.view, |
| window: result.window, |
| split: result.split, |
| pitchType: result.pitchType, |
| }); |
| } |
|
|
| export function buildPitcherCompareEmbed(result, fileName = 'pitcher-compare-chart.png') { |
| return buildBaseballChartEmbed({ |
| title: 'Pitcher Compare Suite', |
| description: 'Baseline, year-over-year, and risk/reward comparison for the selected pitcher.', |
| fileName, |
| color: PALETTE.success, |
| read: result.read, |
| source: result.source, |
| resolvedDate: result.resolvedDate, |
| player: result.pitcherName, |
| team: result.team, |
| opponent: result.opponentTeam, |
| view: result.view, |
| window: result.window, |
| }); |
| } |
|
|
| function escapeCsv(value) { |
| const stringValue = String(value); |
| if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) { |
| return `"${stringValue.replaceAll('"', '""')}"`; |
| } |
| return stringValue; |
| } |
|
|
| function buildSummaryRead(summary) { |
| const settled = summary.wins + summary.losses + summary.voids; |
| if (settled === 0) { |
| return 'No settled bets yet. Once results are graded, this page will summarize record and overall performance.'; |
| } |
|
|
| return `Record sits at **${summary.wins}-${summary.losses}-${summary.voids}** across **${summary.totalBets}** tracked bets.`; |
| } |
|
|
| function buildTrendRead(summary, points) { |
| if (points.length === 0) { |
| return 'No trend yet. Grade some bets to build a profitability curve.'; |
| } |
|
|
| const latest = points[points.length - 1].runningProfit; |
| const direction = latest >= 0 ? 'above break-even' : 'below break-even'; |
| return `Current curve is **${direction}** with **${summary.wins + summary.losses + summary.voids}** resolved bets feeding the trend.`; |
| } |
|
|
| function buildPeakSnapshot(points) { |
| if (points.length === 0) { |
| return 'No peak yet'; |
| } |
|
|
| const peak = points.reduce((best, point) => (point.runningProfit > best.runningProfit ? point : best), points[0]); |
| return `${formatSignedCurrency(peak.runningProfit)} at ${peak.label}`; |
| } |
|
|
| function formatStreak(streak) { |
| if (!streak || streak.count === 0) { |
| return 'No active streak'; |
| } |
|
|
| return `${streak.type.toUpperCase()} x${streak.count}`; |
| } |
|
|
| function statusBadge(status) { |
| if (status === 'win') { |
| return 'W'; |
| } |
| if (status === 'loss') { |
| return 'L'; |
| } |
| if (status === 'void') { |
| return 'V'; |
| } |
| if (status === 'deleted') { |
| return 'D'; |
| } |
| return 'O'; |
| } |
|
|
| function listOrNone(values) { |
| return values.length > 0 ? values.map((id) => `#${id}`).join(', ') : 'None'; |
| } |
|
|
| function formatCurrency(value) { |
| return new Intl.NumberFormat('en-US', { |
| style: 'currency', |
| currency: 'USD', |
| }).format(value); |
| } |
|
|
| function formatSignedCurrency(value) { |
| return `${value >= 0 ? '+' : '-'}${formatCurrency(Math.abs(value))}`; |
| } |
|
|
| function formatAmericanOdds(value) { |
| const stringValue = String(value ?? '').trim(); |
| if (!stringValue) { |
| return 'N/A'; |
| } |
|
|
| const numeric = Number(stringValue); |
| if (!Number.isFinite(numeric)) { |
| return stringValue; |
| } |
|
|
| if (numeric > 0) { |
| return `+${numeric}`; |
| } |
|
|
| return `${numeric}`; |
| } |
|
|
| function formatPercent(value) { |
| return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`; |
| } |
|
|
| function formatUnits(value) { |
| return `${(value ?? 0).toFixed(2)}u`; |
| } |
|
|
| function formatMetricNumber(value, digits = 1) { |
| const numeric = Number(value); |
| if (!Number.isFinite(numeric)) { |
| return 'N/A'; |
| } |
| return numeric.toFixed(digits); |
| } |
|
|
| function formatMetricDecimal(value) { |
| const numeric = Number(value); |
| if (!Number.isFinite(numeric)) { |
| return 'N/A'; |
| } |
| return numeric.toFixed(3); |
| } |
|
|
| function formatMetricPercent(value) { |
| const numeric = Number(value); |
| if (!Number.isFinite(numeric)) { |
| return 'N/A'; |
| } |
| const scaled = Math.abs(numeric) <= 1 ? numeric * 100 : numeric; |
| return `${scaled.toFixed(1)}%`; |
| } |
|
|
| function formatMetricAuto(value, labelOrKey) { |
| const key = String(labelOrKey ?? '').toLowerCase(); |
| if (key.includes('%') || key.endsWith('_pct') || key.includes('usage') || key.includes('whiff') || key.includes('strike')) { |
| return formatMetricPercent(value); |
| } |
| if (key.includes('xwoba')) { |
| return formatMetricDecimal(value); |
| } |
| return formatMetricNumber(value); |
| } |
|
|
| function capitalize(value) { |
| return value ? `${value[0].toUpperCase()}${value.slice(1)}` : ''; |
| } |
|
|
| function formatLaneLabel(lane) { |
| const normalized = String(lane ?? 'sportsbook').toLowerCase(); |
| if (normalized === 'dfs') { |
| return 'DFS'; |
| } |
| if (normalized === 'exchange') { |
| return 'EXCHANGE'; |
| } |
| return 'SPORTSBOOK'; |
| } |
|
|
| function describeSharpSource(row) { |
| if (row.lane === 'dfs') { |
| return 'DFS consensus'; |
| } |
| if (row.lane === 'exchange') { |
| return 'Exchange consensus'; |
| } |
| if (row.sharpSourceMode === 'circa') { |
| return 'Circa'; |
| } |
| if (row.sharpSourceMode === 'fanduel_fallback') { |
| return 'FanDuel fallback'; |
| } |
| return 'BetMGM fallback'; |
| } |
|
|
| function getReferenceLabel(row) { |
| return row?.lane === 'sportsbook' ? 'Sharp' : 'Reference'; |
| } |
|
|
| function buildLaneTitle(baseTitle, lane) { |
| const laneLabel = formatLaneLabel(lane); |
| return laneLabel === 'SPORTSBOOK' ? baseTitle : `${laneLabel} ${baseTitle}`; |
| } |
|
|
| function formatSelection(side, lineValue) { |
| const normalizedSide = String(side ?? '').trim().toLowerCase(); |
| const sideLabel = { |
| over: 'Over', |
| under: 'Under', |
| yes: 'Yes', |
| no: 'No', |
| }[normalizedSide] ?? (normalizedSide ? normalizedSide.toUpperCase() : 'Unknown'); |
|
|
| return lineValue !== null && lineValue !== undefined |
| ? `${sideLabel} ${lineValue}` |
| : sideLabel; |
| } |
|
|
| function truncate(value, maxLength) { |
| if (value.length <= maxLength) { |
| return value; |
| } |
| return `${value.slice(0, maxLength - 3)}...`; |
| } |
|
|
| function buildFilterBanner(filters, baseText) { |
| const labels = []; |
| if (filters.lane && String(filters.lane).toLowerCase() !== 'sportsbook') { |
| labels.push(formatLaneLabel(filters.lane)); |
| } |
| if (filters.market) { |
| labels.push(filters.market); |
| } |
| if (filters.dateWindow && filters.dateWindow !== 'all') { |
| labels.push(filters.dateWindow.toUpperCase()); |
| } |
| if (filters.book) { |
| labels.push(filters.book); |
| } |
| if (filters.team) { |
| labels.push(filters.team.toUpperCase()); |
| } |
| if (filters.player) { |
| labels.push(filters.player); |
| } |
| if (filters.sport) { |
| labels.push(filters.sport); |
| } |
| if (filters.status) { |
| labels.push(filters.status.toUpperCase()); |
| } |
| if (filters.minEdge !== undefined && filters.minEdge !== null) { |
| labels.push(`MIN EDGE ${Number(filters.minEdge)}`); |
| } |
| if (filters.minWidth !== undefined && filters.minWidth !== null) { |
| labels.push(`MIN WIDTH ${Number(filters.minWidth)}`); |
| } |
|
|
| if (labels.length === 0) { |
| return baseText; |
| } |
|
|
| return `${baseText}\nFiltered by: **${labels.join(' | ')}**`; |
| } |
|
|
| export function buildBetsPageId(state, page) { |
| const safe = [ |
| 'bets', |
| state.userId, |
| page, |
| state.dateWindow || 'all', |
| state.book || '~', |
| state.sport || '~', |
| state.status || '~', |
| ].map((value) => encodeURIComponent(String(value))); |
|
|
| return safe.join(':'); |
| } |
|
|
| export function parseBetsPageId(customId) { |
| const [prefix, userId, page, dateWindow, book, sport, status] = customId.split(':').map(decodeURIComponent); |
| if (prefix !== 'bets') { |
| return null; |
| } |
|
|
| return { |
| userId, |
| page: Number(page), |
| dateWindow: dateWindow === 'all' ? undefined : dateWindow, |
| book: book === '~' ? undefined : book, |
| sport: sport === '~' ? undefined : sport, |
| status: status === '~' ? undefined : status, |
| }; |
| } |
|
|
| export function buildAlertRoleButtonId(roleName) { |
| return `alert-role:${encodeURIComponent(roleName)}`; |
| } |
|
|
| export function parseAlertRoleButtonId(customId) { |
| const [prefix, encodedRoleName] = customId.split(':'); |
| if (prefix !== 'alert-role' || !encodedRoleName) { |
| return null; |
| } |
|
|
| return decodeURIComponent(encodedRoleName); |
| } |
|
|