Compare commits

...
Author SHA1 Message Date
müde
179a231b58 deploy: add systemd unit + env template, document service setup
also document WUTZ_TZ / WUTZ_DAY_CUTOFF_HOUR env vars
2026-06-14 22:00:13 +02:00
müde
817a560bd6 readme: add fedora setup 2026-06-14 21:58:35 +02:00
müde
2a43b59947 tablet: split price/pfand, light mode, bigger bold text
- show drink price and Pfand separately on tiles and in cart
- add light/dark toggle on the bar-picker page (persisted)
- theme via CSS variables, applied on load for tablet + admin
- larger, bolder text throughout; much bigger total sum
2026-06-14 21:57:52 +02:00
müde
40cdc98f82 admin: fix timestamps, per-day stats, reset, delete drinks/bars
- store created_at as UTC ISO; display/group in Europe/Berlin
- stats grouped by business day (sales night past midnight, 5am cutoff)
- add "Statistik zurücksetzen"
- allow deleting drinks/tresen (refused if referenced by sales)
- CSV exports local wall-clock time
2026-06-14 21:55:51 +02:00
13 changed files with 425 additions and 37 deletions

View file

@ -36,6 +36,17 @@ sudo corepack enable # provides pnpm
sudo apt install -y build-essential python3
```
### Fedora
```sh
# Node 20 + pnpm (corepack ships with the nodejs package)
sudo dnf install -y nodejs
sudo corepack enable # provides pnpm
# Only needed if a prebuilt better-sqlite3 binary is unavailable for your arch
sudo dnf install -y gcc-c++ make python3
```
### Windows
Install Node.js 20 LTS via the official MSI from <https://nodejs.org> (this
@ -70,9 +81,46 @@ ADMIN_PASSWORD=... DB_PATH=/var/lib/wutzcalc/wutz.db node server/dist/index.js
Single Node process serves the API, both client entries (`/` tablet,
`/admin` backoffice), and writes to one SQLite file.
## Run as a systemd service
Template files live in [`deploy/`](deploy/): a unit ([`wutzcalc.service`](deploy/wutzcalc.service))
and an environment file ([`wutzcalc.env.example`](deploy/wutzcalc.env.example)).
They assume the built app lives in `/opt/wutzcalc` and the database in
`/var/lib/wutzcalc` — adjust paths in the unit if yours differ.
```sh
# 1. Dedicated system user (no login, no home)
sudo useradd --system --no-create-home --shell /usr/sbin/nologin wutzcalc
# 2. Install the built app (run `pnpm install && pnpm build` first)
sudo mkdir -p /opt/wutzcalc
sudo cp -a . /opt/wutzcalc # or rsync/checkout into place
sudo chown -R root:root /opt/wutzcalc # app dir stays read-only to the service
# 3. Config + secrets (chmod 600 — holds ADMIN_PASSWORD)
sudo mkdir -p /etc/wutzcalc
sudo install -m 600 deploy/wutzcalc.env.example /etc/wutzcalc/wutzcalc.env
sudoedit /etc/wutzcalc/wutzcalc.env # set ADMIN_PASSWORD
# 4. Install and start the unit
sudo cp deploy/wutzcalc.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now wutzcalc
# Logs / status
systemctl status wutzcalc
journalctl -u wutzcalc -f
```
Confirm `ExecStart` matches your Node path (`command -v node`) — it defaults to
`/usr/bin/node`. The unit creates `/var/lib/wutzcalc` via `StateDirectory`, so
the service user owns the database directory automatically.
## Env vars
- `PORT` (default `3000`)
- `HOST` (default `0.0.0.0`)
- `DB_PATH` (default `./wutz.db`)
- `ADMIN_PASSWORD` (**required** for backoffice login)
- `WUTZ_TZ` (default `Europe/Berlin`) — timezone for stats display and grouping
- `WUTZ_DAY_CUTOFF_HOUR` (default `5`) — sales before this local hour count toward the previous business day

View file

@ -10,6 +10,7 @@ interface Drink { id: number; name: string; price_cents: number; archived: numbe
interface BarRow { id: number; name: string; pfand_cents: number; drink_ids: number[] }
interface Totals { bar_id: number; bar_name: string; tx_count: number; paid_cents: number; crew_count: number; pfand_returns: number }
interface PerDrink { drink_id: number; drink_name: string; sold_qty: number }
interface ByDay { day: string; tx_count: number; paid_cents: number; crew_count: number; pfand_returns: number }
export function Admin() {
const [authed, setAuthed] = useState<boolean | null>(null);
@ -76,12 +77,44 @@ function Dashboard({ onLogout }: { onLogout: () => void }) {
);
}
function fmtDay(day: string): string {
const [y, m, d] = day.split('-');
return `${d}.${m}.${y}`;
}
function Stats() {
const [data, setData] = useState<{ totals: Totals[]; per_drink: PerDrink[] } | null>(null);
useEffect(() => { fetch('/admin/api/stats').then(j).then(setData); }, []);
const [data, setData] = useState<{ totals: Totals[]; per_drink: PerDrink[]; by_day: ByDay[] } | null>(null);
function reload() { fetch('/admin/api/stats').then(j).then(setData); }
useEffect(reload, []);
async function reset() {
if (!confirm('Wirklich die gesamte Statistik (alle Transaktionen) unwiderruflich löschen?')) return;
await fetch('/admin/api/stats/reset', { method: 'POST' });
reload();
}
if (!data) return <p>Lade Statistik</p>;
return (
<>
<div class="row" style="justify-content: space-between">
<h2 style="margin:0">Umsatz nach Tagen</h2>
<button onClick={reset} style="background:#5a2a2a; border-color:#7a3a3a">Statistik zurücksetzen</button>
</div>
<table>
<thead><tr><th>Tag</th><th>Transaktionen</th><th>Bezahlt</th><th>Crew-Transaktionen</th><th>Pfand zurück</th></tr></thead>
<tbody>
{data.by_day.length === 0 && <tr><td colSpan={5} class="muted">Noch keine Verkäufe</td></tr>}
{data.by_day.map(d => (
<tr key={d.day}>
<td>{fmtDay(d.day)}</td>
<td>{d.tx_count}</td>
<td>{formatCents(d.paid_cents)}</td>
<td>{d.crew_count}</td>
<td>{d.pfand_returns}</td>
</tr>
))}
</tbody>
</table>
<h2>Umsatz pro Bar</h2>
<table>
<thead><tr><th>Bar</th><th>Transaktionen</th><th>Bezahlt</th><th>Crew-Transaktionen</th><th>Pfand zurück</th></tr></thead>
@ -153,6 +186,13 @@ function Drinks() {
reload();
}
async function del(d: Drink) {
if (!confirm(`Getränk „${d.name}“ wirklich löschen?`)) return;
const res = await fetch(`/admin/api/drinks/${d.id}`, { method: 'DELETE' });
if (!res.ok) { alert(`Fehler: ${(await res.json().catch(() => null))?.error ?? await res.text()}`); return; }
reload();
}
return (
<>
<h2>Getränke</h2>
@ -174,9 +214,12 @@ function Drinks() {
</td>
<td class={d.archived ? 'muted' : ''}>{d.archived ? 'archiviert' : 'aktiv'}</td>
<td>
<button onClick={() => patch(d.id, { archived: !d.archived } as any)}>
{d.archived ? 'aktivieren' : 'archivieren'}
</button>
<div class="row" style="margin:0">
<button onClick={() => patch(d.id, { archived: !d.archived } as any)}>
{d.archived ? 'aktivieren' : 'archivieren'}
</button>
<button onClick={() => del(d)} style="background:#5a2a2a; border-color:#7a3a3a">löschen</button>
</div>
</td>
</tr>
))}
@ -298,6 +341,13 @@ function Bars() {
reload();
}
async function delBar(b: BarRow) {
if (!confirm(`Tresen „${b.name}“ wirklich löschen?`)) return;
const res = await fetch(`/admin/api/bars/${b.id}`, { method: 'DELETE' });
if (!res.ok) { alert(`Fehler: ${(await res.json().catch(() => null))?.error ?? await res.text()}`); return; }
reload();
}
async function addBar() {
const name = newName.trim();
if (!name) return;
@ -338,6 +388,7 @@ function Bars() {
}
/>
</label>
<button onClick={() => delBar(b)} style="background:#5a2a2a; border-color:#7a3a3a; margin-left:auto">Tresen löschen</button>
</div>
<BarDrinkEditor
bar={b}

View file

@ -1,4 +1,6 @@
import { render } from 'preact';
import { Admin } from './Admin';
import { applyTheme } from '../api';
applyTheme();
render(<Admin />, document.getElementById('app')!);

View file

@ -27,6 +27,22 @@ export function formatCents(cents: number): string {
return `${sign}${(abs / 100).toFixed(2)}`;
}
export type Theme = 'dark' | 'light';
const THEME_KEY = 'wutz.theme';
export function getTheme(): Theme {
return localStorage.getItem(THEME_KEY) === 'light' ? 'light' : 'dark';
}
export function applyTheme(t: Theme = getTheme()): void {
document.documentElement.setAttribute('data-theme', t);
}
export function setTheme(t: Theme): void {
localStorage.setItem(THEME_KEY, t);
applyTheme(t);
}
export function uuid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
return (crypto as any).randomUUID();

View file

@ -1,12 +1,37 @@
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
:root {
--bg: #111;
--fg: #eee;
--surface: #1a1a1a;
--surface-2: #2a2a2a;
--surface-3: #3a3a3a;
--border: #444;
--border-soft: #333;
--pfand: #9ab;
--danger: #ff8a8a;
}
:root[data-theme="light"] {
--bg: #f4f4f5;
--fg: #18181b;
--surface: #ffffff;
--surface-2: #e7e7ea;
--surface-3: #d8d8dc;
--border: #bcbcc2;
--border-soft: #dddde2;
--pfand: #4a6a8a;
--danger: #c0392b;
}
html, body, #app {
margin: 0;
padding: 0;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #111;
color: #eee;
background: var(--bg);
color: var(--fg);
font-weight: 600;
overscroll-behavior: none;
-webkit-user-select: none;
user-select: none;
@ -14,14 +39,15 @@ html, body, #app {
button {
font: inherit;
font-weight: 700;
color: inherit;
background: #2a2a2a;
border: 1px solid #444;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
cursor: pointer;
}
button:active { background: #3a3a3a; }
button:active { background: var(--surface-3); }
button:disabled { opacity: 0.4; }
/* ---------- Tablet UI (portrait) ---------- */
@ -47,7 +73,14 @@ button:disabled { opacity: 0.4; }
.bar-picker button {
width: 280px;
height: 96px;
font-size: 28px;
font-size: 30px;
}
.theme-toggle {
margin-top: 24px;
background: transparent;
border: 1px solid var(--border);
font-size: 18px;
padding: 10px 18px;
}
.topbar {
@ -55,12 +88,12 @@ button:disabled { opacity: 0.4; }
justify-content: space-between;
align-items: center;
padding: 10px 16px;
background: #1a1a1a;
border-bottom: 1px solid #333;
background: var(--surface);
border-bottom: 1px solid var(--border-soft);
flex: 0 0 auto;
}
.topbar .bar-name { font-size: 20px; font-weight: bold; }
.topbar .change { font-size: 14px; padding: 8px 12px; }
.topbar .bar-name { font-size: 26px; font-weight: 800; }
.topbar .change { font-size: 17px; padding: 10px 14px; }
/* Drink grid fills available space with no scrolling tiles auto-size to fit.
3 columns on portrait iPad (~768px); rows divide the remaining height equally. */
@ -86,20 +119,22 @@ button:disabled { opacity: 0.4; }
align-items: center;
text-align: center;
padding: 8px;
font-size: 18px;
font-size: 22px;
}
.drink .name { font-weight: bold; line-height: 1.2; }
.drink .price { font-size: 14px; opacity: 0.7; margin-top: 6px; }
.drink .name { font-weight: 800; line-height: 1.15; }
.drink .price { font-size: 22px; font-weight: 700; margin-top: 6px; }
.drink .pfand { font-size: 15px; font-weight: 600; color: var(--pfand); margin-top: 2px; }
.drink.pfand-return {
background: #5a2a2a;
border-color: #7a3a3a;
color: #fff;
}
.cart {
flex: 0 0 38vh;
background: #1a1a1a;
border-top: 1px solid #333;
background: var(--surface);
border-top: 1px solid var(--border-soft);
padding: 8px 16px;
display: flex;
flex-direction: column;
@ -118,17 +153,20 @@ button:disabled { opacity: 0.4; }
display: flex;
justify-content: space-between;
padding: 3px 0;
font-size: 16px;
font-size: 20px;
font-weight: 600;
}
.cart-line.return { color: #ff8a8a; }
.cart-line.pfand { color: var(--pfand); }
.cart-line.return { color: var(--danger); }
.cart-line.muted { opacity: 0.5; }
.cart-total {
font-size: 26px;
font-weight: bold;
font-size: 56px;
font-weight: 800;
text-align: right;
line-height: 1.1;
padding: 4px 0 8px;
}
.cart-total.negative { color: #ff8a8a; }
.cart-total.negative { color: var(--danger); }
.actions {
display: flex;
@ -137,7 +175,9 @@ button:disabled { opacity: 0.4; }
.actions button {
flex: 1;
height: 64px;
font-size: 18px;
font-size: 22px;
font-weight: 800;
color: #fff;
}
.actions .cancel { background: #5a2a2a; border-color: #7a3a3a; }
.actions .confirm { background: #2a5a2a; border-color: #3a7a3a; }
@ -152,9 +192,9 @@ button:disabled { opacity: 0.4; }
}
.admin h1, .admin h2 { margin-top: 24px; }
.admin table { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
.admin th, .admin td { padding: 6px 8px; border-bottom: 1px solid #333; text-align: left; }
.admin th, .admin td { padding: 6px 8px; border-bottom: 1px solid var(--border-soft); text-align: left; }
.admin input, .admin select {
background: #1a1a1a; color: #eee; border: 1px solid #444; border-radius: 4px; padding: 6px;
background: var(--surface); color: var(--fg); border: 1px solid var(--border); border-radius: 4px; padding: 6px;
}
.admin .row { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; flex-wrap: wrap; }
.admin .muted { opacity: 0.6; }
@ -167,8 +207,8 @@ button:disabled { opacity: 0.4; }
gap: 8px;
padding: 6px 8px;
margin-bottom: 4px;
background: #1a1a1a;
border: 1px solid #333;
background: var(--surface);
border: 1px solid var(--border-soft);
border-radius: 6px;
cursor: grab;
}

View file

@ -1,4 +1,6 @@
import { useState } from 'preact/hooks';
import type { Bar } from '@wutzcalc/shared';
import { getTheme, setTheme } from '../api';
interface Props {
bars: Bar[] | null;
@ -6,6 +8,14 @@ interface Props {
}
export function BarPicker({ bars, onPick }: Props) {
const [theme, setThemeState] = useState(getTheme());
function toggleTheme() {
const next = theme === 'dark' ? 'light' : 'dark';
setTheme(next);
setThemeState(next);
}
return (
<div class="bar-picker">
<h1>Bar auswählen</h1>
@ -18,6 +28,9 @@ export function BarPicker({ bars, onPick }: Props) {
</button>
))
)}
<button class="theme-toggle" onClick={toggleTheme}>
{theme === 'dark' ? '☀ Heller Modus' : '🌙 Dunkler Modus'}
</button>
</div>
);
}

View file

@ -51,6 +51,8 @@ export function Sale({ config, onChangeBar }: Props) {
setPfandReturns(0);
}
const pfandCount = useMemo(() => lines.reduce((sum, l) => sum + l.qty, 0), [lines]);
const isEmpty = lines.length === 0 && pfandReturns === 0;
async function confirm(crew: boolean) {
@ -84,7 +86,10 @@ export function Sale({ config, onChangeBar }: Props) {
{drinks.map(d => (
<button key={d.id} class="drink" onClick={() => addDrink(d.id)}>
<div class="name">{d.name}</div>
<div class="price">{formatCents(d.price_cents + bar.pfand_cents)}</div>
<div class="price">{formatCents(d.price_cents)}</div>
{bar.pfand_cents > 0 && (
<div class="pfand">+ {formatCents(bar.pfand_cents)} Pfand</div>
)}
</button>
))}
<button class="drink pfand-return" onClick={addPfandReturn}>
@ -99,14 +104,19 @@ export function Sale({ config, onChangeBar }: Props) {
{lines.map((l, i) => {
const d = drinkById.get(l.drink_id);
if (!d) return null;
const unit = d.price_cents + bar.pfand_cents;
return (
<div key={i} class="cart-line">
<span>{l.qty}× {d.name}</span>
<span>{formatCents(unit * l.qty)}</span>
<span>{formatCents(d.price_cents * l.qty)}</span>
</div>
);
})}
{bar.pfand_cents > 0 && pfandCount > 0 && (
<div class="cart-line pfand">
<span>{pfandCount}× Pfand</span>
<span>{formatCents(bar.pfand_cents * pfandCount)}</span>
</div>
)}
{pfandReturns > 0 && (
<div class="cart-line return">
<span>{pfandReturns}× Pfand zurück</span>

View file

@ -1,4 +1,6 @@
import { render } from 'preact';
import { App } from './App';
import { applyTheme } from '../api';
applyTheme();
render(<App />, document.getElementById('app')!);

View file

@ -0,0 +1,18 @@
# Copy to /etc/wutzcalc/wutzcalc.env and edit.
# Keep it readable only by root / the service user — it holds the admin password:
# sudo install -m 600 -o root -g root deploy/wutzcalc.env.example /etc/wutzcalc/wutzcalc.env
# Required: backoffice login password.
ADMIN_PASSWORD=changeme
# SQLite database file. With StateDirectory=wutzcalc this dir is created for you.
DB_PATH=/var/lib/wutzcalc/wutz.db
# Network bind (defaults: 0.0.0.0:3000).
PORT=3000
HOST=0.0.0.0
# Sales-day handling (defaults shown). Hours before the cutoff count toward the
# previous business day, so a 03:00 sale lands on the night before.
#WUTZ_TZ=Europe/Berlin
#WUTZ_DAY_CUTOFF_HOUR=5

38
deploy/wutzcalc.service Normal file
View file

@ -0,0 +1,38 @@
[Unit]
Description=wutzcalc — festival drink-sale tracker
Documentation=https://git.berlin.ccc.de/vinzenz/wutzcalc
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=wutzcalc
Group=wutzcalc
# Where `pnpm build` was run — adjust to your install location.
WorkingDirectory=/opt/wutzcalc
# `which node` may differ (e.g. /usr/local/bin/node or an nvm path).
ExecStart=/usr/bin/node server/dist/index.js
# Secrets and config live here, not in the unit. See wutzcalc.env.example.
EnvironmentFile=/etc/wutzcalc/wutzcalc.env
Restart=on-failure
RestartSec=5
# Creates/owns /var/lib/wutzcalc — point DB_PATH there.
StateDirectory=wutzcalc
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ReadWritePaths=/var/lib/wutzcalc
[Install]
WantedBy=multi-user.target

View file

@ -1,5 +1,6 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import type { DB } from '../db.js';
import { businessDay, formatLocal, parseDbTime } from '../time.js';
const SESSION_COOKIE = 'wutz_admin';
@ -76,6 +77,24 @@ export function registerAdminRoutes(app: FastifyInstance, db: DB) {
}
);
app.delete<{ Params: { id: string } }>('/admin/api/drinks/:id', async (req, reply) => {
if (!requireAuth(req, reply)) return;
const id = Number(req.params.id);
const sold = db
.prepare('SELECT 1 FROM transaction_items WHERE drink_id = ? LIMIT 1')
.get(id);
if (sold) {
return reply
.code(409)
.send({ error: 'Getränk wurde bereits verkauft — bitte archivieren statt löschen.' });
}
db.transaction(() => {
db.prepare('DELETE FROM bar_drinks WHERE drink_id = ?').run(id);
db.prepare('DELETE FROM drinks WHERE id = ?').run(id);
})();
return { ok: true };
});
// ----- Bars -----
app.get('/admin/api/bars', async (req, reply) => {
if (!requireAuth(req, reply)) return;
@ -145,6 +164,24 @@ export function registerAdminRoutes(app: FastifyInstance, db: DB) {
}
);
app.delete<{ Params: { id: string } }>('/admin/api/bars/:id', async (req, reply) => {
if (!requireAuth(req, reply)) return;
const id = Number(req.params.id);
const used = db
.prepare('SELECT 1 FROM transactions WHERE bar_id = ? LIMIT 1')
.get(id);
if (used) {
return reply
.code(409)
.send({ error: 'Tresen hat Transaktionen — Löschen würde die Statistik verfälschen.' });
}
db.transaction(() => {
db.prepare('DELETE FROM bar_drinks WHERE bar_id = ?').run(id);
db.prepare('DELETE FROM bars WHERE id = ?').run(id);
})();
return { ok: true };
});
// ----- Stats -----
app.get('/admin/api/stats', async (req, reply) => {
if (!requireAuth(req, reply)) return;
@ -174,7 +211,36 @@ export function registerAdminRoutes(app: FastifyInstance, db: DB) {
)
.all();
return { totals, per_drink: perDrink };
// Per business day (sales night runs past midnight — see time.ts).
const txRows = db
.prepare('SELECT created_at, total_cents, crew, pfand_returns FROM transactions')
.all() as Array<{ created_at: string; total_cents: number; crew: number; pfand_returns: number }>;
const dayMap = new Map<string, { day: string; tx_count: number; paid_cents: number; crew_count: number; pfand_returns: number }>();
for (const r of txRows) {
const day = businessDay(parseDbTime(r.created_at));
let agg = dayMap.get(day);
if (!agg) {
agg = { day, tx_count: 0, paid_cents: 0, crew_count: 0, pfand_returns: 0 };
dayMap.set(day, agg);
}
agg.tx_count += 1;
if (r.crew) agg.crew_count += 1;
else agg.paid_cents += r.total_cents;
agg.pfand_returns += r.pfand_returns;
}
const byDay = [...dayMap.values()].sort((a, b) => b.day.localeCompare(a.day));
return { totals, per_drink: perDrink, by_day: byDay };
});
app.post('/admin/api/stats/reset', async (req, reply) => {
if (!requireAuth(req, reply)) return;
db.transaction(() => {
db.prepare('DELETE FROM transaction_items').run();
db.prepare('DELETE FROM transactions').run();
})();
return { ok: true };
});
// ----- CSV export -----
@ -211,6 +277,11 @@ export function registerAdminRoutes(app: FastifyInstance, db: DB) {
.all() as any[];
}
// created_at is stored as UTC — export it as local wall-clock time.
for (const r of rows) {
if (r.created_at) r.created_at = formatLocal(parseDbTime(r.created_at));
}
const csv = [header.join(',')]
.concat(rows.map(r => header.map(h => csvCell(r[h])).join(',')))
.join('\n');

View file

@ -108,8 +108,8 @@ export function registerPublicRoutes(app: FastifyInstance, db: DB) {
const clientIp = req.ip ?? null;
const insertTx = db.prepare(
`INSERT INTO transactions (bar_id, total_cents, crew, pfand_returns, client_ip, client_uuid)
VALUES (?, ?, ?, ?, ?, ?)`
`INSERT INTO transactions (bar_id, created_at, total_cents, crew, pfand_returns, client_ip, client_uuid)
VALUES (?, ?, ?, ?, ?, ?, ?)`
);
const insertItem = db.prepare(
`INSERT INTO transaction_items
@ -117,8 +117,9 @@ export function registerPublicRoutes(app: FastifyInstance, db: DB) {
VALUES (?, ?, ?, ?, ?, 0)`
);
const createdAt = new Date().toISOString();
const txId = db.transaction(() => {
const info = insertTx.run(bar_id, paidTotal, crew ? 1 : 0, pfand_returns, clientIp, client_uuid);
const info = insertTx.run(bar_id, createdAt, paidTotal, crew ? 1 : 0, pfand_returns, clientIp, client_uuid);
const id = Number(info.lastInsertRowid);
for (const p of priced) {
insertItem.run(id, p.drink_id, p.qty, p.unit_price_cents, p.pfand_cents_per_unit);

78
server/src/time.ts Normal file
View file

@ -0,0 +1,78 @@
// Time handling for the sales day.
//
// Timestamps are stored in the DB as UTC ISO strings (`new Date().toISOString()`).
// For display and for grouping into business days we convert to a fixed local
// timezone (default Europe/Berlin) so the numbers match the bar's wall clock
// regardless of where the server runs.
export const TZ = process.env.WUTZ_TZ ?? 'Europe/Berlin';
// A sale at e.g. 03:00 still belongs to the previous night's business day.
// Anything before this local hour counts towards the day before.
export const BUSINESS_DAY_CUTOFF_HOUR = Number(process.env.WUTZ_DAY_CUTOFF_HOUR ?? 5);
/**
* Parse a value stored in `created_at`. New rows are UTC ISO strings (with `Z`),
* but legacy rows written by SQLite's CURRENT_TIMESTAMP look like
* `YYYY-MM-DD HH:MM:SS` and are also UTC normalise both to a Date.
*/
export function parseDbTime(s: string): Date {
if (/[zZ]|[+-]\d{2}:\d{2}$/.test(s)) return new Date(s);
return new Date(s.replace(' ', 'T') + 'Z');
}
interface LocalParts {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
}
function localParts(d: Date, tz: string = TZ): LocalParts {
const fmt = new Intl.DateTimeFormat('en-CA', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
const parts: Record<string, string> = {};
for (const p of fmt.formatToParts(d)) {
if (p.type !== 'literal') parts[p.type] = p.value;
}
return {
year: Number(parts.year),
month: Number(parts.month),
day: Number(parts.day),
hour: Number(parts.hour === '24' ? '0' : parts.hour),
minute: Number(parts.minute),
second: Number(parts.second),
};
}
/** Local wall-clock time as `YYYY-MM-DD HH:MM:SS` for CSV / display. */
export function formatLocal(d: Date, tz: string = TZ): string {
const p = localParts(d, tz);
const pad = (n: number) => String(n).padStart(2, '0');
return `${p.year}-${pad(p.month)}-${pad(p.day)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)}`;
}
/**
* The business day a timestamp belongs to, as `YYYY-MM-DD`.
* Hours before BUSINESS_DAY_CUTOFF_HOUR are attributed to the previous day.
*/
export function businessDay(d: Date, tz: string = TZ): string {
const p = localParts(d, tz);
// Build a date from the local Y-M-D and roll back a day when before cutoff.
const date = new Date(Date.UTC(p.year, p.month - 1, p.day));
if (p.hour < BUSINESS_DAY_CUTOFF_HOUR) {
date.setUTCDate(date.getUTCDate() - 1);
}
const pad = (n: number) => String(n).padStart(2, '0');
return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
}