import { uuidv7 } from '@sims/domain' import { writeAudit } from './audit' import type { DB } from './db' /** Client branches (D20 — APEX ho_branch_list parity): minimal, per-client, audited. */ export interface Branch { id: string; clientId: string; name: string; code: string | null; active: boolean } interface BranchRow { id: string; client_id: string; name: string; code: string | null; active: number } const toBranch = (r: BranchRow): Branch => ({ id: r.id, clientId: r.client_id, name: r.name, code: r.code, active: r.active === 1, }) export async function listBranches(db: DB, clientId: string): Promise { const rows = await db.all( `SELECT * FROM client_branch WHERE client_id=? ORDER BY active DESC, name`, clientId, ) return rows.map(toBranch) } export async function createBranch( db: DB, userId: string, input: { clientId: string; name: string; code?: string }, ): Promise { return db.transaction(async () => { if (input.name.trim() === '') throw new Error('Branch name is required') const client = await db.get(`SELECT id FROM client WHERE id=?`, input.clientId) if (client === undefined) throw new Error('Client not found') const id = uuidv7() await db.run( `INSERT INTO client_branch (id, client_id, name, code, active) VALUES (?, ?, ?, ?, 1)`, id, input.clientId, input.name.trim(), input.code !== undefined && input.code.trim() !== '' ? input.code.trim() : null, ) const branch = toBranch((await db.get(`SELECT * FROM client_branch WHERE id=?`, id))!) await writeAudit(db, userId, 'create', 'client_branch', id, undefined, branch) return branch }) } export async function updateBranch( db: DB, userId: string, id: string, patch: { name?: string; code?: string; active?: boolean }, ): Promise { return db.transaction(async () => { const beforeRow = await db.get(`SELECT * FROM client_branch WHERE id=?`, id) if (beforeRow === undefined) throw new Error('Branch not found') const before = toBranch(beforeRow) const sets: string[] = [] const args: unknown[] = [] if (patch.name !== undefined) { if (patch.name.trim() === '') throw new Error('Branch name is required') sets.push('name=?'); args.push(patch.name.trim()) } if (patch.code !== undefined) { sets.push('code=?'); args.push(patch.code.trim() === '' ? null : patch.code.trim()) } if (patch.active !== undefined) { sets.push('active=?'); args.push(patch.active ? 1 : 0) } if (sets.length > 0) { args.push(id) await db.run(`UPDATE client_branch SET ${sets.join(', ')} WHERE id=?`, ...args) } const after = toBranch((await db.get(`SELECT * FROM client_branch WHERE id=?`, id))!) await writeAudit(db, userId, 'update', 'client_branch', id, before, after) return after }) }