/** * routes/accounts.mjs — Chart of Accounts endpoints */ export default function registerAccounts(app, pool, buildCtx, writeAudit, hermes) { // GET /api/ledger/accounts — hämta kontoplan app.get('/api/ledger/accounts', async (req, res) => { const tenant_id = req.headers['x-tenant-id'] || 'wavult-group'; const coa_standard = req.query.standard || null; try { const { rows } = await pool.query( `SELECT * FROM ledger_accounts WHERE tenant_id = $1 AND ($2::text IS NULL OR LOWER(coa_standard) = LOWER($2)) AND is_active = TRUE ORDER BY account_number`, [tenant_id, coa_standard] ); res.json({ ok: true, accounts: rows, count: rows.length }); } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); // POST /api/ledger/accounts — lägg till konto app.post('/api/ledger/accounts', async (req, res) => { const ctx = buildCtx(req, 'account'); const { account_number, name, account_type, normal_balance, coa_standard = 'BAS', parent_account, vat_code, metadata = {} } = req.body; if (!account_number || !name || !account_type || !normal_balance) { return res.status(400).json({ ok: false, error: 'account_number, name, account_type, normal_balance krävs' }); } if (!['asset','liability','equity','revenue','expense'].includes(account_type)) { return res.status(400).json({ ok: false, error: 'Ogiltigt account_type' }); } try { const { rows } = await pool.query( `INSERT INTO ledger_accounts (tenant_id, account_number, name, account_type, normal_balance, coa_standard, parent_account, vat_code, metadata) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (tenant_id, account_number, coa_standard) DO UPDATE SET name=EXCLUDED.name, account_type=EXCLUDED.account_type, updated_at=NOW() RETURNING *`, [ctx.tenant_id, account_number, name, account_type, normal_balance, coa_standard, parent_account, vat_code, JSON.stringify(metadata)] ); const account = rows[0]; ctx.entity_id = account.id; await writeAudit(ctx, 'created', null, account); await hermes.emit('finance.account.created', ctx, { account_number, name, coa_standard }); res.status(201).json({ ok: true, account }); } catch (e) { res.status(500).json({ ok: false, error: e.message }); } }); }