paper-dynasty-database/app/routers_v2/gamerewards.py
Cal Corum 1e21894898 fix: skip total_count query for CSV requests and consolidate rewards.py counts
- Guard total_count with `if not csv` ternary to avoid unnecessary
  COUNT query on CSV export paths (10 files)
- Consolidate rewards.py from 3 COUNT queries to 1 (used for both
  empty-check and response)
- Clean up scout_claims.py double `if limit is not None` block
- Normalize scout_opportunities.py from max(1,...) to max(0,...)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 07:43:14 -05:00

204 lines
6.3 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Response
from typing import Optional
import logging
import pydantic
from pandas import DataFrame
from ..db_engine import GameRewards, model_to_dict, DoesNotExist
from ..dependencies import oauth2_scheme, valid_token
router = APIRouter(prefix="/api/v2/gamerewards", tags=["gamerewards"])
class GameRewardModel(pydantic.BaseModel):
name: str
pack_type_id: Optional[int] = None
player_id: Optional[int] = None
money: Optional[int] = None
@router.get("")
async def v1_gamerewards_get(
name: Optional[str] = None,
pack_type_id: Optional[int] = None,
player_id: Optional[int] = None,
money: Optional[int] = None,
csv: Optional[bool] = None,
limit: int = 100,
):
all_rewards = GameRewards.select().order_by(GameRewards.id)
# if all_rewards.count() == 0:
# db.close()
# raise HTTPException(status_code=404, detail=f'There are no awards to filter')
if name is not None:
all_rewards = all_rewards.where(GameRewards.name == name)
if pack_type_id is not None:
all_rewards = all_rewards.where(GameRewards.pack_type_id == pack_type_id)
if player_id is not None:
all_rewards = all_rewards.where(GameRewards.player_id == player_id)
if money is not None:
all_rewards = all_rewards.where(GameRewards.money == money)
limit = max(0, min(limit, 500))
total_count = all_rewards.count() if not csv else 0
all_rewards = all_rewards.limit(limit)
if csv:
data_list = [["id", "pack_type_id", "player_id", "money"]]
for line in all_rewards:
data_list.append(
[
line.id,
line.pack_type_id if line.pack_type else None,
line.player_id if line.player else None,
line.money,
]
)
return_val = DataFrame(data_list).to_csv(header=False, index=False)
return Response(content=return_val, media_type="text/csv")
else:
return_val = {"count": total_count, "gamerewards": []}
for x in all_rewards:
return_val["gamerewards"].append(model_to_dict(x))
return return_val
@router.get("/{gameaward_id}")
async def v1_gamerewards_get_one(gamereward_id, csv: Optional[bool] = None):
try:
this_game_reward = GameRewards.get_by_id(gamereward_id)
except DoesNotExist:
raise HTTPException(
status_code=404, detail=f"No game reward found with id {gamereward_id}"
)
if csv:
data_list = [
["id", "pack_type_id", "player_id", "money"],
[
this_game_reward.id,
this_game_reward.pack_type_id if this_game_reward.pack_type else None,
this_game_reward.player_id if this_game_reward.player else None,
this_game_reward.money,
],
]
return_val = DataFrame(data_list).to_csv(header=False, index=False)
return Response(content=return_val, media_type="text/csv")
else:
return_val = model_to_dict(this_game_reward)
return return_val
@router.post("")
async def v1_gamerewards_post(
game_reward: GameRewardModel, token: str = Depends(oauth2_scheme)
):
if not valid_token(token):
logging.warning("Bad Token: [REDACTED]")
raise HTTPException(
status_code=401,
detail="You are not authorized to post game rewards. This event has been logged.",
)
this_award = GameRewards(
name=game_reward.name,
pack_type_id=game_reward.pack_type_id,
player_id=game_reward.player_id,
money=game_reward.money,
)
saved = this_award.save()
if saved == 1:
return_val = model_to_dict(this_award)
return return_val
else:
raise HTTPException(
status_code=418,
detail="Well slap my ass and call me a teapot; I could not save that roster",
)
@router.patch("/{game_reward_id}")
async def v1_gamerewards_patch(
game_reward_id: int,
name: Optional[str] = None,
pack_type_id: Optional[int] = None,
player_id: Optional[int] = None,
money: Optional[int] = None,
token: str = Depends(oauth2_scheme),
):
if not valid_token(token):
logging.warning("Bad Token: [REDACTED]")
raise HTTPException(
status_code=401,
detail="You are not authorized to patch gamerewards. This event has been logged.",
)
try:
this_game_reward = GameRewards.get_by_id(game_reward_id)
except DoesNotExist:
raise HTTPException(
status_code=404, detail=f"No game reward found with id {game_reward_id}"
)
if name is not None:
this_game_reward.name = name
if pack_type_id is not None:
if not pack_type_id:
this_game_reward.pack_type_id = None
else:
this_game_reward.pack_type_id = pack_type_id
if player_id is not None:
if not player_id:
this_game_reward.player_id = None
else:
this_game_reward.player_id = player_id
if money is not None:
if not money:
this_game_reward.money = None
else:
this_game_reward.money = money
if this_game_reward.save() == 1:
return_val = model_to_dict(this_game_reward)
return return_val
else:
raise HTTPException(
status_code=418,
detail="Well slap my ass and call me a teapot; I could not save that rarity",
)
@router.delete("/{gamereward_id}")
async def v1_gamerewards_delete(gamereward_id, token: str = Depends(oauth2_scheme)):
if not valid_token(token):
logging.warning("Bad Token: [REDACTED]")
raise HTTPException(
status_code=401,
detail="You are not authorized to delete awards. This event has been logged.",
)
try:
this_award = GameRewards.get_by_id(gamereward_id)
except DoesNotExist:
raise HTTPException(
status_code=404, detail=f"No award found with id {gamereward_id}"
)
count = this_award.delete_instance()
if count == 1:
raise HTTPException(
status_code=200, detail=f"Game Reward {gamereward_id} has been deleted"
)
else:
raise HTTPException(
status_code=500, detail=f"Game Reward {gamereward_id} was not deleted"
)