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 7faf9af5..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,11 +19,35 @@ 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] @@ -38,6 +63,7 @@ pub struct Category { pub parent_id: Option, #[serde(with = "ms")] pub updated_at: DateTime, + pub translations: Json, } #[derive(Deserialize)] @@ -45,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> { @@ -57,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 @@ -71,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 {} @@ -96,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?) @@ -129,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?; } @@ -157,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/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/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/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/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 ( +