import _ from 'lodash' import { Type, type Static, type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox' import knex from '../../lib/knex.ts' const resultRoutes: FastifyPluginCallbackTypebox = (fastify, _, done) => { fastify.route({ url: '/', method: 'GET', async handler() { const years = await knex('financialYear').select('*') const accounts = await knex('account').select('*') return Promise.all( years.map((year) => knex('account AS a') .select('a.number', 'a.description') .sum('t.amount as amount') .innerJoin('transaction AS t', function () { this.on('t.accountNumber', '=', 'a.number') }) .innerJoin('entry AS e', function () { this.on('t.entryId', '=', 'e.id') }) .groupBy('a.number', 'a.description') .where('a.number', '>=', 3000) .where('e.financialYearId', year.id) .orderBy('a.number') .then((result) => ({ startDate: year.startDate, endDate: year.endDate, result, })), ), ).then((years) => ({ accounts, years, })) }, }) fastify.route({ url: '/:year', method: 'GET', schema: { params: Type.Object({ year: Type.Number(), }), }, async handler(req) { const year = await knex('financialYear').first('*').where('year', req.params.year) if (!year) return null return knex('transaction AS t') .select('t.accountNumber', 'a.description') .sum('t.amount as amount') .innerJoin('account AS a', function () { this.on('t.accountNumber', '=', 'a.number') }) .innerJoin('entry AS e', function () { this.on('t.entryId', '=', 'e.id') }) .groupBy('t.accountNumber', 'a.description') .where('t.accountNumber', '>=', 3000) .where('e.financialYearId', year.id) .orderBy('t.accountNumber') }, }) done() } export default resultRoutes