diff --git a/.env.selfhost.example b/.env.selfhost.example index c1d6d4df..a90c11e8 100644 --- a/.env.selfhost.example +++ b/.env.selfhost.example @@ -11,7 +11,7 @@ POSTGRES_PASSWORD= ACME_EMAIL=admin@example.org # Release von BazarPro, siehe https://github.com/BazarPro/core/releases -BAZARPRO_VERSION=v2.2.0 +BAZARPRO_VERSION=v2.3.0 # single: ein Verein mit eigenen Basaren (Standard) # platform: mehrere Veranstalter wie auf bazarpro.de, mit Werbeseiten diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 138753f9..882119c2 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -312,7 +312,6 @@ jobs: build-args: | BACKEND_URL=https://${{ secrets.DOMAIN_NAME }} DOMAIN_NAME=${{ secrets.DOMAIN_NAME }} - VITE_PLAUSIBLE_API_HOST=${{ vars.VITE_PLAUSIBLE_API_HOST || secrets.VITE_PLAUSIBLE_API_HOST }} VITE_SITE_URL=${{ steps.meta.outputs.site_url }} VITE_APP_VERSION=${{ steps.meta.outputs.version }} # Backend for production, review apps and self-hosters (docker-compose.selfhost.yml) @@ -353,6 +352,7 @@ jobs: CLOUDFLARE_DNS_API_TOKEN: ${{ secrets.CLOUDFLARE_DNS_API_TOKEN }} DOMAIN_NAME: ${{ vars.DOMAIN_NAME || secrets.DOMAIN_NAME }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} + PLAUSIBLE_API_HOST: ${{ vars.VITE_PLAUSIBLE_API_HOST || secrets.VITE_PLAUSIBLE_API_HOST }} ADMIN_EMAIL: ${{ vars.ADMIN_EMAIL || secrets.ADMIN_EMAIL }} AUTH_SMTP_HOST: ${{ vars.AUTH_SMTP_HOST || secrets.AUTH_SMTP_HOST }} AUTH_SMTP_PORT: ${{ vars.AUTH_SMTP_PORT || secrets.AUTH_SMTP_PORT }} diff --git a/Dockerfile b/Dockerfile index 3a69c4e5..7df04986 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,12 +15,10 @@ COPY . . # https://bazarpro.de (its /api); without it they are rendered without data ARG BACKEND_URL ARG DOMAIN_NAME -ARG VITE_PLAUSIBLE_API_HOST ARG VITE_SITE_URL ARG VITE_APP_VERSION ENV BACKEND_URL=$BACKEND_URL ENV DOMAIN_NAME=$DOMAIN_NAME -ENV VITE_PLAUSIBLE_API_HOST=$VITE_PLAUSIBLE_API_HOST ENV VITE_SITE_URL=$VITE_SITE_URL ENV VITE_APP_VERSION=$VITE_APP_VERSION @@ -47,6 +45,8 @@ COPY server ./server # Code the web server shares with the app (server/dockerfile.test.ts checks the list) COPY src/lib/markdown.ts ./src/lib/markdown.ts COPY src/shared/productLinks.ts ./src/shared/productLinks.ts +COPY src/shared/appRoutes.ts ./src/shared/appRoutes.ts +COPY src/shared/eventJsonLd.ts ./src/shared/eventJsonLd.ts COPY --from=builder /app/dist ./dist USER node diff --git a/ENV.md b/ENV.md index 67f1dd03..36288fa1 100644 --- a/ENV.md +++ b/ENV.md @@ -8,17 +8,15 @@ domain at `/api`: Traefik routes it in production, Vite proxies it in developmen These variables must start with `VITE_` to be accessible in the browser. -| Variable | Required | Description | -| :------------------------ | :------- | :------------------------------------------------------------------------------------------------------- | -| `VITE_SITE_URL` | No | The public URL of the application (e.g., `https://bazarpro.de`). Used for SEO and absolute links. | -| `VITE_BAZARPRO_MODE` | No | `single` to try the self-hosting mode with `vite dev`. In production the server injects `BAZARPRO_MODE`. | -| `DOMAIN_NAME` | No | Base domain used for routing and Plausible analytics. Defaults to `localhost`. | -| `VITE_PLAUSIBLE_API_HOST` | No | API host for self-hosted Plausible Analytics instances. | -| `BACKEND_URL` | No | Where Vite (`dev`, `preview`, prerendering) forwards `/api` to. Defaults to `http://127.0.0.1:3000`. | +| Variable | Required | Description | +| :------------------- | :------- | :------------------------------------------------------------------------------------------------------- | +| `VITE_SITE_URL` | No | The public URL of the application (e.g., `https://bazarpro.de`). Used for SEO and absolute links. | +| `VITE_BAZARPRO_MODE` | No | `single` to try the self-hosting mode with `vite dev`. In production the server injects `BAZARPRO_MODE`. | +| `BACKEND_URL` | No | Where Vite (`dev`, `preview`, prerendering) forwards `/api` to. Defaults to `http://127.0.0.1:3000`. | ## Web Server (runtime) -The Node server (`server/index.ts`) passes these values to the browser at runtime (`window.__BAZARPRO_CONFIG__`), so one image works under any domain. They take precedence over the build-time `VITE_*` values above. +The Node server (`server/index.ts`) passes these values to the browser at runtime (`window.__BAZARPRO_CONFIG__`), so one image works under any domain. | Variable | Description | | :------------------- | :------------------------------------------------------------------------------------------------------------------------ | @@ -55,6 +53,7 @@ Controls the deployment pipeline and server configuration. | `ADMIN_EMAIL`, `AUTH_SMTP_*`, `AUTH_EMAIL_FROM` | **Yes** | Written to `backend.env` on the server. | | `AUTH_GITHUB_*`, `AUTH_GOOGLE_*` | No | OAuth sign-in; callback `https:///api/auth/oauth//callback`. | | `CLOUDFLARE_DNS_API_TOKEN` | **Yes** | Cloudflare API token (Zone:DNS:Edit) for Traefik's ACME DNS challenge. | +| `VITE_PLAUSIBLE_API_HOST` | No | Plausible server of production; the deploy sets it as `PLAUSIBLE_API_HOST`. | --- diff --git a/ansible/roles/docker_deploy/templates/env.j2 b/ansible/roles/docker_deploy/templates/env.j2 index f8095d39..a842baed 100644 --- a/ansible/roles/docker_deploy/templates/env.j2 +++ b/ansible/roles/docker_deploy/templates/env.j2 @@ -3,3 +3,4 @@ IMAGE_TAG={{ image_tag }} DOMAIN_NAME={{ domain_name }} CLOUDFLARE_DNS_API_TOKEN={{ cloudflare_dns_api_token }} POSTGRES_PASSWORD={{ postgres_password }} +PLAUSIBLE_API_HOST={{ plausible_api_host }} diff --git a/ansible/site.yml b/ansible/site.yml index fa38f300..39b8805e 100644 --- a/ansible/site.yml +++ b/ansible/site.yml @@ -11,6 +11,7 @@ domain_name: "{{ lookup('env', 'DOMAIN_NAME') | default('localhost', true) }}" cloudflare_dns_api_token: "{{ lookup('env', 'CLOUDFLARE_DNS_API_TOKEN') | default('', true) }}" postgres_password: "{{ lookup('env', 'POSTGRES_PASSWORD') }}" + plausible_api_host: "{{ lookup('env', 'PLAUSIBLE_API_HOST') }}" # Settings of the backend (backend/README.md), from the CI secrets backend_settings: ADMIN_EMAIL: "{{ lookup('env', 'ADMIN_EMAIL') }}" diff --git a/backend/bench/README.md b/backend/bench/README.md index f0397baa..7e428a69 100644 --- a/backend/bench/README.md +++ b/backend/bench/README.md @@ -4,10 +4,10 @@ k6-Szenarien gegen ein laufendes Backend, so wie die App es benutzt: Abfragen ü Live-Updates über `/api/ws`. Wie `src/lib/api/client.ts` lädt eine geänderte Abfrage nach bis zu 300 ms und höchstens einmal pro Sekunde neu; ändert sich das im Client, hier mit. -| Skript | Was passiert | -| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `browse.js` | Lesekapazität: Besucher laden die öffentliche Eventseite ohne Pause (`VUS`, `DURATION`) | -| `bazaar.js` | Basartag: `CASHIERS` Kassen scannen, verkaufen und stornieren (damit der Artikel verkaufbar bleibt), dazu `VISITORS` Besucher, die die Eventseite `STAY` Sekunden mit Live-Updates offen haben (`DURATION`, `CASH_THINK`) | +| Skript | Was passiert | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `browse.js` | Lesekapazität: Besucher laden die öffentliche Eventseite ohne Pause (`VUS`, `DURATION`) | +| `bazaar.js` | Basartag: `CASHIERS` Kassen scannen, verkaufen und stornieren (damit der Artikel verkaufbar bleibt), dazu `VISITORS` Besucher, die die Eventseite `STAY` Sekunden mit Live-Updates offen haben (`DURATION`, `CASH_THINK`), davon der Anteil `SIGNED_IN` (0–1) angemeldet | **Nie gegen die Review-Apps oder Produktion:** Sie laufen auf demselben Server wie bazarpro.de. @@ -24,7 +24,7 @@ cargo build --release --manifest-path backend/Cargo.toml backend/target/release/bazarpro-backend import export.zip # echte Daten (npx convex export …) oder: seed backend/target/release/bazarpro-backend & # lauscht auf :3000 -node backend/bench/prepare.mjs # Kassen-Accounts, Artikel → backend/bench/.data.json +node backend/bench/prepare.mjs # Kassen- und Besucher-Accounts, Artikel → backend/bench/.data.json BACKEND_PID=$(pgrep -f release/bazarpro-backend) backend/bench/run.sh bazaar.js tag500 -e VISITORS=500 ``` @@ -36,6 +36,8 @@ kostet unter Last mehr als ein CPU-Kern. `prepare.mjs` schaltet `is_e2e_auth_skip_email` ein und macht die Kassen-Accounts zu Admins (dürfen an jeder Kasse verkaufen). Nur auf einer eigenen Datenbank benutzen. +Angemeldete Besucher (`SIGNED_IN`) nutzen `VISITOR_ACCOUNTS` (200) Accounts ohne Rolle +an der Veranstaltung, wie Käufer. Ihre Latenzen stehen getrennt als `*_signed_in`. ### Daten @@ -96,3 +98,25 @@ zwei Läufe je Stand (Spannen): | Eventseite Median / p95 | 43–290 / ~1 400 ms | 5 / 13–25 ms | 539 / 2 409 ms | 7 / 1 186 ms | | Übertragen (2 Minuten) | 0,9–1,2 GB | 0,27 GB | 1,35 GB | 0,64 GB | | Backend-CPU | 0,75–1,2 Kerne | 0,15–0,22 | 1,0 Kerne | 0,48 Kerne | + +## Messung vom 31.10.2026: angemeldete Besucher (#228) + +Demo-Daten (`seed`, Veranstaltung mit 75 Artikeln), Postgres 17 mit Standardkonfiguration, +`DATABASE_MAX_CONNECTIONS` 10, k6 auf demselben Rechner (12 Kerne, nicht exklusiv). +Basartag mit 20 Kassen, Besucher bleiben 30 s. Eventseite Median / p95, angemeldete +Besucher getrennt: + +| Besucher, angemeldet | vorher anonym | vorher angemeldet | nachher anonym | nachher angemeldet | +| -------------------- | ------------- | ----------------- | -------------- | ------------------ | +| 500, 100 % | – | 13 / 61 ms | – | 9 / 26 ms | +| 1000, 0 % | 6 / 107 ms | – | 6 / 95 ms | – | +| 1000, 50 % | 10 / 408 ms | 33 / 1 706 ms | 6 / 121 ms | 10 / 183 ms | +| 1000, 100 % | – | – | – | 14 / 364 ms | + +Vorher lief jede Abfrage eines angemeldeten Besuchers gegen Postgres. Bei 1000 Besuchern, +davon die Hälfte angemeldet, war nicht die CPU knapp (Backend 1,1, Postgres 0,5 Kerne), +sondern der Pool: Auch der Verkauf an der Kasse brauchte im Median 495 statt 28 ms. +Nachher bekommen Angemeldete ohne Rolle an der Veranstaltung die Antworten der Besucher +(`registry.share`), der Verkauf liegt bei 35 ms (Median) / 111 ms (p95). Was bleibt, ist pro +Anfrage die Session und die Rollenprüfung sowie `users.viewer`; bei 1000 Angemeldeten +Verkauf 63 / 153 ms. diff --git a/backend/bench/bazaar.js b/backend/bench/bazaar.js index eb97ddf3..8ddc5ae2 100644 --- a/backend/bench/bazaar.js +++ b/backend/bench/bazaar.js @@ -2,7 +2,8 @@ // updates, the way the app's API client does it (queries over HTTP, the WebSocket only // names changed topics, then the affected queries are refetched). // CASHIERS (20), VISITORS (200), DURATION (60s), STAY (30, seconds per visit), -// CASH_THINK (1, seconds between scans) +// CASH_THINK (1, seconds between scans), SIGNED_IN (0, share of visits with an account +// from prepare.mjs; their latencies are reported separately as *_signed_in) import http from 'k6/http'; import ws from 'k6/ws'; import { sleep } from 'k6'; @@ -15,10 +16,16 @@ const VISITORS = Number(__ENV.VISITORS || 200); const DURATION = __ENV.DURATION || '60s'; const STAY = Number(__ENV.STAY || 30); const CASH_THINK = Number(__ENV.CASH_THINK || 1); +const SIGNED_IN = Number(__ENV.SIGNED_IN || 0); +if (SIGNED_IN > 0 && !DATA.visitors?.length) { + throw new Error('SIGNED_IN braucht Besucher-Accounts: prepare.mjs erneut ausführen.'); +} const pageLoad = new Trend('page_load', true); +const pageLoadSignedIn = new Trend('page_load_signed_in', true); const sale = new Trend('sale', true); const refetch = new Trend('update_refetch', true); +const refetchSignedIn = new Trend('update_refetch_signed_in', true); const updates = new Counter('updates_received'); const wsErrors = new Counter('ws_errors'); @@ -77,6 +84,12 @@ export function cashier() { } export function visitor() { + // Several tabs may share an account, like a buyer with the app on two devices + const cookie = + Math.random() < SIGNED_IN + ? DATA.visitors[Math.floor(Math.random() * DATA.visitors.length)] + : undefined; + const auth = cookie ? { Cookie: cookie } : {}; const start = Date.now(); const entries = EVENT_PAGE.map(([name, args]) => ({ name, @@ -87,8 +100,8 @@ export function visitor() { })); const load = (entry) => { const res = http.post(`${BASE}/query/${entry.name}`, JSON.stringify(entry.args), { - headers: { 'content-type': 'application/json', 'accept-encoding': 'gzip' }, - tags: { fn: entry.name }, + headers: { 'content-type': 'application/json', 'accept-encoding': 'gzip', ...auth }, + tags: { fn: entry.name, signedIn: String(!!cookie) }, }); try { entry.topics = JSON.parse(res.body).topics || []; @@ -97,9 +110,9 @@ export function visitor() { } }; for (const entry of entries) load(entry); - pageLoad.add(Date.now() - start); + (cookie ? pageLoadSignedIn : pageLoad).add(Date.now() - start); - const res = ws.connect(BASE.replace(/^http/, 'ws') + '/ws', {}, (socket) => { + const res = ws.connect(BASE.replace(/^http/, 'ws') + '/ws', { headers: auth }, (socket) => { socket.on('open', () => { const topics = [...new Set(entries.flatMap((e) => e.topics))]; socket.send(JSON.stringify({ type: 'subscribe', topics })); @@ -124,7 +137,7 @@ export function visitor() { load(entry); } updates.add(1); - refetch.add(Date.now() - now); + (cookie ? refetchSignedIn : refetch).add(Date.now() - now); }, 20); socket.on('error', () => wsErrors.add(1)); socket.setTimeout(() => socket.close(), STAY * 1000); diff --git a/backend/bench/prepare.mjs b/backend/bench/prepare.mjs index cf1e3c7f..5844b972 100755 --- a/backend/bench/prepare.mjs +++ b/backend/bench/prepare.mjs @@ -1,12 +1,14 @@ #!/usr/bin/env node // Prepares a running backend for the load tests and writes bench/.data.json: -// the event, its items and signed-in cashier sessions (platform admins, so they may sell). +// the event, its items, signed-in cashier sessions (platform admins, so they may sell) and +// sessions of plain accounts for signed-in visitors (bazaar.js SIGNED_IN). // // DATABASE_URL=… node backend/bench/prepare.mjs // // BASE (http://127.0.0.1:3000/api), EVENT (default: the event with the most items), -// CASHIERS (40), BACKEND_BIN (backend/target/release/bazarpro-backend). -// Turns on is_e2e_auth_skip_email: only for a database of its own, never production. +// CASHIERS (40), VISITOR_ACCOUNTS (200), BACKEND_BIN (backend/target/release/bazarpro-backend). +// Turns on is_e2e_auth_skip_email and registration: only for a database of its own, never +// production. import { execFileSync } from 'node:child_process'; import { writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -16,6 +18,7 @@ import { fileURLToPath } from 'node:url'; const here = dirname(fileURLToPath(import.meta.url)); const BASE = process.env.BASE ?? 'http://127.0.0.1:3000/api'; const CASHIERS = Number(process.env.CASHIERS ?? 40); +const VISITOR_ACCOUNTS = Number(process.env.VISITOR_ACCOUNTS ?? 200); const BIN = process.env.BACKEND_BIN ?? join(here, '../target/release/bazarpro-backend'); const PASSWORD = 'Bench-Passw0rd!'; @@ -43,21 +46,22 @@ async function post(path, body, cookie) { return { status: res.status, body: await res.json(), cookie: session?.split(';')[0] }; } -async function cashierSession(i) { - const email = `bench-kasse${i}@bench.local`; +async function session(email, name) { const signIn = await post('/auth/password', { flow: 'signIn', email, password: PASSWORD }); - if (signIn.cookie) return { email, cookie: signIn.cookie }; - await post('/auth/password', { flow: 'signUp', email, password: PASSWORD, name: `Kasse ${i}` }); + if (signIn.cookie) return signIn.cookie; + await post('/auth/password', { flow: 'signUp', email, password: PASSWORD, name }); const { code } = await ( await fetch(`${BASE}/auth/e2e-code?email=${encodeURIComponent(email)}`) ).json(); const verified = await post('/auth/password', { flow: 'email-verification', email, code }); if (!verified.cookie) throw new Error(`Anmeldung von ${email} fehlgeschlagen: ${JSON.stringify(verified.body)}`); - return { email, cookie: verified.cookie }; + return verified.cookie; } cli('run', 'featureFlags.set', JSON.stringify({ key: 'is_e2e_auth_skip_email', value: true })); +// The demo data (seed) turns registration off +cli('run', 'featureFlags.set', JSON.stringify({ key: 'is_registration_enabled', value: true })); let event = process.env.EVENT; const products = async (id) => @@ -75,15 +79,28 @@ const items = (await products(event)).map((p) => ({ const cashiers = []; for (let i = 0; i < CASHIERS; i++) { - const { email, cookie } = await cashierSession(i); + const email = `bench-kasse${i}@bench.local`; + cashiers.push(await session(email, `Kasse ${i}`)); cli('admin', email); - cashiers.push(cookie); } -writeFileSync(join(here, '.data.json'), JSON.stringify({ event, products: items, cashiers })); +// Buyers without a role at the event: what they see could be shared with other visitors +const visitors = []; +for (let i = 0; i < VISITOR_ACCOUNTS; i += 10) { + const batch = Array.from({ length: Math.min(10, VISITOR_ACCOUNTS - i) }, (_, j) => + session(`bench-besucher${i + j}@bench.local`, `Besucher ${i + j}`) + ); + visitors.push(...(await Promise.all(batch))); +} + +writeFileSync( + join(here, '.data.json'), + JSON.stringify({ event, products: items, cashiers, visitors }) +); const available = (await products(event)).filter((p) => p.status === 'available').length; console.log( - `Veranstaltung ${event}: ${items.length} Artikel (${available} verkaufbar), ${cashiers.length} Kassen.` + `Veranstaltung ${event}: ${items.length} Artikel (${available} verkaufbar), ` + + `${cashiers.length} Kassen, ${visitors.length} Besucher-Accounts.` ); if (available < items.length) console.log('Zum Verkaufen alle Artikel freigeben, siehe README (Abschnitt Daten).'); diff --git a/backend/bench/summary.mjs b/backend/bench/summary.mjs index bfab258b..bef548f4 100755 --- a/backend/bench/summary.mjs +++ b/backend/bench/summary.mjs @@ -14,7 +14,7 @@ for (const file of process.argv.slice(2)) { const rows = Object.entries(m).filter( ([key, v]) => 'med' in v && - (key.startsWith('http_req_duration') || ['page_load', 'sale', 'update_refetch'].includes(key)) + ['http_req_duration', 'page_load', 'sale', 'update_refetch'].some((name) => key.startsWith(name)) ); for (const [key, v] of rows.sort()) { const label = key.replace('http_req_duration', 'http').padEnd(48); diff --git a/backend/migrations/0015_event_address.sql b/backend/migrations/0015_event_address.sql new file mode 100644 index 00000000..f59dbf57 --- /dev/null +++ b/backend/migrations/0015_event_address.sql @@ -0,0 +1,3 @@ +-- Address of the venue next to the free-text location (its name, e.g. "Turnhalle Nord"): +-- search engines show an event in their event results only with a postal address. +ALTER TABLE events ADD COLUMN street text, ADD COLUMN postal_code text, ADD COLUMN city text; diff --git a/backend/migrations/0016_event_country.sql b/backend/migrations/0016_event_country.sql new file mode 100644 index 00000000..73f6d913 --- /dev/null +++ b/backend/migrations/0016_event_country.sql @@ -0,0 +1,2 @@ +-- Country of the venue's address (ISO 3166-1 alpha-2, e.g. DE, AT, CH); empty is Germany. +ALTER TABLE events ADD COLUMN country text; diff --git a/backend/migrations/0019_category_translations.sql b/backend/migrations/0019_category_translations.sql new file mode 100644 index 00000000..1e14f012 --- /dev/null +++ b/backend/migrations/0019_category_translations.sql @@ -0,0 +1,20 @@ +-- Names of a category in other languages. `label` stays the name that counts: it decides +-- the extra fields of its items and is shown wherever a language has no translation. +ALTER TABLE categories ADD COLUMN translations jsonb NOT NULL DEFAULT '{}'; + +UPDATE categories c +SET translations = jsonb_build_object('en', d.en) +FROM (VALUES + ('Kleidung', 'Clothing'), + ('Schuhe', 'Shoes'), + ('Sport', 'Sports'), + ('Fahrräder', 'Bikes'), + ('Elektronik', 'Electronics'), + ('Bücher', 'Books'), + ('Spielzeug', 'Toys'), + ('Möbel', 'Furniture'), + ('Haushalt', 'Household'), + ('Accessoires', 'Accessories'), + ('Sonstiges', 'Other') +) AS d (de, en) +WHERE c.label = d.de; diff --git a/backend/src/demo/mod.rs b/backend/src/demo/mod.rs index 6139c472..5898c944 100644 --- a/backend/src/demo/mod.rs +++ b/backend/src/demo/mod.rs @@ -107,8 +107,8 @@ impl Seeder { product_images: Option>, ) -> AppResult { let mut categories = HashMap::new(); - for (cat, label) in CATEGORIES { - let label = label.get(locale); + for (cat, names) in CATEGORIES { + let label = names.get(locale); let existing: Option = sqlx::query_scalar( "SELECT id FROM categories WHERE label = $1 ORDER BY created_at LIMIT 1", ) @@ -118,10 +118,18 @@ impl Seeder { let id = match existing { Some(id) => id, None => { - sqlx::query_scalar("INSERT INTO categories (label) VALUES ($1) RETURNING id") - .bind(label) - .fetch_one(ctx.conn()) - .await? + // A German demo carries the English name too; an English one needs none + let translations = match locale { + Locale::De => json!({ "en": names.en }), + Locale::En => json!({}), + }; + sqlx::query_scalar( + "INSERT INTO categories (label, translations) VALUES ($1, $2) RETURNING id", + ) + .bind(label) + .bind(translations) + .fetch_one(ctx.conn()) + .await? } }; categories.insert(*cat, id); @@ -348,6 +356,11 @@ pub async fn run(state: &AppState, options: Options) -> anyhow::Result { let failed = |err: crate::error::AppError| anyhow::anyhow!("{err}"); let mut ctx = Ctx::begin(state).await?; + // The backend created the German default categories on its first start. Without users + // nothing uses them yet, and `--locale en` would show them next to the English ones. + sqlx::query("DELETE FROM categories WHERE NOT EXISTS (SELECT 1 FROM users)") + .execute(ctx.conn()) + .await?; ctx.call(None, "seed.seedFeatureFlags", json!({})) .await .map_err(failed)?; diff --git a/backend/src/import.rs b/backend/src/import.rs index 4f979897..adbc773e 100644 --- a/backend/src/import.rs +++ b/backend/src/import.rs @@ -491,6 +491,13 @@ async fn categories( known: &mut Known, report: &mut Report, ) -> anyhow::Result<()> { + // The backend ran before the import and created the default categories. Nothing uses them + // yet, the database has no users; the export would add its own next to them. + if export.docs("categories").next().is_some() { + sqlx::query("DELETE FROM categories") + .execute(&mut *tx) + .await?; + } for doc in export.docs("categories") { sqlx::query( "INSERT INTO categories (id, legacy_id, label, updated_at, created_at) diff --git a/backend/src/main.rs b/backend/src/main.rs index f1a2da12..7770d2c7 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -88,6 +88,16 @@ async fn main() -> anyhow::Result<()> { { tracing::warn!(error = %err, "ADMIN_EMAIL not promoted"); } + if let Err(err) = rpc::call( + &state, + None, + "categories.seedIfEmpty", + serde_json::json!({}), + ) + .await + { + tracing::warn!(error = %err, "default categories not created"); + } let hub = state.hub.clone(); tokio::spawn(async move { diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index e228e02b..46bc062a 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -1,25 +1,53 @@ //! Product categories. use chrono::{DateTime, Utc}; +use futures::FutureExt; +use futures::future::BoxFuture; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; +use sqlx::types::Json; use uuid::Uuid; use super::access::require_admin; -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use crate::realtime::Topic; use crate::register; -use crate::rpc::{Ctx, Registry}; +use crate::rpc::{Audience, Ctx, Registry}; use crate::shape::{Id, ms}; const TOPIC: Topic = Topic::Table("categories"); pub fn register(registry: &mut Registry) { register!(registry, Mutation "categories.createCategory" => create_category); + register!(registry, Mutation "categories.updateCategory" => update_category); + register!(registry, Mutation "categories.deleteCategory" => delete_category); + register!(registry, Query "categories.listForAdmin" => list_for_admin); register!(registry, Query "categories.getAllCategories" => get_all_categories); + registry.share("categories.getAllCategories", same_for_everybody); register!(registry, Query "categories.getCategoryLabel" => get_category_label); register!(registry, Query "categories.getCategoryId" => get_category_id); register!(registry, InternalMutation "categories.seedCategories" => seed_categories); + register!(registry, InternalMutation "categories.seedIfEmpty" => seed_if_empty); +} + +/// Names in other languages. `label` remains the name that decides the extra fields +/// (category_fields) and the one shown when a language has no translation. +#[skip_serializing_none] +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Translations { + pub en: Option, +} + +impl Translations { + fn trimmed(self) -> Self { + Self { + en: self + .en + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()), + } + } } #[skip_serializing_none] @@ -35,6 +63,7 @@ pub struct Category { pub parent_id: Option, #[serde(with = "ms")] pub updated_at: DateTime, + pub translations: Json, } #[derive(Deserialize)] @@ -42,6 +71,15 @@ pub struct Category { struct CreateArgs { label: String, parent_category: Option, + translations: Option, +} + +fn clean_label(label: &str) -> AppResult { + let label = label.trim(); + if label.is_empty() { + return Err(AppError::bad_request("category.labelEmpty")); + } + Ok(label.to_owned()) } async fn find_by_label(ctx: &mut Ctx, label: &str) -> sqlx::Result> { @@ -54,7 +92,8 @@ async fn find_by_label(ctx: &mut Ctx, label: &str) -> sqlx::Result> /// Admins only. Returns the existing category if the label exists already. async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult { require_admin(ctx).await?; - if let Some(existing) = find_by_label(ctx, &args.label).await? { + let label = clean_label(&args.label)?; + if let Some(existing) = find_by_label(ctx, &label).await? { return Ok(existing); } // A parent that does not exist is left out @@ -68,24 +107,135 @@ async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult { None => None, }; let id = sqlx::query_scalar( - "INSERT INTO categories (label, parent_id) VALUES ($1, $2) RETURNING id", + "INSERT INTO categories (label, parent_id, translations) VALUES ($1, $2, $3) RETURNING id", ) - .bind(&args.label) + .bind(&label) .bind(parent) + .bind(Json(args.translations.unwrap_or_default().trimmed())) .fetch_one(ctx.conn()) .await?; ctx.touch(TOPIC); Ok(id) } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UpdateArgs { + category_id: Id, + label: String, + translations: Translations, +} + +/// Admins only. Items and bazaars point to the id and follow; sales keep the name they had. +async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { + require_admin(ctx).await?; + let label = clean_label(&args.label)?; + let taken: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM categories WHERE lower(label) = lower($1) AND id <> $2)", + ) + .bind(&label) + .bind(args.category_id.0) + .fetch_one(ctx.conn()) + .await?; + if taken { + return Err(AppError::bad_request("category.labelTaken")); + } + let updated = sqlx::query( + "UPDATE categories SET label = $2, translations = $3, updated_at = now() WHERE id = $1", + ) + .bind(args.category_id.0) + .bind(&label) + .bind(Json(args.translations.trimmed())) + .execute(ctx.conn()) + .await?; + if updated.rows_affected() == 0 { + return Err(AppError::not_found("notFound.category")); + } + ctx.touch(TOPIC); + Ok(()) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DeleteArgs { + category_id: Id, +} + +/// Admins only, and only what nothing uses: items and bazaars need their category, and a +/// sub-category would lose the fields it inherits. Sales keep the name they recorded. +async fn delete_category(ctx: &mut Ctx, args: DeleteArgs) -> AppResult<()> { + require_admin(ctx).await?; + let id = args.category_id.0; + let (exists, in_use, others): (bool, bool, bool) = sqlx::query_as( + "SELECT EXISTS (SELECT 1 FROM categories WHERE id = $1), + EXISTS (SELECT 1 FROM products WHERE category_id = $1) + OR EXISTS (SELECT 1 FROM event_categories WHERE category_id = $1) + OR EXISTS (SELECT 1 FROM categories WHERE parent_id = $1), + EXISTS (SELECT 1 FROM categories WHERE id <> $1)", + ) + .bind(id) + .fetch_one(ctx.conn()) + .await?; + if !exists { + return Err(AppError::not_found("notFound.category")); + } + if in_use { + return Err(AppError::bad_request("category.inUse")); + } + // No bazaar could be created without one, and the next start would bring the defaults back + if !others { + return Err(AppError::bad_request("category.lastOne")); + } + sqlx::query("DELETE FROM categories WHERE id = $1") + .bind(id) + .execute(ctx.conn()) + .await?; + ctx.touch(TOPIC); + Ok(()) +} + +#[derive(Serialize, sqlx::FromRow)] +#[serde(rename_all = "camelCase")] +struct AdminCategory { + #[sqlx(flatten)] + #[serde(flatten)] + category: Category, + product_count: i64, + event_count: i64, + child_count: i64, +} + +async fn list_for_admin(ctx: &mut Ctx, _: NoArgs) -> AppResult> { + require_admin(ctx).await?; + ctx.read(TOPIC); + Ok(sqlx::query_as( + "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations, + (SELECT count(*) FROM products p WHERE p.category_id = c.id) AS product_count, + (SELECT count(*) FROM event_categories e WHERE e.category_id = c.id) AS event_count, + (SELECT count(*) FROM categories s WHERE s.parent_id = c.id) AS child_count + FROM categories c ORDER BY c.created_at, c.id", + ) + .fetch_all(ctx.conn()) + .await?) +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct NoArgs {} +fn same_for_everybody<'a>( + _: &'a mut sqlx::PgConnection, + _: Uuid, + _: &'a serde_json::Value, +) -> BoxFuture<'a, sqlx::Result> { + async { Ok(Audience::Visitors) }.boxed() +} + async fn get_all_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult> { ctx.read(TOPIC); Ok(sqlx::query_as( - "SELECT id, created_at, label, parent_id, updated_at FROM categories ORDER BY created_at", + "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations + FROM categories c ORDER BY c.created_at", ) .fetch_all(ctx.conn()) .await?) @@ -118,27 +268,30 @@ async fn get_category_id(ctx: &mut Ctx, args: IdArgs) -> AppResult> Ok(find_by_label(ctx, &args.category_label).await?) } -/// The default categories (German labels); adds the missing ones, safe to run repeatedly: -/// `bazarpro-backend run categories.seedCategories` -pub const DEFAULT_CATEGORIES: [&str; 11] = [ - "Kleidung", - "Schuhe", - "Sport", - "Fahrräder", - "Elektronik", - "Bücher", - "Spielzeug", - "Möbel", - "Haushalt", - "Accessoires", - "Sonstiges", +/// The default categories (German label, English name); adds the missing ones, safe to run +/// repeatedly: `bazarpro-backend run categories.seedCategories` +pub const DEFAULT_CATEGORIES: [(&str, &str); 11] = [ + ("Kleidung", "Clothing"), + ("Schuhe", "Shoes"), + ("Sport", "Sports"), + ("Fahrräder", "Bikes"), + ("Elektronik", "Electronics"), + ("Bücher", "Books"), + ("Spielzeug", "Toys"), + ("Möbel", "Furniture"), + ("Haushalt", "Household"), + ("Accessoires", "Accessories"), + ("Sonstiges", "Other"), ]; async fn seed_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<&'static str> { - for label in DEFAULT_CATEGORIES { + for (label, en) in DEFAULT_CATEGORIES { if find_by_label(ctx, label).await?.is_none() { - sqlx::query("INSERT INTO categories (label) VALUES ($1)") + sqlx::query("INSERT INTO categories (label, translations) VALUES ($1, $2)") .bind(label) + .bind(Json(Translations { + en: Some(en.to_owned()), + })) .execute(ctx.conn()) .await?; } @@ -146,3 +299,15 @@ async fn seed_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<&'static str> { ctx.touch(TOPIC); Ok("Categories seeded successfully") } + +/// On every start of the server: without categories no bazaar can be created, and the app +/// has no page to add them. An instance that already has categories keeps exactly those. +async fn seed_if_empty(ctx: &mut Ctx, args: NoArgs) -> AppResult<&'static str> { + let any: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM categories)") + .fetch_one(ctx.conn()) + .await?; + if any { + return Ok("Categories already exist"); + } + seed_categories(ctx, args).await +} diff --git a/backend/src/modules/docs.rs b/backend/src/modules/docs.rs index 886635cb..02e3f61e 100644 --- a/backend/src/modules/docs.rs +++ b/backend/src/modules/docs.rs @@ -141,6 +141,12 @@ pub struct Event { pub cover_image: Option, pub event_map_image: Option, pub location: String, + /// Address of the venue; `location` is its name or, in older events, all of it + pub street: Option, + pub postal_code: Option, + pub city: Option, + /// ISO 3166-1 alpha-2; none is Germany + pub country: Option, #[serde(with = "ms")] pub start_date: DateTime, #[serde(with = "ms")] @@ -181,6 +187,10 @@ struct EventRow { cover_image_id: Option, map_image_id: Option, location: String, + street: Option, + postal_code: Option, + city: Option, + country: Option, start_date: DateTime, end_date: DateTime, contact_info: String, @@ -242,6 +252,10 @@ impl From for Event { cover_image: row.cover_image_id, event_map_image: row.map_image_id, location: row.location, + street: row.street, + postal_code: row.postal_code, + city: row.city, + country: row.country, start_date: row.start_date, end_date: row.end_date, contact_info: row.contact_info, @@ -276,7 +290,8 @@ impl From for Event { /// SELECT list of the events table aliased `e`. pub const EVENT_COLUMNS: &str = "e.id, e.created_at, e.title, e.description, e.cover_image_id, - e.map_image_id, e.location, e.start_date, e.end_date, e.contact_info, + e.map_image_id, e.location, e.street, e.postal_code, e.city, e.country, + e.start_date, e.end_date, e.contact_info, ARRAY(SELECT c.category_id FROM event_categories c WHERE c.event_id = e.id ORDER BY c.position) AS categories, e.services::text[] AS services, e.visibility::text AS visibility, e.is_approved, diff --git a/backend/src/modules/event_products.rs b/backend/src/modules/event_products.rs index 3cbd8e19..f75fe12d 100644 --- a/backend/src/modules/event_products.rs +++ b/backend/src/modules/event_products.rs @@ -7,6 +7,8 @@ use std::collections::HashMap; use chrono::{DateTime, Utc}; +use futures::FutureExt; +use futures::future::BoxFuture; use rust_decimal::Decimal; use rust_decimal::prelude::FromPrimitive; use serde::{Deserialize, Serialize}; @@ -16,7 +18,9 @@ use uuid::Uuid; use super::category_fields::{self, CategoryField}; use super::docs::{self, EVENT_PRODUCT_COLUMNS, Event, EventProduct, Product, User}; -use super::event_roles::{TEAM, assert_vendor_not_paid_out, has_any_role_or_admin, require_team}; +use super::event_roles::{ + TEAM, assert_vendor_not_paid_out, has_any_role_or_admin, is_bystander, require_team, +}; use super::events::is_event_approved; use super::features::discount_unavailable; use super::offers::{close_offers_for_event_product, reopen_closed_offers}; @@ -28,7 +32,7 @@ use crate::flags; use crate::money::Cents; use crate::realtime::Topic; use crate::register; -use crate::rpc::{Ctx, Registry}; +use crate::rpc::{Audience, Ctx, Registry}; use crate::shape::Id; const MAX_INTERNAL_NOTE_LENGTH: usize = 500; @@ -44,6 +48,10 @@ pub fn register(registry: &mut Registry) { register!(registry, Query "eventProducts.getFixedItemData" => get_fixed_item_data); register!(registry, Query "eventProducts.isProductLockedForSeller" => is_product_locked_for_seller); register!(registry, Query "eventProducts.getProductsForEvent" => get_products_for_event); + registry.share( + "eventProducts.getProductsForEvent", + products_for_event_audience, + ); register!(registry, Query "eventProducts.getProductsForEventManagement" => get_products_for_event_management); register!(registry, Query "eventProducts.getEventProduct" => get_event_product); register!(registry, Mutation "eventProducts.setEventProductNote" => set_event_product_note); @@ -572,6 +580,25 @@ async fn listed_products( } /// The items of an event for visitors: the viewer's own and those ready for sale. +/// Only the team and the event's sellers see more than visitors. +fn products_for_event_audience<'a>( + conn: &'a mut PgConnection, + user: Uuid, + args: &'a serde_json::Value, +) -> BoxFuture<'a, sqlx::Result> { + async move { + let Ok(args) = EventArgs::deserialize(args) else { + return Ok(Audience::Personal); + }; + Ok(if is_bystander(conn, args.event_id.0, user).await? { + Audience::Visitors + } else { + Audience::Personal + }) + } + .boxed() +} + async fn get_products_for_event(ctx: &mut Ctx, args: EventArgs) -> AppResult> { let event_id = args.event_id.0; ctx.read(Topic::Event(event_id)); diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index c792d0f7..c0ff834b 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -86,6 +86,27 @@ pub async fn has_any_role( .await } +/// Neither administrator nor in the event team nor selling items there: sees the event and +/// its items like a visitor without an account, so the answers are shared (`rpc::Audience`). +pub async fn is_bystander(conn: &mut PgConnection, event: Uuid, user: Uuid) -> sqlx::Result { + if is_platform_admin(conn, Some(user)).await? { + return Ok(false); + } + let team: Vec<&str> = TEAM.iter().map(|role| role.as_str()).collect(); + sqlx::query_scalar( + "SELECT NOT EXISTS (SELECT 1 FROM events WHERE id = $1 AND organizer_id = $2) + AND NOT EXISTS (SELECT 1 FROM event_roles + WHERE event_id = $1 AND user_id = $2 AND role::text = ANY($3)) + AND NOT EXISTS (SELECT 1 FROM event_products ep JOIN products p ON p.id = ep.product_id + WHERE ep.event_id = $1 AND p.vendor_id = $2)", + ) + .bind(event) + .bind(user) + .bind(team) + .fetch_one(conn) + .await +} + /// Any of the roles; administrators pass when an organizer role is asked for. pub async fn has_any_role_or_admin( conn: &mut PgConnection, diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index 659101b8..d1d54735 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -20,8 +20,8 @@ use super::access::{active_admins, is_platform_admin, require_admin}; use super::category_fields::requirable_fields; use super::docs::{self, Event}; use super::event_roles::{ - self, Role, TEAM, has_any_role_or_admin, has_role_or_admin, load_vendors_with_calculations, - require_team, + self, Role, TEAM, has_any_role_or_admin, has_role_or_admin, is_bystander, + load_vendors_with_calculations, require_team, }; use super::features::MAX_DISCOUNT_PERCENT; use super::moderation::{LogEntry, log_action}; @@ -33,7 +33,7 @@ use crate::i18n::{Locale, mail_text}; use crate::money::Cents; use crate::realtime::Topic; use crate::register; -use crate::rpc::{Ctx, Registry}; +use crate::rpc::{Audience, Ctx, Registry}; use crate::shape::{Id, from_ms}; use crate::{AppState, flags, mail, storage}; @@ -55,6 +55,7 @@ pub fn register(registry: &mut Registry) { register!(registry, Query "events.getFeeLock" => get_fee_lock); register!(registry, Query "events.getMyEvents" => get_my_events); register!(registry, Query "events.get" => get); + registry.share("events.get", list_audience); register!(registry, Query "events.getPublicEventsForAdmin" => get_public_events_for_admin); register!(registry, Query "events.getEventsForAdmin" => get_events_for_admin); register!(registry, Mutation "events.approveEventForAdmin" => approve_event_for_admin); @@ -62,6 +63,7 @@ pub fn register(registry: &mut Registry) { register!(registry, Mutation "events.requestEventReviewForOrganizer" => request_event_review_for_organizer); register!(registry, Query "events.getEvent" => get_event); register!(registry, Query "events.getPublicEventForViewer" => get_public_event_for_viewer); + registry.share("events.getPublicEventForViewer", public_event_audience); register!(registry, Query "events.getEvents" => get_events); register!(registry, Mutation "events.createEvent" => create_event); register!(registry, Mutation "events.editEvent" => edit_event); @@ -216,6 +218,22 @@ async fn get_my_events(ctx: &mut Ctx, args: ListArgs) -> AppResult( + conn: &'a mut sqlx::PgConnection, + user: Uuid, + _: &'a Value, +) -> BoxFuture<'a, sqlx::Result> { + async move { + Ok(if is_platform_admin(conn, Some(user)).await? { + Audience::Personal + } else { + Audience::SignedIn + }) + } + .boxed() +} + async fn get(ctx: &mut Ctx, args: ListArgs) -> AppResult> { ctx.read(Topic::Events); let time = time_condition(args.include_past); @@ -510,6 +528,26 @@ async fn get_event(ctx: &mut Ctx, args: IdArgs) -> AppResult( + conn: &'a mut sqlx::PgConnection, + user: Uuid, + args: &'a Value, +) -> BoxFuture<'a, sqlx::Result> { + async move { + let Ok(args) = IdArgs::deserialize(args) else { + return Ok(Audience::Personal); + }; + Ok(if is_bystander(conn, args.id.0, user).await? { + Audience::Visitors + } else { + Audience::Personal + }) + } + .boxed() +} + async fn get_public_event_for_viewer( ctx: &mut Ctx, args: IdArgs, @@ -746,6 +784,52 @@ struct Logistics { note: Option, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AddressArgs { + street: Option, + postal_code: Option, + city: Option, + country: Option, +} + +/// Street, postal code and town of the venue; empty parts are stored as NULL. +struct Address { + street: Option, + postal_code: Option, + city: Option, + country: Option, +} + +/// Countries the address form offers (ISO 3166-1 alpha-2). +const COUNTRIES: [&str; 5] = ["DE", "AT", "CH", "LI", "LU"]; + +fn sanitize_address(args: Option) -> AppResult
{ + let part = |value: Option, max: usize| -> AppResult> { + let value = value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()); + if value.as_ref().is_some_and(|v| v.chars().count() > max) { + return Err(AppError::bad_request("event.addressTooLong")); + } + Ok(value) + }; + let args = args.unwrap_or(AddressArgs { + street: None, + postal_code: None, + city: None, + country: None, + }); + let country = part(args.country, 2)?.map(|c| c.to_ascii_uppercase()); + if country.as_deref().is_some_and(|c| !COUNTRIES.contains(&c)) { + return Err(AppError::bad_request("event.countryUnknown")); + } + Ok(Address { + street: part(args.street, 200)?, + postal_code: part(args.postal_code, 10)?, + city: part(args.city, 100)?, + country, + }) +} + /// Checks the hand-in and pickup times; empty fields are dropped. fn sanitize_logistics(args: LogisticsArgs) -> AppResult { for (label, start, end) in [ @@ -857,6 +941,7 @@ struct CreateArgs { cover_image: Option, event_map_image: Option, location: String, + address: Option, start_date: f64, end_date: f64, contact_info: String, @@ -890,13 +975,15 @@ async fn create_event(ctx: &mut Ctx, args: CreateArgs) -> AppResult { .transpose()?; let logistics = args.seller_logistics.map(sanitize_logistics).transpose()?; let logistics = logistics.as_ref(); + let address = sanitize_address(args.address)?; let id: Uuid = sqlx::query_scalar( "INSERT INTO events (title, description, cover_image_id, map_image_id, location, start_date, end_date, contact_info, services, visibility, is_approved, approval_status, access_code, vendor_limit, commission, features, dropoff_start, dropoff_end, pickup_start, pickup_end, - logistics_note, organizer_id) + logistics_note, organizer_id, street, postal_code, city, country) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::event_service[], $10::event_visibility, $11, - $12::approval_status, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22) + $12::approval_status, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, + $26) RETURNING id", ) .bind(&args.title) @@ -921,6 +1008,10 @@ async fn create_event(ctx: &mut Ctx, args: CreateArgs) -> AppResult { .bind(logistics.and_then(|l| l.pickup_end)) .bind(logistics.and_then(|l| l.note.clone())) .bind(user) + .bind(&address.street) + .bind(&address.postal_code) + .bind(&address.city) + .bind(&address.country) .fetch_one(ctx.conn()) .await?; set_categories(ctx, id, &args.categories).await?; @@ -941,6 +1032,8 @@ struct EditArgs { cover_image: Option, event_map_image: Option, location: String, + /// Absent (older apps): the stored address stays + address: Option, start_date: f64, end_date: f64, categories: Vec, @@ -1022,6 +1115,8 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { let logistics = args.seller_logistics.map(sanitize_logistics).transpose()?; let keep_logistics = logistics.is_none(); let logistics = logistics.as_ref(); + let keep_address = args.address.is_none(); + let address = sanitize_address(args.address)?; sqlx::query( "UPDATE events SET title = $2, description = $3, cover_image_id = CASE WHEN $4 THEN NULL ELSE COALESCE($5, cover_image_id) END, @@ -1037,7 +1132,11 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { pickup_end = CASE WHEN $20 THEN pickup_end ELSE $24 END, logistics_note = CASE WHEN $20 THEN logistics_note ELSE $25 END, is_approved = CASE WHEN $26 THEN false ELSE is_approved END, - approval_status = CASE WHEN $26 THEN 'pending' ELSE approval_status END + approval_status = CASE WHEN $26 THEN 'pending' ELSE approval_status END, + street = CASE WHEN $27 THEN street ELSE $28 END, + postal_code = CASE WHEN $27 THEN postal_code ELSE $29 END, + city = CASE WHEN $27 THEN city ELSE $30 END, + country = CASE WHEN $27 THEN country ELSE $31 END WHERE id = $1", ) .bind(event.id) @@ -1066,6 +1165,11 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { .bind(logistics.and_then(|l| l.pickup_end)) .bind(logistics.and_then(|l| l.note.clone())) .bind(making_public) + .bind(keep_address) + .bind(&address.street) + .bind(&address.postal_code) + .bind(&address.city) + .bind(&address.country) .execute(ctx.conn()) .await?; set_categories(ctx, event.id, &args.categories).await?; diff --git a/backend/src/rpc.rs b/backend/src/rpc.rs index 2c446f25..c138dc3b 100644 --- a/backend/src/rpc.rs +++ b/backend/src/rpc.rs @@ -101,9 +101,29 @@ pub enum Kind { InternalMutation, } +/// With whom a signed-in user shares the answer of a query. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Audience { + /// Sees what visitors without an account see: the answer is theirs + Visitors, + /// Sees the same as every other signed-in user for whom the check says so + SignedIn, + /// The answer depends on who asks + Personal, +} + +/// Decides for a signed-in user and the arguments whether the answer can be shared, before +/// the query runs; arguments it does not understand are `Personal`, the query then refuses them. +pub type AudienceCheck = for<'a> fn( + &'a mut sqlx::PgConnection, + Uuid, + &'a Value, +) -> BoxFuture<'a, sqlx::Result>; + #[derive(Default)] pub struct Registry { functions: HashMap<&'static str, (Kind, Handler)>, + audiences: HashMap<&'static str, AudienceCheck>, } impl Registry { @@ -116,6 +136,21 @@ impl Registry { self.functions.get(name).copied() } + /// Signed-in users get a shared answer of the query when `check` allows it; without + /// a check each of them gets their own. + pub fn share(&mut self, name: &'static str, check: AudienceCheck) { + assert_eq!( + self.get(name).map(|(kind, _)| kind), + Some(Kind::Query), + "only registered queries are shared: {name}" + ); + self.audiences.insert(name, check); + } + + pub fn audience(&self, name: &str) -> Option { + self.audiences.get(name).copied() + } + pub fn names(&self) -> impl Iterator + '_ { self.functions .iter() @@ -306,6 +341,24 @@ impl Answer { } } +/// The answer `{value, topics}` as it is sent, with the topics. +async fn run_query_body( + state: &AppState, + user: Option, + handler: Handler, + args: Value, +) -> AppResult<(Vec, Vec)> { + let (value, topics) = run_query(state, user, handler, args).await?; + let topics: Vec = topics.iter().map(Topic::key).collect(); + let body = serde_json::to_vec(&json!({ "value": value, "topics": topics })) + .map_err(anyhow::Error::from)?; + Ok((body, topics)) +} + +fn json_response(body: Bytes) -> Response { + ([(header::CONTENT_TYPE, "application/json")], body).into_response() +} + pub async fn query_handler( State(state): State, Path(name): Path, @@ -314,20 +367,24 @@ pub async fn query_handler( Json(args): Json, ) -> AppResult { let handler = find(&name, Kind::Query)?; - let user = current.map(|c| c.user_id); - let answer = async { - let (value, topics) = run_query(&state, user, handler, args.clone()).await?; - let topics: Vec = topics.iter().map(Topic::key).collect(); - let body = serde_json::to_vec(&json!({ "value": value, "topics": topics })) - .map_err(anyhow::Error::from)?; - AppResult::Ok((body, topics)) - }; - let json_response = |body| ([(header::CONTENT_TYPE, "application/json")], body).into_response(); + let mut user = current.map(|c| c.user_id); // Visitors share answers; what a signed-in user sees can depend on them - if user.is_some() { - return Ok(json_response(Bytes::from(answer.await?.0))); + let mut key = format!("{name}\n{args}"); + if let Some(signed_in) = user { + let audience = match FUNCTIONS.audience(&name) { + Some(check) => check(&mut *state.db.acquire().await?, signed_in, &args).await?, + None => Audience::Personal, + }; + match audience { + Audience::Visitors => user = None, + Audience::SignedIn => key.push_str("\nsigned-in"), + Audience::Personal => { + let (body, _) = run_query_body(&state, user, handler, args).await?; + return Ok(json_response(Bytes::from(body))); + } + } } - let key = format!("{name}\n{args}"); + let answer = run_query_body(&state, user, handler, args); let shared = state .hub .cache diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index a45bb3fd..9aaf50c8 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -171,6 +171,227 @@ async fn parallel_mutations_are_serialized_and_retried(db: PgPool) { assert_eq!((count, distinct), (11, 11)); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { + let app = app(&db).await; + let http = app + .mutation("categories.seedIfEmpty", json!({}), None) + .await; + assert_eq!(http.status, StatusCode::NOT_FOUND); + + let labels = || async { + sqlx::query_scalar::<_, String>("SELECT label FROM categories") + .fetch_all(&db) + .await + .unwrap() + }; + let start = || rpc::call(&app.state, None, "categories.seedIfEmpty", json!({})); + + // A new instance gets the defaults, and a second start adds nothing + start().await.unwrap(); + assert_eq!(labels().await.len(), 11); + start().await.unwrap(); + assert_eq!(labels().await.len(), 11); + + // An instance with categories of its own does not get the defaults back + sqlx::query("DELETE FROM categories WHERE label <> 'Kleidung'") + .execute(&db) + .await + .unwrap(); + start().await.unwrap(); + assert_eq!(labels().await, ["Kleidung"]); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn admins_rename_and_translate_categories(db: PgPool) { + let app = app(&db).await; + let user = app.user_session("user@example.org", false).await; + let admin = app.user_session("admin@example.org", true).await; + let create = |label: &'static str| { + let (app, admin) = (&app, &admin); + async move { + let created = app + .mutation( + "categories.createCategory", + json!({ "label": format!(" {label} "), "translations": { "en": " Ski gear " } }), + Some(admin), + ) + .await; + created.body["value"].as_str().unwrap().to_owned() + } + }; + let ski = create("Ski").await; + let bike = create("Räder").await; + let update = |id: &str, label: &str, en: Value| { + let (app, admin) = (&app, &admin); + let args = json!({ "categoryId": id, "label": label, "translations": { "en": en } }); + async move { + app.mutation("categories.updateCategory", args, Some(admin)) + .await + } + }; + + let forbidden = app + .mutation( + "categories.updateCategory", + json!({ "categoryId": ski, "label": "x", "translations": {} }), + Some(&user), + ) + .await; + assert_eq!(forbidden.status, StatusCode::FORBIDDEN); + assert_eq!( + update(&ski, " ", Value::Null).await.body["code"], + "category.labelEmpty" + ); + assert_eq!( + update(&ski, "räder", Value::Null).await.body["code"], + "category.labelTaken" + ); + let unknown_language = app + .mutation( + "categories.updateCategory", + json!({ "categoryId": ski, "label": "Ski", "translations": { "fr": "Ski" } }), + Some(&admin), + ) + .await; + assert_eq!(unknown_language.status, StatusCode::BAD_REQUEST); + + // Everybody reads the names; the other category stays as it was + let list = app + .query("categories.getAllCategories", json!({}), None) + .await; + assert_eq!(list.body["value"][0]["label"], "Ski"); + assert_eq!(list.body["value"][0]["translations"]["en"], "Ski gear"); + + let renamed = update(&ski, " Wintersport ", json!("Winter sports")).await; + assert_eq!(renamed.status, StatusCode::OK, "{:?}", renamed.body); + // Only the case of its own name may change + assert_eq!( + update(&bike, "RÄDER", json!(" ")).await.status, + StatusCode::OK + ); + let list = app + .query("categories.getAllCategories", json!({}), None) + .await; + assert_eq!(list.body["value"][0]["label"], "Wintersport"); + assert_eq!(list.body["value"][0]["translations"]["en"], "Winter sports"); + assert_eq!(list.body["value"][1]["label"], "RÄDER"); + assert_eq!(list.body["value"][1]["translations"], json!({})); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn only_unused_categories_can_be_deleted(db: PgPool) { + let app = app(&db).await; + let user = app.user_session("user@example.org", false).await; + let admin = app.user_session("admin@example.org", true).await; + let create = |args: Value| { + let (app, admin) = (&app, &admin); + async move { + app.mutation("categories.createCategory", args, Some(admin)) + .await + .body["value"] + .as_str() + .unwrap() + .to_owned() + } + }; + let parent = create(json!({ "label": "Ski" })).await; + let child = create(json!({ "label": "Tourenski", "parentCategory": parent })).await; + let delete = |id: String, session| { + let app = &app; + async move { + app.mutation( + "categories.deleteCategory", + json!({ "categoryId": id }), + session, + ) + .await + } + }; + + let listed = app + .query("categories.listForAdmin", json!({}), Some(&user)) + .await; + assert_eq!(listed.status, StatusCode::FORBIDDEN); + assert_eq!( + delete(child.clone(), Some(&user)).await.status, + StatusCode::FORBIDDEN + ); + + // The parent has a sub-category + assert_eq!( + delete(parent.clone(), Some(&admin)).await.body["code"], + "category.inUse" + ); + + // An item uses it: the count shows why, and the category stays + let used = create(json!({ "label": "Bücher" })).await; + let seller: uuid::Uuid = sqlx::query_scalar("SELECT id FROM users LIMIT 1") + .fetch_one(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO products (title, vendor_id, description, condition, category_id, price, + ready_for_sale, sold) + VALUES ('Atlas', $1, 'Alt', 'good', $2, 5, true, false)", + ) + .bind(seller) + .bind(uuid::Uuid::parse_str(&used).unwrap()) + .execute(&db) + .await + .unwrap(); + assert_eq!( + delete(used.clone(), Some(&admin)).await.body["code"], + "category.inUse" + ); + let listed = app + .query("categories.listForAdmin", json!({}), Some(&admin)) + .await; + let rows = listed.body["value"].as_array().unwrap(); + let row = |id: &str| rows.iter().find(|row| row["_id"] == id).unwrap().clone(); + assert_eq!(row(&used)["productCount"], 1); + assert_eq!(row(&parent)["childCount"], 1); + assert_eq!(row(&child)["productCount"], 0); + + assert_eq!( + delete(child.clone(), Some(&admin)).await.status, + StatusCode::OK + ); + assert_eq!( + delete(child, Some(&admin)).await.status, + StatusCode::NOT_FOUND + ); + + // The last category stays: no bazaar can be created without one + sqlx::query("DELETE FROM products") + .execute(&db) + .await + .unwrap(); + assert_eq!(delete(used, Some(&admin)).await.status, StatusCode::OK); + assert_eq!( + delete(parent, Some(&admin)).await.body["code"], + "category.lastOne" + ); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_default_categories_come_with_their_english_names(db: PgPool) { + let app = app(&db).await; + rpc::call(&app.state, None, "categories.seedIfEmpty", json!({})) + .await + .unwrap(); + let list = app + .query("categories.getAllCategories", json!({}), None) + .await; + let bikes = list.body["value"] + .as_array() + .unwrap() + .iter() + .find(|c| c["label"] == "Fahrräder") + .unwrap(); + assert_eq!(bikes["translations"]["en"], "Bikes"); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn feature_flags(db: PgPool) { let app = app(&db).await; diff --git a/backend/tests/api/demo.rs b/backend/tests/api/demo.rs index 2db9d361..07b4c367 100644 --- a/backend/tests/api/demo.rs +++ b/backend/tests/api/demo.rs @@ -262,7 +262,19 @@ async fn bazaars_in_every_state(db: PgPool) { #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn english_demo_for_screenshots(db: PgPool) { let app = TestApp::new(db.clone()); + // The server ran first and created the German default categories + bazarpro_backend::rpc::call(&app.state, None, "categories.seedIfEmpty", json!({})) + .await + .unwrap(); demo::run(&app.state, options(Locale::En)).await.unwrap(); + assert_eq!( + count( + &db, + "SELECT count(*) FROM categories WHERE label = 'Kleidung'" + ) + .await, + 0 + ); sign_in(&app, "sarah.miller@example.org").await; let titles: Vec = sqlx::query_scalar("SELECT title FROM events ORDER BY title") .fetch_all(&db) diff --git a/backend/tests/api/events.rs b/backend/tests/api/events.rs index 0c6cad4d..af1491ae 100644 --- a/backend/tests/api/events.rs +++ b/backend/tests/api/events.rs @@ -62,12 +62,65 @@ async fn edit_args(app: &TestApp, session: &str, id: Uuid) -> Value { }) } +async fn get_event(app: &TestApp, session: &str, id: Uuid) -> Value { + app.query("events.getEvent", json!({ "id": id }), Some(session)) + .await + .body["value"] + .clone() +} + async fn single_mode_app(db: &PgPool) -> TestApp { let mut config = Config::for_tests(""); config.mode = InstanceMode::Single; TestApp::with_config(db.clone(), config) } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_address_is_stored_kept_by_older_apps_and_cleared(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let session = fixtures::session(&db, organizer).await; + let mut args = event_args("Kinderbasar", "logged-in"); + args["location"] = json!("Turnhalle Nord"); + args["address"] = json!({ "street": " Hauptstr. 5 ", "postalCode": "6020", "city": "Innsbruck", "country": "at" }); + let id = create(&app, &session, args).await; + let stored = get_event(&app, &session, id).await; + assert_eq!( + (&stored["street"], &stored["postalCode"], &stored["city"]), + (&json!("Hauptstr. 5"), &json!("6020"), &json!("Innsbruck")) + ); + assert_eq!(stored["country"], "AT"); + + // An app from before the address sends none: it stays + let reply = app + .mutation( + "events.editEvent", + edit_args(&app, &session, id).await, + Some(&session), + ) + .await; + assert_eq!(reply.status, StatusCode::OK, "{}", reply.body); + assert_eq!(get_event(&app, &session, id).await["city"], "Innsbruck"); + + // Empty parts clear it; an event without address leaves the fields out + let mut args = edit_args(&app, &session, id).await; + args["address"] = json!({ "street": "", "postalCode": " ", "city": null }); + let reply = app.mutation("events.editEvent", args, Some(&session)).await; + assert_eq!(reply.status, StatusCode::OK, "{}", reply.body); + let cleared = get_event(&app, &session, id).await; + assert!(cleared.get("street").is_none() && cleared.get("country").is_none()); + + for address in [ + json!({ "postalCode": "1".repeat(11) }), + json!({ "city": "Paris", "country": "FR" }), + ] { + let mut args = edit_args(&app, &session, id).await; + args["address"] = address; + let reply = app.mutation("events.editEvent", args, Some(&session)).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST, "{}", reply.body); + } +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn creating_an_event_makes_the_creator_organizer(db: PgPool) { let app = TestApp::new(db.clone()); diff --git a/backend/tests/api/import.rs b/backend/tests/api/import.rs index 433fce17..5eebdf9b 100644 --- a/backend/tests/api/import.rs +++ b/backend/tests/api/import.rs @@ -313,6 +313,38 @@ async fn imports_after_the_platform_stats_cron_ran(db: PgPool) { assert_eq!(users, 82); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn imports_after_the_start_created_the_default_categories(db: PgPool) { + let app = TestApp::new(db.clone()); + bazarpro_backend::rpc::call(&app.state, None, "categories.seedIfEmpty", json!({})) + .await + .unwrap(); + let created = json!(1_760_000_000_000.5_f64); + let export = write_export( + &[ + ( + "users", + vec![ + json!({ "_id": "user-a", "_creationTime": created, "email": "a@example.org", "status": "active" }), + ], + ), + ( + "categories", + vec![json!({ "_id": "cat-a", "_creationTime": created, "label": "Kleidung" })], + ), + ], + &[], + ); + import::run(&app.state, export.path().to_str().unwrap()) + .await + .unwrap(); + let ids: Vec = sqlx::query_scalar("SELECT id FROM categories") + .fetch_all(&db) + .await + .unwrap(); + assert_eq!(ids, [uuid_for("cat-a")]); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn refuses_to_import_into_a_database_with_users(db: PgPool) { let app = TestApp::new(db.clone()); diff --git a/backend/tests/api/query_cache.rs b/backend/tests/api/query_cache.rs index b49acc5d..4cfce0f8 100644 --- a/backend/tests/api/query_cache.rs +++ b/backend/tests/api/query_cache.rs @@ -1,4 +1,5 @@ -//! Shared answers for visitors: kept until a mutation touches what they read, compressed. +//! Shared answers for visitors, and for signed-in users who see the same: kept until a +//! mutation touches what they read, compressed. use crate::common; @@ -7,9 +8,11 @@ use std::time::Duration; use axum::body::Body; use axum::http::{Request, header}; +use common::fixtures::{self, EventSpec}; use common::{TestApp, disable_starter_products}; use serde_json::{Value, json}; use sqlx::PgPool; +use uuid::Uuid; /// The app with the hub listening to Postgres, as in production. async fn live_app(db: &PgPool) -> TestApp { @@ -53,7 +56,8 @@ async fn visitors_share_answers_until_a_mutation_touches_them(db: PgPool) { .await; assert_eq!(before.body["topics"], json!(["table:categories"])); - // A change nobody announces: visitors keep the cached answer, signed-in users not + // A change nobody announces: everybody keeps the cached answer, the categories are the + // same for all insert_category_unnoticed(&db, "Unbemerkt").await; let cached = app .query("categories.getAllCategories", json!({}), None) @@ -62,7 +66,7 @@ async fn visitors_share_answers_until_a_mutation_touches_them(db: PgPool) { let signed_in = app .query("categories.getAllCategories", json!({}), Some(&admin)) .await; - assert!(labels(&signed_in.body).contains(&"Unbemerkt".to_owned())); + assert_eq!(labels(&signed_in.body), labels(&before.body)); app.mutation( "categories.createCategory", @@ -130,3 +134,109 @@ async fn answers_are_gzipped_when_the_client_accepts_it(db: PgPool) { ); assert_eq!(labels(&plain.body).len(), 5); } + +fn titles(body: &Value) -> Vec { + let mut titles: Vec = body["value"] + .as_array() + .unwrap() + .iter() + .map(|item| item["title"].as_str().unwrap().to_owned()) + .collect(); + titles.sort(); + titles +} + +async fn rename_event_unnoticed(db: &PgPool, event: Uuid, title: &str) { + sqlx::query("UPDATE events SET title = $2 WHERE id = $1") + .bind(event) + .bind(title) + .execute(db) + .await + .unwrap(); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn signed_in_users_without_a_part_in_the_event_share_what_visitors_see(db: PgPool) { + let app = live_app(&db).await; + let organizer = fixtures::user(&db, "Orga").await; + let event = fixtures::event(&db, EventSpec::new("Basar", organizer)).await; + let erika = fixtures::user(&db, "Erika").await; + let skates = fixtures::product(&db, erika, "Inliner", 20.0).await; + fixtures::event_product(&db, event, skates, "available").await; + let buyer = fixtures::user(&db, "Bob").await; + let sessions = [ + fixtures::session(&db, organizer).await, + fixtures::session(&db, erika).await, + fixtures::session(&db, fixtures::admin(&db, "Admin").await).await, + ]; + let buyer = fixtures::session(&db, buyer).await; + let items = json!({ "eventId": event }); + let page = json!({ "id": event }); + let visitor = app + .query("eventProducts.getProductsForEvent", items.clone(), None) + .await; + assert_eq!(titles(&visitor.body), ["Inliner"]); + app.query("events.getPublicEventForViewer", page.clone(), None) + .await; + + // Changes nobody announces: the buyer gets the cached answers of the visitors, the + // team, the seller and administrators see more than visitors and ask the database + let carl = fixtures::user(&db, "Carl").await; + let bike = fixtures::product(&db, carl, "Fahrrad", 80.0).await; + fixtures::event_product(&db, event, bike, "available").await; + rename_event_unnoticed(&db, event, "Neuer Name").await; + let shared = app + .query( + "eventProducts.getProductsForEvent", + items.clone(), + Some(&buyer), + ) + .await; + assert_eq!(shared.body, visitor.body); + let shared = app + .query("events.getPublicEventForViewer", page.clone(), Some(&buyer)) + .await; + assert_eq!(shared.body["value"]["title"], "Basar"); + for session in &sessions { + let own = app + .query( + "eventProducts.getProductsForEvent", + items.clone(), + Some(session), + ) + .await; + assert_eq!(titles(&own.body), ["Fahrrad", "Inliner"]); + let own = app + .query( + "events.getPublicEventForViewer", + page.clone(), + Some(session), + ) + .await; + assert_eq!(own.body["value"]["title"], "Neuer Name"); + } +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn signed_in_users_share_the_event_list_administrators_not(db: PgPool) { + let app = live_app(&db).await; + let organizer = fixtures::user(&db, "Orga").await; + let event = fixtures::event(&db, EventSpec::new("Basar", organizer)).await; + let anna = fixtures::session(&db, fixtures::user(&db, "Anna").await).await; + let bob = fixtures::session(&db, fixtures::user(&db, "Bob").await).await; + let admin = fixtures::session(&db, fixtures::admin(&db, "Admin").await).await; + let list = json!({ "includePast": false }); + let title = |reply: common::Reply| reply.body["value"][0]["title"].clone(); + + let visitors = title(app.query("events.get", list.clone(), None).await); + rename_event_unnoticed(&db, event, "Zweiter Name").await; + // Signed-in users see other events than visitors: an answer of their own, shared + let anna_sees = title(app.query("events.get", list.clone(), Some(&anna)).await); + rename_event_unnoticed(&db, event, "Dritter Name").await; + let bob_sees = title(app.query("events.get", list.clone(), Some(&bob)).await); + let admin_sees = title(app.query("events.get", list.clone(), Some(&admin)).await); + assert_eq!( + [visitors, anna_sees, bob_sees, admin_sees], + ["Basar", "Zweiter Name", "Zweiter Name", "Dritter Name"].map(Value::from) + ); +} diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 51eb2645..3557096e 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -251,6 +251,10 @@ fn pickup_text_with_a_fee_to_pay_and_a_long_item_list() { cover_image: None, event_map_image: None, location: "Halle".into(), + street: None, + postal_code: None, + city: None, + country: None, start_date: time("2026-10-17T08:00:00Z"), end_date: time("2026-10-17T12:00:00Z"), contact_info: String::new(), diff --git a/docker-compose.yml b/docker-compose.yml index 7b34def8..13b26b13 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,6 +26,8 @@ services: environment: - SITE_URL=https://${DOMAIN_NAME:-bazarpro.de} - BACKEND_URL=http://bazarpro-backend:3000 + - PLAUSIBLE_DOMAIN=${DOMAIN_NAME:-bazarpro.de} + - PLAUSIBLE_API_HOST=${PLAUSIBLE_API_HOST:-} labels: - 'traefik.enable=true' - 'traefik.docker.network=proxy' diff --git a/public/images/covers/bike.webp b/public/images/covers/bike.webp new file mode 100644 index 00000000..a6c77da2 Binary files /dev/null and b/public/images/covers/bike.webp differ diff --git a/public/images/covers/clothing.webp b/public/images/covers/clothing.webp new file mode 100644 index 00000000..02e9fa79 Binary files /dev/null and b/public/images/covers/clothing.webp differ diff --git a/public/images/covers/kids.webp b/public/images/covers/kids.webp new file mode 100644 index 00000000..695918c4 Binary files /dev/null and b/public/images/covers/kids.webp differ diff --git a/public/images/covers/market.webp b/public/images/covers/market.webp new file mode 100644 index 00000000..1a31c0e3 Binary files /dev/null and b/public/images/covers/market.webp differ diff --git a/public/images/covers/pattern.webp b/public/images/covers/pattern.webp new file mode 100644 index 00000000..04ce43e9 Binary files /dev/null and b/public/images/covers/pattern.webp differ diff --git a/public/images/covers/ski.webp b/public/images/covers/ski.webp new file mode 100644 index 00000000..7ff7d0c2 Binary files /dev/null and b/public/images/covers/ski.webp differ diff --git a/public/logo.png b/public/logo.png new file mode 100644 index 00000000..740d2fa4 Binary files /dev/null and b/public/logo.png differ diff --git a/scripts/event-covers/index.html b/scripts/event-covers/index.html new file mode 100644 index 00000000..d7732ec9 --- /dev/null +++ b/scripts/event-covers/index.html @@ -0,0 +1,27 @@ + + + + + + + +
+ + + diff --git a/scripts/event-covers/render.mjs b/scripts/event-covers/render.mjs new file mode 100644 index 00000000..8a7814ab --- /dev/null +++ b/scripts/event-covers/render.mjs @@ -0,0 +1,35 @@ +// Renders the scenes to public/images/covers/.webp: node scripts/event-covers/render.mjs +import { mkdirSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { chromium } from 'playwright'; +import { createServer } from 'vite'; + +const output = resolve('public/images/covers'); +mkdirSync(output, { recursive: true }); + +const server = await createServer({ server: { port: 5199 }, logLevel: 'error' }); +await server.listen(); +const browser = await chromium.launch(); +const page = await browser.newPage({ viewport: { width: 1600, height: 900 } }); +await page.goto('http://localhost:5199/scripts/event-covers/index.html'); +await page.waitForSelector('[data-cover]'); + +for (const cover of await page.locator('[data-cover]').all()) { + const id = await cover.getAttribute('data-cover'); + const png = (await cover.screenshot()).toString('base64'); + const webp = await page.evaluate(async (data) => { + const image = new Image(); + image.src = `data:image/png;base64,${data}`; + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + canvas.getContext('2d').drawImage(image, 0, 0); + return canvas.toDataURL('image/webp', 0.85).split(',')[1]; + }, png); + writeFileSync(resolve(output, `${id}.webp`), Buffer.from(webp, 'base64')); + console.log(id, Math.round((webp.length * 0.75) / 1024), 'KB'); +} + +await browser.close(); +await server.close(); diff --git a/scripts/event-covers/scenes.tsx b/scripts/event-covers/scenes.tsx new file mode 100644 index 00000000..07686dc2 --- /dev/null +++ b/scripts/event-covers/scenes.tsx @@ -0,0 +1,156 @@ +/* eslint-disable react-refresh/only-export-components -- a page of its own, not hot-reloaded */ +import type { CSSProperties, ReactNode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { + ItemDrawing, + type ItemDrawingId, +} from '../../src/components/illustrations/ItemIllustrations'; + +/* + * Source of the drawn cover templates in public/images/covers (see render.mjs; the others are + * photos, see src/lib/eventCovers.ts): scenes of 1600x900 + * made of the wizard's item drawings. The hero crops them to 21:9 and puts the title over + * the lower edge, so what matters stays between y 110 and 620 and x 80 and 1520. + */ + +function Item({ + id, + x, + y, + w, + rotate = 0, + filter, +}: { + id: ItemDrawingId; + x: number; + y: number; + w: number; + rotate?: number; + filter?: string; +}) { + const style: CSSProperties = { + position: 'absolute', + left: x, + top: y, + width: w, + height: w * 0.75, + transform: rotate ? `rotate(${rotate}deg)` : undefined, + filter, + }; + return ( +
+ +
+ ); +} + +function Backdrop({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +function SkiSlope() { + const fir = (x: number, y: number, scale: number) => ( + + + + + + ); + return ( + <> + + + + + + + + + + + + + {fir(120, 540, 1.1)} + {fir(230, 530, 0.8)} + {fir(1480, 520, 1.15)} + {fir(1370, 525, 0.75)} + + + + + + + ); +} + +function Pattern() { + const ids: ItemDrawingId[] = [ + 'jacket', + 'toyBricks', + 'skiHelmet', + 'handbag', + 'kidsClothes', + 'bikeLock', + 'ankleBoots', + 'skiBoots', + 'rainBoots', + 'kidsBike', + 'cityBike', + 'skis', + ]; + const tiles = ['#fef3c7', '#dbeafe', '#fce7f3', '#dcfce7']; + return ( + <> + {Array.from({ length: 24 }, (_, i) => { + const col = i % 6; + const row = Math.floor(i / 6); + return ( +
+
+ +
+
+ ); + })} + + ); +} + +const SCENES: Record ReactNode> = { + ski: SkiSlope, + pattern: Pattern, +}; + +function Scenes() { + return ( + <> + {Object.entries(SCENES).map(([id, Scene]) => ( +
+ +
+ ))} + + ); +} + +createRoot(document.getElementById('root')!).render(); diff --git a/server/index.test.ts b/server/index.test.ts index affb836c..e1056bfd 100644 --- a/server/index.test.ts +++ b/server/index.test.ts @@ -116,7 +116,14 @@ describe('static files', () => { const page = await get(`/P/${id.toUpperCase()}`, { redirect: 'manual' }); expect(page.response.status).toBe(301); expect(page.response.headers.get('location')).toBe(`/products/view/${id}`); - expect((await get('/p/', { redirect: 'manual' })).response.status).toBe(200); + expect((await get('/p/', { redirect: 'manual' })).response.status).toBe(404); + }); + + it('answers unknown paths with 404 and noindex, but still with the app', async () => { + const page = await get('/does-not-exist'); + expect(page.response.status).toBe(404); + expect(page.body).toContain('
'); + expect(page.body).toContain('noindex'); }); it('does not serve files outside the dist directory', async () => { diff --git a/server/index.ts b/server/index.ts index 5fb6368a..c00a8029 100644 --- a/server/index.ts +++ b/server/index.ts @@ -8,6 +8,7 @@ import { createGzip } from 'node:zlib'; import { createBackendClient, type BackendQueryClient } from './backend.ts'; import { isDynamicRoute, resolvePage, resolveSiteName, resolveSitemap } from './pages.ts'; import { isMarketingPath, parseInstanceMode, type InstanceMode } from './public-routes.ts'; +import { isAppRoute } from '../src/shared/appRoutes.ts'; import { shortProductLinkTarget } from '../src/shared/productLinks.ts'; import { injectRuntime, @@ -15,7 +16,7 @@ import { type ClientConfig, type RuntimeOptions, } from './runtime.ts'; -import { injectHead } from './seo.ts'; +import { injectHead, notFoundMeta } from './seo.ts'; /** * Production web server for the frontend. Serves the Vite build like the @@ -234,7 +235,21 @@ export async function createServer({ } // Client-side route: the SPA decides what to render - send(req, res, 200, CONTENT_TYPES['.html'], REVALIDATE, shellHtml); + if (isAppRoute(pathname)) { + send(req, res, 200, CONTENT_TYPES['.html'], REVALIDATE, shellHtml); + return; + } + + // Unknown path: the app sends visitors to the start page, search engines get a 404 + const siteName = backend ? await resolveSiteName(backend, mode) : undefined; + send( + req, + res, + 404, + CONTENT_TYPES['.html'], + REVALIDATE, + injectHead(shellHtml, notFoundMeta(siteName)) + ); } catch (err) { console.error('[server] request failed', req.url, err); if (!res.headersSent) res.writeHead(500); diff --git a/server/seo.test.ts b/server/seo.test.ts index 2870be64..d5dfbb72 100644 --- a/server/seo.test.ts +++ b/server/seo.test.ts @@ -66,6 +66,25 @@ describe('eventMeta', () => { expect(meta.title).toBe('Angebote bei Fahrradbasar in Ulm | BazarPro'); expect(meta.canonical).toBe('https://bazarpro.de/public-events/evt1/products'); expect(meta.image).toBeUndefined(); + // Both pages describe the same event; Google needs an image for event results + expect(meta.jsonLd).toMatchObject({ + url: 'https://bazarpro.de/public-events/evt1', + image: ['https://bazarpro.de/og-image.png'], + }); + }); + + it('structures the address of the venue', () => { + const meta = eventMeta( + { ...event, location: 'Turnhalle Nord, Hauptstr. 5, 89073 Ulm' }, + 'https://bazarpro.de', + 'event' + ); + expect(meta.jsonLd).toMatchObject({ + location: { + name: 'Turnhalle Nord', + address: { '@type': 'PostalAddress', postalCode: '89073', addressLocality: 'Ulm' }, + }, + }); }); it('describes the date when the event has no description', () => { diff --git a/server/seo.ts b/server/seo.ts index 0e81aa31..d56eac61 100644 --- a/server/seo.ts +++ b/server/seo.ts @@ -1,3 +1,4 @@ +import { eventJsonLd, eventTown } from '../src/shared/eventJsonLd.ts'; import { stripMarkdownToText } from '../src/lib/markdown.ts'; /** @@ -23,6 +24,10 @@ export interface PublicEvent { title: string; description?: string; location: string; + street?: string | null; + postalCode?: string | null; + city?: string | null; + country?: string | null; startDate: number; endDate: number; coverImageUrl?: string | null; @@ -39,6 +44,8 @@ export interface PublicProduct { /** Default site name; a self-hosted instance passes its association's name instead. */ export const SITE_NAME = 'BazarPro'; +/** General preview picture (public/og-image.png), like the client Seo component */ +const DEFAULT_IMAGE = '/og-image.png'; const DEFAULT_DESCRIPTION = 'Kostenlose Open-Source-Software für Kinderkleiderbasar, Fahrradbörse und Flohmarkt: QR-Etiketten, Kasse per Smartphone, automatische Abrechnung.'; @@ -76,7 +83,7 @@ export function eventMeta( ): PageMeta { const description = buildDescription( event.description, - `Event in ${event.location} am ${formatDateRange(event.startDate, event.endDate)}.` + `Event in ${eventTown(event)} am ${formatDateRange(event.startDate, event.endDate)}.` ); const eventUrl = `${siteUrl}/public-events/${event._id}`; const canonical = page === 'event' ? eventUrl : `${eventUrl}/products`; @@ -85,25 +92,25 @@ export function eventMeta( return { title: page === 'event' - ? `${event.title} in ${event.location} | ${siteName}` - : `Angebote bei ${event.title} in ${event.location} | ${siteName}`, + ? `${event.title} in ${eventTown(event)} | ${siteName}` + : `Angebote bei ${event.title} in ${eventTown(event)} | ${siteName}`, description, canonical, image, jsonLdId: page === 'event' ? `event-jsonld-${event._id}` : `event-products-jsonld-${event._id}`, - jsonLd: { - '@context': 'https://schema.org', - '@type': 'Event', - name: event.title, + jsonLd: eventJsonLd({ + title: event.title, description, - startDate: new Date(event.startDate).toISOString(), - endDate: new Date(event.endDate).toISOString(), - eventStatus: 'https://schema.org/EventScheduled', - eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode', - location: { '@type': 'Place', name: event.location, address: event.location }, + location: event.location, + street: event.street, + postalCode: event.postalCode, + city: event.city, + country: event.country, + startDate: event.startDate, + endDate: event.endDate, url: eventUrl, - ...(image ? { image: [image] } : {}), - }, + image: image ?? `${siteUrl}${DEFAULT_IMAGE}`, + }), }; } diff --git a/src/App.tsx b/src/App.tsx index 6959d722..381339e5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,6 @@ import './styles/App.css'; import { useAuthState, useQuery, useAuthActions } from './lib/api/react'; -import { useEffect } from 'react'; +import { Suspense, useEffect } from 'react'; import { BrowserRouter as Router, Routes, @@ -15,28 +15,20 @@ import { LoginPage } from './pages/public/auth/LoginPage'; import { ThemeProvider } from './components/ui/theme-provider'; import { Toaster } from 'sonner'; import { RegisterPage } from './pages/public/auth/RegisterPage'; -import { MyProductsPage } from './pages/seller/products/MyProductsPage'; -import { MySalesPage } from './pages/seller/sales/MySalesPage'; -import { ProductForm } from './pages/seller/products/ProductForm'; import { PublicProduct } from './pages/public/products/PublicProduct'; import { ShortProductLink } from './pages/public/products/ShortProductLink'; -import { EventManagementDashboard } from './pages/organizer/events/EventManagementDashboard'; -import { SettingsPage } from './pages/organizer/events/dashboard/SettingsPage'; import { UserRoleProvider } from './context/UserRoleProvider'; import { NavigationHistoryProvider } from './context/NavigationHistoryProvider'; import { LandingPage } from './pages/public/landing/LandingPage'; import { HomePage } from './pages/dashboard/HomePage'; import { CurrentBazaarRedirect, InstanceHomePage } from './pages/public/instance/InstanceHomePage'; -import { EditEventForm } from './pages/organizer/events/EditEventForm'; import { PublicEventLanding } from './pages/public/events/PublicEventPage'; import { PublicEventProductsPage } from './pages/public/events/PublicEventProductsPage'; -import { SearchEventsPage } from './pages/seller/events/SearchEventsPage'; import { FeaturesPage } from './pages/public/company/FeaturesPage'; import { PricingPage } from './pages/public/company/PricingPage'; import { AboutPage } from './pages/public/company/AboutPage'; import { ContactPage } from './pages/public/company/ContactPage'; import { LegalPage } from './pages/public/legal/LegalPage'; -import { AccountPage } from './pages/account/AccountPage'; import { UnsubscribePage } from './pages/public/notifications/UnsubscribePage'; import { useTheme } from './components/ui/theme-context'; import { ResponsiveSidebar } from './components/layout/ResponsiveSidebar'; @@ -47,20 +39,6 @@ import { Header } from './components/layout/Header'; import { SidebarProvider } from './context/SidebarProvider'; import { OnboardingProvider } from './context/OnboardingContext'; import { OnboardingOverlay } from './components/onboarding/OnboardingOverlay'; -import { AdminPage } from './pages/administrator/AdminPage'; -import { AdminUsersPage } from './pages/administrator/AdminUsersPage'; -import { AdminEventsPage } from './pages/administrator/AdminEventsPage'; -import { AdminOverviewPage } from './pages/administrator/AdminOverviewPage'; -import { AdminReportsPage } from './pages/administrator/AdminReportsPage'; -import { AdminContentPage } from './pages/administrator/AdminContentPage'; -import { AdminMessagesPage } from './pages/administrator/AdminMessagesPage'; -import { AdminLogPage } from './pages/administrator/AdminLogPage'; -import { AdminSettingsPage } from './pages/administrator/AdminSettingsPage'; -import { AdminLegalPagesPage } from './pages/administrator/AdminLegalPagesPage'; -import { SellerManagementPage } from './pages/organizer/events/dashboard/SellerManagementPage'; -import { ProductManagementPage } from './pages/organizer/events/dashboard/ProductManagementPage'; -import { CashReconciliationPage } from './pages/organizer/events/dashboard/CashReconciliationPage'; -import { CheckoutPage } from './pages/organizer/events/dashboard/CheckoutPage'; import { api } from './lib/api/functions'; import { loginPath } from './lib/loginRedirect'; import { runtimeConfig } from './lib/runtimeConfig'; @@ -69,6 +47,87 @@ import { useTranslation } from 'react-i18next'; import { Capacitor } from '@capacitor/core'; import { WELCOME_PATH } from './native/settings'; import { PageSkeleton } from './components/ui/loading'; +import { lazyPage, preloadPages } from './lib/lazyPage'; +import { AdminGuard } from './pages/administrator/components/AdminShared'; + +// Pages behind the sign-in: own chunks, so the public pages load faster +const MyProductsPage = lazyPage( + () => import('./pages/seller/products/MyProductsPage'), + 'MyProductsPage' +); +const MySalesPage = lazyPage(() => import('./pages/seller/sales/MySalesPage'), 'MySalesPage'); +const ProductForm = lazyPage(() => import('./pages/seller/products/ProductForm'), 'ProductForm'); +const EventManagementDashboard = lazyPage( + () => import('./pages/organizer/events/EventManagementDashboard'), + 'EventManagementDashboard' +); +const SettingsPage = lazyPage( + () => import('./pages/organizer/events/dashboard/SettingsPage'), + 'SettingsPage' +); +const EditEventForm = lazyPage( + () => import('./pages/organizer/events/EditEventForm'), + 'EditEventForm' +); +const SearchEventsPage = lazyPage( + () => import('./pages/seller/events/SearchEventsPage'), + 'SearchEventsPage' +); +const AccountPage = lazyPage(() => import('./pages/account/AccountPage'), 'AccountPage'); +const AdminPage = lazyPage(() => import('./pages/administrator/AdminPage'), 'AdminPage'); +const AdminUsersPage = lazyPage( + () => import('./pages/administrator/AdminUsersPage'), + 'AdminUsersPage' +); +const AdminEventsPage = lazyPage( + () => import('./pages/administrator/AdminEventsPage'), + 'AdminEventsPage' +); +const AdminOverviewPage = lazyPage( + () => import('./pages/administrator/AdminOverviewPage'), + 'AdminOverviewPage' +); +const AdminReportsPage = lazyPage( + () => import('./pages/administrator/AdminReportsPage'), + 'AdminReportsPage' +); +const AdminContentPage = lazyPage( + () => import('./pages/administrator/AdminContentPage'), + 'AdminContentPage' +); +const AdminMessagesPage = lazyPage( + () => import('./pages/administrator/AdminMessagesPage'), + 'AdminMessagesPage' +); +const AdminCategoriesPage = lazyPage( + () => import('./pages/administrator/AdminCategoriesPage'), + 'AdminCategoriesPage' +); +const AdminLogPage = lazyPage(() => import('./pages/administrator/AdminLogPage'), 'AdminLogPage'); +const AdminSettingsPage = lazyPage( + () => import('./pages/administrator/AdminSettingsPage'), + 'AdminSettingsPage' +); +const AdminLegalPagesPage = lazyPage( + () => import('./pages/administrator/AdminLegalPagesPage'), + 'AdminLegalPagesPage' +); +const SellerManagementPage = lazyPage( + () => import('./pages/organizer/events/dashboard/SellerManagementPage'), + 'SellerManagementPage' +); +const ProductManagementPage = lazyPage( + () => import('./pages/organizer/events/dashboard/ProductManagementPage'), + 'ProductManagementPage' +); +const CashReconciliationPage = lazyPage( + () => import('./pages/organizer/events/dashboard/CashReconciliationPage'), + 'CashReconciliationPage' +); +const CheckoutPage = lazyPage( + () => import('./pages/organizer/events/dashboard/CheckoutPage'), + 'CheckoutPage' +); function PublicEventWrapper() { const { eventId } = useParams(); @@ -113,6 +172,21 @@ function landingPage() { return isSingleInstance ? : ; } +/** Signed in: loads the remaining pages while idle, they then also open without connection. */ +function PreloadSignedInPages() { + const { isAuthenticated } = useAuthState(); + useEffect(() => { + if (!isAuthenticated) return; + if (typeof window.requestIdleCallback === 'function') { + const id = window.requestIdleCallback(preloadPages, { timeout: 5000 }); + return () => window.cancelIdleCallback(id); + } + const timer = setTimeout(preloadPages, 2000); + return () => clearTimeout(timer); + }, [isAuthenticated]); + return null; +} + /** Takes over the language saved at the account after login. */ function AccountLocaleSync() { useSyncAccountLocale(); @@ -126,6 +200,7 @@ function App() { + @@ -176,6 +251,22 @@ function App() { element={} /> + {/* Visitors try the creation wizard before signing up (platform only) */} + + + + ) : ( + }> + + + ) + } + /> + }> } /> - } /> } /> } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - } /> + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> @@ -238,6 +331,15 @@ function App() { } function PrivateMainAppContent() { + return ( + + + + ); +} + +/** Pages behind the sign-in: visitors go to the login and come back afterwards. */ +function RequireSignIn({ children }: { children: React.ReactNode }) { const location = useLocation(); const { isAuthenticated, isLoading } = useAuthState(); const { signOut } = useAuthActions(); @@ -262,7 +364,7 @@ function PrivateMainAppContent() { return ; } - return ; + return }>{children}; } export default App; diff --git a/src/assets/landing-page-hero.jpg b/src/assets/landing-page-hero.jpg deleted file mode 100644 index c11a5e81..00000000 Binary files a/src/assets/landing-page-hero.jpg and /dev/null differ diff --git a/src/components/EventHero.tsx b/src/components/EventHero.tsx index 6a8151c3..0ccb8812 100644 --- a/src/components/EventHero.tsx +++ b/src/components/EventHero.tsx @@ -2,7 +2,7 @@ import { Calendar, MapPin } from 'lucide-react'; import { ImageWithFallback } from './ui/image-with-fallback'; import type { Id } from '../lib/api/types'; import { formatDateRangeDE } from '../lib/utils'; -import { cn } from './utils'; +import { cn } from '../lib/utils'; import { useTranslation } from 'react-i18next'; interface EventHeroProps { diff --git a/src/components/auth/PasswordInput.tsx b/src/components/auth/PasswordInput.tsx new file mode 100644 index 00000000..f9364c1d --- /dev/null +++ b/src/components/auth/PasswordInput.tsx @@ -0,0 +1,28 @@ +import { Eye, EyeOff } from 'lucide-react'; +import { useState, type ComponentProps } from 'react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '../../lib/utils'; +import { Input } from '../ui/input'; + +/** + * Password field with a button to show what was typed: instead of a second field to + * repeat the password. Takes the props of Input, also `register(...)` of react-hook-form. + */ +export function PasswordInput({ className, ...props }: Omit, 'type'>) { + const { t } = useTranslation('auth'); + const [shown, setShown] = useState(false); + return ( +
+ + +
+ ); +} diff --git a/src/components/events/EventFilters.tsx b/src/components/events/EventFilters.tsx index 1d1e3a64..2e966c70 100644 --- a/src/components/events/EventFilters.tsx +++ b/src/components/events/EventFilters.tsx @@ -1,5 +1,4 @@ -import { Search } from 'lucide-react'; -import { Input } from '../ui/input'; +import { SearchInput } from '../ui/search-input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'; import { Checkbox } from '../ui/checkbox'; import { Label } from '../ui/label'; @@ -27,15 +26,11 @@ export function EventFilters({
-
- - onSearchChange(e.target.value)} - /> -
+ onSearchChange(e.target.value)} + /> setSearch(e.target.value)} - /> -
+ setSearch(e.target.value)} + /> {candidates.length === 0 ? (

{t('helperPicker.none')}

) : ( diff --git a/src/components/illustrations/ItemIllustrations.tsx b/src/components/illustrations/ItemIllustrations.tsx new file mode 100644 index 00000000..39245053 --- /dev/null +++ b/src/components/illustrations/ItemIllustrations.tsx @@ -0,0 +1,614 @@ +import type { ReactNode } from 'react'; +import { BikeIllustration } from '../../pages/public/landing/components/demo/Illustrations'; +import { cn } from '../../lib/utils'; + +/* + * Drawn items for the creation wizard and the landing page: what sellers bring to each + * kind of bazaar. SVG like the bike of the landing page, so they scale, stay license-free + * and look the same in both themes (they sit on a light backdrop). Every drawing uses the + * same 200x150 box with the item centered, so they line up at any size. + */ + +export type ItemKind = 'kids' | 'clothing' | 'ski' | 'bike'; + +export type ItemDrawingId = + | 'kidsClothes' + | 'toyBricks' + | 'rainBoots' + | 'jacket' + | 'ankleBoots' + | 'handbag' + | 'skis' + | 'skiBoots' + | 'skiHelmet' + | 'cityBike' + | 'kidsBike' + | 'bikeLock'; + +/** The three example items of each kind, in the order of eventTypes..exampleItems. */ +const KIND_ITEMS: Record = { + kids: ['kidsClothes', 'toyBricks', 'rainBoots'], + clothing: ['jacket', 'ankleBoots', 'handbag'], + ski: ['skis', 'skiBoots', 'skiHelmet'], + bike: ['cityBike', 'kidsBike', 'bikeLock'], +}; + +const INK = '#27272a'; + +function Svg({ children, className }: { children: ReactNode; className?: string }) { + return ( + + ); +} + +/** A striped children's T-shirt and denim dungarees with bib pocket and rolled-up legs. */ +function KidsClothes() { + return ( + <> + {/* T-shirt: sloping shoulders, sleeves angled out and down, wide body */} + + {[76, 88, 100].map((y) => ( + + ))} + + + + {/* dungarees */} + + + + + + + + + + + + ); +} + +// Isometric projection for the building bricks: one stud is U wide +const U = 12; +const ISO_X = 0.866; +function iso(ox: number, oy: number, i: number, j: number, k: number): string { + return `${ox + (i - j) * ISO_X * U},${oy + (i + j) * 0.5 * U - k}`; +} + +/** One building brick in isometric view: top and two sides, studs as small cylinders. */ +function IsoBrick({ + ox, + oy, + w, + d, + colors, +}: { + ox: number; + oy: number; + w: number; + d: number; + colors: [top: string, left: string, right: string]; +}) { + const h = 11; + const [top, left, right] = colors; + const studs = []; + for (let j = 0; j < d; j++) { + for (let i = 0; i < w; i++) studs.push([i + 0.5, j + 0.5]); + } + studs.sort((a, b) => a[0] + a[1] - (b[0] + b[1])); + return ( + + + + + {studs.map(([i, j]) => { + const [cx, cy] = iso(ox, oy, i, j, h).split(',').map(Number); + const rx = 3.3; + const ry = 1.9; + return ( + + + + + ); + })} + + ); +} + +const RED: [string, string, string] = ['#f87171', '#dc2626', '#b91c1c']; +const YELLOW: [string, string, string] = ['#fde047', '#eab308', '#ca8a04']; +const BLUE: [string, string, string] = ['#60a5fa', '#2563eb', '#1d4ed8']; +const GREEN: [string, string, string] = ['#4ade80', '#16a34a', '#15803d']; + +/** Building bricks: a stack of three and two loose ones, back to front. */ +function ToyBricks() { + return ( + <> + + + + + + + + ); +} + +/** One children's rubber boot, toe to the left: shaft, rounded toe, thin sole on the foot. */ +function RubberBoot({ x, y }: { x: number; y: number }) { + const fill = '#ef4444'; + const shade = '#b91c1c'; + return ( + + + + {[ + [40, 28], + [58, 38], + [42, 50], + [60, 62], + [22, 76], + [44, 76], + ].map(([cx, cy]) => ( + + ))} + + + ); +} + +/** A pair of children's rubber boots with white dots. */ +function RainBoots() { + return ( + <> + + + + ); +} + +/** A zipped jacket laid flat: stand-up collar, sleeves with cuffs, pockets. */ +function Jacket() { + return ( + <> + {/* sleeves */} + + + + + {/* body */} + + {/* collar */} + + + + + + + ); +} + +/** + * One women's ankle boot, toe to the left, in a 90x90 box: the foot slopes down from the + * heel to the toe, zip on the side, thin sole along the foot and a block heel. + */ +function AnkleBoot({ x, y }: { x: number; y: number }) { + const fill = '#b45309'; + const shade = '#78350f'; + return ( + + {/* block heel */} + + {/* upper */} + + {/* zip */} + + + + {/* thin sole */} + + + ); +} + +/** A pair of women's ankle boots. */ +function AnkleBoots() { + return ( + <> + + + + ); +} + +/** A leather handbag with two handles and a flap. */ +function Handbag() { + return ( + <> + + + + + + + + ); +} + +/** One ski from above, tip at the top, with toe and heel piece of the binding. 14x132. */ +function Ski() { + return ( + + + + + {/* binding: toe piece, heel piece with brake arms */} + + + + + + + ); +} + +/** One ski pole from grip to tip: grip, strap, shaft, basket. */ +function Pole({ from, to }: { from: [number, number]; to: [number, number] }) { + const [x1, y1] = from; + const [x2, y2] = to; + const at = (t: number): [number, number] => [x1 + (x2 - x1) * t, y1 + (y2 - y1) * t]; + const angle = (Math.atan2(y2 - y1, x2 - x1) * 180) / Math.PI - 90; + const [bx, by] = at(0.88); + const [gx, gy] = at(0.1); + return ( + + + + + + + + ); +} + +/** A pair of skis leaning in an A, the poles next to them. */ +function Skis() { + return ( + <> + + + + + + + + + + ); +} + +/** + * A ski boot, toe to the left: forward-leaning black cuff over the shell, buckles lying on + * the front, power strap at the top and a sole with lips at toe and heel. + */ +function SkiBoots() { + const buckle = (x: number, y: number, angle: number) => ( + + + + + ); + return ( + <> + {/* liner and tongue */} + + {/* lower shell */} + + + {/* cuff, leaning forward */} + + + + {buckle(88, 46, -18)} + {buckle(94, 66, -18)} + {buckle(74, 92, -22)} + {/* sole with lips */} + + + + ); +} + +/** A ski helmet from the side: shell down over the ears, ear pad, chin strap, goggles. */ +function SkiHelmet() { + return ( + <> + + + + + + + + {/* goggles on the front, strap around the shell */} + + + + + ); +} + +/** A children's bike with training wheel: proper frame, fork, chain guard. */ +function KidsBike() { + const wheel = (cx: number) => ( + + + + {[0, 45, 90, 135].map((a) => { + const r = (a * Math.PI) / 180; + return ( + + ); + })} + + + ); + return ( + <> + {wheel(54)} + {wheel(146)} + {/* training wheel on the rear axle */} + + + + {/* chain and seat stays, seat tube, top tube, down tube, fork */} + + + + + + + + + + + + ); +} + +/** A U-lock: thin coated steel shackle, thick crossbar with lock cylinder, keys on a ring. */ +function BikeLock() { + return ( + <> + + + + + + + + {/* keys */} + + + + + ); +} + +const DRAWINGS: Record, () => ReactNode> = { + kidsClothes: KidsClothes, + toyBricks: ToyBricks, + rainBoots: RainBoots, + jacket: Jacket, + ankleBoots: AnkleBoots, + handbag: Handbag, + skis: Skis, + skiBoots: SkiBoots, + skiHelmet: SkiHelmet, + kidsBike: KidsBike, + bikeLock: BikeLock, +}; + +/** One item, drawn in the shared 200x150 box. */ +export function ItemDrawing({ id, className }: { id: ItemDrawingId; className?: string }) { + // The old city bike of the landing page story has its own, slightly wider box + if (id === 'cityBike') return ; + const Drawing = DRAWINGS[id]; + return ( + + + + ); +} + +const BACKDROPS: Record = { + kids: 'from-amber-100 via-orange-50 to-rose-100', + clothing: 'from-rose-100 via-stone-50 to-emerald-100', + ski: 'from-sky-200 via-white to-slate-200', + bike: 'from-sky-200 via-sky-100 to-stone-300', +}; + +/** + * An item as a "photo" on the light backdrop of its kind: `item` picks one of the three + * examples; without it the three are arranged like a group shot (cards, page headers). + */ +export function ItemPhoto({ + kind, + item, + className, +}: { + kind: ItemKind; + item?: 0 | 1 | 2; + className?: string; +}) { + const [main, second, third] = KIND_ITEMS[kind]; + return ( +
+ {item !== undefined ? ( + + ) : ( +
+ + + +
+ )} +
+ ); +} diff --git a/src/components/layout/ResponsiveSidebar.tsx b/src/components/layout/ResponsiveSidebar.tsx index fa8aa230..09b76b52 100644 --- a/src/components/layout/ResponsiveSidebar.tsx +++ b/src/components/layout/ResponsiveSidebar.tsx @@ -118,11 +118,6 @@ export function ResponsiveSidebar({ children }: ResponsiveSidebarProps) { currentPage={currentPage} eventId={eventId} eventTitle={eventTitle} - user={{ - name: user?.name || user?.email || user?.phone || 'Anonymous', - role: role, - imageUrl: user?.image, - }} isAdmin={user.systemRole === 'admin'} /> @@ -146,11 +141,6 @@ export function ResponsiveSidebar({ children }: ResponsiveSidebarProps) { eventTitle={eventTitle} isMobile={true} onClose={() => setMobileSidebarOpen(false)} - user={{ - name: user?.name || user?.email || user?.phone || 'Anonymous', - role: role, - imageUrl: user?.image, - }} isAdmin={user.systemRole === 'admin'} /> diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index ca1fa1d5..bc76eada 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -17,7 +17,9 @@ import { Inbox, ScrollText, Scale, + Tags, Home, + type LucideIcon, } from 'lucide-react'; import { Button } from '../ui/button'; import { Separator } from '../ui/separator'; @@ -28,20 +30,15 @@ import { api } from '../../lib/api/functions'; import { useUserRole } from '../../context/UserRoleContext'; import { SheetHeader, SheetTitle } from '../ui/sheet'; import type { Id } from '../../lib/api/types'; -import { saveMenuPath } from '../../lib/menu-history'; import { useInstanceConfig } from '../../hooks/useInstanceConfig'; import { useTranslation } from 'react-i18next'; interface SidebarProps { currentRole: 'organizer' | 'participant' | 'administrator'; currentPage: string; - user: { name: string; role: string; imageUrl?: string } | null; isAdmin?: boolean; isMobile?: boolean; onClose?: () => void; - onLogout?: () => void; - onSwitchRole?: (role: 'organizer' | 'participant' | 'administrator') => void; - isHeaderMenu?: boolean; eventId?: Id<'events'>; eventTitle?: string; } @@ -50,11 +47,8 @@ export function Sidebar({ currentRole, currentPage, isMobile = false, - user, isAdmin = false, onClose, - onSwitchRole, - isHeaderMenu = false, eventId, eventTitle, }: SidebarProps) { @@ -65,7 +59,7 @@ export function Sidebar({ // A self-hosted association approves nothing: its admins create the bazaars const pendingApprovals = useQuery(api.events.countPendingApprovals, isAdmin && !isSingle ? {} : 'skip') ?? 0; - const access = useQuery(api.instance.getMyAccess, user ? {} : 'skip'); + const access = useQuery(api.instance.getMyAccess, {}); const canOrganize = access?.canOrganize ?? !isSingle; const showRoleSwitch = canOrganize || isAdmin; @@ -76,14 +70,12 @@ export function Sidebar({ } }, [access, currentRole, changeRole]); const adminCounts = useQuery(api.moderation.getMenuCounts, isAdmin ? {} : 'skip'); - const notices = useQuery(api.notifications.getUnreadNoticeCounts, user ? {} : 'skip'); + const notices = useQuery(api.notifications.getUnreadNoticeCounts, {}); const participantNotices = (notices?.products ?? 0) + (notices?.sales ?? 0) + (notices?.messages ?? 0); const organizerNotices = notices?.events ?? 0; const handleNavigate = (page: string) => { - const isEventPage = !!eventId && page.startsWith(`/events/view/${eventId}`); - saveMenuPath(currentRole, page, isEventPage ? eventId : undefined); navigate(`${page}`); if (isMobile && onClose) { onClose(); @@ -91,11 +83,7 @@ export function Sidebar({ }; const handleSwitchRole = (role: 'organizer' | 'participant' | 'administrator') => { - if (onSwitchRole) { - onSwitchRole(role); - } else { - changeRole(role); - } + changeRole(role); if (isMobile && onClose) { onClose(); } @@ -104,37 +92,37 @@ export function Sidebar({ // The start page for signed-in users (src/pages/dashboard) const overviewItem = { icon: Home, label: t('menu.overview'), page: '/' }; - const participantMenuItems = [ + const participantMenuItems: MenuItem[] = [ overviewItem, { icon: Package, label: t('menu.myProducts'), page: '/my-products', badge: notices?.products ?? 0, - badgeLabel: 'notifications' as const, + badgeLabel: 'notifications', }, { icon: Receipt, label: t('menu.mySales'), page: '/my-sales', badge: notices?.sales ?? 0, - badgeLabel: 'sales' as const, + badgeLabel: 'sales', }, { icon: Search, label: isSingle ? t('menu.currentBazaar') : t('menu.events'), page: '/browse-events', badge: notices?.messages ?? 0, - badgeLabel: 'organizerMessages' as const, + badgeLabel: 'organizerMessages', }, ]; // Organizers choose their event in the overview; its pages follow below it - const organizerMenuItems = [ - { ...overviewItem, badge: organizerNotices, badgeLabel: 'notifications' as const }, + const organizerMenuItems: MenuItem[] = [ + { ...overviewItem, badge: organizerNotices, badgeLabel: 'notifications' }, ]; - const adminMenuItems = [ + const adminMenuItems: MenuItem[] = [ // The overview shows the admin overview in this role (src/pages/dashboard) overviewItem, { @@ -142,7 +130,7 @@ export function Sidebar({ label: t('menu.reports'), page: '/admin/reports', badge: adminCounts?.openReports ?? 0, - badgeLabel: 'reports' as const, + badgeLabel: 'reports', }, { icon: FileText, @@ -154,7 +142,7 @@ export function Sidebar({ label: t('menu.events'), page: '/admin/events', badge: pendingApprovals, - badgeLabel: 'approvals' as const, + badgeLabel: 'approvals', }, { icon: Users, @@ -166,13 +154,18 @@ export function Sidebar({ label: t('menu.messages'), page: '/admin/messages', badge: adminCounts?.unhandledMessages ?? 0, - badgeLabel: 'messages' as const, + badgeLabel: 'messages', }, { icon: ScrollText, label: t('menu.log'), page: '/admin/log', }, + { + icon: Tags, + label: t('menu.categories'), + page: '/admin/categories', + }, { icon: Scale, label: t('menu.legalPages'), @@ -185,43 +178,37 @@ export function Sidebar({ }, ]; - const eventMenuItems = eventId + const eventMenuItems: MenuItem[] = eventId ? [ { icon: LayoutDashboard, label: t('menu.dashboard'), page: `/events/view/${eventId}`, - activeId: 'event-dashboard', }, { icon: Users, label: t('menu.participants'), page: `/events/view/${eventId}/sellers`, - activeId: 'event-sellers', }, { icon: Box, label: t('menu.products'), page: `/events/view/${eventId}/products`, - activeId: 'event-products', }, { icon: ShoppingCart, label: t('menu.checkout'), page: `/events/view/${eventId}/checkout`, - activeId: 'event-checkout', }, { icon: Banknote, label: t('menu.cash'), page: `/events/view/${eventId}/cash`, - activeId: 'event-cash', }, { icon: Settings, label: t('menu.settings'), page: `/events/view/${eventId}/settings`, - activeId: 'event-settings', }, ] : []; @@ -233,7 +220,7 @@ export function Sidebar({ ? adminMenuItems : participantMenuItems; - const renderMainItem = (item: (typeof mainMenuItems)[number]) => { + const renderMainItem = (item: MenuItem) => { const Icon = item.icon; const isActive = currentPage === item.page; @@ -247,11 +234,8 @@ export function Sidebar({ > {item.label} - {((item as { badge?: number }).badge ?? 0) > 0 && ( - + {(item.badge ?? 0) > 0 && ( + )} ); @@ -265,111 +249,78 @@ export function Sidebar({ )} {/* User Actions Section */} - {user && ( -
- {/* Role Switcher on mobile */} - {!isHeaderMenu && showRoleSwitch && ( -
-
- {t('menu.switchRole')} -
- {canOrganize && ( - - )} +
+ {showRoleSwitch && ( +
+
{t('menu.switchRole')}
+ {canOrganize && ( - {isAdmin && ( - + )} +
- )} -
- )} + + {isAdmin && ( + + )} +
+ )} +
); } +interface MenuItem { + icon: LucideIcon; + label: string; + page: string; + badge?: number; + badgeLabel?: BadgeKind; +} + type BadgeKind = | 'notifications' | 'sales' diff --git a/src/components/navigation/BackToMenuButton.tsx b/src/components/navigation/BackToMenuButton.tsx deleted file mode 100644 index 7e3a9f9f..00000000 --- a/src/components/navigation/BackToMenuButton.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { ArrowLeft } from 'lucide-react'; -import { useNavigate } from 'react-router-dom'; -import { Button } from '../ui/button'; -import { useUserRole } from '../../context/UserRoleContext'; -import { getLastMenuPath } from '../../lib/menu-history'; -import type { Id } from '../../lib/api/types'; -import i18n from '../../i18n'; - -interface BackToMenuButtonProps extends React.ComponentProps { - eventId?: Id<'events'>; - label?: string; - iconOnly?: boolean; - fallbackPath?: string; -} - -export function BackToMenuButton({ - eventId, - label = i18n.t('actions.back'), - iconOnly = false, - fallbackPath, - ...buttonProps -}: BackToMenuButtonProps) { - const navigate = useNavigate(); - const { role } = useUserRole(); - - const handleBack = () => { - const lastPath = getLastMenuPath(role, eventId); - if (lastPath) { - navigate(lastPath); - return; - } - navigate(fallbackPath ?? '/'); - }; - - const ariaLabel = buttonProps['aria-label'] ?? label; - - return ( - - ); -} diff --git a/src/components/onboarding/OnboardingLauncher.tsx b/src/components/onboarding/OnboardingLauncher.tsx deleted file mode 100644 index 8b31bd67..00000000 --- a/src/components/onboarding/OnboardingLauncher.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { HelpCircle } from 'lucide-react'; -import { useAuthState } from '../../lib/api/react'; -import { useOnboarding } from '../../context/OnboardingContext'; -import { Button } from '../ui/button'; -import { useTranslation } from 'react-i18next'; - -export function OnboardingLauncher() { - const { t } = useTranslation('onboarding'); - const { isAuthenticated, isLoading } = useAuthState(); - const { isActive, start, stop } = useOnboarding(); - - if (isLoading || !isAuthenticated) { - return null; - } - - const handleClick = () => { - if (isActive) { - stop(); - } else { - start(); - } - }; - - return ( -
- -
- ); -} diff --git a/src/components/products/ProductCard.tsx b/src/components/products/ProductCard.tsx index fbad0897..fd2885e2 100644 --- a/src/components/products/ProductCard.tsx +++ b/src/components/products/ProductCard.tsx @@ -1,10 +1,10 @@ +import { useTranslation } from 'react-i18next'; +import { discountedPrice } from '../../shared/eventFeatures'; import { Badge } from '../ui/badge'; import { ImageWithFallback } from '../ui/image-with-fallback'; -import { Button } from '../ui/button'; -import { Checkbox } from '../ui/checkbox'; import type { Id } from '../../lib/api/types'; import { formatPriceDE } from '../../lib/utils'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; interface Product { _id: Id<'products'>; @@ -20,26 +20,12 @@ interface Product { interface ProductCardProps { product: Product; categoryLabel?: string; - selected?: boolean; - onSelect?: (id: Id<'products'>) => void; - onEdit?: (id: Id<'products'>) => void; - onViewQR?: (id: Id<'products'>, title: string) => void; - showSelection?: boolean; - showActions?: boolean; } -export function ProductCard({ - product, - categoryLabel, - selected = false, - onSelect, - onEdit, - onViewQR, - showSelection = false, - showActions = true, -}: ProductCardProps) { - const discountedPrice = product.discountPercent - ? product.price * (1 - product.discountPercent / 100) +export function ProductCard({ product, categoryLabel }: ProductCardProps) { + const { t } = useTranslation('events'); + const reducedPrice = product.discountPercent + ? discountedPrice(product.price, product.discountPercent) : null; return ( @@ -61,20 +47,11 @@ export function ProductCard({
- Verkauft + {t('preview.sold')}
)} - {showSelection && onSelect && ( -
- onSelect(product._id)} - className="bg-background" - /> -
- )}
{product.discountPercent && product.discountPercent > 0 && !product.sold && ( -{product.discountPercent}% @@ -101,13 +78,13 @@ export function ProductCard({
)}
- {discountedPrice ? ( + {reducedPrice ? ( <>
{formatPriceDE(product.price)} €
- {formatPriceDE(discountedPrice)} € + {formatPriceDE(reducedPrice)} €
) : ( @@ -115,30 +92,6 @@ export function ProductCard({ )}
- - {showActions && (onEdit || onViewQR) && ( -
- {onEdit && !product.sold && ( - - )} - {onViewQR && ( - - )} -
- )} ); diff --git a/src/components/products/ProductFilters.tsx b/src/components/products/ProductFilters.tsx index 40bb5f27..4f62e18d 100644 --- a/src/components/products/ProductFilters.tsx +++ b/src/components/products/ProductFilters.tsx @@ -1,4 +1,7 @@ -import { SlidersHorizontal, Search, CheckSquare } from 'lucide-react'; +import { SearchInput } from '../ui/search-input'; +import type { CategoryTranslations } from '../../lib/api/types'; +import { categoryName } from '../../i18n/categories'; +import { SlidersHorizontal, CheckSquare } from 'lucide-react'; import { useMemo, useState, useEffect } from 'react'; import { Input } from '../ui/input'; import { Button } from '../ui/button'; @@ -24,7 +27,7 @@ interface ProductFiltersProps { onMaxPriceChange?: (value: string) => void; filterCategory?: string; onFilterCategoryChange?: (value: string) => void; - categories?: { _id: string; label: string }[]; + categories?: { _id: string; label: string; translations?: CategoryTranslations }[]; showBulkSelection?: boolean; onToggleBulkSelection?: () => void; } @@ -54,7 +57,6 @@ export function ProductFilters({ }: ProductFiltersProps) { const { t } = useTranslation('seller'); const [showAdvancedFilters, setShowAdvancedFilters] = useState(false); - const isCompact = false; const hasAdvancedFilterSelection = useMemo( () => (showEventFilter && filterEvent && filterEvent !== 'all') || @@ -82,17 +84,14 @@ export function ProductFilters({ }, [eventSelectionMode, showBulkSelection]); return ( -
-
-
- - onSearchChange(e.target.value)} - /> -
+
+
+ onSearchChange(e.target.value)} + />
diff --git a/src/components/products/UnifiedSaleDialog.tsx b/src/components/products/UnifiedSaleDialog.tsx index 8f7f0d40..5f411f8d 100644 --- a/src/components/products/UnifiedSaleDialog.tsx +++ b/src/components/products/UnifiedSaleDialog.tsx @@ -138,7 +138,6 @@ export function UnifiedSaleDialog({
-

{t('sale.invoiceQuestion')}

diff --git a/src/components/seo/Seo.tsx b/src/components/seo/Seo.tsx index 82966a0a..b40868c4 100644 --- a/src/components/seo/Seo.tsx +++ b/src/components/seo/Seo.tsx @@ -1,14 +1,12 @@ import { useEffect } from 'react'; import { buildSeoDescription, + DEFAULT_SEO_IMAGE, getDefaultDescription, getDefaultSiteName, toAbsoluteUrl, } from '../../lib/seo'; -/** Preview image for links shared on social media and in search results */ -const DEFAULT_IMAGE = '/og-image.png'; - type JsonLd = Record | Record[]; interface SeoProps { @@ -75,7 +73,7 @@ export function Seo({ title, description, canonical, - image = DEFAULT_IMAGE, + image = DEFAULT_SEO_IMAGE, type = 'website', jsonLd, jsonLdId = 'seo-jsonld', diff --git a/src/components/ui/ImageUpload.tsx b/src/components/ui/ImageUpload.tsx index d801e447..aac5d968 100644 --- a/src/components/ui/ImageUpload.tsx +++ b/src/components/ui/ImageUpload.tsx @@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next'; interface ImageUploadProps { onFilesChange: (files: File[]) => void; initialImageUrls?: string[]; + /** Files chosen before, e.g. when a step of a wizard is opened again */ + initialFiles?: File[]; onRemoveExistingImage?: (index: number) => void; maxFiles?: number; accept?: Accept; @@ -19,12 +21,13 @@ const NO_IMAGE_URLS: string[] = []; export function ImageUpload({ onFilesChange, initialImageUrls = NO_IMAGE_URLS, + initialFiles, onRemoveExistingImage, maxFiles = 3, accept = { 'image/*': ['.jpeg', '.jpg', '.png', '.webp'] }, }: ImageUploadProps) { const { t } = useTranslation(); - const [files, setFiles] = useState([]); + const [files, setFiles] = useState(initialFiles ?? []); const [rejected, setRejected] = useState([]); const [processingError, setProcessingError] = useState(null); const [displayedInitialImageUrls, setDisplayedInitialImageUrls] = diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx index eb1bf9bb..4bdb56be 100644 --- a/src/components/ui/alert-dialog.tsx +++ b/src/components/ui/alert-dialog.tsx @@ -3,7 +3,7 @@ import * as React from 'react'; import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; import { buttonVariants, loadingButtonClass } from './button-variants'; import { ButtonSpinner } from './button'; diff --git a/src/components/ui/alert.tsx b/src/components/ui/alert.tsx index 7408851b..05f3be73 100644 --- a/src/components/ui/alert.tsx +++ b/src/components/ui/alert.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import { cva, type VariantProps } from 'class-variance-authority'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; const alertVariants = cva( 'relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current', diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx index 8e629914..f66108cb 100644 --- a/src/components/ui/badge.tsx +++ b/src/components/ui/badge.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import { Slot } from '@radix-ui/react-slot'; import { type VariantProps } from 'class-variance-authority'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; import { badgeVariants } from './badge-variants'; function Badge({ diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx index 88b1f8e5..357ff684 100644 --- a/src/components/ui/button.tsx +++ b/src/components/ui/button.tsx @@ -3,7 +3,7 @@ import { Slot } from '@radix-ui/react-slot'; import { type VariantProps } from 'class-variance-authority'; import { Loader2 } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; import { buttonVariants, loadingButtonClass } from './button-variants'; /** Spinner of a busy button, see `loading`. */ diff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx index 58c225cc..a303b2e6 100644 --- a/src/components/ui/checkbox.tsx +++ b/src/components/ui/checkbox.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; import { CheckIcon } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; function Checkbox({ className, ...props }: React.ComponentProps) { return ( diff --git a/src/components/ui/confirm-dialog.tsx b/src/components/ui/confirm-dialog.tsx new file mode 100644 index 00000000..bc7cf45e --- /dev/null +++ b/src/components/ui/confirm-dialog.tsx @@ -0,0 +1,74 @@ +import type { MouseEventHandler, ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from './alert-dialog'; +import { buttonVariants } from './button-variants'; + +/** + * Asks before doing something: with `trigger` it opens by itself, otherwise through + * `open`. `children` go between the text and the buttons. To keep it open while saving, + * call `event.preventDefault()` in `onConfirm`. + */ +export function ConfirmDialog({ + trigger, + open, + onOpenChange, + title, + description, + children, + confirmLabel, + onConfirm, + destructive = false, + loading = false, + disabled = false, +}: { + trigger?: ReactNode; + open?: boolean; + onOpenChange?: (open: boolean) => void; + title: ReactNode; + description?: ReactNode; + children?: ReactNode; + confirmLabel: ReactNode; + onConfirm: MouseEventHandler; + destructive?: boolean; + loading?: boolean; + disabled?: boolean; +}) { + const { t } = useTranslation('common'); + return ( + + {trigger && {trigger}} + + + {title} + {description && ( + +
{description}
+
+ )} +
+ {children} + + {t('actions.cancel')} + + {confirmLabel} + + +
+
+ ); +} diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index d580d91c..86ec4d79 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import * as DialogPrimitive from '@radix-ui/react-dialog'; import { X } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; import i18n from '../../i18n'; const Dialog = DialogPrimitive.Root; diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx index b7af76c9..a5a3341c 100644 --- a/src/components/ui/dropdown-menu.tsx +++ b/src/components/ui/dropdown-menu.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'; import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; function DropdownMenu({ ...props }: React.ComponentProps) { return ; diff --git a/src/components/ui/empty-state.tsx b/src/components/ui/empty-state.tsx new file mode 100644 index 00000000..0ee37add --- /dev/null +++ b/src/components/ui/empty-state.tsx @@ -0,0 +1,28 @@ +import type { LucideIcon } from 'lucide-react'; +import type { ReactNode } from 'react'; +import { cn } from '../../lib/utils'; + +/** Shown instead of a list or page without content: what is missing and what to do. */ +export function EmptyState({ + icon: Icon, + title, + text, + children, + className, +}: { + icon?: LucideIcon; + title: ReactNode; + text?: ReactNode; + /** The actions */ + children?: ReactNode; + className?: string; +}) { + return ( +
+ {Icon && } +

{title}

+ {text &&

{text}

} + {children &&
{children}
} +
+ ); +} diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx index a1bc1af4..e1f67cb7 100644 --- a/src/components/ui/input.tsx +++ b/src/components/ui/input.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; function Input({ className, type, ...props }: React.ComponentProps<'input'>) { return ( diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx index 2019b025..b30ace38 100644 --- a/src/components/ui/label.tsx +++ b/src/components/ui/label.tsx @@ -3,7 +3,7 @@ import * as React from 'react'; import * as LabelPrimitive from '@radix-ui/react-label'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; function Label({ className, ...props }: React.ComponentProps) { return ( diff --git a/src/components/ui/page-header.tsx b/src/components/ui/page-header.tsx new file mode 100644 index 00000000..8aae8a67 --- /dev/null +++ b/src/components/ui/page-header.tsx @@ -0,0 +1,30 @@ +import type { ReactNode } from 'react'; +import { cn } from '../../lib/utils'; + +/** Title of a page, with its actions on the right. */ +export function PageHeader({ + title, + description, + actions, + className, +}: { + title: ReactNode; + description?: ReactNode; + actions?: ReactNode; + className?: string; +}) { + return ( +
+
+

{title}

+ {description &&
{description}
} +
+ {actions} +
+ ); +} diff --git a/src/components/ui/radio-group.tsx b/src/components/ui/radio-group.tsx index 23f5570d..f0256b54 100644 --- a/src/components/ui/radio-group.tsx +++ b/src/components/ui/radio-group.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import * as RadioGroupPrimitive from '@radix-ui/react-radio-group'; import { CircleIcon } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; function RadioGroup({ className, diff --git a/src/components/ui/scroll-row.tsx b/src/components/ui/scroll-row.tsx new file mode 100644 index 00000000..717c9df8 --- /dev/null +++ b/src/components/ui/scroll-row.tsx @@ -0,0 +1,91 @@ +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { useCallback, useEffect, useState, type ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '../../lib/utils'; +import { Button } from './button'; + +/** + * Swipeable row of cards with arrows on larger screens, shown only where there is + * more to see. `contentKey` tells the arrows that the cards changed. To start over + * with other cards, give the row a React `key`: browsers keep a snapping row on the + * card it showed, even if new cards come before it. + */ +export function ScrollRow({ + children, + contentKey, + className, +}: { + children: ReactNode; + contentKey?: unknown; + className?: string; +}) { + const { t } = useTranslation('common'); + const [scroller, setScroller] = useState(null); + const [canScroll, setCanScroll] = useState({ back: false, forward: false }); + + const update = useCallback(() => { + if (!scroller) return; + const tolerance = 2; + setCanScroll({ + back: scroller.scrollLeft > tolerance, + forward: scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - tolerance, + }); + }, [scroller]); + + useEffect(() => { + if (!scroller) return; + scroller.addEventListener('scroll', update, { passive: true }); + const observer = new ResizeObserver(update); + observer.observe(scroller); + return () => { + scroller.removeEventListener('scroll', update); + observer.disconnect(); + }; + }, [scroller, update]); + + useEffect(update, [update, contentKey]); + + const scroll = (direction: 1 | -1) => + scroller?.scrollBy({ left: direction * scroller.clientWidth * 0.8, behavior: 'smooth' }); + + const arrow = + 'absolute top-1/2 z-20 hidden -translate-y-1/2 rounded-full bg-background shadow-lg'; + + return ( +
+ {canScroll.back && ( + + )} + {canScroll.forward && ( + + )} +
+ {children} +
+
+ ); +} diff --git a/src/components/ui/search-input.tsx b/src/components/ui/search-input.tsx new file mode 100644 index 00000000..98f59630 --- /dev/null +++ b/src/components/ui/search-input.tsx @@ -0,0 +1,14 @@ +import { Search } from 'lucide-react'; +import type { ComponentProps } from 'react'; +import { cn } from '../../lib/utils'; +import { Input } from './input'; + +/** Text field with a search icon; `className` sizes the whole field. */ +export function SearchInput({ className, ...props }: ComponentProps) { + return ( +
+ + +
+ ); +} diff --git a/src/components/ui/select.test.tsx b/src/components/ui/select.test.tsx new file mode 100644 index 00000000..eb20bafe --- /dev/null +++ b/src/components/ui/select.test.tsx @@ -0,0 +1,36 @@ +import { fireEvent, render } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './select'; + +function renderInForm(onValueChange: (value: string) => void) { + const { container } = render( +
+ +
+ ); + return container.querySelector('select') as HTMLSelectElement; +} + +describe('Select', () => { + it('keeps its value when the hidden native select reports nothing', () => { + const onValueChange = vi.fn(); + const native = renderInForm(onValueChange); + fireEvent.change(native, { target: { value: '' } }); + expect(onValueChange).not.toHaveBeenCalled(); + }); + + it('passes on real changes of the native select, e.g. autofill', () => { + const onValueChange = vi.fn(); + const native = renderInForm(onValueChange); + fireEvent.change(native, { target: { value: 'b' } }); + expect(onValueChange).toHaveBeenCalledWith('b'); + }); +}); diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsx index 949d384a..c4544d85 100644 --- a/src/components/ui/select.tsx +++ b/src/components/ui/select.tsx @@ -4,10 +4,20 @@ import * as React from 'react'; import * as SelectPrimitive from '@radix-ui/react-select'; import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; -function Select({ ...props }: React.ComponentProps) { - return ; +function Select({ onValueChange, ...props }: React.ComponentProps) { + return ( +
diff --git a/src/pages/account/components/DigitalIdCard.tsx b/src/pages/account/components/DigitalIdCard.tsx index 737de430..3ac1f108 100644 --- a/src/pages/account/components/DigitalIdCard.tsx +++ b/src/pages/account/components/DigitalIdCard.tsx @@ -11,7 +11,7 @@ import { } from '../../../lib/checkInCode'; import { isNetworkError } from '../../../lib/offlineMode'; import { Button } from '../../../components/ui/button'; -import { QrCode, Eye, EyeOff } from 'lucide-react'; +import { QrCode, EyeOff } from 'lucide-react'; import { QRCodeSVG } from 'qrcode.react'; import { toast } from 'sonner'; import { getUserFacingErrorMessage } from '../../../lib/errors'; @@ -135,22 +135,16 @@ export function DigitalIdCard() {

{t('digitalId.title')}

- + {showDigitalId && ( + + )} {showDigitalId ? ( diff --git a/src/pages/account/components/NotificationsCard.tsx b/src/pages/account/components/NotificationsCard.tsx index 8e10617d..f695d90e 100644 --- a/src/pages/account/components/NotificationsCard.tsx +++ b/src/pages/account/components/NotificationsCard.tsx @@ -10,6 +10,9 @@ import { Checkbox } from '../../../components/ui/checkbox'; import { Label } from '../../../components/ui/label'; import { getUserFacingErrorMessage } from '../../../lib/errors'; +/** The other categories explain themselves by their title */ +const NOTIFICATION_HINTS: readonly string[] = ['buyer', 'reminders', 'organizer']; + /** Which emails the user gets; the red markers in the menu stay either way. */ export function NotificationsCard() { const { t } = useTranslation('account'); @@ -45,7 +48,9 @@ export function NotificationsCard() {
    {NOTIFICATION_CATEGORIES.map((category) => { const title = t(`notifications.categories.${category}.title`); - const description = t(`notifications.categories.${category}.description`); + const description = NOTIFICATION_HINTS.includes(category) + ? t(`notifications.categories.${category}.description` as never) + : null; const id = `notify-${category}`; return (
  • @@ -63,7 +68,7 @@ export function NotificationsCard() { -

    {description}

    + {description &&

    {description}

    }
  • ); diff --git a/src/pages/account/components/SecurityCard.test.tsx b/src/pages/account/components/SecurityCard.test.tsx new file mode 100644 index 00000000..8c79a9f4 --- /dev/null +++ b/src/pages/account/components/SecurityCard.test.tsx @@ -0,0 +1,29 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { SecurityCard } from './SecurityCard'; + +const changePassword = vi.hoisted(() => vi.fn(async () => undefined)); +vi.mock('../../../lib/api/react', () => ({ + useAuthActions: () => ({ changePassword }), +})); + +describe('SecurityCard', () => { + it('changes the password with one field and 10 characters, shown on request', async () => { + render(); + expect(screen.queryByLabelText('Passwort bestätigen')).toBeNull(); + + fireEvent.change(screen.getByLabelText('Aktuelles Passwort'), { target: { value: '123456' } }); + const newPassword = screen.getByLabelText('Neues Passwort setzen'); + fireEvent.change(newPassword, { target: { value: 'kurz' } }); + fireEvent.click(screen.getByRole('button', { name: 'Passwort aktualisieren' })); + expect(await screen.findByText('Mindestens 10 Zeichen')).toHaveClass('text-destructive'); + expect(changePassword).not.toHaveBeenCalled(); + + const [, showNew] = screen.getAllByRole('button', { name: 'Passwort anzeigen' }); + fireEvent.click(showNew); + expect(newPassword).toHaveAttribute('type', 'text'); + fireEvent.change(newPassword, { target: { value: 'kinderbasar' } }); + fireEvent.click(screen.getByRole('button', { name: 'Passwort aktualisieren' })); + await waitFor(() => expect(changePassword).toHaveBeenCalledWith('123456', 'kinderbasar')); + }); +}); diff --git a/src/pages/account/components/SecurityCard.tsx b/src/pages/account/components/SecurityCard.tsx index 6d298988..64508e63 100644 --- a/src/pages/account/components/SecurityCard.tsx +++ b/src/pages/account/components/SecurityCard.tsx @@ -4,25 +4,20 @@ import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { useAuthActions } from '../../../lib/api/react'; import { Button } from '../../../components/ui/button'; -import { Input } from '../../../components/ui/input'; import { Label } from '../../../components/ui/label'; -import { Shield, Check, X } from 'lucide-react'; +import { Shield } from 'lucide-react'; +import { PasswordInput } from '../../../components/auth/PasswordInput'; +import { MIN_PASSWORD_LENGTH } from '../../../shared/constants'; import { toast } from 'sonner'; import { apiErrorCode } from '../../../lib/errors'; import { useTranslation } from 'react-i18next'; import type { TFunction } from 'i18next'; function buildSecuritySchema(t: TFunction<'account'>) { - return z - .object({ - oldPassword: z.string().min(1, t('security.oldRequired')), - newPassword: z.string().min(10, t('security.rules.length')), - confirmPassword: z.string().min(1, t('security.confirmRequired')), - }) - .refine((data) => data.newPassword === data.confirmPassword, { - message: t('security.mismatch'), - path: ['confirmPassword'], - }); + return z.object({ + oldPassword: z.string().min(1, t('security.oldRequired')), + newPassword: z.string().min(MIN_PASSWORD_LENGTH, t('security.rules.length')), + }); } type SecurityFormData = z.infer>; @@ -42,7 +37,6 @@ export function SecurityCard({ providers }: SecurityCardProps) { register, handleSubmit, reset, - watch, setError, formState: { errors, isSubmitting, isDirty }, } = useForm({ @@ -51,13 +45,9 @@ export function SecurityCard({ providers }: SecurityCardProps) { defaultValues: { oldPassword: '', newPassword: '', - confirmPassword: '', }, }); - const newPasswordValue = watch('newPassword') || ''; - const confirmPasswordValue = watch('confirmPassword') || ''; - const onSubmit = async (data: SecurityFormData) => { try { await changePassword(data.oldPassword, data.newPassword); @@ -82,25 +72,6 @@ export function SecurityCard({ providers }: SecurityCardProps) { } }; - const passwordRequirements = { - length: newPasswordValue.length >= 10, - uppercase: /[A-Z]/.test(newPasswordValue), - lowercase: /[a-z]/.test(newPasswordValue), - number: /[0-9]/.test(newPasswordValue), - special: /[!@#$%^&*(),.?":{}|<>]/.test(newPasswordValue), - }; - - const getPasswordStrength = () => { - const metRequirements = Object.values(passwordRequirements).filter(Boolean).length; - if (!newPasswordValue) return { text: '', color: '' }; - if (metRequirements <= 2) return { text: t('security.strength.weak'), color: 'bg-red-500' }; - if (metRequirements <= 4) - return { text: t('security.strength.medium'), color: 'bg-yellow-500' }; - return { text: t('security.strength.strong'), color: 'bg-green-500' }; - }; - - const strength = getPasswordStrength(); - return (
    @@ -136,9 +107,9 @@ export function SecurityCard({ providers }: SecurityCardProps) {
    - @@ -151,83 +122,19 @@ export function SecurityCard({ providers }: SecurityCardProps) {
    - - {errors.newPassword && ( -

    - {errors.newPassword.message} -

    - )} - - {newPasswordValue && ( -
    -
    - {[1, 2, 3, 4, 5].map((i) => ( -
    - ))} -
    - {strength.text && ( -

    {strength.text}

    - )} -
    - )} - -
    - {(['length', 'uppercase', 'lowercase', 'number', 'special'] as const).map( - (rule) => ( - - ) - )} -
    -
    - -
    - - - {errors.confirmPassword && ( -

    - {errors.confirmPassword.message} -

    - )} - {!errors.confirmPassword && newPasswordValue && confirmPasswordValue && ( -
    - {newPasswordValue === confirmPasswordValue ? ( - <> - - - {t('passwordRules.match', { ns: 'auth' })} - - - ) : ( - <> - - - {t('passwordRules.noMatch', { ns: 'auth' })} - - - )} -
    - )} +

    + {t('security.rules.length')} +

    {isDirty && ( @@ -249,12 +156,3 @@ export function SecurityCard({ providers }: SecurityCardProps) {
    ); } - -function RequirementItem({ met, text }: { met: boolean; text: string }) { - return ( -
    - {met ? : } - {text} -
    - ); -} diff --git a/src/pages/administrator/AdminCategoriesPage.test.tsx b/src/pages/administrator/AdminCategoriesPage.test.tsx new file mode 100644 index 00000000..e51016bf --- /dev/null +++ b/src/pages/administrator/AdminCategoriesPage.test.tsx @@ -0,0 +1,112 @@ +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { getFunctionName } from '../../lib/api/functions'; +import { useMutation, useQuery } from '../../lib/api/react'; +import { AdminCategoriesPage } from './AdminCategoriesPage'; + +vi.mock('../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn() })); + +const base = { _creationTime: 1, updatedAt: 1, childCount: 0, productCount: 0, eventCount: 0 }; +const bikes = { + ...base, + _id: 'bikes', + label: 'Fahrräder', + translations: { en: 'Bikes' }, + productCount: 3, + eventCount: 1, +}; +const misc = { ...base, _id: 'misc', label: 'Sonstiges', translations: {} }; +const kids = { + ...base, + _id: 'kids', + label: 'Kinderrad', + translations: {}, + parentCategory: 'bikes', +}; + +const mutations: Record> = {}; + +beforeEach(() => { + for (const name of Object.keys(mutations)) delete mutations[name]; + vi.mocked(useQuery).mockReturnValue([bikes, kids, misc] as never); + vi.mocked(useMutation).mockImplementation(((fn: unknown) => { + const name = getFunctionName(fn); + mutations[name] ??= vi.fn(async () => null); + return mutations[name]; + }) as never); +}); + +const row = (name: string) => screen.getByText(name).closest('tr') as HTMLElement; + +describe('AdminCategoriesPage', () => { + it('shows names, inherited extra fields and usage', () => { + render(); + expect(within(row('Fahrräder')).getByText('Bikes')).toBeInTheDocument(); + expect(within(row('Fahrräder')).getByText('Rahmennummer')).toBeInTheDocument(); + expect(within(row('Fahrräder')).getByText('3 Artikel, 1 Basar')).toBeInTheDocument(); + expect(within(row('Kinderrad')).getByText('Unterkategorie von Fahrräder')).toBeInTheDocument(); + expect(within(row('Kinderrad')).getByText('Rahmennummer')).toBeInTheDocument(); + expect(within(row('Sonstiges')).getByText('Keine')).toBeInTheDocument(); + }); + + it('sorts by name with sub-categories below their parent', () => { + render(); + const names = screen.getAllByRole('row').map((row) => row.querySelector('td .font-medium')); + expect(names.flatMap((name) => name?.textContent ?? [])).toEqual([ + 'Fahrräder', + 'Kinderrad', + 'Sonstiges', + ]); + }); + + it('only offers to delete what nothing uses', () => { + render(); + expect(screen.getByRole('button', { name: 'Löschen: Fahrräder' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Löschen: Sonstiges' })).toBeEnabled(); + }); + + it('keeps the last category', () => { + vi.mocked(useQuery).mockReturnValue([misc] as never); + render(); + expect(screen.getByRole('button', { name: 'Löschen: Sonstiges' })).toBeDisabled(); + }); + + it('saves the changed names and warns when the extra fields change', async () => { + render(); + fireEvent.click(within(row('Fahrräder')).getByRole('button', { name: 'Bearbeiten' })); + const name = screen.getByLabelText('Name'); + expect(screen.queryByText(/ändern sich für alle Artikel/)).not.toBeInTheDocument(); + + fireEvent.change(name, { target: { value: 'Allerlei' } }); + expect(screen.getByText(/ändern sich für alle Artikel/)).toBeInTheDocument(); + expect(screen.getByText(/keine Zusatzfelder/)).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('Englischer Name'), { target: { value: ' Misc ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.updateCategory']).toHaveBeenCalledWith({ + categoryId: 'bikes', + label: 'Allerlei', + translations: { en: 'Misc' }, + }) + ); + await waitFor(() => expect(screen.queryByLabelText('Name')).not.toBeInTheDocument()); + }); + + it('creates a category, but not one with a name that exists', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Kategorie hinzufügen' })); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'sonstiges' } }); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + expect(mutations['categories.createCategory']).not.toHaveBeenCalled(); + + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Wintersport' } }); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.createCategory']).toHaveBeenCalledWith({ + label: 'Wintersport', + translations: { en: undefined }, + }) + ); + }); +}); diff --git a/src/pages/administrator/AdminCategoriesPage.tsx b/src/pages/administrator/AdminCategoriesPage.tsx new file mode 100644 index 00000000..a0e6e2e9 --- /dev/null +++ b/src/pages/administrator/AdminCategoriesPage.tsx @@ -0,0 +1,303 @@ +import { useState, type FormEvent } from 'react'; +import { Pencil, Plus, Tags, Trash2 } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { Badge } from '../../components/ui/badge'; +import { Button } from '../../components/ui/button'; +import { ConfirmDialog } from '../../components/ui/confirm-dialog'; +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from '../../components/ui/dialog'; +import { EmptyState } from '../../components/ui/empty-state'; +import { Input } from '../../components/ui/input'; +import { Label } from '../../components/ui/label'; +import { TableRowsSkeleton } from '../../components/ui/loading'; +import { PageHeader } from '../../components/ui/page-header'; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '../../components/ui/table'; +import { categoryFieldText } from '../../i18n/categoryFields'; +import { api } from '../../lib/api/functions'; +import { useMutation, useQuery } from '../../lib/api/react'; +import type { FunctionReturnType } from '../../lib/api/types'; +import { getUserFacingErrorMessage } from '../../lib/errors'; +import { + getCategoryFields, + getFieldsForLabel, + type CategoryField, +} from '../../shared/categoryFields'; + +type AdminCategory = FunctionReturnType[number]; +/** What the dialog works on: a category, or null for a new one. */ +type Editing = { category: AdminCategory | null }; + +const fieldNames = (fields: CategoryField[]) => + fields.map((field) => categoryFieldText(field, 'label') ?? field.label); + +/** By name, parents first, each followed by its sub-categories. */ +function inTreeOrder(unsorted: AdminCategory[]) { + const categories = [...unsorted].sort((a, b) => a.label.localeCompare(b.label)); + const ids = new Set(categories.map((category) => category._id)); + const isRoot = (category: AdminCategory) => + !category.parentCategory || !ids.has(category.parentCategory); + const withChildren = (parent: AdminCategory, seen: Set): AdminCategory[] => { + seen.add(parent._id); + return [ + parent, + ...categories + .filter((category) => category.parentCategory === parent._id && !seen.has(category._id)) + .flatMap((child) => withChildren(child, seen)), + ]; + }; + const seen = new Set(); + return categories.filter(isRoot).flatMap((root) => withChildren(root, seen)); +} + +function CategoryDialog({ + editing, + categories, + onClose, +}: { + editing: Editing; + categories: AdminCategory[]; + onClose: () => void; +}) { + const { t } = useTranslation('admin'); + const { category } = editing; + const create = useMutation(api.categories.createCategory); + const update = useMutation(api.categories.updateCategory); + const [label, setLabel] = useState(category?.label ?? ''); + const [nameEn, setNameEn] = useState(category?.translations.en ?? ''); + const [saving, setSaving] = useState(false); + + const name = label.trim(); + const fieldsFor = (candidate: string) => + getFieldsForLabel(candidate) ?? + (category?.parentCategory ? getCategoryFields(category.parentCategory, categories) : []); + const fields = fieldNames(fieldsFor(name)); + const fieldsChange = + !!category && + (category.productCount > 0 || category.eventCount > 0) && + fields.join() !== fieldNames(fieldsFor(category.label)).join(); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const isTaken = categories.some( + (other) => other._id !== category?._id && other.label.toLowerCase() === name.toLowerCase() + ); + if (isTaken) { + toast.error(t('categories.duplicate')); + return; + } + setSaving(true); + try { + const translations = { en: nameEn.trim() || undefined }; + if (category) await update({ categoryId: category._id, label: name, translations }); + else await create({ label: name, translations }); + toast.success(t('categories.saved')); + onClose(); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } finally { + setSaving(false); + } + }; + + return ( + !open && onClose()}> + + + {t(category ? 'categories.edit' : 'categories.new')} + +
    +
    + + setLabel(event.target.value)} + maxLength={60} + required + autoFocus + /> +

    {t('categories.fieldsHint')}

    + {name && ( +

    + {fields.length + ? t('categories.fieldsPreview', { fields: fields.join(', ') }) + : t('categories.noFieldsPreview')} +

    + )} + {fieldsChange && ( +

    {t('categories.fieldsChange')}

    + )} +
    +
    + + setNameEn(event.target.value)} + maxLength={60} + /> +

    {t('categories.nameEnHint')}

    +
    + + + +
    +
    +
    + ); +} + +/** The product categories: names in each language, their extra fields and what uses them. */ +export function AdminCategoriesPage() { + const { t } = useTranslation('admin'); + const categories = useQuery(api.categories.listForAdmin, {}); + const remove = useMutation(api.categories.deleteCategory); + const [editing, setEditing] = useState(null); + + const handleDelete = async (category: AdminCategory) => { + try { + await remove({ categoryId: category._id }); + toast.success(t('categories.deleted')); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } + }; + + const whyNotDeletable = (category: AdminCategory) => { + if (category.productCount || category.eventCount || category.childCount) { + return t('categories.inUse'); + } + return categories?.length === 1 ? t('categories.lastOne') : undefined; + }; + + return ( +
    + setEditing({ category: null })}> + + {t('categories.add')} + + } + /> + + {categories?.length === 0 ? ( + + ) : ( +
    + + + + {t('categories.name')} + {t('categories.nameEn')} + {t('categories.fields')} + {t('categories.usage')} + {t('categories.action')} + + + + {!categories ? ( + + ) : ( + inTreeOrder(categories).map((category) => { + const parent = categories.find((c) => c._id === category.parentCategory); + const fields = fieldNames(getCategoryFields(category._id, categories)); + const blocked = whyNotDeletable(category); + return ( + + +
    {category.label}
    + {parent && ( +
    + {t('categories.subOf', { parent: parent.label })} +
    + )} +
    + {category.translations.en ?? '—'} + + {fields.length ? ( +
    + {fields.map((field) => ( + + {field} + + ))} +
    + ) : ( + {t('categories.noFields')} + )} +
    + + {t('categories.usageProducts', { count: category.productCount })},{' '} + {t('categories.usageEvents', { count: category.eventCount })} + + +
    + + {/* A disabled button shows no tooltip itself */} + + + + + } + title={t('categories.deleteTitle', { name: category.label })} + description={t('categories.deleteText')} + confirmLabel={t('categories.delete')} + destructive + onConfirm={() => handleDelete(category)} + /> + +
    +
    +
    + ); + }) + )} +
    +
    +
    + )} + + {editing && categories && ( + setEditing(null)} + /> + )} +
    + ); +} diff --git a/src/pages/administrator/AdminContentPage.tsx b/src/pages/administrator/AdminContentPage.tsx index 632863da..2dbbec11 100644 --- a/src/pages/administrator/AdminContentPage.tsx +++ b/src/pages/administrator/AdminContentPage.tsx @@ -1,34 +1,28 @@ +import { SearchInput } from '../../components/ui/search-input'; +import { PageHeader } from '../../components/ui/page-header'; +import { EmptyState } from '../../components/ui/empty-state'; import { useState } from 'react'; import { Link, useSearchParams } from 'react-router-dom'; import { useMutation, useQuery } from '../../lib/api/react'; import { toast } from 'sonner'; -import { Package, Search, X } from 'lucide-react'; +import { Package, X } from 'lucide-react'; import { api } from '../../lib/api/functions'; import type { Id } from '../../lib/api/types'; import { Badge } from '../../components/ui/badge'; import { Button } from '../../components/ui/button'; -import { Input } from '../../components/ui/input'; import { ModerationActionDialog, type ModerationRequest, } from '../../components/moderation/ModerationActionDialog'; import { getUserFacingErrorMessage } from '../../lib/errors'; import { formatDateTime } from '../../lib/moderation'; -import { AdminGuard, AdminPageHeader, EmptyState, FilterTabs } from './components/AdminShared'; +import { FilterTabs } from './components/AdminShared'; import { useTranslation } from 'react-i18next'; import { ListSkeleton, Loading } from '../../components/ui/loading'; type Tab = 'products' | 'questions'; export function AdminContentPage() { - return ( - - - - ); -} - -function Content() { const { t } = useTranslation('admin'); const [params, setParams] = useSearchParams(); const tab: Tab = params.get('tab') === 'questions' ? 'questions' : 'products'; @@ -48,7 +42,7 @@ function Content() { return (
    - +
    -
    - - setSearch(e.target.value)} - placeholder={tab === 'products' ? t('content.searchProducts') : t('content.searchText')} - className="pl-9" - aria-label={t('content.searchLabel')} - /> -
    + setSearch(e.target.value)} + placeholder={tab === 'products' ? t('content.searchProducts') : t('content.searchText')} + aria-label={t('content.searchLabel')} + />
    @@ -128,7 +119,7 @@ function ProductList({ const restoreProduct = useMutation(api.moderation.restoreProduct); if (products === undefined) return ; - if (products.length === 0) return {t('content.noProducts')}; + if (products.length === 0) return ; return (
      @@ -219,7 +210,7 @@ function QuestionList({ const questions = useQuery(api.moderation.listQuestions, { search, askerId }); if (questions === undefined) return ; - if (questions.length === 0) return {t('content.noQuestions')}; + if (questions.length === 0) return ; return (
        diff --git a/src/pages/administrator/AdminEventsPage.tsx b/src/pages/administrator/AdminEventsPage.tsx index 6ba04c97..8047e98c 100644 --- a/src/pages/administrator/AdminEventsPage.tsx +++ b/src/pages/administrator/AdminEventsPage.tsx @@ -1,8 +1,10 @@ +import { ReasonDialog } from '../../components/moderation/ReasonDialog'; +import { SearchInput } from '../../components/ui/search-input'; +import { PageHeader } from '../../components/ui/page-header'; import { useMutation, useQuery } from '../../lib/api/react'; import { api } from '../../lib/api/functions'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { useMemo, useState } from 'react'; -import { Search } from 'lucide-react'; import { Table, TableBody, @@ -15,25 +17,16 @@ import { Badge } from '../../components/ui/badge'; import { Button } from '../../components/ui/button'; import { formatDateRangeDE } from '../../lib/utils'; import type { Doc, Id } from '../../lib/api/types'; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from '../../components/ui/dialog'; -import { Textarea } from '../../components/ui/text-area'; import { toast } from 'sonner'; -import { Input } from '../../components/ui/input'; import { ModerationActionDialog, type ModerationRequest, } from '../../components/moderation/ModerationActionDialog'; import { getUserFacingErrorMessage } from '../../lib/errors'; -import { AdminGuard, AdminPageHeader, FilterTabs } from './components/AdminShared'; +import { FilterTabs } from './components/AdminShared'; import { useTranslation } from 'react-i18next'; import { TableRowsSkeleton } from '../../components/ui/loading'; +import { formatEventPlace } from '../../shared/eventJsonLd'; type AdminEvent = Doc<'events'> & { isApproved: boolean; @@ -45,14 +38,6 @@ type AdminEvent = Doc<'events'> & { type EventFilter = 'all' | 'pending' | 'running' | 'upcoming' | 'hidden'; export function AdminEventsPage() { - return ( - - - - ); -} - -function Events() { const { t } = useTranslation('admin'); const navigate = useNavigate(); const [params, setParams] = useSearchParams(); @@ -64,8 +49,6 @@ function Events() { const rejectEvent = useMutation(api.events.rejectEventForAdmin); const restoreEvent = useMutation(api.moderation.restoreEvent); const [processingEventId, setProcessingEventId] = useState(null); - const [rejectDialogOpen, setRejectDialogOpen] = useState(false); - const [rejectReason, setRejectReason] = useState(''); const [rejectEventId, setRejectEventId] = useState | null>(null); const eventsLoading = events === undefined; @@ -85,7 +68,7 @@ function Events() { (event) => !term || event.title.toLowerCase().includes(term) || - event.location.toLowerCase().includes(term) || + formatEventPlace(event).toLowerCase().includes(term) || (event.organizerName ?? '').toLowerCase().includes(term) || (event.organizerEmail ?? '').toLowerCase().includes(term) ) @@ -117,26 +100,8 @@ function Events() { try { await approveEvent({ eventId: eventId as Id<'events'> }); toast.success(t('events.approved')); - } finally { - setProcessingEventId(null); - } - }; - - const openRejectDialog = (eventId: Id<'events'>) => { - setRejectEventId(eventId); - setRejectReason(''); - setRejectDialogOpen(true); - }; - - const handleReject = async () => { - if (!rejectEventId) return; - const trimmed = rejectReason.trim(); - if (!trimmed) return; - setProcessingEventId(rejectEventId); - try { - await rejectEvent({ eventId: rejectEventId, reason: trimmed }); - toast.success(t('events.rejected')); - setRejectDialogOpen(false); + } catch (error) { + toast.error(t('events.error'), { description: getUserFacingErrorMessage(error) }); } finally { setProcessingEventId(null); } @@ -160,7 +125,7 @@ function Events() { return (
        - +
        -
        - - setSearch(e.target.value)} - placeholder={t('events.search')} - className="pl-9" - aria-label={t('events.searchLabel')} - /> -
        + setSearch(e.target.value)} + placeholder={t('events.search')} + aria-label={t('events.searchLabel')} + />
        @@ -274,7 +236,7 @@ function Events() { variant="destructive" size="sm" disabled={processingEventId === event._id} - onClick={() => openRejectDialog(event._id)} + onClick={() => setRejectEventId(event._id)} > {t('events.reject')} @@ -295,34 +257,17 @@ function Events() {
        - - - - {t('events.rejectTitle')} - {t('events.rejectText')} - -
        -