import { pool } from '../db'; import type { TenantContext } from './tenantScope'; export type CategoryDirectoryRow = { category_code: string; category_name: string; parent_code: string; level: number | null; status: number | null; }; export async function listCategoriesForManagement(input: { ctx: TenantContext; search?: string; limit?: number; }): Promise<{ rows: CategoryDirectoryRow[]; total: number }> { const branchCode = String(input.ctx.branchCode || '').trim(); if (!branchCode) { throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'invalid_request' }); } const params: unknown[] = [branchCode]; const where = [`item_type = 'category'`, `branch_code = $1`]; const search = String(input.search || '').trim(); if (search) { params.push(`%${search}%`); where.push(`(name ILIKE $${params.length} OR code ILIKE $${params.length})`); } const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 50); params.push(limit); const result = await pool.query( `SELECT code, name, parent_code, level, status, COUNT(*) OVER()::int AS total FROM product_catalog WHERE ${where.join(' AND ')} ORDER BY sort_order ASC, name ASC LIMIT $${params.length}`, params ); const rows = result.rows.map((row) => ({ category_code: String(row.code || ''), category_name: String(row.name || ''), parent_code: String(row.parent_code || ''), level: row.level == null ? null : Number(row.level), status: row.status == null ? null : Number(row.status), })); return { rows, total: Number(result.rows[0]?.total) || rows.length }; }