scaffold festival drink tracker (pnpm workspace, Fastify + SQLite, Preact tablet UI, admin)

This commit is contained in:
müde 2026-05-19 18:12:01 +02:00
commit e0898bea22
34 changed files with 5446 additions and 0 deletions

196
server/src/routes/admin.ts Normal file
View file

@ -0,0 +1,196 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import type { DB } from '../db.js';
const SESSION_COOKIE = 'wutz_admin';
function isAuthed(req: FastifyRequest): boolean {
const expected = process.env.ADMIN_PASSWORD;
if (!expected) return false;
return req.cookies?.[SESSION_COOKIE] === expected;
}
function requireAuth(req: FastifyRequest, reply: FastifyReply): boolean {
if (isAuthed(req)) return true;
reply.code(401).send({ error: 'unauthorized' });
return false;
}
export function registerAdminRoutes(app: FastifyInstance, db: DB) {
app.post<{ Body: { password?: string } }>('/admin/login', async (req, reply) => {
const expected = process.env.ADMIN_PASSWORD;
if (!expected) return reply.code(500).send({ error: 'ADMIN_PASSWORD not set' });
if (req.body?.password !== expected) return reply.code(401).send({ error: 'wrong password' });
reply.setCookie(SESSION_COOKIE, expected, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7,
});
return { ok: true };
});
app.post('/admin/logout', async (_req, reply) => {
reply.clearCookie(SESSION_COOKIE, { path: '/' });
return { ok: true };
});
app.get('/admin/api/me', async (req) => ({ authed: isAuthed(req) }));
// ----- Drinks -----
app.get('/admin/api/drinks', async (req, reply) => {
if (!requireAuth(req, reply)) return;
return db
.prepare('SELECT id, name, price_cents, archived FROM drinks ORDER BY archived, id')
.all();
});
app.post<{ Body: { name: string; price_cents: number } }>(
'/admin/api/drinks',
async (req, reply) => {
if (!requireAuth(req, reply)) return;
const { name, price_cents } = req.body ?? ({} as any);
if (!name || !Number.isInteger(price_cents))
return reply.code(400).send({ error: 'invalid' });
const info = db
.prepare('INSERT INTO drinks (name, price_cents) VALUES (?, ?)')
.run(name, price_cents);
return { id: Number(info.lastInsertRowid) };
}
);
app.patch<{ Params: { id: string }; Body: { name?: string; price_cents?: number; archived?: boolean } }>(
'/admin/api/drinks/:id',
async (req, reply) => {
if (!requireAuth(req, reply)) return;
const id = Number(req.params.id);
const { name, price_cents, archived } = req.body ?? {};
const sets: string[] = [];
const args: any[] = [];
if (name !== undefined) { sets.push('name = ?'); args.push(name); }
if (price_cents !== undefined) { sets.push('price_cents = ?'); args.push(price_cents); }
if (archived !== undefined) { sets.push('archived = ?'); args.push(archived ? 1 : 0); }
if (sets.length === 0) return { ok: true };
args.push(id);
db.prepare(`UPDATE drinks SET ${sets.join(', ')} WHERE id = ?`).run(...args);
return { ok: true };
}
);
// ----- Bars -----
app.get('/admin/api/bars', async (req, reply) => {
if (!requireAuth(req, reply)) return;
const bars = db.prepare('SELECT id, name, pfand_cents FROM bars ORDER BY id').all() as any[];
const drinkRows = db
.prepare('SELECT bar_id, drink_id, sort_order FROM bar_drinks ORDER BY sort_order, drink_id')
.all() as any[];
return bars.map(b => ({
...b,
drink_ids: drinkRows.filter(d => d.bar_id === b.id).map(d => d.drink_id),
}));
});
app.patch<{ Params: { id: string }; Body: { pfand_cents?: number; drink_ids?: number[] } }>(
'/admin/api/bars/:id',
async (req, reply) => {
if (!requireAuth(req, reply)) return;
const id = Number(req.params.id);
const { pfand_cents, drink_ids } = req.body ?? {};
db.transaction(() => {
if (pfand_cents !== undefined) {
db.prepare('UPDATE bars SET pfand_cents = ? WHERE id = ?').run(pfand_cents, id);
}
if (Array.isArray(drink_ids)) {
db.prepare('DELETE FROM bar_drinks WHERE bar_id = ?').run(id);
const ins = db.prepare(
'INSERT INTO bar_drinks (bar_id, drink_id, sort_order) VALUES (?, ?, ?)'
);
drink_ids.forEach((did, idx) => ins.run(id, did, idx));
}
})();
return { ok: true };
}
);
// ----- Stats -----
app.get('/admin/api/stats', async (req, reply) => {
if (!requireAuth(req, reply)) return;
const totals = db
.prepare(
`SELECT b.id AS bar_id, b.name AS bar_name,
COUNT(*) AS tx_count,
COALESCE(SUM(CASE WHEN crew = 0 THEN total_cents ELSE 0 END), 0) AS paid_cents,
COALESCE(SUM(CASE WHEN crew = 1 THEN 1 ELSE 0 END), 0) AS crew_count,
COALESCE(SUM(pfand_returns), 0) AS pfand_returns
FROM transactions t
JOIN bars b ON b.id = t.bar_id
GROUP BY b.id, b.name
ORDER BY b.id`
)
.all();
const perDrink = db
.prepare(
`SELECT d.id AS drink_id, d.name AS drink_name,
COALESCE(SUM(ti.qty), 0) AS sold_qty
FROM transaction_items ti
JOIN drinks d ON d.id = ti.drink_id
GROUP BY d.id, d.name
ORDER BY sold_qty DESC, d.id`
)
.all();
return { totals, per_drink: perDrink };
});
// ----- CSV export -----
app.get<{ Querystring: { what?: string } }>('/admin/api/export.csv', async (req, reply) => {
if (!requireAuth(req, reply)) return;
const what = req.query.what === 'items' ? 'items' : 'transactions';
let rows: any[];
let header: string[];
if (what === 'transactions') {
header = ['id', 'bar_id', 'bar_name', 'created_at', 'total_cents', 'crew', 'pfand_returns', 'client_ip', 'client_uuid'];
rows = db
.prepare(
`SELECT t.id, t.bar_id, b.name AS bar_name, t.created_at, t.total_cents,
t.crew, t.pfand_returns, t.client_ip, t.client_uuid
FROM transactions t JOIN bars b ON b.id = t.bar_id
ORDER BY t.id`
)
.all() as any[];
} else {
header = [
'transaction_id', 'bar_id', 'created_at', 'drink_id', 'drink_name',
'qty', 'unit_price_cents', 'pfand_cents_per_unit',
];
rows = db
.prepare(
`SELECT ti.transaction_id, t.bar_id, t.created_at, ti.drink_id, d.name AS drink_name,
ti.qty, ti.unit_price_cents, ti.pfand_cents_per_unit
FROM transaction_items ti
JOIN transactions t ON t.id = ti.transaction_id
JOIN drinks d ON d.id = ti.drink_id
ORDER BY ti.transaction_id, ti.id`
)
.all() as any[];
}
const csv = [header.join(',')]
.concat(rows.map(r => header.map(h => csvCell(r[h])).join(',')))
.join('\n');
reply
.header('Content-Type', 'text/csv; charset=utf-8')
.header('Content-Disposition', `attachment; filename="${what}.csv"`)
.send(csv);
});
}
function csvCell(v: unknown): string {
if (v === null || v === undefined) return '';
const s = String(v);
if (/[",\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
return s;
}