Boards
leadr.boards¶
Modules:
leadr.boards.adapters¶
Modules:
- orm – Board ORM model.
leadr.boards.adapters.orm¶
Board ORM model.
Classes:
- BoardORM – Board ORM model.
- BoardRatioConfigORM – Board ratio config ORM model.
- BoardStateORM – Board state ORM model.
- BoardTemplateORM – BoardTemplate ORM model.
- BoardTypeEnum – Board type enum for database.
- KeepStrategyEnum – Keep strategy enum for database.
- RatioDisplayEnum – Ratio display enum for database.
- RunEntryORM – Run entry ORM model.
- TieBreakerEnum – Tie breaker enum for database.
- ZeroDenominatorPolicyEnum – Zero denominator policy enum for database.
leadr.boards.adapters.orm.BoardORM¶
Bases: Base
Board ORM model.
Represents a leaderboard/board that belongs to a game in the database. Maps to the boards table with foreign keys to accounts and games, a unique constraint on short_code (globally unique for direct sharing), and a partial unique constraint on (account_id, game_id, slug) for active boards only.
Attributes:
- account (
Mapped[AccountORM]) – - account_id (
Mapped[UUID]) – - board_type (
Mapped[BoardTypeEnum]) – - created_at (
Mapped[timestamp]) – - created_from_template_id (
Mapped[UUID | None]) – - deleted_at (
Mapped[nullable_timestamp]) – - description (
Mapped[str | None]) – - ends_at (
Mapped[datetime | None]) – - game (
Mapped[GameORM]) – - game_id (
Mapped[UUID]) – - icon (
Mapped[str | None]) – - id (
Mapped[uuid_pk]) – - is_active (
Mapped[bool]) – - is_published (
Mapped[bool]) – - keep_strategy (
Mapped[KeepStrategyEnum]) – - name (
Mapped[str]) – - short_code (
Mapped[str]) – - slug (
Mapped[str]) – - sort_direction (
Mapped[str]) – - starts_at (
Mapped[datetime | None]) – - tags (
Mapped[list[str]]) – - template_name (
Mapped[str | None]) – - unit (
Mapped[str | None]) – - updated_at (
Mapped[timestamp]) –
# leadr.boards.adapters.orm.BoardORM.account¶
account: Mapped[AccountORM] = relationship('AccountORM')
# leadr.boards.adapters.orm.BoardORM.account_id¶
account_id: Mapped[UUID] = mapped_column(ForeignKey('accounts.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardORM.board_type¶
board_type: Mapped[BoardTypeEnum] = mapped_column(Enum(BoardTypeEnum, name='board_type', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(BoardTypeEnum.RUN_IDENTITY), server_default='RUN_IDENTITY')
# leadr.boards.adapters.orm.BoardORM.created_at¶
created_at: Mapped[timestamp]
# leadr.boards.adapters.orm.BoardORM.created_from_template_id¶
created_from_template_id: Mapped[UUID | None] = mapped_column(nullable=True, default=None)
# leadr.boards.adapters.orm.BoardORM.deleted_at¶
deleted_at: Mapped[nullable_timestamp]
# leadr.boards.adapters.orm.BoardORM.description¶
description: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardORM.ends_at¶
ends_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, default=None)
# leadr.boards.adapters.orm.BoardORM.game¶
game: Mapped[GameORM] = relationship('GameORM')
# leadr.boards.adapters.orm.BoardORM.game_id¶
game_id: Mapped[UUID] = mapped_column(ForeignKey('games.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardORM.icon¶
icon: Mapped[str | None] = mapped_column(String, nullable=True)
# leadr.boards.adapters.orm.BoardORM.id¶
id: Mapped[uuid_pk]
# leadr.boards.adapters.orm.BoardORM.is_active¶
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False)
# leadr.boards.adapters.orm.BoardORM.is_published¶
is_published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=(sa.text('true')))
# leadr.boards.adapters.orm.BoardORM.keep_strategy¶
keep_strategy: Mapped[KeepStrategyEnum] = mapped_column(Enum(KeepStrategyEnum, name='keep_strategy', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(KeepStrategyEnum.BEST), server_default='BEST')
# leadr.boards.adapters.orm.BoardORM.name¶
name: Mapped[str] = mapped_column(String, nullable=False)
# leadr.boards.adapters.orm.BoardORM.short_code¶
short_code: Mapped[str] = mapped_column(String, nullable=False, unique=True, index=True)
# leadr.boards.adapters.orm.BoardORM.slug¶
slug: Mapped[str] = mapped_column(String, nullable=False, index=True)
# leadr.boards.adapters.orm.BoardORM.sort_direction¶
sort_direction: Mapped[str] = mapped_column(String, nullable=False)
# leadr.boards.adapters.orm.BoardORM.starts_at¶
starts_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, default=None)
# leadr.boards.adapters.orm.BoardORM.tags¶
tags: Mapped[list[str]] = mapped_column(ARRAY(String), nullable=False, default=list, server_default='{}')
# leadr.boards.adapters.orm.BoardORM.template_name¶
template_name: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardORM.unit¶
unit: Mapped[str | None] = mapped_column(String, nullable=True)
# leadr.boards.adapters.orm.BoardORM.updated_at¶
updated_at: Mapped[timestamp] = mapped_column(onupdate=(func.now()))
leadr.boards.adapters.orm.BoardRatioConfigORM¶
Bases: Base
Board ratio config ORM model.
Stores configuration for RATIO board types that derive their ranking from two other boards (numerator and denominator). Maps to the board_ratio_configs table with foreign keys to boards.
Attributes:
- board (
Mapped[BoardORM]) – - board_id (
Mapped[UUID]) – - created_at (
Mapped[timestamp]) – - decimals (
Mapped[int]) – - deleted_at (
Mapped[nullable_timestamp]) – - denominator_board (
Mapped[BoardORM]) – - denominator_board_id (
Mapped[UUID]) – - display (
Mapped[RatioDisplayEnum]) – - id (
Mapped[uuid_pk]) – - min_denominator (
Mapped[float]) – - min_numerator (
Mapped[float]) – - numerator_board (
Mapped[BoardORM]) – - numerator_board_id (
Mapped[UUID]) – - scale (
Mapped[int]) – - tie_breaker (
Mapped[TieBreakerEnum]) – - updated_at (
Mapped[timestamp]) – - zero_denominator_policy (
Mapped[ZeroDenominatorPolicyEnum]) –
# leadr.boards.adapters.orm.BoardRatioConfigORM.board¶
board: Mapped[BoardORM] = relationship('BoardORM', foreign_keys=[board_id])
# leadr.boards.adapters.orm.BoardRatioConfigORM.board_id¶
board_id: Mapped[UUID] = mapped_column(ForeignKey('boards.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardRatioConfigORM.created_at¶
created_at: Mapped[timestamp]
# leadr.boards.adapters.orm.BoardRatioConfigORM.decimals¶
decimals: Mapped[int] = mapped_column(Integer, nullable=False, default=2)
# leadr.boards.adapters.orm.BoardRatioConfigORM.deleted_at¶
deleted_at: Mapped[nullable_timestamp]
# leadr.boards.adapters.orm.BoardRatioConfigORM.denominator_board¶
denominator_board: Mapped[BoardORM] = relationship('BoardORM', foreign_keys=[denominator_board_id])
# leadr.boards.adapters.orm.BoardRatioConfigORM.denominator_board_id¶
denominator_board_id: Mapped[UUID] = mapped_column(ForeignKey('boards.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardRatioConfigORM.display¶
display: Mapped[RatioDisplayEnum] = mapped_column(Enum(RatioDisplayEnum, name='ratio_display', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(RatioDisplayEnum.RAW), server_default='RAW')
# leadr.boards.adapters.orm.BoardRatioConfigORM.id¶
id: Mapped[uuid_pk]
# leadr.boards.adapters.orm.BoardRatioConfigORM.min_denominator¶
min_denominator: Mapped[float] = mapped_column(Float, nullable=False, default=0)
# leadr.boards.adapters.orm.BoardRatioConfigORM.min_numerator¶
min_numerator: Mapped[float] = mapped_column(Float, nullable=False, default=0)
# leadr.boards.adapters.orm.BoardRatioConfigORM.numerator_board¶
numerator_board: Mapped[BoardORM] = relationship('BoardORM', foreign_keys=[numerator_board_id])
# leadr.boards.adapters.orm.BoardRatioConfigORM.numerator_board_id¶
numerator_board_id: Mapped[UUID] = mapped_column(ForeignKey('boards.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardRatioConfigORM.scale¶
scale: Mapped[int] = mapped_column(Integer, nullable=False, default=1000000)
# leadr.boards.adapters.orm.BoardRatioConfigORM.tie_breaker¶
tie_breaker: Mapped[TieBreakerEnum] = mapped_column(Enum(TieBreakerEnum, name='tie_breaker', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(TieBreakerEnum.NUMERATOR_DESC_DENOMINATOR_ASC), server_default='NUMERATOR_DESC_DENOMINATOR_ASC')
# leadr.boards.adapters.orm.BoardRatioConfigORM.updated_at¶
updated_at: Mapped[timestamp] = mapped_column(onupdate=(func.now()))
# leadr.boards.adapters.orm.BoardRatioConfigORM.zero_denominator_policy¶
zero_denominator_policy: Mapped[ZeroDenominatorPolicyEnum] = mapped_column(Enum(ZeroDenominatorPolicyEnum, name='zero_denominator_policy', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(ZeroDenominatorPolicyEnum.NULL), server_default='NULL')
leadr.boards.adapters.orm.BoardStateORM¶
Bases: Base
Board state ORM model.
Represents the materialized ranking state for a single identity on a single board. Maps to the board_states table with foreign keys to boards and identities. The primary_value can be NULL for non-rankable entries.
Denormalized fields (from Identity and ScoreEvent) are stored for query efficiency.
Attributes:
- aux (
Mapped[dict[str, Any] | None]) – - board (
Mapped[BoardORM]) – - board_id (
Mapped[UUID]) – - city (
Mapped[str | None]) – - country (
Mapped[str | None]) – - created_at (
Mapped[timestamp]) – - deleted_at (
Mapped[nullable_timestamp]) – - id (
Mapped[uuid_pk]) – - identity (
Mapped[IdentityORM]) – - identity_id (
Mapped[UUID]) – - is_test (
Mapped[bool]) – - player_name (
Mapped[str]) – - primary_value (
Mapped[float | None]) – - state_metadata (
Mapped[Any | None]) – - timezone (
Mapped[str | None]) – - updated_at (
Mapped[timestamp]) – - value_display (
Mapped[str | None]) –
# leadr.boards.adapters.orm.BoardStateORM.aux¶
aux: Mapped[dict[str, Any] | None] = mapped_column(JSONB, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.board¶
board: Mapped[BoardORM] = relationship('BoardORM')
# leadr.boards.adapters.orm.BoardStateORM.board_id¶
board_id: Mapped[UUID] = mapped_column(ForeignKey('boards.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardStateORM.city¶
city: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.country¶
country: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.created_at¶
created_at: Mapped[timestamp]
# leadr.boards.adapters.orm.BoardStateORM.deleted_at¶
deleted_at: Mapped[nullable_timestamp]
# leadr.boards.adapters.orm.BoardStateORM.id¶
id: Mapped[uuid_pk]
# leadr.boards.adapters.orm.BoardStateORM.identity¶
identity: Mapped[IdentityORM] = relationship('IdentityORM')
# leadr.boards.adapters.orm.BoardStateORM.identity_id¶
identity_id: Mapped[UUID] = mapped_column(ForeignKey('identities.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardStateORM.is_test¶
is_test: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=(sa.text('false')))
# leadr.boards.adapters.orm.BoardStateORM.player_name¶
player_name: Mapped[str] = mapped_column(String, nullable=False, default='', server_default='')
# leadr.boards.adapters.orm.BoardStateORM.primary_value¶
primary_value: Mapped[float | None] = mapped_column(Float, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.state_metadata¶
state_metadata: Mapped[Any | None] = mapped_column('state_metadata', JSONB, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.timezone¶
timezone: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardStateORM.updated_at¶
updated_at: Mapped[timestamp] = mapped_column(onupdate=(func.now()))
# leadr.boards.adapters.orm.BoardStateORM.value_display¶
value_display: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
leadr.boards.adapters.orm.BoardTemplateORM¶
Bases: Base
BoardTemplate ORM model.
Represents a template for automatically generating boards at regular intervals. Maps to the board_templates table with foreign keys to accounts and games. Uses JSONB column for config to support flexible procedural generation configuration.
Functions:
- from_domain – Convert domain entity to ORM model.
- to_domain – Convert ORM model to domain entity.
Attributes:
- account (
Mapped[AccountORM]) – - account_id (
Mapped[UUID]) – - board_type (
Mapped[BoardTypeEnum]) – - config (
Mapped[dict[str, Any]]) – - created_at (
Mapped[timestamp]) – - deleted_at (
Mapped[nullable_timestamp]) – - ends_at (
Mapped[datetime | None]) – - game (
Mapped[GameORM]) – - game_id (
Mapped[UUID]) – - icon (
Mapped[str | None]) – - id (
Mapped[uuid_pk]) – - is_active (
Mapped[bool]) – - is_published (
Mapped[bool]) – - keep_strategy (
Mapped[KeepStrategyEnum]) – - name (
Mapped[str]) – - name_template (
Mapped[str | None]) – - next_run_at (
Mapped[datetime]) – - repeat_interval (
Mapped[str]) – - series (
Mapped[str | None]) – - slug (
Mapped[str | None]) – - sort_direction (
Mapped[str]) – - starts_at (
Mapped[datetime | None]) – - tags (
Mapped[list[str]]) – - unit (
Mapped[str | None]) – - updated_at (
Mapped[timestamp]) –
# leadr.boards.adapters.orm.BoardTemplateORM.account¶
account: Mapped[AccountORM] = relationship('AccountORM')
# leadr.boards.adapters.orm.BoardTemplateORM.account_id¶
account_id: Mapped[UUID] = mapped_column(ForeignKey('accounts.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardTemplateORM.board_type¶
board_type: Mapped[BoardTypeEnum] = mapped_column(Enum(BoardTypeEnum, name='board_type', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(BoardTypeEnum.RUN_IDENTITY), server_default='RUN_IDENTITY')
# leadr.boards.adapters.orm.BoardTemplateORM.config¶
config: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict, server_default='{}')
# leadr.boards.adapters.orm.BoardTemplateORM.created_at¶
created_at: Mapped[timestamp]
# leadr.boards.adapters.orm.BoardTemplateORM.deleted_at¶
deleted_at: Mapped[nullable_timestamp]
# leadr.boards.adapters.orm.BoardTemplateORM.ends_at¶
ends_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, default=None)
# leadr.boards.adapters.orm.BoardTemplateORM.from_domain¶
from_domain(entity)
Convert domain entity to ORM model.
Parameters:
- entity (
BoardTemplate) – The BoardTemplate domain entity to convert.
Returns:
BoardTemplateORM– BoardTemplateORM model with all fields populated from domain entity.
# leadr.boards.adapters.orm.BoardTemplateORM.game¶
game: Mapped[GameORM] = relationship('GameORM')
# leadr.boards.adapters.orm.BoardTemplateORM.game_id¶
game_id: Mapped[UUID] = mapped_column(ForeignKey('games.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.BoardTemplateORM.icon¶
icon: Mapped[str | None] = mapped_column(String, nullable=True)
# leadr.boards.adapters.orm.BoardTemplateORM.id¶
id: Mapped[uuid_pk]
# leadr.boards.adapters.orm.BoardTemplateORM.is_active¶
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False)
# leadr.boards.adapters.orm.BoardTemplateORM.is_published¶
is_published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default=(sa.text('true')))
# leadr.boards.adapters.orm.BoardTemplateORM.keep_strategy¶
keep_strategy: Mapped[KeepStrategyEnum] = mapped_column(Enum(KeepStrategyEnum, name='keep_strategy', native_enum=True, values_callable=(lambda x: [(e.value) for e in x]), create_constraint=False), nullable=False, default=(KeepStrategyEnum.BEST), server_default='BEST')
# leadr.boards.adapters.orm.BoardTemplateORM.name¶
name: Mapped[str] = mapped_column(String, nullable=False)
# leadr.boards.adapters.orm.BoardTemplateORM.name_template¶
name_template: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardTemplateORM.next_run_at¶
next_run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# leadr.boards.adapters.orm.BoardTemplateORM.repeat_interval¶
repeat_interval: Mapped[str] = mapped_column(String, nullable=False)
# leadr.boards.adapters.orm.BoardTemplateORM.series¶
series: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardTemplateORM.slug¶
slug: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.BoardTemplateORM.sort_direction¶
sort_direction: Mapped[str] = mapped_column(String, nullable=False)
# leadr.boards.adapters.orm.BoardTemplateORM.starts_at¶
starts_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, default=None)
# leadr.boards.adapters.orm.BoardTemplateORM.tags¶
tags: Mapped[list[str]] = mapped_column(ARRAY(String), nullable=False, default=list, server_default='{}')
# leadr.boards.adapters.orm.BoardTemplateORM.to_domain¶
to_domain()
Convert ORM model to domain entity.
Returns:
BoardTemplate– BoardTemplate domain entity with all fields populated from ORM model.
# leadr.boards.adapters.orm.BoardTemplateORM.unit¶
unit: Mapped[str | None] = mapped_column(String, nullable=True)
# leadr.boards.adapters.orm.BoardTemplateORM.updated_at¶
updated_at: Mapped[timestamp] = mapped_column(onupdate=(func.now()))
leadr.boards.adapters.orm.BoardTypeEnum¶
Board type enum for database.
Attributes:
- COUNTER –
- RATIO –
- RUN_IDENTITY –
- RUN_RUNS –
# leadr.boards.adapters.orm.BoardTypeEnum.COUNTER¶
COUNTER = 'COUNTER'
# leadr.boards.adapters.orm.BoardTypeEnum.RATIO¶
RATIO = 'RATIO'
# leadr.boards.adapters.orm.BoardTypeEnum.RUN_IDENTITY¶
RUN_IDENTITY = 'RUN_IDENTITY'
# leadr.boards.adapters.orm.BoardTypeEnum.RUN_RUNS¶
RUN_RUNS = 'RUN_RUNS'
leadr.boards.adapters.orm.KeepStrategyEnum¶
Keep strategy enum for database.
Attributes:
# leadr.boards.adapters.orm.KeepStrategyEnum.BEST¶
BEST = 'BEST'
# leadr.boards.adapters.orm.KeepStrategyEnum.FIRST¶
FIRST = 'FIRST'
# leadr.boards.adapters.orm.KeepStrategyEnum.LATEST¶
LATEST = 'LATEST'
# leadr.boards.adapters.orm.KeepStrategyEnum.NA¶
NA = 'NA'
leadr.boards.adapters.orm.RatioDisplayEnum¶
Ratio display enum for database.
Attributes:
# leadr.boards.adapters.orm.RatioDisplayEnum.PERCENT¶
PERCENT = 'PERCENT'
# leadr.boards.adapters.orm.RatioDisplayEnum.RAW¶
RAW = 'RAW'
leadr.boards.adapters.orm.RunEntryORM¶
Bases: Base
Run entry ORM model.
Represents a single scored run entry for RUN_RUNS boards where every submission is ranked. Maps to the run_entries table with foreign keys to boards, identities, and score_events.
Denormalized fields (from Identity and ScoreEvent) are stored for query efficiency.
Attributes:
- board (
Mapped[BoardORM]) – - board_id (
Mapped[UUID]) – - city (
Mapped[str | None]) – - country (
Mapped[str | None]) – - created_at (
Mapped[timestamp]) – - deleted_at (
Mapped[nullable_timestamp]) – - entry_metadata (
Mapped[Any | None]) – - excluded_at (
Mapped[datetime | None]) – - excluded_reason (
Mapped[str | None]) – - id (
Mapped[uuid_pk]) – - identity (
Mapped[IdentityORM]) – - identity_id (
Mapped[UUID]) – - is_test (
Mapped[bool]) – - player_name (
Mapped[str]) – - primary_value (
Mapped[float]) – - score_event (
Mapped[ScoreEventORM]) – - score_event_id (
Mapped[UUID]) – - timezone (
Mapped[str | None]) – - updated_at (
Mapped[timestamp]) – - value_display (
Mapped[str | None]) –
# leadr.boards.adapters.orm.RunEntryORM.board¶
board: Mapped[BoardORM] = relationship('BoardORM')
# leadr.boards.adapters.orm.RunEntryORM.board_id¶
board_id: Mapped[UUID] = mapped_column(ForeignKey('boards.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.RunEntryORM.city¶
city: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.country¶
country: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.created_at¶
created_at: Mapped[timestamp]
# leadr.boards.adapters.orm.RunEntryORM.deleted_at¶
deleted_at: Mapped[nullable_timestamp]
# leadr.boards.adapters.orm.RunEntryORM.entry_metadata¶
entry_metadata: Mapped[Any | None] = mapped_column('entry_metadata', JSONB, nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.excluded_at¶
excluded_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.excluded_reason¶
excluded_reason: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.id¶
id: Mapped[uuid_pk]
# leadr.boards.adapters.orm.RunEntryORM.identity¶
identity: Mapped[IdentityORM] = relationship('IdentityORM')
# leadr.boards.adapters.orm.RunEntryORM.identity_id¶
identity_id: Mapped[UUID] = mapped_column(ForeignKey('identities.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.RunEntryORM.is_test¶
is_test: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=(sa.text('false')))
# leadr.boards.adapters.orm.RunEntryORM.player_name¶
player_name: Mapped[str] = mapped_column(String, nullable=False, default='', server_default='')
# leadr.boards.adapters.orm.RunEntryORM.primary_value¶
primary_value: Mapped[float] = mapped_column(Float, nullable=False)
# leadr.boards.adapters.orm.RunEntryORM.score_event¶
score_event: Mapped[ScoreEventORM] = relationship('ScoreEventORM')
# leadr.boards.adapters.orm.RunEntryORM.score_event_id¶
score_event_id: Mapped[UUID] = mapped_column(ForeignKey('score_events.id', ondelete='CASCADE'), nullable=False, index=True)
# leadr.boards.adapters.orm.RunEntryORM.timezone¶
timezone: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
# leadr.boards.adapters.orm.RunEntryORM.updated_at¶
updated_at: Mapped[timestamp] = mapped_column(onupdate=(func.now()))
# leadr.boards.adapters.orm.RunEntryORM.value_display¶
value_display: Mapped[str | None] = mapped_column(String, nullable=True, default=None)
leadr.boards.adapters.orm.TieBreakerEnum¶
Tie breaker enum for database.
Attributes:
# leadr.boards.adapters.orm.TieBreakerEnum.NUMERATOR_DESC_DENOMINATOR_ASC¶
NUMERATOR_DESC_DENOMINATOR_ASC = 'NUMERATOR_DESC_DENOMINATOR_ASC'
leadr.boards.adapters.orm.ZeroDenominatorPolicyEnum¶
Zero denominator policy enum for database.
Attributes:
# leadr.boards.adapters.orm.ZeroDenominatorPolicyEnum.INFINITY¶
INFINITY = 'INFINITY'
# leadr.boards.adapters.orm.ZeroDenominatorPolicyEnum.NULL¶
NULL = 'NULL'
# leadr.boards.adapters.orm.ZeroDenominatorPolicyEnum.ZERO¶
ZERO = 'ZERO'
leadr.boards.api¶
Modules:
- board_routes – Board API routes.
- board_schemas – API request and response models for boards.
- board_state_routes – API routes for board state management (admin only, read-only).
- board_state_schemas – API response models for board states.
- board_template_routes – Board template API routes.
- board_template_schemas – API request and response models for board templates.
- run_entry_routes – API routes for run entry management (admin only, read-only).
- run_entry_schemas – API response models for run entries.
leadr.boards.api.board_routes¶
Board API routes.
Functions:
- create_board – Create a new board.
- get_board – Get a board by ID.
- handle_list_boards – Shared handler for listing boards with filtering.
- list_boards_admin – List boards (Admin API).
- list_boards_client – List boards (Client API).
- update_board – Update a board.
Attributes:
- client_router –
- logger –
- router –
leadr.boards.api.board_routes.client_router¶
client_router = APIRouter()
leadr.boards.api.board_routes.create_board¶
create_board(request, service, ratio_config_service, auth, background_tasks, pre_create_hook, post_create_hook)
Create a new board.
Creates a new leaderboard associated with an existing game and account. The game must belong to the specified account.
For regular users, account_id must match their API key's account. For superadmins, any account_id is accepted.
For RATIO boards, ratio_config is required and specifies the numerator and denominator boards used to calculate the ratio.
Parameters:
- request (
BoardCreateRequest) – Board creation details including account_id, game_id, name, and settings. - service (
BoardServiceDep) – Injected board service dependency. - ratio_config_service (
BoardRatioConfigServiceDep) – Injected ratio config service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info. - pre_create_hook (
PreCreateBoardHookDep) – Hook called before board creation (for quota checks). - post_create_hook (
PostCreateBoardHookDep) – Hook called after successful board creation.
Returns:
BoardResponse– BoardResponse with the created board including auto-generated ID and timestamps.
Raises:
403– User does not have access to the specified account.404– Game or account not found.400– Game doesn't belong to the specified account, or RATIO board missing config.
leadr.boards.api.board_routes.get_board¶
get_board(board_id, service, ratio_config_service, auth)
Get a board by ID.
Parameters:
- board_id (
BoardID) – Unique identifier for the board. - service (
BoardServiceDep) – Injected board service dependency. - ratio_config_service (
BoardRatioConfigServiceDep) – Injected ratio config service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info.
Returns:
BoardResponse– BoardResponse with full board details (including ratio_config for RATIO boards).
Raises:
403– User does not have access to this board's account.404– Board not found.
leadr.boards.api.board_routes.handle_list_boards¶
handle_list_boards(auth, service, game_service, pagination, account_id, game_id, code, game_slug, slug, is_active, is_published, starts_before, starts_after, ends_before, ends_after)
Shared handler for listing boards with filtering.
Parameters:
- auth (
AuthContext) – Authentication context with user info. - service (
BoardService) – Board service instance. - game_service (
GameService) – Game service instance for game_slug resolution. - pagination (
PaginationParams) – Pagination parameters (cursor, limit, sort). - account_id (
AccountID | None) – Optional account ID to filter boards by. - game_id (
GameID | None) – Optional game ID to filter boards by. - code (
str | None) – Optional short code to filter boards by. - game_slug (
str | None) – Optional game slug to filter boards by game (resolves to game_id). - slug (
str | None) – Optional board slug to filter by specific board (requires game_slug). - is_active (
bool | None) – Optional filter for active status. - is_published (
bool | None) – Optional filter for published status. - starts_before (
datetime | None) – Optional filter for boards starting before this time. - starts_after (
datetime | None) – Optional filter for boards starting after this time. - ends_before (
datetime | None) – Optional filter for boards ending before this time. - ends_after (
datetime | None) – Optional filter for boards ending after this time.
Returns:
PaginatedResponse[BoardResponse]– PaginatedResponse with boards and pagination metadata.
Raises:
400– Invalid cursor, sort field, or cursor state mismatch.404– Game or board not found when using slug filters.
leadr.boards.api.board_routes.list_boards_admin¶
list_boards_admin(auth, service, game_service, pagination, account_id=None, game_id=None, code=None, game_slug=None, slug=None, is_active=None, is_published=None, starts_before=None, starts_after=None, ends_before=None, ends_after=None)
List boards (Admin API).
For regular users:
- If account_id not provided, defaults to their API key's account
- If account_id provided and they are superadmin, can access any account
- If account_id provided and NOT superadmin, must match their account (validated in AuthContext)
Filtering:
- Use ?game_id={id} or ?game_slug={slug} to filter boards by game
- Use ?game_slug={game_slug}&slug={slug} to find a specific board within a game
- Use ?code={code} to filter boards by short code
- Use ?is_active=true/false to filter by active status
- Use ?is_published=true/false to filter by published status
- Use ?starts_before=
&starts_after= for start date range - Use ?ends_before=
&ends_after= for end date range - Note: board slug filter requires game_slug parameter
Pagination:
- Default: 20 items per page, sorted by created_at:desc,id:asc
- Custom sort: Use ?sort=name:asc,created_at:desc
- Valid sort fields: id, name, slug, short_code, created_at, updated_at
- Navigation: Use next_cursor/prev_cursor from response
Example
GET /v1/boards?account_id=acc_123&limit=50&sort=name:asc GET /v1/boards?game_slug=my-game&is_active=true GET /v1/boards?game_slug=my-game&slug=weekly-challenge GET /v1/boards?starts_after=2025-01-01T00:00:00Z&ends_before=2025-12-31T23:59:59ZParameters:
- auth (
AdminAuthContextDep) – Admin authentication context with user info. - service (
BoardServiceDep) – Injected board service dependency. - game_service (
GameServiceDep) – Injected game service dependency. - pagination (
Annotated[PaginationParams, Depends()]) – Pagination parameters (cursor, limit, sort). - account_id (
Annotated[AccountID | None, Query(description='Filter by account ID')]) – Optional account ID to filter boards by. - game_id (
Annotated[GameID | None, Query(description='Filter by game ID')]) – Optional game ID to filter boards by. - code (
Annotated[str | None, Query(description='Filter by short code')]) – Optional short code to filter boards by. - game_slug (
Annotated[str | None, Query(description='Filter by game slug')]) – Optional game slug to filter boards by game (resolves to game_id). - slug (
Annotated[str | None, Query(description='Filter by board slug (requires game_slug)')]) – Optional board slug to filter by specific board (requires game_slug). - is_active (
Annotated[bool | None, Query(description='Filter by active status')]) – Optional filter for active status. - is_published (
Annotated[bool | None, Query(description='Filter by published status')]) – Optional filter for published status. - starts_before (
Annotated[datetime | None, Query(description='Filter boards starting before this time (ISO 8601)')]) – Optional filter for boards starting before this time. - starts_after (
Annotated[datetime | None, Query(description='Filter boards starting after this time (ISO 8601)')]) – Optional filter for boards starting after this time. - ends_before (
Annotated[datetime | None, Query(description='Filter boards ending before this time (ISO 8601)')]) – Optional filter for boards ending before this time. - ends_after (
Annotated[datetime | None, Query(description='Filter boards ending after this time (ISO 8601)')]) – Optional filter for boards ending after this time.
Returns:
PaginatedResponse[BoardResponse]– PaginatedResponse with boards and pagination metadata.
Raises:
400– Invalid cursor, sort field, cursor state mismatch, or slug without game_slug.404– Game or board not found when using slug filters.
leadr.boards.api.board_routes.list_boards_client¶
list_boards_client(auth, service, game_service, pagination, code=None, slug=None, is_published=None, starts_before=None, starts_after=None, ends_before=None, ends_after=None)
List boards (Client API).
Account ID and game ID are automatically derived from the authenticated client session. Clients can optionally filter by various criteria to find specific boards.
Filtering:
- Use ?slug={slug} to find a specific board within the authenticated game
- Use ?code={code} to filter boards by short code
- Use ?is_published=true/false to filter by published status
- Use ?starts_before=
&starts_after= for start date range - Use ?ends_before=
&ends_after= for end date range
Pagination:
- Default: 20 items per page, sorted by created_at:desc,id:asc
- Custom sort: Use ?sort=name:asc,created_at:desc
- Valid sort fields: id, name, slug, short_code, created_at, updated_at
- Navigation: Use next_cursor/prev_cursor from response
Example
GET /v1/client/boards?code=WEEKLY-CHALLENGE&limit=50 GET /v1/client/boards?slug=weekly-challenge GET /v1/client/boards?is_published=true GET /v1/client/boards?starts_after=2025-01-01T00:00:00ZParameters:
- auth (
ClientAuthContextDep) – Client authentication context with device info. - service (
BoardServiceDep) – Injected board service dependency. - game_service (
GameServiceDep) – Injected game service dependency. - pagination (
Annotated[PaginationParams, Depends()]) – Pagination parameters (cursor, limit, sort). - code (
Annotated[str | None, Query(description='Filter by short code')]) – Optional short code to filter boards by. - slug (
Annotated[str | None, Query(description='Filter by board slug')]) – Optional board slug to filter by specific board. - is_published (
Annotated[bool | None, Query(description='Filter by published status')]) – Optional filter for published status. - starts_before (
Annotated[datetime | None, Query(description='Filter boards starting before this time (ISO 8601)')]) – Optional filter for boards starting before this time. - starts_after (
Annotated[datetime | None, Query(description='Filter boards starting after this time (ISO 8601)')]) – Optional filter for boards starting after this time. - ends_before (
Annotated[datetime | None, Query(description='Filter boards ending before this time (ISO 8601)')]) – Optional filter for boards ending before this time. - ends_after (
Annotated[datetime | None, Query(description='Filter boards ending after this time (ISO 8601)')]) – Optional filter for boards ending after this time.
Returns:
PaginatedResponse[BoardResponse]– PaginatedResponse with boards and pagination metadata.
Raises:
400– Invalid cursor, sort field, or cursor state mismatch.
leadr.boards.api.board_routes.logger¶
logger = logging.getLogger(__name__)
leadr.boards.api.board_routes.router¶
router = APIRouter()
leadr.boards.api.board_routes.update_board¶
update_board(board_id, request, service, ratio_config_service, auth)
Update a board.
Supports updating any board field or soft-deleting the board. For RATIO boards, ratio_config can be updated to change calculation settings.
Parameters:
- board_id (
BoardID) – Unique identifier for the board. - request (
BoardUpdateRequest) – Board update details (all fields optional). - service (
BoardServiceDep) – Injected board service dependency. - ratio_config_service (
BoardRatioConfigServiceDep) – Injected ratio config service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info.
Returns:
BoardResponse– BoardResponse with the updated board details.
Raises:
403– User does not have access to this board's account.404– Board not found.
leadr.boards.api.board_schemas¶
API request and response models for boards.
Classes:
- BoardCreateRequest – Request model for creating a board.
- BoardRatioConfigRequest – Request model for ratio config when creating/updating a RATIO board.
- BoardRatioConfigResponse – Response model for ratio config.
- BoardResponse – Response model for a board.
- BoardUpdateRequest – Request model for updating a board.
leadr.boards.api.board_schemas.BoardCreateRequest¶
Bases: BaseModel
Request model for creating a board.
Attributes:
- account_id (
AccountID) – - board_type (
BoardType) – - created_from_template_id (
BoardTemplateID | None) – - description (
str | None) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - is_active (
bool) – - is_published (
bool) – - keep_strategy (
KeepStrategy | None) – - name (
str) – - ratio_config (
BoardRatioConfigRequest | None) – - short_code (
str | None) – - slug (
str | None) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str] | None) – - template_name (
str | None) – - unit (
str | None) –
# leadr.boards.api.board_schemas.BoardCreateRequest.account_id¶
account_id: AccountID = Field(description='ID of the account this board belongs to')
# leadr.boards.api.board_schemas.BoardCreateRequest.board_type¶
board_type: BoardType = Field(default=(BoardType.RUN_IDENTITY), description='Type of board determining score behavior')
# leadr.boards.api.board_schemas.BoardCreateRequest.created_from_template_id¶
created_from_template_id: BoardTemplateID | None = Field(default=None, description='Optional template ID this board was created from')
# leadr.boards.api.board_schemas.BoardCreateRequest.description¶
description: str | None = Field(default=None, description='Optional short description of the board')
# leadr.boards.api.board_schemas.BoardCreateRequest.ends_at¶
ends_at: datetime | None = Field(default=None, description='Optional end time for time-bounded boards (UTC)')
# leadr.boards.api.board_schemas.BoardCreateRequest.game_id¶
game_id: GameID = Field(description='ID of the game this board belongs to')
# leadr.boards.api.board_schemas.BoardCreateRequest.icon¶
icon: str | None = Field(default='fa-crown', description="Icon identifier for the board. Defaults to 'fa-crown'")
# leadr.boards.api.board_schemas.BoardCreateRequest.is_active¶
is_active: bool = Field(default=True, description='Whether the board is currently active')
# leadr.boards.api.board_schemas.BoardCreateRequest.is_published¶
is_published: bool = Field(default=True, description='Whether the board is published and visible on public web views')
# leadr.boards.api.board_schemas.BoardCreateRequest.keep_strategy¶
keep_strategy: KeepStrategy | None = Field(default=None, description='Strategy for keeping scores (RUN_IDENTITY boards only). Defaults to BEST for RUN_IDENTITY, ignored for other board types.')
# leadr.boards.api.board_schemas.BoardCreateRequest.name¶
name: str = Field(description='Name of the board')
# leadr.boards.api.board_schemas.BoardCreateRequest.ratio_config¶
ratio_config: BoardRatioConfigRequest | None = Field(default=None, description='Ratio config (required when board_type is RATIO)')
# leadr.boards.api.board_schemas.BoardCreateRequest.short_code¶
short_code: str | None = Field(default=None, description='Globally unique short code for direct sharing. Auto-generated if not provided')
# leadr.boards.api.board_schemas.BoardCreateRequest.slug¶
slug: str | None = Field(default=None, description='Optional URL-friendly slug. If not provided, will be auto-generated from name')
# leadr.boards.api.board_schemas.BoardCreateRequest.sort_direction¶
sort_direction: SortDirection = Field(default=(SortDirection.DESCENDING), description='Direction to sort scores')
# leadr.boards.api.board_schemas.BoardCreateRequest.starts_at¶
starts_at: datetime | None = Field(default=None, description='Optional start time for time-bounded boards (UTC)')
# leadr.boards.api.board_schemas.BoardCreateRequest.tags¶
tags: list[str] | None = Field(default=None, description='Optional list of tags for categorization')
# leadr.boards.api.board_schemas.BoardCreateRequest.template_name¶
template_name: str | None = Field(default=None, description='Optional template name this board was created from')
# leadr.boards.api.board_schemas.BoardCreateRequest.unit¶
unit: str | None = Field(default=None, description="Unit of measurement for scores (e.g., 'seconds', 'points'). Optional")
leadr.boards.api.board_schemas.BoardRatioConfigRequest¶
Bases: BaseModel
Request model for ratio config when creating/updating a RATIO board.
Attributes:
- decimals (
int) – - denominator_board_id (
BoardID) – - display (
RatioDisplay) – - min_denominator (
float) – - min_numerator (
float) – - numerator_board_id (
BoardID) – - scale (
int) – - tie_breaker (
TieBreaker) – - zero_denominator_policy (
ZeroDenominatorPolicy) –
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.decimals¶
decimals: int = Field(default=2, description='Number of decimal places for display')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.denominator_board_id¶
denominator_board_id: BoardID = Field(description='ID of the denominator board')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.display¶
display: RatioDisplay = Field(default=(RatioDisplay.RAW), description='Display format for ratio values')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.min_denominator¶
min_denominator: float = Field(default=0, description='Minimum denominator value for ranking eligibility')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.min_numerator¶
min_numerator: float = Field(default=0, description='Minimum numerator value for ranking eligibility')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.numerator_board_id¶
numerator_board_id: BoardID = Field(description='ID of the numerator board')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.scale¶
scale: int = Field(default=1000000, description='Scaling factor for ratio storage precision')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.tie_breaker¶
tie_breaker: TieBreaker = Field(default=(TieBreaker.NUMERATOR_DESC_DENOMINATOR_ASC), description='Strategy for breaking ties')
# leadr.boards.api.board_schemas.BoardRatioConfigRequest.zero_denominator_policy¶
zero_denominator_policy: ZeroDenominatorPolicy = Field(default=(ZeroDenominatorPolicy.NULL), description='How to handle zero denominators')
leadr.boards.api.board_schemas.BoardRatioConfigResponse¶
Bases: BaseModel
Response model for ratio config.
Functions:
- from_domain – Convert domain entity to response model.
Attributes:
- created_at (
datetime) – - decimals (
int) – - denominator_board_id (
BoardID) – - display (
RatioDisplay) – - id (
BoardRatioConfigID) – - min_denominator (
float) – - min_numerator (
float) – - numerator_board_id (
BoardID) – - scale (
int) – - tie_breaker (
TieBreaker) – - updated_at (
datetime) – - zero_denominator_policy (
ZeroDenominatorPolicy) –
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.created_at¶
created_at: datetime = Field(description='Timestamp when the config was created (UTC)')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.decimals¶
decimals: int = Field(description='Number of decimal places for display')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.denominator_board_id¶
denominator_board_id: BoardID = Field(description='ID of the denominator board')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.display¶
display: RatioDisplay = Field(description='Display format for ratio values')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.from_domain¶
from_domain(config)
Convert domain entity to response model.
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.id¶
id: BoardRatioConfigID = Field(description='Unique identifier for the ratio config')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.min_denominator¶
min_denominator: float = Field(description='Minimum denominator for ranking eligibility')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.min_numerator¶
min_numerator: float = Field(description='Minimum numerator for ranking eligibility')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.numerator_board_id¶
numerator_board_id: BoardID = Field(description='ID of the numerator board')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.scale¶
scale: int = Field(description='Scaling factor for ratio storage')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.tie_breaker¶
tie_breaker: TieBreaker = Field(description='Strategy for breaking ties')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.updated_at¶
updated_at: datetime = Field(description='Timestamp of last update (UTC)')
# leadr.boards.api.board_schemas.BoardRatioConfigResponse.zero_denominator_policy¶
zero_denominator_policy: ZeroDenominatorPolicy = Field(description='How zero denominators are handled')
leadr.boards.api.board_schemas.BoardResponse¶
Bases: BaseModel
Response model for a board.
Functions:
- from_domain – Convert domain entity to response model.
Attributes:
- account_id (
AccountID) – - board_type (
BoardType) – - created_at (
datetime) – - created_from_template_id (
BoardTemplateID | None) – - description (
str | None) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - id (
BoardID) – - is_active (
bool) – - is_published (
bool) – - keep_strategy (
KeepStrategy) – - name (
str) – - ratio_config (
BoardRatioConfigResponse | None) – - short_code (
str) – - slug (
str) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str]) – - template_name (
str | None) – - unit (
str | None) – - updated_at (
datetime) – - url_short (
str | None) – Short URL for direct board access via short_code.
# leadr.boards.api.board_schemas.BoardResponse.account_id¶
account_id: AccountID = Field(description='ID of the account this board belongs to')
# leadr.boards.api.board_schemas.BoardResponse.board_type¶
board_type: BoardType = Field(description='Type of board determining score behavior')
# leadr.boards.api.board_schemas.BoardResponse.created_at¶
created_at: datetime = Field(description='Timestamp when the board was created (UTC)')
# leadr.boards.api.board_schemas.BoardResponse.created_from_template_id¶
created_from_template_id: BoardTemplateID | None = Field(default=None, description='Template ID this board was created from, or null')
# leadr.boards.api.board_schemas.BoardResponse.description¶
description: str | None = Field(default=None, description='Short description of the board')
# leadr.boards.api.board_schemas.BoardResponse.ends_at¶
ends_at: datetime | None = Field(default=None, description='End time for time-bounded boards (UTC)')
# leadr.boards.api.board_schemas.BoardResponse.from_domain¶
from_domain(board, ratio_config=None)
Convert domain entity to response model.
Parameters:
- board (
Board) – The domain Board entity to convert. - ratio_config (
BoardRatioConfig | None) – Optional ratio config for RATIO boards.
Returns:
BoardResponse– BoardResponse with all fields populated from the domain entity.
# leadr.boards.api.board_schemas.BoardResponse.game_id¶
game_id: GameID = Field(description='ID of the game this board belongs to')
# leadr.boards.api.board_schemas.BoardResponse.icon¶
icon: str | None = Field(description='Icon identifier for the board, or null')
# leadr.boards.api.board_schemas.BoardResponse.id¶
id: BoardID = Field(description='Unique identifier for the board')
# leadr.boards.api.board_schemas.BoardResponse.is_active¶
is_active: bool = Field(description='Whether the board is currently active')
# leadr.boards.api.board_schemas.BoardResponse.is_published¶
is_published: bool = Field(description='Whether the board is published and visible on public web views')
# leadr.boards.api.board_schemas.BoardResponse.keep_strategy¶
keep_strategy: KeepStrategy = Field(description='Strategy for keeping scores (RUN_IDENTITY only)')
# leadr.boards.api.board_schemas.BoardResponse.name¶
name: str = Field(description='Name of the board')
# leadr.boards.api.board_schemas.BoardResponse.ratio_config¶
ratio_config: BoardRatioConfigResponse | None = Field(default=None, description='Ratio config (present only for RATIO boards)')
# leadr.boards.api.board_schemas.BoardResponse.short_code¶
short_code: str = Field(description='Globally unique short code for direct sharing')
# leadr.boards.api.board_schemas.BoardResponse.slug¶
slug: str = Field(description='URL-friendly slug for the board (auto-generated, read-only)')
# leadr.boards.api.board_schemas.BoardResponse.sort_direction¶
sort_direction: SortDirection = Field(description='Direction to sort scores')
# leadr.boards.api.board_schemas.BoardResponse.starts_at¶
starts_at: datetime | None = Field(default=None, description='Start time for time-bounded boards (UTC)')
# leadr.boards.api.board_schemas.BoardResponse.tags¶
tags: list[str] = Field(default_factory=list, description='List of tags for categorization')
# leadr.boards.api.board_schemas.BoardResponse.template_name¶
template_name: str | None = Field(default=None, description='Template name this board was created from, or null')
# leadr.boards.api.board_schemas.BoardResponse.unit¶
unit: str | None = Field(description='Unit of measurement for scores, or null')
# leadr.boards.api.board_schemas.BoardResponse.updated_at¶
updated_at: datetime = Field(description='Timestamp of last update (UTC)')
# leadr.boards.api.board_schemas.BoardResponse.url_short¶
url_short: str | None
Short URL for direct board access via short_code.
Returns the URL if BOARDS_UI_DOMAIN is configured and the board is published, otherwise None.
leadr.boards.api.board_schemas.BoardUpdateRequest¶
Bases: BaseModel
Request model for updating a board.
Attributes:
- board_type (
BoardType | None) – - created_from_template_id (
BoardTemplateID | None) – - deleted (
bool | None) – - description (
str | None) – - ends_at (
datetime | None) – - icon (
str | None) – - is_active (
bool | None) – - is_published (
bool | None) – - keep_strategy (
KeepStrategy | None) – - name (
str | None) – - ratio_config (
BoardRatioConfigRequest | None) – - short_code (
str | None) – - sort_direction (
SortDirection | None) – - starts_at (
datetime | None) – - tags (
list[str] | None) – - template_name (
str | None) – - unit (
str | None) –
# leadr.boards.api.board_schemas.BoardUpdateRequest.board_type¶
board_type: BoardType | None = Field(default=None, description='Updated board type')
# leadr.boards.api.board_schemas.BoardUpdateRequest.created_from_template_id¶
created_from_template_id: BoardTemplateID | None = Field(default=None, description='Updated template ID')
# leadr.boards.api.board_schemas.BoardUpdateRequest.deleted¶
deleted: bool | None = Field(default=None, description='Set to true to soft delete the board')
# leadr.boards.api.board_schemas.BoardUpdateRequest.description¶
description: str | None = Field(default=None, description='Updated board description')
# leadr.boards.api.board_schemas.BoardUpdateRequest.ends_at¶
ends_at: datetime | None = Field(default=None, description='Updated end time')
# leadr.boards.api.board_schemas.BoardUpdateRequest.icon¶
icon: str | None = Field(default=None, description='Updated icon identifier')
# leadr.boards.api.board_schemas.BoardUpdateRequest.is_active¶
is_active: bool | None = Field(default=None, description='Updated active status')
# leadr.boards.api.board_schemas.BoardUpdateRequest.is_published¶
is_published: bool | None = Field(default=None, description='Updated published status')
# leadr.boards.api.board_schemas.BoardUpdateRequest.keep_strategy¶
keep_strategy: KeepStrategy | None = Field(default=None, description='Updated keep strategy')
# leadr.boards.api.board_schemas.BoardUpdateRequest.name¶
name: str | None = Field(default=None, description='Updated board name')
# leadr.boards.api.board_schemas.BoardUpdateRequest.ratio_config¶
ratio_config: BoardRatioConfigRequest | None = Field(default=None, description='Updated ratio config (for RATIO boards only)')
# leadr.boards.api.board_schemas.BoardUpdateRequest.short_code¶
short_code: str | None = Field(default=None, description='Updated short code')
# leadr.boards.api.board_schemas.BoardUpdateRequest.sort_direction¶
sort_direction: SortDirection | None = Field(default=None, description='Updated sort direction')
# leadr.boards.api.board_schemas.BoardUpdateRequest.starts_at¶
starts_at: datetime | None = Field(default=None, description='Updated start time')
# leadr.boards.api.board_schemas.BoardUpdateRequest.tags¶
tags: list[str] | None = Field(default=None, description='Updated tags list')
# leadr.boards.api.board_schemas.BoardUpdateRequest.template_name¶
template_name: str | None = Field(default=None, description='Updated template name')
# leadr.boards.api.board_schemas.BoardUpdateRequest.unit¶
unit: str | None = Field(default=None, description='Updated unit of measurement')
leadr.boards.api.board_state_routes¶
API routes for board state management (admin only, read-only).
Functions:
- get_board_state – Get a single board state by ID (Admin API).
- list_board_states – List board states (Admin API).
Attributes:
- router –
leadr.boards.api.board_state_routes.get_board_state¶
get_board_state(state_id, auth, service)
Get a single board state by ID (Admin API).
Parameters:
- state_id (
BoardStateID) – Board state ID. - auth (
AdminAuthContextDep) – Admin authentication context. - service (
BoardStateServiceDep) – Injected board state service dependency.
Returns:
BoardStateResponse– Board state details.
Raises:
404– Board state not found.
leadr.boards.api.board_state_routes.list_board_states¶
list_board_states(auth, service, pagination, board_id=None, identity_id=None)
List board states (Admin API).
Returns a paginated list of board states. Board states are materialized ranking states computed from score events.
Parameters:
- auth (
AdminAuthContextDep) – Admin authentication context. - service (
BoardStateServiceDep) – Injected board state service dependency. - pagination (
Annotated[PaginationParams, Depends()]) – Pagination parameters (cursor, limit, sort). - board_id (
Annotated[BoardID | None, Query(description='Filter by board ID')]) – Optional filter by board ID. - identity_id (
Annotated[IdentityID | None, Query(description='Filter by identity ID')]) – Optional filter by identity ID.
Returns:
PaginatedResponse[BoardStateResponse]– Paginated list of board states.
Raises:
400– Invalid pagination cursor.
leadr.boards.api.board_state_routes.router¶
router = APIRouter()
leadr.boards.api.board_state_schemas¶
API response models for board states.
Classes:
- BoardStateResponse – Response model for a board state (admin only).
leadr.boards.api.board_state_schemas.BoardStateResponse¶
Bases: BaseModel
Response model for a board state (admin only).
Board states represent the materialized ranking state for an identity on a board. They are computed from score events and used for leaderboard queries.
Functions:
- from_domain – Convert domain entity to response model.
Attributes:
- aux (
dict[str, Any] | None) – - board_id (
BoardID) – - created_at (
datetime) – - id (
BoardStateID) – - identity_id (
IdentityID) – - primary_value (
float | None) – - updated_at (
datetime) –
# leadr.boards.api.board_state_schemas.BoardStateResponse.aux¶
aux: dict[str, Any] | None = Field(default=None, description='Board-type-specific auxiliary data')
# leadr.boards.api.board_state_schemas.BoardStateResponse.board_id¶
board_id: BoardID = Field(description='ID of the board this state belongs to')
# leadr.boards.api.board_state_schemas.BoardStateResponse.created_at¶
created_at: datetime = Field(description='Timestamp when the state was created (UTC)')
# leadr.boards.api.board_state_schemas.BoardStateResponse.from_domain¶
from_domain(state)
Convert domain entity to response model.
Parameters:
- state (
BoardState) – The domain BoardState entity to convert.
Returns:
BoardStateResponse– BoardStateResponse with all fields populated from the domain entity.
# leadr.boards.api.board_state_schemas.BoardStateResponse.id¶
id: BoardStateID = Field(description='Unique identifier for the board state')
# leadr.boards.api.board_state_schemas.BoardStateResponse.identity_id¶
identity_id: IdentityID = Field(description='ID of the identity this state is for')
# leadr.boards.api.board_state_schemas.BoardStateResponse.primary_value¶
primary_value: float | None = Field(default=None, description='Rankable value (null if not rankable)')
# leadr.boards.api.board_state_schemas.BoardStateResponse.updated_at¶
updated_at: datetime = Field(description='Timestamp when the state was last updated (UTC)')
leadr.boards.api.board_template_routes¶
Board template API routes.
Functions:
- create_board_template – Create a new board template.
- get_board_template – Get a board template by ID.
- list_board_templates – List board templates for an account with pagination, optionally filtered by game.
- update_board_template – Update a board template.
Attributes:
- router –
leadr.boards.api.board_template_routes.create_board_template¶
create_board_template(request, service, auth, background_tasks, pre_hook)
Create a new board template.
Creates a template for automatically generating boards at regular intervals. The game must belong to the specified account.
For regular users, account_id must match their API key's account. For superadmins, any account_id is accepted.
Parameters:
- request (
BoardTemplateCreateRequest) – Template creation details including repeat_interval and configuration. - service (
BoardTemplateServiceDep) – Injected board template service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info. - pre_hook (
PreCreateBoardTemplateHookDep) – Pre-create hook for entitlement checks.
Returns:
BoardTemplateResponse– BoardTemplateResponse with the created template including auto-generated ID.
Raises:
403– User does not have access to the specified account, or repeat_interval not allowed.404– Game or account not found.400– Game doesn't belong to the specified account.
leadr.boards.api.board_template_routes.get_board_template¶
get_board_template(template_id, service, auth)
Get a board template by ID.
Parameters:
- template_id (
BoardTemplateID) – Unique identifier for the template. - service (
BoardTemplateServiceDep) – Injected board template service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info.
Returns:
BoardTemplateResponse– BoardTemplateResponse with full template details.
Raises:
403– User does not have access to this template's account.404– Template not found.
leadr.boards.api.board_template_routes.list_board_templates¶
list_board_templates(auth, service, pagination, account_id=None, game_id=None)
List board templates for an account with pagination, optionally filtered by game.
For regular users, account_id is automatically derived from their API key. For superadmins, account_id is optional - if omitted, returns templates from all accounts.
Pagination:
- Default: 20 items per page, sorted by created_at:desc,id:asc
- Custom sort: Use ?sort=name:asc,created_at:desc
- Valid sort fields: id, name, created_at, updated_at
- Navigation: Use next_cursor/prev_cursor from response
Example
GET /v1/board-templates?account_id=acc_123&game_id=gam_456&limit=50&sort=name:ascParameters:
- auth (
AdminAuthContextDep) – Authentication context with user info. - service (
BoardTemplateServiceDep) – Injected board template service dependency. - pagination (
Annotated[PaginationParams, Depends()]) – Pagination parameters (cursor, limit, sort). - account_id (
Annotated[AccountID | None, Query(description='Account ID filter')]) – Optional account_id query parameter (superadmins can omit to see all). - game_id (
Annotated[GameID | None, Query(description='Filter by game ID')]) – Optional game ID to filter templates by.
Returns:
PaginatedResponse[BoardTemplateResponse]– PaginatedResponse with board templates and pagination metadata.
Raises:
400– Invalid cursor, sort field, or cursor state mismatch.403– User does not have access to the specified account.
leadr.boards.api.board_template_routes.router¶
router = APIRouter()
leadr.boards.api.board_template_routes.update_board_template¶
update_board_template(template_id, request, service, auth, background_tasks, pre_hook)
Update a board template.
Supports updating any template field or soft-deleting the template.
Parameters:
- template_id (
BoardTemplateID) – Unique identifier for the template. - request (
BoardTemplateUpdateRequest) – Template update details (all fields optional). - service (
BoardTemplateServiceDep) – Injected board template service dependency. - auth (
AdminAuthContextDep) – Authentication context with user info. - pre_hook (
PreUpdateBoardTemplateHookDep) – Pre-update hook for entitlement checks.
Returns:
BoardTemplateResponse– BoardTemplateResponse with the updated template details.
Raises:
403– User does not have access to this template's account, or repeat_interval not allowed.404– Template not found.
leadr.boards.api.board_template_schemas¶
API request and response models for board templates.
Classes:
- BoardTemplateCreateRequest – Request model for creating a board template.
- BoardTemplateResponse – Response model for a board template.
- BoardTemplateUpdateRequest – Request model for updating a board template.
leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest¶
Bases: BaseModel
Request model for creating a board template.
Attributes:
- account_id (
AccountID) – - config (
dict[str, Any] | None) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - is_active (
bool) – - is_published (
bool) – - keep_strategy (
KeepStrategy) – - name (
str) – - name_template (
str | None) – - next_run_at (
datetime) – - repeat_interval (
str) – - series (
str | None) – - slug (
str | None) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str] | None) – - unit (
str | None) –
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.account_id¶
account_id: AccountID = Field(description='ID of the account this template belongs to')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.config¶
config: dict[str, Any] | None = Field(default=None, description='Reserved for future procedural generation (bounds, variables, randomization rules)')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.ends_at¶
ends_at: datetime | None = Field(default=None, description='Optional end time for time-bounded boards')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.game_id¶
game_id: GameID = Field(description='ID of the game this template belongs to')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.icon¶
icon: str | None = Field(default='fa-crown', description='Icon identifier for boards created from this template')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.is_active¶
is_active: bool = Field(description='Whether the template is currently active')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.is_published¶
is_published: bool = Field(default=True, description='Whether boards created from this template should be published')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.keep_strategy¶
keep_strategy: KeepStrategy = Field(default=(KeepStrategy.BEST), description='Strategy for keeping multiple scores from the same user')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.name¶
name: str = Field(description='Name of the template')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.name_template¶
name_template: str | None = Field(default=None, description='Optional template string for generating board names')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.next_run_at¶
next_run_at: datetime = Field(description='Next scheduled time to create a board from this template (UTC)')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.repeat_interval¶
repeat_interval: str = Field(description="PostgreSQL interval syntax for repeat frequency (e.g., '7 days', '1 month')")
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.series¶
series: str | None = Field(default=None, description='Optional series identifier for sequential board naming')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.slug¶
slug: str | None = Field(default=None, description='URL-friendly slug for boards created from this template')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.sort_direction¶
sort_direction: SortDirection = Field(default=(SortDirection.DESCENDING), description='Direction to sort scores (ascending/descending)')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.starts_at¶
starts_at: datetime | None = Field(default=None, description='Optional start time for time-bounded boards')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.tags¶
tags: list[str] | None = Field(default=None, description='List of tags for categorizing boards created from this template')
# leadr.boards.api.board_template_schemas.BoardTemplateCreateRequest.unit¶
unit: str | None = Field(default=None, description="Unit of measurement for scores (e.g., 'seconds', 'points')")
leadr.boards.api.board_template_schemas.BoardTemplateResponse¶
Bases: BaseModel
Response model for a board template.
Functions:
- from_domain – Convert domain entity to response model.
Attributes:
- account_id (
AccountID) – - config (
dict[str, Any]) – - created_at (
datetime) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - id (
BoardTemplateID) – - is_active (
bool) – - is_published (
bool) – - keep_strategy (
KeepStrategy) – - name (
str) – - name_template (
str | None) – - next_run_at (
datetime) – - repeat_interval (
str) – - series (
str | None) – - slug (
str | None) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str]) – - unit (
str | None) – - updated_at (
datetime) –
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.account_id¶
account_id: AccountID = Field(description='ID of the account this template belongs to')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.config¶
config: dict[str, Any] = Field(default_factory=dict, description='Reserved for future procedural generation (bounds, variables, randomization rules)')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.created_at¶
created_at: datetime = Field(description='Timestamp when the template was created (UTC)')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.ends_at¶
ends_at: datetime | None = Field(description='Optional end time for time-bounded boards')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.from_domain¶
from_domain(template)
Convert domain entity to response model.
Parameters:
- template (
BoardTemplate) – The domain BoardTemplate entity to convert.
Returns:
BoardTemplateResponse– BoardTemplateResponse with all fields populated from the domain entity.
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.game_id¶
game_id: GameID = Field(description='ID of the game this template belongs to')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.icon¶
icon: str | None = Field(description='Icon identifier for boards created from this template')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.id¶
id: BoardTemplateID = Field(description='Unique identifier for the template')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.is_active¶
is_active: bool = Field(description='Whether the template is currently active')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.is_published¶
is_published: bool = Field(description='Whether boards created from this template should be published')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.keep_strategy¶
keep_strategy: KeepStrategy = Field(description='Strategy for keeping multiple scores from the same user')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.name¶
name: str = Field(description='Name of the template')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.name_template¶
name_template: str | None = Field(default=None, description='Template string for generating board names, or null')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.next_run_at¶
next_run_at: datetime = Field(description='Next scheduled run time (UTC)')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.repeat_interval¶
repeat_interval: str = Field(description='Repeat frequency in PostgreSQL interval syntax')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.series¶
series: str | None = Field(default=None, description='Series identifier for sequential board naming, or null')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.slug¶
slug: str | None = Field(description='URL-friendly slug for boards created from this template, or null')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.sort_direction¶
sort_direction: SortDirection = Field(description='Direction to sort scores (ascending/descending)')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.starts_at¶
starts_at: datetime | None = Field(description='Optional start time for time-bounded boards')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.tags¶
tags: list[str] = Field(description='List of tags for categorizing boards created from this template')
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.unit¶
unit: str | None = Field(description="Unit of measurement for scores (e.g., 'seconds', 'points')")
# leadr.boards.api.board_template_schemas.BoardTemplateResponse.updated_at¶
updated_at: datetime = Field(description='Timestamp of last update (UTC)')
leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest¶
Bases: BaseModel
Request model for updating a board template.
Attributes:
- config (
dict[str, Any] | None) – - deleted (
bool | None) – - ends_at (
datetime | None) – - icon (
str | None) – - is_active (
bool | None) – - is_published (
bool | None) – - keep_strategy (
KeepStrategy | None) – - name (
str | None) – - name_template (
str | None) – - next_run_at (
datetime | None) – - repeat_interval (
str | None) – - series (
str | None) – - slug (
str | None) – - sort_direction (
SortDirection | None) – - starts_at (
datetime | None) – - tags (
list[str] | None) – - unit (
str | None) –
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.config¶
config: dict[str, Any] | None = Field(default=None, description='Updated config (reserved for procedural generation)')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.deleted¶
deleted: bool | None = Field(default=None, description='Set to true to soft delete the template')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.ends_at¶
ends_at: datetime | None = Field(default=None, description='Updated end time')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.icon¶
icon: str | None = Field(default=None, description='Updated icon identifier')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.is_active¶
is_active: bool | None = Field(default=None, description='Updated active status')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.is_published¶
is_published: bool | None = Field(default=None, description='Updated published status')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.keep_strategy¶
keep_strategy: KeepStrategy | None = Field(default=None, description='Updated keep strategy')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.name¶
name: str | None = Field(default=None, description='Updated template name')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.name_template¶
name_template: str | None = Field(default=None, description='Updated name template')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.next_run_at¶
next_run_at: datetime | None = Field(default=None, description='Updated next run time')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.repeat_interval¶
repeat_interval: str | None = Field(default=None, description='Updated repeat interval')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.series¶
series: str | None = Field(default=None, description='Updated series identifier')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.slug¶
slug: str | None = Field(default=None, description='Updated slug')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.sort_direction¶
sort_direction: SortDirection | None = Field(default=None, description='Updated sort direction')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.starts_at¶
starts_at: datetime | None = Field(default=None, description='Updated start time')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.tags¶
tags: list[str] | None = Field(default=None, description='Updated tags list')
# leadr.boards.api.board_template_schemas.BoardTemplateUpdateRequest.unit¶
unit: str | None = Field(default=None, description='Updated unit of measurement')
leadr.boards.api.run_entry_routes¶
API routes for run entry management (admin only, read-only).
Functions:
- get_run_entry – Get a single run entry by ID (Admin API).
- list_run_entries – List run entries (Admin API).
Attributes:
- router –
leadr.boards.api.run_entry_routes.get_run_entry¶
get_run_entry(entry_id, auth, service)
Get a single run entry by ID (Admin API).
Parameters:
- entry_id (
RunEntryID) – Run entry ID. - auth (
AdminAuthContextDep) – Admin authentication context. - service (
RunEntryServiceDep) – Injected run entry service dependency.
Returns:
RunEntryResponse– Run entry details.
Raises:
404– Run entry not found.
leadr.boards.api.run_entry_routes.list_run_entries¶
list_run_entries(auth, service, pagination, board_id=None, identity_id=None)
List run entries (Admin API).
Returns a paginated list of run entries. Run entries are individual scored submissions for RUN_RUNS boards where every submission is ranked.
Parameters:
- auth (
AdminAuthContextDep) – Admin authentication context. - service (
RunEntryServiceDep) – Injected run entry service dependency. - pagination (
Annotated[PaginationParams, Depends()]) – Pagination parameters (cursor, limit, sort). - board_id (
Annotated[BoardID | None, Query(description='Filter by board ID')]) – Optional filter by board ID. - identity_id (
Annotated[IdentityID | None, Query(description='Filter by identity ID')]) – Optional filter by identity ID.
Returns:
PaginatedResponse[RunEntryResponse]– Paginated list of run entries.
Raises:
400– Invalid pagination cursor.
leadr.boards.api.run_entry_routes.router¶
router = APIRouter()
leadr.boards.api.run_entry_schemas¶
API response models for run entries.
Classes:
- RunEntryResponse – Response model for a run entry (admin only).
leadr.boards.api.run_entry_schemas.RunEntryResponse¶
Bases: BaseModel
Response model for a run entry (admin only).
Run entries represent individual scored submissions for RUN_RUNS boards where every submission is ranked.
Functions:
- from_domain – Convert domain entity to response model.
Attributes:
- board_id (
BoardID) – - created_at (
datetime) – - id (
RunEntryID) – - identity_id (
IdentityID) – - primary_value (
float) – - score_event_id (
ScoreEventID) – - updated_at (
datetime) –
# leadr.boards.api.run_entry_schemas.RunEntryResponse.board_id¶
board_id: BoardID = Field(description='ID of the board this entry belongs to')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.created_at¶
created_at: datetime = Field(description='Timestamp when the entry was created (UTC)')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.from_domain¶
from_domain(entry)
Convert domain entity to response model.
Parameters:
- entry (
RunEntry) – The domain RunEntry entity to convert.
Returns:
RunEntryResponse– RunEntryResponse with all fields populated from the domain entity.
# leadr.boards.api.run_entry_schemas.RunEntryResponse.id¶
id: RunEntryID = Field(description='Unique identifier for the run entry')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.identity_id¶
identity_id: IdentityID = Field(description='ID of the identity that submitted this entry')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.primary_value¶
primary_value: float = Field(description='Rankable value for this submission')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.score_event_id¶
score_event_id: ScoreEventID = Field(description='ID of the score event that created this entry')
# leadr.boards.api.run_entry_schemas.RunEntryResponse.updated_at¶
updated_at: datetime = Field(description='Timestamp when the entry was last updated (UTC)')
leadr.boards.domain¶
Modules:
- board – Board domain model.
- board_ratio_config – Board ratio config domain model.
- board_state – BoardState domain model for materialized ranking state.
- board_template – BoardTemplate domain model.
- interval_parser – Utilities for parsing PostgreSQL interval syntax.
- run_entry – RunEntry domain model for RUN_RUNS boards.
leadr.boards.domain.board¶
Board domain model.
Classes:
- Board – Board domain entity.
- BoardType – Type of board determining score behavior.
- KeepStrategy – Strategy for keeping scores from the same user (RUN_IDENTITY boards only).
- SortDirection – Sort direction for board scores.
leadr.boards.domain.board.Board¶
Bases: Entity
Board domain entity.
Represents a leaderboard/board that belongs to a game. Boards define how scores are tracked, sorted, and displayed. Each board has a globally unique short_code for direct sharing and can be time-bounded with start/end dates.
Each board belongs to exactly one game and inherits the game's account for multi-tenancy. Boards can be created from templates and can have custom tags for categorization.
Functions:
- restore – Restore a soft-deleted entity.
- soft_delete – Mark entity as soft-deleted.
- validate_board_type_keep_strategy – Validate board_type and keep_strategy combination.
- validate_name – Validate board name is not empty.
- validate_short_code – Validate short_code is not empty.
- validate_slug – Validate slug format (lowercase alphanumeric with hyphens).
Attributes:
- account_id (
AccountID) – - board_type (
BoardType) – - created_at (
datetime) – - created_from_template_id (
BoardTemplateID | None) – - deleted_at (
datetime | None) – - description (
str | None) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - id (
BoardID) – - is_active (
bool) – - is_deleted (
bool) – Check if entity is soft-deleted. - is_published (
bool) – - keep_strategy (
KeepStrategy) – - model_config –
- name (
str) – - short_code (
str) – - slug (
str) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str]) – - template_name (
str | None) – - unit (
str | None) – - updated_at (
datetime) –
# leadr.boards.domain.board.Board.account_id¶
account_id: AccountID = Field(frozen=True, description='ID of the account this board belongs to (immutable)')
# leadr.boards.domain.board.Board.board_type¶
board_type: BoardType = Field(description='Type of board determining score behavior', default=(BoardType.RUN_IDENTITY))
# leadr.boards.domain.board.Board.created_at¶
created_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp when entity was created (UTC)')
# leadr.boards.domain.board.Board.created_from_template_id¶
created_from_template_id: BoardTemplateID | None = Field(default=None, description='Optional template ID this board was created from')
# leadr.boards.domain.board.Board.deleted_at¶
deleted_at: datetime | None = Field(default=None, description='Timestamp when entity was soft-deleted (UTC), or null if active')
# leadr.boards.domain.board.Board.description¶
description: str | None = Field(default=None, description='Short description of the board')
# leadr.boards.domain.board.Board.ends_at¶
ends_at: datetime | None = Field(default=None, description='Optional end time for time-bounded boards')
# leadr.boards.domain.board.Board.game_id¶
game_id: GameID = Field(frozen=True, description='ID of the game this board belongs to (immutable)')
# leadr.boards.domain.board.Board.icon¶
icon: str | None = Field(description='Icon identifier for the board', default='fa-crown')
# leadr.boards.domain.board.Board.id¶
id: BoardID = Field(frozen=True, default_factory=BoardID, description='Unique board identifier')
# leadr.boards.domain.board.Board.is_active¶
is_active: bool = Field(description='Whether the board is currently active', default=True)
# leadr.boards.domain.board.Board.is_deleted¶
is_deleted: bool
Check if entity is soft-deleted.
Returns:
bool– True if the entity has a deleted_at timestamp, False otherwise.
# leadr.boards.domain.board.Board.is_published¶
is_published: bool = Field(description='Whether the board is published and visible on public web views', default=True)
# leadr.boards.domain.board.Board.keep_strategy¶
keep_strategy: KeepStrategy = Field(description='Strategy for keeping multiple scores from the same user (RUN_IDENTITY only)', default=(KeepStrategy.BEST))
# leadr.boards.domain.board.Board.model_config¶
model_config = ConfigDict(validate_assignment=True)
# leadr.boards.domain.board.Board.name¶
name: str = Field(description='Name of the board')
# leadr.boards.domain.board.Board.restore¶
restore()
Restore a soft-deleted entity.
Clears the deleted_at timestamp, making the entity active again.
Example
> > > account.soft_delete() > > > account.restore() > > > assert account.is_deleted is False# leadr.boards.domain.board.Board.short_code¶
short_code: str = Field(description='Globally unique short code for direct board sharing')
# leadr.boards.domain.board.Board.slug¶
slug: str = Field(description='URL-friendly slug for the board (unique per game when active)')
# leadr.boards.domain.board.Board.soft_delete¶
soft_delete()
Mark entity as soft-deleted.
Sets the deleted_at timestamp to the current UTC time. Entities that are already deleted are not affected (deleted_at remains at original deletion time).
Example
> > > account = Account(name="Test", slug="test") > > > account.soft_delete() > > > assert account.is_deleted is True# leadr.boards.domain.board.Board.sort_direction¶
sort_direction: SortDirection = Field(description='Direction to sort scores (ascending/descending)', default=(SortDirection.DESCENDING))
# leadr.boards.domain.board.Board.starts_at¶
starts_at: datetime | None = Field(default=None, description='Optional start time for time-bounded boards')
# leadr.boards.domain.board.Board.tags¶
tags: list[str] = Field(default_factory=list, description='List of tags for categorizing the board')
# leadr.boards.domain.board.Board.template_name¶
template_name: str | None = Field(default=None, description='Optional name of the template this board was created from')
# leadr.boards.domain.board.Board.unit¶
unit: str | None = Field(description="Unit of measurement for scores (e.g., 'seconds', 'points')", default=None)
# leadr.boards.domain.board.Board.updated_at¶
updated_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp of last update (UTC)')
# leadr.boards.domain.board.Board.validate_board_type_keep_strategy¶
validate_board_type_keep_strategy()
Validate board_type and keep_strategy combination.
- RUN_IDENTITY boards must have a non-NA keep_strategy (FIRST, BEST, LATEST)
- Non-RUN_IDENTITY boards (RUN_RUNS, COUNTER, RATIO) must have NA keep_strategy
Returns:
Board– The validated Board instance.
Raises:
ValueError– If the board_type/keep_strategy combination is invalid.
# leadr.boards.domain.board.Board.validate_name¶
validate_name(value)
Validate board name is not empty.
Parameters:
- value (
str) – The board name to validate.
Returns:
str– The validated and trimmed board name.
Raises:
ValueError– If board name is empty or whitespace only.
# leadr.boards.domain.board.Board.validate_short_code¶
validate_short_code(value)
Validate short_code is not empty.
Parameters:
- value (
str) – The short_code to validate.
Returns:
str– The validated and trimmed short_code.
Raises:
ValueError– If short_code is empty or whitespace only.
# leadr.boards.domain.board.Board.validate_slug¶
validate_slug(value)
Validate slug format (lowercase alphanumeric with hyphens).
Parameters:
- value (
str) – The slug to validate.
Returns:
str– The validated slug.
Raises:
ValueError– If slug is invalid.
leadr.boards.domain.board.BoardType¶
Type of board determining score behavior.
Attributes:
- COUNTER –
- RATIO –
- RUN_IDENTITY –
- RUN_RUNS –
# leadr.boards.domain.board.BoardType.COUNTER¶
COUNTER = 'COUNTER'
# leadr.boards.domain.board.BoardType.RATIO¶
RATIO = 'RATIO'
# leadr.boards.domain.board.BoardType.RUN_IDENTITY¶
RUN_IDENTITY = 'RUN_IDENTITY'
# leadr.boards.domain.board.BoardType.RUN_RUNS¶
RUN_RUNS = 'RUN_RUNS'
leadr.boards.domain.board.KeepStrategy¶
Strategy for keeping scores from the same user (RUN_IDENTITY boards only).
Attributes:
# leadr.boards.domain.board.KeepStrategy.BEST¶
BEST = 'BEST'
# leadr.boards.domain.board.KeepStrategy.FIRST¶
FIRST = 'FIRST'
# leadr.boards.domain.board.KeepStrategy.LATEST¶
LATEST = 'LATEST'
# leadr.boards.domain.board.KeepStrategy.NA¶
NA = 'NA'
leadr.boards.domain.board.SortDirection¶
Sort direction for board scores.
Attributes:
- ASCENDING –
- DESCENDING –
# leadr.boards.domain.board.SortDirection.ASCENDING¶
ASCENDING = 'ASCENDING'
# leadr.boards.domain.board.SortDirection.DESCENDING¶
DESCENDING = 'DESCENDING'
leadr.boards.domain.board_ratio_config¶
Board ratio config domain model.
Classes:
- BoardRatioConfig – Configuration for a RATIO board type.
- RatioDisplay – Display format for ratio values.
- TieBreaker – Tie-breaking strategy for equal ratios.
- ZeroDenominatorPolicy – Policy for handling zero denominators in ratio calculations.
leadr.boards.domain.board_ratio_config.BoardRatioConfig¶
Bases: Entity
Configuration for a RATIO board type.
RATIO boards derive their ranking from two other boards (numerator and denominator). The ratio is calculated as: numerator_value / denominator_value * scale
This is useful for metrics like:
- Win rate: wins / games_played
- Kill/Death ratio: kills / deaths
- Accuracy: hits / shots_fired
Functions:
- restore – Restore a soft-deleted entity.
- soft_delete – Mark entity as soft-deleted.
Attributes:
- board_id (
BoardID) – - created_at (
datetime) – - decimals (
int) – - deleted_at (
datetime | None) – - denominator_board_id (
BoardID) – - display (
RatioDisplay) – - id (
BoardRatioConfigID) – - is_deleted (
bool) – Check if entity is soft-deleted. - min_denominator (
float) – - min_numerator (
float) – - model_config –
- numerator_board_id (
BoardID) – - scale (
int) – - tie_breaker (
TieBreaker) – - updated_at (
datetime) – - zero_denominator_policy (
ZeroDenominatorPolicy) –
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.board_id¶
board_id: BoardID = Field(frozen=True)
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.created_at¶
created_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp when entity was created (UTC)')
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.decimals¶
decimals: int = 2
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.deleted_at¶
deleted_at: datetime | None = Field(default=None, description='Timestamp when entity was soft-deleted (UTC), or null if active')
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.denominator_board_id¶
denominator_board_id: BoardID = Field(frozen=True)
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.display¶
display: RatioDisplay = RatioDisplay.RAW
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.id¶
id: BoardRatioConfigID = Field(frozen=True, default_factory=BoardRatioConfigID)
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.is_deleted¶
is_deleted: bool
Check if entity is soft-deleted.
Returns:
bool– True if the entity has a deleted_at timestamp, False otherwise.
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.min_denominator¶
min_denominator: float = 0
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.min_numerator¶
min_numerator: float = 0
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.model_config¶
model_config = ConfigDict(validate_assignment=True)
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.numerator_board_id¶
numerator_board_id: BoardID = Field(frozen=True)
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.restore¶
restore()
Restore a soft-deleted entity.
Clears the deleted_at timestamp, making the entity active again.
Example
> > > account.soft_delete() > > > account.restore() > > > assert account.is_deleted is False# leadr.boards.domain.board_ratio_config.BoardRatioConfig.scale¶
scale: int = 1000000
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.soft_delete¶
soft_delete()
Mark entity as soft-deleted.
Sets the deleted_at timestamp to the current UTC time. Entities that are already deleted are not affected (deleted_at remains at original deletion time).
Example
> > > account = Account(name="Test", slug="test") > > > account.soft_delete() > > > assert account.is_deleted is True# leadr.boards.domain.board_ratio_config.BoardRatioConfig.tie_breaker¶
tie_breaker: TieBreaker = TieBreaker.NUMERATOR_DESC_DENOMINATOR_ASC
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.updated_at¶
updated_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp of last update (UTC)')
# leadr.boards.domain.board_ratio_config.BoardRatioConfig.zero_denominator_policy¶
zero_denominator_policy: ZeroDenominatorPolicy = ZeroDenominatorPolicy.NULL
leadr.boards.domain.board_ratio_config.RatioDisplay¶
Display format for ratio values.
- RAW: Display the ratio value as-is (e.g., 0.75)
- PERCENT: Display as percentage (e.g., 75%)
Attributes:
# leadr.boards.domain.board_ratio_config.RatioDisplay.PERCENT¶
PERCENT = 'PERCENT'
# leadr.boards.domain.board_ratio_config.RatioDisplay.RAW¶
RAW = 'RAW'
leadr.boards.domain.board_ratio_config.TieBreaker¶
Tie-breaking strategy for equal ratios.
NUMERATOR_DESC_DENOMINATOR_ASC: Higher numerator wins, then lower denominator. This favors players who achieved more (higher numerator) with less attempts (lower denominator).
Attributes:
# leadr.boards.domain.board_ratio_config.TieBreaker.NUMERATOR_DESC_DENOMINATOR_ASC¶
NUMERATOR_DESC_DENOMINATOR_ASC = 'NUMERATOR_DESC_DENOMINATOR_ASC'
leadr.boards.domain.board_ratio_config.ZeroDenominatorPolicy¶
Policy for handling zero denominators in ratio calculations.
Determines what value to use when the denominator is zero:
- NULL: Return null/not rankable
- ZERO: Return zero
- INFINITY: Return infinity (highest rank)
Attributes:
# leadr.boards.domain.board_ratio_config.ZeroDenominatorPolicy.INFINITY¶
INFINITY = 'INFINITY'
# leadr.boards.domain.board_ratio_config.ZeroDenominatorPolicy.NULL¶
NULL = 'NULL'
# leadr.boards.domain.board_ratio_config.ZeroDenominatorPolicy.ZERO¶
ZERO = 'ZERO'
leadr.boards.domain.board_state¶
BoardState domain model for materialized ranking state.
Classes:
- BoardState – Materialized ranking state for a single identity on a single board.
leadr.boards.domain.board_state.BoardState¶
Bases: Entity
Materialized ranking state for a single identity on a single board.
BoardState represents the current ranking state of an identity on a board. It is computed from score events and used for leaderboard queries.
For RUN_IDENTITY boards: Contains the selected score based on keep_strategy. For RUN_RUNS boards: Not used (run_entries table is used instead). For COUNTER boards: Contains the accumulated total. For RATIO boards: Contains the computed ratio value.
The aux field contains board-type-specific auxiliary data:
- RUN_IDENTITY: {"selected_event_id": str, "event_count": int}
- COUNTER: {"event_count": int, "last_event_id": str}
- RATIO: {"numerator_value": float, "denominator_value": float}
Denormalized fields (from Identity and ScoreEvent) are stored for query efficiency:
- player_name: Display name at submission time
- is_test: Test mode flag
- timezone, country, city: Geo data from GeoIP
- value_display: Formatted display string
- metadata: Game-specific JSON
Attributes:
- id (
BoardStateID) – Unique identifier for this board state. - board_id (
BoardID) – The board this state belongs to (immutable). - identity_id (
IdentityID) – The identity this state is for (immutable). - primary_value (
float | None) – The rankable value (NULL = not rankable). - aux (
dict[str, Any] | None) – Board-type-specific auxiliary data. - player_name (
str) – Display name at submission time. - is_test (
bool) – Whether this is a test submission. - timezone (
str | None) – Timezone from GeoIP (optional). - country (
str | None) – Country code from GeoIP (optional). - city (
str | None) – City name from GeoIP (optional). - value_display (
str | None) – Formatted display string (optional). - metadata (
Any | None) – Game-specific JSON metadata (optional). - created_at (
datetime) – Timestamp when the state was created (UTC). - updated_at (
datetime) – Timestamp when the state was last updated (UTC). - deleted_at (
datetime | None) – Timestamp when the state was soft-deleted, or None.
Functions:
- restore – Restore a soft-deleted entity.
- soft_delete – Mark entity as soft-deleted.
# leadr.boards.domain.board_state.BoardState.aux¶
aux: dict[str, Any] | None = Field(default=None, description='Board-type-specific auxiliary data')
# leadr.boards.domain.board_state.BoardState.board_id¶
board_id: BoardID = Field(frozen=True, description='Board this state belongs to (immutable)')
# leadr.boards.domain.board_state.BoardState.city¶
city: str | None = Field(default=None, description='City name from GeoIP (from ScoreEvent)')
# leadr.boards.domain.board_state.BoardState.country¶
country: str | None = Field(default=None, description='Country code from GeoIP (from ScoreEvent)')
# leadr.boards.domain.board_state.BoardState.created_at¶
created_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp when entity was created (UTC)')
# leadr.boards.domain.board_state.BoardState.deleted_at¶
deleted_at: datetime | None = Field(default=None, description='Timestamp when entity was soft-deleted (UTC), or null if active')
# leadr.boards.domain.board_state.BoardState.id¶
id: BoardStateID = Field(frozen=True, default_factory=BoardStateID, description='Unique identifier for this board state')
# leadr.boards.domain.board_state.BoardState.identity_id¶
identity_id: IdentityID = Field(frozen=True, description='Identity this state is for (immutable)')
# leadr.boards.domain.board_state.BoardState.is_deleted¶
is_deleted: bool
Check if entity is soft-deleted.
Returns:
bool– True if the entity has a deleted_at timestamp, False otherwise.
# leadr.boards.domain.board_state.BoardState.is_placeholder¶
is_placeholder: bool = Field(default=False, description='True if this is a synthetic placeholder for around_value queries')
# leadr.boards.domain.board_state.BoardState.is_test¶
is_test: bool = Field(default=False, description='Whether this is a test submission (from ScoreEvent)')
# leadr.boards.domain.board_state.BoardState.metadata¶
metadata: Any | None = Field(default=None, description='Game-specific JSON metadata')
# leadr.boards.domain.board_state.BoardState.model_config¶
model_config = ConfigDict(validate_assignment=True)
# leadr.boards.domain.board_state.BoardState.player_name¶
player_name: str = Field(default='', description='Display name at submission time (from Identity)')
# leadr.boards.domain.board_state.BoardState.primary_value¶
primary_value: float | None = Field(default=None, description='Rankable value (NULL = not rankable)')
# leadr.boards.domain.board_state.BoardState.rank¶
rank: int = Field(default=0, description='Computed rank (transient, not persisted)')
# leadr.boards.domain.board_state.BoardState.restore¶
restore()
Restore a soft-deleted entity.
Clears the deleted_at timestamp, making the entity active again.
Example
> > > account.soft_delete() > > > account.restore() > > > assert account.is_deleted is False# leadr.boards.domain.board_state.BoardState.soft_delete¶
soft_delete()
Mark entity as soft-deleted.
Sets the deleted_at timestamp to the current UTC time. Entities that are already deleted are not affected (deleted_at remains at original deletion time).
Example
> > > account = Account(name="Test", slug="test") > > > account.soft_delete() > > > assert account.is_deleted is True# leadr.boards.domain.board_state.BoardState.timezone¶
timezone: str | None = Field(default=None, description='Timezone from GeoIP (from ScoreEvent)')
# leadr.boards.domain.board_state.BoardState.updated_at¶
updated_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp of last update (UTC)')
# leadr.boards.domain.board_state.BoardState.value_display¶
value_display: str | None = Field(default=None, description='Formatted display string')
leadr.boards.domain.board_template¶
BoardTemplate domain model.
Classes:
- BoardTemplate – BoardTemplate domain entity.
leadr.boards.domain.board_template.BoardTemplate¶
Bases: Entity
BoardTemplate domain entity.
Represents a template for automatically generating boards at regular intervals. Templates belong to a game and define the configuration for boards that will be created by the pg_cron scheduler.
Each template specifies a repeat interval (PostgreSQL interval syntax), configuration for boards to be created, and can optionally use template variables in the name generation. Templates can be activated/deactivated and track the next scheduled run.
Functions:
- generate_name – Generate a board name using the name template.
- restore – Restore a soft-deleted entity.
- soft_delete – Mark entity as soft-deleted.
- validate_name – Validate template name is not empty.
- validate_repeat_interval – Validate repeat_interval uses PostgreSQL interval syntax.
- validate_slug – Validate slug format (lowercase alphanumeric with hyphens).
Attributes:
- account_id (
AccountID) – - board_type (
BoardType) – - config (
dict[str, Any]) – - created_at (
datetime) – - deleted_at (
datetime | None) – - ends_at (
datetime | None) – - game_id (
GameID) – - icon (
str | None) – - id (
BoardTemplateID) – - is_active (
bool) – - is_deleted (
bool) – Check if entity is soft-deleted. - is_published (
bool) – - keep_strategy (
KeepStrategy) – - model_config –
- name (
str) – - name_template (
str | None) – - next_run_at (
datetime) – - repeat_interval (
str) – - series (
str | None) – - slug (
str | None) – - sort_direction (
SortDirection) – - starts_at (
datetime | None) – - tags (
list[str]) – - unit (
str | None) – - updated_at (
datetime) –
# leadr.boards.domain.board_template.BoardTemplate.account_id¶
account_id: AccountID = Field(frozen=True, description='ID of the account this template belongs to (immutable)')
# leadr.boards.domain.board_template.BoardTemplate.board_type¶
board_type: BoardType = Field(description='Type of board to create from this template', default=(BoardType.RUN_IDENTITY))
# leadr.boards.domain.board_template.BoardTemplate.config¶
config: dict[str, Any] = Field(default_factory=dict, description='Reserved for future procedural generation (bounds, variables, randomization rules)')
# leadr.boards.domain.board_template.BoardTemplate.created_at¶
created_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp when entity was created (UTC)')
# leadr.boards.domain.board_template.BoardTemplate.deleted_at¶
deleted_at: datetime | None = Field(default=None, description='Timestamp when entity was soft-deleted (UTC), or null if active')
# leadr.boards.domain.board_template.BoardTemplate.ends_at¶
ends_at: datetime | None = Field(default=None, description='Optional end time for time-bounded boards')
# leadr.boards.domain.board_template.BoardTemplate.game_id¶
game_id: GameID = Field(frozen=True, description='ID of the game this template belongs to (immutable)')
# leadr.boards.domain.board_template.BoardTemplate.generate_name¶
generate_name(timestamp, series_value)
Generate a board name using the name template.
If name_template is None, returns the template's name. Otherwise, substitutes placeholders with values derived from the timestamp and series.
Supported placeholders:
- {year}: 4-digit year (e.g., 2025)
- {month}: Full month name (e.g., July)
- {month_short}: Abbreviated month (e.g., Jul)
- {week}: ISO week number (e.g., 29)
- {quarter}: Quarter (e.g., Q1, Q2, Q3, Q4)
- {date}: ISO date (e.g., 2025-07-15)
- {series}: Sequential series value
Parameters:
- timestamp (
datetime) – The datetime to use for generating time-based placeholders. - series_value (
int | None) – Optional series value for {series} placeholder.
Returns:
str– The generated board name.
Raises:
ValueError– If the name_template contains invalid placeholders or if {series} is used but series_value is None.
# leadr.boards.domain.board_template.BoardTemplate.icon¶
icon: str | None = Field(description='Icon identifier for boards created from this template', default='fa-crown')
# leadr.boards.domain.board_template.BoardTemplate.id¶
id: BoardTemplateID = Field(frozen=True, default_factory=BoardTemplateID, description='Unique board template identifier')
# leadr.boards.domain.board_template.BoardTemplate.is_active¶
is_active: bool = Field(description='Whether the template is currently active')
# leadr.boards.domain.board_template.BoardTemplate.is_deleted¶
is_deleted: bool
Check if entity is soft-deleted.
Returns:
bool– True if the entity has a deleted_at timestamp, False otherwise.
# leadr.boards.domain.board_template.BoardTemplate.is_published¶
is_published: bool = Field(description='Whether boards created from this template should be published', default=True)
# leadr.boards.domain.board_template.BoardTemplate.keep_strategy¶
keep_strategy: KeepStrategy = Field(description='Strategy for keeping multiple scores from the same user (RUN_IDENTITY only)', default=(KeepStrategy.BEST))
# leadr.boards.domain.board_template.BoardTemplate.model_config¶
model_config = ConfigDict(validate_assignment=True)
# leadr.boards.domain.board_template.BoardTemplate.name¶
name: str = Field(description='Name of the template')
# leadr.boards.domain.board_template.BoardTemplate.name_template¶
name_template: str | None = Field(default=None, description='Optional template string for generating board names')
# leadr.boards.domain.board_template.BoardTemplate.next_run_at¶
next_run_at: datetime = Field(description='Next scheduled time to create a board from this template')
# leadr.boards.domain.board_template.BoardTemplate.repeat_interval¶
repeat_interval: str = Field(description="PostgreSQL interval syntax for repeat frequency (e.g., '7 days', '1 month')")
# leadr.boards.domain.board_template.BoardTemplate.restore¶
restore()
Restore a soft-deleted entity.
Clears the deleted_at timestamp, making the entity active again.
Example
> > > account.soft_delete() > > > account.restore() > > > assert account.is_deleted is False# leadr.boards.domain.board_template.BoardTemplate.series¶
series: str | None = Field(default=None, description="Optional series identifier for sequential board naming (e.g., 'weekly', 'seasonal')")
# leadr.boards.domain.board_template.BoardTemplate.slug¶
slug: str | None = Field(default=None, description='URL-friendly slug for boards created from this template')
# leadr.boards.domain.board_template.BoardTemplate.soft_delete¶
soft_delete()
Mark entity as soft-deleted.
Sets the deleted_at timestamp to the current UTC time. Entities that are already deleted are not affected (deleted_at remains at original deletion time).
Example
> > > account = Account(name="Test", slug="test") > > > account.soft_delete() > > > assert account.is_deleted is True# leadr.boards.domain.board_template.BoardTemplate.sort_direction¶
sort_direction: SortDirection = Field(description='Direction to sort scores (ascending/descending)', default=(SortDirection.DESCENDING))
# leadr.boards.domain.board_template.BoardTemplate.starts_at¶
starts_at: datetime | None = Field(default=None, description='Optional start time for time-bounded boards')
# leadr.boards.domain.board_template.BoardTemplate.tags¶
tags: list[str] = Field(default_factory=list, description='List of tags for categorizing boards created from this template')
# leadr.boards.domain.board_template.BoardTemplate.unit¶
unit: str | None = Field(description="Unit of measurement for scores (e.g., 'seconds', 'points')", default=None)
# leadr.boards.domain.board_template.BoardTemplate.updated_at¶
updated_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp of last update (UTC)')
# leadr.boards.domain.board_template.BoardTemplate.validate_name¶
validate_name(value)
Validate template name is not empty.
Parameters:
- value (
str) – The template name to validate.
Returns:
str– The validated and trimmed template name.
Raises:
ValueError– If template name is empty or whitespace only.
# leadr.boards.domain.board_template.BoardTemplate.validate_repeat_interval¶
validate_repeat_interval(value)
Validate repeat_interval uses PostgreSQL interval syntax.
Parameters:
- value (
str) – The interval string to validate.
Returns:
str– The validated interval string.
Raises:
ValueError– If interval syntax is invalid.
# leadr.boards.domain.board_template.BoardTemplate.validate_slug¶
validate_slug(value)
Validate slug format (lowercase alphanumeric with hyphens).
Parameters:
- value (
str | None) – The slug to validate, or None.
Returns:
str | None– The validated slug, or None if not provided.
Raises:
ValueError– If slug is invalid.
leadr.boards.domain.interval_parser¶
Utilities for parsing PostgreSQL interval syntax.
Functions:
- parse_interval – Parse PostgreSQL interval syntax to Python relativedelta.
leadr.boards.domain.interval_parser.parse_interval¶
parse_interval(interval_string)
Parse PostgreSQL interval syntax to Python relativedelta.
Supports formats like:
- "7 days"
- "1 week"
- "1 month"
- "1 year"
- "2 hours"
Parameters:
- interval_string (
str) – PostgreSQL interval syntax string.
Returns:
relativedelta– Equivalent Python relativedelta.
Raises:
ValueError– If interval format is invalid or unsupported.
Example
> > > parse_interval("7 days") > > > relativedelta(days=7) > > > parse_interval("1 month") > > > relativedelta(months=1)leadr.boards.domain.run_entry¶
RunEntry domain model for RUN_RUNS boards.
Classes:
- RunEntry – A single scored run entry for RUN_RUNS boards.
leadr.boards.domain.run_entry.RunEntry¶
Bases: Entity
A single scored run entry for RUN_RUNS boards.
RunEntry represents an individual submission on a RUN_RUNS board where every submission is ranked (as opposed to RUN_IDENTITY boards where only one entry per identity is kept based on keep_strategy).
Each run entry is linked to a score event and is immutable except for soft-delete. The primary_value is the rankable value for leaderboard queries.
Denormalized fields (from Identity and ScoreEvent) are stored for query efficiency:
- player_name: Display name at submission time
- is_test: Test mode flag
- timezone, country, city: Geo data from GeoIP
- value_display: Formatted display string
- metadata: Game-specific JSON
Attributes:
- id (
RunEntryID) – Unique identifier for this run entry. - board_id (
BoardID) – The board this entry belongs to (immutable). - identity_id (
IdentityID) – The identity that submitted this entry (immutable). - score_event_id (
ScoreEventID) – The score event that created this entry (immutable). - primary_value (
float) – The rankable value for this submission (immutable). - player_name (
str) – Display name at submission time. - is_test (
bool) – Whether this is a test submission. - timezone (
str | None) – Timezone from GeoIP (optional). - country (
str | None) – Country code from GeoIP (optional). - city (
str | None) – City name from GeoIP (optional). - value_display (
str | None) – Formatted display string (optional). - metadata (
Any | None) – Game-specific JSON metadata (optional). - created_at (
datetime) – Timestamp when the entry was created (UTC). - updated_at (
datetime) – Timestamp when the entry was last updated (UTC). - deleted_at (
datetime | None) – Timestamp when the entry was soft-deleted, or None.
Functions:
- restore – Restore a soft-deleted entity.
- soft_delete – Mark entity as soft-deleted.
# leadr.boards.domain.run_entry.RunEntry.board_id¶
board_id: BoardID = Field(frozen=True, description='Board this entry belongs to (immutable)')
# leadr.boards.domain.run_entry.RunEntry.city¶
city: str | None = Field(default=None, description='City name from GeoIP (from ScoreEvent)')
# leadr.boards.domain.run_entry.RunEntry.country¶
country: str | None = Field(default=None, description='Country code from GeoIP (from ScoreEvent)')
# leadr.boards.domain.run_entry.RunEntry.created_at¶
created_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp when entity was created (UTC)')
# leadr.boards.domain.run_entry.RunEntry.deleted_at¶
deleted_at: datetime | None = Field(default=None, description='Timestamp when entity was soft-deleted (UTC), or null if active')
# leadr.boards.domain.run_entry.RunEntry.excluded_at¶
excluded_at: datetime | None = Field(default=None, description='When this entry was excluded from ranking (e.g., confirmed cheat)')
# leadr.boards.domain.run_entry.RunEntry.excluded_reason¶
excluded_reason: str | None = Field(default=None, description="Reason for exclusion (e.g., 'confirmed_cheat')")
# leadr.boards.domain.run_entry.RunEntry.id¶
id: RunEntryID = Field(frozen=True, default_factory=RunEntryID, description='Unique identifier for this run entry')
# leadr.boards.domain.run_entry.RunEntry.identity_id¶
identity_id: IdentityID = Field(frozen=True, description='Identity that submitted this entry (immutable)')
# leadr.boards.domain.run_entry.RunEntry.is_deleted¶
is_deleted: bool
Check if entity is soft-deleted.
Returns:
bool– True if the entity has a deleted_at timestamp, False otherwise.
# leadr.boards.domain.run_entry.RunEntry.is_placeholder¶
is_placeholder: bool = Field(default=False, description='True if this is a synthetic placeholder for around_value queries')
# leadr.boards.domain.run_entry.RunEntry.is_test¶
is_test: bool = Field(default=False, description='Whether this is a test submission (from ScoreEvent)')
# leadr.boards.domain.run_entry.RunEntry.metadata¶
metadata: Any | None = Field(default=None, description='Game-specific JSON metadata')
# leadr.boards.domain.run_entry.RunEntry.model_config¶
model_config = ConfigDict(validate_assignment=True)
# leadr.boards.domain.run_entry.RunEntry.player_name¶
player_name: str = Field(default='', description='Display name at submission time (from Identity)')
# leadr.boards.domain.run_entry.RunEntry.primary_value¶
primary_value: float = Field(frozen=True, description='Rankable value for this submission (immutable)')
# leadr.boards.domain.run_entry.RunEntry.rank¶
rank: int = Field(default=0, description='Computed rank (transient, not persisted)')
# leadr.boards.domain.run_entry.RunEntry.restore¶
restore()
Restore a soft-deleted entity.
Clears the deleted_at timestamp, making the entity active again.
Example
> > > account.soft_delete() > > > account.restore() > > > assert account.is_deleted is False# leadr.boards.domain.run_entry.RunEntry.score_event_id¶
score_event_id: ScoreEventID = Field(frozen=True, description='Score event that created this entry (immutable)')
# leadr.boards.domain.run_entry.RunEntry.soft_delete¶
soft_delete()
Mark entity as soft-deleted.
Sets the deleted_at timestamp to the current UTC time. Entities that are already deleted are not affected (deleted_at remains at original deletion time).
Example
> > > account = Account(name="Test", slug="test") > > > account.soft_delete() > > > assert account.is_deleted is True# leadr.boards.domain.run_entry.RunEntry.timezone¶
timezone: str | None = Field(default=None, description='Timezone from GeoIP (from ScoreEvent)')
# leadr.boards.domain.run_entry.RunEntry.updated_at¶
updated_at: datetime = Field(default_factory=(lambda: datetime.now(UTC)), description='Timestamp of last update (UTC)')
# leadr.boards.domain.run_entry.RunEntry.value_display¶
value_display: str | None = Field(default=None, description='Formatted display string')
leadr.boards.services¶
Modules:
- board_ratio_config_service – Board ratio config service for managing ratio board configurations.
- board_service – Board service for managing board operations.
- board_state_service – Board state service for managing materialized ranking state.
- board_tasks – Background tasks for board processing.
- board_template_service – BoardTemplate service for managing board template operations.
- dependencies – Board service dependency injection.
- repositories – Board repository services.
- run_entry_service – Run entry service for managing run entries.
- short_code_generator – Utility for generating unique short codes for boards.
leadr.boards.services.board_ratio_config_service¶
Board ratio config service for managing ratio board configurations.
Classes:
- BoardRatioConfigService – Service for managing board ratio configurations.
leadr.boards.services.board_ratio_config_service.BoardRatioConfigService¶
Bases: BaseService[BoardRatioConfig, BoardRatioConfigRepository]
Service for managing board ratio configurations.
Functions:
- create_ratio_config – Create a new ratio config for a board.
- delete – Soft-delete an entity.
- get_by_board_id – Get the ratio config for a specific board.
- get_by_id – Get an entity by its ID.
- get_by_id_or_raise – Get an entity by its ID or raise EntityNotFoundError.
- get_ratio_config – Get a ratio config by ID.
- list_all – List all non-deleted entities.
- soft_delete – Soft-delete an entity and return it before deletion.
- update_ratio_config – Update a ratio config.
Attributes:
- repository –
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.create_ratio_config¶
create_ratio_config(board_id, numerator_board_id, denominator_board_id, zero_denominator_policy=ZeroDenominatorPolicy.NULL, min_denominator=0, min_numerator=0, scale=1000000, display=RatioDisplay.RAW, decimals=2, tie_breaker=TieBreaker.NUMERATOR_DESC_DENOMINATOR_ASC)
Create a new ratio config for a board.
Parameters:
- board_id (
BoardID) – ID of the ratio board. - numerator_board_id (
BoardID) – ID of the numerator board. - denominator_board_id (
BoardID) – ID of the denominator board. - zero_denominator_policy (
ZeroDenominatorPolicy) – How to handle zero denominators. - min_denominator (
float) – Minimum denominator for ranking eligibility. - min_numerator (
float) – Minimum numerator for ranking eligibility. - scale (
int) – Scaling factor for ratio storage. - display (
RatioDisplay) – Display format for ratio values. - decimals (
int) – Number of decimal places for display. - tie_breaker (
TieBreaker) – Strategy for breaking ties.
Returns:
BoardRatioConfig– Created BoardRatioConfig entity.
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.delete¶
delete(entity_id)
Soft-delete an entity.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.get_by_board_id¶
get_by_board_id(board_id)
Get the ratio config for a specific board.
Parameters:
- board_id (
BoardID) – The ratio board ID.
Returns:
BoardRatioConfig | None– BoardRatioConfig if found, None otherwise.
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.get_by_id¶
get_by_id(entity_id)
Get an entity by its ID.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT | None– The domain entity if found, None otherwise
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.get_by_id_or_raise¶
get_by_id_or_raise(entity_id)
Get an entity by its ID or raise EntityNotFoundError.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT– The domain entity
Raises:
EntityNotFoundError– If the entity is not found (converted to HTTP 404 by global handler)
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.get_ratio_config¶
get_ratio_config(config_id)
Get a ratio config by ID.
Parameters:
- config_id (
BoardRatioConfigID) – The ratio config ID.
Returns:
BoardRatioConfig | None– BoardRatioConfig if found, None otherwise.
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.list_all¶
list_all()
List all non-deleted entities.
Returns:
list[DomainEntityT]– List of domain entities
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.repository¶
repository = repository if repository is not None else self._create_repository(session)
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.soft_delete¶
soft_delete(entity_id)
Soft-delete an entity and return it before deletion.
Useful for endpoints that need to return the deleted entity in the response.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Returns:
DomainEntityT– The entity before it was deleted
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_ratio_config_service.BoardRatioConfigService.update_ratio_config¶
update_ratio_config(config_id, zero_denominator_policy=None, min_denominator=None, min_numerator=None, scale=None, display=None, decimals=None, tie_breaker=None)
Update a ratio config.
Parameters:
- config_id (
BoardRatioConfigID) – The ratio config ID. - zero_denominator_policy (
ZeroDenominatorPolicy | None) – New zero denominator policy. - min_denominator (
float | None) – New minimum denominator. - min_numerator (
float | None) – New minimum numerator. - scale (
int | None) – New scale. - display (
RatioDisplay | None) – New display format. - decimals (
int | None) – New decimal places. - tie_breaker (
TieBreaker | None) – New tie breaker strategy.
Returns:
BoardRatioConfig– Updated BoardRatioConfig entity.
Raises:
EntityNotFoundError– If config not found.
leadr.boards.services.board_service¶
Board service for managing board operations.
Classes:
- BoardService – Service for managing board lifecycle and operations.
Attributes:
- logger –
leadr.boards.services.board_service.BoardService¶
Bases: BaseService[Board, BoardRepository]
Service for managing board lifecycle and operations.
This service orchestrates board creation, updates, and retrieval by coordinating between the domain models and repository layer. Ensures business rules like game validation are enforced.
Functions:
- create_board – Create a new board.
- create_board_from_template – Create a new board from a board template.
- delete – Soft-delete an entity.
- get_board – Get a board by its ID.
- get_board_by_short_code – Get a board by its short_code.
- get_by_id – Get an entity by its ID.
- get_by_id_or_raise – Get an entity by its ID or raise EntityNotFoundError.
- list_all – List all non-deleted entities.
- list_boards – List boards with optional filtering and pagination.
- list_boards_by_account – List all boards for an account.
- soft_delete – Soft-delete an entity and return it before deletion.
- update_board – Update board fields.
Attributes:
- repository –
# leadr.boards.services.board_service.BoardService.create_board¶
create_board(account_id, game_id, name, icon='fa-crown', unit=None, is_active=True, is_published=True, sort_direction=SortDirection.DESCENDING, board_type=BoardType.RUN_IDENTITY, keep_strategy=KeepStrategy.BEST, slug=None, short_code=None, created_from_template_id=None, template_name=None, starts_at=None, ends_at=None, tags=None, description=None)
Create a new board.
Parameters:
- account_id (
AccountID) – The ID of the account that owns this board. - game_id (
GameID) – The ID of the game this board belongs to. - name (
str) – The board name. - icon (
str | None) – Icon identifier for the board. Defaults to "fa-crown". - unit (
str | None) – Unit of measurement for scores. Defaults to None. - is_active (
bool) – Whether the board is currently active. Defaults to True. - is_published (
bool) – Whether the board is published and visible on public web views. Defaults to True. - sort_direction (
SortDirection) – Direction to sort scores. Defaults to DESCENDING. - keep_strategy (
KeepStrategy) – Strategy for keeping multiple scores from same user. Defaults to ALL. - slug (
str | None) – Optional URL-friendly slug. If not provided, auto-generated from name. - short_code (
str | None) – Globally unique short code for direct sharing. - created_from_template_id (
BoardTemplateID | None) – Optional template ID this board was created from. - template_name (
str | None) – Optional template name. - starts_at (
datetime | None) – Optional start time for time-bounded boards. - ends_at (
datetime | None) – Optional end time for time-bounded boards. - tags (
list[str] | None) – Optional list of tags for categorization. - description (
str | None) – Optional short description of the board.
Returns:
Board– The created Board domain entity.
Raises:
EntityNotFoundError– If the game doesn't exist.ValueError– If the game doesn't belong to the specified account or slug is invalid.
Example
> > > board = await service.create_board( > > > ... account_id=account.id, > > > ... game_id=game.id, > > > ... name="Speed Run Board", > > > ... icon="trophy", > > > ... unit="seconds", > > > ... is_active=True, > > > ... sort_direction=SortDirection.ASCENDING, > > > ... keep_strategy=KeepStrategy.BEST, > > > ... )# leadr.boards.services.board_service.BoardService.create_board_from_template¶
create_board_from_template(template)
Create a new board from a board template.
Extracts configuration from the template and calculates time boundaries based on the template's repeat_interval. Automatically generates a unique short code for the board. If the template has a series field, generates a sequential series value and uses it in the board name.
Parameters:
- template (
BoardTemplate) – The BoardTemplate to create a board from.
Returns:
Board– The created Board domain entity.
Raises:
ValueError– If interval parsing fails, game doesn't belong to account, or name generation fails.
Example
> > > board = await service.create_board_from_template(template)# leadr.boards.services.board_service.BoardService.delete¶
delete(entity_id)
Soft-delete an entity.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_service.BoardService.get_board¶
get_board(board_id)
Get a board by its ID.
Parameters:
- board_id (
BoardID) – The ID of the board to retrieve.
Returns:
Board | None– The Board domain entity if found, None otherwise.
# leadr.boards.services.board_service.BoardService.get_board_by_short_code¶
get_board_by_short_code(short_code)
Get a board by its short_code.
Parameters:
- short_code (
str) – The short_code to search for.
Returns:
Board | None– The Board domain entity if found, None otherwise.
# leadr.boards.services.board_service.BoardService.get_by_id¶
get_by_id(entity_id)
Get an entity by its ID.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT | None– The domain entity if found, None otherwise
# leadr.boards.services.board_service.BoardService.get_by_id_or_raise¶
get_by_id_or_raise(entity_id)
Get an entity by its ID or raise EntityNotFoundError.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT– The domain entity
Raises:
EntityNotFoundError– If the entity is not found (converted to HTTP 404 by global handler)
# leadr.boards.services.board_service.BoardService.list_all¶
list_all()
List all non-deleted entities.
Returns:
list[DomainEntityT]– List of domain entities
# leadr.boards.services.board_service.BoardService.list_boards¶
list_boards(account_id=None, game_id=None, code=None, slug=None, is_active=None, is_published=None, starts_before=None, starts_after=None, ends_before=None, ends_after=None, *, pagination)
List boards with optional filtering and pagination.
Parameters:
- account_id (
AccountID | None) – Optional account ID to filter by - game_id (
GameID | None) – Optional game ID to filter by - code (
str | None) – Optional short code to filter by - slug (
str | None) – Optional slug to filter by - is_active (
bool | None) – Optional filter for active status - is_published (
bool | None) – Optional filter for published status - starts_before (
datetime | None) – Optional filter for boards starting before this time - starts_after (
datetime | None) – Optional filter for boards starting after this time - ends_before (
datetime | None) – Optional filter for boards ending before this time - ends_after (
datetime | None) – Optional filter for boards ending after this time - pagination (
PaginationParams) – Pagination parameters (required)
Returns:
PaginatedResult[Board]– PaginatedResult containing Board entities matching the filter criteria.
# leadr.boards.services.board_service.BoardService.list_boards_by_account¶
list_boards_by_account(account_id)
List all boards for an account.
Parameters:
- account_id (
AccountID) – The ID of the account to list boards for.
Returns:
# leadr.boards.services.board_service.BoardService.repository¶
repository = repository if repository is not None else self._create_repository(session)
# leadr.boards.services.board_service.BoardService.soft_delete¶
soft_delete(entity_id)
Soft-delete an entity and return it before deletion.
Useful for endpoints that need to return the deleted entity in the response.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Returns:
DomainEntityT– The entity before it was deleted
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_service.BoardService.update_board¶
update_board(board_id, **updates)
Update board fields.
Accepts any fields to update as keyword arguments. Only fields explicitly provided will be updated, allowing null values to clear optional fields.
Parameters:
- board_id (
BoardID) – The ID of the board to update - **updates (
Any) – Field names and values to update
Returns:
Board– The updated Board domain entity
Raises:
EntityNotFoundError– If the board doesn't exist
leadr.boards.services.board_service.logger¶
logger = get_logger(__name__)
leadr.boards.services.board_state_service¶
Board state service for managing materialized ranking state.
Classes:
- BoardStateService – Service for managing board states.
leadr.boards.services.board_state_service.BoardStateService¶
BoardStateService(session)
Service for managing board states.
Board states represent the materialized ranking state for identities on boards. Each identity has at most one state per board. States are updated when new score events are processed.
Functions:
- create_board_state – Create a new board state.
- find_dependent_ratio_boards – Find RATIO boards where this board is numerator or denominator.
- get_board_state – Get a board state by ID.
- get_by_board_and_identity – Get a board state by board and identity.
- get_by_id_or_raise – Get a board state by ID, raising if not found.
- list_board_states – List board states with optional filters.
- recompute_ratio_for_identity – Recalculate ratio value and upsert board state.
- soft_delete – Soft delete a board state.
- upsert_board_state – Create or update a board state.
Attributes:
- repository –
- session –
Parameters:
- session (
AsyncSession) – SQLAlchemy async session
# leadr.boards.services.board_state_service.BoardStateService.create_board_state¶
create_board_state(board_id, identity_id, primary_value=None, aux=None, *, player_name='', is_test=False, timezone=None, country=None, city=None, value_display=None, metadata=None)
Create a new board state.
Parameters:
- board_id (
BoardID) – Board this state belongs to - identity_id (
IdentityID) – Identity this state is for - primary_value (
float | None) – Rankable value (None = not rankable) - aux (
dict[str, Any] | None) – Board-type-specific auxiliary data - player_name (
str) – Display name at submission time - is_test (
bool) – Whether this is a test submission - timezone (
str | None) – Timezone from GeoIP - country (
str | None) – Country code from GeoIP - city (
str | None) – City name from GeoIP - value_display (
str | None) – Formatted display string - metadata (
Any | None) – Game-specific JSON metadata
Returns:
BoardState– Created BoardState entity
# leadr.boards.services.board_state_service.BoardStateService.find_dependent_ratio_boards¶
find_dependent_ratio_boards(board_id)
Find RATIO boards where this board is numerator or denominator.
Parameters:
- board_id (
BoardID) – The board ID to check for dependencies.
Returns:
list[BoardRatioConfig]– List of BoardRatioConfig entities that depend on this board.
# leadr.boards.services.board_state_service.BoardStateService.get_board_state¶
get_board_state(state_id)
Get a board state by ID.
Parameters:
- state_id (
BoardStateID) – Board state ID
Returns:
BoardState | None– BoardState if found, None otherwise
# leadr.boards.services.board_state_service.BoardStateService.get_by_board_and_identity¶
get_by_board_and_identity(board_id, identity_id)
Get a board state by board and identity.
Parameters:
- board_id (
BoardID) – Board ID - identity_id (
IdentityID) – Identity ID
Returns:
BoardState | None– BoardState if found, None otherwise
# leadr.boards.services.board_state_service.BoardStateService.get_by_id_or_raise¶
get_by_id_or_raise(state_id)
Get a board state by ID, raising if not found.
Parameters:
- state_id (
BoardStateID) – Board state ID
Returns:
BoardState– BoardState entity
Raises:
EntityNotFoundError– If state not found
# leadr.boards.services.board_state_service.BoardStateService.list_board_states¶
list_board_states(board_id=None, identity_id=None, is_test=None, pagination=None, around_state=None, around_value=None)
List board states with optional filters.
Parameters:
- board_id (
BoardID | None) – Optional filter by board - identity_id (
IdentityID | None) – Optional filter by identity - is_test (
bool | None) – Optional filter for test entries (True=test only, False=prod only, None=all) - pagination (
PaginationParams | None) – Optional pagination parameters - around_state (
BoardState | None) – Optional target state to center results around - around_value (
float | None) – Optional value to center results around (creates placeholder)
Returns:
PaginatedResult[BoardState]– Paginated list of board states
# leadr.boards.services.board_state_service.BoardStateService.recompute_ratio_for_identity¶
recompute_ratio_for_identity(ratio_config, identity_id)
Recalculate ratio value and upsert board state.
Fetches the numerator and denominator values from the source boards, calculates the ratio, and creates/updates the ratio board state.
Parameters:
- ratio_config (
BoardRatioConfig) – The ratio configuration specifying source boards. - identity_id (
IdentityID) – The identity to recompute the ratio for.
Returns:
BoardState | None– The created/updated BoardState, or None if source data is missing.
# leadr.boards.services.board_state_service.BoardStateService.repository¶
repository = BoardStateRepository(session)
# leadr.boards.services.board_state_service.BoardStateService.session¶
session = session
# leadr.boards.services.board_state_service.BoardStateService.soft_delete¶
soft_delete(state_id)
Soft delete a board state.
Parameters:
- state_id (
BoardStateID) – Board state ID
Returns:
BoardState– The soft-deleted BoardState entity
Raises:
EntityNotFoundError– If state not found
# leadr.boards.services.board_state_service.BoardStateService.upsert_board_state¶
upsert_board_state(board_id, identity_id, primary_value=None, aux=None, *, player_name='', is_test=False, timezone=None, country=None, city=None, value_display=None, metadata=None)
Create or update a board state.
If a state already exists for the board/identity combination, it is updated. Otherwise, a new state is created.
Parameters:
- board_id (
BoardID) – Board this state belongs to - identity_id (
IdentityID) – Identity this state is for - primary_value (
float | None) – Rankable value (None = not rankable) - aux (
dict[str, Any] | None) – Board-type-specific auxiliary data - player_name (
str) – Display name at submission time - is_test (
bool) – Whether this is a test submission - timezone (
str | None) – Timezone from GeoIP - country (
str | None) – Country code from GeoIP - city (
str | None) – City name from GeoIP - value_display (
str | None) – Formatted display string - metadata (
Any | None) – Game-specific JSON metadata
Returns:
BoardState– Created or updated BoardState entity
leadr.boards.services.board_tasks¶
Background tasks for board processing.
Contains tasks for:
- Processing due board templates and creating boards
- Expiring boards past their end date
Functions:
- expire_boards – Expire boards that have passed their end date.
- process_due_templates – Process all due board templates and create boards.
Attributes:
- logger –
leadr.boards.services.board_tasks.expire_boards¶
expire_boards()
Expire boards that have passed their end date.
Queries for active boards where ends_at \<= now() and sets is_active=False.
This task is designed to be called periodically (e.g., every minute).
leadr.boards.services.board_tasks.logger¶
logger = logging.getLogger(__name__)
leadr.boards.services.board_tasks.process_due_templates¶
process_due_templates()
Process all due board templates and create boards.
Queries for active templates where next_run_at \<= now(), creates boards from each template, and updates the template's next_run_at.
This task is designed to be called periodically (e.g., every minute).
leadr.boards.services.board_template_service¶
BoardTemplate service for managing board template operations.
Classes:
- BoardTemplateService – Service for managing board template lifecycle and operations.
Attributes:
- logger –
leadr.boards.services.board_template_service.BoardTemplateService¶
Bases: BaseService[BoardTemplate, BoardTemplateRepository]
Service for managing board template lifecycle and operations.
This service orchestrates board template creation, updates, and retrieval by coordinating between the domain models and repository layer. Ensures business rules like game validation are enforced.
Functions:
- advance_template_schedule – Advance a template's next_run_at by its repeat_interval.
- create_board_template – Create a new board template.
- delete – Soft-delete an entity.
- get_board_template – Get a board template by its ID.
- get_by_id – Get an entity by its ID.
- get_by_id_or_raise – Get an entity by its ID or raise EntityNotFoundError.
- list_all – List all non-deleted entities.
- list_board_templates_by_account – List all board templates for an account with pagination.
- list_board_templates_by_game – List all board templates for a specific game with pagination.
- soft_delete – Soft-delete an entity and return it before deletion.
- update_board_template – Update board template fields.
Attributes:
- repository –
# leadr.boards.services.board_template_service.BoardTemplateService.advance_template_schedule¶
advance_template_schedule(template_id)
Advance a template's next_run_at by its repeat_interval.
This is typically called after successfully creating a board from the template.
Parameters:
- template_id (
BoardTemplateID) – The ID of the template to advance.
Returns:
BoardTemplate– The updated BoardTemplate with advanced next_run_at.
Raises:
EntityNotFoundError– If the template doesn't exist.ValueError– If the repeat_interval cannot be parsed.
Example
> > > template = await service.advance_template_schedule(template.id) > > > > > > # template.next_run_at is now advanced by repeat_interval# leadr.boards.services.board_template_service.BoardTemplateService.create_board_template¶
create_board_template(account_id, game_id, name, slug, repeat_interval, next_run_at, is_active, is_published=True, name_template=None, series=None, icon='fa-crown', unit=None, sort_direction=SortDirection.DESCENDING, keep_strategy=KeepStrategy.BEST, starts_at=None, ends_at=None, tags=None, config=None)
Create a new board template.
Parameters:
- account_id (
AccountID) – The ID of the account that owns this template. - game_id (
GameID) – The ID of the game this template belongs to. - name (
str) – The template name. - repeat_interval (
str) – PostgreSQL interval syntax for repeat frequency. - next_run_at (
datetime) – Next scheduled time to create a board. - is_active (
bool) – Whether the template is currently active. - name_template (
str | None) – Optional template string for generating board names. - series (
str | None) – Optional series identifier for sequential board naming. - config (
dict[str, Any] | None) – Optional configuration object for boards created from this template. - config_template – Optional template configuration for random generation.
Returns:
BoardTemplate– The created BoardTemplate domain entity.
Raises:
EntityNotFoundError– If the game doesn't exist.ValueError– If the game doesn't belong to the specified account or if name_template contains invalid placeholders.
Example
> > > template = await service.create_board_template( > > > ... account_id=account.id, > > > ... game_id=game.id, > > > ... name="Weekly Speed Run Template", > > > ... name_template="Week {series} - {year}", > > > ... series="weekly", > > > ... repeat_interval="7 days", > > > ... next_run_at=datetime.now(UTC) + timedelta(days=7), > > > ... is_active=True, > > > ... )# leadr.boards.services.board_template_service.BoardTemplateService.delete¶
delete(entity_id)
Soft-delete an entity.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_template_service.BoardTemplateService.get_board_template¶
get_board_template(template_id)
Get a board template by its ID.
Parameters:
- template_id (
BoardTemplateID) – The ID of the template to retrieve.
Returns:
BoardTemplate | None– The BoardTemplate domain entity if found, None otherwise.
# leadr.boards.services.board_template_service.BoardTemplateService.get_by_id¶
get_by_id(entity_id)
Get an entity by its ID.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT | None– The domain entity if found, None otherwise
# leadr.boards.services.board_template_service.BoardTemplateService.get_by_id_or_raise¶
get_by_id_or_raise(entity_id)
Get an entity by its ID or raise EntityNotFoundError.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to retrieve
Returns:
DomainEntityT– The domain entity
Raises:
EntityNotFoundError– If the entity is not found (converted to HTTP 404 by global handler)
# leadr.boards.services.board_template_service.BoardTemplateService.list_all¶
list_all()
List all non-deleted entities.
Returns:
list[DomainEntityT]– List of domain entities
# leadr.boards.services.board_template_service.BoardTemplateService.list_board_templates_by_account¶
list_board_templates_by_account(account_id, *, pagination)
List all board templates for an account with pagination.
Parameters:
- account_id (
AccountID | None) – The ID of the account to list templates for. If None, returns all templates (superadmin use case). - pagination (
PaginationParams) – Pagination parameters (required).
Returns:
PaginatedResult[BoardTemplate]– PaginatedResult containing BoardTemplate entities matching the filter criteria.
# leadr.boards.services.board_template_service.BoardTemplateService.list_board_templates_by_game¶
list_board_templates_by_game(account_id, game_id, *, pagination)
List all board templates for a specific game with pagination.
Parameters:
- account_id (
AccountID | None) – The ID of the account. If None, returns templates from all accounts (superadmin use case). - game_id (
GameID) – The ID of the game to list templates for. - pagination (
PaginationParams) – Pagination parameters (required).
Returns:
PaginatedResult[BoardTemplate]– PaginatedResult containing BoardTemplate entities matching the filter criteria.
# leadr.boards.services.board_template_service.BoardTemplateService.repository¶
repository = repository if repository is not None else self._create_repository(session)
# leadr.boards.services.board_template_service.BoardTemplateService.soft_delete¶
soft_delete(entity_id)
Soft-delete an entity and return it before deletion.
Useful for endpoints that need to return the deleted entity in the response.
Parameters:
- entity_id (
UUID | PrefixedID) – The ID of the entity to delete
Returns:
DomainEntityT– The entity before it was deleted
Raises:
EntityNotFoundError– If the entity doesn't exist
# leadr.boards.services.board_template_service.BoardTemplateService.update_board_template¶
update_board_template(template_id, **updates)
Update board template fields.
Accepts any fields to update as keyword arguments. Only fields explicitly provided will be updated, allowing null values to clear optional fields.
Parameters:
- template_id (
BoardTemplateID) – The ID of the template to update. - **updates (
Any) – Field names and values to update
Returns:
BoardTemplate– The updated BoardTemplate domain entity.
Raises:
EntityNotFoundError– If the template doesn't exist.ValueError– If name_template contains invalid placeholders.
leadr.boards.services.board_template_service.logger¶
logger = get_logger(__name__)
leadr.boards.services.dependencies¶
Board service dependency injection.
Functions:
- get_board_ratio_config_service – Get BoardRatioConfigService dependency.
- get_board_service – Get BoardService dependency.
- get_board_state_service – Get BoardStateService dependency.
- get_board_template_service – Get BoardTemplateService dependency.
- get_run_entry_service – Get RunEntryService dependency.
Attributes:
- BoardRatioConfigServiceDep –
- BoardServiceDep –
- BoardStateServiceDep –
- BoardTemplateServiceDep –
- RunEntryServiceDep –
leadr.boards.services.dependencies.BoardRatioConfigServiceDep¶
BoardRatioConfigServiceDep = Annotated[BoardRatioConfigService, Depends(get_board_ratio_config_service)]
leadr.boards.services.dependencies.BoardServiceDep¶
BoardServiceDep = Annotated[BoardService, Depends(get_board_service)]
leadr.boards.services.dependencies.BoardStateServiceDep¶
BoardStateServiceDep = Annotated[BoardStateService, Depends(get_board_state_service)]
leadr.boards.services.dependencies.BoardTemplateServiceDep¶
BoardTemplateServiceDep = Annotated[BoardTemplateService, Depends(get_board_template_service)]
leadr.boards.services.dependencies.RunEntryServiceDep¶
RunEntryServiceDep = Annotated[RunEntryService, Depends(get_run_entry_service)]
leadr.boards.services.dependencies.get_board_ratio_config_service¶
get_board_ratio_config_service(db)
Get BoardRatioConfigService dependency.
Parameters:
- db (
DatabaseSession) – Database session from dependency injection
Returns:
BoardRatioConfigService– BoardRatioConfigService instance for handling ratio config operations
leadr.boards.services.dependencies.get_board_service¶
get_board_service(db)
Get BoardService dependency.
Parameters:
- db (
DatabaseSession) – Database session from dependency injection
Returns:
BoardService– BoardService instance for handling board operations
leadr.boards.services.dependencies.get_board_state_service¶
get_board_state_service(db)
Get BoardStateService dependency.
Parameters:
- db (
DatabaseSession) – Database session from dependency injection
Returns:
BoardStateService– BoardStateService instance for handling board state operations
leadr.boards.services.dependencies.get_board_template_service¶
get_board_template_service(db)
Get BoardTemplateService dependency.
Parameters:
- db (
DatabaseSession) – Database session from dependency injection
Returns:
BoardTemplateService– BoardTemplateService instance for handling board template operations
leadr.boards.services.dependencies.get_run_entry_service¶
get_run_entry_service(db)
Get RunEntryService dependency.
Parameters:
- db (
DatabaseSession) – Database session from dependency injection
Returns:
RunEntryService– RunEntryService instance for handling run entry operations
leadr.boards.services.repositories¶
Board repository services.
Classes:
- BoardRatioConfigRepository – Repository for BoardRatioConfig persistence.
- BoardRepository – Board repository for managing board persistence.
- BoardStateRepository – BoardState repository for managing board state persistence.
- BoardTemplateRepository – BoardTemplate repository for managing board template persistence.
- RunEntryRepository – RunEntry repository for managing run entry persistence.
leadr.boards.services.repositories.BoardRatioConfigRepository¶
Bases: BaseRepository[BoardRatioConfig, BoardRatioConfigORM]
Repository for BoardRatioConfig persistence.
Functions:
- create – Create a new entity in the database.
- delete – Soft delete an entity by setting its deleted_at timestamp.
- filter – Filter ratio configs with optional criteria and pagination.
- get_by_board_id – Get the ratio config for a specific board.
- get_by_id – Get an entity by its ID.
- update – Update an existing entity in the database.
Attributes:
- SORTABLE_FIELDS –
- session –
# leadr.boards.services.repositories.BoardRatioConfigRepository.SORTABLE_FIELDS¶
SORTABLE_FIELDS = {'id', 'created_at', 'updated_at'}
# leadr.boards.services.repositories.BoardRatioConfigRepository.create¶
create(entity)
Create a new entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity to create
Returns:
DomainEntityT– Created domain entity with refreshed data
# leadr.boards.services.repositories.BoardRatioConfigRepository.delete¶
delete(entity_id)
Soft delete an entity by setting its deleted_at timestamp.
Parameters:
- entity_id (
UUID4 | PrefixedID) – ID of entity to delete
Raises:
EntityNotFoundError– If entity is not found
# leadr.boards.services.repositories.BoardRatioConfigRepository.filter¶
filter(board_id=None, *, pagination, **kwargs)
Filter ratio configs with optional criteria and pagination.
Parameters:
- board_id (
BoardID | None) – Optional board ID to filter by. - pagination (
PaginationParams) – Pagination parameters (required).
Returns:
PaginatedResult[BoardRatioConfig]– PaginatedResult containing ratio configs matching the filter criteria.
Raises:
ValueError– If sort field is not in SORTABLE_FIELDS.CursorValidationError– If cursor is invalid or state doesn't match.
# leadr.boards.services.repositories.BoardRatioConfigRepository.get_by_board_id¶
get_by_board_id(board_id)
Get the ratio config for a specific board.
Parameters:
- board_id (
BoardID) – The ID of the ratio board.
Returns:
BoardRatioConfig | None– BoardRatioConfig if found, None otherwise.
# leadr.boards.services.repositories.BoardRatioConfigRepository.get_by_id¶
get_by_id(entity_id, include_deleted=False)
Get an entity by its ID.
Parameters:
- entity_id (
UUID4 | PrefixedID) – Entity ID to retrieve - include_deleted (
bool) – If True, include soft-deleted entities. Defaults to False.
Returns:
DomainEntityT | None– Domain entity if found, None otherwise
# leadr.boards.services.repositories.BoardRatioConfigRepository.session¶
session = session
# leadr.boards.services.repositories.BoardRatioConfigRepository.update¶
update(entity)
Update an existing entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity with updated data
Returns:
DomainEntityT– Updated domain entity with refreshed data
Raises:
EntityNotFoundError– If entity is not found
leadr.boards.services.repositories.BoardRepository¶
Bases: BaseRepository[Board, BoardORM]
Board repository for managing board persistence.
Functions:
- count_boards_by_template – Count boards created from a specific template.
- create – Create a new entity in the database.
- delete – Soft delete an entity by setting its deleted_at timestamp.
- filter – Filter boards with optional criteria and pagination.
- get_by_id – Get an entity by its ID.
- get_by_short_code – Get board by short_code.
- update – Update an existing entity in the database.
Attributes:
- SORTABLE_FIELDS –
- session –
# leadr.boards.services.repositories.BoardRepository.SORTABLE_FIELDS¶
SORTABLE_FIELDS = {'id', 'name', 'slug', 'short_code', 'created_at', 'updated_at'}
# leadr.boards.services.repositories.BoardRepository.count_boards_by_template¶
count_boards_by_template(template_id)
Count boards created from a specific template.
Parameters:
- template_id (
BoardTemplateID) – The template ID to count boards for
Returns:
int– Number of boards created from this template
# leadr.boards.services.repositories.BoardRepository.create¶
create(entity)
Create a new entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity to create
Returns:
DomainEntityT– Created domain entity with refreshed data
# leadr.boards.services.repositories.BoardRepository.delete¶
delete(entity_id)
Soft delete an entity by setting its deleted_at timestamp.
Parameters:
- entity_id (
UUID4 | PrefixedID) – ID of entity to delete
Raises:
EntityNotFoundError– If entity is not found
# leadr.boards.services.repositories.BoardRepository.filter¶
filter(account_id=None, game_id=None, code=None, slug=None, is_active=None, is_published=None, starts_before=None, starts_after=None, ends_before=None, ends_after=None, *, pagination, **kwargs)
Filter boards with optional criteria and pagination.
Parameters:
- account_id (
AccountID | None) – Optional account ID to filter by - game_id (
GameID | None) – Optional game ID to filter by - code (
str | None) – Optional short code to filter by - slug (
str | None) – Optional slug to filter by - is_active (
bool | None) – Optional filter for active status - is_published (
bool | None) – Optional filter for published status - starts_before (
datetime | None) – Optional filter for boards starting before this time - starts_after (
datetime | None) – Optional filter for boards starting after this time - ends_before (
datetime | None) – Optional filter for boards ending before this time - ends_after (
datetime | None) – Optional filter for boards ending after this time - pagination (
PaginationParams) – Pagination parameters (required)
Returns:
PaginatedResult[Board]– PaginatedResult containing boards matching the filter criteria
Raises:
ValueError– If sort field is not in SORTABLE_FIELDSCursorValidationError– If cursor is invalid or state doesn't match
# leadr.boards.services.repositories.BoardRepository.get_by_id¶
get_by_id(entity_id, include_deleted=False)
Get an entity by its ID.
Parameters:
- entity_id (
UUID4 | PrefixedID) – Entity ID to retrieve - include_deleted (
bool) – If True, include soft-deleted entities. Defaults to False.
Returns:
DomainEntityT | None– Domain entity if found, None otherwise
# leadr.boards.services.repositories.BoardRepository.get_by_short_code¶
get_by_short_code(short_code)
Get board by short_code.
Parameters:
- short_code (
str) – The short_code to search for
Returns:
Board | None– Board entity if found, None otherwise
# leadr.boards.services.repositories.BoardRepository.session¶
session = session
# leadr.boards.services.repositories.BoardRepository.update¶
update(entity)
Update an existing entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity with updated data
Returns:
DomainEntityT– Updated domain entity with refreshed data
Raises:
EntityNotFoundError– If entity is not found
leadr.boards.services.repositories.BoardStateRepository¶
Bases: BaseRepository[BoardState, BoardStateORM]
BoardState repository for managing board state persistence.
Board states represent the materialized ranking state for identities on boards. Each identity has at most one state per board.
Functions:
- create – Create a new entity in the database.
- delete – Soft delete an entity by setting its deleted_at timestamp.
- execute_around_query – Execute a query that returns states centered around a target state.
- execute_around_value_query – Execute a query that returns states centered around a hypothetical value.
- filter – Filter board states with optional criteria and pagination.
- get_by_board_and_identity – Get a board state by board and identity.
- get_by_id – Get an entity by its ID.
- get_rank – Compute rank for a board state using COUNT approach.
- update – Update an existing entity in the database.
Attributes:
- SORTABLE_FIELDS –
- session –
# leadr.boards.services.repositories.BoardStateRepository.SORTABLE_FIELDS¶
SORTABLE_FIELDS = {'id', 'primary_value', 'created_at', 'updated_at'}
# leadr.boards.services.repositories.BoardStateRepository.create¶
create(entity)
Create a new entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity to create
Returns:
DomainEntityT– Created domain entity with refreshed data
# leadr.boards.services.repositories.BoardStateRepository.delete¶
delete(entity_id)
Soft delete an entity by setting its deleted_at timestamp.
Parameters:
- entity_id (
UUID4 | PrefixedID) – ID of entity to delete
Raises:
EntityNotFoundError– If entity is not found
# leadr.boards.services.repositories.BoardStateRepository.execute_around_query¶
execute_around_query(board_id, target_state, sort_fields, limit, is_test=None)
Execute a query that returns states centered around a target state.
This method fetches states in a window around the target state, respecting the sort order. For limit=5 with DESC sort, it returns 2 states above (better ranked), the target, and 2 states below (worse ranked).
When the target is near an edge, the window adjusts to fill up to the limit.
Parameters:
- board_id (
BoardID) – Board ID to filter by. - target_state (
BoardState) – The state to center results around. - sort_fields (
list[SortField]) – Sort fields defining the ranking order. - limit (
int) – Total number of states to return (including target). - is_test (
bool | None) – Optional filter for test entries.
Returns:
PaginatedResult[BoardState]– PaginatedResult with states centered around target.
# leadr.boards.services.repositories.BoardStateRepository.execute_around_value_query¶
execute_around_value_query(board_id, target_value, sort_fields, limit, is_test=None)
Execute a query that returns states centered around a hypothetical value.
Creates a synthetic placeholder state with the given value and returns it along with neighboring states. The placeholder has is_placeholder=True and uses sentinel nil UUIDs for id and identity_id.
Parameters:
- board_id (
BoardID) – Board ID to filter by. - target_value (
float) – The hypothetical score value to center results around. - sort_fields (
list[SortField]) – Sort fields defining the ranking order. - limit (
int) – Total number of states to return (including placeholder). - is_test (
bool | None) – Optional filter for test entries.
Returns:
PaginatedResult[BoardState]– PaginatedResult with states centered around value (including placeholder).
# leadr.boards.services.repositories.BoardStateRepository.filter¶
filter(board_id=None, identity_id=None, is_test=None, *, pagination, **kwargs)
Filter board states with optional criteria and pagination.
Parameters:
- board_id (
BoardID | None) – Optional board ID to filter by. - identity_id (
IdentityID | None) – Optional identity ID to filter by. - is_test (
bool | None) – Optional filter for test entries (True=test only, False=prod only, None=all). - pagination (
PaginationParams) – Pagination parameters (required).
Returns:
PaginatedResult[BoardState]– PaginatedResult containing board states matching the filter criteria.
Raises:
ValueError– If sort field is not in SORTABLE_FIELDS.CursorValidationError– If cursor is invalid or state doesn't match.
# leadr.boards.services.repositories.BoardStateRepository.get_by_board_and_identity¶
get_by_board_and_identity(board_id, identity_id)
Get a board state by board and identity.
Parameters:
- board_id (
BoardID) – The board ID to search for. - identity_id (
IdentityID) – The identity ID to search for.
Returns:
BoardState | None– BoardState entity if found, None otherwise.
# leadr.boards.services.repositories.BoardStateRepository.get_by_id¶
get_by_id(entity_id, include_deleted=False)
Get an entity by its ID.
Parameters:
- entity_id (
UUID4 | PrefixedID) – Entity ID to retrieve - include_deleted (
bool) – If True, include soft-deleted entities. Defaults to False.
Returns:
DomainEntityT | None– Domain entity if found, None otherwise
# leadr.boards.services.repositories.BoardStateRepository.get_rank¶
get_rank(state, sort_fields)
Compute rank for a board state using COUNT approach.
Counts how many entries rank better than the given state using the same multi-field comparison logic used for sorting.
Parameters:
- state (
BoardState) – BoardState to compute rank for. - sort_fields (
list[SortField]) – Sort fields defining the ranking order.
Returns:
int– Rank (1-indexed, where 1 is the best).
# leadr.boards.services.repositories.BoardStateRepository.session¶
session = session
# leadr.boards.services.repositories.BoardStateRepository.update¶
update(entity)
Update an existing entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity with updated data
Returns:
DomainEntityT– Updated domain entity with refreshed data
Raises:
EntityNotFoundError– If entity is not found
leadr.boards.services.repositories.BoardTemplateRepository¶
Bases: BaseRepository[BoardTemplate, BoardTemplateORM]
BoardTemplate repository for managing board template persistence.
Functions:
- create – Create a new entity in the database.
- delete – Soft delete an entity by setting its deleted_at timestamp.
- filter – Filter board templates by account and optional game with pagination.
- get_by_id – Get an entity by its ID.
- update – Update an existing entity in the database.
Attributes:
- SORTABLE_FIELDS –
- session –
# leadr.boards.services.repositories.BoardTemplateRepository.SORTABLE_FIELDS¶
SORTABLE_FIELDS = {'id', 'name', 'created_at', 'updated_at'}
# leadr.boards.services.repositories.BoardTemplateRepository.create¶
create(entity)
Create a new entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity to create
Returns:
DomainEntityT– Created domain entity with refreshed data
# leadr.boards.services.repositories.BoardTemplateRepository.delete¶
delete(entity_id)
Soft delete an entity by setting its deleted_at timestamp.
Parameters:
- entity_id (
UUID4 | PrefixedID) – ID of entity to delete
Raises:
EntityNotFoundError– If entity is not found
# leadr.boards.services.repositories.BoardTemplateRepository.filter¶
filter(account_id=None, game_id=None, *, pagination, **kwargs)
Filter board templates by account and optional game with pagination.
Parameters:
- account_id (
AccountID | None) – Optional account ID to filter by. If None, returns all templates (superadmin use case). Regular users should always pass account_id. - game_id (
GameID | None) – OPTIONAL - Game ID to filter by - pagination (
PaginationParams) – Pagination parameters (required) - **kwargs (
Any) – Additional filter parameters (reserved for future use)
Returns:
PaginatedResult[BoardTemplate]– PaginatedResult containing board templates matching the filter criteria
Raises:
ValueError– If sort field is not in SORTABLE_FIELDSCursorValidationError– If cursor is invalid or state doesn't match
# leadr.boards.services.repositories.BoardTemplateRepository.get_by_id¶
get_by_id(entity_id, include_deleted=False)
Get an entity by its ID.
Parameters:
- entity_id (
UUID4 | PrefixedID) – Entity ID to retrieve - include_deleted (
bool) – If True, include soft-deleted entities. Defaults to False.
Returns:
DomainEntityT | None– Domain entity if found, None otherwise
# leadr.boards.services.repositories.BoardTemplateRepository.session¶
session = session
# leadr.boards.services.repositories.BoardTemplateRepository.update¶
update(entity)
Update an existing entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity with updated data
Returns:
DomainEntityT– Updated domain entity with refreshed data
Raises:
EntityNotFoundError– If entity is not found
leadr.boards.services.repositories.RunEntryRepository¶
Bases: BaseRepository[RunEntry, RunEntryORM]
RunEntry repository for managing run entry persistence.
Run entries represent individual scored submissions for RUN_RUNS boards where every submission is ranked.
Functions:
- create – Create a new entity in the database.
- delete – Soft delete an entity by setting its deleted_at timestamp.
- execute_around_query – Execute a query that returns entries centered around a target entry.
- execute_around_value_query – Execute a query that returns entries centered around a hypothetical value.
- filter – Filter run entries with optional criteria and pagination.
- get_by_board_and_score_event – Get a run entry by board and score event.
- get_by_id – Get an entity by its ID.
- get_rank – Compute rank for a run entry using COUNT approach.
- update – Update an existing entity in the database.
Attributes:
- SORTABLE_FIELDS –
- session –
# leadr.boards.services.repositories.RunEntryRepository.SORTABLE_FIELDS¶
SORTABLE_FIELDS = {'id', 'primary_value', 'created_at', 'updated_at'}
# leadr.boards.services.repositories.RunEntryRepository.create¶
create(entity)
Create a new entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity to create
Returns:
DomainEntityT– Created domain entity with refreshed data
# leadr.boards.services.repositories.RunEntryRepository.delete¶
delete(entity_id)
Soft delete an entity by setting its deleted_at timestamp.
Parameters:
- entity_id (
UUID4 | PrefixedID) – ID of entity to delete
Raises:
EntityNotFoundError– If entity is not found
# leadr.boards.services.repositories.RunEntryRepository.execute_around_query¶
execute_around_query(board_id, target_entry, sort_fields, limit, is_test=None)
Execute a query that returns entries centered around a target entry.
This method fetches entries in a window around the target entry, respecting the sort order. For limit=5 with DESC sort, it returns 2 entries above (better ranked), the target, and 2 entries below (worse ranked).
When the target is near an edge, the window adjusts to fill up to the limit.
Parameters:
- board_id (
BoardID) – Board ID to filter by. - target_entry (
RunEntry) – The entry to center results around. - sort_fields (
list[SortField]) – Sort fields defining the ranking order. - limit (
int) – Total number of entries to return (including target). - is_test (
bool | None) – Optional filter for test entries.
Returns:
PaginatedResult[RunEntry]– PaginatedResult with entries centered around target.
# leadr.boards.services.repositories.RunEntryRepository.execute_around_value_query¶
execute_around_value_query(board_id, target_value, sort_fields, limit, is_test=None)
Execute a query that returns entries centered around a hypothetical value.
Creates a synthetic placeholder entry with the given value and returns it along with neighboring entries. The placeholder has is_placeholder=True and uses sentinel nil UUIDs for id and identity_id.
Parameters:
- board_id (
BoardID) – Board ID to filter by. - target_value (
float) – The hypothetical score value to center results around. - sort_fields (
list[SortField]) – Sort fields defining the ranking order. - limit (
int) – Total number of entries to return (including placeholder). - is_test (
bool | None) – Optional filter for test entries.
Returns:
PaginatedResult[RunEntry]– PaginatedResult with entries centered around value (including placeholder).
# leadr.boards.services.repositories.RunEntryRepository.filter¶
filter(board_id=None, identity_id=None, is_test=None, *, pagination, **kwargs)
Filter run entries with optional criteria and pagination.
Parameters:
- board_id (
BoardID | None) – Optional board ID to filter by. - identity_id (
IdentityID | None) – Optional identity ID to filter by. - is_test (
bool | None) – Optional filter for test entries (True=test only, False=prod only, None=all). - pagination (
PaginationParams) – Pagination parameters (required).
Returns:
PaginatedResult[RunEntry]– PaginatedResult containing run entries matching the filter criteria.
Raises:
ValueError– If sort field is not in SORTABLE_FIELDS.CursorValidationError– If cursor is invalid or state doesn't match.
# leadr.boards.services.repositories.RunEntryRepository.get_by_board_and_score_event¶
get_by_board_and_score_event(board_id, score_event_id)
Get a run entry by board and score event.
Parameters:
- board_id (
BoardID) – The board ID to search for. - score_event_id (
ScoreEventID) – The score event ID to search for.
Returns:
RunEntry | None– RunEntry entity if found, None otherwise.
# leadr.boards.services.repositories.RunEntryRepository.get_by_id¶
get_by_id(entity_id, include_deleted=False)
Get an entity by its ID.
Parameters:
- entity_id (
UUID4 | PrefixedID) – Entity ID to retrieve - include_deleted (
bool) – If True, include soft-deleted entities. Defaults to False.
Returns:
DomainEntityT | None– Domain entity if found, None otherwise
# leadr.boards.services.repositories.RunEntryRepository.get_rank¶
get_rank(entry, sort_fields)
Compute rank for a run entry using COUNT approach.
Counts how many entries rank better than the given entry using the same multi-field comparison logic used for sorting.
Parameters:
- entry (
RunEntry) – RunEntry to compute rank for. - sort_fields (
list[SortField]) – Sort fields defining the ranking order.
Returns:
int– Rank (1-indexed, where 1 is the best).
# leadr.boards.services.repositories.RunEntryRepository.session¶
session = session
# leadr.boards.services.repositories.RunEntryRepository.update¶
update(entity)
Update an existing entity in the database.
Parameters:
- entity (
DomainEntityT) – Domain entity with updated data
Returns:
DomainEntityT– Updated domain entity with refreshed data
Raises:
EntityNotFoundError– If entity is not found
leadr.boards.services.run_entry_service¶
Run entry service for managing run entries.
Classes:
- RunEntryService – Service for managing run entries.
leadr.boards.services.run_entry_service.RunEntryService¶
RunEntryService(session)
Service for managing run entries.
Run entries represent individual scored submissions for RUN_RUNS boards where every submission is ranked.
Functions:
- create_run_entry – Create a new run entry.
- get_by_board_and_score_event – Get a run entry by board and score event.
- get_by_id_or_raise – Get a run entry by ID or raise if not found.
- get_run_entry – Get a run entry by ID.
- list_run_entries – List run entries with optional filtering.
- soft_delete – Soft delete a run entry.
Attributes:
- repository –
- session –
Parameters:
- session (
AsyncSession) – Database session for persistence operations.
# leadr.boards.services.run_entry_service.RunEntryService.create_run_entry¶
create_run_entry(*, board_id, identity_id, score_event_id, primary_value, player_name='', is_test=False, timezone=None, country=None, city=None, value_display=None, metadata=None)
Create a new run entry.
Parameters:
- board_id (
BoardID) – The board this entry belongs to. - identity_id (
IdentityID) – The identity that submitted this entry. - score_event_id (
ScoreEventID) – The score event that created this entry. - primary_value (
float) – The rankable value for this submission. - player_name (
str) – Display name at submission time. - is_test (
bool) – Whether this is a test submission. - timezone (
str | None) – Timezone from GeoIP. - country (
str | None) – Country code from GeoIP. - city (
str | None) – City name from GeoIP. - value_display (
str | None) – Formatted display string. - metadata (
Any | None) – Game-specific JSON metadata.
Returns:
RunEntry– The created run entry.
# leadr.boards.services.run_entry_service.RunEntryService.get_by_board_and_score_event¶
get_by_board_and_score_event(board_id, score_event_id)
Get a run entry by board and score event.
Parameters:
- board_id (
BoardID) – The board ID to search for. - score_event_id (
ScoreEventID) – The score event ID to search for.
Returns:
RunEntry | None– The run entry if found, None otherwise.
# leadr.boards.services.run_entry_service.RunEntryService.get_by_id_or_raise¶
get_by_id_or_raise(entry_id)
Get a run entry by ID or raise if not found.
Parameters:
- entry_id (
RunEntryID) – The run entry ID to look up.
Returns:
RunEntry– The run entry.
Raises:
EntityNotFoundError– If the run entry does not exist.
# leadr.boards.services.run_entry_service.RunEntryService.get_run_entry¶
get_run_entry(entry_id)
Get a run entry by ID.
Parameters:
- entry_id (
RunEntryID) – The run entry ID to look up.
Returns:
RunEntry | None– The run entry if found, None otherwise.
# leadr.boards.services.run_entry_service.RunEntryService.list_run_entries¶
list_run_entries(*, board_id=None, identity_id=None, is_test=None, pagination=None, around_entry=None, around_value=None)
List run entries with optional filtering.
Parameters:
- board_id (
BoardID | None) – Optional board ID to filter by. - identity_id (
IdentityID | None) – Optional identity ID to filter by. - is_test (
bool | None) – Optional filter for test entries (True=test only, False=prod only, None=all). - pagination (
PaginationParams | None) – Optional pagination parameters. - around_entry (
RunEntry | None) – Optional target entry to center results around. - around_value (
float | None) – Optional value to center results around (creates placeholder).
Returns:
PaginatedResult[RunEntry]– Paginated list of run entries.
# leadr.boards.services.run_entry_service.RunEntryService.repository¶
repository = RunEntryRepository(session)
# leadr.boards.services.run_entry_service.RunEntryService.session¶
session = session
# leadr.boards.services.run_entry_service.RunEntryService.soft_delete¶
soft_delete(entry_id)
Soft delete a run entry.
Parameters:
- entry_id (
RunEntryID) – The run entry ID to delete.
Returns:
RunEntry– The deleted run entry.
Raises:
EntityNotFoundError– If the run entry does not exist.
leadr.boards.services.short_code_generator¶
Utility for generating unique short codes for boards.
Short codes are used for direct board sharing (e.g., example.com/board/ABC123XY). They must be globally unique across all boards.
Functions:
- generate_short_code – Generate a random 8-character alphanumeric short code.
- generate_unique_short_code – Generate a globally unique short code with collision retry logic.
Attributes:
- CHARSET –
- CODE_LENGTH –
leadr.boards.services.short_code_generator.CHARSET¶
CHARSET = '23456789ABCDEFGHJKMNPQRSTUVWXYZ'
leadr.boards.services.short_code_generator.CODE_LENGTH¶
CODE_LENGTH = 5
leadr.boards.services.short_code_generator.generate_short_code¶
generate_short_code()
Generate a random 8-character alphanumeric short code.
Uses cryptographically strong random number generator for security. Excludes ambiguous characters (0/O, 1/I/l) for better readability.
Returns:
str– 5-character uppercase alphanumeric code (e.g., 'A7B3X').
Example
> > > code = generate_short_code() > > > len(code) > > > 5 > > > code.isupper() > > > Trueleadr.boards.services.short_code_generator.generate_unique_short_code¶
generate_unique_short_code(session, max_retries=10)
Generate a globally unique short code with collision retry logic.
Generates random codes and checks database for uniqueness. If a collision is detected, retries up to max_retries times before raising an error.
Parameters:
- session (
AsyncSession) – Database session for uniqueness checking. - max_retries (
int) – Maximum number of generation attempts (default 10).
Returns:
str– Unique 5-character short code guaranteed not to exist in database.
Raises:
RuntimeError– If unable to generate unique code within max_retries attempts.