import _ from 'lodash' import * as z from 'zod' import type { FastifyPluginCallbackZod } from 'fastify-type-provider-zod' import knex from '../../lib/knex.ts' const entryRoutes: FastifyPluginCallbackZod = (fastify, _, done) => { fastify.route({ url: '/', method: 'GET', schema: { querystring: z.object({ journal: z.string(), year: z.coerce.number(), }), }, async handler(req) { const financialYearId = (await knex('financialYear').first('id').where('year', req.query.year))?.id const journalId = (await knex('journal').first('id').where('identifier', req.query.journal))?.id if (!financialYearId || !journalId) { return null } return knex('entry AS e') .select('e.*') .sum('t.amount AS amount') .innerJoin('transaction AS t', 'e.id', 't.entryId') .orderBy('e.id') .where({ financialYearId, journalId }) .andWhere('t.amount', '>', 0) .groupBy('e.id') }, }) fastify.route({ url: '/:id', method: 'GET', schema: { params: z.object({ id: z.number(), }), }, async handler(req) { return knex('entry AS e') .first('e.id', 'j.identifier AS journal', 'e.number', 'e.entryDate', 'e.transactionDate', 'e.description', { transactions: knex .select(knex.raw('json_agg(transactions)')) .from( knex('transaction') .select('accountNumber', 'objectId') .where('transaction.entryId', knex.ref('e.id')) .as('transactions'), ), }) .sum('t.amount AS amount') .innerJoin('journal AS j', 'e.journalId', 'j.id') .innerJoin('transaction AS t', 'e.id', 't.entryId') .where('e.id', req.params.id) .andWhere('t.amount', '>', 0) .groupBy('e.id', 'j.identifier') }, }) done() } export default entryRoutes