From 5ec20422ae9217f4b2638b531f7c879a997edb03 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 13:09:59 +0100 Subject: [PATCH 1/6] feat(categories): color field, categories for children's vehicles, bike template per guide (#300) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New category field "color" for bikes, clothing and sports gear; it can be made required and shows in the record (PDF/CSV) and at intake - Default categories for bike sales and children's bazaars: children's bikes, balance bikes, scooters, unicycles, ride-on toys, cargo bikes, e-bikes, bike trailers, child bike seats, bike accessories; migration 0032 adds them where the default categories are in use - Unicycles and child seats no longer get the bike fields (no frame number) - Children's vehicles are preselected for the children's bazaar and the bike sale; the bike sale template requires the frame number and has a €3 intake fee, as in the guide "Fahrradbörse organisieren" Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0032_more_categories.sql | 19 +++++++ backend/src/modules/categories.rs | 13 ++++- backend/src/modules/category_fields.rs | 60 +++++++++++++++++++-- backend/tests/api/categories.rs | 6 +-- src/lib/api/types.ts | 1 + src/lib/eventTypes.test.ts | 29 ++++++++++ src/lib/eventTypes.ts | 14 +++-- src/locales/de/organizer.json | 2 +- src/locales/de/records.json | 4 ++ src/locales/en/organizer.json | 2 +- src/locales/en/records.json | 4 ++ src/shared/categoryFields.ts | 16 +++++- src/shared/eventFeatures.test.ts | 33 ++++++++---- 13 files changed, 178 insertions(+), 25 deletions(-) create mode 100644 backend/migrations/0032_more_categories.sql diff --git a/backend/migrations/0032_more_categories.sql b/backend/migrations/0032_more_categories.sql new file mode 100644 index 00000000..09eeeefd --- /dev/null +++ b/backend/migrations/0032_more_categories.sql @@ -0,0 +1,19 @@ +-- More categories for bike sales and children's bazaars (#300), same as DEFAULT_CATEGORIES +-- in src/modules/categories.rs. Only for instances that use the default categories: an +-- instance with its own list keeps it, and an empty one gets all of them when seeded. +INSERT INTO categories (label, translations) +SELECT d.de, jsonb_build_object('en', d.en) +FROM (VALUES + ('Kinderfahrräder', 'Children''s bikes'), + ('Laufräder', 'Balance bikes'), + ('Roller & Scooter', 'Scooters'), + ('Einräder', 'Unicycles'), + ('Bobbycars & Rutschfahrzeuge', 'Ride-on toys'), + ('Lastenräder', 'Cargo bikes'), + ('E-Bikes & Pedelecs', 'E-bikes'), + ('Fahrradanhänger', 'Bike trailers'), + ('Fahrrad-Kindersitze', 'Child bike seats'), + ('Fahrradzubehör', 'Bike accessories') +) AS d (de, en) +WHERE EXISTS (SELECT 1 FROM categories WHERE label = 'Fahrräder') + AND NOT EXISTS (SELECT 1 FROM categories c WHERE lower(c.label) = lower(d.de)); diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index 46bc062a..2ae20f31 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -270,11 +270,22 @@ async fn get_category_id(ctx: &mut Ctx, args: IdArgs) -> AppResult> /// 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] = [ +pub const DEFAULT_CATEGORIES: [(&str, &str); 21] = [ ("Kleidung", "Clothing"), ("Schuhe", "Shoes"), ("Sport", "Sports"), ("Fahrräder", "Bikes"), + // For bike sales and children's bazaars (#300); same list in migration 0032 + ("Kinderfahrräder", "Children's bikes"), + ("Laufräder", "Balance bikes"), + ("Roller & Scooter", "Scooters"), + ("Einräder", "Unicycles"), + ("Bobbycars & Rutschfahrzeuge", "Ride-on toys"), + ("Lastenräder", "Cargo bikes"), + ("E-Bikes & Pedelecs", "E-bikes"), + ("Fahrradanhänger", "Bike trailers"), + ("Fahrrad-Kindersitze", "Child bike seats"), + ("Fahrradzubehör", "Bike accessories"), ("Elektronik", "Electronics"), ("Bücher", "Books"), ("Spielzeug", "Toys"), diff --git a/backend/src/modules/category_fields.rs b/backend/src/modules/category_fields.rs index c065ec0b..25ce4458 100644 --- a/backend/src/modules/category_fields.rs +++ b/backend/src/modules/category_fields.rs @@ -44,10 +44,12 @@ const BIKE: &[CategoryField] = &[ field("frameSize", "frameSize", "Rahmengröße"), field("wheelSize", "wheelSize", "Laufradgröße"), field("brand", "bikeBrand", "Marke"), + field("color", "color", "Farbe"), ]; const CLOTHING: &[CategoryField] = &[ size("clothingSize", "Größe"), field("brand", "brand", "Marke"), + field("color", "color", "Farbe"), ]; const SHOES: &[CategoryField] = &[ size("shoeSize", "Größe (EU)"), @@ -56,6 +58,7 @@ const SHOES: &[CategoryField] = &[ const SPORT: &[CategoryField] = &[ size("sportSize", "Größe / Länge"), field("brand", "brand", "Marke"), + field("color", "color", "Farbe"), ]; const ELECTRONICS: &[CategoryField] = &[ field("brand", "brand", "Marke"), @@ -77,8 +80,10 @@ static RULES: LazyLock> = LazyLock::new(|| { Rule { // "rad" only as a whole word or word ending, so "Radio" does not count as a bike matches: re(r"fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx"), - // Accessories and clothing for cyclists have no frame number - exclude: Some(re(r"zubehör|teile|bekleidung|helm|anhänger|schloss")), + // No frame number: accessories, cycling clothes, trailers, child seats, unicycles + exclude: Some(re( + r"zubehör|teile|bekleidung|helm|anhänger|schloss|sitz|einr[aä]d", + )), fields: BIKE, }, Rule { @@ -243,18 +248,62 @@ mod tests { fn categories_are_matched_by_keywords() { assert_eq!( keys("Fahrräder"), - ["frameNumber", "frameSize", "wheelSize", "brand"] + ["frameNumber", "frameSize", "wheelSize", "brand", "color"] ); assert_eq!(keys("Kinderrad"), keys("Fahrräder")); assert_eq!(keys("E-Bikes / Pedelecs"), keys("Fahrräder")); assert!(keys("Radio").is_empty()); assert!(keys("Fahrradzubehör").is_empty()); - assert_eq!(keys("Damenmode"), ["size", "brand"]); + assert_eq!(keys("Damenmode"), ["size", "brand", "color"]); assert!(keys("Sondermodelle").is_empty()); assert_eq!(keys("Skischuhe"), ["size", "brand"]); + assert_eq!(keys("Sport"), ["size", "brand", "color"]); assert_eq!(keys("Laptops"), ["brand", "model"]); } + /// The default categories for bikes and children's vehicles (#300) + #[test] + fn bike_categories_have_a_frame_number_only_when_ridden_with_one() { + let bike = keys("Fahrräder"); + for label in [ + "Kinderfahrräder", + "Kinderrad", + "Laufräder", + "Laufrad", + "Lastenräder", + "E-Bikes & Pedelecs", + ] { + assert_eq!(keys(label), bike, "{label}"); + } + for label in [ + "Roller & Scooter", + "Einräder", + "Einrad", + "Bobbycars & Rutschfahrzeuge", + "Fahrradanhänger", + "Fahrrad-Kindersitze", + "Fahrradzubehör", + ] { + assert!(keys(label).is_empty(), "{label}"); + } + } + + #[test] + fn every_default_category_is_matched_on_purpose() { + for (label, _) in crate::modules::categories::DEFAULT_CATEGORIES { + let has_frame_number = keys(label).contains(&"frameNumber"); + let bike = matches!( + label, + "Fahrräder" + | "Kinderfahrräder" + | "Laufräder" + | "Lastenräder" + | "E-Bikes & Pedelecs" + ); + assert_eq!(has_frame_number, bike, "{label}"); + } + } + #[test] fn sizes_are_short() { let fields = fields_for_label("Damenmode").unwrap(); @@ -284,7 +333,7 @@ mod tests { parent: Some(bikes), }, ]; - assert_eq!(category_fields(kids, &categories).len(), 4); + assert_eq!(category_fields(kids, &categories).len(), 5); } #[test] @@ -297,6 +346,7 @@ mod tests { "frameSize", "wheelSize", "brand", + "color", "size", "model" ] diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index 9aaf50c8..e0a552a4 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -168,7 +168,7 @@ async fn parallel_mutations_are_serialized_and_retried(db: PgPool) { .fetch_one(&db) .await .unwrap(); - assert_eq!((count, distinct), (11, 11)); + assert_eq!((count, distinct), (21, 21)); } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] @@ -189,9 +189,9 @@ async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { // A new instance gets the defaults, and a second start adds nothing start().await.unwrap(); - assert_eq!(labels().await.len(), 11); + assert_eq!(labels().await.len(), 21); start().await.unwrap(); - assert_eq!(labels().await.len(), 11); + assert_eq!(labels().await.len(), 21); // An instance with categories of its own does not get the defaults back sqlx::query("DELETE FROM categories WHERE label <> 'Kleidung'") diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index beaa198e..bc09c232 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -361,6 +361,7 @@ export type CategoryFieldText = | 'clothingSize' | 'shoeSize' | 'sportSize' + | 'color' | 'model'; export type DiscountRules = { diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index d4e8e389..ba1168af 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -58,6 +58,35 @@ describe('event types', () => { expect(match('skiBazaar', 'Sport')).toBe(true); expect(match('bikeExchange', 'Fahrräder')).toBe(true); expect(match('bikeExchange', 'Radios')).toBe(false); + // Children's vehicles at both, cargo bikes, trailers and accessories only at the bike sale + for (const label of [ + 'Kinderfahrräder', + 'Laufräder', + 'Roller & Scooter', + 'Einräder', + 'Bobbycars & Rutschfahrzeuge', + ]) { + expect(match('kidsBazaar', label), label).toBe(true); + expect(match('bikeExchange', label), label).toBe(true); + } + for (const label of [ + 'Lastenräder', + 'E-Bikes & Pedelecs', + 'Fahrradanhänger', + 'Fahrradzubehör', + ]) { + expect(match('bikeExchange', label), label).toBe(true); + expect(match('kidsBazaar', label), label).toBe(false); + } + expect(match('bikeExchange', 'Einrichtung')).toBe(false); + }); + + it('the bike sale follows the guide: frame number required and an intake fee', () => { + const bikes = findEventType('bikeExchange')!; + expect(bikes.features.requiredFields).toEqual(['frameNumber']); + expect(bikes.features.intakeFee).toBe(3); + expect(bikes.features.photosOptional).toBe(false); + expect(bikes.features.priceOffers && bikes.features.minimumPrice).toBe(true); }); it('drafts may name a kind that no longer exists', () => { diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index af51467a..e84b05d4 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -21,6 +21,8 @@ export interface EventType { } const BIKES = /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i; +/** Ridden by children, sold at children's bazaars and at bike sales */ +const KIDS_VEHICLES = /laufr|roller|scooter|einr[aä]d|bobby|rutsch/i; export const EVENT_TYPES: EventType[] = [ { @@ -42,7 +44,7 @@ export const EVENT_TYPES: EventType[] = [ labelMark: 'universal', priceOnLabel: false, }, - categoryMatch: /kind|baby|spiel|kleid|schuh|buch/i, + categoryMatch: new RegExp(`kind|baby|spiel|kleid|schuh|buch|${KIDS_VEHICLES.source}`, 'i'), }, { // Second-hand for everyone, e.g. a women's clothing bazaar or a flea market @@ -84,7 +86,9 @@ export const EVENT_TYPES: EventType[] = [ categoryMatch: /ski|snowboard|winter|sport|schuh/i, }, { - // Classic bike exchange: items are handed in, sold at a cash desk, paid out after + // Classic bike exchange as in the guide "Fahrradbörse organisieren" of the docs: bikes + // are handed in, sold at a cash desk, paid out after. A record for the police is the + // same plus private sellers only, fixed data and a limit, switched on by the organizer. id: 'bikeExchange', item: 'bike', examplePrices: [140, 65, 25], @@ -95,10 +99,14 @@ export const EVENT_TYPES: EventType[] = [ minimumPrice: true, questions: true, photosOptional: false, + // Against suspicion of theft, and it belongs on the purchase contract + requiredFields: ['frameNumber'], + // Charged for every accepted bike, sold or not, like in the guide + intakeFee: 3, labelFormat: 'standard', priceOnLabel: true, }, - categoryMatch: BIKES, + categoryMatch: new RegExp(`${BIKES.source}|${KIDS_VEHICLES.source}`, 'i'), }, ]; diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 70042f41..07c26652 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -1088,7 +1088,7 @@ "bikeExchange": { "title": "Fahrradbörse", "text": "Räder, Schlösser und Zubehör: abgeben, an der Kasse verkaufen, danach auszahlen.", - "highlights": ["Fotos Pflicht", "Verhandeln (VB)", "Große Etiketten"], + "highlights": ["Fotos Pflicht", "Verhandeln (VB)", "Rahmennummer Pflicht"], "exampleTitle": "Fahrradbörse", "exampleItems": ["Hollandrad, 28 Zoll", "Kinderrad 20 Zoll", "Bügelschloss"] } diff --git a/src/locales/de/records.json b/src/locales/de/records.json index 9e37f32f..f730aa1a 100644 --- a/src/locales/de/records.json +++ b/src/locales/de/records.json @@ -100,6 +100,10 @@ }, "model": { "label": "Modell" + }, + "color": { + "label": "Farbe", + "placeholder": "z. B. Rot" } }, "service": { diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index fd6fd8dc..a635bce7 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -1088,7 +1088,7 @@ "bikeExchange": { "title": "Bike sale", "text": "Bikes, locks and accessories: hand in, sell at the cash desk, pay out afterwards.", - "highlights": ["Photos required", "Negotiable price", "Large labels"], + "highlights": ["Photos required", "Negotiable price", "Frame number required"], "exampleTitle": "Bike sale", "exampleItems": ["City bike, 28 inch", "Children's bike 20 inch", "U-lock"] } diff --git a/src/locales/en/records.json b/src/locales/en/records.json index 60828ac8..e287b11a 100644 --- a/src/locales/en/records.json +++ b/src/locales/en/records.json @@ -100,6 +100,10 @@ }, "model": { "label": "Model" + }, + "color": { + "label": "Color", + "placeholder": "e.g. red" } }, "service": { diff --git a/src/shared/categoryFields.ts b/src/shared/categoryFields.ts index 3639a6bb..2e9f13fa 100644 --- a/src/shared/categoryFields.ts +++ b/src/shared/categoryFields.ts @@ -30,6 +30,7 @@ export type CategoryFieldText = | 'shoeSize' | 'sportSize' | 'brand' + | 'color' | 'model'; const MAX_VALUE_LENGTH = 120; @@ -40,6 +41,14 @@ export function fieldMaxLength(field: CategoryField): number { return field.maxLength ?? MAX_VALUE_LENGTH; } +/** Helps to find an item again on site and to describe it, e.g. a bike for the police */ +const COLOR_FIELD: CategoryField = { + key: 'color', + text: 'color', + label: 'Farbe', + placeholder: 'z. B. Rot', +}; + const BIKE_FIELDS: CategoryField[] = [ { key: 'frameNumber', @@ -52,6 +61,7 @@ const BIKE_FIELDS: CategoryField[] = [ { key: 'frameSize', text: 'frameSize', label: 'Rahmengröße', placeholder: 'z. B. 52 cm oder M' }, { key: 'wheelSize', text: 'wheelSize', label: 'Laufradgröße', placeholder: 'z. B. 28 Zoll' }, { key: 'brand', text: 'bikeBrand', label: 'Marke', placeholder: 'z. B. Cube' }, + COLOR_FIELD, ]; const CLOTHING_FIELDS: CategoryField[] = [ @@ -63,6 +73,7 @@ const CLOTHING_FIELDS: CategoryField[] = [ maxLength: MAX_SIZE_LENGTH, }, { key: 'brand', text: 'brand', label: 'Marke' }, + COLOR_FIELD, ]; const SHOE_FIELDS: CategoryField[] = [ @@ -85,6 +96,7 @@ const SPORT_FIELDS: CategoryField[] = [ maxLength: MAX_SIZE_LENGTH, }, { key: 'brand', text: 'brand', label: 'Marke' }, + COLOR_FIELD, ]; const ELECTRONICS_FIELDS: CategoryField[] = [ @@ -100,8 +112,8 @@ const FIELD_RULES: { match: RegExp; exclude?: RegExp; fields: CategoryField[] }[ { // "rad" only as a whole word or word ending, so "Radio" does not count as a bike match: /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i, - // Accessories and clothing for cyclists have no frame number - exclude: /zubehör|teile|bekleidung|helm|anhänger|schloss/i, + // No frame number: accessories, cycling clothes, trailers, child seats, unicycles + exclude: /zubehör|teile|bekleidung|helm|anhänger|schloss|sitz|einr[aä]d/i, fields: BIKE_FIELDS, }, { match: /schuh|stiefel|sneaker/i, fields: SHOE_FIELDS }, diff --git a/src/shared/eventFeatures.test.ts b/src/shared/eventFeatures.test.ts index fb0755d7..7d97475a 100644 --- a/src/shared/eventFeatures.test.ts +++ b/src/shared/eventFeatures.test.ts @@ -16,7 +16,7 @@ import { } from './eventFeatures'; const keys = (label: string) => getFieldsForLabel(label)?.map((field) => field.key); -const BIKE_KEYS = ['frameNumber', 'frameSize', 'wheelSize', 'brand']; +const BIKE_KEYS = ['frameNumber', 'frameSize', 'wheelSize', 'brand', 'color']; describe('category fields by keyword', () => { test.each([ @@ -30,21 +30,36 @@ describe('category fields by keyword', () => { 'Trekkingräder', 'Rennräder & Gravelbikes', 'BMX & Dirtbikes', - 'Einrad', 'Laufrad', + // The default categories for bikes and children's vehicles (#300) + 'Kinderfahrräder', + 'Laufräder', + 'Lastenräder', + 'E-Bikes & Pedelecs', ])('"%s" gets the bike fields', (label) => { expect(keys(label)).toEqual(BIKE_KEYS); }); - test.each(['Radio & HiFi', 'Fahrradzubehör', 'Fahrradteile', 'Fahrradhelme', 'Sonstiges'])( - '"%s" gets no bike fields', - (label) => { - expect(keys(label)).not.toEqual(BIKE_KEYS); - } - ); + // Same cases as in backend/src/modules/category_fields.rs + test.each([ + 'Radio & HiFi', + 'Fahrradzubehör', + 'Fahrradteile', + 'Fahrradhelme', + 'Sonstiges', + 'Roller & Scooter', + 'Einräder', + 'Einrad', + 'Bobbycars & Rutschfahrzeuge', + 'Fahrradanhänger', + 'Fahrrad-Kindersitze', + ])('"%s" gets no bike fields', (label) => { + expect(keys(label)).toBeUndefined(); + }); test('cycling clothes count as clothing, sports shoes as shoes', () => { - expect(keys('Fahrradbekleidung')).toEqual(['size', 'brand']); + expect(keys('Fahrradbekleidung')).toEqual(['size', 'brand', 'color']); + expect(keys('Skischuhe')).toEqual(['size', 'brand']); expect(getFieldsForLabel('Sportschuhe')?.[0].label).toBe('Größe (EU)'); expect(getFieldsForLabel('Kleidung')?.[0].label).toBe('Größe'); expect(getFieldsForLabel('Damenmode')?.[0].label).toBe('Größe'); From eecd4046c2ec8a63afe2498cac7e1b024438eccc Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 13:34:27 +0100 Subject: [PATCH 2/6] feat(categories): main categories with one level of sub-categories (#300) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Default tree: "Fahrräder" with children's and cargo bikes, e-bikes, trailers, child seats and accessories; new main category "Kinderfahrzeuge" with balance bikes, scooters, unicycles, ride-on toys. Migration 0032 builds it on instances with the default categories and fixes their order (seeded categories shared one creation time) - Admins pick the main category when creating or editing; the backend keeps it one level deep (category.parentNotMain, category.hasSubcategories) - A label a field rule excludes on purpose has no fields, so "Fahrradanhänger" below "Fahrräder" does not inherit the frame number - Grouped lists: the bazaar form shows main categories that select their sub-categories and open to pick them one by one; item form and filters indent sub-categories; a filter on a main category includes them; bazaar pages name a fully chosen main category instead of all its children Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0032_more_categories.sql | 69 ++++++-- backend/src/modules/categories.rs | 161 +++++++++++++----- backend/src/modules/category_fields.rs | 83 +++++++-- backend/tests/api/categories.rs | 97 ++++++++++- .../products/CategorySelectItems.tsx | 44 +++++ src/components/products/ProductFilters.tsx | 15 +- src/hooks/useMyProductsFilters.ts | 10 +- src/i18n/categories.ts | 13 ++ src/lib/api/types.ts | 8 +- src/lib/eventTypes.test.ts | 1 + src/lib/eventTypes.ts | 2 +- src/locales/de/admin.json | 4 + src/locales/de/errors.json | 2 + src/locales/de/organizer.json | 2 + src/locales/en/admin.json | 4 + src/locales/en/errors.json | 2 + src/locales/en/organizer.json | 2 + .../AdminCategoriesPage.test.tsx | 29 ++++ .../administrator/AdminCategoriesPage.tsx | 53 +++++- .../components/EditEventCategories.test.tsx | 58 +++++++ .../events/components/EditEventCategories.tsx | 97 +++++++++-- .../components/wizard/WizardPreviews.tsx | 9 +- .../components/EventSettingsSummary.tsx | 14 +- src/pages/public/events/PublicEventPage.tsx | 4 +- .../public/events/PublicEventProductsPage.tsx | 5 +- src/pages/seller/products/MyProductsPage.tsx | 1 + .../components/MyProductBasicInfo.tsx | 10 +- src/shared/categoryFields.ts | 14 +- src/shared/categoryTree.test.ts | 43 +++++ src/shared/categoryTree.ts | 64 +++++++ src/shared/eventFeatures.test.ts | 20 ++- 31 files changed, 808 insertions(+), 132 deletions(-) create mode 100644 src/components/products/CategorySelectItems.tsx create mode 100644 src/pages/organizer/events/components/EditEventCategories.test.tsx create mode 100644 src/shared/categoryTree.test.ts create mode 100644 src/shared/categoryTree.ts diff --git a/backend/migrations/0032_more_categories.sql b/backend/migrations/0032_more_categories.sql index 09eeeefd..5742702b 100644 --- a/backend/migrations/0032_more_categories.sql +++ b/backend/migrations/0032_more_categories.sql @@ -1,19 +1,56 @@ --- More categories for bike sales and children's bazaars (#300), same as DEFAULT_CATEGORIES --- in src/modules/categories.rs. Only for instances that use the default categories: an --- instance with its own list keeps it, and an empty one gets all of them when seeded. +-- Categories for bike sales and children's bazaars (#300), grouped under main categories so +-- the lists stay short. Same tree and order as DEFAULT_CATEGORIES in src/modules/categories.rs. +-- Only for instances that use the default categories: an instance with its own list keeps +-- it, and an empty one gets the whole tree when it is seeded. +CREATE TEMPORARY TABLE default_categories (n int, de text, en text, parent text, added bool) ON COMMIT DROP; +INSERT INTO default_categories VALUES + (0, 'Kleidung', 'Clothing', NULL, false), + (1, 'Schuhe', 'Shoes', NULL, false), + (2, 'Sport', 'Sports', NULL, false), + (3, 'Fahrräder', 'Bikes', NULL, false), + (4, 'Kinderfahrräder', 'Children''s bikes', 'Fahrräder', true), + (5, 'Lastenräder', 'Cargo bikes', 'Fahrräder', true), + (6, 'E-Bikes & Pedelecs', 'E-bikes', 'Fahrräder', true), + (7, 'Fahrradanhänger', 'Bike trailers', 'Fahrräder', true), + (8, 'Fahrrad-Kindersitze', 'Child bike seats', 'Fahrräder', true), + (9, 'Fahrradzubehör', 'Bike accessories', 'Fahrräder', true), + (10, 'Kinderfahrzeuge', 'Children''s vehicles', NULL, true), + (11, 'Laufräder', 'Balance bikes', 'Kinderfahrzeuge', true), + (12, 'Roller & Scooter', 'Scooters', 'Kinderfahrzeuge', true), + (13, 'Einräder', 'Unicycles', 'Kinderfahrzeuge', true), + (14, 'Bobbycars & Rutschfahrzeuge', 'Ride-on toys', 'Kinderfahrzeuge', true), + (15, 'Elektronik', 'Electronics', NULL, false), + (16, 'Bücher', 'Books', NULL, false), + (17, 'Spielzeug', 'Toys', NULL, false), + (18, 'Möbel', 'Furniture', NULL, false), + (19, 'Haushalt', 'Household', NULL, false), + (20, 'Accessoires', 'Accessories', NULL, false), + (21, 'Sonstiges', 'Other', NULL, false); + +-- Only the added ones: a default category an admin deleted stays deleted INSERT INTO categories (label, translations) SELECT d.de, jsonb_build_object('en', d.en) -FROM (VALUES - ('Kinderfahrräder', 'Children''s bikes'), - ('Laufräder', 'Balance bikes'), - ('Roller & Scooter', 'Scooters'), - ('Einräder', 'Unicycles'), - ('Bobbycars & Rutschfahrzeuge', 'Ride-on toys'), - ('Lastenräder', 'Cargo bikes'), - ('E-Bikes & Pedelecs', 'E-bikes'), - ('Fahrradanhänger', 'Bike trailers'), - ('Fahrrad-Kindersitze', 'Child bike seats'), - ('Fahrradzubehör', 'Bike accessories') -) AS d (de, en) -WHERE EXISTS (SELECT 1 FROM categories WHERE label = 'Fahrräder') +FROM default_categories d +WHERE d.added + AND EXISTS (SELECT 1 FROM categories WHERE label = 'Fahrräder') AND NOT EXISTS (SELECT 1 FROM categories c WHERE lower(c.label) = lower(d.de)); + +-- Sub-categories go under their main category, one level deep: only categories on top that +-- have no sub-categories of their own, under a main category that is on top itself +UPDATE categories c +SET parent_id = p.id, updated_at = now() +FROM default_categories d +JOIN categories p ON p.label = d.parent AND p.parent_id IS NULL +WHERE c.label = d.de + AND c.parent_id IS NULL + AND NOT EXISTS (SELECT 1 FROM categories s WHERE s.parent_id = c.id); + +-- Lists follow the creation time, but the seeded categories all share one: put the default +-- ones in their order, so "Kinderfahrzeuge" follows "Fahrräder" and "Sonstiges" stays last +UPDATE categories c +SET created_at = b.first + d.n * interval '1 millisecond' +FROM default_categories d, + (SELECT min(c.created_at) AS first + FROM categories c JOIN default_categories d ON d.de = c.label) b +WHERE c.label = d.de + AND EXISTS (SELECT 1 FROM categories WHERE label = 'Fahrräder'); diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index 2ae20f31..6f69c87e 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -96,16 +96,10 @@ async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult { if let Some(existing) = find_by_label(ctx, &label).await? { return Ok(existing); } - // A parent that does not exist is left out - let parent: Option = match args.parent_category { - Some(parent) => { - sqlx::query_scalar("SELECT id FROM categories WHERE id = $1") - .bind(parent.0) - .fetch_optional(ctx.conn()) - .await? - } - None => None, - }; + let parent = args.parent_category.map(|parent| parent.0); + if let Some(parent) = parent { + check_parent(ctx, None, parent).await?; + } let id = sqlx::query_scalar( "INSERT INTO categories (label, parent_id, translations) VALUES ($1, $2, $3) RETURNING id", ) @@ -124,6 +118,36 @@ struct UpdateArgs { category_id: Id, label: String, translations: Translations, + /// The main category; none makes it a main category itself + #[serde(default)] + parent_category: Option, +} + +/// Categories have one level of sub-categories, so lists stay short and grouped: the parent +/// must be a main category, and a category with sub-categories cannot become one itself. +async fn check_parent(ctx: &mut Ctx, category: Option, parent: Uuid) -> AppResult<()> { + let parent_of_parent: Option> = + sqlx::query_scalar("SELECT parent_id FROM categories WHERE id = $1") + .bind(parent) + .fetch_optional(ctx.conn()) + .await?; + let Some(parent_of_parent) = parent_of_parent else { + return Err(AppError::not_found("notFound.category")); + }; + if Some(parent) == category || parent_of_parent.is_some() { + return Err(AppError::bad_request("category.parentNotMain")); + } + if let Some(category) = category { + let has_children: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM categories WHERE parent_id = $1)") + .bind(category) + .fetch_one(ctx.conn()) + .await?; + if has_children { + return Err(AppError::bad_request("category.hasSubcategories")); + } + } + Ok(()) } /// Admins only. Items and bazaars point to the id and follow; sales keep the name they had. @@ -140,12 +164,18 @@ async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { if taken { return Err(AppError::bad_request("category.labelTaken")); } + let parent = args.parent_category.map(|parent| parent.0); + if let Some(parent) = parent { + check_parent(ctx, Some(args.category_id.0), parent).await?; + } let updated = sqlx::query( - "UPDATE categories SET label = $2, translations = $3, updated_at = now() WHERE id = $1", + "UPDATE categories SET label = $2, translations = $3, parent_id = $4, updated_at = now() + WHERE id = $1", ) .bind(args.category_id.0) .bind(&label) .bind(Json(args.translations.trimmed())) + .bind(parent) .execute(ctx.conn()) .await?; if updated.rows_affected() == 0 { @@ -268,44 +298,85 @@ async fn get_category_id(ctx: &mut Ctx, args: IdArgs) -> AppResult> Ok(find_by_label(ctx, &args.category_label).await?) } -/// 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); 21] = [ - ("Kleidung", "Clothing"), - ("Schuhe", "Shoes"), - ("Sport", "Sports"), - ("Fahrräder", "Bikes"), - // For bike sales and children's bazaars (#300); same list in migration 0032 - ("Kinderfahrräder", "Children's bikes"), - ("Laufräder", "Balance bikes"), - ("Roller & Scooter", "Scooters"), - ("Einräder", "Unicycles"), - ("Bobbycars & Rutschfahrzeuge", "Ride-on toys"), - ("Lastenräder", "Cargo bikes"), - ("E-Bikes & Pedelecs", "E-bikes"), - ("Fahrradanhänger", "Bike trailers"), - ("Fahrrad-Kindersitze", "Child bike seats"), - ("Fahrradzubehör", "Bike accessories"), - ("Elektronik", "Electronics"), - ("Bücher", "Books"), - ("Spielzeug", "Toys"), - ("Möbel", "Furniture"), - ("Haushalt", "Household"), - ("Accessoires", "Accessories"), - ("Sonstiges", "Other"), +/// A default category: German label, English name and the label of its main category. +pub struct DefaultCategory { + pub label: &'static str, + pub en: &'static str, + pub parent: Option<&'static str>, +} + +const fn main(label: &'static str, en: &'static str) -> DefaultCategory { + DefaultCategory { + label, + en, + parent: None, + } +} + +const fn sub(parent: &'static str, label: &'static str, en: &'static str) -> DefaultCategory { + DefaultCategory { + label, + en, + parent: Some(parent), + } +} + +/// The default categories, main categories before their sub-categories; adds the missing +/// ones, safe to run repeatedly: `bazarpro-backend run categories.seedCategories`. +/// Same tree as migration 0032. +pub const DEFAULT_CATEGORIES: [DefaultCategory; 22] = [ + main("Kleidung", "Clothing"), + main("Schuhe", "Shoes"), + main("Sport", "Sports"), + main("Fahrräder", "Bikes"), + sub("Fahrräder", "Kinderfahrräder", "Children's bikes"), + sub("Fahrräder", "Lastenräder", "Cargo bikes"), + sub("Fahrräder", "E-Bikes & Pedelecs", "E-bikes"), + sub("Fahrräder", "Fahrradanhänger", "Bike trailers"), + sub("Fahrräder", "Fahrrad-Kindersitze", "Child bike seats"), + sub("Fahrräder", "Fahrradzubehör", "Bike accessories"), + // Ridden by children, sold at children's bazaars and bike sales (#300) + main("Kinderfahrzeuge", "Children's vehicles"), + sub("Kinderfahrzeuge", "Laufräder", "Balance bikes"), + sub("Kinderfahrzeuge", "Roller & Scooter", "Scooters"), + sub("Kinderfahrzeuge", "Einräder", "Unicycles"), + sub( + "Kinderfahrzeuge", + "Bobbycars & Rutschfahrzeuge", + "Ride-on toys", + ), + main("Elektronik", "Electronics"), + main("Bücher", "Books"), + main("Spielzeug", "Toys"), + main("Möbel", "Furniture"), + main("Haushalt", "Household"), + main("Accessoires", "Accessories"), + main("Sonstiges", "Other"), ]; async fn seed_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<&'static str> { - for (label, en) in DEFAULT_CATEGORIES { - if find_by_label(ctx, label).await?.is_none() { - sqlx::query("INSERT INTO categories (label, translations) VALUES ($1, $2)") - .bind(label) - .bind(Json(Translations { - en: Some(en.to_owned()), - })) - .execute(ctx.conn()) - .await?; + for (position, category) in DEFAULT_CATEGORIES.iter().enumerate() { + if find_by_label(ctx, category.label).await?.is_some() { + continue; } + // Main categories come first; a renamed or deleted one leaves the sub-category on top + let parent = match category.parent { + Some(parent) => find_by_label(ctx, parent).await?, + None => None, + }; + // Lists follow the creation time, and one run is one transaction with one now() + sqlx::query( + "INSERT INTO categories (label, parent_id, translations, created_at) + VALUES ($1, $2, $3, now() + $4 * interval '1 millisecond')", + ) + .bind(category.label) + .bind(parent) + .bind(Json(Translations { + en: Some(category.en.to_owned()), + })) + .bind(position as f64) + .execute(ctx.conn()) + .await?; } ctx.touch(TOPIC); Ok("Categories seeded successfully") diff --git a/backend/src/modules/category_fields.rs b/backend/src/modules/category_fields.rs index 25ce4458..b6791f7c 100644 --- a/backend/src/modules/category_fields.rs +++ b/backend/src/modules/category_fields.rs @@ -120,15 +120,20 @@ pub fn requirable_fields() -> Vec { .collect() } +/// The fields of a label, None when no rule speaks about it. A label a rule excludes on +/// purpose ("Fahrradanhänger") has no fields: as a sub-category of "Fahrräder" it must not +/// inherit the frame number. pub fn fields_for_label(label: &str) -> Option<&'static [CategoryField]> { let name = label.trim(); - RULES - .iter() - .find(|rule| { - rule.matches.is_match(name) - && !rule.exclude.as_ref().is_some_and(|ex| ex.is_match(name)) - }) - .map(|rule| rule.fields) + let mut excluded = false; + for rule in RULES.iter().filter(|rule| rule.matches.is_match(name)) { + if rule.exclude.as_ref().is_some_and(|ex| ex.is_match(name)) { + excluded = true; + } else { + return Some(rule.fields); + } + } + excluded.then_some(&[]) } /// A category with its parent, for the inheritance of fields. @@ -288,19 +293,45 @@ mod tests { } } + /// With the inheritance from the main category, as the default tree is seeded #[test] fn every_default_category_is_matched_on_purpose() { - for (label, _) in crate::modules::categories::DEFAULT_CATEGORIES { - let has_frame_number = keys(label).contains(&"frameNumber"); + let defaults = &crate::modules::categories::DEFAULT_CATEGORIES; + let id = |label: &str| { + let index = defaults.iter().position(|c| c.label == label).unwrap(); + Uuid::from_u128(index as u128 + 1) + }; + let tree: Vec = defaults + .iter() + .map(|c| CategoryRef { + id: id(c.label), + label: c.label.into(), + parent: c.parent.map(id), + }) + .collect(); + for category in defaults { + let fields = category_fields(id(category.label), &tree); + let has_frame_number = fields.iter().any(|f| f.key == "frameNumber"); let bike = matches!( - label, + category.label, "Fahrräder" | "Kinderfahrräder" | "Laufräder" | "Lastenräder" | "E-Bikes & Pedelecs" ); - assert_eq!(has_frame_number, bike, "{label}"); + assert_eq!(has_frame_number, bike, "{}", category.label); + // One level: a main category is listed before its sub-categories + if let Some(parent) = category.parent { + let main = defaults.iter().position(|c| c.label == parent).unwrap(); + assert!(defaults[main].parent.is_none(), "{parent}"); + assert!( + main < defaults + .iter() + .position(|c| c.label == category.label) + .unwrap() + ); + } } } @@ -336,6 +367,36 @@ mod tests { assert_eq!(category_fields(kids, &categories).len(), 5); } + #[test] + fn excluded_sub_categories_do_not_inherit_the_frame_number() { + let bikes = Uuid::new_v4(); + let trailers = Uuid::new_v4(); + let clothes = Uuid::new_v4(); + let categories = vec![ + CategoryRef { + id: bikes, + label: "Fahrräder".into(), + parent: None, + }, + CategoryRef { + id: trailers, + label: "Fahrradanhänger".into(), + parent: Some(bikes), + }, + CategoryRef { + id: clothes, + label: "Fahrradbekleidung".into(), + parent: Some(bikes), + }, + ]; + assert!(category_fields(trailers, &categories).is_empty()); + let keys: Vec<_> = category_fields(clothes, &categories) + .iter() + .map(|f| f.key) + .collect(); + assert_eq!(keys, ["size", "brand", "color"]); + } + #[test] fn requirable_fields_are_unique_by_key() { let keys: Vec<_> = requirable_fields().iter().map(|f| f.key).collect(); diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index e0a552a4..22d1595a 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -168,7 +168,7 @@ async fn parallel_mutations_are_serialized_and_retried(db: PgPool) { .fetch_one(&db) .await .unwrap(); - assert_eq!((count, distinct), (21, 21)); + assert_eq!((count, distinct), (22, 22)); } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] @@ -189,9 +189,9 @@ async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { // A new instance gets the defaults, and a second start adds nothing start().await.unwrap(); - assert_eq!(labels().await.len(), 21); + assert_eq!(labels().await.len(), 22); start().await.unwrap(); - assert_eq!(labels().await.len(), 21); + assert_eq!(labels().await.len(), 22); // An instance with categories of its own does not get the defaults back sqlx::query("DELETE FROM categories WHERE label <> 'Kleidung'") @@ -390,6 +390,97 @@ async fn the_default_categories_come_with_their_english_names(db: PgPool) { .find(|c| c["label"] == "Fahrräder") .unwrap(); assert_eq!(bikes["translations"]["en"], "Bikes"); + + // One level of sub-categories, the main category with them + let parent_of = |label: &str| { + let list = list.body["value"].as_array().unwrap(); + let child = list.iter().find(|c| c["label"] == label).unwrap(); + let parent = child.get("parentCategory")?; + list.iter() + .find(|c| &c["_id"] == parent) + .map(|c| c["label"].as_str().unwrap().to_owned()) + }; + assert_eq!(parent_of("Fahrradanhänger").as_deref(), Some("Fahrräder")); + assert_eq!(parent_of("Laufräder").as_deref(), Some("Kinderfahrzeuge")); + assert_eq!(parent_of("Fahrräder"), None); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn admins_move_categories_one_level_deep(db: PgPool) { + let app = app(&db).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 + } + }; + let id = |response: common::Reply| response.body["value"].as_str().unwrap().to_owned(); + let bikes = id(create(json!({ "label": "Fahrräder" })).await); + let kids = id(create(json!({ "label": "Kinderfahrräder", "parentCategory": bikes })).await); + let trailers = id(create(json!({ "label": "Fahrradanhänger" })).await); + let update = |category: &str, label: &str, parent: Option<&str>| { + let (app, admin) = (&app, &admin); + let args = json!({ + "categoryId": category, + "label": label, + "translations": {}, + "parentCategory": parent, + }); + async move { + app.mutation("categories.updateCategory", args, Some(admin)) + .await + } + }; + let parent_of = |category: String| { + let db = &db; + async move { + sqlx::query_scalar::<_, Option>( + "SELECT parent_id FROM categories WHERE id = $1", + ) + .bind(uuid::Uuid::parse_str(&category).unwrap()) + .fetch_one(db) + .await + .unwrap() + .map(|id| id.to_string()) + } + }; + + // A main category gets a sub-category, and it can go back to the top + let moved = update(&trailers, "Fahrradanhänger", Some(&bikes)).await; + assert_eq!(moved.status, StatusCode::OK, "{:?}", moved.body); + assert_eq!(parent_of(trailers.clone()).await, Some(bikes.clone())); + update(&trailers, "Fahrradanhänger", None).await; + assert_eq!(parent_of(trailers.clone()).await, None); + + // No second level, no loop, and no main category with sub-categories below another + assert_eq!( + update(&trailers, "Fahrradanhänger", Some(&kids)).await.body["code"], + "category.parentNotMain" + ); + assert_eq!( + create(json!({ "label": "Laufräder", "parentCategory": kids })) + .await + .body["code"], + "category.parentNotMain" + ); + assert_eq!( + update(&bikes, "Fahrräder", Some(&bikes)).await.body["code"], + "category.parentNotMain" + ); + assert_eq!( + update(&bikes, "Fahrräder", Some(&trailers)).await.body["code"], + "category.hasSubcategories" + ); + let gone = uuid::Uuid::new_v4().to_string(); + assert_eq!( + update(&trailers, "Fahrradanhänger", Some(&gone)) + .await + .status, + StatusCode::NOT_FOUND + ); + assert_eq!(parent_of(bikes).await, None); } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] diff --git a/src/components/products/CategorySelectItems.tsx b/src/components/products/CategorySelectItems.tsx new file mode 100644 index 00000000..2b0d50a7 --- /dev/null +++ b/src/components/products/CategorySelectItems.tsx @@ -0,0 +1,44 @@ +import { Fragment } from 'react'; +import { SelectGroup, SelectItem, SelectSeparator } from '../ui/select'; +import { categoryName } from '../../i18n/categories'; +import type { CategoryTranslations } from '../../lib/api/types'; +import { groupCategories } from '../../shared/categoryTree'; + +type SelectableCategory = { + _id: string; + label: string; + parentCategory?: string; + translations?: CategoryTranslations; +}; + +/** + * The options of a category select: main categories, each followed by its indented + * sub-categories, so a long list reads as a few groups. + */ +export function CategorySelectItems({ categories }: { categories: readonly SelectableCategory[] }) { + const groups = groupCategories(categories); + // A line around each group with sub-categories, one between two groups + const hasChildren = (index: number) => (groups[index]?.children.length ?? 0) > 0; + return groups.map(({ category, children }, index) => + children.length === 0 ? ( + + {categoryName(category)} + + ) : ( + + {index > 0 && !hasChildren(index - 1) && } + + + {categoryName(category)} + + {children.map((child) => ( + + {categoryName(child)} + + ))} + + {index < groups.length - 1 && } + + ) + ); +} diff --git a/src/components/products/ProductFilters.tsx b/src/components/products/ProductFilters.tsx index 977d9d90..aa020def 100644 --- a/src/components/products/ProductFilters.tsx +++ b/src/components/products/ProductFilters.tsx @@ -1,6 +1,6 @@ import { SearchInput } from '../ui/search-input'; import type { CategoryTranslations } from '../../lib/api/types'; -import { categoryName } from '../../i18n/categories'; +import { CategorySelectItems } from './CategorySelectItems'; import { SlidersHorizontal, CheckSquare } from 'lucide-react'; import { useMemo, useState, useEffect } from 'react'; import { Input } from '../ui/input'; @@ -29,7 +29,12 @@ interface ProductFiltersProps { onMaxPriceChange?: (value: string) => void; filterCategory?: string; onFilterCategoryChange?: (value: string) => void; - categories?: { _id: string; label: string; translations?: CategoryTranslations }[]; + categories?: { + _id: string; + label: string; + parentCategory?: string; + translations?: CategoryTranslations; + }[]; showBulkSelection?: boolean; onToggleBulkSelection?: () => void; /** Tiles or list; the toggle shows with a handler */ @@ -163,11 +168,7 @@ export function ProductFilters({ {t('filters.allCategories')} - {categories.map((category) => ( - - {categoryName(category)} - - ))} + )} diff --git a/src/hooks/useMyProductsFilters.ts b/src/hooks/useMyProductsFilters.ts index 50e6a4a5..49a67b51 100644 --- a/src/hooks/useMyProductsFilters.ts +++ b/src/hooks/useMyProductsFilters.ts @@ -1,4 +1,5 @@ import type { Id } from '../lib/api/types'; +import { withSubcategories } from '../shared/categoryTree'; export interface ProductForFilter { _id: Id<'products'>; @@ -21,6 +22,8 @@ export interface MyProductsFilterState { sortBy: string; minPrice: string; maxPrice: string; + /** For the filter on a main category, which also shows its sub-categories */ + categories?: readonly { _id: string; parentCategory?: string }[]; } /** @@ -31,11 +34,14 @@ export function filterAndSortProducts( products: T[], state: MyProductsFilterState ): T[] { + const inCategory = + state.filterCategory === 'all' + ? undefined + : withSubcategories(state.filterCategory, state.categories); let filtered = products.filter((p) => { const matchesSearch = p.title.toLowerCase().includes(state.searchTerm.toLowerCase()); const matchesEvent = state.filterEvent === 'all' || p.eventIds.includes(state.filterEvent); - const matchesCategory = - state.filterCategory === 'all' || p.productCategory === state.filterCategory; + const matchesCategory = !inCategory || inCategory.has(p.productCategory); const matchesStatus = state.filterStatus === 'all' || (state.filterStatus === 'sold' && p.sold) || diff --git a/src/i18n/categories.ts b/src/i18n/categories.ts index 75191f39..d6bc9c76 100644 --- a/src/i18n/categories.ts +++ b/src/i18n/categories.ts @@ -1,5 +1,6 @@ import type { CategoryTranslations } from '../lib/api/types'; import i18n from '.'; +import { collapseSubcategories } from '../shared/categoryTree'; type NamedCategory = { label: string; translations?: CategoryTranslations | undefined }; @@ -22,3 +23,15 @@ export function categoryNames( ? found.map((category) => categoryName(category as NamedCategory)) : undefined; } + +/** + * The names of the categories a bazaar allows, shortened: a main category chosen with all + * its sub-categories stands for them. + */ +export function eventCategoryNames( + ids: readonly string[] | undefined, + categories: readonly (NamedCategory & { _id: string; parentCategory?: string })[] | undefined +): string[] | undefined { + if (!ids || !categories) return undefined; + return categoryNames(collapseSubcategories(ids, categories), categories); +} diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index bc09c232..53b23d5e 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -643,7 +643,13 @@ export interface Api { >; updateCategory: FunctionReference< 'mutation', - { categoryId: Id<'categories'>; label: string; translations: CategoryTranslations }, + { + categoryId: Id<'categories'>; + label: string; + translations: CategoryTranslations; + /** Unset: a main category */ + parentCategory?: Id<'categories'> | undefined; + }, null >; deleteCategory: FunctionReference<'mutation', { categoryId: Id<'categories'> }, null>; diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index ba1168af..c3bcefb3 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -65,6 +65,7 @@ describe('event types', () => { 'Roller & Scooter', 'Einräder', 'Bobbycars & Rutschfahrzeuge', + 'Kinderfahrzeuge', ]) { expect(match('kidsBazaar', label), label).toBe(true); expect(match('bikeExchange', label), label).toBe(true); diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index e84b05d4..408db225 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -22,7 +22,7 @@ export interface EventType { const BIKES = /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i; /** Ridden by children, sold at children's bazaars and at bike sales */ -const KIDS_VEHICLES = /laufr|roller|scooter|einr[aä]d|bobby|rutsch/i; +const KIDS_VEHICLES = /kinderfahrz|laufr|roller|scooter|einr[aä]d|bobby|rutsch/i; export const EVENT_TYPES: EventType[] = [ { diff --git a/src/locales/de/admin.json b/src/locales/de/admin.json index 676d995a..2a5ef112 100644 --- a/src/locales/de/admin.json +++ b/src/locales/de/admin.json @@ -288,6 +288,10 @@ "noFields": "Keine", "usage": "Verwendung", "subOf": "Unterkategorie von {{parent}}", + "parent": "Hauptkategorie", + "noParent": "Keine – ist selbst Hauptkategorie", + "parentHint": "Unterkategorien stehen in allen Listen unter ihrer Hauptkategorie. Ohne eigene Zusatzfelder übernehmen sie die der Hauptkategorie.", + "parentLocked": "Diese Kategorie hat Unterkategorien und bleibt deshalb Hauptkategorie.", "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}}", diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 26f1f2f0..8a182e15 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -39,6 +39,8 @@ "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.", + "parentNotMain": "Eine Unterkategorie kann nur unter einer Hauptkategorie stehen.", + "hasSubcategories": "Diese Kategorie hat selbst Unterkategorien und kann deshalb keine Unterkategorie werden.", "lastOne": "Die letzte Kategorie kann nicht gelöscht werden." }, "common": { diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 07c26652..e9e646c5 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -101,6 +101,8 @@ "categories": { "title": "Kategorien & Services", "allowed": "Erlaubte Artikelkategorien *", + "subcategories": "Unterkategorien von {{name}}", + "groupHint": "Eine Hauptkategorie wählt ihre Unterkategorien mit. Über den Pfeil wählst du sie einzeln.", "services": "Zusätzliche Services" }, "contact": { diff --git a/src/locales/en/admin.json b/src/locales/en/admin.json index f3d219dc..1c2122ca 100644 --- a/src/locales/en/admin.json +++ b/src/locales/en/admin.json @@ -288,6 +288,10 @@ "noFields": "None", "usage": "Usage", "subOf": "Sub-category of {{parent}}", + "parent": "Main category", + "noParent": "None – is a main category itself", + "parentHint": "Sub-categories are listed under their main category everywhere. Without extra fields of their own, they take those of the main category.", + "parentLocked": "This category has sub-categories, so it stays a main category.", "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}}", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index c6d398a2..996c22f1 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -39,6 +39,8 @@ "labelEmpty": "Please enter a name.", "labelTaken": "A category with this name already exists.", "inUse": "This category is still in use and cannot be deleted.", + "parentNotMain": "A sub-category can only be placed under a main category.", + "hasSubcategories": "This category has sub-categories of its own and therefore cannot become a sub-category.", "lastOne": "The last category cannot be deleted." }, "common": { diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index a635bce7..52728dc0 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -101,6 +101,8 @@ "categories": { "title": "Categories & services", "allowed": "Allowed item categories *", + "subcategories": "Sub-categories of {{name}}", + "groupHint": "A main category selects its sub-categories too. Use the arrow to pick them one by one.", "services": "Additional services" }, "contact": { diff --git a/src/pages/administrator/AdminCategoriesPage.test.tsx b/src/pages/administrator/AdminCategoriesPage.test.tsx index e51016bf..3d7a6d9f 100644 --- a/src/pages/administrator/AdminCategoriesPage.test.tsx +++ b/src/pages/administrator/AdminCategoriesPage.test.tsx @@ -109,4 +109,33 @@ describe('AdminCategoriesPage', () => { }) ); }); + + it('moves a category under a main category, one level deep', async () => { + render(); + fireEvent.click(within(row('Sonstiges')).getByRole('button', { name: 'Bearbeiten' })); + // The hidden native select of the dialog: only main categories to choose from + const parent = document.querySelector('select') as HTMLSelectElement; + const options = [...parent.options].map((option) => option.value); + expect(options).toEqual(['none', 'bikes']); + fireEvent.change(parent, { target: { value: 'bikes' } }); + // Without fields of its own it takes those of the main category + expect(screen.getByText(/Zusatzfelder mit diesem Namen: Rahmennummer/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.updateCategory']).toHaveBeenCalledWith({ + categoryId: 'misc', + label: 'Sonstiges', + translations: { en: undefined }, + parentCategory: 'bikes', + }) + ); + }); + + it('keeps a category with sub-categories on top', () => { + vi.mocked(useQuery).mockReturnValue([{ ...bikes, childCount: 1 }, kids, misc] as never); + render(); + fireEvent.click(within(row('Fahrräder')).getByRole('button', { name: 'Bearbeiten' })); + expect(screen.getByText(/bleibt deshalb Hauptkategorie/)).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Hauptkategorie' })).toBeDisabled(); + }); }); diff --git a/src/pages/administrator/AdminCategoriesPage.tsx b/src/pages/administrator/AdminCategoriesPage.tsx index a0e6e2e9..a40f13d9 100644 --- a/src/pages/administrator/AdminCategoriesPage.tsx +++ b/src/pages/administrator/AdminCategoriesPage.tsx @@ -15,6 +15,13 @@ import { import { EmptyState } from '../../components/ui/empty-state'; import { Input } from '../../components/ui/input'; import { Label } from '../../components/ui/label'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '../../components/ui/select'; import { TableRowsSkeleton } from '../../components/ui/loading'; import { PageHeader } from '../../components/ui/page-header'; import { @@ -28,7 +35,7 @@ import { 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 type { FunctionReturnType, Id } from '../../lib/api/types'; import { getUserFacingErrorMessage } from '../../lib/errors'; import { getCategoryFields, @@ -37,6 +44,9 @@ import { } from '../../shared/categoryFields'; type AdminCategory = FunctionReturnType[number]; +/** Value of the parent select for a main category */ +const NO_PARENT = 'none'; + /** What the dialog works on: a category, or null for a new one. */ type Editing = { category: AdminCategory | null }; @@ -77,17 +87,23 @@ function CategoryDialog({ const update = useMutation(api.categories.updateCategory); const [label, setLabel] = useState(category?.label ?? ''); const [nameEn, setNameEn] = useState(category?.translations.en ?? ''); + const [parent, setParent] = useState(category?.parentCategory ?? NO_PARENT); + // One level: only main categories can take sub-categories, and one with its own stays on top + const mainCategories = categories.filter( + (other) => !other.parentCategory && other._id !== category?._id + ); + const hasChildren = (category?.childCount ?? 0) > 0; const [saving, setSaving] = useState(false); const name = label.trim(); - const fieldsFor = (candidate: string) => + const fieldsFor = (candidate: string, parentId: string | undefined) => getFieldsForLabel(candidate) ?? - (category?.parentCategory ? getCategoryFields(category.parentCategory, categories) : []); - const fields = fieldNames(fieldsFor(name)); + (parentId && parentId !== NO_PARENT ? getCategoryFields(parentId, categories) : []); + const fields = fieldNames(fieldsFor(name, parent)); const fieldsChange = !!category && (category.productCount > 0 || category.eventCount > 0) && - fields.join() !== fieldNames(fieldsFor(category.label)).join(); + fields.join() !== fieldNames(fieldsFor(category.label, category.parentCategory)).join(); const submit = async (event: FormEvent) => { event.preventDefault(); @@ -101,8 +117,12 @@ function CategoryDialog({ 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 }); + const parentCategory = parent === NO_PARENT ? undefined : (parent as Id<'categories'>); + if (category) { + await update({ categoryId: category._id, label: name, translations, parentCategory }); + } else { + await create({ label: name, translations, parentCategory }); + } toast.success(t('categories.saved')); onClose(); } catch (error) { @@ -141,6 +161,25 @@ function CategoryDialog({

{t('categories.fieldsChange')}

)} +
+ + +

+ {t(hasChildren ? 'categories.parentLocked' : 'categories.parentHint')} +

+
+ ({ _id: id, label, parentCategory, translations: {} }) as unknown as Doc<'categories'>; +const list = [ + category('bikes', 'Fahrräder'), + category('cargo', 'Lastenräder', 'bikes'), + category('trailers', 'Fahrradanhänger', 'bikes'), + category('misc', 'Sonstiges'), +]; + +let chosen: string[] = []; +function Form({ categories = [] as string[] }) { + const methods = useForm({ defaultValues: { categories, services: [] } }); + chosen = methods.watch('categories'); + return ( + + + + ); +} + +describe('EditEventCategories', () => { + it('shows main categories and their sub-categories only when opened', () => { + render(
); + expect(screen.getByText('Fahrräder')).toBeInTheDocument(); + expect(screen.getByText('0/2')).toBeInTheDocument(); + expect(screen.queryByText('Lastenräder')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })); + expect(screen.getByText('Lastenräder')).toBeInTheDocument(); + }); + + it('a main category comes and goes with its sub-categories', () => { + render(); + fireEvent.click(screen.getByText('Fahrräder')); + expect(chosen).toEqual(['bikes', 'cargo', 'trailers']); + expect(screen.getByText('2/2')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })); + fireEvent.click(screen.getByText('Fahrradanhänger')); + expect(chosen).toEqual(['bikes', 'cargo']); + + // Not all chosen: a click chooses the rest, the next one clears the group + const badge = screen.getByText('1/2').parentElement as HTMLElement; + fireEvent.click(within(badge).getByText('Fahrräder')); + expect(chosen).toEqual(['bikes', 'cargo', 'trailers']); + fireEvent.click(within(badge).getByText('Fahrräder')); + expect(chosen).toEqual([]); + + fireEvent.click(screen.getByText('Sonstiges')); + expect(chosen).toEqual(['misc']); + }); +}); diff --git a/src/pages/organizer/events/components/EditEventCategories.tsx b/src/pages/organizer/events/components/EditEventCategories.tsx index 1d9b0bf1..f0320e3f 100644 --- a/src/pages/organizer/events/components/EditEventCategories.tsx +++ b/src/pages/organizer/events/components/EditEventCategories.tsx @@ -5,7 +5,10 @@ import { Label } from '../../../../components/ui/label'; import { Badge } from '../../../../components/ui/badge'; import { EVENT_SERVICES } from '../../../../shared/constants'; import type { Doc } from '../../../../lib/api/types'; -import { useEffect } from 'react'; +import { useEffect, useState } from 'react'; +import { ChevronDown } from 'lucide-react'; +import { groupCategories } from '../../../../shared/categoryTree'; +import { cn } from '../../../../lib/utils'; import { useTranslation } from 'react-i18next'; import { serviceLabel } from '../../../../i18n/services'; import { categoryName } from '../../../../i18n/categories'; @@ -31,15 +34,32 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { register('services'); }, [register]); + const [expanded, setExpanded] = useState([]); + const groups = groupCategories(categoryList.map((cat) => ({ ...cat, _id: String(cat._id) }))); + + const choose = (current: string[]) => + setValue('categories', current, { shouldValidate: true, shouldDirty: true, shouldTouch: true }); + const toggleCategory = (catId: string) => { const id = String(catId); - const current = categories.includes(id) - ? categories.filter((c: string) => c !== id) - : [...categories, id]; + choose(categories.includes(id) ? categories.filter((c) => c !== id) : [...categories, id]); + }; - setValue('categories', current, { shouldValidate: true, shouldDirty: true, shouldTouch: true }); + /** A main category comes with its sub-categories, and goes with them. */ + const toggleGroup = (ids: string[]) => { + const all = ids.every((id) => categories.includes(id)); + choose( + all + ? categories.filter((c) => !ids.includes(c)) + : [...categories, ...ids.filter((id) => !categories.includes(id))] + ); }; + const toggleExpanded = (id: string) => + setExpanded((current) => + current.includes(id) ? current.filter((c) => c !== id) : [...current, id] + ); + const toggleService = (svc: string) => { const current = services.includes(svc) ? services.filter((s: string) => s !== svc) @@ -52,20 +72,67 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) {
- {categoryList.map((cat) => { - const catId = String(cat._id); + {groups.map(({ category, children }) => { + const id = category._id; + if (children.length === 0) { + return ( + toggleCategory(id)} + > + {categoryName(category)} + + ); + } + const childIds = children.map((child) => child._id); + const chosenChildren = childIds.filter((c) => categories.includes(c)).length; + const isOpen = expanded.includes(id); return ( - toggleCategory(catId)} - > - {categoryName(cat)} - +
+ + toggleGroup([id, ...childIds])} + > + {categoryName(category)} + + {chosenChildren}/{childIds.length} + + + + + {isOpen && ( +
+ {children.map((child) => ( + toggleCategory(child._id)} + > + {categoryName(child)} + + ))} +
+ )} +
); })}
+

{t('categories.groupHint')}

{errors.categories && {errors.categories.message as string}}
diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index 9e20e23a..00c1d1b9 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -48,7 +48,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'; +import { eventCategoryNames } from '../../../../../i18n/categories'; /* * Previews of the creation wizard: next to each step they show what buyers and sellers @@ -409,9 +409,10 @@ export function ItemsPreview({ type }: { type?: EventType }) { const features = values.features ?? {}; const { kind, items } = useExamples(type); const categoryList = useQuery(api.categories.getAllCategories); - const chosen = (categoryList ?? []) - .filter((category) => values.categories?.includes(category._id as string)) - .map((category) => categoryName(category)); + const chosenIds = (categoryList ?? []) + .map((category) => category._id as string) + .filter((id) => values.categories?.includes(id)); + const chosen = eventCategoryNames(chosenIds, categoryList) ?? []; 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 dd2e2c90..e22bb2f4 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -10,7 +10,7 @@ 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 { eventCategoryNames } from '../../../../../i18n/categories'; import { api } from '../../../../../lib/api/functions'; import { useQuery } from '../../../../../lib/api/react'; import { formatEventPlace } from '../../../../../shared/eventJsonLd'; @@ -120,11 +120,13 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) {
- {(categoryNames(event.categories, categoryList) ?? event.categoryLabels).map((label) => ( - - {label} - - ))} + {(eventCategoryNames(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 32830aec..951e3c42 100644 --- a/src/pages/public/events/PublicEventPage.tsx +++ b/src/pages/public/events/PublicEventPage.tsx @@ -35,7 +35,7 @@ import { useInstanceConfig } from '../../../hooks/useInstanceConfig'; import { SellerBroadcasts } from '../../../components/broadcasts/SellerBroadcasts'; import { MyRejections } from '../../../components/participation/MyRejections'; import { useTranslation } from 'react-i18next'; -import { categoryNames } from '../../../i18n/categories'; +import { eventCategoryNames } from '../../../i18n/categories'; import { serviceLabel } from '../../../i18n/services'; import { useNowPassing } from '../../../hooks/useNowPassing'; import { registrationTimes } from '../../../shared/eventFeatures'; @@ -381,7 +381,7 @@ export function PublicEventLanding({ eventId, onNavigate }: PublicEventLandingPr

{t('page.categories')}

- {(categoryNames(event.categories, categoryList) ?? event.categoryLabels)?.map( + {(eventCategoryNames(event.categories, categoryList) ?? event.categoryLabels)?.map( (category: string) => ( diff --git a/src/pages/public/events/PublicEventProductsPage.tsx b/src/pages/public/events/PublicEventProductsPage.tsx index 0ec9836b..0fdf7c81 100644 --- a/src/pages/public/events/PublicEventProductsPage.tsx +++ b/src/pages/public/events/PublicEventProductsPage.tsx @@ -29,6 +29,7 @@ import { Footer } from '../../../components/layout/Footer'; import { useInstanceConfig } from '../../../hooks/useInstanceConfig'; import { useTranslation } from 'react-i18next'; import { categoryNames } from '../../../i18n/categories'; +import { withSubcategories } from '../../../shared/categoryTree'; import { autoViewMode, loadViewMode, @@ -114,9 +115,11 @@ export function PublicEventProductsPage() { const productList = (products as ProductWithDiscount[] | undefined) ?? []; const isRunning = !!event && isEventRunning(event, now); + const inCategory = + filterCategory === 'all' ? undefined : withSubcategories(filterCategory, categoryList); let result = productList.filter((p: ProductWithDiscount) => { const matchesSearch = p.title.toLowerCase().includes(searchTerm.toLowerCase()); - const matchesCategory = filterCategory === 'all' || p.productCategory === filterCategory; + const matchesCategory = !inCategory || inCategory.has(p.productCategory); const matchesStatus = matchesPublicStatusFilter(p, filterStatus, isRunning); const matchesMinPrice = minPrice === '' || p.price >= parseFloat(minPrice); const matchesMaxPrice = maxPrice === '' || p.price <= parseFloat(maxPrice); diff --git a/src/pages/seller/products/MyProductsPage.tsx b/src/pages/seller/products/MyProductsPage.tsx index 91462c3b..95b63ce9 100644 --- a/src/pages/seller/products/MyProductsPage.tsx +++ b/src/pages/seller/products/MyProductsPage.tsx @@ -431,6 +431,7 @@ export function MyProductsPage() { sortBy, minPrice, maxPrice, + categories: categoryList, }) : []; diff --git a/src/pages/seller/products/components/MyProductBasicInfo.tsx b/src/pages/seller/products/components/MyProductBasicInfo.tsx index ec9928cf..94f6dd10 100644 --- a/src/pages/seller/products/components/MyProductBasicInfo.tsx +++ b/src/pages/seller/products/components/MyProductBasicInfo.tsx @@ -1,13 +1,11 @@ import { FieldError } from '../../../../components/ui/field-error'; 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'; import { Select, SelectContent, - SelectItem, SelectTrigger, SelectValue, } from '../../../../components/ui/select'; @@ -15,9 +13,9 @@ import { CONDITION_OPTIONS } from '../../../../constants/records'; import { PRODUCT_CONDITIONS } from '../../../../shared/constants'; import { api } from '../../../../lib/api/functions'; import { useQuery } from '../../../../lib/api/react'; -import type { Doc } from '../../../../lib/api/types'; import { cn } from '../../../../lib/utils'; import { MyProductCategoryFields, MyProductNegotiation } from './MyProductExtras'; +import { CategorySelectItems } from '../../../../components/products/CategorySelectItems'; import { useTranslation } from 'react-i18next'; import { FormSkeleton, Loading } from '../../../../components/ui/loading'; import type { ReactNode } from 'react'; @@ -116,11 +114,7 @@ export function MyProductBasicInfo({ - {categoryList.map((c: Doc<'categories'>) => ( - - {categoryName(c)} - - ))} + {errors.categoryId && {errors.categoryId.message as string}} diff --git a/src/shared/categoryFields.ts b/src/shared/categoryFields.ts index 2e9f13fa..8b3638da 100644 --- a/src/shared/categoryFields.ts +++ b/src/shared/categoryFields.ts @@ -140,10 +140,20 @@ export const REQUIRABLE_FIELDS: CategoryField[] = (() => { export const REQUIRABLE_FIELD_KEYS = REQUIRABLE_FIELDS.map((field) => field.key); -/** Fields for a single category label, without looking at parent categories. */ +/** + * Fields for a single category label, without looking at parent categories; undefined + * when no rule speaks about it. A label a rule excludes on purpose ("Fahrradanhänger") has + * no fields: as a sub-category of "Fahrräder" it must not inherit the frame number. + */ export function getFieldsForLabel(label: string): CategoryField[] | undefined { const name = label.trim(); - return FIELD_RULES.find((rule) => rule.match.test(name) && !rule.exclude?.test(name))?.fields; + let excluded = false; + for (const rule of FIELD_RULES) { + if (!rule.match.test(name)) continue; + if (!rule.exclude?.test(name)) return rule.fields; + excluded = true; + } + return excluded ? [] : undefined; } type CategoryLike = { _id: string; label: string; parentCategory?: string }; diff --git a/src/shared/categoryTree.test.ts b/src/shared/categoryTree.test.ts new file mode 100644 index 00000000..aa0e41ba --- /dev/null +++ b/src/shared/categoryTree.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { collapseSubcategories, groupCategories, withSubcategories } from './categoryTree'; + +const categories = [ + { _id: 'clothes' }, + { _id: 'bikes' }, + { _id: 'cargo', parentCategory: 'bikes' }, + { _id: 'trailers', parentCategory: 'bikes' }, + { _id: 'bells', parentCategory: 'trailers' }, + { _id: 'orphan', parentCategory: 'gone' }, +]; + +describe('category tree', () => { + it('groups sub-categories under their main category, one level deep', () => { + const groups = groupCategories(categories).map(({ category, children }) => [ + category._id, + children.map((child) => child._id), + ]); + // A deeper one and one with a missing parent are shown on top instead of getting lost + expect(groups).toEqual([ + ['clothes', []], + ['bikes', ['cargo', 'trailers']], + ['bells', []], + ['orphan', []], + ]); + }); + + it('a filter on a main category finds its sub-categories', () => { + expect([...withSubcategories('bikes', categories)]).toEqual(['bikes', 'cargo', 'trailers']); + expect([...withSubcategories('cargo', categories)]).toEqual(['cargo']); + expect([...withSubcategories('bikes', undefined)]).toEqual(['bikes']); + }); + + it('a main category with all its sub-categories stands for them', () => { + expect(collapseSubcategories(['clothes', 'bikes', 'cargo', 'trailers'], categories)).toEqual([ + 'clothes', + 'bikes', + ]); + // Not all chosen: every name stays + expect(collapseSubcategories(['bikes', 'cargo'], categories)).toEqual(['bikes', 'cargo']); + expect(collapseSubcategories(['cargo', 'trailers'], categories)).toEqual(['cargo', 'trailers']); + }); +}); diff --git a/src/shared/categoryTree.ts b/src/shared/categoryTree.ts new file mode 100644 index 00000000..c340605b --- /dev/null +++ b/src/shared/categoryTree.ts @@ -0,0 +1,64 @@ +/** + * Main categories with one level of sub-categories (e.g. "Fahrräder" with "Lastenräder"), + * so the lists stay short. Pure helpers only, so the frontend can import this file as well. + */ + +type TreeCategory = { _id: string; parentCategory?: string }; + +export interface CategoryGroup { + category: T; + children: T[]; +} + +/** + * Main categories in the given order, each with its sub-categories. A category whose main + * category is missing, or that hangs deeper, counts as a main category itself. + */ +export function groupCategories( + categories: readonly T[] +): CategoryGroup[] { + const byId = new Map(categories.map((category) => [category._id, category])); + const isMain = (category: T) => { + const parent = category.parentCategory ? byId.get(category.parentCategory) : undefined; + return !parent || !!parent.parentCategory || parent._id === category._id; + }; + return categories.filter(isMain).map((category) => ({ + category, + children: categories.filter((child) => !isMain(child) && child.parentCategory === category._id), + })); +} + +/** The category and its sub-categories, e.g. for a filter on a main category. */ +export function withSubcategories( + categoryId: string, + categories: readonly TreeCategory[] | undefined +): Set { + const ids = new Set([categoryId]); + for (const category of categories ?? []) { + if (category.parentCategory === categoryId) ids.add(category._id); + } + return ids; +} + +/** + * The chosen categories for display: a main category that comes with all its + * sub-categories stands for them, so "Fahrräder" replaces seven names. + */ +export function collapseSubcategories( + ids: readonly string[], + categories: readonly TreeCategory[] | undefined +): string[] { + if (!categories) return [...ids]; + const chosen = new Set(ids); + const covered = new Set(); + for (const { category, children } of groupCategories(categories)) { + if ( + children.length > 0 && + chosen.has(category._id) && + children.every((child) => chosen.has(child._id)) + ) { + for (const child of children) covered.add(child._id); + } + } + return ids.filter((id) => !covered.has(id)); +} diff --git a/src/shared/eventFeatures.test.ts b/src/shared/eventFeatures.test.ts index 7d97475a..fb5c3ec8 100644 --- a/src/shared/eventFeatures.test.ts +++ b/src/shared/eventFeatures.test.ts @@ -54,7 +54,25 @@ describe('category fields by keyword', () => { 'Fahrradanhänger', 'Fahrrad-Kindersitze', ])('"%s" gets no bike fields', (label) => { - expect(keys(label)).toBeUndefined(); + expect(keys(label) ?? []).toEqual([]); + }); + + test('excluded on purpose means no fields, also below "Fahrräder"', () => { + expect(keys('Fahrradanhänger')).toEqual([]); + expect(keys('Radio & HiFi')).toBeUndefined(); + const categories = [ + { _id: 'bikes', label: 'Fahrräder' }, + { _id: 'trailers', label: 'Fahrradanhänger', parentCategory: 'bikes' }, + { _id: 'clothes', label: 'Fahrradbekleidung', parentCategory: 'bikes' }, + { _id: 'kids', label: 'Für Kinder', parentCategory: 'bikes' }, + ]; + expect(getCategoryFields('trailers', categories)).toEqual([]); + expect(getCategoryFields('clothes', categories).map((f) => f.key)).toEqual([ + 'size', + 'brand', + 'color', + ]); + expect(getCategoryFields('kids', categories).map((f) => f.key)).toEqual(BIKE_KEYS); }); test('cycling clothes count as clothing, sports shoes as shoes', () => { From afc7ad74890623d87971d2d04fffd68b9f75277c Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 14:22:36 +0100 Subject: [PATCH 3/6] feat(categories): sub-categories for every main category, admins pick extra fields (#300) - Default tree with 12 main and 60 sub-categories, e.g. baby, children's, women's and men's clothes, ski and ball sports, phones and consoles, novels and children's books, Lego and board games, prams; migration 0032 adds them where the default categories are in use - Admins choose the extra fields of a category from a fixed list (frame number, frame and wheel size, brand, color, one kind of size, model) or leave them to the name as before; stored in categories.fields (0033), checked by the backend (category.unknownField, category.oneSize) and used everywhere fields are resolved, sub-categories inherit them - Kinds of bazaars preselect a matching main category with its sub-categories, minus what they exclude (women's clothes at a children's bazaar, prams at a bike sale) Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0032_more_categories.sql | 97 ++++++++--- backend/migrations/0033_category_fields.sql | 3 + backend/src/modules/categories.rs | 85 +++++++++- backend/src/modules/category_fields.rs | 144 ++++++++++++++-- backend/src/modules/event_products.rs | 4 +- backend/src/modules/products.rs | 10 +- backend/src/modules/purchases.rs | 6 +- backend/src/modules/seller_records.rs | 2 +- backend/tests/api/categories.rs | 78 ++++++++- src/lib/api/types.ts | 5 + src/lib/eventTypes.test.ts | 33 +++- src/lib/eventTypes.ts | 35 +++- src/locales/de/admin.json | 19 ++- src/locales/de/errors.json | 2 + src/locales/en/admin.json | 19 ++- src/locales/en/errors.json | 2 + .../AdminCategoriesPage.test.tsx | 44 ++++- .../administrator/AdminCategoriesPage.tsx | 88 +++++++--- src/pages/organizer/events/EditEventForm.tsx | 8 +- src/shared/categoryFields.ts | 158 +++++++++++------- 20 files changed, 687 insertions(+), 155 deletions(-) create mode 100644 backend/migrations/0033_category_fields.sql diff --git a/backend/migrations/0032_more_categories.sql b/backend/migrations/0032_more_categories.sql index 5742702b..05623aa5 100644 --- a/backend/migrations/0032_more_categories.sql +++ b/backend/migrations/0032_more_categories.sql @@ -1,31 +1,82 @@ --- Categories for bike sales and children's bazaars (#300), grouped under main categories so --- the lists stay short. Same tree and order as DEFAULT_CATEGORIES in src/modules/categories.rs. +-- Sub-categories for every main category, among them bikes and children's vehicles for bike +-- sales and children's bazaars (#300), so the lists stay short. Same tree and order as +-- DEFAULT_CATEGORIES in src/modules/categories.rs. -- Only for instances that use the default categories: an instance with its own list keeps -- it, and an empty one gets the whole tree when it is seeded. CREATE TEMPORARY TABLE default_categories (n int, de text, en text, parent text, added bool) ON COMMIT DROP; INSERT INTO default_categories VALUES (0, 'Kleidung', 'Clothing', NULL, false), - (1, 'Schuhe', 'Shoes', NULL, false), - (2, 'Sport', 'Sports', NULL, false), - (3, 'Fahrräder', 'Bikes', NULL, false), - (4, 'Kinderfahrräder', 'Children''s bikes', 'Fahrräder', true), - (5, 'Lastenräder', 'Cargo bikes', 'Fahrräder', true), - (6, 'E-Bikes & Pedelecs', 'E-bikes', 'Fahrräder', true), - (7, 'Fahrradanhänger', 'Bike trailers', 'Fahrräder', true), - (8, 'Fahrrad-Kindersitze', 'Child bike seats', 'Fahrräder', true), - (9, 'Fahrradzubehör', 'Bike accessories', 'Fahrräder', true), - (10, 'Kinderfahrzeuge', 'Children''s vehicles', NULL, true), - (11, 'Laufräder', 'Balance bikes', 'Kinderfahrzeuge', true), - (12, 'Roller & Scooter', 'Scooters', 'Kinderfahrzeuge', true), - (13, 'Einräder', 'Unicycles', 'Kinderfahrzeuge', true), - (14, 'Bobbycars & Rutschfahrzeuge', 'Ride-on toys', 'Kinderfahrzeuge', true), - (15, 'Elektronik', 'Electronics', NULL, false), - (16, 'Bücher', 'Books', NULL, false), - (17, 'Spielzeug', 'Toys', NULL, false), - (18, 'Möbel', 'Furniture', NULL, false), - (19, 'Haushalt', 'Household', NULL, false), - (20, 'Accessoires', 'Accessories', NULL, false), - (21, 'Sonstiges', 'Other', NULL, false); + (1, 'Babykleidung', 'Baby clothes', 'Kleidung', true), + (2, 'Kinderkleidung', 'Children''s clothes', 'Kleidung', true), + (3, 'Damenkleidung', 'Women''s clothes', 'Kleidung', true), + (4, 'Herrenkleidung', 'Men''s clothes', 'Kleidung', true), + (5, 'Umstandsmode', 'Maternity wear', 'Kleidung', true), + (6, 'Schuhe', 'Shoes', NULL, false), + (7, 'Kinderschuhe', 'Children''s shoes', 'Schuhe', true), + (8, 'Damenschuhe', 'Women''s shoes', 'Schuhe', true), + (9, 'Herrenschuhe', 'Men''s shoes', 'Schuhe', true), + (10, 'Sportschuhe', 'Sports shoes', 'Schuhe', true), + (11, 'Sport', 'Sports', NULL, false), + (12, 'Ski & Snowboard', 'Skis & snowboards', 'Sport', true), + (13, 'Skischuhe', 'Ski boots', 'Sport', true), + (14, 'Sportbekleidung', 'Sportswear', 'Sport', true), + (15, 'Helme & Protektoren', 'Helmets & protectors', 'Sport', true), + (16, 'Ballsport', 'Ball sports', 'Sport', true), + (17, 'Fitness', 'Fitness', 'Sport', true), + (18, 'Camping & Outdoor', 'Camping & outdoor', 'Sport', true), + (19, 'Fahrräder', 'Bikes', NULL, false), + (20, 'Kinderfahrräder', 'Children''s bikes', 'Fahrräder', true), + (21, 'Lastenräder', 'Cargo bikes', 'Fahrräder', true), + (22, 'E-Bikes & Pedelecs', 'E-bikes', 'Fahrräder', true), + (23, 'Fahrradanhänger', 'Bike trailers', 'Fahrräder', true), + (24, 'Fahrrad-Kindersitze', 'Child bike seats', 'Fahrräder', true), + (25, 'Fahrradzubehör', 'Bike accessories', 'Fahrräder', true), + (26, 'Kinderfahrzeuge', 'Children''s vehicles', NULL, true), + (27, 'Laufräder', 'Balance bikes', 'Kinderfahrzeuge', true), + (28, 'Roller & Scooter', 'Scooters', 'Kinderfahrzeuge', true), + (29, 'Einräder', 'Unicycles', 'Kinderfahrzeuge', true), + (30, 'Bobbycars & Rutschfahrzeuge', 'Ride-on toys', 'Kinderfahrzeuge', true), + (31, 'Kinderwagen & Buggys', 'Prams & buggies', 'Kinderfahrzeuge', true), + (32, 'Elektronik', 'Electronics', NULL, false), + (33, 'Handys & Smartphones', 'Mobile phones', 'Elektronik', true), + (34, 'Computer & Tablets', 'Computers & tablets', 'Elektronik', true), + (35, 'Foto & Kamera', 'Photo & camera', 'Elektronik', true), + (36, 'Konsolen & Videospiele', 'Consoles & video games', 'Elektronik', true), + (37, 'Audio & HiFi', 'Audio & hi-fi', 'Elektronik', true), + (38, 'Bücher', 'Books', NULL, false), + (39, 'Kinderbücher', 'Children''s books', 'Bücher', true), + (40, 'Romane', 'Novels', 'Bücher', true), + (41, 'Sachbücher', 'Non-fiction', 'Bücher', true), + (42, 'Kochbücher', 'Cookbooks', 'Bücher', true), + (43, 'Comics', 'Comics', 'Bücher', true), + (44, 'Spielzeug', 'Toys', NULL, false), + (45, 'Babyspielzeug', 'Baby toys', 'Spielzeug', true), + (46, 'Puppen & Plüsch', 'Dolls & plush', 'Spielzeug', true), + (47, 'Lego & Bausteine', 'Lego & building blocks', 'Spielzeug', true), + (48, 'Brett- & Kartenspiele', 'Board & card games', 'Spielzeug', true), + (49, 'Outdoor-Spielzeug', 'Outdoor toys', 'Spielzeug', true), + (50, 'Möbel', 'Furniture', NULL, false), + (51, 'Kindermöbel', 'Children''s furniture', 'Möbel', true), + (52, 'Wohnzimmermöbel', 'Living room', 'Möbel', true), + (53, 'Schlafzimmermöbel', 'Bedroom', 'Möbel', true), + (54, 'Büromöbel', 'Office furniture', 'Möbel', true), + (55, 'Gartenmöbel', 'Garden furniture', 'Möbel', true), + (56, 'Haushalt', 'Household', NULL, false), + (57, 'Küche & Kochen', 'Kitchen & cooking', 'Haushalt', true), + (58, 'Dekoration', 'Decoration', 'Haushalt', true), + (59, 'Heimtextilien', 'Home textiles', 'Haushalt', true), + (60, 'Werkzeug & Garten', 'Tools & garden', 'Haushalt', true), + (61, 'Accessoires', 'Accessories', NULL, false), + (62, 'Taschen & Rucksäcke', 'Bags & backpacks', 'Accessoires', true), + (63, 'Schmuck & Uhren', 'Jewellery & watches', 'Accessoires', true), + (64, 'Mützen & Schals', 'Hats & scarves', 'Accessoires', true), + (65, 'Sonnenbrillen', 'Sunglasses', 'Accessoires', true), + (66, 'Gürtel', 'Belts', 'Accessoires', true), + (67, 'Sonstiges', 'Other', NULL, false), + (68, 'Musikinstrumente', 'Musical instruments', 'Sonstiges', true), + (69, 'Filme & Musik', 'Films & music', 'Sonstiges', true), + (70, 'Basteln & Handarbeit', 'Crafts & needlework', 'Sonstiges', true), + (71, 'Sammeln', 'Collectibles', 'Sonstiges', true); -- Only the added ones: a default category an admin deleted stays deleted INSERT INTO categories (label, translations) diff --git a/backend/migrations/0033_category_fields.sql b/backend/migrations/0033_category_fields.sql new file mode 100644 index 00000000..84f5d950 --- /dev/null +++ b/backend/migrations/0033_category_fields.sql @@ -0,0 +1,3 @@ +-- Extra item fields an admin picked for a category (#300), e.g. {frameNumber,color}; the ids +-- of category_fields::SELECTABLE. NULL: the fields follow the name, as before. +ALTER TABLE categories ADD COLUMN fields text[]; diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index 6f69c87e..e46872fc 100644 --- a/backend/src/modules/categories.rs +++ b/backend/src/modules/categories.rs @@ -9,6 +9,7 @@ use sqlx::types::Json; use uuid::Uuid; use super::access::require_admin; +use super::category_fields; use crate::error::{AppError, AppResult}; use crate::realtime::Topic; use crate::register; @@ -64,6 +65,8 @@ pub struct Category { #[serde(with = "ms")] pub updated_at: DateTime, pub translations: Json, + /// Extra fields an admin picked (category_fields::SELECTABLE); unset: by the name + pub fields: Option>, } #[derive(Deserialize)] @@ -72,6 +75,14 @@ struct CreateArgs { label: String, parent_category: Option, translations: Option, + fields: Option>, +} + +/// The extra fields an admin picked, checked; None leaves them to the name. +fn checked_fields(fields: Option>) -> AppResult>> { + fields + .map(|ids| category_fields::checked_selection(&ids).map_err(AppError::bad_request)) + .transpose() } fn clean_label(label: &str) -> AppResult { @@ -93,6 +104,7 @@ async fn find_by_label(ctx: &mut Ctx, label: &str) -> sqlx::Result> async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult { require_admin(ctx).await?; let label = clean_label(&args.label)?; + let fields = checked_fields(args.fields)?; if let Some(existing) = find_by_label(ctx, &label).await? { return Ok(existing); } @@ -101,11 +113,13 @@ async fn create_category(ctx: &mut Ctx, args: CreateArgs) -> AppResult { check_parent(ctx, None, parent).await?; } let id = sqlx::query_scalar( - "INSERT INTO categories (label, parent_id, translations) VALUES ($1, $2, $3) RETURNING id", + "INSERT INTO categories (label, parent_id, translations, fields) VALUES ($1, $2, $3, $4) + RETURNING id", ) .bind(&label) .bind(parent) .bind(Json(args.translations.unwrap_or_default().trimmed())) + .bind(fields) .fetch_one(ctx.conn()) .await?; ctx.touch(TOPIC); @@ -121,6 +135,9 @@ struct UpdateArgs { /// The main category; none makes it a main category itself #[serde(default)] parent_category: Option, + /// The extra fields; none leaves them to the name + #[serde(default)] + fields: Option>, } /// Categories have one level of sub-categories, so lists stay short and grouped: the parent @@ -154,6 +171,7 @@ async fn check_parent(ctx: &mut Ctx, category: Option, parent: Uuid) -> Ap async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { require_admin(ctx).await?; let label = clean_label(&args.label)?; + let fields = checked_fields(args.fields)?; let taken: bool = sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM categories WHERE lower(label) = lower($1) AND id <> $2)", ) @@ -169,13 +187,15 @@ async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { check_parent(ctx, Some(args.category_id.0), parent).await?; } let updated = sqlx::query( - "UPDATE categories SET label = $2, translations = $3, parent_id = $4, updated_at = now() + "UPDATE categories SET label = $2, translations = $3, parent_id = $4, fields = $5, + updated_at = now() WHERE id = $1", ) .bind(args.category_id.0) .bind(&label) .bind(Json(args.translations.trimmed())) .bind(parent) + .bind(fields) .execute(ctx.conn()) .await?; if updated.rows_affected() == 0 { @@ -239,7 +259,7 @@ async fn list_for_admin(ctx: &mut Ctx, _: NoArgs) -> AppResult( async fn get_all_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult> { ctx.read(TOPIC); Ok(sqlx::query_as( - "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations + "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations, c.fields FROM categories c ORDER BY c.created_at", ) .fetch_all(ctx.conn()) @@ -324,10 +344,26 @@ const fn sub(parent: &'static str, label: &'static str, en: &'static str) -> Def /// The default categories, main categories before their sub-categories; adds the missing /// ones, safe to run repeatedly: `bazarpro-backend run categories.seedCategories`. /// Same tree as migration 0032. -pub const DEFAULT_CATEGORIES: [DefaultCategory; 22] = [ +pub const DEFAULT_CATEGORIES: [DefaultCategory; 72] = [ main("Kleidung", "Clothing"), + sub("Kleidung", "Babykleidung", "Baby clothes"), + sub("Kleidung", "Kinderkleidung", "Children's clothes"), + sub("Kleidung", "Damenkleidung", "Women's clothes"), + sub("Kleidung", "Herrenkleidung", "Men's clothes"), + sub("Kleidung", "Umstandsmode", "Maternity wear"), main("Schuhe", "Shoes"), + sub("Schuhe", "Kinderschuhe", "Children's shoes"), + sub("Schuhe", "Damenschuhe", "Women's shoes"), + sub("Schuhe", "Herrenschuhe", "Men's shoes"), + sub("Schuhe", "Sportschuhe", "Sports shoes"), main("Sport", "Sports"), + sub("Sport", "Ski & Snowboard", "Skis & snowboards"), + sub("Sport", "Skischuhe", "Ski boots"), + sub("Sport", "Sportbekleidung", "Sportswear"), + sub("Sport", "Helme & Protektoren", "Helmets & protectors"), + sub("Sport", "Ballsport", "Ball sports"), + sub("Sport", "Fitness", "Fitness"), + sub("Sport", "Camping & Outdoor", "Camping & outdoor"), main("Fahrräder", "Bikes"), sub("Fahrräder", "Kinderfahrräder", "Children's bikes"), sub("Fahrräder", "Lastenräder", "Cargo bikes"), @@ -335,7 +371,6 @@ pub const DEFAULT_CATEGORIES: [DefaultCategory; 22] = [ sub("Fahrräder", "Fahrradanhänger", "Bike trailers"), sub("Fahrräder", "Fahrrad-Kindersitze", "Child bike seats"), sub("Fahrräder", "Fahrradzubehör", "Bike accessories"), - // Ridden by children, sold at children's bazaars and bike sales (#300) main("Kinderfahrzeuge", "Children's vehicles"), sub("Kinderfahrzeuge", "Laufräder", "Balance bikes"), sub("Kinderfahrzeuge", "Roller & Scooter", "Scooters"), @@ -345,13 +380,51 @@ pub const DEFAULT_CATEGORIES: [DefaultCategory; 22] = [ "Bobbycars & Rutschfahrzeuge", "Ride-on toys", ), + sub("Kinderfahrzeuge", "Kinderwagen & Buggys", "Prams & buggies"), main("Elektronik", "Electronics"), + sub("Elektronik", "Handys & Smartphones", "Mobile phones"), + sub("Elektronik", "Computer & Tablets", "Computers & tablets"), + sub("Elektronik", "Foto & Kamera", "Photo & camera"), + sub( + "Elektronik", + "Konsolen & Videospiele", + "Consoles & video games", + ), + sub("Elektronik", "Audio & HiFi", "Audio & hi-fi"), main("Bücher", "Books"), + sub("Bücher", "Kinderbücher", "Children's books"), + sub("Bücher", "Romane", "Novels"), + sub("Bücher", "Sachbücher", "Non-fiction"), + sub("Bücher", "Kochbücher", "Cookbooks"), + sub("Bücher", "Comics", "Comics"), main("Spielzeug", "Toys"), + sub("Spielzeug", "Babyspielzeug", "Baby toys"), + sub("Spielzeug", "Puppen & Plüsch", "Dolls & plush"), + sub("Spielzeug", "Lego & Bausteine", "Lego & building blocks"), + sub("Spielzeug", "Brett- & Kartenspiele", "Board & card games"), + sub("Spielzeug", "Outdoor-Spielzeug", "Outdoor toys"), main("Möbel", "Furniture"), + sub("Möbel", "Kindermöbel", "Children's furniture"), + sub("Möbel", "Wohnzimmermöbel", "Living room"), + sub("Möbel", "Schlafzimmermöbel", "Bedroom"), + sub("Möbel", "Büromöbel", "Office furniture"), + sub("Möbel", "Gartenmöbel", "Garden furniture"), main("Haushalt", "Household"), + sub("Haushalt", "Küche & Kochen", "Kitchen & cooking"), + sub("Haushalt", "Dekoration", "Decoration"), + sub("Haushalt", "Heimtextilien", "Home textiles"), + sub("Haushalt", "Werkzeug & Garten", "Tools & garden"), main("Accessoires", "Accessories"), + sub("Accessoires", "Taschen & Rucksäcke", "Bags & backpacks"), + sub("Accessoires", "Schmuck & Uhren", "Jewellery & watches"), + sub("Accessoires", "Mützen & Schals", "Hats & scarves"), + sub("Accessoires", "Sonnenbrillen", "Sunglasses"), + sub("Accessoires", "Gürtel", "Belts"), main("Sonstiges", "Other"), + sub("Sonstiges", "Musikinstrumente", "Musical instruments"), + sub("Sonstiges", "Filme & Musik", "Films & music"), + sub("Sonstiges", "Basteln & Handarbeit", "Crafts & needlework"), + sub("Sonstiges", "Sammeln", "Collectibles"), ]; async fn seed_categories(ctx: &mut Ctx, _: NoArgs) -> AppResult<&'static str> { diff --git a/backend/src/modules/category_fields.rs b/backend/src/modules/category_fields.rs index b6791f7c..bf533ad6 100644 --- a/backend/src/modules/category_fields.rs +++ b/backend/src/modules/category_fields.rs @@ -1,5 +1,6 @@ //! Extra item fields per category, e.g. frame number for bikes. -//! Category names are free text, so the fields are matched by keywords. +//! Admins pick them from a fixed list per category; otherwise they follow the name, matched +//! by keywords, since category names are free text. use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::LazyLock; @@ -65,6 +66,42 @@ const ELECTRONICS: &[CategoryField] = &[ field("model", "model", "Modell"), ]; +/// The fields an admin can pick for a category, by `text`; one size at most, since all +/// sizes share the key. Same list as SELECTABLE_FIELDS in src/shared/categoryFields.ts. +pub const SELECTABLE: &[CategoryField] = &[ + field("frameNumber", "frameNumber", "Rahmennummer"), + field("frameSize", "frameSize", "Rahmengröße"), + field("wheelSize", "wheelSize", "Laufradgröße"), + field("brand", "brand", "Marke"), + field("color", "color", "Farbe"), + size("clothingSize", "Größe"), + size("shoeSize", "Größe (EU)"), + size("sportSize", "Größe / Länge"), + field("model", "model", "Modell"), +]; + +fn selectable(id: &str) -> Option { + SELECTABLE.iter().find(|field| field.text == id).copied() +} + +/// The fields an admin picked, in the order of the list; the error code when one is +/// unknown or two share a key (two sizes). +pub fn checked_selection(ids: &[String]) -> Result, &'static str> { + let mut keys = HashSet::new(); + let mut chosen = HashSet::new(); + for id in ids { + let field = selectable(id).ok_or("category.unknownField")?; + if chosen.insert(field.text) && !keys.insert(field.key) { + return Err("category.oneSize"); + } + } + Ok(SELECTABLE + .iter() + .filter(|field| chosen.contains(field.text)) + .map(|field| field.text.to_owned()) + .collect()) +} + struct Rule { matches: Regex, exclude: Option, @@ -113,9 +150,9 @@ static RULES: LazyLock> = LazyLock::new(|| { /// Fields an organizer can make required, one per key. pub fn requirable_fields() -> Vec { let mut seen = HashSet::new(); - RULES + SELECTABLE .iter() - .flat_map(|rule| rule.fields.iter().copied()) + .copied() .filter(|field| seen.insert(field.key)) .collect() } @@ -141,10 +178,13 @@ pub struct CategoryRef { pub id: Uuid, pub label: String, pub parent: Option, + /// Picked by an admin; None: by the name + pub fields: Option>, } -/// Fields of a category; sub-categories without their own set inherit the parent's. -pub fn category_fields(category: Uuid, categories: &[CategoryRef]) -> &'static [CategoryField] { +/// Fields of a category: the ones an admin picked, else those of its name; sub-categories +/// without either inherit the parent's. +pub fn category_fields(category: Uuid, categories: &[CategoryRef]) -> Vec { let by_id: HashMap = categories.iter().map(|c| (c.id, c)).collect(); let mut seen = HashSet::new(); let mut current = by_id.get(&category).copied(); @@ -152,30 +192,44 @@ pub fn category_fields(category: Uuid, categories: &[CategoryRef]) -> &'static [ if !seen.insert(cat.id) { break; } + if let Some(ids) = &cat.fields { + return ids.iter().filter_map(|id| selectable(id)).collect(); + } if let Some(fields) = fields_for_label(&cat.label) { - return fields; + return fields.to_vec(); } current = cat.parent.and_then(|parent| by_id.get(&parent).copied()); } - &[] + Vec::new() } pub async fn load_categories(conn: &mut sqlx::PgConnection) -> sqlx::Result> { - let rows: Vec<(Uuid, String, Option)> = - sqlx::query_as("SELECT id, label, parent_id FROM categories") - .fetch_all(conn) - .await?; + #[derive(sqlx::FromRow)] + struct Row { + id: Uuid, + label: String, + parent_id: Option, + fields: Option>, + } + let rows: Vec = sqlx::query_as("SELECT id, label, parent_id, fields FROM categories") + .fetch_all(conn) + .await?; Ok(rows .into_iter() - .map(|(id, label, parent)| CategoryRef { id, label, parent }) + .map(|row| CategoryRef { + id: row.id, + label: row.label, + parent: row.parent_id, + fields: row.fields, + }) .collect()) } /// The first field of the category whose trimmed value is longer than allowed. -pub fn too_long( - fields: &'static [CategoryField], +pub fn too_long<'a>( + fields: &'a [CategoryField], attributes: Option<&BTreeMap>, -) -> Option<&'static CategoryField> { +) -> Option<&'a CategoryField> { let attributes = attributes?; fields.iter().find(|field| { attributes @@ -307,6 +361,7 @@ mod tests { id: id(c.label), label: c.label.into(), parent: c.parent.map(id), + fields: None, }) .collect(); for category in defaults { @@ -357,11 +412,13 @@ mod tests { id: bikes, label: "Fahrräder".into(), parent: None, + fields: None, }, CategoryRef { id: kids, label: "Für Kinder".into(), parent: Some(bikes), + fields: None, }, ]; assert_eq!(category_fields(kids, &categories).len(), 5); @@ -377,16 +434,19 @@ mod tests { id: bikes, label: "Fahrräder".into(), parent: None, + fields: None, }, CategoryRef { id: trailers, label: "Fahrradanhänger".into(), parent: Some(bikes), + fields: None, }, CategoryRef { id: clothes, label: "Fahrradbekleidung".into(), parent: Some(bikes), + fields: None, }, ]; assert!(category_fields(trailers, &categories).is_empty()); @@ -397,6 +457,60 @@ mod tests { assert_eq!(keys, ["size", "brand", "color"]); } + #[test] + fn admins_pick_fields_that_override_the_name() { + let pick = |ids: &[&str]| { + checked_selection(&ids.iter().map(|id| id.to_string()).collect::>()) + }; + assert_eq!( + pick(&["model", "brand", "brand"]), + Ok(vec!["brand".into(), "model".into()]) + ); + assert_eq!(pick(&["shoeSize", "sportSize"]), Err("category.oneSize")); + assert_eq!(pick(&["bikeBrand"]), Err("category.unknownField")); + // Every field a name can bring can be picked as well, by its key + for rule in RULES.iter() { + for field in rule.fields { + assert!( + SELECTABLE.iter().any(|s| s.key == field.key), + "{}", + field.key + ); + } + } + + let (bikes, trailers, kids) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); + let categories = vec![ + CategoryRef { + id: bikes, + label: "Räder".into(), + parent: None, + fields: Some(vec!["frameNumber".into(), "color".into()]), + }, + CategoryRef { + id: trailers, + label: "Fahrradanhänger".into(), + parent: Some(bikes), + fields: Some(vec!["brand".into()]), + }, + CategoryRef { + id: kids, + label: "Für Kinder".into(), + parent: Some(bikes), + fields: None, + }, + ]; + let keys = |id| -> Vec<_> { + category_fields(id, &categories) + .iter() + .map(|f| f.key) + .collect() + }; + assert_eq!(keys(bikes), ["frameNumber", "color"]); + assert_eq!(keys(trailers), ["brand"]); + assert_eq!(keys(kids), ["frameNumber", "color"]); + } + #[test] fn requirable_fields_are_unique_by_key() { let keys: Vec<_> = requirable_fields().iter().map(|f| f.key).collect(); diff --git a/backend/src/modules/event_products.rs b/backend/src/modules/event_products.rs index 2850f221..351818e0 100644 --- a/backend/src/modules/event_products.rs +++ b/backend/src/modules/event_products.rs @@ -253,7 +253,7 @@ pub fn missing_label(info: &str, fields: &[CategoryField]) -> String { pub async fn fields_of( conn: &mut PgConnection, category: Uuid, -) -> sqlx::Result<&'static [CategoryField]> { +) -> sqlx::Result> { let categories = category_fields::load_categories(conn).await?; Ok(category_fields::category_fields(category, &categories)) } @@ -264,7 +264,7 @@ async fn assert_ready_for_event( product: &Product, event: &Event, ) -> AppResult<()> { - let fields = fields_of(conn, product.product_category).await?; + let fields = &fields_of(conn, product.product_category).await?; let missing = missing_for_event(product, event, fields); if missing.is_empty() { return Ok(()); diff --git a/backend/src/modules/products.rs b/backend/src/modules/products.rs index c9724726..f2913a09 100644 --- a/backend/src/modules/products.rs +++ b/backend/src/modules/products.rs @@ -66,7 +66,7 @@ async fn generate_upload_url(ctx: &mut Ctx, _: NoArgs) -> AppResult { /// Rejects values longer than their field allows, e.g. sizes that would not fit on the /// labels. Only sizes are that short; other fields are cut at 120 characters. pub(super) fn check_attribute_lengths( - fields: &'static [category_fields::CategoryField], + fields: &[category_fields::CategoryField], attributes: Option<&BTreeMap>, ) -> AppResult<()> { match category_fields::too_long(fields, attributes) { @@ -88,7 +88,7 @@ pub(super) async fn normalize_extras( attributes: Option<&BTreeMap>, minimum_price: Option, ) -> AppResult<(Option>, Option)> { - let fields = fields_of(conn, category).await?; + let fields = &fields_of(conn, category).await?; check_attribute_lengths(fields, attributes)?; let minimum = match minimum_price { Some(minimum) if !minimum.is_finite() || minimum < 0.0 => { @@ -269,7 +269,7 @@ async fn own_unlocked_product(ctx: &mut Ctx, id: Uuid) -> AppResult { /// An edit must not remove what an upcoming event of the item requires, e.g. its last /// photo or a required field like the frame number. async fn assert_ready_for_upcoming_events(ctx: &mut Ctx, product: &Product) -> AppResult<()> { - let fields = fields_of(ctx.conn(), product.product_category).await?; + let fields = &fields_of(ctx.conn(), product.product_category).await?; let now = Utc::now(); for relation in relations_of_product(ctx.conn(), product.id).await? { let Some(event) = docs::event(ctx.conn(), relation.event_id).await? else { @@ -413,7 +413,7 @@ struct AttributesArgs { /// Fills in category fields, e.g. the frame number an event requires; keeps the others. async fn add_product_attributes(ctx: &mut Ctx, args: AttributesArgs) -> AppResult<()> { let product = own_unlocked_product(ctx, args.product_id.0).await?; - let fields = fields_of(ctx.conn(), product.product_category).await?; + let fields = &fields_of(ctx.conn(), product.product_category).await?; check_attribute_lengths(fields, Some(&args.attributes))?; let mut merged: BTreeMap = product .attributes @@ -764,7 +764,7 @@ async fn get_product(ctx: &mut Ctx, args: ProductArgs) -> AppResult AppResult<()> { let title = event.title.clone(); if let [item] = items { - let fields = fields_of(ctx.conn(), item.product.product_category).await?; + let fields = &fields_of(ctx.conn(), item.product.product_category).await?; let attributes = category_fields::describe_attributes(fields, item.product.attributes.as_ref()); let (product, total, path) = ( @@ -786,7 +786,7 @@ async fn get_checkout_item( .await? .is_some_and(|seller| seller.payout_received); let list_price = current_list_price(&product, &relation); - let fields = fields_of(ctx.conn(), product.product_category).await?; + let fields = &fields_of(ctx.conn(), product.product_category).await?; let minimum_price = product .minimum_price .filter(|minimum| event.resolved_features().minimum_price && *minimum < list_price); @@ -885,7 +885,7 @@ async fn get_checkout_snapshot(ctx: &mut Ctx, args: EventIdArgs) -> AppResult Vec { match category { Some(category) => category_fields::describe_attributes( - category_fields::category_fields(category, categories), + &category_fields::category_fields(category, categories), attributes, ), None => Vec::new(), diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index 22d1595a..773ba7f0 100644 --- a/backend/tests/api/categories.rs +++ b/backend/tests/api/categories.rs @@ -168,7 +168,7 @@ async fn parallel_mutations_are_serialized_and_retried(db: PgPool) { .fetch_one(&db) .await .unwrap(); - assert_eq!((count, distinct), (22, 22)); + assert_eq!((count, distinct), (72, 72)); } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] @@ -189,9 +189,9 @@ async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { // A new instance gets the defaults, and a second start adds nothing start().await.unwrap(); - assert_eq!(labels().await.len(), 22); + assert_eq!(labels().await.len(), 72); start().await.unwrap(); - assert_eq!(labels().await.len(), 22); + assert_eq!(labels().await.len(), 72); // An instance with categories of its own does not get the defaults back sqlx::query("DELETE FROM categories WHERE label <> 'Kleidung'") @@ -513,3 +513,75 @@ async fn feature_flags(db: PgPool) { false ); } + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn admins_pick_the_extra_fields(db: PgPool) { + let app = app(&db).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 + } + }; + let fields_of = |label: &'static str| { + let app = &app; + async move { + let list = app + .query("categories.getAllCategories", json!({}), None) + .await; + list.body["value"] + .as_array() + .unwrap() + .iter() + .find(|c| c["label"] == label) + .unwrap() + .get("fields") + .cloned() + } + }; + + // Picked fields are stored in the order of the list, without doubles + let created = + create(json!({ "label": "Kinderwagen", "fields": ["color", "brand", "color"] })).await; + assert_eq!(created.status, StatusCode::OK, "{:?}", created.body); + assert_eq!( + fields_of("Kinderwagen").await, + Some(json!(["brand", "color"])) + ); + // Without a choice the name decides, as before + create(json!({ "label": "Fahrräder" })).await; + assert_eq!(fields_of("Fahrräder").await, None); + + assert_eq!( + create(json!({ "label": "Mäntel", "fields": ["clothingSize", "shoeSize"] })) + .await + .body["code"], + "category.oneSize" + ); + assert_eq!( + create(json!({ "label": "Mäntel", "fields": ["height"] })) + .await + .body["code"], + "category.unknownField" + ); + + // An empty choice means none at all; leaving it out goes back to the name + let id = created.body["value"].as_str().unwrap().to_owned(); + let update = |fields: Option| { + let (app, admin, id) = (&app, &admin, id.clone()); + let mut args = json!({ "categoryId": id, "label": "Kinderwagen", "translations": {} }); + if let Some(fields) = fields { + args["fields"] = fields; + } + async move { + app.mutation("categories.updateCategory", args, Some(admin)) + .await + } + }; + assert_eq!(update(Some(json!([]))).await.status, StatusCode::OK); + assert_eq!(fields_of("Kinderwagen").await, Some(json!([]))); + update(None).await; + assert_eq!(fields_of("Kinderwagen").await, None); +} diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index 53b23d5e..1f0090ca 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -185,6 +185,8 @@ export interface Docs { parentCategory?: Id<'categories'> | undefined; updatedAt: number; label: string; + /** Extra fields an admin picked (ids of SELECTABLE_FIELDS); unset: by the name */ + fields?: string[] | undefined; }; eventLocationCategories: { _id: Id<'eventLocationCategories'>; @@ -638,6 +640,7 @@ export interface Api { parentCategory?: Id<'categories'> | undefined; label: string; translations?: CategoryTranslations | undefined; + fields?: string[] | undefined; }, Id<'categories'> >; @@ -649,6 +652,8 @@ export interface Api { translations: CategoryTranslations; /** Unset: a main category */ parentCategory?: Id<'categories'> | undefined; + /** Unset: by the name */ + fields?: string[] | undefined; }, null >; diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index c3bcefb3..a0a5fe3f 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { EVENT_TYPES, findEventType } from './eventTypes'; +import { EVENT_TYPES, findEventType, preselectedCategories } from './eventTypes'; import { resolveEventFeatures, showsPriceOnLabel } from '../shared/eventFeatures'; import { REQUIRABLE_FIELD_KEYS } from '../shared/categoryFields'; import i18n from '../i18n'; @@ -82,6 +82,37 @@ describe('event types', () => { expect(match('bikeExchange', 'Einrichtung')).toBe(false); }); + it('a main category brings its sub-categories, unless the kind excludes them', () => { + const tree = [ + { _id: 'clothes', label: 'Kleidung' }, + { _id: 'kidsClothes', label: 'Kinderkleidung', parentCategory: 'clothes' }, + { _id: 'women', label: 'Damenkleidung', parentCategory: 'clothes' }, + { _id: 'maternity', label: 'Umstandsmode', parentCategory: 'clothes' }, + { _id: 'books', label: 'Bücher' }, + { _id: 'novels', label: 'Romane', parentCategory: 'books' }, + { _id: 'kidsBooks', label: 'Kinderbücher', parentCategory: 'books' }, + { _id: 'bikes', label: 'Fahrräder' }, + { _id: 'cargo', label: 'Lastenräder', parentCategory: 'bikes' }, + { _id: 'vehicles', label: 'Kinderfahrzeuge' }, + { _id: 'scooters', label: 'Roller & Scooter', parentCategory: 'vehicles' }, + { _id: 'prams', label: 'Kinderwagen & Buggys', parentCategory: 'vehicles' }, + { _id: 'electronics', label: 'Elektronik' }, + { _id: 'games', label: 'Konsolen & Videospiele', parentCategory: 'electronics' }, + ]; + const chosen = (id: string) => preselectedCategories(findEventType(id)!, tree); + expect(chosen('kidsBazaar')).toEqual([ + 'clothes', + 'kidsClothes', + 'maternity', + 'books', + 'kidsBooks', + 'vehicles', + 'scooters', + 'prams', + ]); + expect(chosen('bikeExchange')).toEqual(['bikes', 'cargo', 'vehicles', 'scooters']); + }); + it('the bike sale follows the guide: frame number required and an intake fee', () => { const bikes = findEventType('bikeExchange')!; expect(bikes.features.requiredFields).toEqual(['frameNumber']); diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index 408db225..f9faa8a4 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -16,8 +16,13 @@ export interface EventType { examplePrices: [number, number, number]; commission: number; features: StoredEventFeatures; - /** Categories preselected by name, e.g. all bike categories */ + /** + * Categories preselected by name, e.g. all bike categories. A main category that matches + * brings its sub-categories along. + */ categoryMatch?: RegExp; + /** Not preselected, even below a main category that matches, e.g. women's clothes */ + categoryExclude?: RegExp; } const BIKES = /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i; @@ -44,7 +49,8 @@ export const EVENT_TYPES: EventType[] = [ labelMark: 'universal', priceOnLabel: false, }, - categoryMatch: new RegExp(`kind|baby|spiel|kleid|schuh|buch|${KIDS_VEHICLES.source}`, 'i'), + categoryMatch: new RegExp(`kind|baby|spiel|kleid|schuh|b[uü]ch|${KIDS_VEHICLES.source}`, 'i'), + categoryExclude: /damen|herren|roman|sachb|kochb|comic|video|konsole/i, }, { // Second-hand for everyone, e.g. a women's clothing bazaar or a flea market @@ -65,7 +71,7 @@ export const EVENT_TYPES: EventType[] = [ labelMark: 'universal', priceOnLabel: false, }, - categoryMatch: /kleid|schuh|accessoir|haushalt|buch|spiel/i, + categoryMatch: /kleid|schuh|accessoir|haushalt|b[uü]ch|spiel/i, }, { // Fewer, pricier items: a negotiable price and questions about size and condition @@ -107,6 +113,8 @@ export const EVENT_TYPES: EventType[] = [ priceOnLabel: true, }, categoryMatch: new RegExp(`${BIKES.source}|${KIDS_VEHICLES.source}`, 'i'), + // Pushed, not ridden + categoryExclude: /kinderwagen|buggy/i, }, ]; @@ -114,3 +122,24 @@ export const EVENT_TYPES: EventType[] = [ export function findEventType(id: string | undefined): EventType | undefined { return EVENT_TYPES.find((type) => type.id === id); } + +/** + * The categories a kind of bazaar preselects: those whose name matches, and the + * sub-categories of a main category that matches, unless the kind excludes them. + */ +export function preselectedCategories( + type: Pick, + categories: readonly { _id: string; label: string; parentCategory?: string }[] +): string[] { + const { categoryMatch: match, categoryExclude: exclude } = type; + if (!match) return []; + const byId = new Map(categories.map((category) => [category._id, category])); + return categories + .filter((category) => { + if (exclude?.test(category.label)) return false; + if (match.test(category.label)) return true; + const parent = category.parentCategory ? byId.get(category.parentCategory) : undefined; + return !!parent && !parent.parentCategory && match.test(parent.label); + }) + .map((category) => category._id); +} diff --git a/src/locales/de/admin.json b/src/locales/de/admin.json index 2a5ef112..efefeb15 100644 --- a/src/locales/de/admin.json +++ b/src/locales/de/admin.json @@ -288,14 +288,27 @@ "noFields": "Keine", "usage": "Verwendung", "subOf": "Unterkategorie von {{parent}}", + "pickFields": "Zusatzfelder selbst wählen", + "fieldsPicked": "Selbst gewählt", + "fieldNames": { + "frameNumber": "Rahmennummer", + "frameSize": "Rahmengröße", + "wheelSize": "Laufradgröße", + "brand": "Marke", + "color": "Farbe", + "clothingSize": "Größe (Kleidung)", + "shoeSize": "Größe (Schuhe, EU)", + "sportSize": "Größe / Länge (Sport)", + "model": "Modell" + }, "parent": "Hauptkategorie", "noParent": "Keine – ist selbst Hauptkategorie", "parentHint": "Unterkategorien stehen in allen Listen unter ihrer Hauptkategorie. Ohne eigene Zusatzfelder übernehmen sie die der Hauptkategorie.", "parentLocked": "Diese Kategorie hat Unterkategorien und bleibt deshalb Hauptkategorie.", "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.", + "fieldsHint": "Automatisch: Der Name entscheidet über die Zusatzfelder, etwa die Rahmennummer bei „Fahrräder“. Passt der Name zu keinem Feld, gelten die der Hauptkategorie. Der Name entscheidet auch, welche Kategorien neue Basare vorausgewählt bekommen.", + "fieldsPreview": "Zusatzfelder: {{fields}}", + "noFieldsPreview": "Die Kategorie hat 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", diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 8a182e15..c2776e53 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -41,6 +41,8 @@ "inUse": "Diese Kategorie wird noch verwendet und kann nicht gelöscht werden.", "parentNotMain": "Eine Unterkategorie kann nur unter einer Hauptkategorie stehen.", "hasSubcategories": "Diese Kategorie hat selbst Unterkategorien und kann deshalb keine Unterkategorie werden.", + "unknownField": "Dieses Zusatzfeld gibt es nicht.", + "oneSize": "Bitte wähle höchstens eine Art von Größe.", "lastOne": "Die letzte Kategorie kann nicht gelöscht werden." }, "common": { diff --git a/src/locales/en/admin.json b/src/locales/en/admin.json index 1c2122ca..37e54816 100644 --- a/src/locales/en/admin.json +++ b/src/locales/en/admin.json @@ -288,14 +288,27 @@ "noFields": "None", "usage": "Usage", "subOf": "Sub-category of {{parent}}", + "pickFields": "Choose the extra fields myself", + "fieldsPicked": "Chosen by hand", + "fieldNames": { + "frameNumber": "Frame number", + "frameSize": "Frame size", + "wheelSize": "Wheel size", + "brand": "Brand", + "color": "Color", + "clothingSize": "Size (clothing)", + "shoeSize": "Size (shoes, EU)", + "sportSize": "Size / length (sports)", + "model": "Model" + }, "parent": "Main category", "noParent": "None – is a main category itself", "parentHint": "Sub-categories are listed under their main category everywhere. Without extra fields of their own, they take those of the main category.", "parentLocked": "This category has sub-categories, so it stays a main category.", "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.", + "fieldsHint": "Automatic: the name decides the extra fields, such as the frame number for “Fahrräder”. If the name fits no field, those of the main category apply. The name also decides which categories new bazaars get preselected.", + "fieldsPreview": "Extra fields: {{fields}}", + "noFieldsPreview": "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", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 996c22f1..c55f12c6 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -41,6 +41,8 @@ "inUse": "This category is still in use and cannot be deleted.", "parentNotMain": "A sub-category can only be placed under a main category.", "hasSubcategories": "This category has sub-categories of its own and therefore cannot become a sub-category.", + "unknownField": "This extra field does not exist.", + "oneSize": "Please choose at most one kind of size.", "lastOne": "The last category cannot be deleted." }, "common": { diff --git a/src/pages/administrator/AdminCategoriesPage.test.tsx b/src/pages/administrator/AdminCategoriesPage.test.tsx index 3d7a6d9f..693f9fff 100644 --- a/src/pages/administrator/AdminCategoriesPage.test.tsx +++ b/src/pages/administrator/AdminCategoriesPage.test.tsx @@ -27,6 +27,15 @@ const kids = { const mutations: Record> = {}; beforeEach(() => { + // jsdom has no ResizeObserver; switch and checkbox use it + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + } + ); 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) => { @@ -119,7 +128,7 @@ describe('AdminCategoriesPage', () => { expect(options).toEqual(['none', 'bikes']); fireEvent.change(parent, { target: { value: 'bikes' } }); // Without fields of its own it takes those of the main category - expect(screen.getByText(/Zusatzfelder mit diesem Namen: Rahmennummer/)).toBeInTheDocument(); + expect(screen.getByText(/Zusatzfelder: Rahmennummer/)).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); await waitFor(() => expect(mutations['categories.updateCategory']).toHaveBeenCalledWith({ @@ -127,6 +136,7 @@ describe('AdminCategoriesPage', () => { label: 'Sonstiges', translations: { en: undefined }, parentCategory: 'bikes', + fields: undefined, }) ); }); @@ -138,4 +148,36 @@ describe('AdminCategoriesPage', () => { expect(screen.getByText(/bleibt deshalb Hauptkategorie/)).toBeInTheDocument(); expect(screen.getByRole('combobox', { name: 'Hauptkategorie' })).toBeDisabled(); }); + + it('lets admins pick the extra fields instead of the name', async () => { + render(); + fireEvent.click(within(row('Sonstiges')).getByRole('button', { name: 'Bearbeiten' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Zusatzfelder selbst wählen' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Marke' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Größe (Kleidung)' })); + // One size at most: the shoe size replaces the clothing size + fireEvent.click(screen.getByRole('checkbox', { name: 'Größe (Schuhe, EU)' })); + expect(screen.getByRole('checkbox', { name: 'Größe (Kleidung)' })).not.toBeChecked(); + expect(screen.getByText('Zusatzfelder: Marke, Größe (EU)')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.updateCategory']).toHaveBeenCalledWith( + expect.objectContaining({ categoryId: 'misc', fields: ['brand', 'shoeSize'] }) + ) + ); + }); + + it('starts the choice from the fields of the name and marks picked ones', () => { + vi.mocked(useQuery).mockReturnValue([bikes, kids, { ...misc, fields: ['model'] }] as never); + render(); + expect(within(row('Sonstiges')).getByText('Selbst gewählt')).toBeInTheDocument(); + expect(within(row('Sonstiges')).getByText('Modell')).toBeInTheDocument(); + + fireEvent.click(within(row('Fahrräder')).getByRole('button', { name: 'Bearbeiten' })); + fireEvent.click(screen.getByRole('checkbox', { name: 'Zusatzfelder selbst wählen' })); + expect(screen.getByRole('checkbox', { name: 'Rahmennummer' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Marke' })).toBeChecked(); + expect(screen.getByRole('checkbox', { name: 'Modell' })).not.toBeChecked(); + }); }); diff --git a/src/pages/administrator/AdminCategoriesPage.tsx b/src/pages/administrator/AdminCategoriesPage.tsx index a40f13d9..b98b2213 100644 --- a/src/pages/administrator/AdminCategoriesPage.tsx +++ b/src/pages/administrator/AdminCategoriesPage.tsx @@ -14,7 +14,9 @@ import { } from '../../components/ui/dialog'; import { EmptyState } from '../../components/ui/empty-state'; import { Input } from '../../components/ui/input'; +import { Checkbox } from '../../components/ui/checkbox'; import { Label } from '../../components/ui/label'; +import { Switch } from '../../components/ui/switch'; import { Select, SelectContent, @@ -40,6 +42,8 @@ import { getUserFacingErrorMessage } from '../../lib/errors'; import { getCategoryFields, getFieldsForLabel, + SELECTABLE_FIELDS, + selectableIds, type CategoryField, } from '../../shared/categoryFields'; @@ -50,6 +54,8 @@ const NO_PARENT = 'none'; /** What the dialog works on: a category, or null for a new one. */ type Editing = { category: AdminCategory | null }; +const fieldKey = (id: string) => SELECTABLE_FIELDS.find((field) => field.text === id)?.key; + const fieldNames = (fields: CategoryField[]) => fields.map((field) => categoryFieldText(field, 'label') ?? field.label); @@ -93,17 +99,30 @@ function CategoryDialog({ (other) => !other.parentCategory && other._id !== category?._id ); const hasChildren = (category?.childCount ?? 0) > 0; + // Picked extra fields (ids of SELECTABLE_FIELDS); undefined: they follow the name + const [picked, setPicked] = useState(category?.fields); const [saving, setSaving] = useState(false); const name = label.trim(); - const fieldsFor = (candidate: string, parentId: string | undefined) => + const byName = (candidate: string) => getFieldsForLabel(candidate) ?? - (parentId && parentId !== NO_PARENT ? getCategoryFields(parentId, categories) : []); - const fields = fieldNames(fieldsFor(name, parent)); + (parent !== NO_PARENT ? getCategoryFields(parent, categories) : []); + const fields = fieldNames( + picked ? SELECTABLE_FIELDS.filter((field) => picked.includes(field.text)) : byName(name) + ); const fieldsChange = !!category && (category.productCount > 0 || category.eventCount > 0) && - fields.join() !== fieldNames(fieldsFor(category.label, category.parentCategory)).join(); + fields.join() !== fieldNames(getCategoryFields(category._id, categories)).join(); + + const pickOwn = (own: boolean) => setPicked(own ? selectableIds(byName(name)) : undefined); + const togglePicked = (field: CategoryField, on: boolean) => + setPicked((current = []) => + on + ? // One size at most: all sizes share the key + [...current.filter((id) => fieldKey(id) !== field.key), field.text] + : current.filter((id) => id !== field.text) + ); const submit = async (event: FormEvent) => { event.preventDefault(); @@ -118,11 +137,9 @@ function CategoryDialog({ try { const translations = { en: nameEn.trim() || undefined }; const parentCategory = parent === NO_PARENT ? undefined : (parent as Id<'categories'>); - if (category) { - await update({ categoryId: category._id, label: name, translations, parentCategory }); - } else { - await create({ label: name, translations, parentCategory }); - } + const args = { label: name, translations, parentCategory, fields: picked }; + if (category) await update({ categoryId: category._id, ...args }); + else await create(args); toast.success(t('categories.saved')); onClose(); } catch (error) { @@ -149,17 +166,6 @@ function CategoryDialog({ required autoFocus /> -

{t('categories.fieldsHint')}

- {name && ( -

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

- )} - {fieldsChange && ( -

{t('categories.fieldsChange')}

- )}
@@ -191,6 +197,43 @@ function CategoryDialog({ />

{t('categories.nameEnHint')}

+
+ {t('categories.fields')} +
+ + +
+ {picked ? ( +
+ {SELECTABLE_FIELDS.map((field) => ( +
+ togglePicked(field, on === true)} + /> + +
+ ))} +
+ ) : ( +

{t('categories.fieldsHint')}

+ )} + {name && ( +

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

+ )} + {fieldsChange && ( +

{t('categories.fieldsChange')}

+ )} +
@@ -245,14 +273,58 @@ function CategoryDialog({ ); } -/** The product categories: names in each language, their extra fields and what uses them. */ -export function AdminCategoriesPage() { +/** The fields of a row: its own, or "like the main category" for a sub-category. */ +function FieldsOf({ category, parent }: { category: AdminCategory; parent?: AdminCategory }) { const { t } = useTranslation('admin'); - const categories = useQuery(api.categories.listForAdmin, {}); - const remove = useMutation(api.categories.deleteCategory); - const [editing, setEditing] = useState(null); + if (parent && !category.fields) { + return ( + + {t('categories.inherit', { name: parent.label })} + + ); + } + if (category.fieldList.length === 0) { + return {t('categories.noFields')}; + } + return ( +
+ {fieldNames(category.fieldList).map((field) => ( + + {field} + + ))} +
+ ); +} - const handleDelete = async (category: AdminCategory) => { +function CategoryRow({ + category, + categories, + sub = false, + childCount, + open, + onToggle, + onEdit, + onAddSub, +}: { + category: AdminCategory; + categories: AdminCategory[]; + sub?: boolean; + childCount: number; + open?: boolean; + onToggle?: () => void; + onEdit: () => void; + onAddSub?: () => void; +}) { + const { t } = useTranslation('admin'); + const remove = useMutation(api.categories.deleteCategory); + const blocked = + category.productCount || category.eventCount || category.childCount + ? t('categories.inUse') + : categories.length === 1 + ? t('categories.lastOne') + : undefined; + const handleDelete = async () => { try { await remove({ categoryId: category._id }); toast.success(t('categories.deleted')); @@ -261,127 +333,192 @@ export function AdminCategoriesPage() { } }; - 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')} +
+
+ {!sub && + (childCount > 0 ? ( + + ) : ( + + ))} +
+
{category.label}
+
+ {[ + category.translations.en, + !sub && childCount > 0 && t('categories.subcategories', { count: childCount }), + ] + .filter(Boolean) + .join(' · ')} +
+
+
+
+ other._id === category.parentCategory)} + /> +
+
+ {t('categories.usageProducts', { count: category.productCount })} ·{' '} + {t('categories.usageEvents', { count: category.eventCount })} +
+
+ {onAddSub && ( + - } - /> + )} + + {/* 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} + /> + +
+
+ ); +} - {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 ?? '—'} - - {category.fields && ( -
- {t('categories.fieldsPicked')} -
- )} - {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)} - /> - -
-
-
- ); - }) - )} -
-
+function CategoryTree({ + categories, + onEdit, +}: { + categories: AdminCategory[]; + onEdit: (editing: Editing) => void; +}) { + const [open, setOpen] = useState([]); + const toggle = (id: string) => + setOpen((current) => + current.includes(id) ? current.filter((other) => other !== id) : [...current, id] + ); + return ( +
+ {groupCategories(categories).map(({ category, children }) => ( +
+ toggle(category._id)} + onEdit={() => onEdit({ category })} + onAddSub={() => { + setOpen((current) => [...new Set([...current, category._id])]); + onEdit({ parent: category._id }); + }} + /> + {open.includes(category._id) && + children.map((child) => ( + onEdit({ category: child })} + /> + ))}
- )} + ))} +
+ ); +} + +/** The product categories and the extra fields their items have. */ +export function AdminCategoriesPage() { + const { t } = useTranslation('admin'); + const categories = useQuery(api.categories.listForAdmin, {}); + const definitions = useQuery(api.categories.listFields, {}); + const [tab, setTab] = useState('categories'); + const [editing, setEditing] = useState(null); + + return ( +
+ + +
+ + {t('categories.tabCategories')} + {t('categories.tabFields')} + + {tab === 'categories' && ( + + )} +
+ + + {categories?.length === 0 ? ( + + ) : !categories ? ( + + + + +
+ ) : ( + + )} +
+ + + +
- {editing && categories && ( + {editing && categories && definitions && ( setEditing(null)} /> )} diff --git a/src/pages/administrator/AdminCategoryFields.tsx b/src/pages/administrator/AdminCategoryFields.tsx new file mode 100644 index 00000000..1b8ffc50 --- /dev/null +++ b/src/pages/administrator/AdminCategoryFields.tsx @@ -0,0 +1,270 @@ +import { useState, type FormEvent } from 'react'; +import { ListPlus, Pencil, Plus, 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 { Checkbox } from '../../components/ui/checkbox'; +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 { api } from '../../lib/api/functions'; +import { useMutation, useQuery } from '../../lib/api/react'; +import type { FunctionReturnType } from '../../lib/api/types'; +import { getUserFacingErrorMessage } from '../../lib/errors'; + +type AdminField = FunctionReturnType[number]; + +/** A German and an English input side by side. */ +function TextPair({ + id, + label, + labelEn, + value, + valueEn, + onChange, + onChangeEn, + hint, + required = false, +}: { + id: string; + label: string; + labelEn: string; + value: string; + valueEn: string; + onChange: (value: string) => void; + onChangeEn: (value: string) => void; + hint?: string; + required?: boolean; +}) { + return ( +
+
+
+ + onChange(event.target.value)} + maxLength={120} + required={required} + /> +
+
+ + onChangeEn(event.target.value)} + maxLength={120} + /> +
+
+ {hint &&

{hint}

} +
+ ); +} + +function FieldDialog({ field, onClose }: { field: AdminField | null; onClose: () => void }) { + const { t } = useTranslation('admin'); + const save = useMutation(api.categories.saveField); + const [values, setValues] = useState({ + label: field?.label ?? '', + labelEn: field?.labelEn ?? '', + placeholder: field?.placeholder ?? '', + placeholderEn: field?.placeholderEn ?? '', + hint: field?.hint ?? '', + hintEn: field?.hintEn ?? '', + short: field?.short ?? false, + }); + const [saving, setSaving] = useState(false); + const set = (key: keyof typeof values) => (value: string) => + setValues((current) => ({ ...current, [key]: value })); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setSaving(true); + try { + await save({ fieldId: field?._id, ...values }); + toast.success(t('categoryFields.saved')); + onClose(); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } finally { + setSaving(false); + } + }; + + return ( + !open && onClose()}> + + + {t(field ? 'categoryFields.edit' : 'categoryFields.new')} + + + + + + + + + + + + + + ); +} + +/** The extra fields admins define; categories pick from them. */ +export function AdminCategoryFields() { + const { t } = useTranslation('admin'); + const fields = useQuery(api.categories.listFieldsForAdmin, {}); + const remove = useMutation(api.categories.deleteField); + const [editing, setEditing] = useState<{ field: AdminField | null } | null>(null); + + const handleDelete = async (field: AdminField) => { + try { + await remove({ fieldId: field._id }); + toast.success(t('categoryFields.deleted')); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } + }; + + return ( +
+
+

{t('categoryFields.intro')}

+ +
+ {fields?.length === 0 ? ( + + ) : ( +
+ {(fields ?? []).map((field) => ( +
+
+
+ {field.label} + {field.short && ( + + {t('categoryFields.shortBadge')} + + )} +
+ {field.labelEn && ( +
{field.labelEn}
+ )} +
+
+ {field.placeholder ?? '—'} +
+
+ {field.categoryCount + ? t('categoryFields.used', { count: field.categoryCount }) + : t('categoryFields.unused')} +
+
+ + + 0} + aria-label={`${t('categories.delete')}: ${field.label}`} + > + + + } + title={t('categoryFields.deleteTitle', { name: field.label })} + description={t('categoryFields.deleteText')} + confirmLabel={t('categories.delete')} + destructive + onConfirm={() => handleDelete(field)} + /> + +
+
+ ))} +
+ )} + {editing && ( + setEditing(null)} + /> + )} +
+ ); +} diff --git a/src/pages/organizer/events/components/EditEventCategories.test.tsx b/src/pages/organizer/events/components/EditEventCategories.test.tsx index 6b062b6a..120c4230 100644 --- a/src/pages/organizer/events/components/EditEventCategories.test.tsx +++ b/src/pages/organizer/events/components/EditEventCategories.test.tsx @@ -1,5 +1,5 @@ -import { fireEvent, render, screen, within } from '@testing-library/react'; -import { describe, expect, it } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { FormProvider, useForm } from 'react-hook-form'; import type { Doc } from '../../../../lib/api/types'; import { EditEventCategories } from './EditEventCategories'; @@ -24,35 +24,56 @@ function Form({ categories = [] as string[] }) { ); } +beforeEach(() => { + // jsdom has no ResizeObserver; the checkbox uses it + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + } + ); +}); + describe('EditEventCategories', () => { - it('shows main categories and their sub-categories only when opened', () => { + it('one row per main category; opened, its sub-categories', () => { render(
); - expect(screen.getByText('Fahrräder')).toBeInTheDocument(); - expect(screen.getByText('0/2')).toBeInTheDocument(); - expect(screen.queryByText('Lastenräder')).not.toBeInTheDocument(); - + expect(screen.getByText('0 von 2 Hauptkategorien gewählt')).toBeInTheDocument(); + expect(screen.queryByLabelText('Lastenräder')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })); - expect(screen.getByText('Lastenräder')).toBeInTheDocument(); + expect(screen.getByLabelText('Lastenräder')).not.toBeChecked(); }); - it('a main category comes and goes with its sub-categories', () => { + it('a main category with all sub-categories is stored as itself', () => { render(); - fireEvent.click(screen.getByText('Fahrräder')); - expect(chosen).toEqual(['bikes', 'cargo', 'trailers']); - expect(screen.getByText('2/2')).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText('Fahrräder')); + expect(chosen).toEqual(['bikes']); + expect(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })).toHaveTextContent( + 'alle' + ); + // One sub-category less: the others are stored, the main category is half chosen fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })); - fireEvent.click(screen.getByText('Fahrradanhänger')); - expect(chosen).toEqual(['bikes', 'cargo']); - - // Not all chosen: a click chooses the rest, the next one clears the group - const badge = screen.getByText('1/2').parentElement as HTMLElement; - fireEvent.click(within(badge).getByText('Fahrräder')); - expect(chosen).toEqual(['bikes', 'cargo', 'trailers']); - fireEvent.click(within(badge).getByText('Fahrräder')); + fireEvent.click(screen.getByLabelText('Fahrradanhänger')); + expect(chosen).toEqual(['cargo']); + expect(screen.getByLabelText('Fahrräder')).toHaveAttribute('data-state', 'indeterminate'); + expect(screen.getByText('1 von 2')).toBeInTheDocument(); + + // Half chosen: a click chooses all, the next one none + fireEvent.click(screen.getByLabelText('Fahrräder')); + expect(chosen).toEqual(['bikes']); + fireEvent.click(screen.getByLabelText('Fahrräder')); expect(chosen).toEqual([]); + }); - fireEvent.click(screen.getByText('Sonstiges')); - expect(chosen).toEqual(['misc']); + it('all and none at once; a stored main category shows all its sub-categories', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder' })); + expect(screen.getByLabelText('Lastenräder')).toBeChecked(); + fireEvent.click(screen.getByRole('button', { name: 'Alle' })); + expect(chosen).toEqual(['bikes', 'misc']); + fireEvent.click(screen.getByRole('button', { name: 'Keine' })); + expect(chosen).toEqual([]); }); }); diff --git a/src/pages/organizer/events/components/EditEventCategories.tsx b/src/pages/organizer/events/components/EditEventCategories.tsx index f0320e3f..00873d4d 100644 --- a/src/pages/organizer/events/components/EditEventCategories.tsx +++ b/src/pages/organizer/events/components/EditEventCategories.tsx @@ -3,20 +3,150 @@ import { FieldError } from '../../../../components/ui/field-error'; import { useFormContext } from 'react-hook-form'; import { Label } from '../../../../components/ui/label'; import { Badge } from '../../../../components/ui/badge'; +import { Checkbox } from '../../../../components/ui/checkbox'; import { EVENT_SERVICES } from '../../../../shared/constants'; import type { Doc } from '../../../../lib/api/types'; import { useEffect, useState } from 'react'; -import { ChevronDown } from 'lucide-react'; -import { groupCategories } from '../../../../shared/categoryTree'; -import { cn } from '../../../../lib/utils'; +import { ChevronRight } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { serviceLabel } from '../../../../i18n/services'; import { categoryName } from '../../../../i18n/categories'; +import { + compactSelection, + expandSelection, + groupCategories, +} from '../../../../shared/categoryTree'; +import { cn } from '../../../../lib/utils'; type EventCategoriesProbs = { categoryList: Doc<'categories'>[]; }; +/** + * The categories a bazaar allows: one row per main category with a checkbox for all of + * it; opened, its sub-categories can be chosen one by one. + */ +function AllowedCategories({ categoryList }: EventCategoriesProbs) { + const { t } = useTranslation('organizer'); + const { watch, setValue } = useFormContext(); + const [open, setOpen] = useState([]); + const list = categoryList.map((category) => ({ ...category, _id: String(category._id) })); + const groups = groupCategories(list); + const stored: string[] = watch('categories') || []; + const selected = expandSelection(stored, list); + + const choose = (next: Set) => + setValue('categories', compactSelection(next, list), { + shouldValidate: true, + shouldDirty: true, + shouldTouch: true, + }); + const setAll = (ids: string[], on: boolean) => { + const next = new Set(selected); + ids.forEach((id) => (on ? next.add(id) : next.delete(id))); + choose(next); + }; + const toggleOpen = (id: string) => + setOpen((current) => + current.includes(id) ? current.filter((other) => other !== id) : [...current, id] + ); + const everything = groups.flatMap(({ category, children }) => + children.length ? children.map((child) => child._id) : [category._id] + ); + const chosenGroups = groups.filter(({ category, children }) => + (children.length ? children : [category]).some((c) => selected.has(c._id)) + ).length; + + return ( +
+
+
+ +

+ {t('categories.chosenSummary', { count: chosenGroups, total: groups.length })} +

+
+
+ + +
+
+
+ {groups.map(({ category, children }) => { + const ids = children.length ? children.map((child) => child._id) : [category._id]; + const count = ids.filter((id) => selected.has(id)).length; + const state = + count === 0 ? false : count === ids.length ? true : ('indeterminate' as const); + const isOpen = open.includes(category._id); + const id = `allowed-${category._id}`; + return ( +
+
+ setAll(ids, state !== true)} + /> + + {children.length > 0 && ( + + )} +
+ {isOpen && ( +
+ {children.map((child) => { + const childId = `allowed-${child._id}`; + return ( +
+ setAll([child._id], on === true)} + /> + +
+ ); + })} +
+ )} +
+ ); + })} +
+

{t('categories.allowedHint')}

+
+ ); +} + export function EditEventCategories({ categoryList }: EventCategoriesProbs) { const { t } = useTranslation('organizer'); const { @@ -26,7 +156,6 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { formState: { errors }, } = useFormContext(); - const categories: string[] = watch('categories') || []; const services: string[] = watch('services') || []; useEffect(() => { @@ -34,32 +163,6 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { register('services'); }, [register]); - const [expanded, setExpanded] = useState([]); - const groups = groupCategories(categoryList.map((cat) => ({ ...cat, _id: String(cat._id) }))); - - const choose = (current: string[]) => - setValue('categories', current, { shouldValidate: true, shouldDirty: true, shouldTouch: true }); - - const toggleCategory = (catId: string) => { - const id = String(catId); - choose(categories.includes(id) ? categories.filter((c) => c !== id) : [...categories, id]); - }; - - /** A main category comes with its sub-categories, and goes with them. */ - const toggleGroup = (ids: string[]) => { - const all = ids.every((id) => categories.includes(id)); - choose( - all - ? categories.filter((c) => !ids.includes(c)) - : [...categories, ...ids.filter((id) => !categories.includes(id))] - ); - }; - - const toggleExpanded = (id: string) => - setExpanded((current) => - current.includes(id) ? current.filter((c) => c !== id) : [...current, id] - ); - const toggleService = (svc: string) => { const current = services.includes(svc) ? services.filter((s: string) => s !== svc) @@ -69,72 +172,8 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { return ( -
- -
- {groups.map(({ category, children }) => { - const id = category._id; - if (children.length === 0) { - return ( - toggleCategory(id)} - > - {categoryName(category)} - - ); - } - const childIds = children.map((child) => child._id); - const chosenChildren = childIds.filter((c) => categories.includes(c)).length; - const isOpen = expanded.includes(id); - return ( -
- - toggleGroup([id, ...childIds])} - > - {categoryName(category)} - - {chosenChildren}/{childIds.length} - - - - - {isOpen && ( -
- {children.map((child) => ( - toggleCategory(child._id)} - > - {categoryName(child)} - - ))} -
- )} -
- ); - })} -
-

{t('categories.groupHint')}

- {errors.categories && {errors.categories.message as string}} -
+ + {errors.categories && {errors.categories.message as string}}
diff --git a/src/pages/organizer/events/components/EditEventFeatures.tsx b/src/pages/organizer/events/components/EditEventFeatures.tsx index 3812fa77..d3794e8c 100644 --- a/src/pages/organizer/events/components/EditEventFeatures.tsx +++ b/src/pages/organizer/events/components/EditEventFeatures.tsx @@ -9,7 +9,9 @@ import { Label } from '../../../../components/ui/label'; import { useQuery } from '../../../../lib/api/react'; import { api } from '../../../../lib/api/functions'; import { MAX_DISCOUNT_PERCENT } from '../../../../shared/eventFeatures'; -import { getCategoryFields, REQUIRABLE_FIELDS } from '../../../../shared/categoryFields'; +import { getCategoryFields } from '../../../../shared/categoryFields'; +import { expandCategories } from '../../../../shared/categoryTree'; +import { useRequirableFields } from '../../../../hooks/useCategoryFields'; import { feeLockHint, type FeeLock } from '../../../../lib/sellerFees'; import { categoryFieldText } from '../../../../i18n/categoryFields'; import { useTranslation } from 'react-i18next'; @@ -164,12 +166,17 @@ function RequiredFieldsPicker() { const { t } = useTranslation('organizer'); const { control, watch } = useFormContext(); const categoryList = useQuery(api.categories.getAllCategories); - const chosenCategories = (watch('categories') as string[] | undefined) ?? []; + const requirable = useRequirableFields(); + // A chosen main category stands for its sub-categories, which may have other fields + const chosenCategories = expandCategories( + (watch('categories') as string[] | undefined) ?? [], + categoryList + ); const required = (watch('features.requiredFields') as string[] | undefined) ?? []; const available = new Set( chosenCategories.flatMap((id) => getCategoryFields(id, categoryList).map((f) => f.key)) ); - const fields = REQUIRABLE_FIELDS.filter( + const fields = requirable.filter( (field) => available.has(field.key) || required.includes(field.key) ); diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index 00c1d1b9..96e1f134 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -45,7 +45,7 @@ import { } from '../../../../../lib/sellerFees'; import { cn, formatDateRangeDE, formatPriceDE } from '../../../../../lib/utils'; import { categoryFieldText } from '../../../../../i18n/categoryFields'; -import { REQUIRABLE_FIELDS } from '../../../../../shared/categoryFields'; +import { useRequirableFields } from '../../../../../hooks/useCategoryFields'; import { formatEventPlace } from '../../../../../shared/eventJsonLd'; import { MAX_DISCOUNT_PERCENT } from '../../../../../shared/eventFeatures'; import { eventCategoryNames } from '../../../../../i18n/categories'; @@ -409,13 +409,14 @@ export function ItemsPreview({ type }: { type?: EventType }) { const features = values.features ?? {}; const { kind, items } = useExamples(type); const categoryList = useQuery(api.categories.getAllCategories); + const requirable = useRequirableFields(); const chosenIds = (categoryList ?? []) .map((category) => category._id as string) .filter((id) => values.categories?.includes(id)); const chosen = eventCategoryNames(chosenIds, categoryList) ?? []; - const required = REQUIRABLE_FIELDS.filter((field) => - features.requiredFields?.includes(field.key) - ).map((field) => categoryFieldText(field, 'label') ?? field.label); + const required = requirable + .filter((field) => features.requiredFields?.includes(field.key)) + .map((field) => categoryFieldText(field, 'label') ?? field.label); const limit = given(features.maxItemsPerSeller); const small = features.labelFormat === 'small'; const showPrice = !!features.priceOnLabel && !features.discounts; diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index e22bb2f4..08933c53 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -8,7 +8,7 @@ import { Badge } from '../../../../../components/ui/badge'; import { dateLocale } from '../../../../../i18n/format'; import { useTranslation } from 'react-i18next'; import { serviceLabel } from '../../../../../i18n/services'; -import { REQUIRABLE_FIELDS } from '../../../../../shared/categoryFields'; +import { useRequirableFields } from '../../../../../hooks/useCategoryFields'; import { categoryFieldText } from '../../../../../i18n/categoryFields'; import { eventCategoryNames } from '../../../../../i18n/categories'; import { api } from '../../../../../lib/api/functions'; @@ -60,6 +60,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 requirable = useRequirableFields(); const categoryList = useQuery(api.categories.getAllCategories); const timeFormat = new Intl.DateTimeFormat(dateLocale(), { weekday: 'short', @@ -157,9 +158,8 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { - features.requiredFields?.includes(field.key) - ) + fields: requirable + .filter((field) => features.requiredFields?.includes(field.key)) .map((field) => categoryFieldText(field, 'label') ?? field.label) .join(', '), })} diff --git a/src/pages/public/products/components/PublicProductInfo.tsx b/src/pages/public/products/components/PublicProductInfo.tsx index aa846d3a..3dfb27ec 100644 --- a/src/pages/public/products/components/PublicProductInfo.tsx +++ b/src/pages/public/products/components/PublicProductInfo.tsx @@ -3,7 +3,6 @@ import { cn, formatPriceDE } from '../../../../lib/utils'; import { CONDITION_OPTIONS } from '../../../../constants/records'; import { useTranslation } from 'react-i18next'; import { categoryFieldText } from '../../../../i18n/categoryFields'; -import type { CategoryFieldText } from '../../../../shared/categoryFields'; function conditionTitle(condition: string) { return condition in CONDITION_OPTIONS @@ -92,7 +91,7 @@ export function PublicProductDetails({ attributeList = [], }: { description?: string; - attributeList?: { label: string; text?: CategoryFieldText; value: string }[]; + attributeList?: { label: string; labelEn?: string; value: string }[]; }) { const { t } = useTranslation('product'); return ( @@ -104,7 +103,7 @@ export function PublicProductDetails({ {attributeList.map((row) => (
- {(row.text && categoryFieldText({ text: row.text }, 'label')) ?? row.label} + {categoryFieldText(row, 'label') ?? row.label}
{row.value}
diff --git a/src/pages/seller/products/MyProductsPage.tsx b/src/pages/seller/products/MyProductsPage.tsx index 95b63ce9..261f6191 100644 --- a/src/pages/seller/products/MyProductsPage.tsx +++ b/src/pages/seller/products/MyProductsPage.tsx @@ -42,6 +42,7 @@ import { useMarkNoticesSeen } from '../../../hooks/useMarkNoticesSeen'; import { Trans, useTranslation } from 'react-i18next'; import { ListSkeleton, Loading } from '../../../components/ui/loading'; import { Skeleton } from '../../../components/ui/skeleton'; +import { isCategoryAllowed } from '../../../shared/categoryTree'; /** * Main Product List View for the Users Producs @@ -222,11 +223,24 @@ export function MyProductsPage() { return map; }, [eventProductStatuses]); + const selectionEvent = events?.find((event) => event._id === eventSelectionEventId); + // The bazaar only takes items of the categories it allows + const isCategoryRefused = (productId: Id<'products'>) => { + const product = productsById.get(productId); + return ( + !!product && + !!selectionEvent && + !assignedProductIds.has(productId) && + !isCategoryAllowed(product.productCategory, selectionEvent.categories, categoryList) + ); + }; + const isSelectionLocked = (productId: Id<'products'>) => { if (!isEventSelectionMode) return false; const product = productsById.get(productId); if (!product) return false; if (product.sold) return true; + if (isCategoryRefused(productId)) return true; if (!assignedProductIds.has(productId)) return false; const status = eventProductStatusMap.get(productId as string); return status !== 'announced'; @@ -240,6 +254,10 @@ export function MyProductsPage() { toast.error(t('myProducts.soldCannotAdd')); return; } + if (isCategoryRefused(productId)) { + toast.error(t('myProducts.categoryNotAllowed', { event: selectionEvent?.title ?? '' })); + return; + } if (isSelectionLocked(productId)) { toast.error(t('myProducts.cannotUnregister')); return; diff --git a/src/pages/seller/products/ProductForm.tsx b/src/pages/seller/products/ProductForm.tsx index 86232a0b..a780f8a2 100644 --- a/src/pages/seller/products/ProductForm.tsx +++ b/src/pages/seller/products/ProductForm.tsx @@ -16,6 +16,7 @@ import { MyProductSelectEvents } from './components/MyProductSelectEvents'; import { isPriceInRange, PRODUCT_CONDITIONS } from '../../../shared/constants'; import { missingForEvent, resolveEventFeatures } from '../../../shared/eventFeatures'; import { getCategoryFields } from '../../../shared/categoryFields'; +import { isCategoryAllowed } from '../../../shared/categoryTree'; import { uploadImages } from '../../../lib/uploadImages'; import { isMinimumPriceBelowPrice, @@ -249,6 +250,15 @@ export function ProductForm() { } clearErrors('imageFiles'); + // The picker only offers what the bazaars take; a category chosen before stays + const refusing = chosenEvents.find( + (event) => !isCategoryAllowed(data.categoryId, event.categories, categoryList) + ); + if (refusing && !fixedData?.fixed) { + toast.error(t('form.categoryNotAllowedShort', { event: refusing.title })); + return; + } + const categoryFields = getCategoryFields(data.categoryId, categoryList); const missingField = categoryFields.find( (field) => requiredFields.includes(field.key) && !data.attributes?.[field.key]?.trim() @@ -436,6 +446,7 @@ export function ProductForm() { )} ({ eventTitles: ['Fahrradbörse'], }); -const frameNumber = getFieldsForLabel('Fahrräder')!.filter((field) => field.key === 'frameNumber'); +const frameNumber = [ + { + _id: 'frameNumber', + key: 'frameNumber', + label: 'Rahmennummer', + placeholder: 'z. B. WBK123456', + hint: 'Nicht gefunden? Schreib „nicht gefunden“ hinein – wir suchen sie vor Ort gemeinsam.', + short: false, + notFoundButton: true, + }, +]; function renderDialog(items = [item('Helm'), item('Schloss')]) { const onSave = vi.fn().mockResolvedValue(undefined); diff --git a/src/pages/seller/products/components/MyProductBasicInfo.tsx b/src/pages/seller/products/components/MyProductBasicInfo.tsx index 94f6dd10..8a9ec5ff 100644 --- a/src/pages/seller/products/components/MyProductBasicInfo.tsx +++ b/src/pages/seller/products/components/MyProductBasicInfo.tsx @@ -3,19 +3,15 @@ import { useFormContext } from 'react-hook-form'; import { Label } from '../../../../components/ui/label'; import { Input } from '../../../../components/ui/input'; import { Textarea } from '../../../../components/ui/text-area'; -import { - Select, - SelectContent, - SelectTrigger, - SelectValue, -} from '../../../../components/ui/select'; import { CONDITION_OPTIONS } from '../../../../constants/records'; import { PRODUCT_CONDITIONS } from '../../../../shared/constants'; import { api } from '../../../../lib/api/functions'; import { useQuery } from '../../../../lib/api/react'; import { cn } from '../../../../lib/utils'; import { MyProductCategoryFields, MyProductNegotiation } from './MyProductExtras'; -import { CategorySelectItems } from '../../../../components/products/CategorySelectItems'; +import { CategoryPicker } from '../../../../components/products/CategoryPicker'; +import { isCategoryAllowed } from '../../../../shared/categoryTree'; +import { categoryName } from '../../../../i18n/categories'; import { useTranslation } from 'react-i18next'; import { FormSkeleton, Loading } from '../../../../components/ui/loading'; import type { ReactNode } from 'react'; @@ -27,17 +23,20 @@ import type { ReactNode } from 'react'; * category fields a chosen bazaar requires. `fixedFields`: set while a bazaar keeps a * record of the item; title, category, price and these fields cannot change then. * `negotiation`: the negotiation box, or what to show instead (e.g. a button to open it). + * `bazaars`: the chosen bazaars; only categories all of them take can be picked. */ export function MyProductBasicInfo({ allowOffers = true, requiredFields, fixedFields, negotiation, + bazaars = [], }: { allowOffers?: boolean; requiredFields?: string[]; fixedFields?: string[]; negotiation?: ReactNode; + bazaars?: { title: string; categories?: string[] }[]; }) { const fixed = fixedFields !== undefined; const { t } = useTranslation('seller'); @@ -53,6 +52,18 @@ export function MyProductBasicInfo({ // Watch values for controlled components like Select const categoryId = watch('categoryId'); const condition = watch('condition'); + // Only categories every chosen bazaar takes + const restricting = bazaars.filter((event) => (event.categories?.length ?? 0) > 0); + const restricted = restricting.length > 0; + const isAllowed = (id: string) => + restricting.every((event) => isCategoryAllowed(id, event.categories, categoryList)); + const chosenCategory = categoryList?.find((category) => category._id === categoryId); + const refusedBy = + chosenCategory && !fixed + ? restricting.find( + (event) => !isCategoryAllowed(chosenCategory._id, event.categories, categoryList) + ) + : undefined; if (!categoryList) { return ( @@ -103,21 +114,36 @@ export function MyProductBasicInfo({
- - {errors.categoryId && {errors.categoryId.message as string}} + /> + {errors.categoryId ? ( + {errors.categoryId.message as string} + ) : refusedBy ? ( + + {t('form.categoryNotAllowed', { + category: categoryName(chosenCategory!), + event: refusedBy.title, + })} + + ) : ( + restricted && ( +

+ {t('form.categoriesOfBazaar', { + events: restricting.map((event) => event.title).join(', '), + })} +

+ ) + )}
diff --git a/src/shared/categoryFields.ts b/src/shared/categoryFields.ts index aefb7129..b505c1ad 100644 --- a/src/shared/categoryFields.ts +++ b/src/shared/categoryFields.ts @@ -1,214 +1,59 @@ /** * Extra item fields per product category (e.g. frame number for bikes, size for clothes). - * The values live on the product, so an item keeps them when it moves on to the next - * bazaar. Pure helpers only, so the frontend can import this file as well. + * Admins define the fields and pick them per category; the server sends each category with + * the fields its items have (`fieldList`, inherited from the main category). The values + * live on the product, so an item keeps them when it moves on to the next bazaar. + * Pure helpers only, so the frontend can import this file as well. */ export interface CategoryField { + /** Picked by categories, e.g. "clothingSize" */ + _id: string; + /** Under which the value is stored on the item; sizes share "size" */ key: string; - /** Translation of label, placeholder and hint: categoryFields. in src/locales */ - text: CategoryFieldText; label: string; + labelEn?: string; placeholder?: string; + placeholderEn?: string; hint?: string; - /** Longest value; sizes stay short so they fit on the labels */ - maxLength?: number; + hintEn?: string; + /** At most MAX_SHORT_LENGTH characters, so it fits on the labels (e.g. a size) */ + short: boolean; /** * Sellers may not find the value (e.g. a worn frame number): a button fills in the - * agreed text (categoryFields..notFoundValue), the same for everyone, so it can be + * agreed text (records:categoryFields.notFoundValue), the same for everyone, so it can be * filtered in the records (#299). A required field stays required. */ - notFoundButton?: boolean; + notFoundButton: boolean; } -export type CategoryFieldText = - | 'frameNumber' - | 'frameSize' - | 'wheelSize' - | 'bikeBrand' - | 'clothingSize' - | 'shoeSize' - | 'sportSize' - | 'brand' - | 'color' - | 'model'; - const MAX_VALUE_LENGTH = 120; -/** Longest size, e.g. "134/140" or "160 cm"; longer ones would not fit on the labels */ -export const MAX_SIZE_LENGTH = 7; +/** Longest short value, e.g. "134/140" or "160 cm"; longer ones would not fit on the labels */ +export const MAX_SHORT_LENGTH = 7; -export function fieldMaxLength(field: CategoryField): number { - return field.maxLength ?? MAX_VALUE_LENGTH; +export function fieldMaxLength(field: Pick): number { + return field.short ? MAX_SHORT_LENGTH : MAX_VALUE_LENGTH; } -const FRAME_NUMBER: CategoryField = { - key: 'frameNumber', - text: 'frameNumber', - label: 'Rahmennummer', - placeholder: 'z. B. WBK123456', - hint: 'Nicht gefunden? Schreib „nicht gefunden“ hinein – wir suchen sie vor Ort gemeinsam.', - notFoundButton: true, -}; -const FRAME_SIZE: CategoryField = { - key: 'frameSize', - text: 'frameSize', - label: 'Rahmengröße', - placeholder: 'z. B. 52 cm oder M', -}; -const WHEEL_SIZE: CategoryField = { - key: 'wheelSize', - text: 'wheelSize', - label: 'Laufradgröße', - placeholder: 'z. B. 28 Zoll', -}; -const BRAND: CategoryField = { key: 'brand', text: 'brand', label: 'Marke' }; -const BIKE_BRAND: CategoryField = { ...BRAND, text: 'bikeBrand', placeholder: 'z. B. Cube' }; -/** Helps to find an item again on site and to describe it, e.g. a bike for the police */ -const COLOR: CategoryField = { - key: 'color', - text: 'color', - label: 'Farbe', - placeholder: 'z. B. Rot', -}; -const CLOTHING_SIZE: CategoryField = { - key: 'size', - text: 'clothingSize', - label: 'Größe', - placeholder: 'z. B. M oder 128', - maxLength: MAX_SIZE_LENGTH, -}; -const SHOE_SIZE: CategoryField = { - key: 'size', - text: 'shoeSize', - label: 'Größe (EU)', - placeholder: 'z. B. 38', - maxLength: MAX_SIZE_LENGTH, -}; -const SPORT_SIZE: CategoryField = { - key: 'size', - text: 'sportSize', - label: 'Größe / Länge', - placeholder: 'z. B. 160 cm', - maxLength: MAX_SIZE_LENGTH, -}; -const MODEL: CategoryField = { key: 'model', text: 'model', label: 'Modell' }; - -/** - * The fields an admin can pick for a category, by `text`; one size at most, since all - * sizes share the key. Same list as SELECTABLE in backend/src/modules/category_fields.rs. - */ -export const SELECTABLE_FIELDS: CategoryField[] = [ - FRAME_NUMBER, - FRAME_SIZE, - WHEEL_SIZE, - BRAND, - COLOR, - CLOTHING_SIZE, - SHOE_SIZE, - SPORT_SIZE, - MODEL, -]; - -const BIKE_FIELDS = [FRAME_NUMBER, FRAME_SIZE, WHEEL_SIZE, BIKE_BRAND, COLOR]; -const CLOTHING_FIELDS = [CLOTHING_SIZE, BRAND, COLOR]; -const SHOE_FIELDS = [SHOE_SIZE, BRAND]; -const SPORT_FIELDS = [SPORT_SIZE, BRAND, COLOR]; -const ELECTRONICS_FIELDS = [BRAND, MODEL]; - -/** - * Category names are free text (admins create e.g. "Trekkingräder" or "E-Bikes / Pedelecs"), - * so fields are matched by keywords. The first matching rule wins. - */ -const FIELD_RULES: { match: RegExp; exclude?: RegExp; fields: CategoryField[] }[] = [ - { - // "rad" only as a whole word or word ending, so "Radio" does not count as a bike - match: /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i, - // No frame number: accessories, cycling clothes, trailers, child seats, unicycles - exclude: /zubehör|teile|bekleidung|helm|anhänger|schloss|sitz|einr[aä]d/i, - fields: BIKE_FIELDS, - }, - { match: /schuh|stiefel|sneaker/i, fields: SHOE_FIELDS }, - // "mode" only as a word or word ending ("Damenmode"), not in "Sondermodelle" - { match: /kleid|jacke|hose|\bmode\b|mode$|shirt|pullover/i, fields: CLOTHING_FIELDS }, - { match: /sport|\bski|snowboard/i, fields: SPORT_FIELDS }, - { - match: /elektron|handy|smartphone|computer|laptop|tablet|kamera|konsole/i, - fields: ELECTRONICS_FIELDS, - }, -]; - /** * Fields an organizer can make required for a bazaar, one per key. The same key means - * the same thing in every category (e.g. "brand"), so one choice covers all of them. + * the same thing in every category (e.g. "size"), so one choice covers all of them. */ -export const REQUIRABLE_FIELDS: CategoryField[] = SELECTABLE_FIELDS.filter( - (field, index) => SELECTABLE_FIELDS.findIndex((other) => other.key === field.key) === index -); - -/** - * Fields as ids of SELECTABLE_FIELDS, e.g. to start an admin's choice from those of the - * name; a variant like the bike brand becomes the plain field with its key. - */ -export function selectableIds(fields: CategoryField[]): string[] { - const ids = fields.map( - (field) => - ( - SELECTABLE_FIELDS.find((s) => s.text === field.text) ?? - SELECTABLE_FIELDS.find((s) => s.key === field.key) - )?.text +export function requirableFields(definitions: readonly CategoryField[] | undefined) { + return (definitions ?? []).filter( + (field, index, all) => all.findIndex((other) => other.key === field.key) === index ); - return SELECTABLE_FIELDS.map((field) => field.text).filter((id) => ids.includes(id)); } -export const REQUIRABLE_FIELD_KEYS = REQUIRABLE_FIELDS.map((field) => field.key); +type CategoryWithFields = { _id: string; fieldList?: CategoryField[] }; -/** - * Fields for a single category label, without looking at parent categories; undefined - * when no rule speaks about it. A label a rule excludes on purpose ("Fahrradanhänger") has - * no fields: as a sub-category of "Fahrräder" it must not inherit the frame number. - */ -export function getFieldsForLabel(label: string): CategoryField[] | undefined { - const name = label.trim(); - let excluded = false; - for (const rule of FIELD_RULES) { - if (!rule.match.test(name)) continue; - if (!rule.exclude?.test(name)) return rule.fields; - excluded = true; - } - return excluded ? [] : undefined; -} - -type CategoryLike = { - _id: string; - label: string; - parentCategory?: string; - /** Picked by an admin (ids of SELECTABLE_FIELDS); unset: by the name */ - fields?: string[]; -}; - -/** - * Fields for a category: the ones an admin picked, else those of its name. Sub-categories - * without either inherit the fields of their parent. - */ +/** The fields of a category, as the server resolved them. */ export function getCategoryFields( categoryId: string | undefined, - categories: CategoryLike[] | undefined + categories: readonly CategoryWithFields[] | undefined ): CategoryField[] { if (!categoryId || !categories) return []; - const byId = new Map(categories.map((c) => [c._id, c])); - const seen = new Set(); - let current = byId.get(categoryId); - while (current && !seen.has(current._id)) { - seen.add(current._id); - if (current.fields) { - const picked = current.fields; - return SELECTABLE_FIELDS.filter((field) => picked.includes(field.text)); - } - const fields = getFieldsForLabel(current.label); - if (fields) return fields; - current = current.parentCategory ? byId.get(current.parentCategory) : undefined; - } - return []; + return categories.find((category) => category._id === categoryId)?.fieldList ?? []; } /** @@ -228,13 +73,27 @@ export function sanitizeAttributes( return Object.keys(result).length > 0 ? result : undefined; } +/** A value of an item with the name of its field, as the server describes it too. */ +export interface DescribedAttribute { + label: string; + labelEn?: string; + /** The id of the field */ + text: string; + value: string; +} + /** Label/value pairs for display, in the order the category defines. */ export function describeAttributes( fields: CategoryField[], attributes: Record | undefined -): { label: string; text: CategoryFieldText; value: string }[] { +): DescribedAttribute[] { if (!attributes) return []; return fields .filter((field) => attributes[field.key]) - .map((field) => ({ label: field.label, text: field.text, value: attributes[field.key] })); + .map((field) => ({ + label: field.label, + labelEn: field.labelEn, + text: field._id, + value: attributes[field.key], + })); } diff --git a/src/shared/categoryTree.test.ts b/src/shared/categoryTree.test.ts index aa0e41ba..1ede93dc 100644 --- a/src/shared/categoryTree.test.ts +++ b/src/shared/categoryTree.test.ts @@ -1,5 +1,14 @@ import { describe, expect, it } from 'vitest'; -import { collapseSubcategories, groupCategories, withSubcategories } from './categoryTree'; +import { + collapseSubcategories, + compactSelection, + expandCategories, + expandSelection, + groupCategories, + isCategoryAllowed, + isForItems, + withSubcategories, +} from './categoryTree'; const categories = [ { _id: 'clothes' }, @@ -40,4 +49,30 @@ describe('category tree', () => { expect(collapseSubcategories(['bikes', 'cargo'], categories)).toEqual(['bikes', 'cargo']); expect(collapseSubcategories(['cargo', 'trailers'], categories)).toEqual(['cargo', 'trailers']); }); + + it('a bazaar stores a main category when all its sub-categories are chosen', () => { + const tree = categories.filter((category) => category._id !== 'bells'); + expect([...expandSelection(['bikes', 'clothes'], tree)]).toEqual([ + 'clothes', + 'cargo', + 'trailers', + ]); + expect(compactSelection(new Set(['clothes', 'cargo', 'trailers']), tree)).toEqual([ + 'clothes', + 'bikes', + ]); + expect(compactSelection(new Set(['cargo']), tree)).toEqual(['cargo']); + expect(expandCategories(['bikes'], tree)).toEqual(['bikes', 'cargo', 'trailers']); + }); + + it('a bazaar takes a category it allows or whose main category it allows', () => { + expect(isCategoryAllowed('cargo', ['bikes'], categories)).toBe(true); + expect(isCategoryAllowed('cargo', ['cargo'], categories)).toBe(true); + expect(isCategoryAllowed('trailers', ['cargo'], categories)).toBe(false); + expect(isCategoryAllowed('clothes', ['bikes'], categories)).toBe(false); + // Without a list it takes everything + expect(isCategoryAllowed('clothes', [], categories)).toBe(true); + expect(isForItems('bikes', categories)).toBe(false); + expect(isForItems('cargo', categories)).toBe(true); + }); }); diff --git a/src/shared/categoryTree.ts b/src/shared/categoryTree.ts index c340605b..b07fae9a 100644 --- a/src/shared/categoryTree.ts +++ b/src/shared/categoryTree.ts @@ -62,3 +62,84 @@ export function collapseSubcategories( } return ids.filter((id) => !covered.has(id)); } + +/** The ids and the sub-categories of the main categories among them. */ +export function expandCategories( + ids: readonly string[], + categories: readonly TreeCategory[] | undefined +): string[] { + const result = new Set(ids); + for (const category of categories ?? []) { + if (category.parentCategory && ids.includes(category.parentCategory)) { + result.add(category._id); + } + } + return [...result]; +} + +/** + * Whether a bazaar takes items of this category: it allows the category or its main + * category. Bazaars without a list take everything. Same rule as the backend + * (event_products::assert_category_allowed). + */ +export function isCategoryAllowed( + categoryId: string | undefined, + allowed: readonly string[] | undefined, + categories: readonly TreeCategory[] | undefined +): boolean { + if (!categoryId || !allowed || allowed.length === 0) return true; + if (allowed.includes(categoryId)) return true; + const parent = categories?.find((category) => category._id === categoryId)?.parentCategory; + return !!parent && allowed.includes(parent); +} + +/** Whether items can go into the category: one with sub-categories only groups them. */ +export function isForItems( + categoryId: string, + categories: readonly TreeCategory[] | undefined +): boolean { + return !(categories ?? []).some((category) => category.parentCategory === categoryId); +} + +/** + * The categories a bazaar allows, one per category items can go into: a stored main + * category stands for all its sub-categories. + */ +export function expandSelection( + stored: readonly string[], + categories: readonly TreeCategory[] +): Set { + const result = new Set(); + for (const { category, children } of groupCategories(categories)) { + const all = stored.includes(category._id); + if (children.length === 0) { + if (all) result.add(category._id); + continue; + } + for (const child of children) { + if (all || stored.includes(child._id)) result.add(child._id); + } + } + return result; +} + +/** + * What a bazaar stores: a main category when all its sub-categories are chosen, so ones + * an admin adds later are allowed too; otherwise the chosen sub-categories. + */ +export function compactSelection( + selected: ReadonlySet, + categories: readonly TreeCategory[] +): string[] { + const result: string[] = []; + for (const { category, children } of groupCategories(categories)) { + if (children.length === 0) { + if (selected.has(category._id)) result.push(category._id); + } else if (children.every((child) => selected.has(child._id))) { + result.push(category._id); + } else { + result.push(...children.filter((child) => selected.has(child._id)).map((c) => c._id)); + } + } + return result; +} diff --git a/src/shared/eventFeatures.test.ts b/src/shared/eventFeatures.test.ts index fb5c3ec8..94a33f90 100644 --- a/src/shared/eventFeatures.test.ts +++ b/src/shared/eventFeatures.test.ts @@ -2,7 +2,9 @@ import { describe, expect, test } from 'vitest'; import { describeAttributes, getCategoryFields, - getFieldsForLabel, + fieldMaxLength, + requirableFields, + type CategoryField, sanitizeAttributes, } from './categoryFields'; import { @@ -15,115 +17,62 @@ import { resolveEventFeatures, } from './eventFeatures'; -const keys = (label: string) => getFieldsForLabel(label)?.map((field) => field.key); -const BIKE_KEYS = ['frameNumber', 'frameSize', 'wheelSize', 'brand', 'color']; - -describe('category fields by keyword', () => { - test.each([ - 'Fahrräder', - 'Fahrrad', - 'Cityräder & Hollandräder', - 'Kinder- & Jugendräder', - 'Falträder & Klappräder', - 'E-Bikes / Pedelecs', - 'Mountainbikes (MTB)', - 'Trekkingräder', - 'Rennräder & Gravelbikes', - 'BMX & Dirtbikes', - 'Laufrad', - // The default categories for bikes and children's vehicles (#300) - 'Kinderfahrräder', - 'Laufräder', - 'Lastenräder', - 'E-Bikes & Pedelecs', - ])('"%s" gets the bike fields', (label) => { - expect(keys(label)).toEqual(BIKE_KEYS); - }); - - // Same cases as in backend/src/modules/category_fields.rs - test.each([ - 'Radio & HiFi', - 'Fahrradzubehör', - 'Fahrradteile', - 'Fahrradhelme', - 'Sonstiges', - 'Roller & Scooter', - 'Einräder', - 'Einrad', - 'Bobbycars & Rutschfahrzeuge', - 'Fahrradanhänger', - 'Fahrrad-Kindersitze', - ])('"%s" gets no bike fields', (label) => { - expect(keys(label) ?? []).toEqual([]); +/** A field as admins define it (category_field_definitions). */ +const field = (id: string, label: string, extra: Partial = {}): CategoryField => ({ + _id: id, + key: id, + label, + short: false, + notFoundButton: false, + ...extra, +}); +const FRAME_NUMBER = field('frameNumber', 'Rahmennummer', { labelEn: 'Frame number' }); +const BRAND = field('brand', 'Marke'); +const SIZE = field('clothingSize', 'Größe', { key: 'size', short: true }); + +describe('category fields', () => { + test('come with the category, as the server resolved them', () => { + const categories = [{ _id: 'bikes', fieldList: [FRAME_NUMBER, BRAND] }, { _id: 'books' }]; + expect(getCategoryFields('bikes', categories)).toEqual([FRAME_NUMBER, BRAND]); + expect(getCategoryFields('books', categories)).toEqual([]); + expect(getCategoryFields('gone', categories)).toEqual([]); + expect(getCategoryFields(undefined, categories)).toEqual([]); + expect(getCategoryFields('bikes', undefined)).toEqual([]); }); - test('excluded on purpose means no fields, also below "Fahrräder"', () => { - expect(keys('Fahrradanhänger')).toEqual([]); - expect(keys('Radio & HiFi')).toBeUndefined(); - const categories = [ - { _id: 'bikes', label: 'Fahrräder' }, - { _id: 'trailers', label: 'Fahrradanhänger', parentCategory: 'bikes' }, - { _id: 'clothes', label: 'Fahrradbekleidung', parentCategory: 'bikes' }, - { _id: 'kids', label: 'Für Kinder', parentCategory: 'bikes' }, - ]; - expect(getCategoryFields('trailers', categories)).toEqual([]); - expect(getCategoryFields('clothes', categories).map((f) => f.key)).toEqual([ - 'size', - 'brand', - 'color', + test('one per key can be required, short ones fit on the labels', () => { + const shoeSize = field('shoeSize', 'Größe (EU)', { key: 'size', short: true }); + expect(requirableFields([FRAME_NUMBER, SIZE, shoeSize]).map((f) => f._id)).toEqual([ + 'frameNumber', + 'clothingSize', ]); - expect(getCategoryFields('kids', categories).map((f) => f.key)).toEqual(BIKE_KEYS); - }); - - test('cycling clothes count as clothing, sports shoes as shoes', () => { - expect(keys('Fahrradbekleidung')).toEqual(['size', 'brand', 'color']); - expect(keys('Skischuhe')).toEqual(['size', 'brand']); - expect(getFieldsForLabel('Sportschuhe')?.[0].label).toBe('Größe (EU)'); - expect(getFieldsForLabel('Kleidung')?.[0].label).toBe('Größe'); - expect(getFieldsForLabel('Damenmode')?.[0].label).toBe('Größe'); - expect(getFieldsForLabel('Sondermodelle')).toBeUndefined(); - expect(getFieldsForLabel('Wintersport')?.[0].label).toBe('Größe / Länge'); - expect(keys('Elektronik')).toEqual(['brand', 'model']); - }); - - test('categories without a rule have no fields', () => { - expect(getFieldsForLabel('Bücher')).toBeUndefined(); - expect(getFieldsForLabel('Sonstiges')).toBeUndefined(); - }); - - test('sub-categories inherit the fields of their parent', () => { - const categories = [ - { _id: 'bikes', label: 'Räder' }, - { _id: 'special', label: 'Sondermodelle', parentCategory: 'bikes' }, - { _id: 'loop', label: 'Loop', parentCategory: 'loop' }, - ]; - expect(getCategoryFields('special', categories).map((f) => f.key)).toEqual(BIKE_KEYS); - expect(getCategoryFields('loop', categories)).toEqual([]); - expect(getCategoryFields(undefined, categories)).toEqual([]); - expect(getCategoryFields('bikes', undefined)).toEqual([]); + expect(requirableFields(undefined)).toEqual([]); + expect(fieldMaxLength(SIZE)).toBe(7); + expect(fieldMaxLength(BRAND)).toBe(120); }); test('sanitize keeps known, non-empty, trimmed and shortened values', () => { - const fields = getFieldsForLabel('Trekkingräder')!; + const fields = [FRAME_NUMBER, BRAND, SIZE]; expect( sanitizeAttributes(fields, { frameNumber: ' WBK 1 ', brand: '', colour: 'rot', - frameSize: 'x'.repeat(200), + size: '134/140/146', }) - ).toEqual({ frameNumber: 'WBK 1', frameSize: 'x'.repeat(120) }); + ).toEqual({ frameNumber: 'WBK 1', size: '134/140' }); expect(sanitizeAttributes(fields, { brand: ' ' })).toBeUndefined(); expect(sanitizeAttributes(fields, undefined)).toBeUndefined(); }); - test('describe lists values in category order with labels', () => { - const fields = getFieldsForLabel('Trekkingräder')!; - expect(describeAttributes(fields, { brand: 'Cube', frameNumber: 'WBK 1' })).toEqual([ - { label: 'Rahmennummer', text: 'frameNumber', value: 'WBK 1' }, - { label: 'Marke', text: 'bikeBrand', value: 'Cube' }, + test('describe lists values in category order with both names', () => { + expect( + describeAttributes([FRAME_NUMBER, BRAND], { brand: 'Cube', frameNumber: 'WBK 1' }) + ).toEqual([ + { label: 'Rahmennummer', labelEn: 'Frame number', text: 'frameNumber', value: 'WBK 1' }, + { label: 'Marke', labelEn: undefined, text: 'brand', value: 'Cube' }, ]); - expect(describeAttributes(fields, undefined)).toEqual([]); + expect(describeAttributes([BRAND], undefined)).toEqual([]); }); }); diff --git a/src/tests/auth/features.spec.ts b/src/tests/auth/features.spec.ts index 13a0787a..091e9461 100644 --- a/src/tests/auth/features.spec.ts +++ b/src/tests/auth/features.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type Page } from '@playwright/test'; -import { runBackend } from '../utils'; +import { pickCategory, runBackend } from '../utils'; import { BUYER, ORGANIZER, @@ -278,8 +278,7 @@ test.describe('organizer tools', () => { const dialog = page.getByRole('dialog'); await dialog.getByLabel('Titel *').fill(itemTitle); await dialog.getByRole('radio', { name: 'Gebraucht', exact: true }).click(); - await dialog.locator('#categoryId').click(); - await page.getByRole('option', { name: 'Fahrräder', exact: true }).click(); + await pickCategory(page, 'Fahrräder', 'Trekkingräder', dialog); await dialog.getByLabel('Rahmennummer').fill('BAT 123'); await dialog.getByLabel('Preis (€) *').fill('140'); await dialog.getByRole('button', { name: 'Speichern', exact: true }).click(); @@ -319,15 +318,13 @@ test.describe('category fields', () => { test('bike categories show bike fields in the product form, others do not', async ({ page }) => { await login(page, SELLER); await page.goto('/products/new'); - await page.locator('#categoryId').click(); - await page.getByRole('option', { name: 'Fahrräder', exact: true }).click(); + await pickCategory(page, 'Fahrräder', 'Trekkingräder'); await expect(page.getByLabel('Rahmennummer')).toBeVisible(); await expect(page.getByText(/Nicht gefunden\? Schreib „nicht gefunden“ hinein/)).toBeVisible(); await page.getByRole('button', { name: 'Nicht gefunden' }).click(); await expect(page.getByLabel('Rahmennummer')).toHaveValue('nicht gefunden'); - await page.locator('#categoryId').click(); - await page.getByRole('option', { name: 'Bücher', exact: true }).click(); + await pickCategory(page, 'Bücher', 'Romane'); await expect(page.getByLabel('Rahmennummer')).toHaveCount(0); }); }); diff --git a/src/tests/auth/products.spec.ts b/src/tests/auth/products.spec.ts index e22a55e5..965bf048 100644 --- a/src/tests/auth/products.spec.ts +++ b/src/tests/auth/products.spec.ts @@ -1,7 +1,7 @@ import { test, expect, type Page } from '@playwright/test'; import { approveEventByTitle } from '../helpers/eventApproval'; import { fillEventWizard } from '../helpers/eventForm'; -import { isOverview } from '../utils'; +import { isOverview, pickCategory } from '../utils'; test.describe('product inventory flow as co-organizer', () => { test('seller creates products, adds to event, co-organizer manages inventory', async ({ @@ -150,9 +150,8 @@ async function createProductWithEvent( await page.getByRole('radio', { name: 'Gebraucht, wie neu' }).click(); await expect(page.getByRole('radio', { name: 'Gebraucht, wie neu' })).toBeChecked(); - await page.getByLabel('Kategorie *').click(); - await page.getByRole('option', { name: 'Sport', exact: true }).click(); - await expect(page.locator('#categoryId')).toContainText('Sport'); + await pickCategory(page, 'Sport', 'Wintersport'); + await expect(page.locator('#categoryId')).toContainText('Sport › Wintersport'); await page.getByLabel('Preis (€) *').fill('25'); diff --git a/src/tests/public/onboarding-trigger.spec.ts b/src/tests/public/onboarding-trigger.spec.ts index c348982e..8f4ef287 100644 --- a/src/tests/public/onboarding-trigger.spec.ts +++ b/src/tests/public/onboarding-trigger.spec.ts @@ -1,5 +1,5 @@ import { test, expect, type Page } from '@playwright/test'; -import { runBackend } from '../utils'; +import { pickCategory, runBackend } from '../utils'; test.describe.configure({ mode: 'serial' }); @@ -134,8 +134,7 @@ async function fillAndCreateProduct(page: Page, eventTitle: string, productTitle await page.getByRole('radio', { name: 'Gebraucht, wie neu' }).click(); - await page.getByLabel('Kategorie *').click(); - await page.getByRole('option', { name: 'Sport', exact: true }).click(); + await pickCategory(page, 'Sport', 'Wintersport'); await page.getByLabel('Preis (€) *').fill('25'); diff --git a/src/tests/utils.ts b/src/tests/utils.ts index 301d78d1..6efba7b6 100644 --- a/src/tests/utils.ts +++ b/src/tests/utils.ts @@ -27,3 +27,23 @@ export function seedBackend(...flags: string[]) { /** Where the login page leads: the overview (`/`, src/pages/dashboard) */ export const isOverview = (url: URL) => url.pathname === '/'; + +/** + * Picks the category of an item: opens the picker, then the main category, then the + * sub-category (items go into sub-categories). + */ +export async function pickCategory( + page: import('@playwright/test').Page, + main: string, + sub: string, + scope: import('@playwright/test').Locator | import('@playwright/test').Page = page +) { + await scope.locator('#categoryId').click(); + await page.getByRole('menu').waitFor(); + const item = page.getByRole('menuitem', { name: sub, exact: true }); + // The only main category left, e.g. at a bike sale, is open already + if (!(await item.isVisible())) { + await page.getByRole('menuitem', { name: new RegExp(`^${main}`) }).click(); + } + await item.click(); +}