File size: 1,346 Bytes
bf34e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.category import Category, CategoryMapping


async def get_category_tree(db: AsyncSession, active_only: bool = True) -> list[dict]:
    query = select(Category).order_by(Category.sort_order)
    if active_only:
        query = query.where(Category.is_active == True)
    result = await db.execute(query)
    all_cats = result.scalars().all()

    cat_map: dict[int, dict] = {}
    roots: list[dict] = []

    for c in all_cats:
        node = {
            "id": c.id,
            "name": c.name,
            "parent_id": c.parent_id,
            "sort_order": c.sort_order,
            "children": [],
        }
        cat_map[c.id] = node

    for c in all_cats:
        node = cat_map[c.id]
        if c.parent_id and c.parent_id in cat_map:
            cat_map[c.parent_id]["children"].append(node)
        elif not c.parent_id:
            roots.append(node)

    return roots


async def get_source_mappings(db: AsyncSession, source_id: int) -> dict[int, dict]:
    result = await db.execute(
        select(CategoryMapping).where(CategoryMapping.source_id == source_id)
    )
    mappings = result.scalars().all()
    return {
        m.source_type_id: {"category_id": m.category_id, "name": m.source_type_name}
        for m in mappings
    }