brf/server/routes/api/suppliers.ts
2025-12-18 10:20:02 +01:00

66 lines
1.5 KiB
TypeScript

import _ from 'lodash'
import z from 'zod'
import type { FastifyPluginCallbackZod } from 'fastify-type-provider-zod'
import { SupplierSchema } from '../../schemas/db.ts'
const supplierRoutes: FastifyPluginCallbackZod = (fastify, _, done) => {
const { db } = fastify
fastify.route({
url: '/',
method: 'GET',
schema: {
response: {
200: z.array(SupplierSchema),
},
},
handler() {
return db.selectFrom('supplier').selectAll().orderBy('name').execute()
},
})
fastify.route({
url: '/:id',
method: 'GET',
schema: {
params: z.object({ id: z.coerce.number() }),
response: {
200: SupplierSchema,
},
},
handler(req) {
return db.selectFrom('supplier').selectAll().where('id', '=', req.params.id).executeTakeFirst()
},
})
fastify.route({
url: '/merge',
method: 'POST',
schema: {
body: z.object({
ids: z.array(z.number()),
}),
},
async handler(req) {
const suppliers = await db.selectFrom('supplier').selectAll().where('id', 'in', req.body.ids).execute()
const trx = await db.startTransaction().execute()
await trx
.updateTable('invoice')
.set('supplierId', req.body.ids[0])
.where('supplierId', 'in', req.body.ids.slice(1))
.execute()
await trx.deleteFrom('supplier').where('id', 'in', req.body.ids.slice(1)).execute()
await trx.commit().execute()
return suppliers
},
})
done()
}
export default supplierRoutes