71 lines
1.7 KiB
TypeScript
71 lines
1.7 KiB
TypeScript
import _ from 'lodash'
|
|
import * as z from 'zod'
|
|
import type { FastifyPluginCallbackZod } from 'fastify-type-provider-zod'
|
|
import StatusError from '../../lib/status_error.ts'
|
|
|
|
const transactionRoutes: FastifyPluginCallbackZod = (fastify, _, done) => {
|
|
const { db } = fastify
|
|
|
|
fastify.route({
|
|
url: '/',
|
|
method: 'GET',
|
|
schema: {
|
|
querystring: z.object({
|
|
year: z.optional(z.coerce.number()),
|
|
accountNumber: z.optional(z.coerce.number()),
|
|
}),
|
|
},
|
|
async handler(req) {
|
|
const query: { financialYearId?: number; accountNumber?: number } = {}
|
|
|
|
if (req.query.year) {
|
|
const year = await db
|
|
.selectFrom('financialYear')
|
|
.selectAll()
|
|
.where('year', '=', req.query.year)
|
|
.executeTakeFirst()
|
|
|
|
if (!year) throw new StatusError(404, `Year ${req.query.year} not found.`)
|
|
|
|
query.financialYearId = year.id
|
|
}
|
|
|
|
if (req.query.accountNumber) {
|
|
query.accountNumber = req.query.accountNumber
|
|
}
|
|
|
|
return db
|
|
.selectFrom('transaction as t')
|
|
.innerJoin('entry as e', 't.entryId', 'e.id')
|
|
.select([
|
|
't.accountNumber',
|
|
'e.transactionDate',
|
|
't.entryId',
|
|
't.amount',
|
|
't.description',
|
|
't.invoiceId',
|
|
'e.description as entryDescription',
|
|
])
|
|
.where((eb) => eb.and(query))
|
|
.execute()
|
|
},
|
|
})
|
|
|
|
fastify.route({
|
|
url: '/:id',
|
|
method: 'GET',
|
|
schema: {
|
|
params: z.object({
|
|
id: z.number(),
|
|
}),
|
|
},
|
|
handler(req) {
|
|
return db.selectFrom('transaction').selectAll().where('id', '=', req.params.id).execute()
|
|
},
|
|
})
|
|
|
|
done()
|
|
}
|
|
|
|
export default transactionRoutes
|