import express, { Request } from "express"; import { getLogin } from "../auth"; import { parseToken, formatDate } from "../utils"; import { generateQr } from "../qr"; import { addPendingQr } from "../pizza"; import { markGroupQrGenerated } from "../groups"; import { emitToUser } from "../websocket"; import { GenerateQrData } from "../../../types"; import crypto from "crypto"; const router = express.Router(); /** * Vygeneruje QR kódy pro platbu vybraným uživatelům. */ router.post("/generate", async (req: Request<{}, any, GenerateQrData["body"]>, res, next) => { const login = getLogin(parseToken(req)); try { const { recipients, bankAccount, bankAccountHolder, groupId } = req.body; if (!recipients || !Array.isArray(recipients) || recipients.length === 0) { return res.status(400).json({ error: "Nebyl předán seznam příjemců" }); } if (!bankAccount) { return res.status(400).json({ error: "Nebylo předáno číslo účtu" }); } if (!bankAccountHolder) { return res.status(400).json({ error: "Nebylo předáno jméno držitele účtu" }); } const today = formatDate(new Date()); for (const recipient of recipients) { if (!recipient.login) { return res.status(400).json({ error: "Příjemce nemá vyplněný login" }); } if (!recipient.purpose || recipient.purpose.trim().length === 0) { return res.status(400).json({ error: `Příjemce ${recipient.login} nemá vyplněný účel platby` }); } if (!Number.isInteger(recipient.amount) || recipient.amount <= 0) { return res.status(400).json({ error: `Příjemce ${recipient.login} má neplatnou částku` }); } // Vygenerovat QR kód const id = crypto.randomUUID(); await generateQr(recipient.login, bankAccount, bankAccountHolder, recipient.amount / 100, recipient.purpose, id); // Uložit jako nevyřízený QR kód a okamžitě doručit příjemci const pendingQr = { id, date: today, creator: login, totalPrice: recipient.amount, purpose: recipient.purpose, ...(groupId ? { groupId } : {}), }; await addPendingQr(recipient.login, pendingQr); emitToUser(recipient.login, 'pendingQr', pendingQr); } if (groupId) { await markGroupQrGenerated(login, groupId); } res.status(200).json({ success: true, count: recipients.length }); } catch (e: any) { next(e); } }); export default router;