From 14103e48b75a9588944ebfc7c622978a734b3f93 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Wed, 4 Mar 2026 08:13:31 -0600 Subject: [PATCH 01/12] feat: Add Scouting feature (Wonder Pick-style social pack opening) When a player opens a pack, a scout opportunity is posted to #pack-openings with face-down card buttons. Other players can blind-pick one card using daily scout tokens (2/day), receiving a copy. The opener keeps all cards. New files: - discord_ui/scout_view.py: ScoutView with dynamic buttons and claim logic - helpers/scouting.py: create_scout_opportunity() and embed builder - cogs/economy_new/scouting.py: /scout-tokens command and cleanup task Modified: - helpers/main.py: Hook into open_st_pr_packs() after display_cards() - paperdynasty.py: Register scouting cog Requires new API endpoints in paper-dynasty-database (scout_opportunities). Tracks #44. Co-Authored-By: Claude Opus 4.6 --- cogs/economy_new/scouting.py | 104 +++++++++++ discord_ui/__init__.py | 35 ++-- discord_ui/scout_view.py | 339 +++++++++++++++++++++++++++++++++++ helpers/__init__.py | 9 +- helpers/main.py | 46 +++-- helpers/scouting.py | 173 ++++++++++++++++++ paperdynasty.py | 69 +++---- 7 files changed, 716 insertions(+), 59 deletions(-) create mode 100644 cogs/economy_new/scouting.py create mode 100644 discord_ui/scout_view.py create mode 100644 helpers/scouting.py diff --git a/cogs/economy_new/scouting.py b/cogs/economy_new/scouting.py new file mode 100644 index 0000000..9e895e5 --- /dev/null +++ b/cogs/economy_new/scouting.py @@ -0,0 +1,104 @@ +""" +Scouting Cog — Scout token management and expired opportunity cleanup. +""" + +import datetime +import logging + +import discord +from discord import app_commands +from discord.ext import commands, tasks + +from api_calls import db_get +from helpers.utils import int_timestamp +from helpers.discord_utils import get_team_embed +from helpers.main import get_team_by_owner +from helpers.constants import PD_SEASON, IMAGES + +logger = logging.getLogger("discord_app") + +SCOUT_TOKENS_PER_DAY = 2 + + +class Scouting(commands.Cog): + """Scout token tracking and expired opportunity cleanup.""" + + def __init__(self, bot): + self.bot = bot + self.cleanup_expired.start() + + async def cog_unload(self): + self.cleanup_expired.cancel() + + @app_commands.command( + name="scout-tokens", + description="Check how many scout tokens you have left today", + ) + async def scout_tokens_command(self, interaction: discord.Interaction): + await interaction.response.defer(ephemeral=True) + + team = await get_team_by_owner(interaction.user.id) + if not team: + await interaction.followup.send( + "You need a Paper Dynasty team first!", + ephemeral=True, + ) + return + + now = datetime.datetime.now() + midnight = int_timestamp( + datetime.datetime(now.year, now.month, now.day, 0, 0, 0) + ) + + used_today = await db_get( + "rewards", + params=[ + ("name", "Scout Token"), + ("team_id", team["id"]), + ("created_after", midnight), + ], + ) + tokens_used = used_today["count"] if used_today else 0 + tokens_remaining = max(0, SCOUT_TOKENS_PER_DAY - tokens_used) + + embed = get_team_embed(title="Scout Tokens", team=team) + embed.description = ( + f"**{tokens_remaining}** of **{SCOUT_TOKENS_PER_DAY}** tokens remaining today.\n\n" + f"Tokens reset at midnight Central." + ) + + if tokens_remaining == 0: + embed.description += "\n\nYou've used all your tokens! Check back tomorrow." + + await interaction.followup.send(embed=embed, ephemeral=True) + + @tasks.loop(minutes=15) + async def cleanup_expired(self): + """Log expired unclaimed scout opportunities. + + This is a safety net — the ScoutView's on_timeout handles the UI side. + If the bot restarted mid-scout, those views are lost; this just logs it. + """ + try: + now = int_timestamp(datetime.datetime.now()) + expired = await db_get( + "scout_opportunities", + params=[ + ("claimed", False), + ("expired_before", now), + ], + ) + if expired and expired.get("count", 0) > 0: + logger.info( + f"Found {expired['count']} expired unclaimed scout opportunities" + ) + except Exception as e: + logger.debug(f"Scout cleanup check failed (API may not be ready): {e}") + + @cleanup_expired.before_loop + async def before_cleanup(self): + await self.bot.wait_until_ready() + + +async def setup(bot): + await bot.add_cog(Scouting(bot)) diff --git a/discord_ui/__init__.py b/discord_ui/__init__.py index 6e40231..88a3f9d 100644 --- a/discord_ui/__init__.py +++ b/discord_ui/__init__.py @@ -7,17 +7,32 @@ This package contains all Discord UI classes and components used throughout the from .confirmations import Question, Confirm, ButtonOptions from .pagination import Pagination from .selectors import ( - SelectChoicePackTeam, SelectOpenPack, SelectPaperdexCardset, - SelectPaperdexTeam, SelectBuyPacksCardset, SelectBuyPacksTeam, - SelectUpdatePlayerTeam, SelectView + SelectChoicePackTeam, + SelectOpenPack, + SelectPaperdexCardset, + SelectPaperdexTeam, + SelectBuyPacksCardset, + SelectBuyPacksTeam, + SelectUpdatePlayerTeam, + SelectView, ) from .dropdowns import Dropdown, DropdownView +from .scout_view import ScoutView __all__ = [ - 'Question', 'Confirm', 'ButtonOptions', - 'Pagination', - 'SelectChoicePackTeam', 'SelectOpenPack', 'SelectPaperdexCardset', - 'SelectPaperdexTeam', 'SelectBuyPacksCardset', 'SelectBuyPacksTeam', - 'SelectUpdatePlayerTeam', 'SelectView', - 'Dropdown', 'DropdownView' -] \ No newline at end of file + "Question", + "Confirm", + "ButtonOptions", + "Pagination", + "SelectChoicePackTeam", + "SelectOpenPack", + "SelectPaperdexCardset", + "SelectPaperdexTeam", + "SelectBuyPacksCardset", + "SelectBuyPacksTeam", + "SelectUpdatePlayerTeam", + "SelectView", + "Dropdown", + "DropdownView", + "ScoutView", +] diff --git a/discord_ui/scout_view.py b/discord_ui/scout_view.py new file mode 100644 index 0000000..2e7dfb8 --- /dev/null +++ b/discord_ui/scout_view.py @@ -0,0 +1,339 @@ +""" +Scout View — Face-down card button UI for the Scouting feature. + +When a player opens a pack, a ScoutView is posted with one button per card. +Other players can click a button to "scout" (blind-pick) one card, receiving +a copy. The opener keeps all their cards. Multiple players can scout different +cards from the same pack — each costs one scout token. +""" + +import datetime +import logging + +import discord + +from api_calls import db_get, db_post, db_patch +from helpers.main import get_team_by_owner, get_card_embeds +from helpers.utils import int_timestamp +from helpers.discord_utils import get_team_embed +from helpers.constants import IMAGES, PD_SEASON + +logger = logging.getLogger("discord_app") + +SCOUT_TOKENS_PER_DAY = 2 + + +class ScoutView(discord.ui.View): + """Displays face-down card buttons for a scout opportunity. + + - One button per card, labeled "Card 1" ... "Card N" + - Any player EXCEPT the pack opener can interact + - Each card can be scouted once; multiple players can scout different cards + - One scout per player per pack + - Timeout: 30 minutes + """ + + def __init__( + self, + scout_opp_id: int, + cards: list[dict], + opener_team: dict, + opener_user_id: int, + bot, + ): + super().__init__(timeout=1800.0) + self.scout_opp_id = scout_opp_id + self.cards = cards + self.opener_team = opener_team + self.opener_user_id = opener_user_id + self.bot = bot + self.message: discord.Message | None = None + self.card_lines: list[tuple[int, str]] = [] + + # Per-card claim tracking: position -> scouter team name + self.claimed_positions: dict[int, str] = {} + # Per-user lock: user IDs who have already scouted this pack + self.scouted_users: set[int] = set() + # Positions currently being processed (prevent double-click race) + self.processing: set[int] = set() + + for i, card in enumerate(cards): + button = ScoutButton( + card=card, + position=i, + scout_view=self, + ) + self.add_item(button) + + @property + def all_claimed(self) -> bool: + return len(self.claimed_positions) >= len(self.cards) + + async def update_message(self): + """Refresh the embed with current claim state.""" + if not self.message: + return + + from helpers.scouting import build_scouted_card_list + + scouted_ids = {} + for pos, team_name in self.claimed_positions.items(): + player_id = self.cards[pos]["player"]["player_id"] + scouted_ids[player_id] = team_name + + card_list = build_scouted_card_list(self.card_lines, scouted_ids) + claim_count = len(self.claimed_positions) + + if self.all_claimed: + title = "Fully Scouted!" + footer_text = f"Paper Dynasty Season {PD_SEASON} \u2022 All cards scouted" + else: + title = f"Scout Opportunity! ({claim_count}/{len(self.cards)} scouted)" + footer_text = ( + f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player" + ) + + embed = get_team_embed(title=title, team=self.opener_team) + embed.description = ( + f"**{self.opener_team['lname']}**'s pack\n\n" f"{card_list}\n\n" + ) + if not self.all_claimed: + embed.description += ( + "Pick a card — but which is which?\n" + "Costs 1 Scout Token (2 per day, resets at midnight Central)." + ) + + embed.set_footer(text=footer_text, icon_url=IMAGES["logo"]) + + try: + await self.message.edit(embed=embed, view=self) + except Exception as e: + logger.error(f"Failed to update scout message: {e}") + + async def on_timeout(self): + """Disable all buttons and update the embed when the window expires.""" + for item in self.children: + item.disabled = True + + if self.message: + try: + from helpers.scouting import build_scouted_card_list + + scouted_ids = {} + for pos, team_name in self.claimed_positions.items(): + player_id = self.cards[pos]["player"]["player_id"] + scouted_ids[player_id] = team_name + + card_list = build_scouted_card_list(self.card_lines, scouted_ids) + claim_count = len(self.claimed_positions) + + if claim_count > 0: + title = ( + f"Scout Window Closed ({claim_count}/{len(self.cards)} scouted)" + ) + else: + title = "Scout Window Closed" + + embed = get_team_embed(title=title, team=self.opener_team) + embed.description = ( + f"**{self.opener_team['lname']}**'s pack\n\n" f"{card_list}" + ) + embed.set_footer( + text=f"Paper Dynasty Season {PD_SEASON}", + icon_url=IMAGES["logo"], + ) + await self.message.edit(embed=embed, view=self) + except Exception as e: + logger.error(f"Failed to edit expired scout message: {e}") + + +class ScoutButton(discord.ui.Button): + """A single face-down card button in a ScoutView.""" + + def __init__(self, card: dict, position: int, scout_view: ScoutView): + super().__init__( + label=f"Card {position + 1}", + style=discord.ButtonStyle.secondary, + row=0, + ) + self.card = card + self.position = position + self.scout_view: ScoutView = scout_view + + async def callback(self, interaction: discord.Interaction): + view = self.scout_view + + # Block the opener + if interaction.user.id == view.opener_user_id: + await interaction.response.send_message( + "You can't scout your own pack!", + ephemeral=True, + ) + return + + # One scout per player per pack + if interaction.user.id in view.scouted_users: + await interaction.response.send_message( + "You already scouted a card from this pack!", + ephemeral=True, + ) + return + + # This card already taken + if self.position in view.claimed_positions: + await interaction.response.send_message( + "This card was already scouted! Try a different one.", + ephemeral=True, + ) + return + + # Prevent double-click race on same card + if self.position in view.processing: + await interaction.response.send_message( + "Hold on, someone's claiming this card right now...", + ephemeral=True, + ) + return + + view.processing.add(self.position) + await interaction.response.defer(ephemeral=True) + + try: + # Get scouting player's team + scouter_team = await get_team_by_owner(interaction.user.id) + if not scouter_team: + await interaction.followup.send( + "You need a Paper Dynasty team to scout! Ask an admin to set one up.", + ephemeral=True, + ) + return + + # Check scout token balance + now = datetime.datetime.now() + midnight = int_timestamp( + datetime.datetime(now.year, now.month, now.day, 0, 0, 0) + ) + used_today = await db_get( + "rewards", + params=[ + ("name", "Scout Token"), + ("team_id", scouter_team["id"]), + ("created_after", midnight), + ], + ) + tokens_used = used_today["count"] if used_today else 0 + + if tokens_used >= SCOUT_TOKENS_PER_DAY: + await interaction.followup.send( + "You're out of scout tokens for today! You get 2 per day, resetting at midnight Central.", + ephemeral=True, + ) + return + + # Record the claim in the database + try: + await db_post( + "scout_claims", + payload={ + "scout_opportunity_id": view.scout_opp_id, + "card_id": self.card["id"], + "claimed_by_team_id": scouter_team["id"], + }, + ) + except Exception as e: + logger.error(f"Failed to record scout claim: {e}") + await interaction.followup.send( + "Something went wrong claiming this scout. Try again!", + ephemeral=True, + ) + return + + # Consume a scout token + current = await db_get("current") + await db_post( + "rewards", + payload={ + "name": "Scout Token", + "team_id": scouter_team["id"], + "season": current["season"] if current else PD_SEASON, + "week": current["week"] if current else 1, + "created": int_timestamp(now), + }, + ) + + # Create a copy of the card for the scouter + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": self.card["player"]["player_id"], + "team_id": scouter_team["id"], + } + ], + }, + ) + + # Track the claim + view.claimed_positions[self.position] = scouter_team["lname"] + view.scouted_users.add(interaction.user.id) + + # Update this button + self.disabled = True + self.style = discord.ButtonStyle.success + self.label = "Scouted!" + + # If all cards claimed, disable remaining buttons and stop + if view.all_claimed: + for item in view.children: + item.disabled = True + view.stop() + + # Update the shared embed + await view.update_message() + + # Send the scouter their card details (ephemeral) + player_name = self.card["player"]["p_name"] + rarity_name = self.card["player"]["rarity"]["name"] + + card_for_embed = { + "player": self.card["player"], + "team": scouter_team, + } + card_embeds = await get_card_embeds(card_for_embed) + await interaction.followup.send( + content=f"You scouted a **{rarity_name}** {player_name}!", + embeds=card_embeds, + ephemeral=True, + ) + + # Notify for shiny scouts (rarity >= 5) + if self.card["player"]["rarity"]["value"] >= 5: + try: + from helpers.discord_utils import send_to_channel + + notif_embed = get_team_embed(title="Rare Scout!", team=scouter_team) + notif_embed.description = ( + f"**{scouter_team['lname']}** scouted a " + f"**{rarity_name}** {player_name}!" + ) + notif_embed.set_thumbnail( + url=self.card["player"].get("headshot", IMAGES["logo"]) + ) + await send_to_channel( + view.bot, "pd-network-news", embed=notif_embed + ) + except Exception as e: + logger.error(f"Failed to send shiny scout notification: {e}") + + except Exception as e: + logger.error(f"Unexpected error in scout callback: {e}", exc_info=True) + try: + await interaction.followup.send( + "Something went wrong. Please try again.", + ephemeral=True, + ) + except Exception: + pass + finally: + view.processing.discard(self.position) diff --git a/helpers/__init__.py b/helpers/__init__.py index 4b62f4e..8c7e39d 100644 --- a/helpers/__init__.py +++ b/helpers/__init__.py @@ -6,7 +6,7 @@ The package is organized into logical modules for better maintainability. Modules: - constants: Application constants and configuration -- utils: General utility functions +- utils: General utility functions - random_content: Random content generators - search_utils: Search and fuzzy matching functionality - discord_utils: Discord helper functions @@ -21,9 +21,10 @@ Modules: # This allows existing code to continue working during the migration from helpers.main import * -# Import from migrated modules +# Import from migrated modules from .constants import * from .utils import * from .random_content import * -from .search_utils import * -from .discord_utils import * \ No newline at end of file +from .search_utils import * +from .discord_utils import * +from .scouting import * diff --git a/helpers/main.py b/helpers/main.py index ed16a3b..4dfc659 100644 --- a/helpers/main.py +++ b/helpers/main.py @@ -8,7 +8,7 @@ import traceback import discord import pygsheets -import requests +import aiohttp from discord.ext import commands from api_calls import * @@ -43,17 +43,21 @@ async def get_player_photo(player): ) try: - resp = requests.get(req_url, timeout=0.5) - except Exception as e: + async with aiohttp.ClientSession() as session: + async with session.get( + req_url, timeout=aiohttp.ClientTimeout(total=0.5) + ) as resp: + if resp.status == 200: + data = await resp.json() + if data["player"] and data["player"][0]["strSport"] == "Baseball": + await db_patch( + "players", + object_id=player["player_id"], + params=[("headshot", data["player"][0]["strThumb"])], + ) + return data["player"][0]["strThumb"] + except Exception: return None - if resp.status_code == 200 and resp.json()["player"]: - if resp.json()["player"][0]["strSport"] == "Baseball": - await db_patch( - "players", - object_id=player["player_id"], - params=[("headshot", resp.json()["player"][0]["strThumb"])], - ) - return resp.json()["player"][0]["strThumb"] return None @@ -1681,9 +1685,9 @@ async def paperdex_team_embed(team: dict, mlb_team: dict) -> list[discord.Embed] for cardset_id in coll_data: if cardset_id != "total_owned": if coll_data[cardset_id]["players"]: - coll_data[cardset_id]["embeds"][0].description = ( - f"{mlb_team['lname']} / {coll_data[cardset_id]['name']}" - ) + coll_data[cardset_id]["embeds"][ + 0 + ].description = f"{mlb_team['lname']} / {coll_data[cardset_id]['name']}" coll_data[cardset_id]["embeds"][0].add_field( name="# Collected / # Total Cards", value=f"{coll_data[cardset_id]['owned']} / {len(coll_data[cardset_id]['players'])}", @@ -1749,6 +1753,8 @@ async def open_st_pr_packs(all_packs: list, team: dict, context): all_cards = [] for p_id in pack_ids: new_cards = await db_get("cards", params=[("pack_id", p_id)]) + for card in new_cards["cards"]: + card.setdefault("pack_id", p_id) all_cards.extend(new_cards["cards"]) if not all_cards: @@ -1764,6 +1770,18 @@ async def open_st_pr_packs(all_packs: list, team: dict, context): await context.channel.send(content=f"Let's head down to {pack_channel.mention}!") await display_cards(all_cards, team, pack_channel, author, pack_cover=pack_cover) + # Create scout opportunities for each pack + from helpers.scouting import create_scout_opportunity + + for p_id in pack_ids: + pack_cards = [c for c in all_cards if c.get("pack_id") == p_id] + if pack_cards: + await create_scout_opportunity( + pack_cards, team, pack_channel, author, context + ) + if len(pack_ids) > 1: + await asyncio.sleep(2) + async def get_choice_from_cards( interaction: discord.Interaction, diff --git a/helpers/scouting.py b/helpers/scouting.py new file mode 100644 index 0000000..32536fc --- /dev/null +++ b/helpers/scouting.py @@ -0,0 +1,173 @@ +""" +Scouting Helper Functions + +Handles creation of scout opportunities after pack openings +and embed formatting for the scouting feature. +""" + +import asyncio +import datetime +import logging +import random + +import discord + +from api_calls import db_post +from helpers.utils import int_timestamp +from helpers.discord_utils import get_team_embed +from helpers.constants import IMAGES, PD_SEASON + +logger = logging.getLogger("discord_app") + +SCOUT_WINDOW_SECONDS = 1800 # 30 minutes + +# Rarity value → display symbol +RARITY_SYMBOLS = { + 8: "\U0001f7e1", # HoF — yellow + 5: "\U0001f7e3", # MVP — purple + 3: "\U0001f535", # All-Star — blue + 2: "\U0001f7e2", # Starter — green + 1: "\u26aa", # Reserve — white + 0: "\u26ab", # Replacement — black +} + + +def _build_card_lines(cards: list[dict]) -> list[tuple[int, str]]: + """Build a shuffled list of (player_id, display_line) tuples.""" + lines = [] + for card in cards: + player = card["player"] + rarity_val = player["rarity"]["value"] + symbol = RARITY_SYMBOLS.get(rarity_val, "\u26ab") + lines.append( + ( + player["player_id"], + f"{symbol} {player['rarity']['name']} — {player['p_name']}", + ) + ) + random.shuffle(lines) + return lines + + +def build_scout_embed( + opener_team: dict, + cards: list[dict], + card_lines: list[tuple[int, str]] = None, +) -> discord.Embed: + """Build the embed shown above the scout buttons. + + Shows a shuffled list of cards (rarity + player name) so scouters + know what's in the pack but not which button maps to which card. + Returns (embed, card_lines) so the view can store the shuffled order. + """ + embed = get_team_embed(title="Scout Opportunity!", team=opener_team) + + if card_lines is None: + card_lines = _build_card_lines(cards) + + card_list = "\n".join(line for _, line in card_lines) + + embed.description = ( + f"**{opener_team['lname']}** just opened a pack!\n\n" + f"**Cards in this pack:**\n{card_list}\n\n" + f"Pick a card — but which is which?\n" + f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" + f"This window closes in **30 minutes**." + ) + embed.set_footer( + text=f"Paper Dynasty Season {PD_SEASON} \u2022 One player per pack", + icon_url=IMAGES["logo"], + ) + return embed, card_lines + + +def build_scouted_card_list( + card_lines: list[tuple[int, str]], + scouted_cards: dict[int, str], +) -> str: + """Rebuild the card list marking scouted cards with the scouter's team name. + + Parameters + ---------- + card_lines : shuffled list of (player_id, display_line) tuples + scouted_cards : {player_id: scouter_team_name} for each claimed card + """ + result = [] + for player_id, line in card_lines: + if player_id in scouted_cards: + team_name = scouted_cards[player_id] + result.append(f"{line} \u2014 \u2714\ufe0f *{team_name}*") + else: + result.append(line) + return "\n".join(result) + + +async def create_scout_opportunity( + pack_cards: list[dict], + opener_team: dict, + channel: discord.TextChannel, + opener_user, + context, +) -> None: + """Create a scout opportunity and post the ScoutView to the channel. + + Called after display_cards() completes in open_st_pr_packs(). + Wrapped in try/except so scouting failures never crash pack opening. + + Parameters + ---------- + pack_cards : list of card dicts from a single pack + opener_team : team dict for the pack opener + channel : the #pack-openings channel + opener_user : discord.Member or discord.User who opened the pack + context : the command context (Context or Interaction), used to get bot + """ + from discord_ui.scout_view import ScoutView + + # Only create scout opportunities in the pack-openings channel + if not channel or channel.name != "pack-openings": + return + + if not pack_cards: + return + + now = datetime.datetime.now() + expires_at = int_timestamp(now + datetime.timedelta(seconds=SCOUT_WINDOW_SECONDS)) + created = int_timestamp(now) + + card_ids = [c["id"] for c in pack_cards] + + try: + scout_opp = await db_post( + "scout_opportunities", + payload={ + "pack_id": pack_cards[0].get("pack_id"), + "opener_team_id": opener_team["id"], + "card_ids": card_ids, + "expires_at": expires_at, + "created": created, + }, + ) + except Exception as e: + logger.error(f"Failed to create scout opportunity: {e}") + return + + embed, card_lines = build_scout_embed(opener_team, pack_cards) + + # Get bot reference from context + bot = getattr(context, "bot", None) or getattr(context, "client", None) + + view = ScoutView( + scout_opp_id=scout_opp["id"], + cards=pack_cards, + opener_team=opener_team, + opener_user_id=opener_user.id, + bot=bot, + ) + view.card_lines = card_lines + + try: + msg = await channel.send(embed=embed, view=view) + view.message = msg + except Exception as e: + logger.error(f"Failed to post scout opportunity message: {e}") diff --git a/paperdynasty.py b/paperdynasty.py index d7d9ea1..951654a 100644 --- a/paperdynasty.py +++ b/paperdynasty.py @@ -12,12 +12,12 @@ from in_game.gameplay_queries import get_channel_game_or_none from health_server import run_health_server from notify_restart import send_restart_notification -raw_log_level = os.getenv('LOG_LEVEL') -if raw_log_level == 'DEBUG': +raw_log_level = os.getenv("LOG_LEVEL") +if raw_log_level == "DEBUG": log_level = logging.DEBUG -elif raw_log_level == 'INFO': +elif raw_log_level == "INFO": log_level = logging.INFO -elif raw_log_level == 'WARN': +elif raw_log_level == "WARN": log_level = logging.WARNING else: log_level = logging.ERROR @@ -29,17 +29,17 @@ else: # level=log_level # ) # logger.getLogger('discord.http').setLevel(logger.INFO) -logger = logging.getLogger('discord_app') +logger = logging.getLogger("discord_app") logger.setLevel(log_level) handler = RotatingFileHandler( - filename='logs/discord.log', + filename="logs/discord.log", # encoding='utf-8', maxBytes=32 * 1024 * 1024, # 32 MiB backupCount=5, # Rotate through 5 files ) -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) # dt_fmt = '%Y-%m-%d %H:%M:%S' @@ -48,27 +48,30 @@ handler.setFormatter(formatter) logger.addHandler(handler) COGS = [ - 'cogs.owner', - 'cogs.admins', - 'cogs.economy', - 'cogs.players', - 'cogs.gameplay', + "cogs.owner", + "cogs.admins", + "cogs.economy", + "cogs.players", + "cogs.gameplay", + "cogs.economy_new.scouting", ] intents = discord.Intents.default() intents.members = True intents.message_content = True -bot = commands.Bot(command_prefix='.', - intents=intents, - # help_command=None, - description='The Paper Dynasty Bot\nIf you have questions, feel free to contact Cal.', - case_insensitive=True, - owner_id=258104532423147520) +bot = commands.Bot( + command_prefix=".", + intents=intents, + # help_command=None, + description="The Paper Dynasty Bot\nIf you have questions, feel free to contact Cal.", + case_insensitive=True, + owner_id=258104532423147520, +) @bot.event async def on_ready(): - logger.info('Logged in as:') + logger.info("Logged in as:") logger.info(bot.user.name) logger.info(bot.user.id) @@ -77,9 +80,11 @@ async def on_ready(): @bot.tree.error -async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError): +async def on_app_command_error( + interaction: discord.Interaction, error: discord.app_commands.AppCommandError +): """Global error handler for all app commands (slash commands).""" - logger.error(f'App command error in {interaction.command}: {error}', exc_info=error) + logger.error(f"App command error in {interaction.command}: {error}", exc_info=error) # CRITICAL: Release play lock if command failed during gameplay # This prevents permanent user lockouts when exceptions occur @@ -97,22 +102,23 @@ async def on_app_command_error(interaction: discord.Interaction, error: discord. session.add(current_play) session.commit() except Exception as lock_error: - logger.error(f'Failed to release play lock after error: {lock_error}', exc_info=lock_error) + logger.error( + f"Failed to release play lock after error: {lock_error}", + exc_info=lock_error, + ) # Try to respond to the user try: if not interaction.response.is_done(): await interaction.response.send_message( - f'❌ An error occurred: {str(error)}', - ephemeral=True + f"❌ An error occurred: {str(error)}", ephemeral=True ) else: await interaction.followup.send( - f'❌ An error occurred: {str(error)}', - ephemeral=True + f"❌ An error occurred: {str(error)}", ephemeral=True ) except Exception as e: - logger.error(f'Failed to send error message to user: {e}') + logger.error(f"Failed to send error message to user: {e}") async def main(): @@ -120,10 +126,10 @@ async def main(): for c in COGS: try: await bot.load_extension(c) - logger.info(f'Loaded cog: {c}') + logger.info(f"Loaded cog: {c}") except Exception as e: - logger.error(f'Failed to load cog: {c}') - logger.error(f'{e}') + logger.error(f"Failed to load cog: {c}") + logger.error(f"{e}") # Start health server and bot concurrently async with bot: @@ -132,7 +138,7 @@ async def main(): try: # Start bot (this blocks until bot stops) - await bot.start(os.environ.get('BOT_TOKEN', 'NONE')) + await bot.start(os.environ.get("BOT_TOKEN", "NONE")) finally: # Cleanup: cancel health server when bot stops health_task.cancel() @@ -141,4 +147,5 @@ async def main(): except asyncio.CancelledError: pass + asyncio.run(main()) -- 2.25.1 From d538c679c319be12ab3a99aca171ed5e7801f959 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Wed, 4 Mar 2026 19:29:44 -0600 Subject: [PATCH 02/12] refactor: Consolidate scouting utilities, add test suite, use Discord timestamps - Consolidate SCOUT_TOKENS_PER_DAY and get_scout_tokens_used() into helpers/scouting.py (was duplicated across 3 files) - Add midnight_timestamp() utility to helpers/utils.py - Remove _build_scouted_ids() wrapper, use self.claims directly - Fix build_scout_embed return type annotation - Use Discord relative timestamps for scout window countdown - Add 66-test suite covering helpers, ScoutView, and cog Co-Authored-By: Claude Opus 4.6 --- cogs/economy_new/scouting.py | 18 +- discord_ui/__init__.py | 6 +- discord_ui/scout_view.py | 137 +-- helpers/scouting.py | 53 +- helpers/utils.py | 115 +-- tests/scouting/__init__.py | 0 tests/scouting/conftest.py | 160 ++++ tests/scouting/test_scout_view.py | 1029 +++++++++++++++++++++++ tests/scouting/test_scouting_cog.py | 269 ++++++ tests/scouting/test_scouting_helpers.py | 374 ++++++++ 10 files changed, 1987 insertions(+), 174 deletions(-) create mode 100644 tests/scouting/__init__.py create mode 100644 tests/scouting/conftest.py create mode 100644 tests/scouting/test_scout_view.py create mode 100644 tests/scouting/test_scouting_cog.py create mode 100644 tests/scouting/test_scouting_helpers.py diff --git a/cogs/economy_new/scouting.py b/cogs/economy_new/scouting.py index 9e895e5..118927a 100644 --- a/cogs/economy_new/scouting.py +++ b/cogs/economy_new/scouting.py @@ -10,6 +10,7 @@ from discord import app_commands from discord.ext import commands, tasks from api_calls import db_get +from helpers.scouting import SCOUT_TOKENS_PER_DAY, get_scout_tokens_used from helpers.utils import int_timestamp from helpers.discord_utils import get_team_embed from helpers.main import get_team_by_owner @@ -17,8 +18,6 @@ from helpers.constants import PD_SEASON, IMAGES logger = logging.getLogger("discord_app") -SCOUT_TOKENS_PER_DAY = 2 - class Scouting(commands.Cog): """Scout token tracking and expired opportunity cleanup.""" @@ -45,20 +44,7 @@ class Scouting(commands.Cog): ) return - now = datetime.datetime.now() - midnight = int_timestamp( - datetime.datetime(now.year, now.month, now.day, 0, 0, 0) - ) - - used_today = await db_get( - "rewards", - params=[ - ("name", "Scout Token"), - ("team_id", team["id"]), - ("created_after", midnight), - ], - ) - tokens_used = used_today["count"] if used_today else 0 + tokens_used = await get_scout_tokens_used(team["id"]) tokens_remaining = max(0, SCOUT_TOKENS_PER_DAY - tokens_used) embed = get_team_embed(title="Scout Tokens", team=team) diff --git a/discord_ui/__init__.py b/discord_ui/__init__.py index 88a3f9d..ffc1390 100644 --- a/discord_ui/__init__.py +++ b/discord_ui/__init__.py @@ -17,7 +17,10 @@ from .selectors import ( SelectView, ) from .dropdowns import Dropdown, DropdownView -from .scout_view import ScoutView + +# ScoutView intentionally NOT imported here to avoid circular import: +# helpers.main → discord_ui → scout_view → helpers.main +# Import directly: from discord_ui.scout_view import ScoutView __all__ = [ "Question", @@ -34,5 +37,4 @@ __all__ = [ "SelectView", "Dropdown", "DropdownView", - "ScoutView", ] diff --git a/discord_ui/scout_view.py b/discord_ui/scout_view.py index 2e7dfb8..11ce77a 100644 --- a/discord_ui/scout_view.py +++ b/discord_ui/scout_view.py @@ -3,32 +3,30 @@ Scout View — Face-down card button UI for the Scouting feature. When a player opens a pack, a ScoutView is posted with one button per card. Other players can click a button to "scout" (blind-pick) one card, receiving -a copy. The opener keeps all their cards. Multiple players can scout different -cards from the same pack — each costs one scout token. +a copy. The opener keeps all their cards. Multiple players can scout the same +card — each gets their own copy. """ -import datetime import logging import discord -from api_calls import db_get, db_post, db_patch +from api_calls import db_get, db_post from helpers.main import get_team_by_owner, get_card_embeds +from helpers.scouting import SCOUT_TOKENS_PER_DAY, get_scout_tokens_used from helpers.utils import int_timestamp from helpers.discord_utils import get_team_embed from helpers.constants import IMAGES, PD_SEASON logger = logging.getLogger("discord_app") -SCOUT_TOKENS_PER_DAY = 2 - class ScoutView(discord.ui.View): """Displays face-down card buttons for a scout opportunity. - One button per card, labeled "Card 1" ... "Card N" - Any player EXCEPT the pack opener can interact - - Each card can be scouted once; multiple players can scout different cards + - Any card can be scouted multiple times by different players - One scout per player per pack - Timeout: 30 minutes """ @@ -40,6 +38,7 @@ class ScoutView(discord.ui.View): opener_team: dict, opener_user_id: int, bot, + expires_unix: int = None, ): super().__init__(timeout=1800.0) self.scout_opp_id = scout_opp_id @@ -47,15 +46,18 @@ class ScoutView(discord.ui.View): self.opener_team = opener_team self.opener_user_id = opener_user_id self.bot = bot + self.expires_unix = expires_unix self.message: discord.Message | None = None self.card_lines: list[tuple[int, str]] = [] - # Per-card claim tracking: position -> scouter team name - self.claimed_positions: dict[int, str] = {} + # Per-card claim tracking: player_id -> list of scouter team names + self.claims: dict[int, list[str]] = {} # Per-user lock: user IDs who have already scouted this pack self.scouted_users: set[int] = set() - # Positions currently being processed (prevent double-click race) - self.processing: set[int] = set() + # Users currently being processed (prevent double-click race) + self.processing_users: set[int] = set() + # Total scout count + self.total_scouts = 0 for i, card in enumerate(cards): button = ScoutButton( @@ -65,10 +67,6 @@ class ScoutView(discord.ui.View): ) self.add_item(button) - @property - def all_claimed(self) -> bool: - return len(self.claimed_positions) >= len(self.cards) - async def update_message(self): """Refresh the embed with current claim state.""" if not self.message: @@ -76,34 +74,26 @@ class ScoutView(discord.ui.View): from helpers.scouting import build_scouted_card_list - scouted_ids = {} - for pos, team_name in self.claimed_positions.items(): - player_id = self.cards[pos]["player"]["player_id"] - scouted_ids[player_id] = team_name - - card_list = build_scouted_card_list(self.card_lines, scouted_ids) - claim_count = len(self.claimed_positions) - - if self.all_claimed: - title = "Fully Scouted!" - footer_text = f"Paper Dynasty Season {PD_SEASON} \u2022 All cards scouted" - else: - title = f"Scout Opportunity! ({claim_count}/{len(self.cards)} scouted)" - footer_text = ( - f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player" - ) + card_list = build_scouted_card_list(self.card_lines, self.claims) + title = f"Scout Opportunity! ({self.total_scouts} scouted)" embed = get_team_embed(title=title, team=self.opener_team) - embed.description = ( - f"**{self.opener_team['lname']}**'s pack\n\n" f"{card_list}\n\n" - ) - if not self.all_claimed: - embed.description += ( - "Pick a card — but which is which?\n" - "Costs 1 Scout Token (2 per day, resets at midnight Central)." - ) + if self.expires_unix: + time_line = f"Scout window closes ." + else: + time_line = "Scout window closes in **30 minutes**." - embed.set_footer(text=footer_text, icon_url=IMAGES["logo"]) + embed.description = ( + f"**{self.opener_team['lname']}**'s pack\n\n" + f"{card_list}\n\n" + f"Pick a card — but which is which?\n" + f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" + f"{time_line}" + ) + embed.set_footer( + text=f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player", + icon_url=IMAGES["logo"], + ) try: await self.message.edit(embed=embed, view=self) @@ -119,18 +109,10 @@ class ScoutView(discord.ui.View): try: from helpers.scouting import build_scouted_card_list - scouted_ids = {} - for pos, team_name in self.claimed_positions.items(): - player_id = self.cards[pos]["player"]["player_id"] - scouted_ids[player_id] = team_name + card_list = build_scouted_card_list(self.card_lines, self.claims) - card_list = build_scouted_card_list(self.card_lines, scouted_ids) - claim_count = len(self.claimed_positions) - - if claim_count > 0: - title = ( - f"Scout Window Closed ({claim_count}/{len(self.cards)} scouted)" - ) + if self.total_scouts > 0: + title = f"Scout Window Closed ({self.total_scouts} scouted)" else: title = "Scout Window Closed" @@ -179,23 +161,11 @@ class ScoutButton(discord.ui.Button): ) return - # This card already taken - if self.position in view.claimed_positions: - await interaction.response.send_message( - "This card was already scouted! Try a different one.", - ephemeral=True, - ) + # Prevent double-click race for same user + if interaction.user.id in view.processing_users: return - # Prevent double-click race on same card - if self.position in view.processing: - await interaction.response.send_message( - "Hold on, someone's claiming this card right now...", - ephemeral=True, - ) - return - - view.processing.add(self.position) + view.processing_users.add(interaction.user.id) await interaction.response.defer(ephemeral=True) try: @@ -209,19 +179,7 @@ class ScoutButton(discord.ui.Button): return # Check scout token balance - now = datetime.datetime.now() - midnight = int_timestamp( - datetime.datetime(now.year, now.month, now.day, 0, 0, 0) - ) - used_today = await db_get( - "rewards", - params=[ - ("name", "Scout Token"), - ("team_id", scouter_team["id"]), - ("created_after", midnight), - ], - ) - tokens_used = used_today["count"] if used_today else 0 + tokens_used = await get_scout_tokens_used(scouter_team["id"]) if tokens_used >= SCOUT_TOKENS_PER_DAY: await interaction.followup.send( @@ -257,7 +215,7 @@ class ScoutButton(discord.ui.Button): "team_id": scouter_team["id"], "season": current["season"] if current else PD_SEASON, "week": current["week"] if current else 1, - "created": int_timestamp(now), + "created": int_timestamp(), }, ) @@ -275,19 +233,12 @@ class ScoutButton(discord.ui.Button): ) # Track the claim - view.claimed_positions[self.position] = scouter_team["lname"] + player_id = self.card["player"]["player_id"] + if player_id not in view.claims: + view.claims[player_id] = [] + view.claims[player_id].append(scouter_team["lname"]) view.scouted_users.add(interaction.user.id) - - # Update this button - self.disabled = True - self.style = discord.ButtonStyle.success - self.label = "Scouted!" - - # If all cards claimed, disable remaining buttons and stop - if view.all_claimed: - for item in view.children: - item.disabled = True - view.stop() + view.total_scouts += 1 # Update the shared embed await view.update_message() @@ -336,4 +287,4 @@ class ScoutButton(discord.ui.Button): except Exception: pass finally: - view.processing.discard(self.position) + view.processing_users.discard(interaction.user.id) diff --git a/helpers/scouting.py b/helpers/scouting.py index 32536fc..ab2d2c2 100644 --- a/helpers/scouting.py +++ b/helpers/scouting.py @@ -12,13 +12,14 @@ import random import discord -from api_calls import db_post -from helpers.utils import int_timestamp +from api_calls import db_get, db_post +from helpers.utils import int_timestamp, midnight_timestamp from helpers.discord_utils import get_team_embed from helpers.constants import IMAGES, PD_SEASON logger = logging.getLogger("discord_app") +SCOUT_TOKENS_PER_DAY = 2 SCOUT_WINDOW_SECONDS = 1800 # 30 minutes # Rarity value → display symbol @@ -32,6 +33,19 @@ RARITY_SYMBOLS = { } +async def get_scout_tokens_used(team_id: int) -> int: + """Return how many scout tokens a team has used today.""" + used_today = await db_get( + "rewards", + params=[ + ("name", "Scout Token"), + ("team_id", team_id), + ("created_after", midnight_timestamp()), + ], + ) + return used_today["count"] if used_today else 0 + + def _build_card_lines(cards: list[dict]) -> list[tuple[int, str]]: """Build a shuffled list of (player_id, display_line) tuples.""" lines = [] @@ -53,7 +67,8 @@ def build_scout_embed( opener_team: dict, cards: list[dict], card_lines: list[tuple[int, str]] = None, -) -> discord.Embed: + expires_unix: int = None, +) -> tuple[discord.Embed, list[tuple[int, str]]]: """Build the embed shown above the scout buttons. Shows a shuffled list of cards (rarity + player name) so scouters @@ -67,12 +82,17 @@ def build_scout_embed( card_list = "\n".join(line for _, line in card_lines) + if expires_unix: + time_line = f"Scout window closes ." + else: + time_line = "Scout window closes in **30 minutes**." + embed.description = ( f"**{opener_team['lname']}** just opened a pack!\n\n" f"**Cards in this pack:**\n{card_list}\n\n" f"Pick a card — but which is which?\n" f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" - f"This window closes in **30 minutes**." + f"{time_line}" ) embed.set_footer( text=f"Paper Dynasty Season {PD_SEASON} \u2022 One player per pack", @@ -83,20 +103,25 @@ def build_scout_embed( def build_scouted_card_list( card_lines: list[tuple[int, str]], - scouted_cards: dict[int, str], + scouted_cards: dict[int, list[str]], ) -> str: - """Rebuild the card list marking scouted cards with the scouter's team name. + """Rebuild the card list marking scouted cards with scouter team names. Parameters ---------- card_lines : shuffled list of (player_id, display_line) tuples - scouted_cards : {player_id: scouter_team_name} for each claimed card + scouted_cards : {player_id: [team_name, ...]} for each claimed card """ result = [] for player_id, line in card_lines: - if player_id in scouted_cards: - team_name = scouted_cards[player_id] - result.append(f"{line} \u2014 \u2714\ufe0f *{team_name}*") + teams = scouted_cards.get(player_id) + if teams: + count = len(teams) + names = ", ".join(f"*{t}*" for t in teams) + if count == 1: + result.append(f"{line} \u2014 \u2714\ufe0f {names}") + else: + result.append(f"{line} \u2014 \u2714\ufe0f x{count} ({names})") else: result.append(line) return "\n".join(result) @@ -152,7 +177,12 @@ async def create_scout_opportunity( logger.error(f"Failed to create scout opportunity: {e}") return - embed, card_lines = build_scout_embed(opener_team, pack_cards) + expires_unix = int( + (now + datetime.timedelta(seconds=SCOUT_WINDOW_SECONDS)).timestamp() + ) + embed, card_lines = build_scout_embed( + opener_team, pack_cards, expires_unix=expires_unix + ) # Get bot reference from context bot = getattr(context, "bot", None) or getattr(context, "client", None) @@ -163,6 +193,7 @@ async def create_scout_opportunity( opener_team=opener_team, opener_user_id=opener_user.id, bot=bot, + expires_unix=expires_unix, ) view.card_lines = card_lines diff --git a/helpers/utils.py b/helpers/utils.py index 9fc70e3..7535bf7 100644 --- a/helpers/utils.py +++ b/helpers/utils.py @@ -4,6 +4,7 @@ General Utilities This module contains standalone utility functions with minimal dependencies, including timestamp conversion, position abbreviations, and simple helpers. """ + import datetime from typing import Optional import discord @@ -16,48 +17,55 @@ def int_timestamp(datetime_obj: Optional[datetime.datetime] = None): return int(datetime.datetime.now().timestamp()) +def midnight_timestamp() -> int: + """Return today's midnight (00:00:00) as an integer millisecond timestamp.""" + now = datetime.datetime.now() + midnight = datetime.datetime(now.year, now.month, now.day, 0, 0, 0) + return int_timestamp(midnight) + + def get_pos_abbrev(field_pos: str) -> str: """Convert position name to standard abbreviation.""" - if field_pos.lower() == 'catcher': - return 'C' - elif field_pos.lower() == 'first baseman': - return '1B' - elif field_pos.lower() == 'second baseman': - return '2B' - elif field_pos.lower() == 'third baseman': - return '3B' - elif field_pos.lower() == 'shortstop': - return 'SS' - elif field_pos.lower() == 'left fielder': - return 'LF' - elif field_pos.lower() == 'center fielder': - return 'CF' - elif field_pos.lower() == 'right fielder': - return 'RF' + if field_pos.lower() == "catcher": + return "C" + elif field_pos.lower() == "first baseman": + return "1B" + elif field_pos.lower() == "second baseman": + return "2B" + elif field_pos.lower() == "third baseman": + return "3B" + elif field_pos.lower() == "shortstop": + return "SS" + elif field_pos.lower() == "left fielder": + return "LF" + elif field_pos.lower() == "center fielder": + return "CF" + elif field_pos.lower() == "right fielder": + return "RF" else: - return 'P' + return "P" def position_name_to_abbrev(position_name): """Convert position name to abbreviation (alternate format).""" - if position_name == 'Catcher': - return 'C' - elif position_name == 'First Base': - return '1B' - elif position_name == 'Second Base': - return '2B' - elif position_name == 'Third Base': - return '3B' - elif position_name == 'Shortstop': - return 'SS' - elif position_name == 'Left Field': - return 'LF' - elif position_name == 'Center Field': - return 'CF' - elif position_name == 'Right Field': - return 'RF' - elif position_name == 'Pitcher': - return 'P' + if position_name == "Catcher": + return "C" + elif position_name == "First Base": + return "1B" + elif position_name == "Second Base": + return "2B" + elif position_name == "Third Base": + return "3B" + elif position_name == "Shortstop": + return "SS" + elif position_name == "Left Field": + return "LF" + elif position_name == "Center Field": + return "CF" + elif position_name == "Right Field": + return "RF" + elif position_name == "Pitcher": + return "P" else: return position_name @@ -67,13 +75,13 @@ def user_has_role(user: discord.User | discord.Member, role_name: str) -> bool: for x in user.roles: if x.name == role_name: return True - + return False def get_roster_sheet_legacy(team): """Get legacy roster sheet URL for a team.""" - return f'https://docs.google.com/spreadsheets/d/{team.gsheet}/edit' + return f"https://docs.google.com/spreadsheets/d/{team.gsheet}/edit" def get_roster_sheet(team): @@ -83,13 +91,15 @@ def get_roster_sheet(team): Handles both dict and Team object formats. """ # Handle both dict (team["gsheet"]) and object (team.gsheet) formats - gsheet = team.get("gsheet") if isinstance(team, dict) else getattr(team, "gsheet", None) - return f'https://docs.google.com/spreadsheets/d/{gsheet}/edit' + gsheet = ( + team.get("gsheet") if isinstance(team, dict) else getattr(team, "gsheet", None) + ) + return f"https://docs.google.com/spreadsheets/d/{gsheet}/edit" def get_player_url(team, player) -> str: """Generate player URL for SBA or Baseball Reference.""" - if team.get('league') == 'SBA': + if team.get("league") == "SBA": return f'https://statsplus.net/super-baseball-association/player/{player["player_id"]}' else: return f'https://www.baseball-reference.com/players/{player["bbref_id"][0]}/{player["bbref_id"]}.shtml' @@ -101,7 +111,7 @@ def owner_only(ctx) -> bool: owners = [287463767924137994, 1087936030899347516] # Handle both Context (has .author) and Interaction (has .user) objects - user = getattr(ctx, 'user', None) or getattr(ctx, 'author', None) + user = getattr(ctx, "user", None) or getattr(ctx, "author", None) if user and user.id in owners: return True @@ -121,35 +131,36 @@ def get_context_user(ctx): discord.User or discord.Member: The user who invoked the command """ # Handle both Context (has .author) and Interaction (has .user) objects - return getattr(ctx, 'user', None) or getattr(ctx, 'author', None) + return getattr(ctx, "user", None) or getattr(ctx, "author", None) def get_cal_user(ctx): """Get the Cal user from context. Always returns an object with .mention attribute.""" import logging - logger = logging.getLogger('discord_app') - + + logger = logging.getLogger("discord_app") + # Define placeholder user class first class PlaceholderUser: def __init__(self): self.mention = "<@287463767924137994>" self.id = 287463767924137994 - + # Handle both Context and Interaction objects - if hasattr(ctx, 'bot'): # Context object + if hasattr(ctx, "bot"): # Context object bot = ctx.bot logger.debug("get_cal_user: Using Context object") - elif hasattr(ctx, 'client'): # Interaction object + elif hasattr(ctx, "client"): # Interaction object bot = ctx.client logger.debug("get_cal_user: Using Interaction object") else: logger.error("get_cal_user: No bot or client found in context") return PlaceholderUser() - + if not bot: logger.error("get_cal_user: bot is None") return PlaceholderUser() - + logger.debug(f"get_cal_user: Searching among members") try: for user in bot.get_all_members(): @@ -158,7 +169,7 @@ def get_cal_user(ctx): return user except Exception as e: logger.error(f"get_cal_user: Exception in get_all_members: {e}") - + # Fallback: try to get user directly by ID logger.debug("get_cal_user: User not found in get_all_members, trying get_user") try: @@ -170,7 +181,7 @@ def get_cal_user(ctx): logger.debug("get_cal_user: get_user returned None") except Exception as e: logger.error(f"get_cal_user: Exception in get_user: {e}") - + # Last resort: return a placeholder user object with mention logger.debug("get_cal_user: Using placeholder user") - return PlaceholderUser() \ No newline at end of file + return PlaceholderUser() diff --git a/tests/scouting/__init__.py b/tests/scouting/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/scouting/conftest.py b/tests/scouting/conftest.py new file mode 100644 index 0000000..523e38f --- /dev/null +++ b/tests/scouting/conftest.py @@ -0,0 +1,160 @@ +"""Shared fixtures for scouting feature tests.""" + +import pytest +import asyncio +from unittest.mock import AsyncMock, MagicMock, Mock + +import discord +from discord.ext import commands + +# --------------------------------------------------------------------------- +# Sample data factories +# --------------------------------------------------------------------------- + + +def _make_player(player_id, name, rarity_name, rarity_value, headshot=None): + """Build a minimal player dict matching the API shape used by scouting.""" + return { + "player_id": player_id, + "p_name": name, + "rarity": {"name": rarity_name, "value": rarity_value, "color": "ffffff"}, + "headshot": headshot or "https://example.com/headshot.jpg", + } + + +def _make_card(card_id, player): + """Wrap a player dict inside a card dict (as returned by the cards API).""" + return {"id": card_id, "player": player} + + +@pytest.fixture +def sample_players(): + """Five players spanning different rarities for a realistic pack.""" + return [ + _make_player(101, "Mike Trout", "MVP", 5), + _make_player(102, "Juan Soto", "All-Star", 3), + _make_player(103, "Marcus Semien", "Starter", 2), + _make_player(104, "Willy Adames", "Reserve", 1), + _make_player(105, "Generic Bench", "Replacement", 0), + ] + + +@pytest.fixture +def sample_cards(sample_players): + """Five card dicts wrapping the sample players.""" + return [_make_card(i + 1, p) for i, p in enumerate(sample_players)] + + +@pytest.fixture +def opener_team(): + """Team dict for the pack opener.""" + return { + "id": 10, + "abbrev": "OPN", + "sname": "Openers", + "lname": "Opening Squad", + "gm_id": 99999, + "gmname": "Opener GM", + "color": "a6ce39", + "logo": "https://example.com/logo.png", + "season": 4, + } + + +@pytest.fixture +def scouter_team(): + """Team dict for a player who scouts a card.""" + return { + "id": 20, + "abbrev": "SCT", + "sname": "Scouts", + "lname": "Scouting Squad", + "gm_id": 88888, + "gmname": "Scout GM", + "color": "3498db", + "logo": "https://example.com/scout_logo.png", + "season": 4, + } + + +@pytest.fixture +def scouter_team_2(): + """Second scouter team for multi-scout tests.""" + return { + "id": 30, + "abbrev": "SC2", + "sname": "Scouts2", + "lname": "Second Scouts", + "gm_id": 77777, + "gmname": "Scout GM 2", + "color": "e74c3c", + "logo": "https://example.com/scout2_logo.png", + "season": 4, + } + + +# --------------------------------------------------------------------------- +# Discord mocks +# --------------------------------------------------------------------------- + + +@pytest.fixture +def mock_bot(): + """Mock Discord bot.""" + bot = AsyncMock(spec=commands.Bot) + bot.get_cog = Mock(return_value=None) + bot.add_cog = AsyncMock() + bot.wait_until_ready = AsyncMock() + + # Mock guild / channel lookup for send_to_channel + channel_mock = AsyncMock(spec=discord.TextChannel) + channel_mock.send = AsyncMock() + guild_mock = Mock(spec=discord.Guild) + guild_mock.text_channels = [channel_mock] + channel_mock.name = "pd-network-news" + bot.guilds = [guild_mock] + return bot + + +@pytest.fixture +def mock_interaction(): + """Mock Discord interaction for slash commands.""" + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.response.is_done = Mock(return_value=False) + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + + interaction.user = Mock(spec=discord.Member) + interaction.user.id = 12345 + interaction.user.mention = "<@12345>" + + interaction.channel = Mock(spec=discord.TextChannel) + interaction.channel.name = "pack-openings" + interaction.channel.send = AsyncMock() + + return interaction + + +@pytest.fixture +def mock_channel(): + """Mock #pack-openings channel.""" + channel = AsyncMock(spec=discord.TextChannel) + channel.name = "pack-openings" + channel.send = AsyncMock() + return channel + + +# --------------------------------------------------------------------------- +# Logging suppression +# --------------------------------------------------------------------------- + + +@pytest.fixture(autouse=True) +def silence_logging(): + """Suppress log noise during tests.""" + import logging + + logging.getLogger("discord_app").setLevel(logging.CRITICAL) diff --git a/tests/scouting/test_scout_view.py b/tests/scouting/test_scout_view.py new file mode 100644 index 0000000..10853a0 --- /dev/null +++ b/tests/scouting/test_scout_view.py @@ -0,0 +1,1029 @@ +"""Tests for discord_ui/scout_view.py — ScoutView and ScoutButton behavior. + +Covers view initialization, button callbacks (guard rails, claim flow, +token checks, multi-scout), embed updates, and timeout handling. + +Note: All tests that instantiate ScoutView must be async because +discord.ui.View.__init__ requires a running event loop. +""" + +import pytest +from unittest.mock import AsyncMock, MagicMock, Mock, patch + +import discord + +from discord_ui.scout_view import ScoutView, ScoutButton, SCOUT_TOKENS_PER_DAY + +# --------------------------------------------------------------------------- +# ScoutView initialization +# --------------------------------------------------------------------------- + + +class TestScoutViewInit: + """Tests for ScoutView construction and initial state.""" + + @pytest.mark.asyncio + async def test_creates_one_button_per_card( + self, sample_cards, opener_team, mock_bot + ): + """Should add exactly one button per card in the pack.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + buttons = [c for c in view.children if isinstance(c, discord.ui.Button)] + assert len(buttons) == len(sample_cards) + + @pytest.mark.asyncio + async def test_buttons_labeled_sequentially( + self, sample_cards, opener_team, mock_bot + ): + """Buttons should be labeled 'Card 1', 'Card 2', etc.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + labels = [c.label for c in view.children if isinstance(c, discord.ui.Button)] + expected = [f"Card {i + 1}" for i in range(len(sample_cards))] + assert labels == expected + + @pytest.mark.asyncio + async def test_buttons_are_secondary_style( + self, sample_cards, opener_team, mock_bot + ): + """All buttons should start with the gray/secondary style (face-down).""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + for btn in view.children: + if isinstance(btn, discord.ui.Button): + assert btn.style == discord.ButtonStyle.secondary + + @pytest.mark.asyncio + async def test_initial_state_is_clean(self, sample_cards, opener_team, mock_bot): + """Claims, scouted_users, and processing_users should all start empty.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + assert view.claims == {} + assert view.scouted_users == set() + assert view.processing_users == set() + assert view.total_scouts == 0 + + @pytest.mark.asyncio + async def test_timeout_is_30_minutes(self, sample_cards, opener_team, mock_bot): + """The view timeout should be 1800 seconds (30 minutes).""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + assert view.timeout == 1800.0 + + +# --------------------------------------------------------------------------- +# ScoutButton callback — guard rails +# --------------------------------------------------------------------------- + + +class TestScoutButtonGuards: + """Tests for the access control checks in ScoutButton.callback.""" + + def _make_view(self, sample_cards, opener_team, mock_bot): + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + return view + + @pytest.mark.asyncio + async def test_opener_blocked(self, sample_cards, opener_team, mock_bot): + """The pack opener should be rejected with an ephemeral message.""" + view = self._make_view(sample_cards, opener_team, mock_bot) + button = view.children[0] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.user = Mock() + interaction.user.id = 99999 # same as opener + + await button.callback(interaction) + + interaction.response.send_message.assert_called_once() + call_kwargs = interaction.response.send_message.call_args[1] + assert call_kwargs["ephemeral"] is True + assert "own pack" in interaction.response.send_message.call_args[0][0].lower() + + @pytest.mark.asyncio + async def test_already_scouted_blocked(self, sample_cards, opener_team, mock_bot): + """A user who already scouted this pack should be rejected.""" + view = self._make_view(sample_cards, opener_team, mock_bot) + view.scouted_users.add(12345) + button = view.children[0] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await button.callback(interaction) + + interaction.response.send_message.assert_called_once() + assert ( + "already scouted" + in interaction.response.send_message.call_args[0][0].lower() + ) + + @pytest.mark.asyncio + async def test_double_click_silently_ignored( + self, sample_cards, opener_team, mock_bot + ): + """If a user is already being processed, the click should be silently dropped.""" + view = self._make_view(sample_cards, opener_team, mock_bot) + view.processing_users.add(12345) + button = view.children[0] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.user = Mock() + interaction.user.id = 12345 + + await button.callback(interaction) + + # Should not have called defer or send_message + interaction.response.defer.assert_not_called() + + +# --------------------------------------------------------------------------- +# ScoutButton callback — successful scout flow +# --------------------------------------------------------------------------- + + +class TestScoutButtonSuccess: + """Tests for the happy-path scout claim flow.""" + + def _make_view_with_message(self, sample_cards, opener_team, mock_bot): + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + return view + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_successful_scout_creates_card_copy( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """A valid scout should POST a scout_claim, consume a token, and create a card copy.""" + view = self._make_view_with_message(sample_cards, opener_team, mock_bot) + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.response.send_message = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + button = view.children[0] + await button.callback(interaction) + + # Should have deferred + interaction.response.defer.assert_called_once_with(ephemeral=True) + + # db_post should be called 3 times: scout_claims, rewards, cards + assert mock_db_post.call_count == 3 + + # Verify scout_claims POST + claim_call = mock_db_post.call_args_list[0] + assert claim_call[0][0] == "scout_claims" + + # Verify rewards POST (token consumption) + reward_call = mock_db_post.call_args_list[1] + assert reward_call[0][0] == "rewards" + assert reward_call[1]["payload"]["name"] == "Scout Token" + + # Verify cards POST (card copy) + card_call = mock_db_post.call_args_list[2] + assert card_call[0][0] == "cards" + + # User should be marked as scouted + assert 12345 in view.scouted_users + assert view.total_scouts == 1 + + # Ephemeral follow-up with card details + interaction.followup.send.assert_called() + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_no_team_rejects( + self, + mock_get_team, + mock_db_post, + sample_cards, + opener_team, + mock_bot, + ): + """A user without a PD team should be rejected with an ephemeral message.""" + view = self._make_view_with_message(sample_cards, opener_team, mock_bot) + mock_get_team.return_value = None + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + button = view.children[0] + await button.callback(interaction) + + interaction.followup.send.assert_called_once() + msg = interaction.followup.send.call_args[0][0] + assert "team" in msg.lower() + assert mock_db_post.call_count == 0 + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_out_of_tokens_rejects( + self, + mock_get_team, + mock_get_tokens, + mock_db_post, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """A user who has used all daily tokens should be rejected.""" + view = self._make_view_with_message(sample_cards, opener_team, mock_bot) + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = SCOUT_TOKENS_PER_DAY # all used + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + button = view.children[0] + await button.callback(interaction) + + interaction.followup.send.assert_called_once() + msg = interaction.followup.send.call_args[0][0] + assert "out of scout tokens" in msg.lower() + assert mock_db_post.call_count == 0 + + +# --------------------------------------------------------------------------- +# Multi-scout behavior +# --------------------------------------------------------------------------- + + +class TestMultiScout: + """Tests for the multi-scout-per-card design. + + Any card can be scouted by multiple different players, but each player + can only scout one card per pack. + """ + + def _make_view_with_message(self, sample_cards, opener_team, mock_bot): + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + return view + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_two_users_can_scout_same_card( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + sample_cards, + opener_team, + scouter_team, + scouter_team_2, + mock_bot, + ): + """Two different users should both be able to scout the same card.""" + view = self._make_view_with_message(sample_cards, opener_team, mock_bot) + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + button = view.children[0] # both pick the same card + + # First scouter + mock_get_team.return_value = scouter_team + interaction1 = AsyncMock(spec=discord.Interaction) + interaction1.response = AsyncMock() + interaction1.response.defer = AsyncMock() + interaction1.followup = AsyncMock() + interaction1.followup.send = AsyncMock() + interaction1.user = Mock() + interaction1.user.id = 11111 + + await button.callback(interaction1) + assert 11111 in view.scouted_users + assert view.total_scouts == 1 + + # Second scouter — same card + mock_get_team.return_value = scouter_team_2 + interaction2 = AsyncMock(spec=discord.Interaction) + interaction2.response = AsyncMock() + interaction2.response.defer = AsyncMock() + interaction2.followup = AsyncMock() + interaction2.followup.send = AsyncMock() + interaction2.user = Mock() + interaction2.user.id = 22222 + + await button.callback(interaction2) + assert 22222 in view.scouted_users + assert view.total_scouts == 2 + + # Claims should track both teams under the same player_id + player_id = sample_cards[0]["player"]["player_id"] + assert player_id in view.claims + assert len(view.claims[player_id]) == 2 + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_same_user_cannot_scout_twice( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """The same user should be blocked from scouting a second card.""" + view = self._make_view_with_message(sample_cards, opener_team, mock_bot) + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + # First scout succeeds + interaction1 = AsyncMock(spec=discord.Interaction) + interaction1.response = AsyncMock() + interaction1.response.defer = AsyncMock() + interaction1.followup = AsyncMock() + interaction1.followup.send = AsyncMock() + interaction1.user = Mock() + interaction1.user.id = 12345 + + await view.children[0].callback(interaction1) + assert view.total_scouts == 1 + + # Second scout by same user is blocked + interaction2 = AsyncMock(spec=discord.Interaction) + interaction2.response = AsyncMock() + interaction2.response.send_message = AsyncMock() + interaction2.user = Mock() + interaction2.user.id = 12345 + + await view.children[1].callback(interaction2) + + interaction2.response.send_message.assert_called_once() + assert ( + "already scouted" + in interaction2.response.send_message.call_args[0][0].lower() + ) + assert view.total_scouts == 1 # unchanged + + @pytest.mark.asyncio + async def test_buttons_never_disabled_after_scout( + self, sample_cards, opener_team, mock_bot + ): + """All buttons should remain enabled regardless of how many scouts happen. + + This verifies the 'unlimited scouts per card' design — buttons + only disable on timeout, not on individual claims. + """ + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + # Simulate claims on every card + for card in sample_cards: + pid = card["player"]["player_id"] + view.claims[pid] = ["Team A", "Team B"] + + for btn in view.children: + if isinstance(btn, discord.ui.Button): + assert not btn.disabled + + +# --------------------------------------------------------------------------- +# ScoutView.on_timeout +# --------------------------------------------------------------------------- + + +class TestScoutViewTimeout: + """Tests for the timeout handler that closes the scout window.""" + + @pytest.mark.asyncio + async def test_timeout_disables_all_buttons( + self, sample_cards, opener_team, mock_bot + ): + """After timeout, every button should be disabled.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + await view.on_timeout() + + for btn in view.children: + if isinstance(btn, discord.ui.Button): + assert btn.disabled + + @pytest.mark.asyncio + async def test_timeout_updates_embed_title( + self, sample_cards, opener_team, mock_bot + ): + """The embed title should change to 'Scout Window Closed' on timeout.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + await view.on_timeout() + + view.message.edit.assert_called_once() + call_kwargs = view.message.edit.call_args[1] + embed = call_kwargs["embed"] + assert "closed" in embed.title.lower() + + @pytest.mark.asyncio + async def test_timeout_with_scouts_shows_count( + self, sample_cards, opener_team, mock_bot + ): + """When there were scouts, the closed title should include the count.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.total_scouts = 5 + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + await view.on_timeout() + + embed = view.message.edit.call_args[1]["embed"] + assert "5" in embed.title + + @pytest.mark.asyncio + async def test_timeout_without_message_is_safe( + self, sample_cards, opener_team, mock_bot + ): + """Timeout should not crash if the message reference is None.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.message = None + + # Should not raise + await view.on_timeout() + + +# --------------------------------------------------------------------------- +# Processing user cleanup +# --------------------------------------------------------------------------- + + +class TestProcessingUserCleanup: + """Verify the processing_users set is cleaned up in all code paths.""" + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_processing_cleared_on_success( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """After a successful scout, the user should be removed from processing_users.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await view.children[0].callback(interaction) + + assert 12345 not in view.processing_users + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_processing_cleared_on_claim_db_failure( + self, + mock_get_team, + mock_get_tokens, + mock_db_post, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """If db_post('scout_claims') raises, processing_users should still be cleared.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_post.side_effect = Exception("DB down") + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await view.children[0].callback(interaction) + + assert 12345 not in view.processing_users + # Scout should not have been recorded + assert view.total_scouts == 0 + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_processing_cleared_on_no_team( + self, + mock_get_team, + sample_cards, + opener_team, + mock_bot, + ): + """If the user has no team, they should still be removed from processing_users.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + mock_get_team.return_value = None + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await view.children[0].callback(interaction) + + assert 12345 not in view.processing_users + + +# --------------------------------------------------------------------------- +# db_get("current") fallback +# --------------------------------------------------------------------------- + + +class TestCurrentSeasonFallback: + """Tests for the fallback when db_get('current') returns None.""" + + @pytest.mark.asyncio + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_current_returns_none_uses_fallback( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """When db_get('current') returns None, rewards should use PD_SEASON fallback.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = None # db_get("current") returns None + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await view.children[0].callback(interaction) + + # Should still complete successfully + assert view.total_scouts == 1 + assert 12345 in view.scouted_users + + # Verify the rewards POST used fallback values + from helpers.constants import PD_SEASON + + reward_call = mock_db_post.call_args_list[1] + assert reward_call[1]["payload"]["season"] == PD_SEASON + assert reward_call[1]["payload"]["week"] == 1 + + +# --------------------------------------------------------------------------- +# Shiny scout notification +# --------------------------------------------------------------------------- + + +class TestShinyScoutNotification: + """Tests for the rare-card notification path (rarity >= 5).""" + + @pytest.mark.asyncio + @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_shiny_card_sends_notification( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + mock_send_to_channel, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """Scouting a card with rarity >= 5 should post to #pd-network-news.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, # card 0 is MVP (rarity 5) + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + # Card 0 is MVP (rarity value 5) — should trigger notification + await view.children[0].callback(interaction) + + mock_send_to_channel.assert_called_once() + call_args = mock_send_to_channel.call_args + assert call_args[0][1] == "pd-network-news" + + @pytest.mark.asyncio + @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_non_shiny_card_no_notification( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + mock_send_to_channel, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """Scouting a card with rarity < 5 should NOT post a notification.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, # card 2 is Starter (rarity 2) + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + # Card 2 is Starter (rarity value 2) — no notification + await view.children[2].callback(interaction) + + mock_send_to_channel.assert_not_called() + + @pytest.mark.asyncio + @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) + @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) + @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) + async def test_shiny_notification_failure_does_not_crash( + self, + mock_get_team, + mock_get_tokens, + mock_db_get, + mock_db_post, + mock_card_embeds, + mock_send_to_channel, + sample_cards, + opener_team, + scouter_team, + mock_bot, + ): + """If sending the shiny notification fails, the scout should still succeed.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock() + + mock_get_team.return_value = scouter_team + mock_get_tokens.return_value = 0 + mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") + mock_db_post.return_value = {"id": 100} + mock_card_embeds.return_value = [Mock(spec=discord.Embed)] + mock_send_to_channel.side_effect = Exception("Channel not found") + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + # Should not raise even though notification fails + await view.children[0].callback(interaction) + + # Scout should still complete + assert view.total_scouts == 1 + assert 12345 in view.scouted_users + + +# --------------------------------------------------------------------------- +# update_message edge cases +# --------------------------------------------------------------------------- + + +class TestUpdateMessage: + """Tests for ScoutView.update_message edge cases.""" + + @pytest.mark.asyncio + async def test_update_message_with_no_message_is_noop( + self, sample_cards, opener_team, mock_bot + ): + """update_message should silently return if self.message is None.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = None + + # Should not raise + await view.update_message() + + @pytest.mark.asyncio + async def test_update_message_edit_failure_is_caught( + self, sample_cards, opener_team, mock_bot + ): + """If message.edit raises, it should be caught and logged, not re-raised.""" + view = ScoutView( + scout_opp_id=1, + cards=sample_cards, + opener_team=opener_team, + opener_user_id=99999, + bot=mock_bot, + ) + view.card_lines = [ + (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) + ] + view.message = AsyncMock(spec=discord.Message) + view.message.edit = AsyncMock( + side_effect=discord.HTTPException(Mock(status=500), "Server error") + ) + + # Should not raise + await view.update_message() diff --git a/tests/scouting/test_scouting_cog.py b/tests/scouting/test_scouting_cog.py new file mode 100644 index 0000000..5bca155 --- /dev/null +++ b/tests/scouting/test_scouting_cog.py @@ -0,0 +1,269 @@ +"""Tests for cogs/economy_new/scouting.py — the Scouting cog. + +Covers the /scout-tokens command and the cleanup_expired background task. + +Note: Scouting.__init__ calls self.cleanup_expired.start() which requires +a running event loop. All tests that instantiate the cog must be async. +""" + +import datetime + +import pytest +from unittest.mock import AsyncMock, MagicMock, Mock, patch + +import discord +from discord.ext import commands + +from cogs.economy_new.scouting import Scouting, SCOUT_TOKENS_PER_DAY + + +def _make_team(): + return { + "id": 1, + "lname": "Test Team", + "color": "a6ce39", + "logo": "https://example.com/logo.png", + "season": 4, + } + + +# --------------------------------------------------------------------------- +# Cog setup +# --------------------------------------------------------------------------- + + +class TestScoutingCogSetup: + """Tests for cog initialization and lifecycle.""" + + @pytest.mark.asyncio + async def test_cog_initializes(self, mock_bot): + """The Scouting cog should initialize without errors.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + assert cog.bot is mock_bot + + @pytest.mark.asyncio + async def test_cleanup_task_starts(self, mock_bot): + """The cleanup_expired loop task should be started on init.""" + cog = Scouting(mock_bot) + assert cog.cleanup_expired.is_running() + cog.cleanup_expired.cancel() + + @pytest.mark.asyncio + async def test_cog_unload_calls_cancel(self, mock_bot): + """Unloading the cog should call cancel on the cleanup task.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + # Verify cog_unload runs without error + await cog.cog_unload() + + +# --------------------------------------------------------------------------- +# /scout-tokens command +# --------------------------------------------------------------------------- + + +class TestScoutTokensCommand: + """Tests for the /scout-tokens slash command.""" + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_shows_remaining_tokens( + self, mock_get_team, mock_get_tokens, mock_bot + ): + """Should display the correct number of remaining tokens.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = _make_team() + mock_get_tokens.return_value = 1 # 1 used today + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + interaction.response.defer.assert_called_once_with(ephemeral=True) + interaction.followup.send.assert_called_once() + + call_kwargs = interaction.followup.send.call_args[1] + embed = call_kwargs["embed"] + remaining = SCOUT_TOKENS_PER_DAY - 1 + assert str(remaining) in embed.description + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_no_team_rejects(self, mock_get_team, mock_get_tokens, mock_bot): + """A user without a PD team should get a rejection message.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = None + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + msg = interaction.followup.send.call_args[0][0] + assert "team" in msg.lower() + mock_get_tokens.assert_not_called() + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_all_tokens_used_shows_zero( + self, mock_get_team, mock_get_tokens, mock_bot + ): + """When all tokens are used, should show 0 remaining with extra message.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = _make_team() + mock_get_tokens.return_value = SCOUT_TOKENS_PER_DAY + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + embed = interaction.followup.send.call_args[1]["embed"] + assert "0" in embed.description + assert ( + "used all" in embed.description.lower() + or "tomorrow" in embed.description.lower() + ) + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_no_tokens_used_shows_full( + self, mock_get_team, mock_get_tokens, mock_bot + ): + """When no tokens have been used, should show the full daily allowance.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = _make_team() + mock_get_tokens.return_value = 0 + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + embed = interaction.followup.send.call_args[1]["embed"] + assert str(SCOUT_TOKENS_PER_DAY) in embed.description + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_db_get_returns_none(self, mock_get_team, mock_get_tokens, mock_bot): + """If get_scout_tokens_used returns 0 (API failure handled internally), should show full tokens.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = _make_team() + mock_get_tokens.return_value = ( + 0 # get_scout_tokens_used handles None internally + ) + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + embed = interaction.followup.send.call_args[1]["embed"] + assert str(SCOUT_TOKENS_PER_DAY) in embed.description + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.get_scout_tokens_used", new_callable=AsyncMock) + @patch("cogs.economy_new.scouting.get_team_by_owner", new_callable=AsyncMock) + async def test_over_limit_tokens_shows_zero( + self, mock_get_team, mock_get_tokens, mock_bot + ): + """If somehow more tokens than the daily limit were used, should show 0 not negative.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_get_team.return_value = _make_team() + mock_get_tokens.return_value = 5 # more than SCOUT_TOKENS_PER_DAY + + interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.defer = AsyncMock() + interaction.followup = AsyncMock() + interaction.followup.send = AsyncMock() + interaction.user = Mock() + interaction.user.id = 12345 + + await cog.scout_tokens_command.callback(cog, interaction) + + embed = interaction.followup.send.call_args[1]["embed"] + # Should show "0" not "-3" + assert "0" in embed.description + assert "-" not in embed.description.split("remaining")[0] + + +# --------------------------------------------------------------------------- +# cleanup_expired task +# --------------------------------------------------------------------------- + + +class TestCleanupExpired: + """Tests for the background cleanup task.""" + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.db_get", new_callable=AsyncMock) + async def test_cleanup_logs_expired_opportunities(self, mock_db_get, mock_bot): + """The cleanup task should query for expired unclaimed opportunities.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_db_get.return_value = {"count": 3} + + # Call the coroutine directly (not via the loop) + await cog.cleanup_expired.coro(cog) + + mock_db_get.assert_called_once() + call_args = mock_db_get.call_args + assert call_args[0][0] == "scout_opportunities" + + @pytest.mark.asyncio + @patch("cogs.economy_new.scouting.db_get", new_callable=AsyncMock) + async def test_cleanup_handles_api_failure(self, mock_db_get, mock_bot): + """Cleanup should not crash if the API is unavailable.""" + cog = Scouting(mock_bot) + cog.cleanup_expired.cancel() + + mock_db_get.side_effect = Exception("API not ready") + + # Should not raise + await cog.cleanup_expired.coro(cog) diff --git a/tests/scouting/test_scouting_helpers.py b/tests/scouting/test_scouting_helpers.py new file mode 100644 index 0000000..dc635da --- /dev/null +++ b/tests/scouting/test_scouting_helpers.py @@ -0,0 +1,374 @@ +"""Tests for helpers/scouting.py — embed builders and scout opportunity creation. + +Covers the pure functions (_build_card_lines, build_scout_embed, +build_scouted_card_list) and the async create_scout_opportunity flow. +""" + +import pytest +from unittest.mock import AsyncMock, MagicMock, Mock, patch + +import discord + +from helpers.scouting import ( + _build_card_lines, + build_scout_embed, + build_scouted_card_list, + create_scout_opportunity, + RARITY_SYMBOLS, +) + +# --------------------------------------------------------------------------- +# _build_card_lines +# --------------------------------------------------------------------------- + + +class TestBuildCardLines: + """Tests for the shuffled card line builder.""" + + def test_returns_correct_count(self, sample_cards): + """Should produce one line per card in the pack.""" + lines = _build_card_lines(sample_cards) + assert len(lines) == len(sample_cards) + + def test_each_line_contains_player_id(self, sample_cards): + """Each tuple's first element should be the player_id from the card.""" + lines = _build_card_lines(sample_cards) + ids = {pid for pid, _ in lines} + expected_ids = {c["player"]["player_id"] for c in sample_cards} + assert ids == expected_ids + + def test_each_line_contains_player_name(self, sample_cards): + """The display string should include the player's name.""" + lines = _build_card_lines(sample_cards) + for pid, display in lines: + card = next(c for c in sample_cards if c["player"]["player_id"] == pid) + assert card["player"]["p_name"] in display + + def test_each_line_contains_rarity_name(self, sample_cards): + """The display string should include the rarity tier name.""" + lines = _build_card_lines(sample_cards) + for pid, display in lines: + card = next(c for c in sample_cards if c["player"]["player_id"] == pid) + assert card["player"]["rarity"]["name"] in display + + def test_rarity_symbol_present(self, sample_cards): + """Each line should start with the appropriate rarity emoji.""" + lines = _build_card_lines(sample_cards) + for pid, display in lines: + card = next(c for c in sample_cards if c["player"]["player_id"] == pid) + rarity_val = card["player"]["rarity"]["value"] + expected_symbol = RARITY_SYMBOLS.get(rarity_val, "\u26ab") + assert display.startswith(expected_symbol) + + def test_output_is_shuffled(self, sample_cards): + """Over many runs, the order should not always match the input order. + + We run 20 iterations — if it comes out sorted every time, the shuffle + is broken (probability ~1/20! per run, effectively zero). + """ + input_order = [c["player"]["player_id"] for c in sample_cards] + saw_different = False + for _ in range(20): + lines = _build_card_lines(sample_cards) + output_order = [pid for pid, _ in lines] + if output_order != input_order: + saw_different = True + break + assert saw_different, "Card lines were never shuffled across 20 runs" + + def test_empty_cards(self): + """Empty input should produce an empty list.""" + assert _build_card_lines([]) == [] + + def test_unknown_rarity_uses_fallback_symbol(self): + """A rarity value not in RARITY_SYMBOLS should get the black circle fallback.""" + card = { + "id": 99, + "player": { + "player_id": 999, + "p_name": "Unknown Rarity", + "rarity": {"name": "Legendary", "value": 99, "color": "gold"}, + }, + } + lines = _build_card_lines([card]) + assert lines[0][1].startswith("\u26ab") # black circle fallback + + +# --------------------------------------------------------------------------- +# build_scout_embed +# --------------------------------------------------------------------------- + + +class TestBuildScoutEmbed: + """Tests for the embed builder shown above scout buttons.""" + + def test_returns_embed_and_card_lines(self, opener_team, sample_cards): + """Should return a (discord.Embed, list) tuple.""" + embed, card_lines = build_scout_embed(opener_team, sample_cards) + assert isinstance(embed, discord.Embed) + assert isinstance(card_lines, list) + assert len(card_lines) == len(sample_cards) + + def test_embed_description_contains_team_name(self, opener_team, sample_cards): + """The embed body should mention the opener's team name.""" + embed, _ = build_scout_embed(opener_team, sample_cards) + assert opener_team["lname"] in embed.description + + def test_embed_description_contains_all_player_names( + self, opener_team, sample_cards + ): + """Every player name from the pack should appear in the embed.""" + embed, _ = build_scout_embed(opener_team, sample_cards) + for card in sample_cards: + assert card["player"]["p_name"] in embed.description + + def test_embed_mentions_token_cost(self, opener_team, sample_cards): + """The embed should tell users about the scout token cost.""" + embed, _ = build_scout_embed(opener_team, sample_cards) + assert "Scout Token" in embed.description + + def test_embed_mentions_time_limit(self, opener_team, sample_cards): + """The embed should mention the 30-minute window.""" + embed, _ = build_scout_embed(opener_team, sample_cards) + assert "30 minutes" in embed.description + + def test_prebuilt_card_lines_are_reused(self, opener_team, sample_cards): + """When card_lines are passed in, they should be reused (not rebuilt).""" + prebuilt = [(101, "Custom Line 1"), (102, "Custom Line 2")] + embed, returned_lines = build_scout_embed( + opener_team, sample_cards, card_lines=prebuilt + ) + assert returned_lines is prebuilt + assert "Custom Line 1" in embed.description + assert "Custom Line 2" in embed.description + + +# --------------------------------------------------------------------------- +# build_scouted_card_list +# --------------------------------------------------------------------------- + + +class TestBuildScoutedCardList: + """Tests for the card list formatter that marks scouted cards.""" + + def test_no_scouts_returns_plain_lines(self): + """With no scouts, output should match the raw card lines.""" + card_lines = [ + (101, "\U0001f7e3 MVP — Mike Trout"), + (102, "\U0001f535 All-Star — Juan Soto"), + ] + result = build_scouted_card_list(card_lines, {}) + assert result == "\U0001f7e3 MVP — Mike Trout\n\U0001f535 All-Star — Juan Soto" + + def test_single_scout_shows_team_name(self): + """A card scouted once should show a checkmark and the team name.""" + card_lines = [ + (101, "\U0001f7e3 MVP — Mike Trout"), + (102, "\U0001f535 All-Star — Juan Soto"), + ] + scouted = {101: ["Scouting Squad"]} + result = build_scouted_card_list(card_lines, scouted) + assert "\u2714\ufe0f" in result # checkmark + assert "*Scouting Squad*" in result + # Unscouted card should appear plain + lines = result.split("\n") + assert "\u2714" not in lines[1] + + def test_multiple_scouts_shows_count_and_names(self): + """A card scouted multiple times should show the count and all team names.""" + card_lines = [(101, "\U0001f7e3 MVP — Mike Trout")] + scouted = {101: ["Team A", "Team B", "Team C"]} + result = build_scouted_card_list(card_lines, scouted) + assert "x3" in result + assert "*Team A*" in result + assert "*Team B*" in result + assert "*Team C*" in result + + def test_mixed_scouted_and_unscouted(self): + """Only scouted cards should have marks; unscouted cards stay plain.""" + card_lines = [ + (101, "Line A"), + (102, "Line B"), + (103, "Line C"), + ] + scouted = {102: ["Some Team"]} + result = build_scouted_card_list(card_lines, scouted) + lines = result.split("\n") + assert "\u2714" not in lines[0] + assert "\u2714" in lines[1] + assert "\u2714" not in lines[2] + + def test_empty_input(self): + """Empty card lines should produce an empty string.""" + assert build_scouted_card_list([], {}) == "" + + def test_two_scouts_shows_count(self): + """Two scouts on the same card should show x2.""" + card_lines = [(101, "Line A")] + scouted = {101: ["Team X", "Team Y"]} + result = build_scouted_card_list(card_lines, scouted) + assert "x2" in result + + +# --------------------------------------------------------------------------- +# create_scout_opportunity +# --------------------------------------------------------------------------- + + +class TestCreateScoutOpportunity: + """Tests for the async scout opportunity creation flow.""" + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_posts_to_api_and_sends_message( + self, mock_db_post, sample_cards, opener_team, mock_channel, mock_bot + ): + """Should POST to scout_opportunities and send a message to the channel.""" + mock_db_post.return_value = {"id": 42} + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + await create_scout_opportunity( + sample_cards, opener_team, mock_channel, opener_user, context + ) + + # API was called to create the opportunity + mock_db_post.assert_called_once() + call_args = mock_db_post.call_args + assert call_args[0][0] == "scout_opportunities" + assert call_args[1]["payload"]["opener_team_id"] == opener_team["id"] + + # Message was sent to the channel + mock_channel.send.assert_called_once() + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_skips_wrong_channel( + self, mock_db_post, sample_cards, opener_team, mock_bot + ): + """Should silently return when the channel is not #pack-openings.""" + channel = AsyncMock(spec=discord.TextChannel) + channel.name = "general" + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + await create_scout_opportunity( + sample_cards, opener_team, channel, opener_user, context + ) + + mock_db_post.assert_not_called() + channel.send.assert_not_called() + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_skips_empty_pack( + self, mock_db_post, opener_team, mock_channel, mock_bot + ): + """Should silently return when pack_cards is empty.""" + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + await create_scout_opportunity( + [], opener_team, mock_channel, opener_user, context + ) + + mock_db_post.assert_not_called() + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_skips_none_channel( + self, mock_db_post, sample_cards, opener_team, mock_bot + ): + """Should handle None channel without crashing.""" + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + await create_scout_opportunity( + sample_cards, opener_team, None, opener_user, context + ) + + mock_db_post.assert_not_called() + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_api_failure_does_not_raise( + self, mock_db_post, sample_cards, opener_team, mock_channel, mock_bot + ): + """Scout creation failure must never crash the pack opening flow.""" + mock_db_post.side_effect = Exception("API down") + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + # Should not raise + await create_scout_opportunity( + sample_cards, opener_team, mock_channel, opener_user, context + ) + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_channel_send_failure_does_not_raise( + self, mock_db_post, sample_cards, opener_team, mock_channel, mock_bot + ): + """If the channel.send fails, it should be caught gracefully.""" + mock_db_post.return_value = {"id": 42} + mock_channel.send.side_effect = discord.HTTPException( + Mock(status=500), "Server error" + ) + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + # Should not raise + await create_scout_opportunity( + sample_cards, opener_team, mock_channel, opener_user, context + ) + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_context_client_fallback( + self, mock_db_post, sample_cards, opener_team, mock_channel, mock_bot + ): + """When context.bot is None, should fall back to context.client for the bot ref.""" + mock_db_post.return_value = {"id": 42} + opener_user = Mock() + opener_user.id = 99999 + context = Mock(spec=[]) # empty spec — no .bot attribute + context.client = mock_bot + + await create_scout_opportunity( + sample_cards, opener_team, mock_channel, opener_user, context + ) + + mock_channel.send.assert_called_once() + + @pytest.mark.asyncio + @patch("helpers.scouting.db_post", new_callable=AsyncMock) + async def test_view_message_is_assigned( + self, mock_db_post, sample_cards, opener_team, mock_channel, mock_bot + ): + """The message returned by channel.send should be assigned to view.message. + + This linkage is required for update_message and on_timeout to work. + """ + mock_db_post.return_value = {"id": 42} + sent_msg = AsyncMock(spec=discord.Message) + mock_channel.send.return_value = sent_msg + opener_user = Mock() + opener_user.id = 99999 + context = Mock() + context.bot = mock_bot + + await create_scout_opportunity( + sample_cards, opener_team, mock_channel, opener_user, context + ) -- 2.25.1 From d569e9190507bdbc0ea1603e2976f8935d19f724 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Wed, 4 Mar 2026 19:39:43 -0600 Subject: [PATCH 03/12] =?UTF-8?q?fix:=20Address=20PR=20review=20findings?= =?UTF-8?q?=20=E2=80=94=20two=20bugs=20and=20cleanup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix int_timestamp() no-arg path returning seconds instead of milliseconds, which would silently break the daily scout token cap against the real API - Acknowledge double-click interactions with ephemeral message instead of silently returning (Discord requires all interactions to be acked) - Reorder scout flow: create card copy before consuming token so a failure doesn't cost the player a token for nothing - Move build_scouted_card_list import to top of scout_view.py - Remove unused asyncio import from helpers/scouting.py - Fix footer text inconsistency ("One scout per player" everywhere) - Update tests for new operation order and double-click behavior Co-Authored-By: Claude Opus 4.6 --- discord_ui/scout_view.py | 39 ++++++++++++++++++------------- helpers/scouting.py | 3 +-- helpers/utils.py | 11 +++++---- tests/scouting/test_scout_view.py | 31 +++++++++++++++--------- 4 files changed, 51 insertions(+), 33 deletions(-) diff --git a/discord_ui/scout_view.py b/discord_ui/scout_view.py index 11ce77a..0d5a12f 100644 --- a/discord_ui/scout_view.py +++ b/discord_ui/scout_view.py @@ -13,7 +13,11 @@ import discord from api_calls import db_get, db_post from helpers.main import get_team_by_owner, get_card_embeds -from helpers.scouting import SCOUT_TOKENS_PER_DAY, get_scout_tokens_used +from helpers.scouting import ( + SCOUT_TOKENS_PER_DAY, + build_scouted_card_list, + get_scout_tokens_used, +) from helpers.utils import int_timestamp from helpers.discord_utils import get_team_embed from helpers.constants import IMAGES, PD_SEASON @@ -72,8 +76,6 @@ class ScoutView(discord.ui.View): if not self.message: return - from helpers.scouting import build_scouted_card_list - card_list = build_scouted_card_list(self.card_lines, self.claims) title = f"Scout Opportunity! ({self.total_scouts} scouted)" @@ -163,6 +165,10 @@ class ScoutButton(discord.ui.Button): # Prevent double-click race for same user if interaction.user.id in view.processing_users: + await interaction.response.send_message( + "Your scout is already being processed!", + ephemeral=True, + ) return view.processing_users.add(interaction.user.id) @@ -206,6 +212,20 @@ class ScoutButton(discord.ui.Button): ) return + # Create a copy of the card for the scouter (before consuming token + # so a failure here doesn't cost the player a token for nothing) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": self.card["player"]["player_id"], + "team_id": scouter_team["id"], + } + ], + }, + ) + # Consume a scout token current = await db_get("current") await db_post( @@ -219,19 +239,6 @@ class ScoutButton(discord.ui.Button): }, ) - # Create a copy of the card for the scouter - await db_post( - "cards", - payload={ - "cards": [ - { - "player_id": self.card["player"]["player_id"], - "team_id": scouter_team["id"], - } - ], - }, - ) - # Track the claim player_id = self.card["player"]["player_id"] if player_id not in view.claims: diff --git a/helpers/scouting.py b/helpers/scouting.py index ab2d2c2..a21b9f9 100644 --- a/helpers/scouting.py +++ b/helpers/scouting.py @@ -5,7 +5,6 @@ Handles creation of scout opportunities after pack openings and embed formatting for the scouting feature. """ -import asyncio import datetime import logging import random @@ -95,7 +94,7 @@ def build_scout_embed( f"{time_line}" ) embed.set_footer( - text=f"Paper Dynasty Season {PD_SEASON} \u2022 One player per pack", + text=f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player", icon_url=IMAGES["logo"], ) return embed, card_lines diff --git a/helpers/utils.py b/helpers/utils.py index 7535bf7..8b091ab 100644 --- a/helpers/utils.py +++ b/helpers/utils.py @@ -11,10 +11,13 @@ import discord def int_timestamp(datetime_obj: Optional[datetime.datetime] = None): - """Convert current datetime to integer timestamp.""" - if datetime_obj: - return int(datetime.datetime.timestamp(datetime_obj) * 1000) - return int(datetime.datetime.now().timestamp()) + """Convert a datetime to an integer millisecond timestamp. + + If no argument is given, uses the current time. + """ + if datetime_obj is None: + datetime_obj = datetime.datetime.now() + return int(datetime.datetime.timestamp(datetime_obj) * 1000) def midnight_timestamp() -> int: diff --git a/tests/scouting/test_scout_view.py b/tests/scouting/test_scout_view.py index 10853a0..906bb97 100644 --- a/tests/scouting/test_scout_view.py +++ b/tests/scouting/test_scout_view.py @@ -162,19 +162,26 @@ class TestScoutButtonGuards: async def test_double_click_silently_ignored( self, sample_cards, opener_team, mock_bot ): - """If a user is already being processed, the click should be silently dropped.""" + """If a user is already being processed, they should get an ephemeral rejection.""" view = self._make_view(sample_cards, opener_team, mock_bot) view.processing_users.add(12345) button = view.children[0] interaction = AsyncMock(spec=discord.Interaction) + interaction.response = AsyncMock() + interaction.response.send_message = AsyncMock() interaction.user = Mock() interaction.user.id = 12345 await button.callback(interaction) - # Should not have called defer or send_message - interaction.response.defer.assert_not_called() + interaction.response.send_message.assert_called_once() + call_kwargs = interaction.response.send_message.call_args[1] + assert call_kwargs["ephemeral"] is True + assert ( + "already being processed" + in interaction.response.send_message.call_args[0][0].lower() + ) # --------------------------------------------------------------------------- @@ -242,22 +249,22 @@ class TestScoutButtonSuccess: # Should have deferred interaction.response.defer.assert_called_once_with(ephemeral=True) - # db_post should be called 3 times: scout_claims, rewards, cards + # db_post should be called 3 times: scout_claims, cards, rewards assert mock_db_post.call_count == 3 # Verify scout_claims POST claim_call = mock_db_post.call_args_list[0] assert claim_call[0][0] == "scout_claims" - # Verify rewards POST (token consumption) - reward_call = mock_db_post.call_args_list[1] + # Verify cards POST (card copy — created before token consumption) + card_call = mock_db_post.call_args_list[1] + assert card_call[0][0] == "cards" + + # Verify rewards POST (token consumption — after card is safely created) + reward_call = mock_db_post.call_args_list[2] assert reward_call[0][0] == "rewards" assert reward_call[1]["payload"]["name"] == "Scout Token" - # Verify cards POST (card copy) - card_call = mock_db_post.call_args_list[2] - assert card_call[0][0] == "cards" - # User should be marked as scouted assert 12345 in view.scouted_users assert view.total_scouts == 1 @@ -797,9 +804,11 @@ class TestCurrentSeasonFallback: assert 12345 in view.scouted_users # Verify the rewards POST used fallback values + # Order: scout_claims (0), cards (1), rewards (2) from helpers.constants import PD_SEASON - reward_call = mock_db_post.call_args_list[1] + reward_call = mock_db_post.call_args_list[2] + assert reward_call[0][0] == "rewards" assert reward_call[1]["payload"]["season"] == PD_SEASON assert reward_call[1]["payload"]["week"] == 1 -- 2.25.1 From 89f80727bd2655ac4eb65553ca119b766bb4674b Mon Sep 17 00:00:00 2001 From: cal Date: Thu, 5 Mar 2026 03:12:20 +0000 Subject: [PATCH 04/12] Update .gitea/workflows/docker-build.yml --- .gitea/workflows/docker-build.yml | 31 +++++++++++-------------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/.gitea/workflows/docker-build.yml b/.gitea/workflows/docker-build.yml index a4a0ceb..f286fc9 100644 --- a/.gitea/workflows/docker-build.yml +++ b/.gitea/workflows/docker-build.yml @@ -12,6 +12,7 @@ on: push: branches: - main + - next-release pull_request: branches: - main @@ -39,35 +40,25 @@ jobs: id: calver uses: cal/gitea-actions/calver@main - # Dev build: push with dev + dev-SHA tags (PR/feature branches) - - name: Build Docker image (dev) - if: github.ref != 'refs/heads/main' - uses: https://github.com/docker/build-push-action@v5 + - name: Resolve Docker tags + id: tags + uses: cal/gitea-actions/docker-tags@main with: - context: . - push: true - tags: | - manticorum67/paper-dynasty-discordapp:dev - manticorum67/paper-dynasty-discordapp:dev-${{ steps.calver.outputs.sha_short }} - cache-from: type=registry,ref=manticorum67/paper-dynasty-discordapp:buildcache - cache-to: type=registry,ref=manticorum67/paper-dynasty-discordapp:buildcache,mode=max + image: manticorum67/paper-dynasty-discordapp + version: ${{ steps.calver.outputs.version }} + sha_short: ${{ steps.calver.outputs.sha_short }} - # Production build: push with latest + CalVer tags (main only) - - name: Build Docker image (production) - if: github.ref == 'refs/heads/main' + - name: Build and push Docker image uses: https://github.com/docker/build-push-action@v5 with: context: . push: true - tags: | - manticorum67/paper-dynasty-discordapp:latest - manticorum67/paper-dynasty-discordapp:${{ steps.calver.outputs.version }} - manticorum67/paper-dynasty-discordapp:${{ steps.calver.outputs.version_sha }} + tags: ${{ steps.tags.outputs.tags }} cache-from: type=registry,ref=manticorum67/paper-dynasty-discordapp:buildcache cache-to: type=registry,ref=manticorum67/paper-dynasty-discordapp:buildcache,mode=max - name: Tag release - if: success() && github.ref == 'refs/heads/main' + if: success() && steps.tags.outputs.channel == 'stable' uses: cal/gitea-actions/gitea-tag@main with: version: ${{ steps.calver.outputs.version }} @@ -96,7 +87,7 @@ jobs: fi - name: Discord Notification - Success - if: success() && github.ref == 'refs/heads/main' + if: success() && steps.tags.outputs.channel != 'dev' uses: cal/gitea-actions/discord-notify@main with: webhook_url: ${{ secrets.DISCORD_WEBHOOK }} -- 2.25.1 From 75b9968149c7d8a178f3f638ed1239ded5f6e471 Mon Sep 17 00:00:00 2001 From: cal Date: Thu, 5 Mar 2026 03:15:37 +0000 Subject: [PATCH 05/12] Update .gitea/workflows/docker-build.yml --- .gitea/workflows/docker-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/docker-build.yml b/.gitea/workflows/docker-build.yml index f286fc9..f409d19 100644 --- a/.gitea/workflows/docker-build.yml +++ b/.gitea/workflows/docker-build.yml @@ -99,7 +99,7 @@ jobs: timestamp: ${{ steps.calver.outputs.timestamp }} - name: Discord Notification - Failure - if: failure() && github.ref == 'refs/heads/main' + if: failure() && steps.tags.outputs.channel != 'dev' uses: cal/gitea-actions/discord-notify@main with: webhook_url: ${{ secrets.DISCORD_WEBHOOK }} -- 2.25.1 From 0ce0707e3ead65396973a4033e239cd5e9372045 Mon Sep 17 00:00:00 2001 From: cal Date: Thu, 5 Mar 2026 03:16:36 +0000 Subject: [PATCH 06/12] Update .gitea/workflows/docker-build.yml --- .gitea/workflows/docker-build.yml | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/.gitea/workflows/docker-build.yml b/.gitea/workflows/docker-build.yml index f409d19..9fae8dc 100644 --- a/.gitea/workflows/docker-build.yml +++ b/.gitea/workflows/docker-build.yml @@ -68,23 +68,20 @@ jobs: run: | echo "## Docker Build Successful" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY + echo "**Channel:** \`${{ steps.tags.outputs.channel }}\`" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY echo "**Image Tags:**" >> $GITHUB_STEP_SUMMARY - echo "- \`manticorum67/paper-dynasty-discordapp:latest\`" >> $GITHUB_STEP_SUMMARY - echo "- \`manticorum67/paper-dynasty-discordapp:${{ steps.calver.outputs.version }}\`" >> $GITHUB_STEP_SUMMARY - echo "- \`manticorum67/paper-dynasty-discordapp:${{ steps.calver.outputs.version_sha }}\`" >> $GITHUB_STEP_SUMMARY + IFS=',' read -ra TAG_ARRAY <<< "${{ steps.tags.outputs.tags }}" + for tag in "${TAG_ARRAY[@]}"; do + echo "- \`${tag}\`" >> $GITHUB_STEP_SUMMARY + done echo "" >> $GITHUB_STEP_SUMMARY echo "**Build Details:**" >> $GITHUB_STEP_SUMMARY echo "- Branch: \`${{ steps.calver.outputs.branch }}\`" >> $GITHUB_STEP_SUMMARY echo "- Commit: \`${{ github.sha }}\`" >> $GITHUB_STEP_SUMMARY echo "- Timestamp: \`${{ steps.calver.outputs.timestamp }}\`" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - if [ "${{ github.ref }}" == "refs/heads/main" ]; then - echo "Pushed to Docker Hub!" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "Pull with: \`docker pull manticorum67/paper-dynasty-discordapp:latest\`" >> $GITHUB_STEP_SUMMARY - else - echo "_PR build - image not pushed to Docker Hub_" >> $GITHUB_STEP_SUMMARY - fi + echo "Pull with: \`docker pull manticorum67/paper-dynasty-discordapp:${{ steps.tags.outputs.primary_tag }}\`" >> $GITHUB_STEP_SUMMARY - name: Discord Notification - Success if: success() && steps.tags.outputs.channel != 'dev' -- 2.25.1 From ed00a97c0d66d44b8f0570dfc1bffd309ccd95f9 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Thu, 5 Mar 2026 15:57:25 -0600 Subject: [PATCH 07/12] fix: update owner_only to use Cal's correct Discord ID Co-Authored-By: Claude Opus 4.6 --- helpers/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/helpers/utils.py b/helpers/utils.py index 8b091ab..6b6185f 100644 --- a/helpers/utils.py +++ b/helpers/utils.py @@ -111,7 +111,8 @@ def get_player_url(team, player) -> str: def owner_only(ctx) -> bool: """Check if user is the bot owner.""" # ID for discord User Cal - owners = [287463767924137994, 1087936030899347516] + owners = [258104532423147520] + # owners += [287463767924137994, 1087936030899347516] # Handle both Context (has .author) and Interaction (has .user) objects user = getattr(ctx, "user", None) or getattr(ctx, "author", None) -- 2.25.1 From 77c3f3004c3788531373e4d9c3c66a833369865d Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Fri, 6 Mar 2026 13:03:15 -0600 Subject: [PATCH 08/12] fix: align scouting rarity symbols with system colors Co-Authored-By: Claude Opus 4.6 --- helpers/scouting.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/helpers/scouting.py b/helpers/scouting.py index a21b9f9..421ec32 100644 --- a/helpers/scouting.py +++ b/helpers/scouting.py @@ -23,12 +23,12 @@ SCOUT_WINDOW_SECONDS = 1800 # 30 minutes # Rarity value → display symbol RARITY_SYMBOLS = { - 8: "\U0001f7e1", # HoF — yellow - 5: "\U0001f7e3", # MVP — purple - 3: "\U0001f535", # All-Star — blue - 2: "\U0001f7e2", # Starter — green - 1: "\u26aa", # Reserve — white - 0: "\u26ab", # Replacement — black + 8: "\U0001f7e3", # HoF — purple (#751cea) + 5: "\U0001f535", # MVP — cyan/blue (#56f1fa) + 3: "\U0001f7e1", # All-Star — gold (#FFD700) + 2: "\u26aa", # Starter — silver (#C0C0C0) + 1: "\U0001f7e4", # Reserve — bronze (#CD7F32) + 0: "\u26ab", # Replacement — dark gray (#454545) } -- 2.25.1 From 8e605c2140c5d696a54b9f2ada43860065e3a7df Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Fri, 6 Mar 2026 13:22:45 -0600 Subject: [PATCH 09/12] fix: add pack_id to scouted card creation, enhance embed with card links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Include pack_id in db_post("cards") payload (API requires it) - Player names now link to card image URLs in scout embed - Display format: "🟡 All-Star — [2023 Mike Trout](card_image_url)" Co-Authored-By: Claude Opus 4.6 --- discord_ui/scout_view.py | 1 + helpers/scouting.py | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/discord_ui/scout_view.py b/discord_ui/scout_view.py index 0d5a12f..83712e6 100644 --- a/discord_ui/scout_view.py +++ b/discord_ui/scout_view.py @@ -221,6 +221,7 @@ class ScoutButton(discord.ui.Button): { "player_id": self.card["player"]["player_id"], "team_id": scouter_team["id"], + "pack_id": self.card["pack"]["id"], } ], }, diff --git a/helpers/scouting.py b/helpers/scouting.py index 421ec32..6666b94 100644 --- a/helpers/scouting.py +++ b/helpers/scouting.py @@ -52,10 +52,17 @@ def _build_card_lines(cards: list[dict]) -> list[tuple[int, str]]: player = card["player"] rarity_val = player["rarity"]["value"] symbol = RARITY_SYMBOLS.get(rarity_val, "\u26ab") + desc = player.get("description", "") + image_url = player.get("image", "") + name_display = ( + f"[{desc} {player['p_name']}]({image_url})" + if image_url + else f"{desc} {player['p_name']}" + ) lines.append( ( player["player_id"], - f"{symbol} {player['rarity']['name']} — {player['p_name']}", + f"{symbol} {player['rarity']['name']} — {name_display}", ) ) random.shuffle(lines) -- 2.25.1 From e160be4137794dd43523ae90dfb1b56b76827c71 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Fri, 6 Mar 2026 18:47:52 -0600 Subject: [PATCH 10/12] fix: add missing pack, description, image fields to scouting test fixtures Co-Authored-By: Claude Opus 4.6 --- tests/scouting/conftest.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/scouting/conftest.py b/tests/scouting/conftest.py index 523e38f..22164fd 100644 --- a/tests/scouting/conftest.py +++ b/tests/scouting/conftest.py @@ -12,19 +12,29 @@ from discord.ext import commands # --------------------------------------------------------------------------- -def _make_player(player_id, name, rarity_name, rarity_value, headshot=None): +def _make_player( + player_id, + name, + rarity_name, + rarity_value, + headshot=None, + description="2023", + image=None, +): """Build a minimal player dict matching the API shape used by scouting.""" return { "player_id": player_id, "p_name": name, "rarity": {"name": rarity_name, "value": rarity_value, "color": "ffffff"}, "headshot": headshot or "https://example.com/headshot.jpg", + "description": description, + "image": image or f"https://example.com/cards/{player_id}/battingcard.png", } -def _make_card(card_id, player): +def _make_card(card_id, player, pack_id=100): """Wrap a player dict inside a card dict (as returned by the cards API).""" - return {"id": card_id, "player": player} + return {"id": card_id, "player": player, "pack": {"id": pack_id}} @pytest.fixture -- 2.25.1 From da55cbe4d49488540ad9c0b46185a1b38583107f Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Fri, 6 Mar 2026 21:12:46 -0600 Subject: [PATCH 11/12] feat: limit scouting to Standard/Premium packs, simplify scout view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add SCOUTABLE_PACK_TYPES env var (default: Standard,Premium) to control which pack types offer scout opportunities - Unify embed construction into build_scout_embed() — removes 3 near-duplicate embed builders across scout_view.py and scouting.py - Replace manual total_scouts counter with derived property from claims dict - Remove redundant db_get("current") API call per scout click — use PD_SEASON - Remove duplicate expiry computation in create_scout_opportunity - Move send_to_channel to top-level import, remove redundant local import - Update tests to match simplified code Co-Authored-By: Claude Opus 4.6 --- discord_ui/scout_view.py | 66 ++++++++----------------- helpers/main.py | 18 ++++--- helpers/scouting.py | 81 ++++++++++++++++++++++--------- tests/scouting/test_scout_view.py | 47 +++++------------- 4 files changed, 99 insertions(+), 113 deletions(-) diff --git a/discord_ui/scout_view.py b/discord_ui/scout_view.py index 83712e6..a5a64ba 100644 --- a/discord_ui/scout_view.py +++ b/discord_ui/scout_view.py @@ -11,15 +11,15 @@ import logging import discord -from api_calls import db_get, db_post +from api_calls import db_post from helpers.main import get_team_by_owner, get_card_embeds from helpers.scouting import ( SCOUT_TOKENS_PER_DAY, - build_scouted_card_list, + build_scout_embed, get_scout_tokens_used, ) from helpers.utils import int_timestamp -from helpers.discord_utils import get_team_embed +from helpers.discord_utils import get_team_embed, send_to_channel from helpers.constants import IMAGES, PD_SEASON logger = logging.getLogger("discord_app") @@ -60,8 +60,6 @@ class ScoutView(discord.ui.View): self.scouted_users: set[int] = set() # Users currently being processed (prevent double-click race) self.processing_users: set[int] = set() - # Total scout count - self.total_scouts = 0 for i, card in enumerate(cards): button = ScoutButton( @@ -71,30 +69,21 @@ class ScoutView(discord.ui.View): ) self.add_item(button) + @property + def total_scouts(self) -> int: + return sum(len(v) for v in self.claims.values()) + async def update_message(self): """Refresh the embed with current claim state.""" if not self.message: return - card_list = build_scouted_card_list(self.card_lines, self.claims) - - title = f"Scout Opportunity! ({self.total_scouts} scouted)" - embed = get_team_embed(title=title, team=self.opener_team) - if self.expires_unix: - time_line = f"Scout window closes ." - else: - time_line = "Scout window closes in **30 minutes**." - - embed.description = ( - f"**{self.opener_team['lname']}**'s pack\n\n" - f"{card_list}\n\n" - f"Pick a card — but which is which?\n" - f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" - f"{time_line}" - ) - embed.set_footer( - text=f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player", - icon_url=IMAGES["logo"], + embed, _ = build_scout_embed( + self.opener_team, + card_lines=self.card_lines, + expires_unix=self.expires_unix, + claims=self.claims, + total_scouts=self.total_scouts, ) try: @@ -109,22 +98,12 @@ class ScoutView(discord.ui.View): if self.message: try: - from helpers.scouting import build_scouted_card_list - - card_list = build_scouted_card_list(self.card_lines, self.claims) - - if self.total_scouts > 0: - title = f"Scout Window Closed ({self.total_scouts} scouted)" - else: - title = "Scout Window Closed" - - embed = get_team_embed(title=title, team=self.opener_team) - embed.description = ( - f"**{self.opener_team['lname']}**'s pack\n\n" f"{card_list}" - ) - embed.set_footer( - text=f"Paper Dynasty Season {PD_SEASON}", - icon_url=IMAGES["logo"], + embed, _ = build_scout_embed( + self.opener_team, + card_lines=self.card_lines, + claims=self.claims, + total_scouts=self.total_scouts, + closed=True, ) await self.message.edit(embed=embed, view=self) except Exception as e: @@ -228,14 +207,12 @@ class ScoutButton(discord.ui.Button): ) # Consume a scout token - current = await db_get("current") await db_post( "rewards", payload={ "name": "Scout Token", "team_id": scouter_team["id"], - "season": current["season"] if current else PD_SEASON, - "week": current["week"] if current else 1, + "season": PD_SEASON, "created": int_timestamp(), }, ) @@ -246,7 +223,6 @@ class ScoutButton(discord.ui.Button): view.claims[player_id] = [] view.claims[player_id].append(scouter_team["lname"]) view.scouted_users.add(interaction.user.id) - view.total_scouts += 1 # Update the shared embed await view.update_message() @@ -269,8 +245,6 @@ class ScoutButton(discord.ui.Button): # Notify for shiny scouts (rarity >= 5) if self.card["player"]["rarity"]["value"] >= 5: try: - from helpers.discord_utils import send_to_channel - notif_embed = get_team_embed(title="Rare Scout!", team=scouter_team) notif_embed.description = ( f"**{scouter_team['lname']}** scouted a " diff --git a/helpers/main.py b/helpers/main.py index 4dfc659..0b989a5 100644 --- a/helpers/main.py +++ b/helpers/main.py @@ -1770,15 +1770,17 @@ async def open_st_pr_packs(all_packs: list, team: dict, context): await context.channel.send(content=f"Let's head down to {pack_channel.mention}!") await display_cards(all_cards, team, pack_channel, author, pack_cover=pack_cover) - # Create scout opportunities for each pack - from helpers.scouting import create_scout_opportunity + # Create scout opportunities for each pack (Standard/Premium only) + from helpers.scouting import create_scout_opportunity, SCOUTABLE_PACK_TYPES - for p_id in pack_ids: - pack_cards = [c for c in all_cards if c.get("pack_id") == p_id] - if pack_cards: - await create_scout_opportunity( - pack_cards, team, pack_channel, author, context - ) + pack_type_name = all_packs[0].get("pack_type", {}).get("name") + if pack_type_name in SCOUTABLE_PACK_TYPES: + for p_id in pack_ids: + pack_cards = [c for c in all_cards if c.get("pack_id") == p_id] + if pack_cards: + await create_scout_opportunity( + pack_cards, team, pack_channel, author, context + ) if len(pack_ids) > 1: await asyncio.sleep(2) diff --git a/helpers/scouting.py b/helpers/scouting.py index 6666b94..6c926bb 100644 --- a/helpers/scouting.py +++ b/helpers/scouting.py @@ -7,6 +7,7 @@ and embed formatting for the scouting feature. import datetime import logging +import os import random import discord @@ -20,6 +21,8 @@ logger = logging.getLogger("discord_app") SCOUT_TOKENS_PER_DAY = 2 SCOUT_WINDOW_SECONDS = 1800 # 30 minutes +_scoutable_raw = os.environ.get("SCOUTABLE_PACK_TYPES", "Standard,Premium") +SCOUTABLE_PACK_TYPES = {s.strip() for s in _scoutable_raw.split(",") if s.strip()} # Rarity value → display symbol RARITY_SYMBOLS = { @@ -71,39 +74,70 @@ def _build_card_lines(cards: list[dict]) -> list[tuple[int, str]]: def build_scout_embed( opener_team: dict, - cards: list[dict], + cards: list[dict] = None, card_lines: list[tuple[int, str]] = None, expires_unix: int = None, + claims: dict[int, list[str]] = None, + total_scouts: int = 0, + closed: bool = False, ) -> tuple[discord.Embed, list[tuple[int, str]]]: """Build the embed shown above the scout buttons. Shows a shuffled list of cards (rarity + player name) so scouters know what's in the pack but not which button maps to which card. Returns (embed, card_lines) so the view can store the shuffled order. - """ - embed = get_team_embed(title="Scout Opportunity!", team=opener_team) - if card_lines is None: + Parameters + ---------- + closed : if True, renders the "Scout Window Closed" variant + claims : scouted card tracking dict for build_scouted_card_list + total_scouts : number of scouts so far (for title display) + """ + if card_lines is None and cards is not None: card_lines = _build_card_lines(cards) - card_list = "\n".join(line for _, line in card_lines) - - if expires_unix: - time_line = f"Scout window closes ." + if claims and card_lines: + card_list = build_scouted_card_list(card_lines, claims) + elif card_lines: + card_list = "\n".join(line for _, line in card_lines) else: - time_line = "Scout window closes in **30 minutes**." + card_list = "" - embed.description = ( - f"**{opener_team['lname']}** just opened a pack!\n\n" - f"**Cards in this pack:**\n{card_list}\n\n" - f"Pick a card — but which is which?\n" - f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" - f"{time_line}" - ) - embed.set_footer( - text=f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player", - icon_url=IMAGES["logo"], - ) + if closed: + if total_scouts > 0: + title = f"Scout Window Closed ({total_scouts} scouted)" + else: + title = "Scout Window Closed" + elif total_scouts > 0: + title = f"Scout Opportunity! ({total_scouts} scouted)" + else: + title = "Scout Opportunity!" + + embed = get_team_embed(title=title, team=opener_team) + + if closed: + embed.description = f"**{opener_team['lname']}**'s pack\n\n" f"{card_list}" + embed.set_footer( + text=f"Paper Dynasty Season {PD_SEASON}", + icon_url=IMAGES["logo"], + ) + else: + if expires_unix: + time_line = f"Scout window closes ." + else: + time_line = "Scout window closes in **30 minutes**." + + embed.description = ( + f"**{opener_team['lname']}**'s pack\n\n" + f"{card_list}\n\n" + f"Pick a card — but which is which?\n" + f"Costs 1 Scout Token (2 per day, resets at midnight Central).\n" + f"{time_line}" + ) + embed.set_footer( + text=f"Paper Dynasty Season {PD_SEASON} \u2022 One scout per player", + icon_url=IMAGES["logo"], + ) return embed, card_lines @@ -163,7 +197,9 @@ async def create_scout_opportunity( return now = datetime.datetime.now() - expires_at = int_timestamp(now + datetime.timedelta(seconds=SCOUT_WINDOW_SECONDS)) + expires_dt = now + datetime.timedelta(seconds=SCOUT_WINDOW_SECONDS) + expires_at = int_timestamp(expires_dt) + expires_unix = int(expires_dt.timestamp()) created = int_timestamp(now) card_ids = [c["id"] for c in pack_cards] @@ -183,9 +219,6 @@ async def create_scout_opportunity( logger.error(f"Failed to create scout opportunity: {e}") return - expires_unix = int( - (now + datetime.timedelta(seconds=SCOUT_WINDOW_SECONDS)).timestamp() - ) embed, card_lines = build_scout_embed( opener_team, pack_cards, expires_unix=expires_unix ) diff --git a/tests/scouting/test_scout_view.py b/tests/scouting/test_scout_view.py index 906bb97..186c0b1 100644 --- a/tests/scouting/test_scout_view.py +++ b/tests/scouting/test_scout_view.py @@ -210,14 +210,12 @@ class TestScoutButtonSuccess: @pytest.mark.asyncio @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_successful_scout_creates_card_copy( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, sample_cards, @@ -230,7 +228,6 @@ class TestScoutButtonSuccess: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -369,14 +366,12 @@ class TestMultiScout: @pytest.mark.asyncio @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_two_users_can_scout_same_card( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, sample_cards, @@ -388,7 +383,6 @@ class TestMultiScout: """Two different users should both be able to scout the same card.""" view = self._make_view_with_message(sample_cards, opener_team, mock_bot) mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -430,14 +424,12 @@ class TestMultiScout: @pytest.mark.asyncio @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_same_user_cannot_scout_twice( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, sample_cards, @@ -449,7 +441,6 @@ class TestMultiScout: view = self._make_view_with_message(sample_cards, opener_team, mock_bot) mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -579,7 +570,9 @@ class TestScoutViewTimeout: view.card_lines = [ (c["player"]["player_id"], f"Line {i}") for i, c in enumerate(sample_cards) ] - view.total_scouts = 5 + # Set up claims so total_scouts property returns 5 + pid = sample_cards[0]["player"]["player_id"] + view.claims[pid] = ["Team A", "Team B", "Team C", "Team D", "Team E"] view.message = AsyncMock(spec=discord.Message) view.message.edit = AsyncMock() @@ -617,14 +610,12 @@ class TestProcessingUserCleanup: @pytest.mark.asyncio @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_processing_cleared_on_success( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, sample_cards, @@ -648,7 +639,6 @@ class TestProcessingUserCleanup: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -744,24 +734,22 @@ class TestProcessingUserCleanup: # --------------------------------------------------------------------------- -# db_get("current") fallback +# Rewards use PD_SEASON constant # --------------------------------------------------------------------------- -class TestCurrentSeasonFallback: - """Tests for the fallback when db_get('current') returns None.""" +class TestRewardsSeason: + """Tests that reward records always use the PD_SEASON constant.""" @pytest.mark.asyncio @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) - async def test_current_returns_none_uses_fallback( + async def test_rewards_use_pd_season( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, sample_cards, @@ -769,7 +757,7 @@ class TestCurrentSeasonFallback: scouter_team, mock_bot, ): - """When db_get('current') returns None, rewards should use PD_SEASON fallback.""" + """Reward records should always use the PD_SEASON constant for season.""" view = ScoutView( scout_opp_id=1, cards=sample_cards, @@ -785,7 +773,6 @@ class TestCurrentSeasonFallback: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = None # db_get("current") returns None mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -803,14 +790,13 @@ class TestCurrentSeasonFallback: assert view.total_scouts == 1 assert 12345 in view.scouted_users - # Verify the rewards POST used fallback values + # Verify the rewards POST uses PD_SEASON # Order: scout_claims (0), cards (1), rewards (2) from helpers.constants import PD_SEASON reward_call = mock_db_post.call_args_list[2] assert reward_call[0][0] == "rewards" assert reward_call[1]["payload"]["season"] == PD_SEASON - assert reward_call[1]["payload"]["week"] == 1 # --------------------------------------------------------------------------- @@ -822,17 +808,15 @@ class TestShinyScoutNotification: """Tests for the rare-card notification path (rarity >= 5).""" @pytest.mark.asyncio - @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.send_to_channel", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_shiny_card_sends_notification( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, mock_send_to_channel, @@ -857,7 +841,6 @@ class TestShinyScoutNotification: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -877,17 +860,15 @@ class TestShinyScoutNotification: assert call_args[0][1] == "pd-network-news" @pytest.mark.asyncio - @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.send_to_channel", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_non_shiny_card_no_notification( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, mock_send_to_channel, @@ -912,7 +893,6 @@ class TestShinyScoutNotification: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] @@ -930,17 +910,15 @@ class TestShinyScoutNotification: mock_send_to_channel.assert_not_called() @pytest.mark.asyncio - @patch("helpers.discord_utils.send_to_channel", new_callable=AsyncMock) + @patch("discord_ui.scout_view.send_to_channel", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_card_embeds", new_callable=AsyncMock) @patch("discord_ui.scout_view.db_post", new_callable=AsyncMock) - @patch("discord_ui.scout_view.db_get", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_scout_tokens_used", new_callable=AsyncMock) @patch("discord_ui.scout_view.get_team_by_owner", new_callable=AsyncMock) async def test_shiny_notification_failure_does_not_crash( self, mock_get_team, mock_get_tokens, - mock_db_get, mock_db_post, mock_card_embeds, mock_send_to_channel, @@ -965,7 +943,6 @@ class TestShinyScoutNotification: mock_get_team.return_value = scouter_team mock_get_tokens.return_value = 0 - mock_db_get.return_value = {"season": 4, "week": 1} # db_get("current") mock_db_post.return_value = {"id": 100} mock_card_embeds.return_value = [Mock(spec=discord.Embed)] mock_send_to_channel.side_effect = Exception("Channel not found") -- 2.25.1 From c721d0a94209a4277f020a51b4424a1d1c7044b7 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Thu, 5 Mar 2026 06:03:23 -0600 Subject: [PATCH 12/12] fix: replace bare except: with typed NoResultFound in gameplay_queries (#25) Co-Authored-By: Claude Sonnet 4.6 --- in_game/gameplay_queries.py | 1796 +++++++++++++++++++++++------------ 1 file changed, 1184 insertions(+), 612 deletions(-) diff --git a/in_game/gameplay_queries.py b/in_game/gameplay_queries.py index 6880b1b..4ead0f7 100644 --- a/in_game/gameplay_queries.py +++ b/in_game/gameplay_queries.py @@ -3,15 +3,52 @@ import logging import math from typing import Literal +import sqlalchemy import pydantic from sqlalchemy import func from api_calls import db_get, db_post from sqlmodel import col, update -from in_game.gameplay_models import CACHE_LIMIT, BatterScouting, BatterScoutingBase, BattingCard, BattingCardBase, BattingRatings, BattingRatingsBase, Card, CardBase, Cardset, CardsetBase, GameCardsetLink, Lineup, PitcherScouting, PitchingCard, PitchingCardBase, PitchingRatings, PitchingRatingsBase, Player, PlayerBase, PositionRating, PositionRatingBase, RosterLink, Session, Team, TeamBase, select, or_, Game, Play -from exceptions import DatabaseError, PositionNotFoundException, log_errors, log_exception, PlayNotFoundException +from in_game.gameplay_models import ( + CACHE_LIMIT, + BatterScouting, + BatterScoutingBase, + BattingCard, + BattingCardBase, + BattingRatings, + BattingRatingsBase, + Card, + CardBase, + Cardset, + CardsetBase, + GameCardsetLink, + Lineup, + PitcherScouting, + PitchingCard, + PitchingCardBase, + PitchingRatings, + PitchingRatingsBase, + Player, + PlayerBase, + PositionRating, + PositionRatingBase, + RosterLink, + Session, + Team, + TeamBase, + select, + or_, + Game, + Play, +) +from exceptions import ( + DatabaseError, + PositionNotFoundException, + log_errors, + log_exception, + PlayNotFoundException, +) - -logger = logging.getLogger('discord_app') +logger = logging.getLogger("discord_app") class DecisionModel(pydantic.BaseModel): @@ -34,20 +71,28 @@ class DecisionModel(pydantic.BaseModel): def get_batting_team(session: Session, this_play: Play) -> Team: - return this_play.game.away_team if this_play.inning_half == 'top' else this_play.game.home_team + return ( + this_play.game.away_team + if this_play.inning_half == "top" + else this_play.game.home_team + ) def get_games_by_channel(session: Session, channel_id: int) -> list[Game]: - logger.info(f'Getting games in channel {channel_id}') - return session.exec(select(Game).where(Game.channel_id == channel_id, Game.active)).all() + logger.info(f"Getting games in channel {channel_id}") + return session.exec( + select(Game).where(Game.channel_id == channel_id, Game.active) + ).all() def get_channel_game_or_none(session: Session, channel_id: int) -> Game | None: - logger.info(f'Getting one game from channel {channel_id}') + logger.info(f"Getting one game from channel {channel_id}") all_games = get_games_by_channel(session, channel_id) if len(all_games) > 1: - err = 'Too many games found in get_channel_game_or_none' - logger.error(f'cogs.gameplay - get_channel_game_or_none - channel_id: {channel_id} / {err}') + err = "Too many games found in get_channel_game_or_none" + logger.error( + f"cogs.gameplay - get_channel_game_or_none - channel_id: {channel_id} / {err}" + ) raise Exception(err) elif len(all_games) == 0: return None @@ -55,224 +100,298 @@ def get_channel_game_or_none(session: Session, channel_id: int) -> Game | None: def get_active_games_by_team(session: Session, team: Team) -> list[Game]: - logger.info(f'Getting game for team {team.lname}') - return session.exec(select(Game).where(Game.active, or_(Game.away_team_id == team.id, Game.home_team_id == team.id))).all() + logger.info(f"Getting game for team {team.lname}") + return session.exec( + select(Game).where( + Game.active, or_(Game.away_team_id == team.id, Game.home_team_id == team.id) + ) + ).all() async def get_team_or_none( - session: Session, team_id: int | None = None, gm_id: int | None = None, team_abbrev: str | None = None, skip_cache: bool = False, main_team: bool = None, gauntlet_team: bool = None, include_packs: bool = False) -> Team | None: - logger.info(f'Getting team or none / team_id: {team_id} / gm_id: {gm_id} / team_abbrev: {team_abbrev} / skip_cache: {skip_cache} / main_team: {main_team} / gauntlet_team: {gauntlet_team}') - + session: Session, + team_id: int | None = None, + gm_id: int | None = None, + team_abbrev: str | None = None, + skip_cache: bool = False, + main_team: bool = None, + gauntlet_team: bool = None, + include_packs: bool = False, +) -> Team | None: + logger.info( + f"Getting team or none / team_id: {team_id} / gm_id: {gm_id} / team_abbrev: {team_abbrev} / skip_cache: {skip_cache} / main_team: {main_team} / gauntlet_team: {gauntlet_team}" + ) + this_team = None if gm_id is not None: if main_team is None and gauntlet_team is None: main_team = True gauntlet_team = False elif main_team == gauntlet_team: - log_exception(KeyError, 'Must select either main_team or gauntlet_team') - - logger.info(f'main_team: {main_team} / gauntlet_team: {gauntlet_team}') + log_exception(KeyError, "Must select either main_team or gauntlet_team") + + logger.info(f"main_team: {main_team} / gauntlet_team: {gauntlet_team}") if team_id is None and gm_id is None and team_abbrev is None: - log_exception(KeyError, 'One of "team_id", "gm_id", or "team_abbrev" must be included in search') - + log_exception( + KeyError, + 'One of "team_id", "gm_id", or "team_abbrev" must be included in search', + ) + if not skip_cache: if team_id is not None: - logger.info(f'Getting team by team_id: {team_id}') + logger.info(f"Getting team by team_id: {team_id}") this_team = session.get(Team, team_id) else: if gm_id is not None: - logger.info(f'Getting team by gm_id: {gm_id}') + logger.info(f"Getting team by gm_id: {gm_id}") for team in session.exec(select(Team).where(Team.gmid == gm_id)).all(): - if ('gauntlet' in team.abbrev.lower() and gauntlet_team) or ('gauntlet' not in team.abbrev.lower() and main_team): - logger.info(f'Found the team: {team}') + if ("gauntlet" in team.abbrev.lower() and gauntlet_team) or ( + "gauntlet" not in team.abbrev.lower() and main_team + ): + logger.info(f"Found the team: {team}") this_team = team break - logger.info(f'post loop, this_team: {this_team}') + logger.info(f"post loop, this_team: {this_team}") else: - logger.info(f'Getting team by abbrev: {team_abbrev}') - this_team = session.exec(select(Team).where(func.lower(Team.abbrev) == team_abbrev.lower())).one_or_none() - + logger.info(f"Getting team by abbrev: {team_abbrev}") + this_team = session.exec( + select(Team).where(func.lower(Team.abbrev) == team_abbrev.lower()) + ).one_or_none() + if this_team is not None: - logger.info(f'we found a team: {this_team} / created: {this_team.created}') + logger.info(f"we found a team: {this_team} / created: {this_team.created}") tdelta = datetime.datetime.now() - this_team.created - logger.info(f'tdelta: {tdelta}') + logger.info(f"tdelta: {tdelta}") if tdelta.total_seconds() < CACHE_LIMIT: return this_team # else: # session.delete(this_team) # session.commit() - + def cache_team(json_data: dict) -> Team: - logger.info(f'gameplay_queries - cache_team - writing a team to cache: {json_data}') + logger.info( + f"gameplay_queries - cache_team - writing a team to cache: {json_data}" + ) valid_team = TeamBase.model_validate(json_data, from_attributes=True) - logger.info(f'gameplay_queries - cache_team - valid_team: {valid_team}') + logger.info(f"gameplay_queries - cache_team - valid_team: {valid_team}") db_team = Team.model_validate(valid_team) - logger.info(f'gameplay_queries - cache_team - db_team: {db_team}') - logger.info(f'Checking for existing team ID: {db_team.id}') + logger.info(f"gameplay_queries - cache_team - db_team: {db_team}") + logger.info(f"Checking for existing team ID: {db_team.id}") try: this_team = session.exec(select(Team).where(Team.id == db_team.id)).one() - logger.info(f'Found team: {this_team}\nUpdating with db team: {db_team}') - + logger.info(f"Found team: {this_team}\nUpdating with db team: {db_team}") + for key, value in db_team.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_team, key, value) - logger.info(f'Set this_team to db_team') + logger.info(f"Set this_team to db_team") session.add(this_team) session.commit() - logger.info(f'Refreshing this_team') + logger.info(f"Refreshing this_team") session.refresh(this_team) return this_team - except: - logger.info(f'Team not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Team not found, adding to db") session.add(db_team) session.commit() session.refresh(db_team) return db_team - + if team_id is not None: - t_query = await db_get('teams', object_id=team_id, params=[('inc_packs', include_packs)]) + t_query = await db_get( + "teams", object_id=team_id, params=[("inc_packs", include_packs)] + ) if t_query is not None: return cache_team(t_query) - + elif gm_id is not None: - t_query = await db_get('teams', params=[('gm_id', gm_id), ('inc_packs', include_packs)]) - if t_query['count'] != 0: - for team in t_query['teams']: - logger.info(f'in t_query loop / team: {team} / gauntlet_team: {gauntlet_team} / main_team: {main_team}') - if (gauntlet_team and 'gauntlet' in team['abbrev'].lower()) or (main_team and 'gauntlet' not in team['abbrev'].lower()): + t_query = await db_get( + "teams", params=[("gm_id", gm_id), ("inc_packs", include_packs)] + ) + if t_query["count"] != 0: + for team in t_query["teams"]: + logger.info( + f"in t_query loop / team: {team} / gauntlet_team: {gauntlet_team} / main_team: {main_team}" + ) + if (gauntlet_team and "gauntlet" in team["abbrev"].lower()) or ( + main_team and "gauntlet" not in team["abbrev"].lower() + ): return cache_team(team) - + elif team_abbrev is not None: - t_query = await db_get('teams', params=[('abbrev', team_abbrev), ('inc_packs', include_packs)]) - if t_query['count'] != 0: - if 'gauntlet' in team_abbrev.lower(): - return cache_team(t_query['teams'][0]) - - for team in [x for x in t_query['teams'] if 'gauntlet' not in x['abbrev'].lower()]: + t_query = await db_get( + "teams", params=[("abbrev", team_abbrev), ("inc_packs", include_packs)] + ) + if t_query["count"] != 0: + if "gauntlet" in team_abbrev.lower(): + return cache_team(t_query["teams"][0]) + + for team in [ + x for x in t_query["teams"] if "gauntlet" not in x["abbrev"].lower() + ]: return cache_team(team) - - logger.warning(f'No team found') + + logger.warning(f"No team found") return None -async def get_cardset_or_none(session: Session, cardset_id: int = None, cardset_name: str = None): - logger.info(f'Getting cardset or none / cardset_id: {cardset_id} / cardset_name: {cardset_name}') +async def get_cardset_or_none( + session: Session, cardset_id: int = None, cardset_name: str = None +): + logger.info( + f"Getting cardset or none / cardset_id: {cardset_id} / cardset_name: {cardset_name}" + ) if cardset_id is None and cardset_name is None: - log_exception(KeyError, 'One of "cardset_id" or "cardset_name" must be included in search') - + log_exception( + KeyError, 'One of "cardset_id" or "cardset_name" must be included in search' + ) + if cardset_id is not None: - logger.info(f'Getting cardset by id: {cardset_id}') + logger.info(f"Getting cardset by id: {cardset_id}") this_cardset = session.get(Cardset, cardset_id) else: - logger.info(f'Getting cardset by name: {cardset_name}') - this_cardset = session.exec(select(Cardset).where(func.lower(Cardset.name) == cardset_name.lower())).one_or_none() - + logger.info(f"Getting cardset by name: {cardset_name}") + this_cardset = session.exec( + select(Cardset).where(func.lower(Cardset.name) == cardset_name.lower()) + ).one_or_none() + if this_cardset is not None: - logger.info(f'we found a cardset: {this_cardset}') + logger.info(f"we found a cardset: {this_cardset}") return this_cardset - + def cache_cardset(json_data: dict) -> Cardset: - logger.info(f'gameplay_queries - cache_team - writing a team to cache: {json_data}') + logger.info( + f"gameplay_queries - cache_team - writing a team to cache: {json_data}" + ) valid_cardset = CardsetBase.model_validate(json_data, from_attributes=True) - logger.info(f'gameplay_queries - cache_team - valid_cardset: {valid_cardset}') + logger.info(f"gameplay_queries - cache_team - valid_cardset: {valid_cardset}") db_cardset = Cardset.model_validate(valid_cardset) - logger.info(f'gameplay_queries - cache_team - db_cardset: {db_cardset}') + logger.info(f"gameplay_queries - cache_team - db_cardset: {db_cardset}") session.add(db_cardset) session.commit() session.refresh(db_cardset) return db_cardset - + if cardset_id is not None: - c_query = await db_get('cardsets', object_id=cardset_id) + c_query = await db_get("cardsets", object_id=cardset_id) if c_query is not None: return cache_cardset(c_query) - + elif cardset_name is not None: - c_query = await db_get('cardsets', params=[('name', cardset_name)]) - if c_query['count'] != 0: - return cache_cardset(c_query['cardsets'][0]) - - logger.warning(f'No cardset found') + c_query = await db_get("cardsets", params=[("name", cardset_name)]) + if c_query["count"] != 0: + return cache_cardset(c_query["cardsets"][0]) + + logger.warning(f"No cardset found") return None -async def get_player_or_none(session: Session, player_id: int, skip_cache: bool = False) -> Player | None: - logger.info(f'gameplay_models - get_player_or_none - player_id: {player_id} / skip_cache: {skip_cache}') +async def get_player_or_none( + session: Session, player_id: int, skip_cache: bool = False +) -> Player | None: + logger.info( + f"gameplay_models - get_player_or_none - player_id: {player_id} / skip_cache: {skip_cache}" + ) if not skip_cache: this_player = session.get(Player, player_id) if this_player is not None: - logger.info(f'we found a cached player: {this_player}\ncreated: {this_player.created}') + logger.info( + f"we found a cached player: {this_player}\ncreated: {this_player.created}" + ) tdelta = datetime.datetime.now() - this_player.created - logger.info(f'tdelta: {tdelta}') + logger.info(f"tdelta: {tdelta}") if tdelta.total_seconds() < CACHE_LIMIT: - logger.info(f'returning this player') + logger.info(f"returning this player") return this_player # else: # logger.warning('Deleting old player record') # session.delete(this_player) # session.commit() - + def cache_player(json_data: dict) -> Player: - logger.info(f'gameplay_models - get_player_or_none - cache_player - caching player data: {json_data}') + logger.info( + f"gameplay_models - get_player_or_none - cache_player - caching player data: {json_data}" + ) valid_player = PlayerBase.model_validate(json_data, from_attributes=True) db_player = Player.model_validate(valid_player) try: this_player = session.get(Player, player_id) - logger.info(f'Found player: {this_player}\nUpdating with db_player: {db_player}') - + logger.info( + f"Found player: {this_player}\nUpdating with db_player: {db_player}" + ) + for key, value in db_player.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_player, key, value) - logger.info(f'Set this_player to db_player') + logger.info(f"Set this_player to db_player") session.add(this_player) session.commit() - logger.info(f'Refreshing this_player') + logger.info(f"Refreshing this_player") session.refresh(this_player) return this_player - except: + except sqlalchemy.exc.NoResultFound: session.add(db_player) session.commit() session.refresh(db_player) return db_player - - p_query = await db_get('players', object_id=player_id, params=[('inc_dex', False)]) + + p_query = await db_get("players", object_id=player_id, params=[("inc_dex", False)]) if p_query is not None: - if 'id' not in p_query: - p_query['id'] = p_query['player_id'] - if 'name' not in p_query: - p_query['name'] = p_query['p_name'] + if "id" not in p_query: + p_query["id"] = p_query["player_id"] + if "name" not in p_query: + p_query["name"] = p_query["p_name"] return cache_player(p_query) - + return None -async def get_batter_scouting_or_none(session: Session, card: Card, skip_cache: bool = False) -> BatterScouting | None: - logger.info(f'Getting batting scouting for card ID #{card.id}: {card.player.name_with_desc} / skip_cache: {skip_cache}') +async def get_batter_scouting_or_none( + session: Session, card: Card, skip_cache: bool = False +) -> BatterScouting | None: + logger.info( + f"Getting batting scouting for card ID #{card.id}: {card.player.name_with_desc} / skip_cache: {skip_cache}" + ) - s_query = await db_get(f'battingcardratings/player/{card.player.id}?variant={card.variant}', none_okay=False) - if s_query['count'] != 2: - log_exception(DatabaseError, f'Scouting for {card.player.name_with_desc} was not found.') + s_query = await db_get( + f"battingcardratings/player/{card.player.id}?variant={card.variant}", + none_okay=False, + ) + if s_query["count"] != 2: + log_exception( + DatabaseError, f"Scouting for {card.player.name_with_desc} was not found." + ) - bs_query = session.exec(select(BatterScouting).where(BatterScouting.battingcard_id == s_query['ratings'][0]['battingcard']['id'])).all() - logger.info(f'bs_query: {bs_query}') + bs_query = session.exec( + select(BatterScouting).where( + BatterScouting.battingcard_id == s_query["ratings"][0]["battingcard"]["id"] + ) + ).all() + logger.info(f"bs_query: {bs_query}") if len(bs_query) > 0: this_scouting = bs_query[0] - logger.info(f'this_scouting: {this_scouting}') - logger.info(f'we found a cached scouting: {this_scouting} / created {this_scouting.created}') + logger.info(f"this_scouting: {this_scouting}") + logger.info( + f"we found a cached scouting: {this_scouting} / created {this_scouting.created}" + ) tdelta = datetime.datetime.now() - this_scouting.created - logger.debug(f'tdelta: {tdelta}') - if tdelta.total_seconds() < CACHE_LIMIT and None not in [this_scouting.battingcard, this_scouting.ratings_vl, this_scouting.ratings_vr]: - logger.info(f'returning cached scouting') + logger.debug(f"tdelta: {tdelta}") + if tdelta.total_seconds() < CACHE_LIMIT and None not in [ + this_scouting.battingcard, + this_scouting.ratings_vl, + this_scouting.ratings_vr, + ]: + logger.info(f"returning cached scouting") return this_scouting else: - logger.info(f'Refreshing cache') + logger.info(f"Refreshing cache") # logger.info(f'deleting cached scouting') # session.delete(this_scouting.battingcard) # session.delete(this_scouting.ratings_vl) @@ -280,8 +399,10 @@ async def get_batter_scouting_or_none(session: Session, card: Card, skip_cache: # session.delete(this_scouting) # session.commit() - def cache_scouting(batting_card: dict, ratings_vr: dict, ratings_vl: dict) -> BatterScouting: - logger.info(f'Beginning batter scouting cache process') + def cache_scouting( + batting_card: dict, ratings_vr: dict, ratings_vl: dict + ) -> BatterScouting: + logger.info(f"Beginning batter scouting cache process") valid_bc = BattingCardBase.model_validate(batting_card, from_attributes=True) db_bc = BattingCard.model_validate(valid_bc) @@ -290,71 +411,81 @@ async def get_batter_scouting_or_none(session: Session, card: Card, skip_cache: valid_vr = BattingRatingsBase.model_validate(ratings_vr, from_attributes=True) db_vr = BattingRatings.model_validate(valid_vr) - logger.info(f'db_bc: {db_bc}\n\ndb_vl: {db_vl}\n\ndb_vr: {db_vr}') + logger.info(f"db_bc: {db_bc}\n\ndb_vl: {db_vl}\n\ndb_vr: {db_vr}") - logger.info(f'Checking for existing battingcard ID: {db_bc.id}') + logger.info(f"Checking for existing battingcard ID: {db_bc.id}") try: - this_card = session.exec(select(BattingCard).where(BattingCard.id == db_bc.id)).one() - logger.info(f'Found card: {this_card}\nUpdating with db card: {db_bc}') - + this_card = session.exec( + select(BattingCard).where(BattingCard.id == db_bc.id) + ).one() + logger.info(f"Found card: {this_card}\nUpdating with db card: {db_bc}") + for key, value in db_bc.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_card, key, value) - logger.info(f'Set this_card to db_bc') + logger.info(f"Set this_card to db_bc") session.add(this_card) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_card = db_bc session.add(this_card) # session.commit() # session.refresh(db_card) # return db_card - logger.info(f'Checking for existing vl ratings ID: {db_vl.id}') + logger.info(f"Checking for existing vl ratings ID: {db_vl.id}") try: - this_vl_rating = session.exec(select(BattingRatings).where(BattingRatings.id == db_vl.id)).one() - logger.info(f'Found ratings: {this_vl_rating}\nUpdating with db ratings: {db_vl}') - + this_vl_rating = session.exec( + select(BattingRatings).where(BattingRatings.id == db_vl.id) + ).one() + logger.info( + f"Found ratings: {this_vl_rating}\nUpdating with db ratings: {db_vl}" + ) + for key, value in db_vl.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_vl_rating, key, value) - logger.info(f'Set this_vr_rating to db_vl') + logger.info(f"Set this_vr_rating to db_vl") session.add(this_vl_rating) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_vl_rating = db_vl session.add(this_vl_rating) # session.commit() # session.refresh(db_card) # return db_card - logger.info(f'Checking for existing vr ratings ID: {db_vr.id}') + logger.info(f"Checking for existing vr ratings ID: {db_vr.id}") try: - this_vr_rating = session.exec(select(BattingRatings).where(BattingRatings.id == db_vr.id)).one() - logger.info(f'Found ratings: {this_vr_rating}\nUpdating with db ratings: {db_vr}') - + this_vr_rating = session.exec( + select(BattingRatings).where(BattingRatings.id == db_vr.id) + ).one() + logger.info( + f"Found ratings: {this_vr_rating}\nUpdating with db ratings: {db_vr}" + ) + for key, value in db_vr.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_vr_rating, key, value) - logger.info(f'Set this_vr_rating to db_vl') + logger.info(f"Set this_vr_rating to db_vl") session.add(this_vr_rating) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_vr_rating = db_vr session.add(this_vr_rating) # session.commit() @@ -362,9 +493,7 @@ async def get_batter_scouting_or_none(session: Session, card: Card, skip_cache: # return db_card db_scouting = BatterScouting( - battingcard=this_card, - ratings_vl=this_vl_rating, - ratings_vr=this_vr_rating + battingcard=this_card, ratings_vl=this_vl_rating, ratings_vr=this_vr_rating ) # db_scouting = BatterScouting( @@ -372,53 +501,85 @@ async def get_batter_scouting_or_none(session: Session, card: Card, skip_cache: # ratings_vl=db_vl, # ratings_vr=db_vr # ) - + session.add(db_scouting) - logger.info(f'caching scouting') + logger.info(f"caching scouting") session.commit() session.refresh(db_scouting) - logger.info(f'scouting id: {db_scouting.id} / battingcard: {db_scouting.battingcard.id} / vL: {db_scouting.ratings_vl.id} / vR: {db_scouting.ratings_vr.id}') + logger.info( + f"scouting id: {db_scouting.id} / battingcard: {db_scouting.battingcard.id} / vL: {db_scouting.ratings_vl.id} / vR: {db_scouting.ratings_vr.id}" + ) return db_scouting - + return cache_scouting( - batting_card=s_query['ratings'][0]['battingcard'], - ratings_vr=s_query['ratings'][0] if s_query['ratings'][0]['vs_hand'] == 'R' else s_query['ratings'][1], - ratings_vl=s_query['ratings'][0] if s_query['ratings'][0]['vs_hand'] == 'L' else s_query['ratings'][1] + batting_card=s_query["ratings"][0]["battingcard"], + ratings_vr=( + s_query["ratings"][0] + if s_query["ratings"][0]["vs_hand"] == "R" + else s_query["ratings"][1] + ), + ratings_vl=( + s_query["ratings"][0] + if s_query["ratings"][0]["vs_hand"] == "L" + else s_query["ratings"][1] + ), ) -async def get_pitcher_scouting_or_none(session: Session, card: Card, skip_cache: bool = False) -> PitcherScouting | None: - logger.info(f'Getting pitching scouting for card ID #{card.id}: {card.player.name_with_desc}') - - s_query = await db_get(f'pitchingcardratings/player/{card.player.id}?variant={card.variant}', none_okay=False) - if s_query['count'] != 2: - log_exception(DatabaseError, f'Scouting for {card.player.name_with_desc} was not found.') +async def get_pitcher_scouting_or_none( + session: Session, card: Card, skip_cache: bool = False +) -> PitcherScouting | None: + logger.info( + f"Getting pitching scouting for card ID #{card.id}: {card.player.name_with_desc}" + ) - bs_query = session.exec(select(PitcherScouting).where(PitcherScouting.pitchingcard_id == s_query['ratings'][0]['pitchingcard']['id'])).all() - logger.info(f'bs_query: {bs_query}') + s_query = await db_get( + f"pitchingcardratings/player/{card.player.id}?variant={card.variant}", + none_okay=False, + ) + if s_query["count"] != 2: + log_exception( + DatabaseError, f"Scouting for {card.player.name_with_desc} was not found." + ) + + bs_query = session.exec( + select(PitcherScouting).where( + PitcherScouting.pitchingcard_id + == s_query["ratings"][0]["pitchingcard"]["id"] + ) + ).all() + logger.info(f"bs_query: {bs_query}") # this_scouting = session.get(PitcherScouting, s_query['ratings'][0]['pitchingcard']['id']) if len(bs_query) > 0: this_scouting = bs_query[0] - logger.info(f'we found a cached scouting: {this_scouting} / created {this_scouting.created}') + logger.info( + f"we found a cached scouting: {this_scouting} / created {this_scouting.created}" + ) tdelta = datetime.datetime.now() - this_scouting.created - logger.debug(f'tdelta: {tdelta}') + logger.debug(f"tdelta: {tdelta}") - if tdelta.total_seconds() < CACHE_LIMIT and None not in [this_scouting.pitchingcard, this_scouting.ratings_vl, this_scouting.ratings_vr]: - logger.info(f'returning cached scouting') + if tdelta.total_seconds() < CACHE_LIMIT and None not in [ + this_scouting.pitchingcard, + this_scouting.ratings_vl, + this_scouting.ratings_vr, + ]: + logger.info(f"returning cached scouting") return this_scouting - + else: - logger.info(f'Refreshing cache') + logger.info(f"Refreshing cache") # logger.info(f'deleting cached scouting') # session.delete(this_scouting.pitchingcard) # session.delete(this_scouting.ratings_vl) # session.delete(this_scouting.ratings_vr) # session.delete(this_scouting) # session.commit() - - def cache_scouting(pitching_card: dict, ratings_vr: dict, ratings_vl: dict) -> PitcherScouting: - logger.info(f'Beginning pitcher scouting cache process') + + def cache_scouting( + pitching_card: dict, ratings_vr: dict, ratings_vl: dict + ) -> PitcherScouting: + logger.info(f"Beginning pitcher scouting cache process") valid_bc = PitchingCardBase.model_validate(pitching_card, from_attributes=True) db_bc = PitchingCard.model_validate(valid_bc) @@ -427,71 +588,81 @@ async def get_pitcher_scouting_or_none(session: Session, card: Card, skip_cache: valid_vr = PitchingRatingsBase.model_validate(ratings_vr, from_attributes=True) db_vr = PitchingRatings.model_validate(valid_vr) - logger.info(f'db_bc: {db_bc}\n\ndb_vl: {db_vl}\n\ndb_vr: {db_vr}') + logger.info(f"db_bc: {db_bc}\n\ndb_vl: {db_vl}\n\ndb_vr: {db_vr}") - logger.info(f'Checking for existing battingcard ID: {db_bc.id}') + logger.info(f"Checking for existing battingcard ID: {db_bc.id}") try: - this_card = session.exec(select(PitchingCard).where(PitchingCard.id == db_bc.id)).one() - logger.info(f'Found card: {this_card}\nUpdating with db card: {db_bc}') - + this_card = session.exec( + select(PitchingCard).where(PitchingCard.id == db_bc.id) + ).one() + logger.info(f"Found card: {this_card}\nUpdating with db card: {db_bc}") + for key, value in db_bc.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_card, key, value) - logger.info(f'Set this_card to db_bc') + logger.info(f"Set this_card to db_bc") session.add(this_card) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_card = db_bc session.add(this_card) # session.commit() # session.refresh(db_card) # return db_card - logger.info(f'Checking for existing vl ratings ID: {db_vl.id}') + logger.info(f"Checking for existing vl ratings ID: {db_vl.id}") try: - this_vl_rating = session.exec(select(PitchingRatings).where(PitchingRatings.id == db_vl.id)).one() - logger.info(f'Found ratings: {this_vl_rating}\nUpdating with db ratings: {db_vl}') - + this_vl_rating = session.exec( + select(PitchingRatings).where(PitchingRatings.id == db_vl.id) + ).one() + logger.info( + f"Found ratings: {this_vl_rating}\nUpdating with db ratings: {db_vl}" + ) + for key, value in db_vl.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_vl_rating, key, value) - logger.info(f'Set this_vr_rating to db_vl') + logger.info(f"Set this_vr_rating to db_vl") session.add(this_vl_rating) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_vl_rating = db_vl session.add(this_vl_rating) # session.commit() # session.refresh(db_card) # return db_card - logger.info(f'Checking for existing vr ratings ID: {db_vr.id}') + logger.info(f"Checking for existing vr ratings ID: {db_vr.id}") try: - this_vr_rating = session.exec(select(PitchingRatings).where(PitchingRatings.id == db_vr.id)).one() - logger.info(f'Found ratings: {this_vr_rating}\nUpdating with db ratings: {db_vr}') - + this_vr_rating = session.exec( + select(PitchingRatings).where(PitchingRatings.id == db_vr.id) + ).one() + logger.info( + f"Found ratings: {this_vr_rating}\nUpdating with db ratings: {db_vr}" + ) + for key, value in db_vr.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_vr_rating, key, value) - logger.info(f'Set this_vr_rating to db_vl') + logger.info(f"Set this_vr_rating to db_vl") session.add(this_vr_rating) # session.commit() # logger.info(f'Refreshing this_card') # session.refresh(this_card) # return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") this_vr_rating = db_vr session.add(this_vr_rating) # session.commit() @@ -499,87 +670,115 @@ async def get_pitcher_scouting_or_none(session: Session, card: Card, skip_cache: # return db_card db_scouting = PitcherScouting( - pitchingcard=this_card, - ratings_vl=this_vl_rating, - ratings_vr=this_vr_rating + pitchingcard=this_card, ratings_vl=this_vl_rating, ratings_vr=this_vr_rating ) - + session.add(db_scouting) - logger.info(f'caching scouting') + logger.info(f"caching scouting") session.commit() session.refresh(db_scouting) - logger.info(f'scouting id: {db_scouting.id} / pitching: {db_scouting.pitchingcard.id} / vL: {db_scouting.ratings_vl.id} / vR: {db_scouting.ratings_vr.id}') + logger.info( + f"scouting id: {db_scouting.id} / pitching: {db_scouting.pitchingcard.id} / vL: {db_scouting.ratings_vl.id} / vR: {db_scouting.ratings_vr.id}" + ) return db_scouting scouting = cache_scouting( - pitching_card=s_query['ratings'][0]['pitchingcard'], - ratings_vr=s_query['ratings'][0] if s_query['ratings'][0]['vs_hand'] == 'R' else s_query['ratings'][1], - ratings_vl=s_query['ratings'][0] if s_query['ratings'][0]['vs_hand'] == 'L' else s_query['ratings'][1] + pitching_card=s_query["ratings"][0]["pitchingcard"], + ratings_vr=( + s_query["ratings"][0] + if s_query["ratings"][0]["vs_hand"] == "R" + else s_query["ratings"][1] + ), + ratings_vl=( + s_query["ratings"][0] + if s_query["ratings"][0]["vs_hand"] == "L" + else s_query["ratings"][1] + ), ) - pos_rating = await get_position(session, card, 'P') + pos_rating = await get_position(session, card, "P") return scouting def get_player_id_from_dict(json_data: dict) -> int: - logger.info(f'Getting player from dict {json_data}') - if 'player_id' in json_data: - return json_data['player_id'] - elif 'id' in json_data: - return json_data['id'] - log_exception(KeyError, 'Player ID could not be extracted from json data') + logger.info(f"Getting player from dict {json_data}") + if "player_id" in json_data: + return json_data["player_id"] + elif "id" in json_data: + return json_data["id"] + log_exception(KeyError, "Player ID could not be extracted from json data") def get_player_name_from_dict(json_data: dict) -> str: - logger.info(f'Getting player from dict {json_data}') - if 'name' in json_data: - return json_data['name'] - elif 'p_name' in json_data: - return json_data['p_name'] - log_exception(KeyError, 'Player name could not be extracted from json data') + logger.info(f"Getting player from dict {json_data}") + if "name" in json_data: + return json_data["name"] + elif "p_name" in json_data: + return json_data["p_name"] + log_exception(KeyError, "Player name could not be extracted from json data") -async def shared_get_scouting(session: Session, this_card: Card, which: Literal['batter', 'pitcher']): - if which == 'batter': - logger.info(f'Pulling batter scouting for {this_card.player.name_with_desc}') +async def shared_get_scouting( + session: Session, this_card: Card, which: Literal["batter", "pitcher"] +): + if which == "batter": + logger.info(f"Pulling batter scouting for {this_card.player.name_with_desc}") this_scouting = await get_batter_scouting_or_none(session, this_card) else: - logger.info(f'Pulling pitcher scouting for {this_card.player.name_with_desc}') + logger.info(f"Pulling pitcher scouting for {this_card.player.name_with_desc}") this_scouting = await get_pitcher_scouting_or_none(session, this_card) - logger.info(f'this_scouting: {this_scouting}') + logger.info(f"this_scouting: {this_scouting}") return this_scouting -async def get_position(session: Session, this_card: Card, position: Literal['P', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF'], skip_cache: bool = False) -> PositionRating: - logger.info(f'Pulling position rating for {this_card.player.name_with_desc} at {position} / skip_cache: {skip_cache}') +async def get_position( + session: Session, + this_card: Card, + position: Literal["P", "C", "1B", "2B", "3B", "SS", "LF", "CF", "RF"], + skip_cache: bool = False, +) -> PositionRating: + logger.info( + f"Pulling position rating for {this_card.player.name_with_desc} at {position} / skip_cache: {skip_cache}" + ) if not skip_cache: - this_pos = session.exec(select(PositionRating).where(PositionRating.player_id == this_card.player.id, PositionRating.position == position, PositionRating.variant == this_card.variant)).all() - logger.info(f'Ratings found: {len(this_pos)}') + this_pos = session.exec( + select(PositionRating).where( + PositionRating.player_id == this_card.player.id, + PositionRating.position == position, + PositionRating.variant == this_card.variant, + ) + ).all() + logger.info(f"Ratings found: {len(this_pos)}") if len(this_pos) > 0: - logger.info(f'we found a cached position rating: {this_pos[0]} / created: {this_pos[0].created}') + logger.info( + f"we found a cached position rating: {this_pos[0]} / created: {this_pos[0].created}" + ) tdelta = datetime.datetime.now() - this_pos[0].created - logger.debug(f'tdelta: {tdelta}') + logger.debug(f"tdelta: {tdelta}") if tdelta.total_seconds() < CACHE_LIMIT: return this_pos[0] else: session.delete(this_pos[0]) session.commit() - + def cache_pos(json_data: dict) -> PositionRating: - if 'id' in json_data: - del json_data['id'] + if "id" in json_data: + del json_data["id"] valid_pos = PositionRatingBase.model_validate(json_data, from_attributes=True) db_pos = PositionRating.model_validate(valid_pos) session.add(db_pos) session.commit() session.refresh(db_pos) return db_pos - - p_query = await db_get('cardpositions', params=[('player_id', this_card.player.id), ('position', position)]) - if p_query['count'] > 0: - json_data = p_query['positions'][0] - json_data['player_id'] = get_player_id_from_dict(json_data['player']) + + p_query = await db_get( + "cardpositions", + params=[("player_id", this_card.player.id), ("position", position)], + ) + if p_query["count"] > 0: + json_data = p_query["positions"][0] + json_data["player_id"] = get_player_id_from_dict(json_data["player"]) this_pos = cache_pos(json_data) session.add(this_pos) @@ -587,86 +786,119 @@ async def get_position(session: Session, this_card: Card, position: Literal['P', session.refresh(this_pos) return this_pos - - log_exception(PositionNotFoundException, f'{position} ratings not found for {this_card.player.name_with_desc}') + + log_exception( + PositionNotFoundException, + f"{position} ratings not found for {this_card.player.name_with_desc}", + ) -async def get_all_positions(session: Session, this_card: Card, skip_cache: bool = False) -> int: - logger.info(f'Pulling all position ratings for {this_card.player.name_with_desc} / skip_cache: {skip_cache}') +async def get_all_positions( + session: Session, this_card: Card, skip_cache: bool = False +) -> int: + logger.info( + f"Pulling all position ratings for {this_card.player.name_with_desc} / skip_cache: {skip_cache}" + ) if not skip_cache: - all_pos = session.exec(select(PositionRating).where(PositionRating.player_id == this_card.player.id, PositionRating.variant == this_card.variant)).all() - logger.info(f'Ratings found: {len(all_pos)}') + all_pos = session.exec( + select(PositionRating).where( + PositionRating.player_id == this_card.player.id, + PositionRating.variant == this_card.variant, + ) + ).all() + logger.info(f"Ratings found: {len(all_pos)}") should_repull = False for position in all_pos: - logger.info(f'we found a cached position rating: {position} / created: {position.created}') + logger.info( + f"we found a cached position rating: {position} / created: {position.created}" + ) tdelta = datetime.datetime.now() - position.created - logger.debug(f'tdelta: {tdelta}') + logger.debug(f"tdelta: {tdelta}") if tdelta.total_seconds() >= CACHE_LIMIT or datetime.datetime.now().day < 5: session.delete(position) session.commit() should_repull = True - + if not should_repull and len(all_pos) > 0: - logger.info(f'Returning {len(all_pos)}') + logger.info(f"Returning {len(all_pos)}") return len(all_pos) - p_query = await db_get('cardpositions', params=[('player_id', this_card.player.id)]) + p_query = await db_get("cardpositions", params=[("player_id", this_card.player.id)]) - if not p_query or p_query['count'] == 0: - logger.info(f'No positions received, returning 0') + if not p_query or p_query["count"] == 0: + logger.info(f"No positions received, returning 0") return 0 - - old_pos = session.exec(select(PositionRating).where(PositionRating.player_id == this_card.player_id)).all() + + old_pos = session.exec( + select(PositionRating).where(PositionRating.player_id == this_card.player_id) + ).all() for position in old_pos: - logger.info(f'Deleting orphaned position rating: {position}') + logger.info(f"Deleting orphaned position rating: {position}") session.delete(position) - + session.commit() - + def cache_pos(json_data: dict) -> PositionRating: - if 'id' in json_data: - del json_data['id'] + if "id" in json_data: + del json_data["id"] valid_pos = PositionRatingBase.model_validate(json_data, from_attributes=True) db_pos = PositionRating.model_validate(valid_pos) session.add(db_pos) session.commit() session.refresh(db_pos) return db_pos - + added_count = 0 - for json_data in p_query['positions']: - logger.info(f'Processing: {json_data}') - json_data['player_id'] = get_player_id_from_dict(json_data['player']) + for json_data in p_query["positions"]: + logger.info(f"Processing: {json_data}") + json_data["player_id"] = get_player_id_from_dict(json_data["player"]) this_pos = cache_pos(json_data) session.add(this_pos) added_count += 1 - + return added_count -async def get_or_create_ai_card(session: Session, player: Player, team: Team, skip_cache: bool = False, dev_mode: bool = False) -> Card: - logger.info(f'Getting or creating card for {player.name_with_desc} on the {team.sname} / skip_cache: {skip_cache}') +async def get_or_create_ai_card( + session: Session, + player: Player, + team: Team, + skip_cache: bool = False, + dev_mode: bool = False, +) -> Card: + logger.info( + f"Getting or creating card for {player.name_with_desc} on the {team.sname} / skip_cache: {skip_cache}" + ) if not team.is_ai: - err = f'Cannot create AI cards for human teams' - logger.error(f'gameplay_models - get_or_create_ai_card: {err}') + err = f"Cannot create AI cards for human teams" + logger.error(f"gameplay_models - get_or_create_ai_card: {err}") raise TypeError(err) - - logger.info(f'gameplay_models - get_or_create_ai_card - player.id: {player.id} / team.id: {team.id}') + + logger.info( + f"gameplay_models - get_or_create_ai_card - player.id: {player.id} / team.id: {team.id}" + ) if not skip_cache: - c_query = session.exec(select(Card).where(Card.player == player, Card.team == team)).all() + c_query = session.exec( + select(Card).where(Card.player == player, Card.team == team) + ).all() if len(c_query) > 0: this_card = c_query[0] - logger.info(f'we found a cached card: {this_card} / created: {this_card.created}') + logger.info( + f"we found a cached card: {this_card} / created: {this_card.created}" + ) tdelta = datetime.datetime.now() - this_card.created - logger.debug(f'tdelta: {tdelta}') - if tdelta.total_seconds() < CACHE_LIMIT and (this_card.pitcherscouting is not None or this_card.batterscouting is not None): - logger.info(f'returning this_card') + logger.debug(f"tdelta: {tdelta}") + if tdelta.total_seconds() < CACHE_LIMIT and ( + this_card.pitcherscouting is not None + or this_card.batterscouting is not None + ): + logger.info(f"returning this_card") return this_card # else: # logger.info(f'deleting card record') @@ -674,58 +906,73 @@ async def get_or_create_ai_card(session: Session, player: Player, team: Team, sk # session.commit() async def pull_card(p: Player, t: Team): - c_query = await db_get('cards', params=[('team_id', t.id), ('player_id', p.id)]) - if c_query['count'] > 0: - json_data = c_query['cards'][0] - logger.info(f'gameplay_models - get_or_create_ai_card - pull_card - caching json_data: {json_data}') - json_data['team_id'] = json_data['team']['id'] - json_data['player_id'] = get_player_id_from_dict(json_data['player']) - valid_card = CardBase.model_validate(c_query['cards'][0], from_attributes=True) + c_query = await db_get("cards", params=[("team_id", t.id), ("player_id", p.id)]) + if c_query["count"] > 0: + json_data = c_query["cards"][0] + logger.info( + f"gameplay_models - get_or_create_ai_card - pull_card - caching json_data: {json_data}" + ) + json_data["team_id"] = json_data["team"]["id"] + json_data["player_id"] = get_player_id_from_dict(json_data["player"]) + valid_card = CardBase.model_validate( + c_query["cards"][0], from_attributes=True + ) db_card = Card.model_validate(valid_card) - logger.info(f'gameplay_queries - cache_team - db_card: {db_card}') - logger.info(f'Checking for existing card ID: {db_card.id}') + logger.info(f"gameplay_queries - cache_team - db_card: {db_card}") + logger.info(f"Checking for existing card ID: {db_card.id}") try: - this_card = session.exec(select(Card).where(Card.id == db_card.id)).one() - logger.info(f'Found card: {this_card}\nUpdating with db card: {db_card}') - + this_card = session.exec( + select(Card).where(Card.id == db_card.id) + ).one() + logger.info( + f"Found card: {this_card}\nUpdating with db card: {db_card}" + ) + for key, value in db_card.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_card, key, value) - logger.info(f'Set this_card to db_card') + logger.info(f"Set this_card to db_card") session.add(this_card) session.commit() - logger.info(f'Refreshing this_card') + logger.info(f"Refreshing this_card") session.refresh(this_card) return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") session.add(db_card) session.commit() session.refresh(db_card) return db_card else: return None - + this_card = await pull_card(player, team) if this_card is not None: - if player.pos_1 not in ['SP', 'RP']: - this_card.batterscouting = await shared_get_scouting(session, this_card, 'batter') + if player.pos_1 not in ["SP", "RP"]: + this_card.batterscouting = await shared_get_scouting( + session, this_card, "batter" + ) else: - this_card.pitcherscouting = await shared_get_scouting(session, this_card, 'pitcher') - + this_card.pitcherscouting = await shared_get_scouting( + session, this_card, "pitcher" + ) + session.add(this_card) session.commit() session.refresh(this_card) return this_card - logger.info(f'gameplay_models - get_or_create_ai_card: creating {player.description} {player.name} card for {team.abbrev}') + logger.info( + f"gameplay_models - get_or_create_ai_card: creating {player.description} {player.name} card for {team.abbrev}" + ) if dev_mode: # Find next available ID since Card model has autoincrement=False from sqlmodel import func + max_id = session.exec(select(func.max(Card.id))).one() next_id = (max_id or 0) + 1 this_card = Card(id=next_id, player=player, team=team) @@ -735,42 +982,51 @@ async def get_or_create_ai_card(session: Session, player: Player, team: Team, sk return this_card await db_post( - 'cards', - payload={'cards': [ - {'player_id': player.id, 'team_id': team.id, 'pack_id': 1} - ]} + "cards", + payload={"cards": [{"player_id": player.id, "team_id": team.id, "pack_id": 1}]}, ) - + this_card = await pull_card(player, team) if this_card is not None: - if player.pos_1 not in ['SP', 'RP']: - this_card.batterscouting = await shared_get_scouting(session, this_card, 'batter') + if player.pos_1 not in ["SP", "RP"]: + this_card.batterscouting = await shared_get_scouting( + session, this_card, "batter" + ) else: - this_card.pitcherscouting = await shared_get_scouting(session, this_card, 'pitcher') - + this_card.pitcherscouting = await shared_get_scouting( + session, this_card, "pitcher" + ) + session.add(this_card) session.commit() session.refresh(this_card) return this_card - - err = f'Could not create {player.name} card for {team.abbrev}' - logger.error(f'gameplay_models - get_or_create_ai_card - {err}') + + err = f"Could not create {player.name} card for {team.abbrev}" + logger.error(f"gameplay_models - get_or_create_ai_card - {err}") raise LookupError(err) @log_errors -async def get_card_or_none(session: Session, card_id: int, skip_cache: bool = False) -> Card | None: - logger.info(f'Getting card {card_id} / skip_cache: {skip_cache}') +async def get_card_or_none( + session: Session, card_id: int, skip_cache: bool = False +) -> Card | None: + logger.info(f"Getting card {card_id} / skip_cache: {skip_cache}") if not skip_cache: this_card = session.get(Card, card_id) if this_card is not None: - logger.info(f'we found a cached card: {this_card} / created: {this_card.created}') + logger.info( + f"we found a cached card: {this_card} / created: {this_card.created}" + ) tdelta = datetime.datetime.now() - this_card.created - logger.debug(f'tdelta: {tdelta}') - if tdelta.total_seconds() < CACHE_LIMIT and (this_card.pitcherscouting is not None or this_card.batterscouting is not None): - logger.info(f'returning this_card') + logger.debug(f"tdelta: {tdelta}") + if tdelta.total_seconds() < CACHE_LIMIT and ( + this_card.pitcherscouting is not None + or this_card.batterscouting is not None + ): + logger.info(f"returning this_card") return this_card # else: # logger.info(f'deleting this_card') @@ -778,7 +1034,7 @@ async def get_card_or_none(session: Session, card_id: int, skip_cache: bool = Fa # session.delete(this_card.batterscouting) # except Exception as e: # logger.error(f'Could not delete batter scouting: {e}') - + # try: # session.delete(this_card.pitcherscouting) # except Exception as e: @@ -786,120 +1042,183 @@ async def get_card_or_none(session: Session, card_id: int, skip_cache: bool = Fa # session.delete(this_card) # session.commit() - + def cache_card(json_data: dict) -> Card: valid_card = CardBase.model_validate(json_data, from_attributes=True) db_card = Card.model_validate(valid_card) - logger.info(f'gameplay_queries - cache_team - db_card: {db_card}') - logger.info(f'Checking for existing card ID: {db_card.id}') + logger.info(f"gameplay_queries - cache_team - db_card: {db_card}") + logger.info(f"Checking for existing card ID: {db_card.id}") try: this_card = session.exec(select(Card).where(Card.id == db_card.id)).one() - logger.info(f'Found card: {this_card}\nUpdating with db card: {db_card}') - + logger.info(f"Found card: {this_card}\nUpdating with db card: {db_card}") + # this_team = db_team for key, value in db_card.model_dump(exclude_unset=True).items(): - logger.info(f'Setting key ({key}) to value ({value})') + logger.info(f"Setting key ({key}) to value ({value})") setattr(this_card, key, value) - logger.info(f'Set this_card to db_card') + logger.info(f"Set this_card to db_card") session.add(this_card) session.commit() - logger.info(f'Refreshing this_card') + logger.info(f"Refreshing this_card") session.refresh(this_card) return this_card - except: - logger.info(f'Card not found, adding to db') + except sqlalchemy.exc.NoResultFound: + logger.info(f"Card not found, adding to db") session.add(db_card) session.commit() session.refresh(db_card) return db_card - - c_query = await db_get('cards', object_id=card_id) + + c_query = await db_get("cards", object_id=card_id) if c_query is not None: - c_query['team_id'] = c_query['team']['id'] - c_query['player_id'] = get_player_id_from_dict(c_query['player']) - - this_player = await get_player_or_none(session, player_id=c_query['player_id']) - this_team = await get_team_or_none(session, team_id=c_query['team_id']) + c_query["team_id"] = c_query["team"]["id"] + c_query["player_id"] = get_player_id_from_dict(c_query["player"]) + + this_player = await get_player_or_none(session, player_id=c_query["player_id"]) + this_team = await get_team_or_none(session, team_id=c_query["team_id"]) if this_player is None: - raise LookupError(f'Player ID {c_query["player_id"]} not found during card check') + raise LookupError( + f'Player ID {c_query["player_id"]} not found during card check' + ) if this_team is None: - raise LookupError(f'Team ID {c_query["team_id"]} not found during card check') + raise LookupError( + f'Team ID {c_query["team_id"]} not found during card check' + ) - logger.info(f'Caching card ID {card_id} now') + logger.info(f"Caching card ID {card_id} now") this_card = cache_card(c_query) - - logger.info(f'Card is cached, checking for scouting') - all_pos = [x for x in [this_player.pos_1, this_player.pos_2, this_player.pos_3, this_player.pos_3, this_player.pos_4, this_player.pos_5, this_player.pos_6, this_player.pos_7, this_player.pos_8] if x is not None] - logger.info(f'All positions: {all_pos}') - if 'SP' in all_pos or 'RP' in all_pos: - logger.info(f'Pulling pitcher scouting') - this_card.pitcherscouting = await shared_get_scouting(session, this_card, 'pitcher') - if any(item in all_pos for item in ['DH', 'C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF']): - logger.info(f'Pulling batter scouting') - this_card.batterscouting = await shared_get_scouting(session, this_card, 'batter') - - logger.info(f'Updating this_card') + + logger.info(f"Card is cached, checking for scouting") + all_pos = [ + x + for x in [ + this_player.pos_1, + this_player.pos_2, + this_player.pos_3, + this_player.pos_3, + this_player.pos_4, + this_player.pos_5, + this_player.pos_6, + this_player.pos_7, + this_player.pos_8, + ] + if x is not None + ] + logger.info(f"All positions: {all_pos}") + if "SP" in all_pos or "RP" in all_pos: + logger.info(f"Pulling pitcher scouting") + this_card.pitcherscouting = await shared_get_scouting( + session, this_card, "pitcher" + ) + if any( + item in all_pos + for item in ["DH", "C", "1B", "2B", "3B", "SS", "LF", "CF", "RF"] + ): + logger.info(f"Pulling batter scouting") + this_card.batterscouting = await shared_get_scouting( + session, this_card, "batter" + ) + + logger.info(f"Updating this_card") session.add(this_card) session.commit() - logger.info(f'Refreshing this_card') + logger.info(f"Refreshing this_card") session.refresh(this_card) - logger.info(f'this_card: {this_card}') + logger.info(f"this_card: {this_card}") return this_card return None -def get_game_lineups(session: Session, this_game: Game, specific_team: Team = None, is_active: bool = None) -> list[Lineup]: - logger.info(f'Getting lineups for game {this_game.id} / specific_team: {specific_team} / is_active: {is_active}') +def get_game_lineups( + session: Session, + this_game: Game, + specific_team: Team = None, + is_active: bool = None, +) -> list[Lineup]: + logger.info( + f"Getting lineups for game {this_game.id} / specific_team: {specific_team} / is_active: {is_active}" + ) st = select(Lineup).where(Lineup.game == this_game) - + if specific_team is not None: st = st.where(Lineup.team == specific_team) if is_active is not None: st = st.where(Lineup.active == is_active) - + return session.exec(st).all() -def get_players_last_pa(session: Session, lineup_member: Lineup, none_okay: bool = False): - logger.info(f'Getting last AB for {lineup_member.player.name_with_desc} on the {lineup_member.team.lname}') - last_pa = session.exec(select(Play).where(Play.game == lineup_member.game, Play.batter == lineup_member).order_by(Play.play_num.desc()).limit(1)).all() +def get_players_last_pa( + session: Session, lineup_member: Lineup, none_okay: bool = False +): + logger.info( + f"Getting last AB for {lineup_member.player.name_with_desc} on the {lineup_member.team.lname}" + ) + last_pa = session.exec( + select(Play) + .where(Play.game == lineup_member.game, Play.batter == lineup_member) + .order_by(Play.play_num.desc()) + .limit(1) + ).all() if len(last_pa) == 1: return last_pa[0] else: if none_okay: return None else: - log_exception(PlayNotFoundException, f'No play found for {lineup_member.player.name_with_desc}\'s last AB') + log_exception( + PlayNotFoundException, + f"No play found for {lineup_member.player.name_with_desc}'s last AB", + ) -def get_one_lineup(session: Session, this_game: Game, this_team: Team, active: bool = True, position: str = None, batting_order: int = None) -> Lineup: - logger.info(f'Getting one lineup / this_game: {this_game.id} / this_team: {this_team.lname} / active: {active}, position: {position}, batting_order: {batting_order}') +def get_one_lineup( + session: Session, + this_game: Game, + this_team: Team, + active: bool = True, + position: str = None, + batting_order: int = None, +) -> Lineup: + logger.info( + f"Getting one lineup / this_game: {this_game.id} / this_team: {this_team.lname} / active: {active}, position: {position}, batting_order: {batting_order}" + ) if position is None and batting_order is None: - raise KeyError('Position or batting order must be provided for get_one_lineup') - - st = select(Lineup).where(Lineup.game == this_game, Lineup.team == this_team, Lineup.active == active) + raise KeyError("Position or batting order must be provided for get_one_lineup") + + st = select(Lineup).where( + Lineup.game == this_game, Lineup.team == this_team, Lineup.active == active + ) if position is not None: st = st.where(Lineup.position == position) else: st = st.where(Lineup.batting_order == batting_order) - - logger.info(f'get_one_lineup query: {st}') + + logger.info(f"get_one_lineup query: {st}") compiled = st.compile(compile_kwargs={"literal_binds": True}) - logger.info(f'get_one_lineup literal SQL: {compiled}') + logger.info(f"get_one_lineup literal SQL: {compiled}") this_lineup = session.exec(st).one() - logger.info(f'Found lineup: {this_lineup}') + logger.info(f"Found lineup: {this_lineup}") return this_lineup -def get_last_team_play(session: Session, this_game: Game, this_team: Team, none_okay: bool = False): - logger.info(f'Getting last play for the {this_team.lname} in game {this_game.id}') - last_play = session.exec(select(Play).join(Lineup, onclause=Lineup.id == Play.batter_id).where(Play.game == this_game, Lineup.team == this_team).order_by(Play.play_num.desc()).limit(1)).all() +def get_last_team_play( + session: Session, this_game: Game, this_team: Team, none_okay: bool = False +): + logger.info(f"Getting last play for the {this_team.lname} in game {this_game.id}") + last_play = session.exec( + select(Play) + .join(Lineup, onclause=Lineup.id == Play.batter_id) + .where(Play.game == this_game, Lineup.team == this_team) + .order_by(Play.play_num.desc()) + .limit(1) + ).all() if len(last_play) == 1: return last_play[0] @@ -907,50 +1226,78 @@ def get_last_team_play(session: Session, this_game: Game, this_team: Team, none_ if none_okay: return None else: - log_exception(PlayNotFoundException, f'No last play found for the {this_team.sname}') + log_exception( + PlayNotFoundException, f"No last play found for the {this_team.sname}" + ) -def get_sorted_lineups(session: Session, this_game: Game, this_team: Team) -> list[Lineup]: - logger.info(f'Getting sorted lineups for the {this_team.lname} in game {this_game.id}') - custom_order = {'P': 1, 'C': 2, '1B': 3, '2B': 4, '3B': 5, 'SS': 6, 'LF': 7, 'CF': 8, 'RF': 9} +def get_sorted_lineups( + session: Session, this_game: Game, this_team: Team +) -> list[Lineup]: + logger.info( + f"Getting sorted lineups for the {this_team.lname} in game {this_game.id}" + ) + custom_order = { + "P": 1, + "C": 2, + "1B": 3, + "2B": 4, + "3B": 5, + "SS": 6, + "LF": 7, + "CF": 8, + "RF": 9, + } - all_lineups = session.exec(select(Lineup).where(Lineup.game == this_game, Lineup.active == True, Lineup.team == this_team)).all() + all_lineups = session.exec( + select(Lineup).where( + Lineup.game == this_game, Lineup.active == True, Lineup.team == this_team + ) + ).all() - sorted_lineups = sorted(all_lineups, key=lambda x: custom_order.get(x.position, float('inf'))) + sorted_lineups = sorted( + all_lineups, key=lambda x: custom_order.get(x.position, float("inf")) + ) return sorted_lineups def get_db_ready_plays(session: Session, this_game: Game, db_game_id: int): - logger.info(f'Getting db ready plays for game {this_game.id}') - all_plays = session.exec(select(Play).where(Play.game == this_game).order_by(Play.play_num.desc())).all() + logger.info(f"Getting db ready plays for game {this_game.id}") + all_plays = session.exec( + select(Play).where(Play.game == this_game).order_by(Play.play_num.desc()) + ).all() - obc_list = ['000', '001', '010', '100', '011', '101', '110', '111'] + obc_list = ["000", "001", "010", "100", "011", "101", "110", "111"] return_plays = [] for play in all_plays: dump = play.model_dump() - dump['game_id'] = db_game_id - dump['on_base_code'] = obc_list[play.on_base_code] - dump['batter_id'] = play.batter.player.id - dump['pitcher_id'] = play.pitcher.player.id - dump['catcher_id'] = play.catcher.player.id - if 'runner_id' in dump and dump['runner_id'] is not None: - dump['runner_id'] = play.runner.player.id - if 'defender_id' in dump and dump['defender_id'] is not None: - dump['defender_id'] = play.defender.player.id - if 'on_first_id' in dump and dump['on_first_id'] is not None: - dump['on_first_id'] = play.on_first.player.id - if 'on_second_id' in dump and dump['on_second_id'] is not None: - dump['on_second_id'] = play.on_second.player.id - if 'on_third_id' in dump and dump['on_third_id'] is not None: - dump['on_third_id'] = play.on_third.player.id + dump["game_id"] = db_game_id + dump["on_base_code"] = obc_list[play.on_base_code] + dump["batter_id"] = play.batter.player.id + dump["pitcher_id"] = play.pitcher.player.id + dump["catcher_id"] = play.catcher.player.id + if "runner_id" in dump and dump["runner_id"] is not None: + dump["runner_id"] = play.runner.player.id + if "defender_id" in dump and dump["defender_id"] is not None: + dump["defender_id"] = play.defender.player.id + if "on_first_id" in dump and dump["on_first_id"] is not None: + dump["on_first_id"] = play.on_first.player.id + if "on_second_id" in dump and dump["on_second_id"] is not None: + dump["on_second_id"] = play.on_second.player.id + if "on_third_id" in dump and dump["on_third_id"] is not None: + dump["on_third_id"] = play.on_third.player.id return_plays.append(dump) - - return {'plays': return_plays} + + return {"plays": return_plays} -def get_db_ready_decisions(session: Session, this_game: Game, db_game_id: int) -> list[DecisionModel]: - logger.info(f'Game {this_game.id} | Getting db ready decisions for game {this_game.id}') +def get_db_ready_decisions( + session: Session, this_game: Game, db_game_id: int +) -> list[DecisionModel]: + logger.info( + f"Game {this_game.id} | Getting db ready decisions for game {this_game.id}" + ) save = None away_starter = None home_starter = None @@ -968,146 +1315,219 @@ def get_db_ready_decisions(session: Session, this_game: Game, db_game_id: int) - # { : DecisionModel } } - final_inning = session.exec(select(func.max(Play.inning_num)).where(Play.game == this_game)).one() - away_starter = session.exec(select(Lineup).where(Lineup.game == this_game, Lineup.team == this_game.away_team, Lineup.position == 'P', Lineup.after_play == 0)).one() + final_inning = session.exec( + select(func.max(Play.inning_num)).where(Play.game == this_game) + ).one() + away_starter = session.exec( + select(Lineup).where( + Lineup.game == this_game, + Lineup.team == this_game.away_team, + Lineup.position == "P", + Lineup.after_play == 0, + ) + ).one() away_pitcher = away_starter last_winner = None last_loser = None # Get starting pitchers and update this as a pointer for the play crawl - for play in session.exec(select(Play).where(Play.game == this_game).order_by(Play.play_num)).all(): - logger.info(f'Game {this_game.id} | Crawling play #{play.play_num}') + for play in session.exec( + select(Play).where(Play.game == this_game).order_by(Play.play_num) + ).all(): + logger.info(f"Game {this_game.id} | Crawling play #{play.play_num}") runs_scored = 0 - if play.inning_half == 'top': + if play.inning_half == "top": if home_starter is None: - logger.info(f'Game {this_game.id} | Setting home starter to {play.pitcher.player.name_with_desc} on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting home starter to {play.pitcher.player.name_with_desc} on play #{play.play_num}" + ) home_starter = play.pitcher if home_finisher is None: - logger.info(f'Game {this_game.id} | Setting home finisher to {play.pitcher.player.name_with_desc} on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting home finisher to {play.pitcher.player.name_with_desc} on play #{play.play_num}" + ) home_finisher = play.pitcher - + if home_pitcher != play.pitcher: - logger.info(f'Game {this_game.id} | Setting home pitcher to {play.pitcher.player.name_with_desc} on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting home pitcher to {play.pitcher.player.name_with_desc} on play #{play.play_num}" + ) home_pitcher = play.pitcher if save == play.pitcher: if play.home_score > play.away_score: if play.pitcher not in holds: - logger.info(f'Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to holds on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to holds on play #{play.play_num}" + ) holds.append(play.pitcher) else: if play.pitcher not in b_save: - logger.info(f'Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to blown saves on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to blown saves on play #{play.play_num}" + ) b_save.append(play.pitcher) - - elif play.home_score > play.away_score and play.home_score - play.away_score <= 3 and home_pitcher != home_starter and play.inning_num >= final_inning - 2: - logger.info(f'Game {this_game.id} | Setting {play.pitcher.player.name_with_desc} to save on play #{play.play_num}') + + elif ( + play.home_score > play.away_score + and play.home_score - play.away_score <= 3 + and home_pitcher != home_starter + and play.inning_num >= final_inning - 2 + ): + logger.info( + f"Game {this_game.id} | Setting {play.pitcher.player.name_with_desc} to save on play #{play.play_num}" + ) save = home_pitcher - - elif play.inning_half == 'bot': + + elif play.inning_half == "bot": if away_finisher is None: - logger.info(f'Game {this_game.id} | Setting away finisher to {play.pitcher.player.name_with_desc} on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting away finisher to {play.pitcher.player.name_with_desc} on play #{play.play_num}" + ) away_finisher = play.pitcher - + if away_pitcher != play.pitcher: - logger.info(f'Game {this_game.id} | Setting away pitcher to {play.pitcher.player.name_with_desc} on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting away pitcher to {play.pitcher.player.name_with_desc} on play #{play.play_num}" + ) away_pitcher = play.pitcher if save == play.pitcher: if play.away_score > play.home_score: if play.pitcher not in holds: - logger.info(f'Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to holds on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to holds on play #{play.play_num}" + ) holds.append(play.pitcher) else: if play.pitcher not in b_save: - logger.info(f'Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to blown saves on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending {play.pitcher.player.name_with_desc} to blown saves on play #{play.play_num}" + ) b_save.append(play.pitcher) - - elif play.away_score > play.home_score and play.away_score - play.home_score <= 3 and away_pitcher != away_starter and play.inning_num >= final_inning - 2: - logger.info(f'Game {this_game.id} | Setting {play.pitcher.player.name_with_desc} to save on play #{play.play_num}') + + elif ( + play.away_score > play.home_score + and play.away_score - play.home_score <= 3 + and away_pitcher != away_starter + and play.inning_num >= final_inning - 2 + ): + logger.info( + f"Game {this_game.id} | Setting {play.pitcher.player.name_with_desc} to save on play #{play.play_num}" + ) save = away_pitcher - + if play.is_go_ahead: run_diff = play.home_score - play.away_score - for x in [play.on_first_final, play.on_second_final, play.on_third_final, play.batter_final]: + for x in [ + play.on_first_final, + play.on_second_final, + play.on_third_final, + play.batter_final, + ]: runs_scored += 1 if x == 4 else 0 - if play.inning_half == 'top': + if play.inning_half == "top": run_diff -= runs_scored else: run_diff += runs_scored - logger.info(f'run_diff for go-ahead: {run_diff}') - logger.info(f'go-ahead play: {play}') + logger.info(f"run_diff for go-ahead: {run_diff}") + logger.info(f"go-ahead play: {play}") count = 1 - for runner, dest in [(play.on_third, play.on_third_final), (play.on_second, play.on_second_final), (play.on_first, play.on_first_final), (play.batter, play.batter_final)]: - logger.info(f'Game {this_game.id} | Looking for go-ahead runner / runner, dest: {runner}, {dest} / count: {count}') + for runner, dest in [ + (play.on_third, play.on_third_final), + (play.on_second, play.on_second_final), + (play.on_first, play.on_first_final), + (play.batter, play.batter_final), + ]: + logger.info( + f"Game {this_game.id} | Looking for go-ahead runner / runner, dest: {runner}, {dest} / count: {count}" + ) if dest == 4 and count == abs(run_diff): winning_play = get_players_last_pa(session, runner) loser = winning_play.pitcher - logger.info(f'Game {this_game.id} | Setting loser to {loser} on play #{play.play_num}') - + logger.info( + f"Game {this_game.id} | Setting loser to {loser} on play #{play.play_num}" + ) + if save == loser: - logger.info(f'Game {this_game.id} | Appending {loser} to blown saves on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending {loser} to blown saves on play #{play.play_num}" + ) b_save.append(loser) - - winner = home_pitcher if play.inning_half == 'bot' else away_pitcher - logger.info(f'Game {this_game.id} | Setting winner to {winner} on play #{play.play_num}') + + winner = home_pitcher if play.inning_half == "bot" else away_pitcher + logger.info( + f"Game {this_game.id} | Setting winner to {winner} on play #{play.play_num}" + ) break count += 1 - + if winner is None: - winner = home_pitcher if play.inning_half == 'bot' else away_pitcher - logger.info(f'Game {this_game.id} | Setting winner to {winner} by default on play #{play.play_num}') - + winner = home_pitcher if play.inning_half == "bot" else away_pitcher + logger.info( + f"Game {this_game.id} | Setting winner to {winner} by default on play #{play.play_num}" + ) + if loser is None: - logger.info(f'Game {this_game.id} | Setting loser to {play.pitcher} by default on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Setting loser to {play.pitcher} by default on play #{play.play_num}" + ) loser = play.pitcher - + if play.is_tied and runs_scored == 0: - logger.info(f'Game {this_game.id} | Clearing winner and loser on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Clearing winner and loser on play #{play.play_num}" + ) last_winner = winner last_loser = loser winner, loser = None, None if save is not None: - logger.info(f'Game {this_game.id} | Appending current save pitcher {save.player.name_with_desc} to blown saves and clearing save on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Appending current save pitcher {save.player.name_with_desc} to blown saves and clearing save on play #{play.play_num}" + ) b_save.append(save) save = None - + if play.pitcher.player_id not in decisions: - logger.info(f'Game {this_game.id} | Adding {play.pitcher.player.name} to decisions dict on play #{play.play_num}') + logger.info( + f"Game {this_game.id} | Adding {play.pitcher.player.name} to decisions dict on play #{play.play_num}" + ) decisions[play.pitcher.player_id] = DecisionModel( game_id=db_game_id, season=this_game.season, week=0 if this_game.week is None else this_game.week, pitcher_id=play.pitcher.player_id, - pitcher_team_id=play.pitcher.team_id + pitcher_team_id=play.pitcher.team_id, ) - + # After the play loop, determine winner/loser from final game state if still None - final_play = session.exec(select(Play).where(Play.game == this_game).order_by(Play.play_num.desc())).first() + final_play = session.exec( + select(Play).where(Play.game == this_game).order_by(Play.play_num.desc()) + ).first() if winner is None: if final_play.home_score > final_play.away_score: winner = home_finisher - logger.info(f'Setting winner to home_finisher: {winner}') + logger.info(f"Setting winner to home_finisher: {winner}") else: winner = away_finisher - logger.info(f'Setting winner to away_finisher: {winner}') + logger.info(f"Setting winner to away_finisher: {winner}") if loser is None: if final_play.home_score > final_play.away_score: loser = away_finisher - logger.info(f'Setting loser to away_finisher: {loser}') + logger.info(f"Setting loser to away_finisher: {loser}") else: loser = home_finisher - logger.info(f'Setting loser to home_finisher: {loser}') - - logger.info(f'winner: {winner} / loser: {loser}') + logger.info(f"Setting loser to home_finisher: {loser}") + + logger.info(f"winner: {winner} / loser: {loser}") if winner is not None: decisions[winner.player_id].win = 1 if loser is not None: @@ -1120,301 +1540,453 @@ def get_db_ready_decisions(session: Session, this_game: Game, db_game_id: int) - decisions[away_finisher.player_id].game_finished = 1 if home_finisher is not None: decisions[home_finisher.player_id].game_finished = 1 - + for lineup in holds: decisions[lineup.player_id].hold = 1 - + if save is not None: decisions[save.player_id].is_save = 1 decisions[save.player_id].hold = 0 - + for lineup in b_save: decisions[lineup.player_id].b_save = 1 decisions[lineup.player_id].is_save = 0 - + return [x.model_dump() for x in decisions.values()] -async def post_game_rewards(session: Session, winning_team: Team, losing_team: Team, this_game: Game): +async def post_game_rewards( + session: Session, winning_team: Team, losing_team: Team, this_game: Game +): wr_query = await db_get( - 'gamerewards', params=[('name', f'{"Short" if this_game.short_game else "Full"} Game Win')]) + "gamerewards", + params=[("name", f'{"Short" if this_game.short_game else "Full"} Game Win')], + ) lr_query = await db_get( - 'gamerewards', params=[('name', f'{"Short" if this_game.short_game else "Full"} Game Loss')]) - if not wr_query['count'] or not lr_query['count']: - raise DatabaseError(f'Game rewards were not found. Leaving this game active.') - - win_reward = wr_query['gamerewards'][0] - loss_reward = lr_query['gamerewards'][0] + "gamerewards", + params=[("name", f'{"Short" if this_game.short_game else "Full"} Game Loss')], + ) + if not wr_query["count"] or not lr_query["count"]: + raise DatabaseError(f"Game rewards were not found. Leaving this game active.") + + win_reward = wr_query["gamerewards"][0] + loss_reward = lr_query["gamerewards"][0] win_string = f'1x {win_reward["pack_type"]["name"]} Pack\n' # Post Campaign Team Choice packs - if this_game.ai_team is not None and losing_team.is_ai and 'gauntlet' not in this_game.game_type and not this_game.short_game: - g_query = await db_get('games', params=[('team1_id', winning_team.id), ('season', this_game.season), ('forfeit', False)]) + if ( + this_game.ai_team is not None + and losing_team.is_ai + and "gauntlet" not in this_game.game_type + and not this_game.short_game + ): + g_query = await db_get( + "games", + params=[ + ("team1_id", winning_team.id), + ("season", this_game.season), + ("forfeit", False), + ], + ) win_points = 0 - for x in g_query['games']: - if (x['away_score'] > x['home_score'] and x['away_team']['id'] == winning_team.id) or (x['home_score'] > x['away_score'] and x['home_team']['id'] == winning_team.id): - if x['game_type'] == 'minor-league': + for x in g_query["games"]: + if ( + x["away_score"] > x["home_score"] + and x["away_team"]["id"] == winning_team.id + ) or ( + x["home_score"] > x["away_score"] + and x["home_team"]["id"] == winning_team.id + ): + if x["game_type"] == "minor-league": win_points += 1 - elif x['game_type'] in ['major-league', 'flashback']: + elif x["game_type"] in ["major-league", "flashback"]: win_points += 2 - - elif x['game_type'] == 'hall-of-fame': + + elif x["game_type"] == "hall-of-fame": win_points += 3 - - if this_game.game_type == 'minor-league': + + if this_game.game_type == "minor-league": this_game_points = 1 - elif this_game.game_type in ['major-league', 'flashback']: + elif this_game.game_type in ["major-league", "flashback"]: this_game_points = 2 else: this_game_points = 3 pre_game_points = win_points - this_game_points if math.floor(win_points / 6) > math.floor(pre_game_points / 6): - await db_post('packs/one', payload={ - 'team_id': winning_team.id, - 'pack_type_id': 8, - 'pack_team_id': losing_team.id - }) - win_string += f'1x {losing_team.abbrev} Team Choice pack\n' + await db_post( + "packs/one", + payload={ + "team_id": winning_team.id, + "pack_type_id": 8, + "pack_team_id": losing_team.id, + }, + ) + win_string += f"1x {losing_team.abbrev} Team Choice pack\n" win_string += f'{win_reward["money"]}₼\n' loss_string = f'{loss_reward["money"]}₼\n' - if 'gauntlet' in this_game.game_type: + if "gauntlet" in this_game.game_type: winning_abbrev = winning_team.abbrev.lower() - if 'gauntlet' in winning_abbrev: - winning_team = await get_team_or_none(session, team_abbrev=winning_abbrev.split('-')[1]) + if "gauntlet" in winning_abbrev: + winning_team = await get_team_or_none( + session, team_abbrev=winning_abbrev.split("-")[1] + ) if winning_team is None: - raise DatabaseError(f'Main team not found for {winning_abbrev}') - - losing_abbrev = losing_team.abbrev.lower() - if 'gauntlet' in losing_abbrev: - losing_team = await get_team_or_none(session, team_abbrev=losing_abbrev.split('-')[1]) - if losing_team is None: - raise DatabaseError(f'Main team not found for {losing_abbrev}') + raise DatabaseError(f"Main team not found for {winning_abbrev}") - await db_post('packs/one', payload={'team_id': winning_team.id, 'pack_type_id': win_reward['pack_type']['id']}) + losing_abbrev = losing_team.abbrev.lower() + if "gauntlet" in losing_abbrev: + losing_team = await get_team_or_none( + session, team_abbrev=losing_abbrev.split("-")[1] + ) + if losing_team is None: + raise DatabaseError(f"Main team not found for {losing_abbrev}") + + await db_post( + "packs/one", + payload={ + "team_id": winning_team.id, + "pack_type_id": win_reward["pack_type"]["id"], + }, + ) await db_post(f'teams/{winning_team.id}/money/{win_reward["money"]}') await db_post(f'teams/{losing_team.id}/money/{loss_reward["money"]}') return win_string, loss_string -def get_available_subs(session: Session, this_game: Game, this_team: Team) -> list[Card]: - logger.info(f'Getting all available subs') - team_lineups = session.exec(select(Lineup).where(Lineup.game == this_game, Lineup.team == this_team)).all() +def get_available_subs( + session: Session, this_game: Game, this_team: Team +) -> list[Card]: + logger.info(f"Getting all available subs") + team_lineups = session.exec( + select(Lineup).where(Lineup.game == this_game, Lineup.team == this_team) + ).all() used_card_ids = [x.card.id for x in team_lineups] - logger.info(f'USED CARD IDS: {used_card_ids}') + logger.info(f"USED CARD IDS: {used_card_ids}") - all_roster_links = session.exec(select(RosterLink).where(RosterLink.game == this_game, RosterLink.team == this_team)).all() + all_roster_links = session.exec( + select(RosterLink).where( + RosterLink.game == this_game, RosterLink.team == this_team + ) + ).all() return [x.card for x in all_roster_links if x.card_id not in used_card_ids] -def get_available_pitchers(session: Session, this_game: Game, this_team: Team, sort: Literal['starter-desc', 'closer-desc'] = 'closer-desc') -> list[Card]: - logger.info(f'getting available pitchers for team {this_team.id} in game {this_game.id}') +def get_available_pitchers( + session: Session, + this_game: Game, + this_team: Team, + sort: Literal["starter-desc", "closer-desc"] = "closer-desc", +) -> list[Card]: + logger.info( + f"getting available pitchers for team {this_team.id} in game {this_game.id}" + ) all_subs = get_available_subs(session, this_game, this_team) - logger.info(f'all_subs: {all_subs}') + logger.info(f"all_subs: {all_subs}") pitchers = [x for x in all_subs if x.pitcherscouting is not None] - logger.info(f'pitchers: {pitchers}') - + logger.info(f"pitchers: {pitchers}") + def sort_by_pow(this_card: Card): s_pow = this_card.pitcherscouting.pitchingcard.starter_rating r_pow = this_card.pitcherscouting.pitchingcard.relief_rating - c_pow = this_card.pitcherscouting.pitchingcard.closer_rating if this_card.pitcherscouting.pitchingcard.closer_rating is not None else 0 - - if sort == 'starter-desc': + c_pow = ( + this_card.pitcherscouting.pitchingcard.closer_rating + if this_card.pitcherscouting.pitchingcard.closer_rating is not None + else 0 + ) + + if sort == "starter-desc": r_val = (s_pow * 3) + r_pow else: r_val = (c_pow * 10) - (r_pow * 5) - (s_pow * 3) - + return r_val - + pitchers.sort(key=sort_by_pow, reverse=True) return pitchers -def get_available_batters(session: Session, this_game: Game, this_team: Team) -> list[Card]: - logger.info(f'getting available batters for team {this_team.id} in game {this_game.id}') +def get_available_batters( + session: Session, this_game: Game, this_team: Team +) -> list[Card]: + logger.info( + f"getting available batters for team {this_team.id} in game {this_game.id}" + ) all_subs = get_available_subs(session, this_game, this_team) - logger.info(f'all_subs: {all_subs}') + logger.info(f"all_subs: {all_subs}") batters = [x for x in all_subs if x.batterscouting is not None] - logger.info(f'batters: {batters}') + logger.info(f"batters: {batters}") return batters def get_batter_card(this_card: Card = None, this_lineup: Lineup = None) -> BattingCard: if this_card is not None: - logger.info(f'Getting batter card for {this_card.player.name}') + logger.info(f"Getting batter card for {this_card.player.name}") return this_card.batterscouting.battingcard if this_lineup is not None: - logger.info(f'Getting batter card for {this_lineup.player.name}') + logger.info(f"Getting batter card for {this_lineup.player.name}") return this_lineup.card.batterscouting.battingcard - log_exception(KeyError, 'Either a Card or Lineup must be provided to get_batter_card') + log_exception( + KeyError, "Either a Card or Lineup must be provided to get_batter_card" + ) def get_batting_statline(session: Session, this_lineup: Lineup) -> str: - logger.info(f'Getting batting statline for {this_lineup.player.name} in Game {this_lineup.game.id}') + logger.info( + f"Getting batting statline for {this_lineup.player.name} in Game {this_lineup.game.id}" + ) - at_bats = session.exec(select(func.count(Play.id)).where( - Play.game == this_lineup.game, Play.batter == this_lineup, Play.ab == 1, Play.complete == True - )).one() - hits = session.exec(select(func.count(Play.id)).where( + at_bats = session.exec( + select(func.count(Play.id)).where( + Play.game == this_lineup.game, + Play.batter == this_lineup, + Play.ab == 1, + Play.complete == True, + ) + ).one() + hits = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.batter == this_lineup, Play.hit == 1 - )).one() + ) + ).one() - bat_string = f'{hits}-{at_bats}' - logger.info(f'at-bat bat_string: {bat_string}') + bat_string = f"{hits}-{at_bats}" + logger.info(f"at-bat bat_string: {bat_string}") - homeruns = session.exec(select(func.count(Play.id)).where( + homeruns = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.batter == this_lineup, Play.homerun == 1 - )).one() + ) + ).one() if homeruns > 0: - number_string = f'{homeruns} ' if homeruns > 1 else "" - bat_string += f', {number_string}HR' + number_string = f"{homeruns} " if homeruns > 1 else "" + bat_string += f", {number_string}HR" - triples = session.exec(select(func.count(Play.id)).where( + triples = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.batter == this_lineup, Play.triple == 1 - )).one() + ) + ).one() if triples > 0: - number_string = f'{triples} ' if triples > 1 else "" - bat_string += f', {number_string}3B' - - doubles = session.exec(select(func.count(Play.id)).where( - Play.game == this_lineup.game, Play.batter == this_lineup, Play.double == 1 - )).one() - if doubles > 0: - number_string = f'{doubles} ' if doubles > 1 else "" - bat_string += f', {number_string}2B' - - stolenbases = session.exec(select(func.count(Play.id)).where( - Play.game == this_lineup.game, Play.runner == this_lineup, Play.sb == 1 - )).one() - if stolenbases > 0: - number_string = f'{stolenbases} ' if stolenbases > 1 else "" - bat_string += f', {number_string}SB' - - walks = session.exec(select(func.count(Play.id)).where( - Play.game == this_lineup.game, Play.batter == this_lineup, Play.bb == 1 - )).one() - if walks > 0: - number_string = f'{walks} ' if walks > 1 else "" - bat_string += f', {number_string}BB' - - strikeouts = session.exec(select(func.count(Play.id)).where( - Play.game == this_lineup.game, Play.batter == this_lineup, Play.so == 1 - )).one() - if strikeouts > 0: - number_string = f'{strikeouts} ' if strikeouts > 1 else "" - bat_string += f', {number_string}K' - - logger.info(f'bat_string: {bat_string}') + number_string = f"{triples} " if triples > 1 else "" + bat_string += f", {number_string}3B" - if bat_string == '0-0': - return '1st AB' + doubles = session.exec( + select(func.count(Play.id)).where( + Play.game == this_lineup.game, Play.batter == this_lineup, Play.double == 1 + ) + ).one() + if doubles > 0: + number_string = f"{doubles} " if doubles > 1 else "" + bat_string += f", {number_string}2B" + + stolenbases = session.exec( + select(func.count(Play.id)).where( + Play.game == this_lineup.game, Play.runner == this_lineup, Play.sb == 1 + ) + ).one() + if stolenbases > 0: + number_string = f"{stolenbases} " if stolenbases > 1 else "" + bat_string += f", {number_string}SB" + + walks = session.exec( + select(func.count(Play.id)).where( + Play.game == this_lineup.game, Play.batter == this_lineup, Play.bb == 1 + ) + ).one() + if walks > 0: + number_string = f"{walks} " if walks > 1 else "" + bat_string += f", {number_string}BB" + + strikeouts = session.exec( + select(func.count(Play.id)).where( + Play.game == this_lineup.game, Play.batter == this_lineup, Play.so == 1 + ) + ).one() + if strikeouts > 0: + number_string = f"{strikeouts} " if strikeouts > 1 else "" + bat_string += f", {number_string}K" + + logger.info(f"bat_string: {bat_string}") + + if bat_string == "0-0": + return "1st AB" else: return bat_string def get_pitching_statline(session: Session, this_lineup: Lineup) -> str: - logger.info(f'Getting pitching statline for {this_lineup.player.name} in Game {this_lineup.game.id}') + logger.info( + f"Getting pitching statline for {this_lineup.player.name} in Game {this_lineup.game.id}" + ) - outs = session.exec(select(func.sum(Play.outs)).where( - Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.complete == True - )).one() + outs = session.exec( + select(func.sum(Play.outs)).where( + Play.game == this_lineup.game, + Play.pitcher == this_lineup, + Play.complete == True, + ) + ).one() if outs is None: - return '***N E W P I T C H E R***' + return "***N E W P I T C H E R***" whole_innings = math.floor(outs / 3) rem_outs = outs % 3 - pit_string = f'{whole_innings}.{rem_outs} IP' - logger.info(f'IP pit_string: {pit_string}') + pit_string = f"{whole_innings}.{rem_outs} IP" + logger.info(f"IP pit_string: {pit_string}") - runs = session.exec(select(func.count(Play.id)).where( + runs = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.run == 1 - )).one() + ) + ).one() if runs > 0: - number_string = f'{runs} ' if runs > 1 else "" - pit_string += f', {number_string}R' + number_string = f"{runs} " if runs > 1 else "" + pit_string += f", {number_string}R" - e_runs = session.exec(select(func.count(Play.id)).where( + e_runs = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.e_run == 1 - )).one() + ) + ).one() if e_runs != runs: - pit_string += f' ({e_runs} ER)' + pit_string += f" ({e_runs} ER)" - hits = session.exec(select(func.count(Play.id)).where( + hits = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.hit == 1 - )).one() + ) + ).one() if hits > 0: - pit_string += f', {hits} H' + pit_string += f", {hits} H" - walks = session.exec(select(func.count(Play.id)).where( + walks = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.bb == 1 - )).one() + ) + ).one() if walks > 0: - number_string = f'{walks} ' if walks > 1 else "" - pit_string += f', {number_string}BB' + number_string = f"{walks} " if walks > 1 else "" + pit_string += f", {number_string}BB" - strikeouts = session.exec(select(func.count(Play.id)).where( + strikeouts = session.exec( + select(func.count(Play.id)).where( Play.game == this_lineup.game, Play.pitcher == this_lineup, Play.so == 1 - )).one() + ) + ).one() if strikeouts > 0: - number_string = f'{strikeouts} ' if strikeouts > 1 else "" - pit_string += f', {number_string}K' + number_string = f"{strikeouts} " if strikeouts > 1 else "" + pit_string += f", {number_string}K" return pit_string def get_game_cardset_links(session: Session, this_game: Game) -> list[GameCardsetLink]: - logger.info(f'Getting game cardset links for game: {this_game}') - cardset_links = session.exec(select(GameCardsetLink).where(GameCardsetLink.game == this_game)).all() - logger.info(f'links: {cardset_links}') + logger.info(f"Getting game cardset links for game: {this_game}") + cardset_links = session.exec( + select(GameCardsetLink).where(GameCardsetLink.game == this_game) + ).all() + logger.info(f"links: {cardset_links}") return cardset_links -def get_plays_by_pitcher(session: Session, this_game: Game, this_lineup: Lineup, reversed: bool = False) -> list[Play]: - logger.info(f'Getting all pitching plays for {this_lineup.card.player.name_with_desc}') +def get_plays_by_pitcher( + session: Session, this_game: Game, this_lineup: Lineup, reversed: bool = False +) -> list[Play]: + logger.info( + f"Getting all pitching plays for {this_lineup.card.player.name_with_desc}" + ) statement = select(Play).where(Play.game == this_game, Play.pitcher == this_lineup) if reversed: statement = statement.order_by(Play.play_num.desc()) all_plays = session.exec(statement).all() - - logger.info(f'all_plays: {all_plays}') + + logger.info(f"all_plays: {all_plays}") return all_plays -def get_pitcher_runs_by_innings(session: Session, this_game: Game, this_pitcher: Lineup, innings: list[int]) -> int: - logger.info(f'Checking runs for {this_pitcher.player.name_with_desc} in innings: {innings}') - runs = session.exec(select(func.count(Play.id)).where( - Play.game == this_game, Play.pitcher == this_pitcher, Play.run == 1, Play.inning_num.in_(innings) - )).one() - logger.info(f'runs: {runs}') +def get_pitcher_runs_by_innings( + session: Session, this_game: Game, this_pitcher: Lineup, innings: list[int] +) -> int: + logger.info( + f"Checking runs for {this_pitcher.player.name_with_desc} in innings: {innings}" + ) + runs = session.exec( + select(func.count(Play.id)).where( + Play.game == this_game, + Play.pitcher == this_pitcher, + Play.run == 1, + Play.inning_num.in_(innings), + ) + ).one() + logger.info(f"runs: {runs}") return runs - -def reset_cache(session: Session, players: bool = True, scouting: bool = True, team: bool = True): + +def reset_cache( + session: Session, players: bool = True, scouting: bool = True, team: bool = True +): if players: - logger.warning(f'Resetting created date for Players') - session.exec(update(Player).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) + logger.warning(f"Resetting created date for Players") + session.exec( + update(Player).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) if scouting: - logger.warning(f'Resetting created date for scouting objects') - session.exec(update(BattingCard).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(BatterScouting).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(PitchingCard).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(PitcherScouting).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(PositionRating).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(PitchingRatings).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - session.exec(update(BattingRatings).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) + logger.warning(f"Resetting created date for scouting objects") + session.exec( + update(BattingCard).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(BatterScouting).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(PitchingCard).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(PitcherScouting).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(PositionRating).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(PitchingRatings).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.exec( + update(BattingRatings).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) if team: - logger.warning(f'Resetting created date for Teams') - session.exec(update(Team).values(created=datetime.datetime.now() - datetime.timedelta(days=365))) - + logger.warning(f"Resetting created date for Teams") + session.exec( + update(Team).values( + created=datetime.datetime.now() - datetime.timedelta(days=365) + ) + ) + session.commit() -- 2.25.1