From 44c203e9a38bccf1b0e35fa55e8f6b81c86ec727 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 12:03:38 +0100 Subject: [PATCH 1/3] fix(categories): create the default categories on a new instance A new self-hosted instance had no categories and no way to add them in the app, so no bazaar could be created. The server now fills an empty table on start; an instance with categories keeps exactly those. The Convex import and the demo seed replace the defaults while no users exist, so they do not end up next to the imported or English categories. Co-Authored-By: Claude Opus 5.5 --- backend/src/demo/mod.rs | 5 +++++ backend/src/import.rs | 7 +++++++ backend/src/main.rs | 10 ++++++++++ backend/src/modules/categories.rs | 13 +++++++++++++ backend/tests/api/categories.rs | 31 ++++++++++++++++++++++++++++++ backend/tests/api/demo.rs | 12 ++++++++++++ backend/tests/api/import.rs | 32 +++++++++++++++++++++++++++++++ 7 files changed, 110 insertions(+) diff --git a/backend/src/demo/mod.rs b/backend/src/demo/mod.rs index 6139c472..d41e1271 100644 --- a/backend/src/demo/mod.rs +++ b/backend/src/demo/mod.rs @@ -348,6 +348,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 7faf9af5..b2e02f36 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -23,6 +23,7 @@ pub fn register(registry: &mut Registry) { 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); } #[skip_serializing_none] @@ -157,3 +158,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/tests/api/categories.rs b/backend/tests/api/categories.rs index a45bb3fd..bd91b1cf 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -171,6 +171,37 @@ 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 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/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()); From d01b8456453eba88c872c39a2a4ab125a91c980a Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 12:03:38 +0100 Subject: [PATCH 2/3] feat(admin): page to view and edit categories, with English names Admins see every category with its extra fields and usage, can add and rename categories, and delete those nothing uses. The name still decides the extra fields, so the dialog shows them while typing and warns when they change. Categories get translated names in `translations`, shown wherever a name is displayed; `label` stays the name for the field rules and the fallback. The default categories get their English names, also on existing instances. Co-Authored-By: Claude Opus 5.5 --- .../migrations/0019_category_translations.sql | 20 ++ backend/src/demo/mod.rs | 20 +- backend/src/modules/categories.rs | 183 +++++++++-- backend/tests/api/categories.rs | 190 +++++++++++ src/App.tsx | 5 + src/components/layout/Sidebar.tsx | 6 + src/components/products/ProductFilters.tsx | 6 +- src/i18n/categories.test.ts | 23 ++ src/i18n/categories.ts | 24 ++ src/lib/api/types.ts | 22 +- src/locales/de/admin.json | 34 ++ src/locales/de/common.json | 3 +- src/locales/de/errors.json | 6 + src/locales/en/admin.json | 34 ++ src/locales/en/common.json | 3 +- src/locales/en/errors.json | 6 + .../AdminCategoriesPage.test.tsx | 112 +++++++ .../administrator/AdminCategoriesPage.tsx | 303 ++++++++++++++++++ .../events/components/EditEventCategories.tsx | 3 +- .../components/wizard/WizardPreviews.tsx | 3 +- .../components/EventSettingsSummary.tsx | 6 +- src/pages/public/events/PublicEventPage.tsx | 16 +- .../public/events/PublicEventProductsPage.tsx | 6 +- src/pages/public/products/PublicProduct.tsx | 7 +- .../components/MyProductBasicInfo.tsx | 3 +- .../products/components/MyProductsGrid.tsx | 5 +- src/shared/appRoutes.ts | 1 + 27 files changed, 1002 insertions(+), 48 deletions(-) create mode 100644 backend/migrations/0019_category_translations.sql create mode 100644 src/i18n/categories.test.ts create mode 100644 src/i18n/categories.ts create mode 100644 src/pages/administrator/AdminCategoriesPage.test.tsx create mode 100644 src/pages/administrator/AdminCategoriesPage.tsx 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 d41e1271..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); diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index b2e02f36..46bc062a 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -5,10 +5,11 @@ 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::{Audience, Ctx, Registry}; @@ -18,6 +19,9 @@ 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); @@ -26,6 +30,26 @@ pub fn register(registry: &mut Registry) { 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] #[derive(Debug, Serialize, sqlx::FromRow)] #[serde(rename_all = "camelCase")] @@ -39,6 +63,7 @@ pub struct Category { pub parent_id: Option, #[serde(with = "ms")] pub updated_at: DateTime, + pub translations: Json, } #[derive(Deserialize)] @@ -46,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> { @@ -58,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 @@ -72,16 +107,118 @@ 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 {} @@ -97,7 +234,8 @@ fn same_for_everybody<'a>( 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?) @@ -130,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?; } diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index bd91b1cf..9aaf50c8 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -202,6 +202,196 @@ async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { 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/src/App.tsx b/src/App.tsx index 80d15a0f..381339e5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -99,6 +99,10 @@ 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'), @@ -305,6 +309,7 @@ function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index 5859904b..bc76eada 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -17,6 +17,7 @@ import { Inbox, ScrollText, Scale, + Tags, Home, type LucideIcon, } from 'lucide-react'; @@ -160,6 +161,11 @@ export function Sidebar({ label: t('menu.log'), page: '/admin/log', }, + { + icon: Tags, + label: t('menu.categories'), + page: '/admin/categories', + }, { icon: Scale, label: t('menu.legalPages'), diff --git a/src/components/products/ProductFilters.tsx b/src/components/products/ProductFilters.tsx index fdb85c2b..4f62e18d 100644 --- a/src/components/products/ProductFilters.tsx +++ b/src/components/products/ProductFilters.tsx @@ -1,4 +1,6 @@ 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'; @@ -25,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; } @@ -145,7 +147,7 @@ export function ProductFilters({ {t('filters.allCategories')} {categories.map((category) => ( - {category.label} + {categoryName(category)} ))} diff --git a/src/i18n/categories.test.ts b/src/i18n/categories.test.ts new file mode 100644 index 00000000..34b74192 --- /dev/null +++ b/src/i18n/categories.test.ts @@ -0,0 +1,23 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import i18n from '.'; +import { categoryName, categoryNames } from './categories'; + +const bikes = { _id: 'b', label: 'Fahrräder', translations: { en: 'Bikes' } }; +const misc = { _id: 'm', label: 'Sonstiges', translations: {} }; + +describe('category names', () => { + afterEach(() => i18n.changeLanguage('de')); + + it('uses the translation of the current language, else the label', async () => { + expect(categoryName(bikes)).toBe('Fahrräder'); + await i18n.changeLanguage('en'); + expect(categoryName(bikes)).toBe('Bikes'); + expect(categoryName(misc)).toBe('Sonstiges'); + }); + + it('gives up when the list is not there or lacks a category', () => { + expect(categoryNames(['b'], undefined)).toBeUndefined(); + expect(categoryNames(['gone'], [bikes])).toBeUndefined(); + expect(categoryNames(['m', 'b'], [bikes, misc])).toEqual(['Sonstiges', 'Fahrräder']); + }); +}); diff --git a/src/i18n/categories.ts b/src/i18n/categories.ts new file mode 100644 index 00000000..75191f39 --- /dev/null +++ b/src/i18n/categories.ts @@ -0,0 +1,24 @@ +import type { CategoryTranslations } from '../lib/api/types'; +import i18n from '.'; + +type NamedCategory = { label: string; translations?: CategoryTranslations | undefined }; + +/** + * The name of a category in the current language. For display only: the extra fields and + * the bazaar types go by `label`, whatever the language. + */ +export function categoryName(category: NamedCategory): string { + return (i18n.resolvedLanguage === 'en' && category.translations?.en) || category.label; +} + +/** The names of the given ids; undefined until the list is there or if one is missing. */ +export function categoryNames( + ids: readonly string[] | undefined, + categories: readonly (NamedCategory & { _id: string })[] | undefined +): string[] | undefined { + if (!ids || !categories) return undefined; + const found = ids.map((id) => categories.find((category) => category._id === id)); + return found.every((category) => category !== undefined) + ? found.map((category) => categoryName(category as NamedCategory)) + : undefined; +} diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index eaf0ea9a..7b18f8c3 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -32,6 +32,9 @@ export type Id = string & { __tableName: T }; export type Doc = Docs[T]; +/** Names of a category in other languages; `label` counts where one is missing. */ +export type CategoryTranslations = { en?: string | undefined }; + export interface Docs { users: { _id: Id<'users'>; @@ -165,6 +168,7 @@ export interface Docs { productId: Id<'products'>; }; categories: { + translations: CategoryTranslations; _id: Id<'categories'>; _creationTime: number; parentCategory?: Id<'categories'> | undefined; @@ -586,9 +590,24 @@ export interface Api { categories: { createCategory: FunctionReference< 'mutation', - { parentCategory?: Id<'categories'> | undefined; label: string }, + { + parentCategory?: Id<'categories'> | undefined; + label: string; + translations?: CategoryTranslations | undefined; + }, Id<'categories'> >; + updateCategory: FunctionReference< + 'mutation', + { categoryId: Id<'categories'>; label: string; translations: CategoryTranslations }, + null + >; + deleteCategory: FunctionReference<'mutation', { categoryId: Id<'categories'> }, null>; + listForAdmin: FunctionReference< + 'query', + EmptyObject, + (Doc<'categories'> & { productCount: number; eventCount: number; childCount: number })[] + >; getAllCategories: FunctionReference< 'query', EmptyObject, @@ -598,6 +617,7 @@ export interface Api { parentCategory?: Id<'categories'> | undefined; updatedAt: number; label: string; + translations: CategoryTranslations; }[] >; getCategoryLabel: FunctionReference<'query', { categoryId: Id<'categories'> }, string | null>; diff --git a/src/locales/de/admin.json b/src/locales/de/admin.json index ef31371f..4c4c35d3 100644 --- a/src/locales/de/admin.json +++ b/src/locales/de/admin.json @@ -273,5 +273,39 @@ "saving": "Wird gespeichert…", "save": "Speichern", "replaceWithTemplate": "Den aktuellen Text durch die Vorlage ersetzen?" + }, + "categories": { + "title": "Kategorien", + "subtitle": "Kategorien, aus denen Basare und Artikel wählen.", + "add": "Kategorie hinzufügen", + "edit": "Kategorie bearbeiten", + "new": "Neue Kategorie", + "name": "Name", + "nameEn": "Englischer Name", + "nameEnHint": "Optional. Ohne englischen Namen sehen englischsprachige Besucher den Namen oben.", + "fields": "Zusatzfelder", + "noFields": "Keine", + "usage": "Verwendung", + "subOf": "Unterkategorie von {{parent}}", + "action": "Aktion", + "fieldsHint": "Der Name entscheidet über die Zusatzfelder der Artikel, etwa die Rahmennummer bei Fahrrädern. Er entscheidet auch, welche Kategorien neue Basare vorausgewählt bekommen.", + "fieldsPreview": "Zusatzfelder mit diesem Namen: {{fields}}", + "noFieldsPreview": "Mit diesem Namen hat die Kategorie keine Zusatzfelder.", + "fieldsChange": "Die Zusatzfelder ändern sich für alle Artikel dieser Kategorie.", + "duplicate": "Eine Kategorie mit diesem Namen gibt es schon.", + "saved": "Kategorie gespeichert", + "deleted": "Kategorie gelöscht", + "delete": "Löschen", + "deleteTitle": "„{{name}}“ löschen?", + "deleteText": "Bisherige Verkäufe und Abrechnungen behalten den Namen.", + "inUse": "Wird noch von Artikeln, Basaren oder Unterkategorien verwendet.", + "lastOne": "Die letzte Kategorie kann nicht gelöscht werden.", + "empty": "Noch keine Kategorien", + "editShort": "Bearbeiten", + "save": "Speichern", + "usageProducts_one": "{{count}} Artikel", + "usageProducts_other": "{{count}} Artikel", + "usageEvents_one": "{{count}} Basar", + "usageEvents_other": "{{count}} Basare" } } diff --git a/src/locales/de/common.json b/src/locales/de/common.json index 7131d84b..627bb4bc 100644 --- a/src/locales/de/common.json +++ b/src/locales/de/common.json @@ -53,7 +53,8 @@ "approvals": "{{count}} Events warten auf Freigabe", "messages": "{{count}} offene Kontaktanfragen", "organizerMessages": "{{count}} neue Nachrichten vom Veranstalter" - } + }, + "categories": "Kategorien" }, "footer": { "tagline": "Die moderne Plattform für Marktplatz-Veranstaltungen", diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 24697369..c9c658f4 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -34,6 +34,12 @@ "tooMany": "Höchstens {{max}} Artikel pro Verkauf.", "tooManySales": "Höchstens {{max}} Verkäufe auf einmal nachbuchen." }, + "category": { + "labelEmpty": "Bitte gib einen Namen ein.", + "labelTaken": "Eine Kategorie mit diesem Namen gibt es schon.", + "inUse": "Diese Kategorie wird noch verwendet und kann nicht gelöscht werden.", + "lastOne": "Die letzte Kategorie kann nicht gelöscht werden." + }, "common": { "invalidEmail": "Bitte gib eine gültige E-Mail-Adresse ein." }, diff --git a/src/locales/en/admin.json b/src/locales/en/admin.json index 1d7cc997..d3e5bd13 100644 --- a/src/locales/en/admin.json +++ b/src/locales/en/admin.json @@ -273,5 +273,39 @@ "saving": "Saving…", "save": "Save", "replaceWithTemplate": "Replace the current text with the template?" + }, + "categories": { + "title": "Categories", + "subtitle": "The categories bazaars and items choose from.", + "add": "Add category", + "edit": "Edit category", + "new": "New category", + "name": "Name", + "nameEn": "English name", + "nameEnHint": "Optional. Without an English name, English-speaking visitors see the name above.", + "fields": "Extra fields", + "noFields": "None", + "usage": "Usage", + "subOf": "Sub-category of {{parent}}", + "action": "Action", + "fieldsHint": "The name decides the extra fields of its items, such as the frame number for bikes. It also decides which categories new bazaars get preselected.", + "fieldsPreview": "Extra fields with this name: {{fields}}", + "noFieldsPreview": "With this name the category has no extra fields.", + "fieldsChange": "The extra fields change for all items of this category.", + "duplicate": "A category with this name already exists.", + "saved": "Category saved", + "deleted": "Category deleted", + "delete": "Delete", + "deleteTitle": "Delete “{{name}}”?", + "deleteText": "Past sales and settlements keep the name.", + "inUse": "Still used by items, bazaars or sub-categories.", + "lastOne": "The last category cannot be deleted.", + "empty": "No categories yet", + "editShort": "Edit", + "save": "Save", + "usageProducts_one": "{{count}} item", + "usageProducts_other": "{{count}} items", + "usageEvents_one": "{{count}} bazaar", + "usageEvents_other": "{{count}} bazaars" } } diff --git a/src/locales/en/common.json b/src/locales/en/common.json index 7731240a..b986c8b3 100644 --- a/src/locales/en/common.json +++ b/src/locales/en/common.json @@ -53,7 +53,8 @@ "approvals": "{{count}} events awaiting approval", "messages": "{{count}} open contact requests", "organizerMessages": "{{count}} new messages from the organizer" - } + }, + "categories": "Categories" }, "footer": { "tagline": "The modern platform for marketplace events", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index b99d21d5..e1e6fff2 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -34,6 +34,12 @@ "tooMany": "At most {{max}} items per sale.", "tooManySales": "Sync at most {{max}} sales at once." }, + "category": { + "labelEmpty": "Please enter a name.", + "labelTaken": "A category with this name already exists.", + "inUse": "This category is still in use and cannot be deleted.", + "lastOne": "The last category cannot be deleted." + }, "common": { "invalidEmail": "Please enter a valid email address." }, 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/organizer/events/components/EditEventCategories.tsx b/src/pages/organizer/events/components/EditEventCategories.tsx index b8d75e1d..dfb54f1c 100644 --- a/src/pages/organizer/events/components/EditEventCategories.tsx +++ b/src/pages/organizer/events/components/EditEventCategories.tsx @@ -6,6 +6,7 @@ import type { Doc } from '../../../../lib/api/types'; import { useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { serviceLabel } from '../../../../i18n/services'; +import { categoryName } from '../../../../i18n/categories'; type EventCategoriesProbs = { categoryList: Doc<'categories'>[]; @@ -61,7 +62,7 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { className="cursor-pointer" onClick={() => toggleCategory(catId)} > - {cat.label} + {categoryName(cat)} ); })} diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index 26bb9a3b..6b02a22e 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -41,6 +41,7 @@ import { categoryFieldText } from '../../../../../i18n/categoryFields'; import { REQUIRABLE_FIELDS } from '../../../../../shared/categoryFields'; import { formatEventPlace } from '../../../../../shared/eventJsonLd'; import { MAX_DISCOUNT_PERCENT } from '../../../../../shared/eventFeatures'; +import { categoryName } from '../../../../../i18n/categories'; /* * Previews of the creation wizard: next to each step they show what buyers and sellers @@ -389,7 +390,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { const categoryList = useQuery(api.categories.getAllCategories); const chosen = (categoryList ?? []) .filter((category) => values.categories?.includes(category._id as string)) - .map((category) => category.label); + .map((category) => categoryName(category)); const required = REQUIRABLE_FIELDS.filter((field) => features.requiredFields?.includes(field.key) ).map((field) => categoryFieldText(field, 'label') ?? field.label); diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index b4319ac0..be2c53fd 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -10,6 +10,9 @@ import { useTranslation } from 'react-i18next'; import { serviceLabel } from '../../../../../i18n/services'; import { REQUIRABLE_FIELDS } from '../../../../../shared/categoryFields'; import { categoryFieldText } from '../../../../../i18n/categoryFields'; +import { categoryNames } from '../../../../../i18n/categories'; +import { api } from '../../../../../lib/api/functions'; +import { useQuery } from '../../../../../lib/api/react'; import { formatEventPlace } from '../../../../../shared/eventJsonLd'; type EventWithLabels = Doc<'events'> & { categoryLabels: string[] }; @@ -56,6 +59,7 @@ function formatRange(start: number, end?: number) { /** Read-only overview of the current event settings. */ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { const { t } = useTranslation('organizer'); + const categoryList = useQuery(api.categories.getAllCategories); const timeFormat = new Intl.DateTimeFormat(dateLocale(), { weekday: 'short', day: '2-digit', @@ -96,7 +100,7 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) {
- {event.categoryLabels.map((label) => ( + {(categoryNames(event.categories, categoryList) ?? event.categoryLabels).map((label) => ( {label} diff --git a/src/pages/public/events/PublicEventPage.tsx b/src/pages/public/events/PublicEventPage.tsx index 06d3992c..1e660421 100644 --- a/src/pages/public/events/PublicEventPage.tsx +++ b/src/pages/public/events/PublicEventPage.tsx @@ -33,6 +33,7 @@ import { Footer } from '../../../components/layout/Footer'; import { useInstanceConfig } from '../../../hooks/useInstanceConfig'; import { SellerBroadcasts } from '../../../components/broadcasts/SellerBroadcasts'; import { useTranslation } from 'react-i18next'; +import { categoryNames } from '../../../i18n/categories'; import { serviceLabel } from '../../../i18n/services'; /** @@ -58,6 +59,7 @@ export function PublicEventLanding({ eventId, onNavigate }: PublicEventLandingPr api.events.getPublicEventForViewer, eventId ? { id: eventId as Id<'events'> } : 'skip' ); + const categoryList = usePublicQuery(api.categories.getAllCategories, {}); const coverImageUrls = usePublicQuery( api.products.getImageUrls, event?.coverImage ? { storageIds: [event.coverImage] } : 'skip' @@ -275,12 +277,14 @@ export function PublicEventLanding({ eventId, onNavigate }: PublicEventLandingPr

{t('page.categories')}

- {event.categoryLabels?.map((category: string) => ( - - - {category} - - ))} + {(categoryNames(event.categories, categoryList) ?? event.categoryLabels)?.map( + (category: string) => ( + + + {category} + + ) + )}
diff --git a/src/pages/public/events/PublicEventProductsPage.tsx b/src/pages/public/events/PublicEventProductsPage.tsx index 1ef19de0..dea06b4d 100644 --- a/src/pages/public/events/PublicEventProductsPage.tsx +++ b/src/pages/public/events/PublicEventProductsPage.tsx @@ -26,6 +26,7 @@ import { matchesPublicStatusFilter } from '../../../lib/eventProductStatus'; import { Footer } from '../../../components/layout/Footer'; import { useInstanceConfig } from '../../../hooks/useInstanceConfig'; import { useTranslation } from 'react-i18next'; +import { categoryNames } from '../../../i18n/categories'; /** * Public Event Product List showing all products for a public event @@ -257,10 +258,7 @@ export function PublicEventProductsPage() { > ) => c._id === product.productCategory) - ?.label - } // Read-only view + categoryLabel={categoryNames([product.productCategory], categoryList)?.[0]} />
))} diff --git a/src/pages/public/products/PublicProduct.tsx b/src/pages/public/products/PublicProduct.tsx index 21049606..77afb17c 100644 --- a/src/pages/public/products/PublicProduct.tsx +++ b/src/pages/public/products/PublicProduct.tsx @@ -35,6 +35,7 @@ import { buildSeoDescription, toAbsoluteUrl } from '../../../lib/seo'; import { Footer } from '../../../components/layout/Footer'; import { useInstanceConfig } from '../../../hooks/useInstanceConfig'; import { useTranslation } from 'react-i18next'; +import { categoryNames } from '../../../i18n/categories'; import { areQuestionsOpen } from '../../../shared/eventFeatures'; /** @@ -51,6 +52,7 @@ export function PublicProduct() { api.products.getProduct, productId ? { productId: productId as Id<'products'> } : 'skip' ); + const categoryList = usePublicQuery(api.categories.getAllCategories, {}); const currentUser = useQuery(api.users.viewer); const isAdmin = useQuery(api.moderation.isViewerAdmin, {}); const deleteProduct = useMutation(api.products.deleteProduct); @@ -259,7 +261,10 @@ export function PublicProduct() { price={product.price} condition={product.condition} sold={product.sold} - categoryName={product.categoryName} + categoryName={ + categoryNames([product.productCategory], categoryList)?.[0] ?? + product.categoryName + } discountPercent={product.discountPercent} negotiable={product.isNegotiable} /> diff --git a/src/pages/seller/products/components/MyProductBasicInfo.tsx b/src/pages/seller/products/components/MyProductBasicInfo.tsx index f3c10021..cbfa0b96 100644 --- a/src/pages/seller/products/components/MyProductBasicInfo.tsx +++ b/src/pages/seller/products/components/MyProductBasicInfo.tsx @@ -1,4 +1,5 @@ import { useFormContext } from 'react-hook-form'; +import { categoryName } from '../../../../i18n/categories'; import { Label } from '../../../../components/ui/label'; import { Input } from '../../../../components/ui/input'; import { Textarea } from '../../../../components/ui/text-area'; @@ -117,7 +118,7 @@ export function MyProductBasicInfo({ {categoryList.map((c: Doc<'categories'>) => ( - {c.label} + {categoryName(c)} ))} diff --git a/src/pages/seller/products/components/MyProductsGrid.tsx b/src/pages/seller/products/components/MyProductsGrid.tsx index 5b58c303..e9ab268e 100644 --- a/src/pages/seller/products/components/MyProductsGrid.tsx +++ b/src/pages/seller/products/components/MyProductsGrid.tsx @@ -4,6 +4,9 @@ import { MyProductCard, type MyProductCardProduct } from './MyProductCard'; import type { InvoiceCopy } from '../../../../lib/saleBreakdown'; import { MyProductsEmptyState } from './MyProductsEmptyState'; import i18n from '../../../../i18n'; +import { categoryName } from '../../../../i18n/categories'; + +const categoryLabelOf = (category: CategoryItem | undefined) => category && categoryName(category); /** Dummy product for onboarding when the user has no products yet. Not stored in DB. */ const onboardingDummyProduct = (): MyProductCardProduct => ({ @@ -94,7 +97,7 @@ export function MyProductsGrid({ categoryLabel={ isDummy ? 'Beispiel' - : categories?.find((c) => c._id === product.productCategory)?.label + : categoryLabelOf(categories?.find((c) => c._id === product.productCategory)) } isSelected={!isDummy && selectedProductIds.includes(product._id)} onToggleSelect={isDummy || selectionLocked ? noop : onToggleSelection} diff --git a/src/shared/appRoutes.ts b/src/shared/appRoutes.ts index eaeba3ac..733e061b 100644 --- a/src/shared/appRoutes.ts +++ b/src/shared/appRoutes.ts @@ -42,6 +42,7 @@ export const APP_ROUTES = [ '/admin/events', '/admin', '/admin/reports', + '/admin/categories', '/admin/content', '/admin/messages', '/admin/log', From 634f02e9e2a1adbe5021c3a5a4f8ae7155f77773 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 12:27:40 +0100 Subject: [PATCH 3/3] fix(ui): a select in a form keeps its value while its options load Inside a form Radix keeps a hidden native select. A value arriving before its option made that one report "", which wiped the value: opening an item to edit with the categories already loaded lost its category and condition, so its extra fields were gone and saving failed. No option can be empty, so an empty value is ignored. Co-Authored-By: Claude Opus 5.5 --- src/components/ui/select.test.tsx | 36 +++++++++++++++++++++++++++++++ src/components/ui/select.tsx | 14 ++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 src/components/ui/select.test.tsx 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 5ad3d008..c4544d85 100644 --- a/src/components/ui/select.tsx +++ b/src/components/ui/select.tsx @@ -6,8 +6,18 @@ import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react'; import { cn } from '../../lib/utils'; -function Select({ ...props }: React.ComponentProps) { - return ; +function Select({ onValueChange, ...props }: React.ComponentProps) { + return ( +