brf/server/routes/api/balances.ts
2025-12-09 12:00:39 +01:00

37 lines
1.1 KiB
TypeScript

import _ from 'lodash'
import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'
import knex from '../../lib/knex.ts'
const balanceRoutes: FastifyPluginCallbackTypebox = (fastify, _, done) => {
fastify.route({
url: '/',
method: 'GET',
async handler() {
const financialYears = await knex('financialYear').select('*').orderBy('year', 'asc')
return knex('accountBalance AS ab')
.select(
'ab.accountNumber',
'a.description',
Object.fromEntries(
financialYears.map((fy) => [
fy.year,
knex.raw(`SUM(CASE WHEN fy.year = ${fy.year} THEN ab."out" ELSE 0 END)`),
]),
),
)
.innerJoin('financialYear AS fy', 'fy.id', 'ab.financialYearId')
.innerJoin('account AS a', function () {
this.on('ab.accountNumber', '=', 'a.number')
})
.groupBy('ab.accountNumber', 'a.description')
.where('ab.accountNumber', '<', 3000)
.orderBy('ab.accountNumber')
},
})
done()
}
export default balanceRoutes