78 lines
2.4 KiB
Python
78 lines
2.4 KiB
Python
import uuid
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from ...auth import verify_token
|
|
from ...outbound.postgres.database import get_db
|
|
from ...outbound.postgres.entities.vocab_entities import UserLanguagePairEntity
|
|
from ...outbound.postgres.repositories.pack_repository import PostgresPackRepository
|
|
|
|
router = APIRouter(prefix="/packs", tags=["bff-packs"])
|
|
|
|
|
|
class PackSelectionItem(BaseModel):
|
|
id: str
|
|
name: str
|
|
name_target: str
|
|
description: str
|
|
description_target: str
|
|
source_lang: str
|
|
target_lang: str
|
|
proficiencies: list[str]
|
|
entry_count: int
|
|
already_added: bool
|
|
|
|
|
|
@router.get("", response_model=list[PackSelectionItem])
|
|
async def list_packs_for_selection(
|
|
source_lang: str,
|
|
target_lang: str,
|
|
db: AsyncSession = Depends(get_db),
|
|
token_data: dict = Depends(verify_token),
|
|
) -> list[PackSelectionItem]:
|
|
user_id = uuid.UUID(token_data["sub"])
|
|
|
|
pack_repo = PostgresPackRepository(db)
|
|
|
|
packs = await pack_repo.list_packs(
|
|
source_lang=source_lang,
|
|
target_lang=target_lang,
|
|
published_only=True,
|
|
)
|
|
|
|
# The UserLanguagePair may not exist yet for brand-new users
|
|
result = await db.execute(
|
|
select(UserLanguagePairEntity).where(
|
|
UserLanguagePairEntity.user_id == user_id,
|
|
UserLanguagePairEntity.source_lang == source_lang,
|
|
UserLanguagePairEntity.target_lang == target_lang,
|
|
)
|
|
)
|
|
pair_entity = result.scalar_one_or_none()
|
|
already_added_ids: set[str] = set()
|
|
if pair_entity is not None:
|
|
already_added_ids = await pack_repo.get_pack_ids_added_by_user(
|
|
user_id, pair_entity.id
|
|
)
|
|
|
|
items = []
|
|
for pack in packs:
|
|
count = await pack_repo.count_entries_for_pack(uuid.UUID(pack.id))
|
|
items.append(
|
|
PackSelectionItem(
|
|
id=pack.id,
|
|
name=pack.name,
|
|
name_target=pack.name_target,
|
|
description=pack.description,
|
|
description_target=pack.description_target,
|
|
source_lang=pack.source_lang,
|
|
target_lang=pack.target_lang,
|
|
proficiencies=pack.proficiencies,
|
|
entry_count=count,
|
|
already_added=pack.id in already_added_ids,
|
|
)
|
|
)
|
|
return items
|