67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
import _ from 'lodash'
|
|
import { Type, type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'
|
|
import knex from '../../lib/knex.ts'
|
|
|
|
const entryRoutes: FastifyPluginCallbackTypebox = (fastify, _, done) => {
|
|
fastify.route({
|
|
url: '/',
|
|
method: 'GET',
|
|
schema: {
|
|
querystring: Type.Object({
|
|
journal: Type.String(),
|
|
year: Type.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: Type.Object({
|
|
id: Type.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
|