import { type FastifyPluginCallback } from 'fastify' import knex from '../lib/knex.ts' const apiRoutes: FastifyPluginCallback = (fastify, _, done) => { fastify.route({ url: '/result', method: 'GET', async handler(req, res) { const years = await knex('financialYear').select('*') return Promise.all( years.map((year) => knex('account') .select('account.number', 'account.description') .sum('transaction.amount as amount') .innerJoin('transaction', function () { this.on('transaction.accountNumber', '=', 'account.number') }) .innerJoin('entry', function () { this.on('transaction.entryId', '=', 'entry.id') }) .groupBy('account.number', 'account.description') .where('account.number', '>=', 3000) .where('entry.financialYearId', year.id) .orderBy('account.number') .then((result) => ({ startDate: year.startDate, endDate: year.endDate, result, })), ), ) }, }) fastify.route({ url: '/result/:year', method: 'GET', async handler(req, res) { const year = await knex('financialYear').first('*').where('startDate', `${req.params.year}0101`) const result = await knex('account') .select('account.number', 'account.description') .sum('transaction.amount as amount') .innerJoin('transaction', function () { this.on('transaction.accountNumber', '=', 'account.number') }) .innerJoin('entry', function () { this.on('transaction.entryId', '=', 'entry.id') }) .groupBy('account.number', 'account.description') .where('account.number', '>=', 3000) .where('entry.financialYearId', year.id) .orderBy('account.number') return result }, }) done() } export default apiRoutes