101 lines
3.0 KiB
TypeScript
101 lines
3.0 KiB
TypeScript
import _ from 'lodash'
|
|
import { Type, 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 financialYears = await knex('financialYear').select('*').orderBy('year', 'asc')
|
|
|
|
return knex('transaction AS t')
|
|
.select(
|
|
't.accountNumber',
|
|
'a.description',
|
|
Object.fromEntries(
|
|
financialYears.map((fy) => [
|
|
fy.year,
|
|
knex.raw(`SUM(CASE WHEN fy.year = ${fy.year} THEN t.amount ELSE 0 END)`),
|
|
]),
|
|
),
|
|
)
|
|
.sum('t.amount AS amount')
|
|
.innerJoin('entry AS e', function () {
|
|
this.on('t.entryId', '=', 'e.id')
|
|
})
|
|
.innerJoin('financialYear AS fy', 'fy.id', 'e.financialYearId')
|
|
.innerJoin('account AS a', function () {
|
|
this.on('t.accountNumber', '=', 'a.number')
|
|
})
|
|
.groupBy('t.accountNumber', 'a.description')
|
|
.where('t.accountNumber', '>=', 3000)
|
|
.orderBy('t.accountNumber')
|
|
},
|
|
// 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
|