Learn by Directing AI
All materials

batches.ts

tsbatches.ts
import { Router, Request, Response } from 'express'
import { prisma } from '../lib/db'
import { requireAuth } from '../lib/auth'

const router = Router()

router.get('/', requireAuth, async (_req: Request, res: Response) => {
  try {
    const batches = await prisma.batch.findMany({
      include: { cooperative: true },
      orderBy: { date_reception: 'desc' },
    })
    res.json(batches)
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch batches' })
  }
})

router.get('/:id', requireAuth, async (req: Request, res: Response) => {
  try {
    const batch = await prisma.batch.findUnique({
      where: { id: parseInt(req.params.id) },
      include: {
        cooperative: true,
        quality_checks: true,
        shipment_items: { include: { shipment: true } },
      },
    })
    if (!batch) {
      return res.status(404).json({ error: 'Batch not found' })
    }
    res.json(batch)
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch batch' })
  }
})

router.post('/', requireAuth, async (req: Request, res: Response) => {
  try {
    const { cooperative_id, date_reception, poids_brut, variete, notes } = req.body
    const batch = await prisma.batch.create({
      data: {
        cooperative_id,
        date_reception: new Date(date_reception),
        poids_brut,
        variete,
        notes,
      },
    })
    res.status(201).json(batch)
  } catch (error) {
    res.status(500).json({ error: 'Failed to create batch' })
  }
})

router.patch('/:id', requireAuth, async (req: Request, res: Response) => {
  try {
    const { stage, net_weight, grade_qualite, notes } = req.body
    const batch = await prisma.batch.update({
      where: { id: parseInt(req.params.id) },
      data: { stage, net_weight, grade_qualite, notes },
    })
    res.json(batch)
  } catch (error) {
    res.status(500).json({ error: 'Failed to update batch' })
  }
})

export default router