api / app /services /category.py
hanbinsite's picture
feat: complete core feature improvements
bf34e9d
Raw History Blame Contribute Delete
1.35 kB
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
}