diff --git a/backend/migrations/0032_more_categories.sql b/backend/migrations/0032_more_categories.sql new file mode 100644 index 00000000..05623aa5 --- /dev/null +++ b/backend/migrations/0032_more_categories.sql @@ -0,0 +1,107 @@ +-- 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, '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) +SELECT d.de, jsonb_build_object('en', d.en) +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/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/migrations/0034_category_field_definitions.sql b/backend/migrations/0034_category_field_definitions.sql new file mode 100644 index 00000000..87089518 --- /dev/null +++ b/backend/migrations/0034_category_field_definitions.sql @@ -0,0 +1,209 @@ +-- Extra fields become data an admin edits (#300): the definitions in their own table, the +-- categories name the ones they use. Plus the default tree for bike sales and children's +-- bazaars: more kinds of bikes, "Baby & Kind", "Freizeit & Hobby" and a "Weitere …" in +-- every main category, since items now go into the sub-categories. + +CREATE TABLE category_field_definitions ( + -- Picked by categories (categories.fields), e.g. 'clothingSize' + id text PRIMARY KEY, + -- Under which the value is stored on the item; sizes share 'size' + key text NOT NULL, + label text NOT NULL, + label_en text, + placeholder text, + placeholder_en text, + hint text, + hint_en text, + -- At most 7 characters, so it fits on the labels (e.g. a size) + short boolean NOT NULL DEFAULT false, + -- Sellers may enter the agreed "not found", e.g. for a worn frame number + not_found_button boolean NOT NULL DEFAULT false, + position integer NOT NULL DEFAULT 0, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- The fields so far, with the texts of src/locales//records.json +INSERT INTO category_field_definitions + (id, key, label, label_en, placeholder, placeholder_en, hint, hint_en, short, not_found_button, position) +VALUES + ('frameNumber', 'frameNumber', 'Rahmennummer', 'Frame number', 'z. B. WBK123456', 'e.g. WBK123456', + 'Nicht gefunden? Schreib „nicht gefunden“ hinein – wir suchen sie vor Ort gemeinsam.', + 'Can''t find it? Enter “not found” – we''ll look for it together on site.', false, true, 1), + ('frameSize', 'frameSize', 'Rahmengröße', 'Frame size', 'z. B. 52 cm oder M', 'e.g. 52 cm or M', NULL, NULL, false, false, 2), + ('wheelSize', 'wheelSize', 'Laufradgröße', 'Wheel size', 'z. B. 28 Zoll', 'e.g. 28 inch', NULL, NULL, false, false, 3), + ('brand', 'brand', 'Marke', 'Brand', NULL, NULL, NULL, NULL, false, false, 7), + ('color', 'color', 'Farbe', 'Color', 'z. B. Rot', 'e.g. red', NULL, NULL, false, false, 8), + ('clothingSize', 'size', 'Größe', 'Size', 'z. B. M oder 128', 'e.g. M or 128', NULL, NULL, true, false, 4), + ('shoeSize', 'size', 'Größe (EU)', 'Size (EU)', 'z. B. 38', 'e.g. 38', NULL, NULL, true, false, 5), + ('sportSize', 'size', 'Größe / Länge', 'Size / length', 'z. B. 160 cm', 'e.g. 160 cm', NULL, NULL, true, false, 6), + ('model', 'model', 'Modell', 'Model', NULL, NULL, NULL, NULL, false, false, 9); + +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, 'Babykleidung', 'Baby clothes', 'Kleidung', false), + (2, 'Kinderkleidung', 'Children''s clothes', 'Kleidung', false), + (3, 'Damenkleidung', 'Women''s clothes', 'Kleidung', false), + (4, 'Herrenkleidung', 'Men''s clothes', 'Kleidung', false), + (5, 'Umstandsmode', 'Maternity wear', 'Kleidung', false), + (6, 'Schuhe', 'Shoes', NULL, false), + (7, 'Kinderschuhe', 'Children''s shoes', 'Schuhe', false), + (8, 'Damenschuhe', 'Women''s shoes', 'Schuhe', false), + (9, 'Herrenschuhe', 'Men''s shoes', 'Schuhe', false), + (10, 'Sportschuhe', 'Sports shoes', 'Schuhe', false), + (11, 'Sport', 'Sports', NULL, false), + (12, 'Wintersport', 'Winter sports', 'Sport', false), + (13, 'Skischuhe', 'Ski boots', 'Sport', false), + (14, 'Sportbekleidung', 'Sportswear', 'Sport', false), + (15, 'Helme & Protektoren', 'Helmets & protectors', 'Sport', false), + (16, 'Ballsport', 'Ball sports', 'Sport', false), + (17, 'Fitness', 'Fitness', 'Sport', false), + (18, 'Camping & Outdoor', 'Camping & outdoor', 'Sport', false), + (19, 'Weitere Sportarten', 'Other sports', 'Sport', true), + (20, 'Fahrräder', 'Bikes', NULL, false), + (21, 'Cityräder & Hollandräder', 'City & Dutch bikes', 'Fahrräder', true), + (22, 'Trekkingräder', 'Trekking bikes', 'Fahrräder', true), + (23, 'Mountainbikes (MTB)', 'Mountain bikes (MTB)', 'Fahrräder', true), + (24, 'Rennräder & Gravelbikes', 'Road & gravel bikes', 'Fahrräder', true), + (25, 'BMX & Dirtbikes', 'BMX & dirt bikes', 'Fahrräder', true), + (26, 'Falträder & Klappräder', 'Folding bikes', 'Fahrräder', true), + (27, 'Kinder- & Jugendräder', 'Children''s & youth bikes', 'Fahrräder', false), + (28, 'E-Bikes & Pedelecs', 'E-bikes', 'Fahrräder', false), + (29, 'Lastenräder', 'Cargo bikes', 'Fahrräder', false), + (30, 'Fahrradanhänger', 'Bike trailers', 'Fahrräder', false), + (31, 'Fahrrad-Kindersitze', 'Child bike seats', 'Fahrräder', false), + (32, 'Fahrradzubehör', 'Bike accessories', 'Fahrräder', false), + (33, 'Kinderfahrzeuge', 'Children''s vehicles', NULL, false), + (34, 'Laufräder', 'Balance bikes', 'Kinderfahrzeuge', false), + (35, 'Roller & Scooter', 'Scooters', 'Kinderfahrzeuge', false), + (36, 'Einräder', 'Unicycles', 'Kinderfahrzeuge', false), + (37, 'Bobbycars & Rutschfahrzeuge', 'Ride-on toys', 'Kinderfahrzeuge', false), + (38, 'Baby & Kind', 'Baby & child', NULL, true), + (39, 'Kinderwagen & Buggys', 'Prams & buggies', 'Baby & Kind', false), + (40, 'Autokindersitze', 'Car seats', 'Baby & Kind', true), + (41, 'Babyausstattung', 'Baby gear', 'Baby & Kind', true), + (42, 'Elektronik', 'Electronics', NULL, false), + (43, 'Handys & Smartphones', 'Mobile phones', 'Elektronik', false), + (44, 'Computer & Tablets', 'Computers & tablets', 'Elektronik', false), + (45, 'Foto & Kamera', 'Photo & camera', 'Elektronik', false), + (46, 'Konsolen & Videospiele', 'Consoles & video games', 'Elektronik', false), + (47, 'Audio & HiFi', 'Audio & hi-fi', 'Elektronik', false), + (48, 'Weitere Elektronik', 'Other electronics', 'Elektronik', true), + (49, 'Bücher', 'Books', NULL, false), + (50, 'Kinder- & Jugendbücher', 'Children''s & youth books', 'Bücher', false), + (51, 'Romane', 'Novels', 'Bücher', false), + (52, 'Sachbücher', 'Non-fiction', 'Bücher', false), + (53, 'Kochbücher', 'Cookbooks', 'Bücher', false), + (54, 'Comics', 'Comics', 'Bücher', false), + (55, 'Weitere Bücher', 'Other books', 'Bücher', true), + (56, 'Spielzeug', 'Toys', NULL, false), + (57, 'Babyspielzeug', 'Baby toys', 'Spielzeug', false), + (58, 'Puppen & Plüsch', 'Dolls & plush', 'Spielzeug', false), + (59, 'Lego & Bausteine', 'Lego & building blocks', 'Spielzeug', false), + (60, 'Spiele & Puzzles', 'Games & puzzles', 'Spielzeug', false), + (61, 'Outdoor-Spielzeug', 'Outdoor toys', 'Spielzeug', false), + (62, 'Weiteres Spielzeug', 'Other toys', 'Spielzeug', true), + (63, 'Möbel', 'Furniture', NULL, false), + (64, 'Kindermöbel', 'Children''s furniture', 'Möbel', false), + (65, 'Wohnzimmermöbel', 'Living room', 'Möbel', false), + (66, 'Schlafzimmermöbel', 'Bedroom', 'Möbel', false), + (67, 'Büromöbel', 'Office furniture', 'Möbel', false), + (68, 'Gartenmöbel', 'Garden furniture', 'Möbel', false), + (69, 'Weitere Möbel', 'Other furniture', 'Möbel', true), + (70, 'Haushalt', 'Household', NULL, false), + (71, 'Küche & Kochen', 'Kitchen & cooking', 'Haushalt', false), + (72, 'Dekoration', 'Decoration', 'Haushalt', false), + (73, 'Heimtextilien', 'Home textiles', 'Haushalt', false), + (74, 'Werkzeug & Garten', 'Tools & garden', 'Haushalt', false), + (75, 'Weiteres für den Haushalt', 'Other household goods', 'Haushalt', true), + (76, 'Accessoires', 'Accessories', NULL, false), + (77, 'Taschen & Rucksäcke', 'Bags & backpacks', 'Accessoires', false), + (78, 'Schmuck & Uhren', 'Jewellery & watches', 'Accessoires', false), + (79, 'Mützen & Schals', 'Hats & scarves', 'Accessoires', false), + (80, 'Sonnenbrillen', 'Sunglasses', 'Accessoires', false), + (81, 'Gürtel', 'Belts', 'Accessoires', false), + (82, 'Weitere Accessoires', 'Other accessories', 'Accessoires', true), + (83, 'Freizeit & Hobby', 'Leisure & hobbies', NULL, true), + (84, 'Musikinstrumente', 'Musical instruments', 'Freizeit & Hobby', false), + (85, 'Filme & Musik', 'Films & music', 'Freizeit & Hobby', false), + (86, 'Basteln & Handarbeit', 'Crafts & needlework', 'Freizeit & Hobby', false), + (87, 'Sammeln', 'Collectibles', 'Freizeit & Hobby', false), + (88, 'Sonstiges', 'Other', NULL, false); + +-- Renamed defaults, with their English name if it is still the default one +UPDATE categories c +SET label = r.new, updated_at = now(), + translations = CASE WHEN c.translations->>'en' = r.old_en + THEN jsonb_set(c.translations, '{en}', to_jsonb(r.new_en)) ELSE c.translations END +FROM (VALUES + ('Kinderfahrräder', 'Kinder- & Jugendräder', 'Children''s bikes', 'Children''s & youth bikes'), + ('Ski & Snowboard', 'Wintersport', 'Skis & snowboards', 'Winter sports'), + ('Kinderbücher', 'Kinder- & Jugendbücher', 'Children''s books', 'Children''s & youth books'), + ('Brett- & Kartenspiele', 'Spiele & Puzzles', 'Board & card games', 'Games & puzzles') +) AS r (old, new, old_en, new_en) +WHERE c.label = r.old + AND EXISTS (SELECT 1 FROM categories WHERE label = 'Fahrräder') + AND NOT EXISTS (SELECT 1 FROM categories o WHERE lower(o.label) = lower(r.new)); + +-- Only the added ones, where the default categories are in use +INSERT INTO categories (label, translations) +SELECT d.de, jsonb_build_object('en', d.en) +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)); + +-- Default sub-categories under their main category: those on top, and those that moved +-- (prams from "Kinderfahrzeuge" to "Baby & Kind", hobbies from "Sonstiges") +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.id <> p.id + AND NOT EXISTS (SELECT 1 FROM categories s WHERE s.parent_id = c.id) + AND (c.parent_id IS NULL + OR (c.label = 'Kinderwagen & Buggys' + AND c.parent_id = (SELECT id FROM categories WHERE label = 'Kinderfahrzeuge')) + OR (d.parent = 'Freizeit & Hobby' + AND c.parent_id = (SELECT id FROM categories WHERE label = 'Sonstiges'))); + +-- The fields so far followed the name; now each category names its own. Same rules as +-- before (the first that matches wins; "Fahrradanhänger" and the like have none). +UPDATE categories +SET fields = CASE + WHEN label ~* 'fahrr|räder|\yrad\y|rad$|bike|pedelec|\ymtb\y|bmx' + AND label !~* 'zubehör|teile|bekleidung|helm|anhänger|schloss|sitz|einr(a|ä)d' + THEN '{frameNumber,frameSize,wheelSize,brand,color}'::text[] + WHEN label ~* 'schuh|stiefel|sneaker' THEN '{shoeSize,brand}'::text[] + WHEN label ~* 'kleid|jacke|hose|\ymode\y|mode$|shirt|pullover' + THEN '{clothingSize,brand,color}'::text[] + WHEN label ~* 'sport|\yski|snowboard' THEN '{sportSize,brand,color}'::text[] + WHEN label ~* 'elektron|handy|smartphone|computer|laptop|tablet|kamera|konsole' + THEN '{brand,model}'::text[] + WHEN label ~* 'fahrr|räder|\yrad\y|rad$|bike|pedelec|\ymtb\y|bmx' THEN '{}'::text[] +END +WHERE fields IS NULL; + +-- A sub-category with the fields of its main category takes them from there, so a change +-- of the main category reaches it +UPDATE categories c +SET fields = NULL +FROM categories p +WHERE c.parent_id = p.id AND c.fields IS NOT NULL AND c.fields = p.fields; +-- No fields on top, or below a main category without any: nothing to pick +UPDATE categories c +SET fields = NULL +WHERE c.fields = '{}' + AND (c.parent_id IS NULL + OR EXISTS (SELECT 1 FROM categories p WHERE p.id = c.parent_id + AND (p.fields IS NULL OR p.fields = '{}'))); + +-- Lists follow the creation time: the default ones in their order +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/demo/catalog.rs b/backend/src/demo/catalog.rs index f56f2a29..62508114 100644 --- a/backend/src/demo/catalog.rs +++ b/backend/src/demo/catalog.rs @@ -83,6 +83,7 @@ pub enum Cat { Household, Accessories, Other, + BabyKids, } impl Cat { @@ -98,7 +99,7 @@ impl Cat { Self::Toys => "toys", Self::Furniture => "chair", Self::Household | Self::Accessories => "tote", - Self::Other => "wooden_train", + Self::Other | Self::BabyKids => "wooden_train", } } } @@ -116,8 +117,76 @@ pub const CATEGORIES: &[(Cat, Text)] = &[ (Cat::Household, t("Haushalt", "Household")), (Cat::Accessories, t("Accessoires", "Accessories")), (Cat::Other, t("Sonstiges", "Other")), + (Cat::BabyKids, t("Baby & Kind", "Baby & child")), ]; +/// The sub-category of a demo item (German label of a default category), by words of its +/// title in either language: items go into sub-categories, main categories only group them. +pub fn sub_label(cat: Cat, title: &str) -> &'static str { + let title = title.to_lowercase(); + let has = |words: &[&str]| words.iter().any(|word| title.contains(word)); + match cat { + Cat::Clothing if has(&["ski", "funktions", "thermal"]) => "Sportbekleidung", + Cat::Clothing if has(&["body", "baby"]) => "Babykleidung", + Cat::Clothing if has(&["damen", "women"]) => "Damenkleidung", + Cat::Clothing if has(&["herren", "men's", "bomber", "w32"]) => "Herrenkleidung", + Cat::Clothing => "Kinderkleidung", + Cat::Shoes if has(&["skischuh", "ski boot"]) => "Skischuhe", + Cat::Shoes if has(&["laufschuh", "running"]) => "Sportschuhe", + Cat::Shoes if has(&["sneaker"]) => "Herrenschuhe", + Cat::Shoes => "Kinderschuhe", + Cat::Sports if has(&["yoga", "fitness"]) => "Fitness", + Cat::Sports if has(&["helm"]) => "Helme & Protektoren", + Cat::Sports if has(&["ball", "football"]) => "Ballsport", + Cat::Sports if has(&["outdoor", "wander", "hiking"]) => "Camping & Outdoor", + Cat::Sports => "Wintersport", + Cat::Bikes if has(&["kindersitz", "child bike seat", "child seat"]) => { + "Fahrrad-Kindersitze" + } + Cat::Bikes if has(&["e-bike"]) => "E-Bikes & Pedelecs", + Cat::Bikes if has(&["trekking"]) => "Trekkingräder", + Cat::Bikes if has(&["mountain", "fully", "mtb", "rockrider"]) => "Mountainbikes (MTB)", + Cat::Bikes if has(&["renn", "road", "gravel"]) => "Rennräder & Gravelbikes", + Cat::Bikes if has(&["falt", "fold"]) => "Falträder & Klappräder", + Cat::Bikes if has(&["kinder", "jugend", "child", "youth", "kid"]) => { + "Kinder- & Jugendräder" + } + Cat::Bikes => "Cityräder & Hollandräder", + Cat::Electronics if has(&["kopfhörer", "headphone", "radio"]) => "Audio & HiFi", + Cat::Electronics if has(&["kamera", "camera"]) => "Foto & Kamera", + Cat::Electronics if has(&["notebook", "laptop", "tablet"]) => "Computer & Tablets", + Cat::Electronics if has(&["smartphone", "handy", "phone"]) => "Handys & Smartphones", + Cat::Electronics => "Weitere Elektronik", + Cat::Books if has(&["kinder", "jugend", "erstlese", "bilderbuch"]) => { + "Kinder- & Jugendbücher" + } + Cat::Books if has(&["krimi", "roman", "klassiker"]) => "Romane", + Cat::Books if has(&["kochbuch"]) => "Kochbücher", + Cat::Books if has(&["sachbuch", "ratgeber", "reiseführer"]) => "Sachbücher", + Cat::Books => "Weitere Bücher", + Cat::Toys if has(&["kuschel", "puppe", "plüsch"]) => "Puppen & Plüsch", + Cat::Toys if has(&["baustein", "lego"]) => "Lego & Bausteine", + Cat::Toys if has(&["puzzle", "spiel"]) && !has(&["sandspiel"]) => "Spiele & Puzzles", + Cat::Toys if has(&["sand", "outdoor"]) => "Outdoor-Spielzeug", + Cat::Toys => "Weiteres Spielzeug", + Cat::Furniture if has(&["kinder"]) => "Kindermöbel", + Cat::Furniture if has(&["sofa", "sessel", "lowboard"]) => "Wohnzimmermöbel", + Cat::Furniture => "Weitere Möbel", + Cat::Household if has(&["kaffee", "küche", "pfanne"]) => "Küche & Kochen", + Cat::Household if has(&["bettwäsche"]) => "Heimtextilien", + Cat::Household => "Weiteres für den Haushalt", + Cat::Accessories if has(&["handschuh", "mütze"]) => "Mützen & Schals", + Cat::Accessories if has(&["beutel", "tasche"]) => "Taschen & Rucksäcke", + Cat::Accessories if has(&["gürtel"]) => "Gürtel", + Cat::Accessories => "Weitere Accessoires", + Cat::Other | Cat::BabyKids if has(&["autokindersitz", "car seat"]) => "Autokindersitze", + Cat::Other | Cat::BabyKids if has(&["kinderwagen", "pram"]) => "Kinderwagen & Buggys", + Cat::Other if has(&["gesellschaftsspiel", "board game"]) => "Spiele & Puzzles", + Cat::BabyKids => "Babyausstattung", + Cat::Other => "Sonstiges", + } +} + pub struct Person { pub first: Text, pub last: Text, @@ -302,7 +371,7 @@ pub const KIDS: &[Item] = &[ "Fünf T-Shirts in Grün- und Blautönen, kaum getragen, keine Flecken.", "Five T-shirts in green and blue, hardly worn, no stains.", ), - &[("size", "110/116", "4-5 years")], + &[("size", "110/116", "4-5 y")], ), item( Cat::Clothing, @@ -314,7 +383,7 @@ pub const KIDS: &[Item] = &[ "Wasserabweisend, mit abnehmbarer Kapuze. Ärmel leicht ausgewaschen.", "Water-repellent with a detachable hood. Sleeves slightly faded.", ), - &[("size", "122", "6-7 years")], + &[("size", "122", "6-7 y")], ), item( Cat::Clothing, @@ -356,7 +425,7 @@ pub const KIDS: &[Item] = &[ "Nur einmal zur Kommunion getragen.", "Worn once for a family celebration.", ), - &[("size", "140", "10 years")], + &[("size", "140", "10 y")], ), item( Cat::Clothing, @@ -383,7 +452,7 @@ pub const KIDS: &[Item] = &[ "Bio-Baumwolle, kurz- und langärmlig gemischt.", "Organic cotton, short and long sleeves.", ), - &[("size", "62/68", "3-6 months")], + &[("size", "62/68", "3-6 m")], ), item( Cat::Shoes, @@ -395,7 +464,7 @@ pub const KIDS: &[Item] = &[ "Klettverschluss, helle Sohle, kaum Abrieb.", "Velcro straps, light sole, barely worn.", ), - &[("size", "31", "12.5 kids")], + &[("size", "31", "12.5 K")], ), item( Cat::Shoes, @@ -714,7 +783,7 @@ pub const SKI: &[Item] = &[ "Verstärkte Knie, verstellbare Träger.", "Reinforced knees, adjustable braces.", ), - &[("size", "140", "10 years")], + &[("size", "140", "10 y")], ), item( Cat::Clothing, diff --git a/backend/src/demo/core.rs b/backend/src/demo/core.rs index 1f66e96b..9b8dfb4a 100644 --- a/backend/src/demo/core.rs +++ b/backend/src/demo/core.rs @@ -187,7 +187,7 @@ pub async fn insert_feature_showcase( .bind(bike.description) .bind(Decimal::from(bike.price)) .bind(vendor) - .bind(category) + .bind(seeder.item_category(Cat::Bikes, bike.title)) .bind(listing.status == "sold") .bind(bike.attributes) .bind(bike.accepts_offers.then_some(true)) @@ -732,10 +732,12 @@ async fn insert_event(seeder: &Seeder, ctx: &mut Ctx, spec: EventSpec<'_>) -> Ap .fetch_one(ctx.conn()) .await?; sqlx::query( - "INSERT INTO event_categories (event_id, position, category_id) VALUES ($1, 0, $2)", + "INSERT INTO event_categories (event_id, position, category_id) + VALUES ($1, 0, $2), ($1, 1, $3)", ) .bind(id) .bind(seeder.category(Cat::Sports)) + .bind(seeder.category(Cat::Bikes)) .execute(ctx.conn()) .await?; seeder @@ -745,6 +747,7 @@ async fn insert_event(seeder: &Seeder, ctx: &mut Ctx, spec: EventSpec<'_>) -> Ap } struct ProductSpec<'a> { + cat: Cat, title: &'a str, description: &'a str, condition: &'a str, @@ -767,7 +770,7 @@ async fn insert_product(seeder: &Seeder, ctx: &mut Ctx, spec: ProductSpec<'_>) - .bind(spec.condition) .bind(Decimal::from(spec.price)) .bind(spec.vendor) - .bind(seeder.category(Cat::Sports)) + .bind(seeder.item_category(spec.cat, spec.title)) .bind(spec.sold) .bind(at) .fetch_one(ctx.conn()) @@ -839,6 +842,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; insert_product(seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Hochwertige Outdoor-Jacke", "High-quality outdoor jacket"), description: tr( "Verkaufe meine wenig getragene Outdoor-Jacke der Marke NorthFace in Größe L. Sie ist wind- und wasserdicht, atmungsaktiv und ideal für Wanderungen oder den täglichen Weg zur Arbeit bei schlechtem Wetter. Die Jacke hat keinerlei Beschädigungen, alle Reißverschlüsse funktionieren einwandfrei. Farbe: Dunkelblau mit orangen Akzenten. Neupreis lag bei 250€. Tierfreier Nichtraucherhaushalt.", @@ -854,6 +858,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; insert_product(seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Wanderstiefel Gr. 42", "Hiking boots size 8"), description: tr( "Robuste Wanderstiefel von Meindl, Modell \"Borneo\", Größe 42. Das Leder ist gut gepflegt und wurde regelmäßig gewachst. Die Sohle hat noch ein sehr gutes Profil und bietet sicheren Halt auch in schwierigem Gelände. Ich verkaufe sie nur, weil sie mir nach einer Fußverletzung leider nicht mehr optimal passen. Perfekt für die nächste Bergtour! Einlegesohlen sind frisch gewaschen.", @@ -909,6 +914,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; let ski = insert_product(seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Atomic Carving Ski 160cm", "Atomic carving skis 160 cm"), description: tr( "Verkaufe meine treuen Atomic Redster Carving Ski in der Länge 160cm. Sie sind etwa 3 Jahre alt und wurden pro Saison ca. 1 Woche gefahren. Der Belag hat vor dem letzten Urlaub einen frischen Service bekommen (Kanten geschliffen, gewachst) und ist in einem top Zustand ohne tiefe Kratzer. Die Bindung ist natürlich dabei und voll funktionsfähig. Ideal für fortgeschrittene Fahrer, die einen sportlichen aber fehlerverzeihenden Ski suchen.", @@ -924,6 +930,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; let helmet = insert_product(seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Uvex Skihelm Gr. M (55-59cm)", "Uvex ski helmet size M (55-59 cm)"), description: tr( "Sicherheit geht vor! Ich biete hier einen hochwertigen Skihelm der Marke Uvex in Matt-Schwarz an. Größe M, verstellbar für Kopfumfang 55-59cm. Der Helm ist sturzfrei und wurde nur eine Saison getragen, daher ist er praktisch wie neu und hat keine sichtbaren Gebrauchsspuren. Er verfügt über ein verstellbares Belüftungssystem und ein herausnehmbares, waschbares Innenfutter. Neupreis war 89€.", @@ -939,6 +946,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; let mtb = insert_product(seeder, ctx, ProductSpec { + cat: Cat::Bikes, title: tr( "Mountainbike 'Rockrider' 26 Zoll", "Mountain bike 'Rockrider' 26 inch", @@ -957,6 +965,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes .await?; let seat = insert_product(seeder, ctx, ProductSpec { + cat: Cat::Bikes, title: tr("Kindersitz Römer für Fahrrad", "Römer child bike seat"), description: tr( "Sicherer Kindersitz für das Fahrrad. Einfache Montage am Rahmen. Inklusive Halterung und Anschnallgurten. Der Bezug ist waschbar und in einem kräftigen Rot.", @@ -1012,6 +1021,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Vintage Lederball", "Vintage leather football"), description: tr( "Ein echtes Sammlerstück aus den 70ern.", @@ -1030,6 +1040,7 @@ pub async fn insert(seeder: &Seeder, ctx: &mut Ctx, users: &CoreUsers) -> AppRes seeder, ctx, ProductSpec { + cat: Cat::Sports, title: tr("Alte Schlittschuhe Gr. 39", "Old ice skates size 6"), description: tr( "Gut erhaltene Kufen für Einsteiger.", diff --git a/backend/src/demo/extended.rs b/backend/src/demo/extended.rs index c44a75be..9acc69f8 100644 --- a/backend/src/demo/extended.rs +++ b/backend/src/demo/extended.rs @@ -368,7 +368,7 @@ impl Demo<'_> { "description": self.text(item.description), "condition": item.condition, "images": images, - "productCategory": self.seeder.category(item.cat), + "productCategory": self.seeder.item_category(item.cat, item.title.de), "price": item.price, "readyForSale": true, "sold": false, @@ -810,7 +810,7 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> access_code: None, vendor_limit: Some(60), commission: 15.0, - categories: &[Cat::Clothing, Cat::Shoes, Cat::Toys, Cat::Books, Cat::Other], + categories: &[Cat::Clothing, Cat::Shoes, Cat::Toys, Cat::Books, Cat::Other, Cat::BabyKids, Cat::Bikes, Cat::Sports, Cat::Furniture], cover: "cover_clothes", features: json!({ "discounts": true, @@ -1006,7 +1006,7 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "title": demo.text(item.title), "description": demo.text(item.description), "condition": item.condition, - "productCategory": demo.seeder.category(item.cat), + "productCategory": demo.seeder.item_category(item.cat, item.title.de), "price": item.price, }), ) @@ -1260,7 +1260,19 @@ async fn flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> access_code: None, vendor_limit: None, commission: 10.0, - categories: &[Cat::Household, Cat::Furniture, Cat::Electronics, Cat::Bikes, Cat::Clothing], + categories: &[ + Cat::Household, + Cat::Furniture, + Cat::Electronics, + Cat::Bikes, + Cat::Clothing, + Cat::Shoes, + Cat::Accessories, + Cat::Sports, + Cat::Toys, + Cat::Books, + Cat::Other, + ], cover: "cover_market", features: json!({ "discounts": true, @@ -1594,7 +1606,8 @@ async fn other_events(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<() &EventPlan { vendor_limit: Some(3), visibility: "logged-in", - categories: &[Cat::Clothing, Cat::Shoes], + // Children's things from the kids' list + categories: &[Cat::Clothing, Cat::Shoes, Cat::Toys, Cat::Books, Cat::Other, Cat::BabyKids, Cat::Bikes, Cat::Sports, Cat::Furniture], features: json!({ "discounts": false, "labelFormat": "small", "labelMark": "universal" }), ..plan( sabine, diff --git a/backend/src/demo/mod.rs b/backend/src/demo/mod.rs index 9c553ad7..0926b1b3 100644 --- a/backend/src/demo/mod.rs +++ b/backend/src/demo/mod.rs @@ -58,6 +58,8 @@ pub struct Seeder { images: HashMap<&'static str, Uuid>, product_images: Vec, categories: HashMap, + /// Default categories by German label + subs: HashMap<&'static str, Uuid>, } pub struct UserSpec<'a> { @@ -99,13 +101,15 @@ impl<'a> UserSpec<'a> { } impl Seeder { - /// Makes sure the default categories exist in the language of the demo. + /// Makes sure the default categories exist in the language of the demo, with their + /// sub-categories, as an instance gets them on its first start. pub async fn load( ctx: &mut Ctx, locale: Locale, images: HashMap<&'static str, Uuid>, product_images: Option>, ) -> AppResult { + crate::modules::categories::insert_default_tree(ctx, locale == Locale::En).await?; let mut categories = HashMap::new(); for (cat, names) in CATEGORIES { let label = names.get(locale); @@ -134,6 +138,21 @@ impl Seeder { }; categories.insert(*cat, id); } + // Items go into the sub-categories of the default tree + let english = locale == Locale::En; + let mut subs = HashMap::new(); + for category in &crate::modules::categories::DEFAULT_CATEGORIES { + let label = crate::modules::categories::default_label(category.label, english); + let id: Option = sqlx::query_scalar( + "SELECT id FROM categories WHERE label = $1 ORDER BY created_at LIMIT 1", + ) + .bind(label) + .fetch_optional(ctx.conn()) + .await?; + if let Some(id) = id { + subs.insert(category.label, id); + } + } ctx.touch(crate::realtime::Topic::Table("categories")); let product_images = product_images.unwrap_or_else(|| { PRODUCT_IMAGE_KEYS @@ -150,6 +169,7 @@ impl Seeder { images, product_images, categories, + subs, }) } @@ -165,10 +185,16 @@ impl Seeder { self.product_images.clone() } + /// The main category, e.g. for the categories a bazaar allows. pub fn category(&self, cat: Cat) -> Uuid { self.categories[&cat] } + /// The sub-category of an item, by the words of its title (catalog::sub_label). + pub fn item_category(&self, cat: Cat, title: &str) -> Uuid { + self.subs[catalog::sub_label(cat, title)] + } + /// The user with this email, created with a password account if missing. pub async fn ensure_user(&self, ctx: &mut Ctx, spec: &UserSpec<'_>) -> AppResult { let existing: Option = diff --git a/backend/src/modules/categories.rs b/backend/src/modules/categories.rs index 46bc062a..69ed039e 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::{self, CategoryField, FieldIndex}; use crate::error::{AppError, AppResult}; use crate::realtime::Topic; use crate::register; @@ -26,12 +27,16 @@ pub fn register(registry: &mut Registry) { registry.share("categories.getAllCategories", same_for_everybody); register!(registry, Query "categories.getCategoryLabel" => get_category_label); register!(registry, Query "categories.getCategoryId" => get_category_id); + register!(registry, Query "categories.listFields" => list_fields); + registry.share("categories.listFields", same_for_everybody); + register!(registry, Query "categories.listFieldsForAdmin" => list_fields_for_admin); + register!(registry, Mutation "categories.saveField" => save_field); + register!(registry, Mutation "categories.deleteField" => delete_field); register!(registry, InternalMutation "categories.seedCategories" => seed_categories); register!(registry, InternalMutation "categories.seedIfEmpty" => seed_if_empty); } -/// Names in other languages. `label` remains the name that decides the extra fields -/// (category_fields) and the one shown when a language has no translation. +/// Names in other languages. `label` is the one shown when a language has no translation. #[skip_serializing_none] #[derive(Debug, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -64,6 +69,19 @@ pub struct Category { #[serde(with = "ms")] pub updated_at: DateTime, pub translations: Json, + /// Ids of the extra fields an admin picked; unset: those of the main category + pub fields: Option>, + /// The extra fields its items have, from its own choice or its main category + #[sqlx(skip)] + #[serde(default)] + pub field_list: Vec, +} + +/// Fills in the fields each category ends up with. +fn with_fields<'a>(categories: impl Iterator, index: &FieldIndex) { + for category in categories { + category.field_list = index.fields(category.id); + } } #[derive(Deserialize)] @@ -72,6 +90,21 @@ struct CreateArgs { label: String, parent_category: Option, translations: Option, + fields: Option>, +} + +/// The extra fields an admin picked, checked; None: those of the main category. +async fn checked_fields( + ctx: &mut Ctx, + fields: Option>, +) -> AppResult>> { + let Some(ids) = fields else { + return Ok(None); + }; + let definitions = category_fields::load_definitions(ctx.conn()).await?; + category_fields::checked_selection(&ids, &definitions) + .map(Some) + .map_err(AppError::bad_request) } fn clean_label(label: &str) -> AppResult { @@ -93,25 +126,22 @@ 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(ctx, args.fields).await?; 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", + "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); @@ -124,12 +154,59 @@ struct UpdateArgs { category_id: Id, label: String, translations: Translations, + /// The main category; none makes it a main category itself + #[serde(default)] + parent_category: Option, + /// The extra fields; none: those of the main category + #[serde(default)] + fields: 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(()) +} + +/// Items go into a category without sub-categories: a main category only groups them. +pub async fn assert_for_items(conn: &mut sqlx::PgConnection, category: Uuid) -> AppResult<()> { + let has_children: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM categories WHERE parent_id = $1)") + .bind(category) + .fetch_one(conn) + .await?; + if has_children { + return Err(AppError::bad_request("product.chooseSubcategory")); + } + Ok(()) } /// Admins only. Items and bazaars point to the id and follow; sales keep the name they had. async fn update_category(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { require_admin(ctx).await?; let label = clean_label(&args.label)?; + let fields = checked_fields(ctx, args.fields).await?; let taken: bool = sqlx::query_scalar( "SELECT EXISTS (SELECT 1 FROM categories WHERE lower(label) = lower($1) AND id <> $2)", ) @@ -140,12 +217,20 @@ 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, 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 { @@ -208,15 +293,18 @@ struct AdminCategory { async fn list_for_admin(ctx: &mut Ctx, _: NoArgs) -> AppResult> { require_admin(ctx).await?; ctx.read(TOPIC); - Ok(sqlx::query_as( - "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations, + let mut rows: Vec = sqlx::query_as( + "SELECT c.id, c.created_at, c.label, c.parent_id, c.updated_at, c.translations, c.fields, (SELECT count(*) FROM products p WHERE p.category_id = c.id) AS product_count, (SELECT count(*) FROM event_categories e WHERE e.category_id = c.id) AS event_count, (SELECT count(*) FROM categories s WHERE s.parent_id = c.id) AS child_count FROM categories c ORDER BY c.created_at, c.id", ) .fetch_all(ctx.conn()) - .await?) + .await?; + let index = FieldIndex::load(ctx.conn()).await?; + with_fields(rows.iter_mut().map(|row| &mut row.category), &index); + Ok(rows) } #[derive(Deserialize)] @@ -233,12 +321,15 @@ fn same_for_everybody<'a>( 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 - FROM categories c ORDER BY c.created_at", + let mut categories: Vec = sqlx::query_as( + "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, c.id", ) .fetch_all(ctx.conn()) - .await?) + .await?; + let index = FieldIndex::load(ctx.conn()).await?; + with_fields(categories.iter_mut(), &index); + Ok(categories) } #[derive(Deserialize)] @@ -268,36 +359,434 @@ 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); 11] = [ - ("Kleidung", "Clothing"), - ("Schuhe", "Shoes"), - ("Sport", "Sports"), - ("Fahrräder", "Bikes"), - ("Elektronik", "Electronics"), - ("Bücher", "Books"), - ("Spielzeug", "Toys"), - ("Möbel", "Furniture"), - ("Haushalt", "Household"), - ("Accessoires", "Accessories"), - ("Sonstiges", "Other"), +/// The extra fields admins defined, e.g. for the required fields of a bazaar. +async fn list_fields(ctx: &mut Ctx, _: NoArgs) -> AppResult> { + ctx.read(TOPIC); + Ok(category_fields::load_definitions(ctx.conn()).await?) +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct AdminField { + #[serde(flatten)] + field: CategoryField, + /// Categories that picked it themselves + category_count: i64, +} + +async fn list_fields_for_admin(ctx: &mut Ctx, _: NoArgs) -> AppResult> { + require_admin(ctx).await?; + ctx.read(TOPIC); + let definitions = category_fields::load_definitions(ctx.conn()).await?; + let counts: Vec<(String, i64)> = + sqlx::query_as("SELECT f, count(*) FROM categories, unnest(fields) AS f GROUP BY f") + .fetch_all(ctx.conn()) + .await?; + Ok(definitions + .into_iter() + .map(|field| AdminField { + category_count: counts + .iter() + .find(|(id, _)| id == &field.id) + .map_or(0, |(_, count)| *count), + field, + }) + .collect()) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FieldArgs { + /// None: a new field + field_id: Option, + label: String, + label_en: Option, + placeholder: Option, + placeholder_en: Option, + hint: Option, + hint_en: Option, + short: bool, +} + +/// Trimmed, None when empty. +fn text(value: Option) -> Option { + value + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +/// Admins only. Creates or changes an extra field; its key stays, so items keep their values. +async fn save_field(ctx: &mut Ctx, args: FieldArgs) -> AppResult { + require_admin(ctx).await?; + let label = + text(Some(args.label)).ok_or_else(|| AppError::bad_request("category.labelEmpty"))?; + let values = ( + label, + text(args.label_en), + text(args.placeholder), + text(args.placeholder_en), + text(args.hint), + text(args.hint_en), + ); + let id = match args.field_id { + Some(id) => { + let updated = sqlx::query( + "UPDATE category_field_definitions SET label = $2, label_en = $3, placeholder = $4, + placeholder_en = $5, hint = $6, hint_en = $7, short = $8 + WHERE id = $1", + ) + .bind(&id) + .bind(&values.0) + .bind(&values.1) + .bind(&values.2) + .bind(&values.3) + .bind(&values.4) + .bind(&values.5) + .bind(args.short) + .execute(ctx.conn()) + .await?; + if updated.rows_affected() == 0 { + return Err(AppError::not_found("notFound.categoryField")); + } + id + } + None => { + // Its own key: the value of a new field is stored apart from all others + let id = format!("f{}", &Uuid::new_v4().simple().to_string()[..10]); + sqlx::query( + "INSERT INTO category_field_definitions + (id, key, label, label_en, placeholder, placeholder_en, hint, hint_en, short, + position) + VALUES ($1, $1, $2, $3, $4, $5, $6, $7, $8, + (SELECT coalesce(max(position), 0) + 1 FROM category_field_definitions))", + ) + .bind(&id) + .bind(&values.0) + .bind(&values.1) + .bind(&values.2) + .bind(&values.3) + .bind(&values.4) + .bind(&values.5) + .bind(args.short) + .execute(ctx.conn()) + .await?; + id + } + }; + ctx.touch(TOPIC); + Ok(id) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DeleteFieldArgs { + field_id: String, +} + +/// Admins only, and only a field no category picked; items keep their values. +async fn delete_field(ctx: &mut Ctx, args: DeleteFieldArgs) -> AppResult<()> { + require_admin(ctx).await?; + let in_use: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM categories WHERE $1 = ANY (fields))") + .bind(&args.field_id) + .fetch_one(ctx.conn()) + .await?; + if in_use { + return Err(AppError::bad_request("categoryField.inUse")); + } + let deleted = sqlx::query("DELETE FROM category_field_definitions WHERE id = $1") + .bind(&args.field_id) + .execute(ctx.conn()) + .await?; + if deleted.rows_affected() == 0 { + return Err(AppError::not_found("notFound.categoryField")); + } + ctx.touch(TOPIC); + Ok(()) +} + +// The field ids of the defaults, as in migration 0034 +const BIKE: &[&str] = &["frameNumber", "frameSize", "wheelSize", "brand", "color"]; +const CLOTHING: &[&str] = &["clothingSize", "brand", "color"]; +const SHOES: &[&str] = &["shoeSize", "brand"]; +const SPORT: &[&str] = &["sportSize", "brand", "color"]; +const ELECTRONICS: &[&str] = &["brand", "model"]; +const NONE: &[&str] = &[]; + +/// A default category: German label, English name, the label of its main category and the +/// ids of its extra fields (None: those of the main category). +pub struct DefaultCategory { + pub label: &'static str, + pub en: &'static str, + pub parent: Option<&'static str>, + pub fields: Option<&'static [&'static str]>, +} + +const fn main( + label: &'static str, + en: &'static str, + fields: Option<&'static [&'static str]>, +) -> DefaultCategory { + DefaultCategory { + label, + en, + parent: None, + fields, + } +} + +const fn sub( + parent: &'static str, + label: &'static str, + en: &'static str, + fields: Option<&'static [&'static str]>, +) -> DefaultCategory { + DefaultCategory { + label, + en, + parent: Some(parent), + fields, + } +} + +/// 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 0034. +pub const DEFAULT_CATEGORIES: [DefaultCategory; COUNT] = [ + main("Kleidung", "Clothing", Some(CLOTHING)), + sub("Kleidung", "Babykleidung", "Baby clothes", None), + sub("Kleidung", "Kinderkleidung", "Children's clothes", None), + sub("Kleidung", "Damenkleidung", "Women's clothes", None), + sub("Kleidung", "Herrenkleidung", "Men's clothes", None), + sub("Kleidung", "Umstandsmode", "Maternity wear", None), + main("Schuhe", "Shoes", Some(SHOES)), + sub("Schuhe", "Kinderschuhe", "Children's shoes", None), + sub("Schuhe", "Damenschuhe", "Women's shoes", None), + sub("Schuhe", "Herrenschuhe", "Men's shoes", None), + sub("Schuhe", "Sportschuhe", "Sports shoes", None), + main("Sport", "Sports", Some(SPORT)), + sub("Sport", "Wintersport", "Winter sports", None), + sub("Sport", "Skischuhe", "Ski boots", Some(SHOES)), + sub("Sport", "Sportbekleidung", "Sportswear", Some(CLOTHING)), + sub("Sport", "Helme & Protektoren", "Helmets & protectors", None), + sub("Sport", "Ballsport", "Ball sports", None), + sub("Sport", "Fitness", "Fitness", None), + sub("Sport", "Camping & Outdoor", "Camping & outdoor", None), + sub("Sport", "Weitere Sportarten", "Other sports", None), + main("Fahrräder", "Bikes", Some(BIKE)), + sub( + "Fahrräder", + "Cityräder & Hollandräder", + "City & Dutch bikes", + None, + ), + sub("Fahrräder", "Trekkingräder", "Trekking bikes", None), + sub( + "Fahrräder", + "Mountainbikes (MTB)", + "Mountain bikes (MTB)", + None, + ), + sub( + "Fahrräder", + "Rennräder & Gravelbikes", + "Road & gravel bikes", + None, + ), + sub("Fahrräder", "BMX & Dirtbikes", "BMX & dirt bikes", None), + sub("Fahrräder", "Falträder & Klappräder", "Folding bikes", None), + sub( + "Fahrräder", + "Kinder- & Jugendräder", + "Children's & youth bikes", + None, + ), + sub("Fahrräder", "E-Bikes & Pedelecs", "E-bikes", None), + sub("Fahrräder", "Lastenräder", "Cargo bikes", None), + sub("Fahrräder", "Fahrradanhänger", "Bike trailers", Some(NONE)), + sub( + "Fahrräder", + "Fahrrad-Kindersitze", + "Child bike seats", + Some(NONE), + ), + sub( + "Fahrräder", + "Fahrradzubehör", + "Bike accessories", + Some(NONE), + ), + main("Kinderfahrzeuge", "Children's vehicles", None), + sub("Kinderfahrzeuge", "Laufräder", "Balance bikes", Some(BIKE)), + sub("Kinderfahrzeuge", "Roller & Scooter", "Scooters", None), + sub("Kinderfahrzeuge", "Einräder", "Unicycles", None), + sub( + "Kinderfahrzeuge", + "Bobbycars & Rutschfahrzeuge", + "Ride-on toys", + None, + ), + main("Baby & Kind", "Baby & child", None), + sub( + "Baby & Kind", + "Kinderwagen & Buggys", + "Prams & buggies", + None, + ), + sub("Baby & Kind", "Autokindersitze", "Car seats", None), + sub("Baby & Kind", "Babyausstattung", "Baby gear", None), + main("Elektronik", "Electronics", Some(ELECTRONICS)), + sub("Elektronik", "Handys & Smartphones", "Mobile phones", None), + sub( + "Elektronik", + "Computer & Tablets", + "Computers & tablets", + None, + ), + sub("Elektronik", "Foto & Kamera", "Photo & camera", None), + sub( + "Elektronik", + "Konsolen & Videospiele", + "Consoles & video games", + None, + ), + sub("Elektronik", "Audio & HiFi", "Audio & hi-fi", None), + sub( + "Elektronik", + "Weitere Elektronik", + "Other electronics", + None, + ), + main("Bücher", "Books", None), + sub( + "Bücher", + "Kinder- & Jugendbücher", + "Children's & youth books", + None, + ), + sub("Bücher", "Romane", "Novels", None), + sub("Bücher", "Sachbücher", "Non-fiction", None), + sub("Bücher", "Kochbücher", "Cookbooks", None), + sub("Bücher", "Comics", "Comics", None), + sub("Bücher", "Weitere Bücher", "Other books", None), + main("Spielzeug", "Toys", None), + sub("Spielzeug", "Babyspielzeug", "Baby toys", None), + sub("Spielzeug", "Puppen & Plüsch", "Dolls & plush", None), + sub( + "Spielzeug", + "Lego & Bausteine", + "Lego & building blocks", + None, + ), + sub("Spielzeug", "Spiele & Puzzles", "Games & puzzles", None), + sub("Spielzeug", "Outdoor-Spielzeug", "Outdoor toys", None), + sub("Spielzeug", "Weiteres Spielzeug", "Other toys", None), + main("Möbel", "Furniture", None), + sub("Möbel", "Kindermöbel", "Children's furniture", None), + sub("Möbel", "Wohnzimmermöbel", "Living room", None), + sub("Möbel", "Schlafzimmermöbel", "Bedroom", None), + sub("Möbel", "Büromöbel", "Office furniture", None), + sub("Möbel", "Gartenmöbel", "Garden furniture", None), + sub("Möbel", "Weitere Möbel", "Other furniture", None), + main("Haushalt", "Household", None), + sub("Haushalt", "Küche & Kochen", "Kitchen & cooking", None), + sub("Haushalt", "Dekoration", "Decoration", None), + sub("Haushalt", "Heimtextilien", "Home textiles", None), + sub("Haushalt", "Werkzeug & Garten", "Tools & garden", None), + sub( + "Haushalt", + "Weiteres für den Haushalt", + "Other household goods", + None, + ), + main("Accessoires", "Accessories", None), + sub( + "Accessoires", + "Taschen & Rucksäcke", + "Bags & backpacks", + None, + ), + sub( + "Accessoires", + "Schmuck & Uhren", + "Jewellery & watches", + None, + ), + sub("Accessoires", "Mützen & Schals", "Hats & scarves", None), + sub("Accessoires", "Sonnenbrillen", "Sunglasses", None), + sub("Accessoires", "Gürtel", "Belts", None), + sub( + "Accessoires", + "Weitere Accessoires", + "Other accessories", + None, + ), + main("Freizeit & Hobby", "Leisure & hobbies", None), + sub( + "Freizeit & Hobby", + "Musikinstrumente", + "Musical instruments", + None, + ), + sub("Freizeit & Hobby", "Filme & Musik", "Films & music", None), + sub( + "Freizeit & Hobby", + "Basteln & Handarbeit", + "Crafts & needlework", + None, + ), + sub("Freizeit & Hobby", "Sammeln", "Collectibles", None), + main("Sonstiges", "Other", None), ]; +const COUNT: usize = 89; 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?; + insert_default_tree(ctx, false).await?; + Ok("Categories seeded successfully") +} + +/// The label of a default category in the language of the instance. +pub fn default_label(german: &str, english: bool) -> &str { + match DEFAULT_CATEGORIES.iter().find(|c| c.label == german) { + Some(category) if english => category.en, + _ => german, + } +} + +/// Adds the missing default categories with their main categories. `english`: an English +/// instance or demo, labelled with the English names and without translations. +pub async fn insert_default_tree(ctx: &mut Ctx, english: bool) -> sqlx::Result<()> { + category_fields::insert_default_fields(ctx.conn()).await?; + for (position, category) in DEFAULT_CATEGORIES.iter().enumerate() { + let label = default_label(category.label, english); + if find_by_label(ctx, 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, default_label(parent, english)).await?, + None => None, + }; + let fields: Option> = category + .fields + .map(|ids| ids.iter().map(|id| (*id).to_owned()).collect()); + // Lists follow the creation time, and one run is one transaction with one now() + sqlx::query( + "INSERT INTO categories (label, parent_id, translations, fields, created_at) + VALUES ($1, $2, $3, $4, now() + $5 * interval '1 millisecond')", + ) + .bind(label) + .bind(parent) + .bind(Json(Translations { + en: (!english).then(|| category.en.to_owned()), + })) + .bind(fields) + .bind(position as f64) + .execute(ctx.conn()) + .await?; } ctx.touch(TOPIC); - Ok("Categories seeded successfully") + Ok(()) } /// On every start of the server: without categories no bazaar can be created, and the app @@ -311,3 +800,46 @@ async fn seed_if_empty(ctx: &mut Ctx, args: NoArgs) -> AppResult<&'static str> { } seed_categories(ctx, args).await } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_tree_is_one_level_deep_and_names_known_fields() { + let known = [ + "frameNumber", + "frameSize", + "wheelSize", + "brand", + "color", + "clothingSize", + "shoeSize", + "sportSize", + "model", + ]; + for (index, category) in DEFAULT_CATEGORIES.iter().enumerate() { + for id in category.fields.unwrap_or_default() { + assert!(known.contains(id), "{} {id}", category.label); + } + if let Some(parent) = category.parent { + let main = DEFAULT_CATEGORIES + .iter() + .position(|c| c.label == parent) + .unwrap(); + assert!(DEFAULT_CATEGORIES[main].parent.is_none(), "{parent}"); + assert!(main < index, "{parent} before {}", category.label); + } + } + // Labels are unique, in German and in English + for english in [false, true] { + let mut labels: Vec<_> = DEFAULT_CATEGORIES + .iter() + .map(|c| default_label(c.label, english)) + .collect(); + labels.sort_unstable(); + labels.dedup(); + assert_eq!(labels.len(), DEFAULT_CATEGORIES.len()); + } + } +} diff --git a/backend/src/modules/category_fields.rs b/backend/src/modules/category_fields.rs index c065ec0b..7057f0d0 100644 --- a/backend/src/modules/category_fields.rs +++ b/backend/src/modules/category_fields.rs @@ -1,140 +1,251 @@ -//! Extra item fields per category, e.g. frame number for bikes. -//! Category names are free text, so the fields are matched by keywords. +//! Extra item fields per category, e.g. frame number for bikes. Admins define the fields +//! (category_field_definitions) and pick them per category; a sub-category without its own +//! choice takes the fields of its main category. use std::collections::{BTreeMap, HashMap, HashSet}; -use std::sync::LazyLock; -use regex::Regex; use serde::Serialize; +use serde_with::skip_serializing_none; use uuid::Uuid; -const MAX_VALUE_LENGTH: usize = 120; -/// Longest size, e.g. "134/140" or "160 cm"; longer ones would not fit on the labels. -/// Same as MAX_SIZE_LENGTH in src/shared/categoryFields.ts. -pub const MAX_SIZE_LENGTH: usize = 7; +/// Longest value of a field. +pub const MAX_VALUE_LENGTH: usize = 120; +/// Longest value of a short field such as a size, e.g. "134/140" or "160 cm"; longer ones +/// would not fit on the labels. Same as MAX_SHORT_LENGTH in src/shared/categoryFields.ts. +pub const MAX_SHORT_LENGTH: usize = 7; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +/// A field an admin defined, with its texts in German and English. +#[skip_serializing_none] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, sqlx::FromRow)] +#[serde(rename_all = "camelCase")] pub struct CategoryField { - pub key: &'static str, - /// Translation of label, placeholder and hint: categoryFields. in src/locales - pub text: &'static str, - pub label: &'static str, - #[serde(skip)] - pub max_length: usize, + /// Picked by categories, e.g. "clothingSize" + #[serde(rename = "_id")] + pub id: String, + /// Under which the value is stored on the item; sizes share "size", so an item keeps + /// its size when it moves to another category + pub key: String, + pub label: String, + pub label_en: Option, + pub placeholder: Option, + pub placeholder_en: Option, + pub hint: Option, + pub hint_en: Option, + /// At most MAX_SHORT_LENGTH characters, so it fits on the labels + pub short: bool, + /// Sellers may enter the agreed "not found", e.g. for a worn frame number + pub not_found_button: bool, } -const fn field(key: &'static str, text: &'static str, label: &'static str) -> CategoryField { - CategoryField { - key, - text, - label, - max_length: MAX_VALUE_LENGTH, +impl CategoryField { + pub fn max_length(&self) -> usize { + if self.short { + MAX_SHORT_LENGTH + } else { + MAX_VALUE_LENGTH + } } -} -const fn size(text: &'static str, label: &'static str) -> CategoryField { - CategoryField { - max_length: MAX_SIZE_LENGTH, - ..field("size", text, label) + /// The label in English if there is one; mails to English speakers use it. + pub fn label_in(&self, english: bool) -> &str { + match &self.label_en { + Some(en) if english && !en.is_empty() => en, + _ => &self.label, + } } } -const BIKE: &[CategoryField] = &[ - field("frameNumber", "frameNumber", "Rahmennummer"), - field("frameSize", "frameSize", "Rahmengröße"), - field("wheelSize", "wheelSize", "Laufradgröße"), - field("brand", "bikeBrand", "Marke"), -]; -const CLOTHING: &[CategoryField] = &[ - size("clothingSize", "Größe"), - field("brand", "brand", "Marke"), -]; -const SHOES: &[CategoryField] = &[ - size("shoeSize", "Größe (EU)"), - field("brand", "brand", "Marke"), -]; -const SPORT: &[CategoryField] = &[ - size("sportSize", "Größe / Länge"), - field("brand", "brand", "Marke"), -]; -const ELECTRONICS: &[CategoryField] = &[ - field("brand", "brand", "Marke"), - field("model", "model", "Modell"), +/// A field of a new instance: (id, key, label, label_en, placeholder, placeholder_en, hint, +/// hint_en, short, not_found_button). Same as migration 0034. +type DefaultField = ( + &'static str, + &'static str, + &'static str, + &'static str, + Option<&'static str>, + Option<&'static str>, + Option<&'static str>, + Option<&'static str>, + bool, + bool, +); + +pub const DEFAULT_FIELDS: [DefaultField; 9] = [ + ( + "frameNumber", + "frameNumber", + "Rahmennummer", + "Frame number", + Some("z. B. WBK123456"), + Some("e.g. WBK123456"), + Some("Nicht gefunden? Schreib „nicht gefunden“ hinein – wir suchen sie vor Ort gemeinsam."), + Some("Can't find it? Enter “not found” – we'll look for it together on site."), + false, + true, + ), + ( + "frameSize", + "frameSize", + "Rahmengröße", + "Frame size", + Some("z. B. 52 cm oder M"), + Some("e.g. 52 cm or M"), + None, + None, + false, + false, + ), + ( + "wheelSize", + "wheelSize", + "Laufradgröße", + "Wheel size", + Some("z. B. 28 Zoll"), + Some("e.g. 28 inch"), + None, + None, + false, + false, + ), + ( + "clothingSize", + "size", + "Größe", + "Size", + Some("z. B. M oder 128"), + Some("e.g. M or 128"), + None, + None, + true, + false, + ), + ( + "shoeSize", + "size", + "Größe (EU)", + "Size (EU)", + Some("z. B. 38"), + Some("e.g. 38"), + None, + None, + true, + false, + ), + ( + "sportSize", + "size", + "Größe / Länge", + "Size / length", + Some("z. B. 160 cm"), + Some("e.g. 160 cm"), + None, + None, + true, + false, + ), + ( + "brand", "brand", "Marke", "Brand", None, None, None, None, false, false, + ), + ( + "color", + "color", + "Farbe", + "Color", + Some("z. B. Rot"), + Some("e.g. red"), + None, + None, + false, + false, + ), + ( + "model", "model", "Modell", "Model", None, None, None, None, false, false, + ), ]; -struct Rule { - matches: Regex, - exclude: Option, - fields: &'static [CategoryField], +/// Adds the default fields that are missing, e.g. after all data was removed; the default +/// categories name them. +pub async fn insert_default_fields(conn: &mut sqlx::PgConnection) -> sqlx::Result<()> { + for (position, field) in DEFAULT_FIELDS.iter().enumerate() { + let (id, key, label, label_en, placeholder, placeholder_en, hint, hint_en, short, nf) = + *field; + sqlx::query( + "INSERT INTO category_field_definitions + (id, key, label, label_en, placeholder, placeholder_en, hint, hint_en, short, + not_found_button, position) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + ON CONFLICT (id) DO NOTHING", + ) + .bind(id) + .bind(key) + .bind(label) + .bind(label_en) + .bind(placeholder) + .bind(placeholder_en) + .bind(hint) + .bind(hint_en) + .bind(short) + .bind(nf) + .bind(position as i32 + 1) + .execute(&mut *conn) + .await?; + } + Ok(()) } -/// The first matching rule wins. `\b` is ASCII-only, as in JavaScript. -static RULES: LazyLock> = LazyLock::new(|| { - let re = |pattern: &str| { - Regex::new(&format!("(?i){}", pattern.replace(r"\b", r"(?-u:\b)"))).unwrap() - }; - vec![ - 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")), - fields: BIKE, - }, - Rule { - matches: re(r"schuh|stiefel|sneaker"), - exclude: None, - fields: SHOES, - }, - // "mode" only as a word or word ending ("Damenmode"), not in "Sondermodelle" - Rule { - matches: re(r"kleid|jacke|hose|\bmode\b|mode$|shirt|pullover"), - exclude: None, - fields: CLOTHING, - }, - Rule { - matches: re(r"sport|\bski|snowboard"), - exclude: None, - fields: SPORT, - }, - Rule { - matches: re(r"elektron|handy|smartphone|computer|laptop|tablet|kamera|konsole"), - exclude: None, - fields: ELECTRONICS, - }, - ] -}); +pub async fn load_definitions(conn: &mut sqlx::PgConnection) -> sqlx::Result> { + sqlx::query_as( + "SELECT id, key, label, label_en, placeholder, placeholder_en, hint, hint_en, short, + not_found_button + FROM category_field_definitions ORDER BY position, created_at, id", + ) + .fetch_all(conn) + .await +} -/// Fields an organizer can make required, one per key. -pub fn requirable_fields() -> Vec { - let mut seen = HashSet::new(); - RULES +/// The fields an admin picked, in the order of the definitions; the error code when one +/// is unknown or two share a key (e.g. two sizes). +pub fn checked_selection( + ids: &[String], + definitions: &[CategoryField], +) -> Result, &'static str> { + let mut keys = HashSet::new(); + let mut chosen = HashSet::new(); + for id in ids { + let field = definitions + .iter() + .find(|field| &field.id == id) + .ok_or("category.unknownField")?; + if chosen.insert(field.id.as_str()) && !keys.insert(field.key.as_str()) { + return Err("category.oneSize"); + } + } + Ok(definitions .iter() - .flat_map(|rule| rule.fields.iter().copied()) - .filter(|field| seen.insert(field.key)) - .collect() + .filter(|field| chosen.contains(field.id.as_str())) + .map(|field| field.id.clone()) + .collect()) } -pub fn fields_for_label(label: &str) -> Option<&'static [CategoryField]> { - let name = label.trim(); - RULES +/// Fields an organizer can make required, one per key. +pub fn requirable_fields(definitions: &[CategoryField]) -> Vec<&CategoryField> { + let mut seen = HashSet::new(); + definitions .iter() - .find(|rule| { - rule.matches.is_match(name) - && !rule.exclude.as_ref().is_some_and(|ex| ex.is_match(name)) - }) - .map(|rule| rule.fields) + .filter(|field| seen.insert(field.key.as_str())) + .collect() } /// A category with its parent, for the inheritance of fields. pub struct CategoryRef { pub id: Uuid, - pub label: String, pub parent: Option, + /// Picked by an admin; None: those of the main category + 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] { +/// The field ids of a category: its own choice, else its main category's. +pub fn field_ids(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(); @@ -142,35 +253,80 @@ pub fn category_fields(category: Uuid, categories: &[CategoryRef]) -> &'static [ if !seen.insert(cat.id) { break; } - if let Some(fields) = fields_for_label(&cat.label) { - return fields; + if let Some(ids) = &cat.fields { + return ids.clone(); } current = cat.parent.and_then(|parent| by_id.get(&parent).copied()); } - &[] + Vec::new() +} + +/// The fields of a category, in the order of the definitions; a deleted one is left out. +pub fn category_fields( + category: Uuid, + categories: &[CategoryRef], + definitions: &[CategoryField], +) -> Vec { + resolve(&field_ids(category, categories), definitions) +} + +pub fn resolve(ids: &[String], definitions: &[CategoryField]) -> Vec { + definitions + .iter() + .filter(|field| ids.contains(&field.id)) + .cloned() + .collect() +} + +/// Categories and field definitions, everything to resolve the fields of a category. +pub struct FieldIndex { + pub categories: Vec, + pub definitions: Vec, +} + +impl FieldIndex { + pub async fn load(conn: &mut sqlx::PgConnection) -> sqlx::Result { + Ok(Self { + categories: load_categories(&mut *conn).await?, + definitions: load_definitions(conn).await?, + }) + } + + pub fn fields(&self, category: Uuid) -> Vec { + category_fields(category, &self.categories, &self.definitions) + } } 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, + parent_id: Option, + fields: Option>, + } + let rows: Vec = sqlx::query_as("SELECT id, 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, + 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 - .get(field.key) - .is_some_and(|value| value.trim().chars().count() > field.max_length) + .get(&field.key) + .is_some_and(|value| value.trim().chars().count() > field.max_length()) }) } @@ -184,11 +340,11 @@ pub fn sanitize_attributes( let result: BTreeMap = fields .iter() .filter_map(|field| { - let value = attributes.get(field.key)?.trim(); + let value = attributes.get(&field.key)?.trim(); (!value.is_empty()).then(|| { ( - field.key.to_owned(), - value.chars().take(field.max_length).collect(), + field.key.clone(), + value.chars().take(field.max_length()).collect(), ) }) }) @@ -196,10 +352,14 @@ pub fn sanitize_attributes( (!result.is_empty()).then_some(result) } +#[skip_serializing_none] #[derive(Debug, Clone, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] pub struct Attribute { - pub label: &'static str, - pub text: &'static str, + pub label: String, + pub label_en: Option, + /// The id of the field + pub text: String, pub value: String, } @@ -215,12 +375,13 @@ pub fn describe_attributes( .iter() .filter_map(|field| { let value = attributes - .get(field.key)? + .get(&field.key)? .as_str() .filter(|v| !v.is_empty())?; Some(Attribute { - label: field.label, - text: field.text, + label: field.label.clone(), + label_en: field.label_en.clone(), + text: field.id.clone(), value: value.to_owned(), }) }) @@ -231,75 +392,108 @@ pub fn describe_attributes( mod tests { use super::*; - fn keys(label: &str) -> Vec<&'static str> { - fields_for_label(label) - .unwrap_or(&[]) - .iter() - .map(|f| f.key) - .collect() + fn definition(id: &str, key: &str, short: bool) -> CategoryField { + CategoryField { + id: id.into(), + key: key.into(), + label: id.into(), + label_en: None, + placeholder: None, + placeholder_en: None, + hint: None, + hint_en: None, + short, + not_found_button: false, + } } - #[test] - fn categories_are_matched_by_keywords() { - assert_eq!( - keys("Fahrräder"), - ["frameNumber", "frameSize", "wheelSize", "brand"] - ); - 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!(keys("Sondermodelle").is_empty()); - assert_eq!(keys("Skischuhe"), ["size", "brand"]); - assert_eq!(keys("Laptops"), ["brand", "model"]); + fn definitions() -> Vec { + vec![ + definition("frameNumber", "frameNumber", false), + definition("brand", "brand", false), + definition("clothingSize", "size", true), + definition("shoeSize", "size", true), + ] } #[test] - fn sizes_are_short() { - let fields = fields_for_label("Damenmode").unwrap(); - let values = |size: &str| BTreeMap::from([("size".to_owned(), size.to_owned())]); - assert!(too_long(fields, Some(&values(" 134/140 "))).is_none()); + fn admins_pick_fields_one_size_at_most() { + let pick = |ids: &[&str]| { + let ids: Vec = ids.iter().map(|id| id.to_string()).collect(); + checked_selection(&ids, &definitions()) + }; assert_eq!( - too_long(fields, Some(&values("134/140/146"))).map(|f| f.key), - Some("size") + pick(&["brand", "frameNumber", "brand"]), + Ok(vec!["frameNumber".into(), "brand".into()]) ); - let brand = BTreeMap::from([("brand".to_owned(), "x".repeat(100))]); - assert!(too_long(fields, Some(&brand)).is_none()); + assert_eq!(pick(&["clothingSize", "shoeSize"]), Err("category.oneSize")); + assert_eq!(pick(&["height"]), Err("category.unknownField")); + let definitions = definitions(); + let keys: Vec<_> = requirable_fields(&definitions) + .iter() + .map(|f| f.key.as_str()) + .collect(); + assert_eq!(keys, ["frameNumber", "brand", "size"]); } #[test] - fn sub_categories_inherit_the_fields() { - let bikes = Uuid::new_v4(); - let kids = Uuid::new_v4(); + fn sub_categories_without_a_choice_take_the_main_categorys() { + let (bikes, kids, trailers, gone) = ( + Uuid::new_v4(), + Uuid::new_v4(), + Uuid::new_v4(), + Uuid::new_v4(), + ); let categories = vec![ CategoryRef { id: bikes, - label: "Fahrräder".into(), parent: None, + fields: Some(vec!["frameNumber".into(), "brand".into(), "deleted".into()]), }, CategoryRef { id: kids, - label: "Für Kinder".into(), parent: Some(bikes), + fields: None, + }, + CategoryRef { + id: trailers, + parent: Some(bikes), + fields: Some(vec![]), }, ]; - assert_eq!(category_fields(kids, &categories).len(), 4); + let keys = |id| -> Vec { + category_fields(id, &categories, &definitions()) + .into_iter() + .map(|f| f.key) + .collect() + }; + // A deleted definition is left out + assert_eq!(keys(bikes), ["frameNumber", "brand"]); + assert_eq!(keys(kids), ["frameNumber", "brand"]); + assert!(keys(trailers).is_empty()); + assert!(keys(gone).is_empty()); } #[test] - fn requirable_fields_are_unique_by_key() { - let keys: Vec<_> = requirable_fields().iter().map(|f| f.key).collect(); + fn short_fields_fit_on_the_labels() { + let fields = vec![ + definition("clothingSize", "size", true), + definition("brand", "brand", false), + ]; + let values = |size: &str| BTreeMap::from([("size".to_owned(), size.to_owned())]); + assert!(too_long(&fields, Some(&values(" 134/140 "))).is_none()); assert_eq!( - keys, - [ - "frameNumber", - "frameSize", - "wheelSize", - "brand", - "size", - "model" - ] + too_long(&fields, Some(&values("134/140/146"))).map(|f| f.key.as_str()), + Some("size") ); + let brand = BTreeMap::from([("brand".to_owned(), "x".repeat(100))]); + assert!(too_long(&fields, Some(&brand)).is_none()); + let long = BTreeMap::from([ + ("brand".to_owned(), format!(" {} ", "y".repeat(200))), + ("other".to_owned(), "z".to_owned()), + ]); + let kept = sanitize_attributes(&fields, Some(&long)).unwrap(); + assert_eq!(kept["brand"].len(), MAX_VALUE_LENGTH); + assert!(!kept.contains_key("other")); } } diff --git a/backend/src/modules/event_products.rs b/backend/src/modules/event_products.rs index 2850f221..84dacdee 100644 --- a/backend/src/modules/event_products.rs +++ b/backend/src/modules/event_products.rs @@ -222,7 +222,7 @@ pub fn missing_for_event( missing.push("photo".to_owned()); } for key in &features.required_fields { - if !fields.iter().any(|field| field.key == key) { + if !fields.iter().any(|field| &field.key == key) { continue; } let value = product @@ -253,9 +253,35 @@ pub fn missing_label(info: &str, fields: &[CategoryField]) -> String { pub async fn fields_of( conn: &mut PgConnection, category: Uuid, -) -> sqlx::Result<&'static [CategoryField]> { - let categories = category_fields::load_categories(conn).await?; - Ok(category_fields::category_fields(category, &categories)) +) -> sqlx::Result> { + Ok(category_fields::FieldIndex::load(conn) + .await? + .fields(category)) +} + +/// A bazaar takes items of the categories it allows; one that allows a main category +/// takes its sub-categories too. Bazaars without a list take everything. +pub async fn assert_category_allowed( + conn: &mut PgConnection, + category: Uuid, + event: &Event, +) -> AppResult<()> { + if event.categories.is_empty() || event.categories.contains(&category) { + return Ok(()); + } + let parent: Option = sqlx::query_scalar("SELECT parent_id FROM categories WHERE id = $1") + .bind(category) + .fetch_optional(conn) + .await? + .flatten(); + if parent.is_some_and(|parent| event.categories.contains(&parent)) { + return Ok(()); + } + Err(AppError::coded( + axum::http::StatusCode::BAD_REQUEST, + "product.categoryNotAllowed", + &[("event", &event.title)], + )) } /// Refuses a new announcement when the item lacks something the event requires. @@ -264,7 +290,8 @@ async fn assert_ready_for_event( product: &Product, event: &Event, ) -> AppResult<()> { - let fields = fields_of(conn, product.product_category).await?; + assert_category_allowed(conn, product.product_category, event).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/events.rs b/backend/src/modules/events.rs index 455d64ab..6046668d 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -17,7 +17,7 @@ use serde_with::skip_serializing_none; use uuid::Uuid; use super::access::{active_admins, is_platform_admin, require_admin}; -use super::category_fields::requirable_fields; +use super::category_fields::{self, requirable_fields}; use super::docs::{self, Event}; use super::event_exclusions::{exclusion, has_handed_in}; use super::event_roles::{ @@ -782,7 +782,20 @@ fn sanitize_intake_fee(fee: Option) -> AppResult> { /// Validates the organizer's choice. `previous`: the stored features; switches an older /// client does not send keep their value. -fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppResult { +/// The keys of the fields a bazaar can make required, e.g. "frameNumber". +async fn requirable_keys(ctx: &mut Ctx) -> sqlx::Result> { + let definitions = category_fields::load_definitions(ctx.conn()).await?; + Ok(requirable_fields(&definitions) + .into_iter() + .map(|field| field.key.clone()) + .collect()) +} + +fn sanitize_features( + features: FeaturesArgs, + previous: Option<&Value>, + known: &[String], +) -> AppResult { let max = features.max_discount_percent; if let Some(max) = max && (!max.is_finite() || !(1.0..=MAX_DISCOUNT_PERCENT as f64).contains(&max)) @@ -810,11 +823,10 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes .and_then(|p| p.get("requiredFields")) .and_then(|v| serde_json::from_value(v.clone()).ok()), }; - let known: Vec<&'static str> = requirable_fields().iter().map(|f| f.key).collect(); let required_fields: Vec = required_fields .unwrap_or_default() .into_iter() - .filter(|key| known.contains(&key.as_str())) + .filter(|key| known.contains(key)) .fold(Vec::new(), |mut keys, key| { if !keys.contains(&key) { keys.push(key); @@ -1191,9 +1203,10 @@ async fn create_event(ctx: &mut Ctx, args: CreateArgs) -> AppResult { check_access_code(&args.visibility, args.access_code.as_deref())?; check_files(ctx, &[args.cover_image, args.event_map_image]).await?; let public = args.visibility == "public" && !single; + let known = requirable_keys(ctx).await?; let features = args .features - .map(|f| sanitize_features(f, None)) + .map(|f| sanitize_features(f, None, &known)) .transpose()?; let logistics = args.seller_logistics.map(sanitize_logistics).transpose()?; let logistics = logistics.as_ref(); @@ -1310,8 +1323,9 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { start = event.start_date; end = event.end_date; } + let known = requirable_keys(ctx).await?; let features = match args.features { - Some(features) => sanitize_features(features, event.features.as_ref())?, + Some(features) => sanitize_features(features, event.features.as_ref(), &known)?, None => event.features.clone().unwrap_or_else(|| json!({})), }; // A sale is booked the way the event was set when it was made. Switching afterwards @@ -1883,6 +1897,10 @@ pub fn notify_admins_event_pending( mod tests { use super::*; + fn known() -> Vec { + vec!["frameNumber".into(), "size".into()] + } + #[test] fn features_are_sanitized() { let stored = sanitize_features( @@ -1898,6 +1916,7 @@ mod tests { ..FeaturesArgs::default() }, Some(&json!({ "fixedSellerData": true, "labelMark": "universal" })), + &known(), ) .unwrap(); assert_eq!(stored["discounts"], false); @@ -1921,6 +1940,7 @@ mod tests { ..FeaturesArgs::default() }, None, + &known(), ) .unwrap(); assert_eq!(stored["publicCatalog"], false); @@ -1933,6 +1953,7 @@ mod tests { ..FeaturesArgs::default() }, Some(&stored), + &known(), ) .unwrap(); assert_eq!(kept["publicCatalog"], false); @@ -1941,7 +1962,11 @@ mod tests { #[test] fn feature_ranges_are_checked() { - let err = |features: FeaturesArgs| sanitize_features(features, None).unwrap_err().code(); + let err = |features: FeaturesArgs| { + sanitize_features(features, None, &known()) + .unwrap_err() + .code() + }; assert_eq!( err(FeaturesArgs { max_discount_percent: Some(80.0), diff --git a/backend/src/modules/products.rs b/backend/src/modules/products.rs index c9724726..438980d4 100644 --- a/backend/src/modules/products.rs +++ b/backend/src/modules/products.rs @@ -12,11 +12,12 @@ use sqlx::PgConnection; use uuid::Uuid; use super::access::is_platform_admin; +use super::categories::assert_for_items; use super::category_fields::{self, Attribute}; use super::docs::{self, Event, EventProduct, Product}; use super::event_products::{ - Events, are_relations_locked, fields_of, is_product_locked, missing_for_event, missing_label, - pick_active_listing, relations_of_product, + Events, are_relations_locked, assert_category_allowed, fields_of, is_product_locked, + missing_for_event, missing_label, pick_active_listing, relations_of_product, }; use super::event_roles::find_organizer_event; use super::events::{admitted_by_visibility, is_live}; @@ -66,14 +67,14 @@ 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) { Some(field) => Err(AppError::coded( axum::http::StatusCode::BAD_REQUEST, "product.sizeTooLong", - &[("max", &field.max_length.to_string())], + &[("max", &field.max_length().to_string())], )), None => Ok(()), } @@ -88,7 +89,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 => { @@ -215,6 +216,7 @@ async fn add_product(ctx: &mut Ctx, args: AddArgs) -> AppResult { } check_condition(&args.condition)?; check_category(ctx.conn(), args.product_category.0).await?; + assert_for_items(ctx.conn(), args.product_category.0).await?; let price = price(args.price)?; let (attributes, minimum) = normalize_extras( ctx.conn(), @@ -269,7 +271,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 { @@ -322,6 +324,21 @@ async fn update_product(ctx: &mut Ctx, args: UpdateArgs) -> AppResult<()> { let product = own_unlocked_product(ctx, args.product_id.0).await?; check_condition(&args.condition)?; check_category(ctx.conn(), args.product_category.0).await?; + if args.product_category.0 != product.product_category { + assert_for_items(ctx.conn(), args.product_category.0).await?; + // The bazaars it is announced for must take the new category + let events: Vec = sqlx::query_scalar( + "SELECT event_id FROM event_products WHERE product_id = $1 AND status = 'announced'", + ) + .bind(product.id) + .fetch_all(ctx.conn()) + .await?; + for event in events { + if let Some(event) = docs::event(ctx.conn(), event).await? { + assert_category_allowed(ctx.conn(), args.product_category.0, &event).await?; + } + } + } let price = price(args.price)?; let (attributes, minimum) = normalize_extras( ctx.conn(), @@ -413,7 +430,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 +781,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) = ( @@ -537,7 +537,10 @@ async fn send_receipt( value: product.clone(), }]; details.extend(attributes.iter().map(|a| Detail { - label: a.label.to_owned(), + label: match (&a.label_en, locale) { + (Some(en), Locale::En) => en.clone(), + _ => a.label.clone(), + }, value: a.value.clone(), })); details.push(Detail { @@ -786,7 +789,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); @@ -860,7 +863,7 @@ async fn get_checkout_snapshot(ctx: &mut Ctx, args: EventIdArgs) -> AppResult AppResult AppResult, attributes: Option<&Value>, ) -> Vec { match category { - Some(category) => category_fields::describe_attributes( - category_fields::category_fields(category, categories), - attributes, - ), + Some(category) => category_fields::describe_attributes(&index.fields(category), attributes), None => Vec::new(), } } @@ -437,7 +434,7 @@ async fn get_proof_of_offers(ctx: &mut Ctx, args: EventArgs) -> AppResult let event = docs::event(ctx.conn(), event_id) .await? .ok_or_else(|| AppError::not_found("notFound.event"))?; - let categories = category_fields::load_categories(ctx.conn()).await?; + let index = category_fields::FieldIndex::load(ctx.conn()).await?; let records: Vec = sqlx::query_as( "SELECT r.product_id, r.seller_id, r.title, r.category_id, r.category_label, r.attributes, r.price, ep.status::text AS status, pu.total_amount AS sold_for, @@ -470,7 +467,7 @@ async fn get_proof_of_offers(ctx: &mut Ctx, args: EventArgs) -> AppResult items.push(ProofItem { product_id: record.product_id, category: record.category_label.unwrap_or_default(), - attributes: attributes(&categories, record.category_id, record.attributes.as_ref()), + attributes: attributes(&index, record.category_id, record.attributes.as_ref()), title: record.title, price: record.price, status, @@ -485,7 +482,7 @@ async fn get_proof_of_offers(ctx: &mut Ctx, args: EventArgs) -> AppResult product_id: purchase.product_id, category: purchase.category_label.clone().unwrap_or_default(), attributes: attributes( - &categories, + &index, purchase.category_id, purchase.product_attributes.as_ref(), ), diff --git a/backend/src/modules/walk_in_sellers.rs b/backend/src/modules/walk_in_sellers.rs index 47d25741..8a949459 100644 --- a/backend/src/modules/walk_in_sellers.rs +++ b/backend/src/modules/walk_in_sellers.rs @@ -160,6 +160,22 @@ async fn save_walk_in_product(ctx: &mut Ctx, args: SaveArgs) -> AppResult } check_condition(&args.condition)?; check_category(ctx.conn(), args.product_category.0).await?; + let changed = match args.product_id { + Some(id) => { + let current: Option = + sqlx::query_scalar("SELECT category_id FROM products WHERE id = $1") + .bind(id.0) + .fetch_optional(ctx.conn()) + .await?; + current != Some(args.product_category.0) + } + None => true, + }; + if changed { + super::categories::assert_for_items(ctx.conn(), args.product_category.0).await?; + super::event_products::assert_category_allowed(ctx.conn(), args.product_category.0, &event) + .await?; + } let (attributes, minimum) = normalize_extras( ctx.conn(), args.product_category.0, diff --git a/backend/tests/api/categories.rs b/backend/tests/api/categories.rs index 9aaf50c8..aad86521 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), (89, 89)); } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] @@ -187,11 +187,21 @@ async fn the_start_of_the_server_only_fills_an_empty_table(db: PgPool) { }; let start = || rpc::call(&app.state, None, "categories.seedIfEmpty", json!({})); + // As after removing all data: the fields of the default categories come back with them + sqlx::query("DELETE FROM category_field_definitions") + .execute(&db) + .await + .unwrap(); // A new instance gets the defaults, and a second start adds nothing start().await.unwrap(); - assert_eq!(labels().await.len(), 11); + let fields: i64 = sqlx::query_scalar("SELECT count(*) FROM category_field_definitions") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(fields, 9); + assert_eq!(labels().await.len(), 89); start().await.unwrap(); - assert_eq!(labels().await.len(), 11); + assert_eq!(labels().await.len(), 89); // An instance with categories of its own does not get the defaults back sqlx::query("DELETE FROM categories WHERE label <> 'Kleidung'") @@ -390,6 +400,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")] @@ -422,3 +523,181 @@ 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); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn admins_define_extra_fields(db: PgPool) { + let app = app(&db).await; + let user = app.user_session("user@example.org", false).await; + let admin = app.user_session("admin@example.org", true).await; + let save = |args: Value, session| { + let app = &app; + async move { app.mutation("categories.saveField", args, session).await } + }; + + let forbidden = save(json!({ "label": "Höhe", "short": false }), Some(&user)).await; + assert_eq!(forbidden.status, StatusCode::FORBIDDEN); + assert_eq!( + save(json!({ "label": " ", "short": false }), Some(&admin)) + .await + .body["code"], + "category.labelEmpty" + ); + let created = save( + json!({ "label": " Höhe ", "labelEn": "Height", "placeholder": "", "short": true }), + Some(&admin), + ) + .await; + let id = created.body["value"].as_str().unwrap().to_owned(); + + // Everybody reads the fields; a new one stores its values under its own key + let fields = app.query("categories.listFields", json!({}), None).await; + let height = fields.body["value"] + .as_array() + .unwrap() + .iter() + .find(|f| f["_id"] == id.as_str()) + .unwrap() + .clone(); + assert_eq!(height["key"], id.as_str()); + assert_eq!(height["label"], "Höhe"); + assert_eq!(height["labelEn"], "Height"); + assert!(height.get("placeholder").is_none()); + assert_eq!(height["short"], true); + + // A category picks it and its items get it; the main category's sub-categories too + let main = app + .mutation( + "categories.createCategory", + json!({ "label": "Möbel", "fields": [id, "brand"] }), + Some(&admin), + ) + .await + .body["value"] + .clone(); + app.mutation( + "categories.createCategory", + json!({ "label": "Regale", "parentCategory": main }), + Some(&admin), + ) + .await; + let list = app + .query("categories.getAllCategories", json!({}), None) + .await; + let shelves = list.body["value"] + .as_array() + .unwrap() + .iter() + .find(|c| c["label"] == "Regale") + .unwrap() + .clone(); + let names: Vec<&str> = shelves["fieldList"] + .as_array() + .unwrap() + .iter() + .map(|f| f["label"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["Marke", "Höhe"]); + + // Renamed in place; in use it cannot be deleted + let renamed = save( + json!({ "fieldId": id, "label": "Höhe (cm)", "short": true }), + Some(&admin), + ) + .await; + assert_eq!(renamed.status, StatusCode::OK); + let delete = |field: &str| { + let (app, admin) = (&app, &admin); + let args = json!({ "fieldId": field }); + async move { + app.mutation("categories.deleteField", args, Some(admin)) + .await + } + }; + assert_eq!(delete(&id).await.body["code"], "categoryField.inUse"); + let counted = app + .query("categories.listFieldsForAdmin", json!({}), Some(&admin)) + .await; + let row = counted.body["value"] + .as_array() + .unwrap() + .iter() + .find(|f| f["_id"] == id.as_str()) + .unwrap() + .clone(); + assert_eq!(row["categoryCount"], 1); + assert_eq!(row["label"], "Höhe (cm)"); + assert_eq!(delete("model").await.status, StatusCode::OK); + assert_eq!(delete("model").await.status, StatusCode::NOT_FOUND); +} diff --git a/backend/tests/api/demo.rs b/backend/tests/api/demo.rs index 2a4a310d..c6c2ca08 100644 --- a/backend/tests/api/demo.rs +++ b/backend/tests/api/demo.rs @@ -53,6 +53,19 @@ async fn bazaars_in_every_state(db: PgPool) { let app = TestApp::new(db.clone()); demo::run(&app.state, options(Locale::De)).await.unwrap(); + // The whole default tree, as on a fresh instance: main categories with sub-categories + assert_eq!(count(&db, "SELECT count(*) FROM categories").await, 89); + assert_eq!( + count( + &db, + "SELECT count(*) FROM categories c JOIN categories p ON p.id = c.parent_id + WHERE c.label = 'Lastenräder' AND p.label = 'Fahrräder' + AND c.translations->>'en' = 'Cargo bikes'" + ) + .await, + 1 + ); + // The accounts of the end-to-end tests and of the demo people sign in with 123456 sign_in(&app, "user1@bazarpro.de").await; let admin = sign_in(&app, "admin@bazarpro.de").await; @@ -367,6 +380,17 @@ async fn english_demo_for_screenshots(db: PgPool) { .await, 0 ); + // The default tree in English, labelled with the English names + assert_eq!(count(&db, "SELECT count(*) FROM categories").await, 89); + assert_eq!( + count( + &db, + "SELECT count(*) FROM categories c JOIN categories p ON p.id = c.parent_id + WHERE c.label = 'Cargo bikes' AND p.label = 'Bikes' AND c.translations = '{}'" + ) + .await, + 1 + ); sign_in(&app, "sarah.miller@example.org").await; let titles: Vec = sqlx::query_scalar("SELECT title FROM events ORDER BY title") .fetch_all(&db) @@ -384,7 +408,8 @@ async fn english_demo_for_screenshots(db: PgPool) { .await .unwrap(); assert!( - labels.contains(&"Toys".to_owned()) && !labels.contains(&"Spielzeug".to_owned()), + labels.contains(&"Dolls & plush".to_owned()) + && !labels.contains(&"Puppen & Plüsch".to_owned()), "{labels:?}" ); assert_eq!( diff --git a/backend/tests/api/products.rs b/backend/tests/api/products.rs index 8aacd73a..1e9c83ad 100644 --- a/backend/tests/api/products.rs +++ b/backend/tests/api/products.rs @@ -142,7 +142,12 @@ async fn adding_updating_and_deleting_items(db: PgPool) { assert_eq!(product["attributes"], json!({ "frameNumber": "WBK123" })); assert_eq!( product["attributeList"], - json!([{ "label": "Rahmennummer", "text": "frameNumber", "value": "WBK123" }]) + json!([{ + "label": "Rahmennummer", + "labelEn": "Frame number", + "text": "frameNumber", + "value": "WBK123" + }]) ); assert_eq!(product["minimumPrice"], 30.0); assert_eq!(product["categoryName"], "Fahrräder"); @@ -1556,3 +1561,99 @@ async fn upload_url_and_image_urls(db: PgPool) { )]) ); } + +/// A category below another one, as an admin arranges them. +async fn sub_category(db: &PgPool, label: &str, parent: Uuid) -> Uuid { + sqlx::query_scalar("INSERT INTO categories (label, parent_id) VALUES ($1, $2) RETURNING id") + .bind(label) + .bind(parent) + .fetch_one(db) + .await + .unwrap() +} + +async fn allow(db: &PgPool, event: Uuid, categories: &[Uuid]) { + for (position, category) in categories.iter().enumerate() { + sqlx::query( + "INSERT INTO event_categories (event_id, position, category_id) VALUES ($1, $2, $3)", + ) + .bind(event) + .bind(position as i32) + .bind(category) + .execute(db) + .await + .unwrap(); + } +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn items_go_into_sub_categories_a_bazaar_allows(db: PgPool) { + let app = TestApp::new(db.clone()); + let erika = seller(&db, "Erika").await; + let bikes = fixtures::category(&db, "Fahrräder").await; + let trekking = sub_category(&db, "Trekkingräder", bikes).await; + let trailers = sub_category(&db, "Fahrradanhänger", bikes).await; + let books = fixtures::category(&db, "Bücher").await; + let image = photo(&app, &erika).await; + + // A main category with sub-categories only groups them + let main = app + .mutation( + "products.addProduct", + product_args(&erika, bikes, vec![image.clone()]), + Some(&erika.session), + ) + .await; + assert_eq!(main.body["code"], "product.chooseSubcategory"); + let bike = add( + &app, + &erika, + product_args(&erika, trekking, vec![image.clone()]), + ) + .await; + let book = add( + &app, + &erika, + product_args(&erika, books, vec![image.clone()]), + ) + .await; + + // A bazaar that allows "Fahrräder" takes its sub-categories, nothing else + let organizer = fixtures::user(&db, "Olga").await; + let market = fixtures::event(&db, EventSpec::new("Radmarkt", organizer)).await; + allow(&db, market, &[bikes]).await; + assert_eq!( + announce(&app, &erika, market, bike).await.status, + StatusCode::OK + ); + let refused = announce(&app, &erika, market, book).await; + assert_eq!(refused.body["code"], "product.categoryNotAllowed"); + assert_eq!( + refused.body["message"], + "Diese Kategorie ist bei „Radmarkt“ nicht erlaubt." + ); + + // One that allows single sub-categories takes only those + let picky = fixtures::event(&db, EventSpec::new("Nur Trekking", organizer)).await; + allow(&db, picky, &[trekking]).await; + assert_eq!( + announce(&app, &erika, picky, bike).await.status, + StatusCode::OK + ); + + // An announced item cannot move to a category one of its bazaars does not take + let args = json!({ + "productId": bike, + "title": "Kinderfahrrad", + "description": "Gut erhalten", + "condition": "good", + "productCategory": trailers, + "images": [image], + "price": 40, + "readyForSale": true, + }); + let moved = app + .mutation("products.updateProduct", args, Some(&erika.session)) + .await; + assert_eq!(moved.body["code"], "product.categoryNotAllowed"); +} diff --git a/backend/tests/common/fixtures.rs b/backend/tests/common/fixtures.rs index 7e4b5c0b..30ce937c 100644 --- a/backend/tests/common/fixtures.rs +++ b/backend/tests/common/fixtures.rs @@ -32,9 +32,17 @@ pub async fn session(db: &PgPool, user: Uuid) -> String { session::create(&mut conn, user).await.unwrap() } +/// A category with the extra fields of the default one of that name (migration 0034). pub async fn category(db: &PgPool, label: &str) -> Uuid { - sqlx::query_scalar("INSERT INTO categories (label) VALUES ($1) RETURNING id") + let fields: Option<&[&str]> = match label { + "Fahrräder" => Some(&["frameNumber", "frameSize", "wheelSize", "brand", "color"]), + "Kleidung" => Some(&["clothingSize", "brand", "color"]), + "Sport" => Some(&["sportSize", "brand", "color"]), + _ => None, + }; + sqlx::query_scalar("INSERT INTO categories (label, fields) VALUES ($1, $2) RETURNING id") .bind(label) + .bind(fields) .fetch_one(db) .await .unwrap() diff --git a/src/components/events/SellerConditions.test.tsx b/src/components/events/SellerConditions.test.tsx index 3739ebe8..bfac2ff4 100644 --- a/src/components/events/SellerConditions.test.tsx +++ b/src/components/events/SellerConditions.test.tsx @@ -1,7 +1,20 @@ import { render, screen } from '@testing-library/react'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { SellerConditions } from './SellerConditions'; +// The extra fields admins defined, for the names of required ones +vi.mock('../../lib/api/react', () => ({ + useQuery: () => [ + { + _id: 'frameNumber', + key: 'frameNumber', + label: 'Rahmennummer', + short: false, + notFoundButton: true, + }, + ], +})); + describe('SellerConditions', () => { it('shows fees, a worked example, the rules and the times', () => { render( diff --git a/src/components/events/SellerConditions.tsx b/src/components/events/SellerConditions.tsx index c77ed359..38646721 100644 --- a/src/components/events/SellerConditions.tsx +++ b/src/components/events/SellerConditions.tsx @@ -8,6 +8,7 @@ import { type SellerConditionsEvent, } from '../../lib/sellerFees'; import { resolveEventFeatures } from '../../shared/eventFeatures'; +import { useCategoryFieldDefinitions } from '../../hooks/useCategoryFields'; import { cn, formatPriceDE } from '../../lib/utils'; import { useTranslation } from 'react-i18next'; @@ -33,7 +34,10 @@ export function SellerConditions({ commission: event.commission, intakeFee: resolveEventFeatures(event).intakeFee, }); - const rules = describeSellerRules(event).filter((rule) => !compact || rule.allowed); + const fieldDefinitions = useCategoryFieldDefinitions(); + const rules = describeSellerRules(event, fieldDefinitions).filter( + (rule) => !compact || rule.allowed + ); const schedule = describeSellerSchedule(event); return ( diff --git a/src/components/products/CategoryPicker.test.tsx b/src/components/products/CategoryPicker.test.tsx new file mode 100644 index 00000000..4cb405de --- /dev/null +++ b/src/components/products/CategoryPicker.test.tsx @@ -0,0 +1,76 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { CategoryPicker } from './CategoryPicker'; + +const categories = [ + { _id: 'bikes', label: 'Fahrräder' }, + { _id: 'trekking', label: 'Trekkingräder', parentCategory: 'bikes' }, + { _id: 'cargo', label: 'Lastenräder', parentCategory: 'bikes' }, + { _id: 'clothes', label: 'Kleidung' }, + { _id: 'kids', label: 'Kinderkleidung', parentCategory: 'clothes' }, + { _id: 'misc', label: 'Sonstiges' }, +]; + +// Radix opens the menu on pointer down +const open = () => + fireEvent.pointerDown(screen.getByRole('button', { name: /Kategorie wählen|›/ }), { + button: 0, + ctrlKey: false, + }); + +describe('CategoryPicker', () => { + it('shows main categories; one opens to its sub-categories, which are picked', () => { + const onChange = vi.fn(); + render( + + ); + open(); + expect(screen.getByRole('menuitem', { name: /Fahrräder/ })).toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'Trekkingräder' })).not.toBeInTheDocument(); + + // A main category with sub-categories only opens them + fireEvent.click(screen.getByRole('menuitem', { name: /Fahrräder/ })); + expect(onChange).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('menuitem', { name: 'Trekkingräder' })); + expect(onChange).toHaveBeenCalledWith('trekking'); + }); + + it('a main category without sub-categories is picked directly', () => { + const onChange = vi.fn(); + render( + + ); + open(); + fireEvent.click(screen.getByRole('menuitem', { name: 'Sonstiges' })); + expect(onChange).toHaveBeenCalledWith('misc'); + }); + + it('names the main category of the choice and leaves out what is not allowed', () => { + render( + {}} + isAllowed={(id) => id !== 'trekking' && id !== 'misc'} + placeholder="Kategorie wählen" + /> + ); + expect(screen.getByRole('button', { name: /Fahrräder ›\s*Lastenräder/ })).toBeInTheDocument(); + open(); + // The group of the choice is open + expect(screen.getByRole('menuitem', { name: 'Lastenräder' })).toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'Trekkingräder' })).not.toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'Sonstiges' })).not.toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: /Kleidung/ })).toBeInTheDocument(); + }); +}); diff --git a/src/components/products/CategoryPicker.tsx b/src/components/products/CategoryPicker.tsx new file mode 100644 index 00000000..74b18578 --- /dev/null +++ b/src/components/products/CategoryPicker.tsx @@ -0,0 +1,141 @@ +import { useState } from 'react'; +import { Check, ChevronDown, ChevronRight } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '../ui/dropdown-menu'; +import { categoryName } from '../../i18n/categories'; +import type { CategoryTranslations } from '../../lib/api/types'; +import { cn } from '../../lib/utils'; +import { groupCategories } from '../../shared/categoryTree'; + +type PickableCategory = { + _id: string; + label: string; + parentCategory?: string; + translations?: CategoryTranslations; +}; + +/** + * The category of an item: first the main categories, a click opens one and shows its + * sub-categories. Items go into sub-categories, so a main category with some is not + * pickable itself. `isAllowed` leaves out what the chosen bazaars do not take. + */ +export function CategoryPicker({ + id, + categories, + value, + onChange, + isAllowed = () => true, + disabled = false, + invalid = false, + placeholder, +}: { + id?: string; + categories: readonly PickableCategory[]; + value: string | undefined; + onChange: (categoryId: string) => void; + isAllowed?: (categoryId: string) => boolean; + disabled?: boolean; + invalid?: boolean; + placeholder: string; +}) { + const { t } = useTranslation('seller'); + const groups = groupCategories(categories) + .map(({ category, children }) => ({ + category, + children: children.filter((child) => isAllowed(child._id)), + leaf: children.length === 0, + })) + .filter(({ category, children, leaf }) => + leaf ? isAllowed(category._id) : children.length > 0 + ); + const selected = categories.find((category) => category._id === value); + const selectedMain = selected?.parentCategory + ? categories.find((category) => category._id === selected.parentCategory) + : undefined; + // The group of the choice is open, or the only one there is + const shownMain = groups.find(({ category }) => category._id === selectedMain?._id); + const initiallyOpen = + shownMain?.category._id ?? + (groups.length === 1 && !groups[0].leaf ? groups[0].category._id : undefined); + const [open, setOpen] = useState(initiallyOpen); + + return ( + isOpen && setOpen(initiallyOpen)}> + + + {selected ? ( + <> + {selectedMain && ( + {categoryName(selectedMain)} › + )} + {categoryName(selected)} + + ) : ( + placeholder + )} + + + + + {groups.length === 0 && ( +

{t('form.noCategories')}

+ )} + {groups.map(({ category, children, leaf }) => { + if (leaf) { + return ( + onChange(category._id)}> + {categoryName(category)} + {value === category._id && } + + ); + } + const isOpen = open === category._id; + return ( +
+ { + event.preventDefault(); + setOpen(isOpen ? undefined : category._id); + }} + className={cn('font-medium', selectedMain?._id === category._id && 'text-primary')} + > + {categoryName(category)} + {children.length} + + + {isOpen && + children.map((child) => ( + onChange(child._id)} + className="pl-6" + > + {categoryName(child)} + {value === child._id && } + + ))} +
+ ); + })} +
+
+ ); +} 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/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx index 5405bb66..f0e4376b 100644 --- a/src/components/ui/checkbox.tsx +++ b/src/components/ui/checkbox.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; -import { CheckIcon } from 'lucide-react'; +import { CheckIcon, MinusIcon } from 'lucide-react'; import { cn } from '../../lib/utils'; @@ -11,7 +11,7 @@ function Checkbox({ className, ...props }: React.ComponentProps - + {props.checked === 'indeterminate' ? ( + + ) : ( + + )} ); diff --git a/src/components/walkIn/WalkInProductDialog.tsx b/src/components/walkIn/WalkInProductDialog.tsx index e2cc2368..b1aa5801 100644 --- a/src/components/walkIn/WalkInProductDialog.tsx +++ b/src/components/walkIn/WalkInProductDialog.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'; import { FormProvider, useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; -import { useApiClient, useMutation } from '../../lib/api/react'; +import { useApiClient, useMutation, useQuery } from '../../lib/api/react'; import { toast } from 'sonner'; import { api } from '../../lib/api/functions'; import type { Doc, Id } from '../../lib/api/types'; @@ -87,6 +87,7 @@ export function WalkInProductDialog({ }) { const { t } = useTranslation('organizer'); const saveProduct = useMutation(api.walkInSellers.saveWalkInProduct); + const event = useQuery(api.events.getEvent, open ? { id: eventId } : 'skip'); const client = useApiClient(); const generateUploadUrl = useMutation(api.products.generateUploadUrl); const [imageFiles, setImageFiles] = useState([]); @@ -176,7 +177,7 @@ export function WalkInProductDialog({
onSubmit(data, false))}> - +
{product && product.images.length > 0 && ( diff --git a/src/hooks/useCategoryFields.ts b/src/hooks/useCategoryFields.ts new file mode 100644 index 00000000..0dcec059 --- /dev/null +++ b/src/hooks/useCategoryFields.ts @@ -0,0 +1,13 @@ +import { api } from '../lib/api/functions'; +import { requirableFields, type CategoryField } from '../shared/categoryFields'; +import { usePublicQuery } from './usePublicQuery'; + +/** The extra fields admins defined; undefined while loading. */ +export function useCategoryFieldDefinitions(): CategoryField[] | undefined { + return usePublicQuery(api.categories.listFields, {}); +} + +/** The fields a bazaar can make required, one per key. */ +export function useRequirableFields(): CategoryField[] { + return requirableFields(useCategoryFieldDefinitions()); +} 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/i18n/categoryFields.ts b/src/i18n/categoryFields.ts index 0b785368..1af0acf6 100644 --- a/src/i18n/categoryFields.ts +++ b/src/i18n/categoryFields.ts @@ -1,13 +1,25 @@ import i18n from '.'; -import type { CategoryFieldText } from '../shared/categoryFields'; -/** Label, placeholder or hint of a category field in the current language. */ +type FieldTexts = { + label?: string; + labelEn?: string; + placeholder?: string; + placeholderEn?: string; + hint?: string; + hintEn?: string; +}; + +/** + * Label, placeholder or hint of a category field in the current language: admins enter + * them in German and English. The texts of the "not found" button are the same for all. + */ export function categoryFieldText( - field: { text: CategoryFieldText }, + field: FieldTexts, part: 'label' | 'placeholder' | 'hint' | 'notFound' | 'notFoundValue' ): string | undefined { - const key = `categoryFields.${field.text}.${part}`; - return i18n.exists(key, { ns: 'records' }) - ? (i18n.t(key as never, { ns: 'records' }) as string) - : undefined; + if (part === 'notFound' || part === 'notFoundValue') { + return i18n.t(`categoryFields.${part}`, { ns: 'records' }); + } + const english = i18n.resolvedLanguage === 'en' ? field[`${part}En`] : undefined; + return english || field[part] || undefined; } diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index beaa198e..ce074112 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -6,6 +6,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ +import type { CategoryField, DescribedAttribute } from '../../shared/categoryFields'; import type { EventProductStatus, EventServices, HelperPermission } from '../../shared/constants'; export type TableName = @@ -185,6 +186,10 @@ export interface Docs { parentCategory?: Id<'categories'> | undefined; updatedAt: number; label: string; + /** Ids of the extra fields an admin picked; unset: those of the main category */ + fields?: string[] | undefined; + /** The extra fields its items have, from its own choice or its main category */ + fieldList: CategoryField[]; }; eventLocationCategories: { _id: Id<'eventLocationCategories'>; @@ -352,16 +357,11 @@ export type BroadcastView = { _id: Id<'eventBroadcasts'>; }; -export type CategoryFieldText = - | 'brand' - | 'frameNumber' - | 'frameSize' - | 'wheelSize' - | 'bikeBrand' - | 'clothingSize' - | 'shoeSize' - | 'sportSize' - | 'model'; +/** An extra field of item categories, as admins define it */ +export type CategoryFieldDefinition = CategoryField; + +/** A value of an item with the name of its field (in German and maybe English) */ +export type CategoryAttribute = DescribedAttribute; export type DiscountRules = { allowed: boolean; @@ -433,7 +433,7 @@ export type ProofItem = { productId?: Id<'products'> | undefined; title: string; category: string; - attributes: { label: string; text: CategoryFieldText; value: string }[]; + attributes: CategoryAttribute[]; price: number; status: string; soldFor?: number | undefined; @@ -637,12 +637,21 @@ export interface Api { parentCategory?: Id<'categories'> | undefined; label: string; translations?: CategoryTranslations | undefined; + fields?: string[] | undefined; }, Id<'categories'> >; 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; + /** Unset: those of the main category */ + fields?: string[] | undefined; + }, null >; deleteCategory: FunctionReference<'mutation', { categoryId: Id<'categories'> }, null>; @@ -651,18 +660,29 @@ export interface Api { EmptyObject, (Doc<'categories'> & { productCount: number; eventCount: number; childCount: number })[] >; - getAllCategories: FunctionReference< + getAllCategories: FunctionReference<'query', EmptyObject, Doc<'categories'>[]>; + listFields: FunctionReference<'query', EmptyObject, CategoryField[]>; + listFieldsForAdmin: FunctionReference< 'query', EmptyObject, + (CategoryField & { categoryCount: number })[] + >; + saveField: FunctionReference< + 'mutation', { - _id: Id<'categories'>; - _creationTime: number; - parentCategory?: Id<'categories'> | undefined; - updatedAt: number; + /** Unset: a new field */ + fieldId?: string | undefined; label: string; - translations: CategoryTranslations; - }[] + labelEn?: string | undefined; + placeholder?: string | undefined; + placeholderEn?: string | undefined; + hint?: string | undefined; + hintEn?: string | undefined; + short: boolean; + }, + string >; + deleteField: FunctionReference<'mutation', { fieldId: string }, null>; getCategoryLabel: FunctionReference<'query', { categoryId: Id<'categories'> }, string | null>; getCategoryId: FunctionReference<'query', { categoryLabel: string }, Id<'categories'> | null>; }; @@ -2441,7 +2461,7 @@ export interface Api { 'minimumPrice' > & { minimumPrice?: number | undefined; - attributeList: { label: string; value: string }[]; + attributeList: CategoryAttribute[]; activeListing: { eventId: Id<'events'>; eventProductId: Id<'eventProducts'>; @@ -2529,7 +2549,7 @@ export interface Api { listPrice: number; minimumPrice: number | undefined; sellerPaidOut: boolean; - attributes: { label: string; text: CategoryFieldText; value: string }[]; + attributes: CategoryAttribute[]; internalNote?: string; } | null >; diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index d4e8e389..498a5fa1 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -1,7 +1,6 @@ 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'; describe('event types', () => { @@ -13,8 +12,17 @@ describe('event types', () => { expect(i18n.exists(key, { ns: 'organizer', lng }), `${lng} ${key}`).toBe(true); } } + // Fields of the default categories (migration 0034) for (const key of type.features.requiredFields ?? []) { - expect(REQUIRABLE_FIELD_KEYS).toContain(key); + expect([ + 'frameNumber', + 'frameSize', + 'wheelSize', + 'brand', + 'color', + 'size', + 'model', + ]).toContain(key); } // A printed price only works without discounts if (type.features.priceOnLabel) expect(showsPriceOnLabel(type)).toBe(true); @@ -58,6 +66,59 @@ 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', + 'Kinderfahrzeuge', + ]) { + 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('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); + // Stored as a bazaar does: the sub-categories, a main category when all are in + expect(chosen('kidsBazaar')).toEqual(['kidsClothes', 'maternity', 'kidsBooks', 'vehicles']); + expect(chosen('bikeExchange')).toEqual(['bikes', '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']); + 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..32874903 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -1,5 +1,6 @@ import type { ItemKind } from '../components/illustrations/ItemIllustrations'; import type { StoredEventFeatures } from '../shared/eventFeatures'; +import { compactSelection, groupCategories } from '../shared/categoryTree'; /** * Kinds of bazaars with suggested settings for the creation wizard, the most asked for @@ -16,11 +17,18 @@ 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; +/** Ridden by children, sold at children's bazaars and at bike sales */ +const KIDS_VEHICLES = /kinderfahrz|laufr|roller|scooter|einr[aä]d|bobby|rutsch/i; export const EVENT_TYPES: EventType[] = [ { @@ -42,7 +50,8 @@ 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|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 @@ -63,7 +72,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 @@ -84,7 +93,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 +106,16 @@ 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'), + // Pushed, not ridden + categoryExclude: /kinderwagen|buggy/i, }, ]; @@ -106,3 +123,28 @@ 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, as a bazaar stores them: the sub-categories + * whose name or main category matches, unless the kind excludes them; a main category + * when all of its are in (compactSelection). + */ +export function preselectedCategories( + type: Pick, + categories: readonly { _id: string; label: string; parentCategory?: string }[] +): string[] { + const { categoryMatch: match, categoryExclude: exclude } = type; + if (!match) return []; + const chosen = new Set(); + for (const { category, children } of groupCategories(categories)) { + if (children.length === 0) { + if (match.test(category.label) && !exclude?.test(category.label)) chosen.add(category._id); + continue; + } + for (const child of children) { + if (exclude?.test(child.label)) continue; + if (match.test(child.label) || match.test(category.label)) chosen.add(child._id); + } + } + return compactSelection(chosen, categories); +} diff --git a/src/lib/productCompletion.test.ts b/src/lib/productCompletion.test.ts index 5608d534..dc03e117 100644 --- a/src/lib/productCompletion.test.ts +++ b/src/lib/productCompletion.test.ts @@ -34,7 +34,19 @@ describe('findProductsToComplete', () => { it('asks for required fields only where the category has them', () => { const categories = [ - { _id: 'cat-bikes', label: 'Fahrräder' }, + { + _id: 'cat-bikes', + label: 'Fahrräder', + fieldList: [ + { + _id: 'frameNumber', + key: 'frameNumber', + label: 'Rahmennummer', + short: false, + notFoundButton: true, + }, + ], + }, { _id: 'cat-toys', label: 'Spielzeug' }, ]; const market = { diff --git a/src/lib/productCompletion.ts b/src/lib/productCompletion.ts index d2f1e362..b731ac8c 100644 --- a/src/lib/productCompletion.ts +++ b/src/lib/productCompletion.ts @@ -39,7 +39,7 @@ export interface ProductToComplete { export function findProductsToComplete( products: CompletionProduct[], targetEvents: CompletionEvent[], - categories?: { _id: string; label: string; parentCategory?: string }[] + categories?: { _id: string; fieldList?: CategoryField[] }[] ): ProductToComplete[] { const result: ProductToComplete[] = []; for (const product of products) { diff --git a/src/lib/sellerFees.ts b/src/lib/sellerFees.ts index dcf28036..cd8d25c4 100644 --- a/src/lib/sellerFees.ts +++ b/src/lib/sellerFees.ts @@ -3,7 +3,7 @@ import { resolveEventFeatures, type StoredEventFeatures } from '../shared/eventF import { formatBerlinRange, formatBerlinTime } from '../shared/berlinTime'; import i18n, { currentLocale } from '../i18n'; import { dateLocale } from '../i18n/format'; -import { REQUIRABLE_FIELDS } from '../shared/categoryFields'; +import { requirableFields, type CategoryField } from '../shared/categoryFields'; import { categoryFieldText } from '../i18n/categoryFields'; function text(key: string, values?: Record): string { @@ -111,7 +111,10 @@ export interface SellerRule { } /** Item limit, photos and the price features of the bazaar, as sellers read them. */ -export function describeSellerRules(event: SellerConditionsEvent): SellerRule[] { +export function describeSellerRules( + event: SellerConditionsEvent, + fieldDefinitions?: readonly CategoryField[] +): SellerRule[] { const features = resolveEventFeatures(event); const rules: SellerRule[] = [ { @@ -128,7 +131,7 @@ export function describeSellerRules(event: SellerConditionsEvent): SellerRule[] if (!features.publicCatalog) { rules.push({ text: text('noPublicCatalog'), allowed: true }); } - const required = REQUIRABLE_FIELDS.filter((field) => + const required = requirableFields(fieldDefinitions).filter((field) => features.requiredFields?.includes(field.key) ); if (required.length > 0) { diff --git a/src/locales/de/admin.json b/src/locales/de/admin.json index 676d995a..55789dcf 100644 --- a/src/locales/de/admin.json +++ b/src/locales/de/admin.json @@ -277,21 +277,34 @@ }, "categories": { "title": "Kategorien", - "subtitle": "Kategorien, aus denen Basare und Artikel wählen.", + "subtitle": "Woraus Basare und Artikel wählen: Hauptkategorien gruppieren, Artikel kommen in die Unterkategorien.", + "tabCategories": "Kategorien", + "tabFields": "Zusatzfelder", "add": "Kategorie hinzufügen", + "addSub": "Unterkategorie", + "addSubTo": "Unterkategorie zu „{{name}}“ hinzufügen", "edit": "Kategorie bearbeiten", "new": "Neue Kategorie", + "newSub": "Neue Unterkategorie", "name": "Name", "nameEn": "Englischer Name", - "nameEnHint": "Optional. Ohne englischen Namen sehen englischsprachige Besucher den Namen oben.", + "nameEnHint": "Optional. Sonst sehen englischsprachige Besucher den deutschen Namen.", + "parent": "Gehört zu", + "noParent": "Keiner – Hauptkategorie", + "parentHint": "Artikel kommen in Unterkategorien. Eine Hauptkategorie fasst sie zusammen.", + "parentLocked": "Hat eigene Unterkategorien und bleibt deshalb Hauptkategorie.", + "subcategories_one": "{{count}} Unterkategorie", + "subcategories_other": "{{count}} Unterkategorien", + "showSub": "Unterkategorien von {{name}} zeigen", "fields": "Zusatzfelder", + "fieldsHelp": "Was Verkäufer zu einem Artikel dieser Kategorie zusätzlich angeben, etwa Größe oder Rahmennummer.", + "inherit": "Wie „{{name}}“", + "inheritFields": "Wie „{{name}}“: {{fields}}", + "inheritNone": "Wie „{{name}}“ (keine)", + "own": "Eigene Auswahl", "noFields": "Keine", - "usage": "Verwendung", - "subOf": "Unterkategorie von {{parent}}", - "action": "Aktion", - "fieldsHint": "Der Name entscheidet über die Zusatzfelder der Artikel, etwa die Rahmennummer bei Fahrrädern. Er entscheidet auch, welche Kategorien neue Basare vorausgewählt bekommen.", - "fieldsPreview": "Zusatzfelder mit diesem Namen: {{fields}}", - "noFieldsPreview": "Mit diesem Namen hat die Kategorie keine Zusatzfelder.", + "oneSize": "Nur eine Größe je Kategorie.", + "manageFields": "Fehlt ein Feld? Lege es unter „Zusatzfelder“ an.", "fieldsChange": "Die Zusatzfelder ändern sich für alle Artikel dieser Kategorie.", "duplicate": "Eine Kategorie mit diesem Namen gibt es schon.", "saved": "Kategorie gespeichert", @@ -304,9 +317,35 @@ "empty": "Noch keine Kategorien", "editShort": "Bearbeiten", "save": "Speichern", + "cancel": "Abbrechen", "usageProducts_one": "{{count}} Artikel", "usageProducts_other": "{{count}} Artikel", "usageEvents_one": "{{count}} Basar", "usageEvents_other": "{{count}} Basare" + }, + "categoryFields": { + "intro": "Felder, die Verkäufer zu ihren Artikeln angeben. Welche eine Kategorie hat, wählst du bei der Kategorie.", + "add": "Feld hinzufügen", + "new": "Neues Zusatzfeld", + "edit": "Zusatzfeld bearbeiten", + "label": "Name", + "labelEn": "Englischer Name", + "placeholder": "Beispiel im Eingabefeld", + "placeholderEn": "Beispiel auf Englisch", + "placeholderHint": "Zum Beispiel „z. B. 38“. Optional.", + "hint": "Hinweis unter dem Feld", + "hintEn": "Hinweis auf Englisch", + "short": "Kurzer Wert", + "shortHint": "Höchstens 7 Zeichen, damit er aufs Etikett passt – zum Beispiel eine Größe.", + "shortBadge": "Kurz", + "used_one": "In {{count}} Kategorie", + "used_other": "In {{count}} Kategorien", + "unused": "Noch in keiner Kategorie", + "saved": "Zusatzfeld gespeichert", + "deleted": "Zusatzfeld gelöscht", + "deleteTitle": "„{{name}}“ löschen?", + "deleteText": "Artikel behalten ihre Werte, sie werden nur nicht mehr angezeigt.", + "inUse": "Wird noch von Kategorien verwendet.", + "empty": "Noch keine Zusatzfelder" } } diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 26f1f2f0..cefa861a 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -39,6 +39,10 @@ "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.", + "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": { @@ -122,7 +126,8 @@ "product": "Artikel nicht gefunden.", "question": "Frage nicht gefunden.", "report": "Meldung nicht gefunden.", - "user": "Nutzer nicht gefunden." + "user": "Nutzer nicht gefunden.", + "categoryField": "Zusatzfeld nicht gefunden." }, "offline": { "failed": "Die Aktion ließ sich nicht nachholen. Bitte von Hand erledigen.", @@ -181,7 +186,9 @@ "rejected": "Der Artikel wurde abgelehnt. Nimm zuerst die Ablehnung zurück.", "rejectedNoRemove": "Abgelehnte Artikel bleiben beim Basar vermerkt und können nicht entfernt werden.", "notRegistered": "Melde dich zuerst als Verkäufer bei diesem Basar an.", - "rejectedHere": "„{{title}}“ wurde bei „{{event}}“ abgelehnt und kann dort nicht erneut angemeldet werden." + "rejectedHere": "„{{title}}“ wurde bei „{{event}}“ abgelehnt und kann dort nicht erneut angemeldet werden.", + "chooseSubcategory": "Bitte wähle eine Unterkategorie, zum Beispiel unter „Fahrräder“ die Art des Rads.", + "categoryNotAllowed": "Diese Kategorie ist bei „{{event}}“ nicht erlaubt." }, "profile": { "nameRequired": "Bitte Vor- und Nachnamen angeben.", @@ -259,5 +266,8 @@ "upload": { "quotaExceeded": "Du hast zu viele Bilder hochgeladen, die noch nicht gespeichert sind. Bitte speichere zuerst oder versuche es später noch einmal.", "tooMany": "Du hast sehr viele Bilder hochgeladen. Bitte versuche es später noch einmal." + }, + "categoryField": { + "inUse": "Dieses Zusatzfeld wird noch von Kategorien verwendet. Entferne es dort zuerst." } } diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 70042f41..344d2aba 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -101,7 +101,14 @@ "categories": { "title": "Kategorien & Services", "allowed": "Erlaubte Artikelkategorien *", - "services": "Zusätzliche Services" + "subcategories": "Unterkategorien von {{name}}", + "services": "Zusätzliche Services", + "allowedHint": "Verkäufer können nur Artikel dieser Kategorien anmelden. Klappe eine Kategorie auf, um einzelne Unterkategorien zu wählen.", + "selectAll": "Alle", + "selectNone": "Keine", + "chosenAll": "alle", + "chosenSome": "{{count}} von {{total}}", + "chosenSummary": "{{count}} von {{total}} Hauptkategorien gewählt" }, "contact": { "title": "Kontakt & Finanzen", @@ -1088,7 +1095,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..eb2e20fb 100644 --- a/src/locales/de/records.json +++ b/src/locales/de/records.json @@ -64,43 +64,8 @@ } }, "categoryFields": { - "frameNumber": { - "label": "Rahmennummer", - "placeholder": "z. B. WBK123456", - "hint": "Nicht gefunden? Schreib „nicht gefunden“ hinein – wir suchen sie vor Ort gemeinsam.", - "notFound": "Nicht gefunden", - "notFoundValue": "nicht gefunden" - }, - "frameSize": { - "label": "Rahmengröße", - "placeholder": "z. B. 52 cm oder M" - }, - "wheelSize": { - "label": "Laufradgröße", - "placeholder": "z. B. 28 Zoll" - }, - "bikeBrand": { - "label": "Marke", - "placeholder": "z. B. Cube" - }, - "clothingSize": { - "label": "Größe", - "placeholder": "z. B. M oder 128" - }, - "shoeSize": { - "label": "Größe (EU)", - "placeholder": "z. B. 38" - }, - "sportSize": { - "label": "Größe / Länge", - "placeholder": "z. B. 160 cm" - }, - "brand": { - "label": "Marke" - }, - "model": { - "label": "Modell" - } + "notFound": "Nicht gefunden", + "notFoundValue": "nicht gefunden" }, "service": { "Parkplatz": "Parkplatz", diff --git a/src/locales/de/seller.json b/src/locales/de/seller.json index 8a25c27c..99d52a34 100644 --- a/src/locales/de/seller.json +++ b/src/locales/de/seller.json @@ -2,6 +2,7 @@ "myProducts": { "soldCannotAdd": "Verkaufte Artikel können nicht mehr zu Basaren hinzugefügt werden.", "cannotUnregister": "Dieser Artikel kann nicht mehr abgemeldet werden.", + "categoryNotAllowed": "Die Kategorie dieses Artikels ist bei „{{event}}“ nicht erlaubt.", "deletedMany_one": "{{count}} Artikel gelöscht", "deletedMany_other": "{{count}} Artikel gelöscht", "deleteFailed": "Löschen fehlgeschlagen", @@ -122,6 +123,10 @@ "chooseCondition": "Zustand wählen", "category": "Kategorie *", "chooseCategory": "Kategorie wählen", + "noCategories": "Keine passende Kategorie.", + "categoryNotAllowed": "„{{category}}“ ist bei „{{event}}“ nicht erlaubt. Wähle eine andere Kategorie oder einen anderen Basar.", + "categoryNotAllowedShort": "Die Kategorie ist bei „{{event}}“ nicht erlaubt.", + "categoriesOfBazaar": "Nur Kategorien, die {{events}} erlaubt.", "price": "Preis (€) *", "images": "Bilder *", "negotiable": "Preis verhandelbar?", diff --git a/src/locales/en/admin.json b/src/locales/en/admin.json index f3d219dc..eb3c3864 100644 --- a/src/locales/en/admin.json +++ b/src/locales/en/admin.json @@ -277,21 +277,34 @@ }, "categories": { "title": "Categories", - "subtitle": "The categories bazaars and items choose from.", + "subtitle": "What bazaars and items choose from: main categories group, items go into the sub-categories.", + "tabCategories": "Categories", + "tabFields": "Extra fields", "add": "Add category", + "addSub": "Sub-category", + "addSubTo": "Add a sub-category to “{{name}}”", "edit": "Edit category", "new": "New category", + "newSub": "New sub-category", "name": "Name", "nameEn": "English name", - "nameEnHint": "Optional. Without an English name, English-speaking visitors see the name above.", + "nameEnHint": "Optional. Otherwise English-speaking visitors see the German name.", + "parent": "Belongs to", + "noParent": "None – main category", + "parentHint": "Items go into sub-categories. A main category groups them.", + "parentLocked": "Has sub-categories of its own, so it stays a main category.", + "subcategories_one": "{{count}} sub-category", + "subcategories_other": "{{count}} sub-categories", + "showSub": "Show the sub-categories of {{name}}", "fields": "Extra fields", + "fieldsHelp": "What sellers enter in addition for an item of this category, such as the size or frame number.", + "inherit": "Like “{{name}}”", + "inheritFields": "Like “{{name}}”: {{fields}}", + "inheritNone": "Like “{{name}}” (none)", + "own": "Own choice", "noFields": "None", - "usage": "Usage", - "subOf": "Sub-category of {{parent}}", - "action": "Action", - "fieldsHint": "The name decides the extra fields of its items, such as the frame number for bikes. It also decides which categories new bazaars get preselected.", - "fieldsPreview": "Extra fields with this name: {{fields}}", - "noFieldsPreview": "With this name the category has no extra fields.", + "oneSize": "Only one size per category.", + "manageFields": "Missing a field? Add it under “Extra fields”.", "fieldsChange": "The extra fields change for all items of this category.", "duplicate": "A category with this name already exists.", "saved": "Category saved", @@ -304,9 +317,35 @@ "empty": "No categories yet", "editShort": "Edit", "save": "Save", + "cancel": "Cancel", "usageProducts_one": "{{count}} item", "usageProducts_other": "{{count}} items", "usageEvents_one": "{{count}} bazaar", "usageEvents_other": "{{count}} bazaars" + }, + "categoryFields": { + "intro": "Fields sellers fill in for their items. Which ones a category has, you choose at the category.", + "add": "Add field", + "new": "New extra field", + "edit": "Edit extra field", + "label": "Name", + "labelEn": "English name", + "placeholder": "Example in the input", + "placeholderEn": "Example in English", + "placeholderHint": "For example “e.g. 38”. Optional.", + "hint": "Hint below the field", + "hintEn": "Hint in English", + "short": "Short value", + "shortHint": "At most 7 characters, so it fits on the label – a size, for example.", + "shortBadge": "Short", + "used_one": "In {{count}} category", + "used_other": "In {{count}} categories", + "unused": "Not in any category yet", + "saved": "Extra field saved", + "deleted": "Extra field deleted", + "deleteTitle": "Delete “{{name}}”?", + "deleteText": "Items keep their values, they are just no longer shown.", + "inUse": "Still used by categories.", + "empty": "No extra fields yet" } } diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index c6d398a2..d8445ab9 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -39,6 +39,10 @@ "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.", + "unknownField": "This extra field does not exist.", + "oneSize": "Please choose at most one kind of size.", "lastOne": "The last category cannot be deleted." }, "common": { @@ -122,7 +126,8 @@ "product": "Item not found.", "question": "Question not found.", "report": "Report not found.", - "user": "User not found." + "user": "User not found.", + "categoryField": "Extra field not found." }, "offline": { "failed": "The action could not be replayed. Please do it by hand.", @@ -181,7 +186,9 @@ "rejected": "The item was rejected. Take the rejection back first.", "rejectedNoRemove": "Rejected items stay on record at the bazaar and cannot be removed.", "notRegistered": "Register as a seller for this bazaar first.", - "rejectedHere": "“{{title}}” was rejected at “{{event}}” and cannot be registered there again." + "rejectedHere": "“{{title}}” was rejected at “{{event}}” and cannot be registered there again.", + "chooseSubcategory": "Please choose a sub-category, for example the kind of bike under “Bikes”.", + "categoryNotAllowed": "This category is not allowed at “{{event}}”." }, "profile": { "nameRequired": "Please enter your first and last name.", @@ -259,5 +266,8 @@ "upload": { "quotaExceeded": "You have uploaded too many images that are not saved yet. Please save first or try again later.", "tooMany": "You have uploaded a lot of images. Please try again later." + }, + "categoryField": { + "inUse": "Categories still use this extra field. Remove it there first." } } diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index fd6fd8dc..fb55e393 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -101,7 +101,14 @@ "categories": { "title": "Categories & services", "allowed": "Allowed item categories *", - "services": "Additional services" + "subcategories": "Sub-categories of {{name}}", + "services": "Additional services", + "allowedHint": "Sellers can only register items of these categories. Open a category to choose single sub-categories.", + "selectAll": "All", + "selectNone": "None", + "chosenAll": "all", + "chosenSome": "{{count}} of {{total}}", + "chosenSummary": "{{count}} of {{total}} main categories chosen" }, "contact": { "title": "Contact & finances", @@ -1088,7 +1095,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..3d08b8fb 100644 --- a/src/locales/en/records.json +++ b/src/locales/en/records.json @@ -64,43 +64,8 @@ } }, "categoryFields": { - "frameNumber": { - "label": "Frame number", - "placeholder": "e.g. WBK123456", - "hint": "Can't find it? Enter “not found” – we'll look for it together on site.", - "notFound": "Not found", - "notFoundValue": "not found" - }, - "frameSize": { - "label": "Frame size", - "placeholder": "e.g. 52 cm or M" - }, - "wheelSize": { - "label": "Wheel size", - "placeholder": "e.g. 28 inch" - }, - "bikeBrand": { - "label": "Brand", - "placeholder": "e.g. Cube" - }, - "clothingSize": { - "label": "Size", - "placeholder": "e.g. M or 128" - }, - "shoeSize": { - "label": "Size (EU)", - "placeholder": "e.g. 38" - }, - "sportSize": { - "label": "Size / length", - "placeholder": "e.g. 160 cm" - }, - "brand": { - "label": "Brand" - }, - "model": { - "label": "Model" - } + "notFound": "Not found", + "notFoundValue": "not found" }, "service": { "Parkplatz": "Parking", diff --git a/src/locales/en/seller.json b/src/locales/en/seller.json index 4ba62e74..f1b975c0 100644 --- a/src/locales/en/seller.json +++ b/src/locales/en/seller.json @@ -2,6 +2,7 @@ "myProducts": { "soldCannotAdd": "Sold items can no longer be added to bazaars.", "cannotUnregister": "This item can no longer be withdrawn.", + "categoryNotAllowed": "The category of this item is not allowed at “{{event}}”.", "deletedMany_one": "{{count}} item deleted", "deletedMany_other": "{{count}} items deleted", "deleteFailed": "Deleting failed", @@ -122,6 +123,10 @@ "chooseCondition": "Choose condition", "category": "Category *", "chooseCategory": "Choose category", + "noCategories": "No matching category.", + "categoryNotAllowed": "“{{category}}” is not allowed at “{{event}}”. Choose another category or bazaar.", + "categoryNotAllowedShort": "The category is not allowed at “{{event}}”.", + "categoriesOfBazaar": "Only categories {{events}} allows.", "price": "Price (€) *", "images": "Photos *", "negotiable": "Price negotiable?", diff --git a/src/pages/administrator/AdminCategoriesPage.test.tsx b/src/pages/administrator/AdminCategoriesPage.test.tsx index e51016bf..8a70b8d0 100644 --- a/src/pages/administrator/AdminCategoriesPage.test.tsx +++ b/src/pages/administrator/AdminCategoriesPage.test.tsx @@ -2,33 +2,79 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/rea import { beforeEach, describe, expect, it, vi } from 'vitest'; import { getFunctionName } from '../../lib/api/functions'; import { useMutation, useQuery } from '../../lib/api/react'; +import type { CategoryField } from '../../shared/categoryFields'; import { AdminCategoriesPage } from './AdminCategoriesPage'; vi.mock('../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn() })); +const field = (id: string, label: string, extra: Partial = {}) => ({ + _id: id, + key: id, + label, + short: false, + notFoundButton: false, + ...extra, +}); +const frameNumber = field('frameNumber', 'Rahmennummer', { placeholder: 'z. B. WBK123456' }); +const brand = field('brand', 'Marke'); +const clothingSize = field('clothingSize', 'Größe', { key: 'size', short: true }); +const shoeSize = field('shoeSize', 'Größe (EU)', { key: 'size', short: true }); +const definitions = [frameNumber, brand, clothingSize, shoeSize]; + const base = { _creationTime: 1, updatedAt: 1, childCount: 0, productCount: 0, eventCount: 0 }; const bikes = { ...base, _id: 'bikes', label: 'Fahrräder', translations: { en: 'Bikes' }, - productCount: 3, + fields: ['frameNumber', 'brand'], + fieldList: [frameNumber, brand], + childCount: 2, eventCount: 1, }; -const misc = { ...base, _id: 'misc', label: 'Sonstiges', translations: {} }; -const kids = { +const trekking = { ...base, - _id: 'kids', - label: 'Kinderrad', + _id: 'trekking', + label: 'Trekkingräder', translations: {}, parentCategory: 'bikes', + fieldList: [frameNumber, brand], + productCount: 3, }; +const trailers = { + ...base, + _id: 'trailers', + label: 'Fahrradanhänger', + translations: {}, + parentCategory: 'bikes', + fields: [], + fieldList: [], +}; +const misc = { ...base, _id: 'misc', label: 'Sonstiges', translations: {}, fieldList: [] }; const mutations: Record> = {}; +let categories: unknown[] = []; beforeEach(() => { + // jsdom has no ResizeObserver; checkbox and radio 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); + categories = [bikes, trekking, trailers, misc]; + vi.mocked(useQuery).mockImplementation(((fn: unknown) => { + const name = getFunctionName(fn); + if (name === 'categories.listFields') return definitions; + if (name === 'categories.listFieldsForAdmin') { + return definitions.map((d) => ({ ...d, categoryCount: d === frameNumber ? 1 : 0 })); + } + return categories; + }) as never); vi.mocked(useMutation).mockImplementation(((fn: unknown) => { const name = getFunctionName(fn); mutations[name] ??= vi.fn(async () => null); @@ -36,76 +82,136 @@ beforeEach(() => { }) as never); }); -const row = (name: string) => screen.getByText(name).closest('tr') as HTMLElement; +const row = (name: string) => screen.getByTestId(`category-${name}`); +const openBikes = () => + fireEvent.click(screen.getByRole('button', { name: 'Unterkategorien von Fahrräder zeigen' })); describe('AdminCategoriesPage', () => { - it('shows names, inherited extra fields and usage', () => { + it('shows main categories with their fields; sub-categories when opened', () => { render(); - expect(within(row('Fahrräder')).getByText('Bikes')).toBeInTheDocument(); + expect(within(row('Fahrräder')).getByText('Bikes · 2 Unterkategorien')).toBeInTheDocument(); expect(within(row('Fahrräder')).getByText('Rahmennummer')).toBeInTheDocument(); - expect(within(row('Fahrräder')).getByText('3 Artikel, 1 Basar')).toBeInTheDocument(); - expect(within(row('Kinderrad')).getByText('Unterkategorie von Fahrräder')).toBeInTheDocument(); - expect(within(row('Kinderrad')).getByText('Rahmennummer')).toBeInTheDocument(); - expect(within(row('Sonstiges')).getByText('Keine')).toBeInTheDocument(); - }); + expect(within(row('Fahrräder')).getByText('0 Artikel · 1 Basar')).toBeInTheDocument(); + expect(screen.queryByTestId('category-Trekkingräder')).not.toBeInTheDocument(); - it('sorts by name with sub-categories below their parent', () => { - render(); - const names = screen.getAllByRole('row').map((row) => row.querySelector('td .font-medium')); - expect(names.flatMap((name) => name?.textContent ?? [])).toEqual([ - 'Fahrräder', - 'Kinderrad', - 'Sonstiges', - ]); + openBikes(); + expect(within(row('Trekkingräder')).getByText('Wie „Fahrräder“')).toBeInTheDocument(); + expect(within(row('Fahrradanhänger')).getByText('Keine')).toBeInTheDocument(); + expect(within(row('Sonstiges')).getByText('Keine')).toBeInTheDocument(); }); it('only offers to delete what nothing uses', () => { render(); + openBikes(); expect(screen.getByRole('button', { name: 'Löschen: Fahrräder' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Löschen: Trekkingräder' })).toBeDisabled(); expect(screen.getByRole('button', { name: 'Löschen: Sonstiges' })).toBeEnabled(); }); it('keeps the last category', () => { - vi.mocked(useQuery).mockReturnValue([misc] as never); + categories = [misc]; render(); expect(screen.getByRole('button', { name: 'Löschen: Sonstiges' })).toBeDisabled(); }); - it('saves the changed names and warns when the extra fields change', async () => { + it('a sub-category takes the fields of its main category or picks its own', async () => { render(); - fireEvent.click(within(row('Fahrräder')).getByRole('button', { name: 'Bearbeiten' })); - const name = screen.getByLabelText('Name'); - expect(screen.queryByText(/ändern sich für alle Artikel/)).not.toBeInTheDocument(); + openBikes(); + fireEvent.click(screen.getByRole('button', { name: 'Bearbeiten: Trekkingräder' })); + expect( + screen.getByLabelText('Wie „Fahrräder“: Rahmennummer, Marke', { exact: false }) + ).toBeChecked(); + expect(screen.queryByRole('checkbox', { name: /Rahmennummer/ })).not.toBeInTheDocument(); - fireEvent.change(name, { target: { value: 'Allerlei' } }); + fireEvent.click(screen.getByLabelText('Eigene Auswahl')); + // The choice starts from the fields of the main category + expect(screen.getByRole('checkbox', { name: /Rahmennummer/ })).toBeChecked(); + fireEvent.click(screen.getByRole('checkbox', { name: /Marke/ })); + // Items use the category: the fields change for them expect(screen.getByText(/ändern sich für alle Artikel/)).toBeInTheDocument(); - expect(screen.getByText(/keine Zusatzfelder/)).toBeInTheDocument(); - - fireEvent.change(screen.getByLabelText('Englischer Name'), { target: { value: ' Misc ' } }); fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); await waitFor(() => expect(mutations['categories.updateCategory']).toHaveBeenCalledWith({ - categoryId: 'bikes', - label: 'Allerlei', - translations: { en: 'Misc' }, + categoryId: 'trekking', + label: 'Trekkingräder', + translations: { en: undefined }, + parentCategory: 'bikes', + fields: ['frameNumber'], }) ); - await waitFor(() => expect(screen.queryByLabelText('Name')).not.toBeInTheDocument()); }); - it('creates a category, but not one with a name that exists', async () => { + it('a main category picks its fields, one size at most', async () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Bearbeiten: Sonstiges' })); + expect(screen.queryByLabelText('Eigene Auswahl')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('checkbox', { name: /^Größe$/ })); + fireEvent.click(screen.getByRole('checkbox', { name: /Größe \(EU\)/ })); + expect(screen.getByRole('checkbox', { name: /^Größe$/ })).not.toBeChecked(); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.updateCategory']).toHaveBeenCalledWith( + expect.objectContaining({ categoryId: 'misc', fields: ['shoeSize'] }) + ) + ); + }); + + it('adds a sub-category right below its main category', async () => { render(); - fireEvent.click(screen.getByRole('button', { name: 'Kategorie hinzufügen' })); - fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'sonstiges' } }); + fireEvent.click( + screen.getByRole('button', { name: 'Unterkategorie zu „Fahrräder“ hinzufügen' }) + ); + expect(screen.getByText('Neue Unterkategorie')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'fahrradanhänger' } }); fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); expect(mutations['categories.createCategory']).not.toHaveBeenCalled(); - fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Wintersport' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Tandems' } }); fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); await waitFor(() => expect(mutations['categories.createCategory']).toHaveBeenCalledWith({ - label: 'Wintersport', + label: 'Tandems', translations: { en: undefined }, + parentCategory: 'bikes', + fields: undefined, + }) + ); + }); + + it('keeps a category with sub-categories on top', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Bearbeiten: Fahrräder' })); + expect(screen.getByText(/bleibt deshalb Hauptkategorie/)).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Gehört zu' })).toBeDisabled(); + }); + + it('admins define the extra fields themselves', async () => { + render(); + fireEvent.mouseDown(screen.getByRole('tab', { name: 'Zusatzfelder' })); + fireEvent.click(screen.getByRole('tab', { name: 'Zusatzfelder' })); + await screen.findByTestId('field-Rahmennummer'); + expect(within(screen.getByTestId('field-Rahmennummer')).getByText('In 1 Kategorie')); + expect(screen.getByRole('button', { name: 'Löschen: Rahmennummer' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Löschen: Marke' })).toBeEnabled(); + + fireEvent.click(screen.getByRole('button', { name: 'Feld hinzufügen' })); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Höhe ' } }); + fireEvent.change(screen.getByLabelText('Englischer Name'), { target: { value: 'Height' } }); + fireEvent.change(screen.getByLabelText('Beispiel im Eingabefeld'), { + target: { value: 'z. B. 120 cm' }, + }); + fireEvent.click(screen.getByLabelText(/Kurzer Wert/)); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => + expect(mutations['categories.saveField']).toHaveBeenCalledWith({ + fieldId: undefined, + label: ' Höhe ', + labelEn: 'Height', + placeholder: 'z. B. 120 cm', + placeholderEn: '', + hint: '', + hintEn: '', + short: true, }) ); }); diff --git a/src/pages/administrator/AdminCategoriesPage.tsx b/src/pages/administrator/AdminCategoriesPage.tsx index a0e6e2e9..fa476c65 100644 --- a/src/pages/administrator/AdminCategoriesPage.tsx +++ b/src/pages/administrator/AdminCategoriesPage.tsx @@ -1,9 +1,10 @@ import { useState, type FormEvent } from 'react'; -import { Pencil, Plus, Tags, Trash2 } from 'lucide-react'; +import { ChevronRight, Pencil, Plus, Tags, Trash2 } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import { Badge } from '../../components/ui/badge'; import { Button } from '../../components/ui/button'; +import { Checkbox } from '../../components/ui/checkbox'; import { ConfirmDialog } from '../../components/ui/confirm-dialog'; import { Dialog, @@ -17,77 +18,95 @@ import { Input } from '../../components/ui/input'; import { Label } from '../../components/ui/label'; import { TableRowsSkeleton } from '../../components/ui/loading'; import { PageHeader } from '../../components/ui/page-header'; +import { RadioGroup, RadioGroupItem } from '../../components/ui/radio-group'; import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from '../../components/ui/table'; + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '../../components/ui/select'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../components/ui/tabs'; 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, - getFieldsForLabel, - type CategoryField, -} from '../../shared/categoryFields'; +import { cn } from '../../lib/utils'; +import type { CategoryField } from '../../shared/categoryFields'; +import { groupCategories } from '../../shared/categoryTree'; +import { AdminCategoryFields } from './AdminCategoryFields'; type AdminCategory = FunctionReturnType[number]; -/** What the dialog works on: a category, or null for a new one. */ -type Editing = { category: AdminCategory | null }; +/** Value of the parent select for a main category */ +const NO_PARENT = 'none'; + +/** What the dialog works on: a category, or a new one (maybe below a main category). */ +type Editing = { category: AdminCategory } | { parent?: string }; const fieldNames = (fields: CategoryField[]) => fields.map((field) => categoryFieldText(field, 'label') ?? field.label); -/** By name, parents first, each followed by its sub-categories. */ -function inTreeOrder(unsorted: AdminCategory[]) { - const categories = [...unsorted].sort((a, b) => a.label.localeCompare(b.label)); - const ids = new Set(categories.map((category) => category._id)); - const isRoot = (category: AdminCategory) => - !category.parentCategory || !ids.has(category.parentCategory); - const withChildren = (parent: AdminCategory, seen: Set): AdminCategory[] => { - seen.add(parent._id); - return [ - parent, - ...categories - .filter((category) => category.parentCategory === parent._id && !seen.has(category._id)) - .flatMap((child) => withChildren(child, seen)), - ]; - }; - const seen = new Set(); - return categories.filter(isRoot).flatMap((root) => withChildren(root, seen)); -} - function CategoryDialog({ editing, categories, + definitions, onClose, }: { editing: Editing; categories: AdminCategory[]; + definitions: CategoryField[]; onClose: () => void; }) { const { t } = useTranslation('admin'); - const { category } = editing; + const category = 'category' in editing ? editing.category : undefined; const create = useMutation(api.categories.createCategory); const update = useMutation(api.categories.updateCategory); const [label, setLabel] = useState(category?.label ?? ''); const [nameEn, setNameEn] = useState(category?.translations.en ?? ''); + const [parent, setParent] = useState( + category?.parentCategory ?? ('parent' in editing ? editing.parent : undefined) ?? NO_PARENT + ); + // One level: only main categories 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 parentCategory = categories.find((other) => other._id === parent); + // Ids of the picked fields; undefined: those of the main category + const [picked, setPicked] = useState( + category?.fields ?? (parentCategory ? undefined : []) + ); const [saving, setSaving] = useState(false); const name = label.trim(); - const fieldsFor = (candidate: string) => - getFieldsForLabel(candidate) ?? - (category?.parentCategory ? getCategoryFields(category.parentCategory, categories) : []); - const fields = fieldNames(fieldsFor(name)); + const inherited = parentCategory?.fieldList ?? []; + const ownChoice = picked ?? inherited.map((field) => field._id); + const effective = definitions.filter((field) => + (picked ?? inherited.map((f) => f._id)).includes(field._id) + ); const fieldsChange = !!category && (category.productCount > 0 || category.eventCount > 0) && - fields.join() !== fieldNames(fieldsFor(category.label)).join(); + fieldNames(effective).join() !== fieldNames(category.fieldList).join(); + + const chooseParent = (value: string) => { + setParent(value); + // On top there is nothing to take over + if (value === NO_PARENT && picked === undefined) setPicked(inherited.map((f) => f._id)); + }; + const toggle = (field: CategoryField, on: boolean) => + setPicked( + on + ? // One size at most: all sizes share the key + [ + ...ownChoice.filter( + (id) => definitions.find((other) => other._id === id)?.key !== field.key + ), + field._id, + ] + : ownChoice.filter((id) => id !== field._id) + ); const submit = async (event: FormEvent) => { event.preventDefault(); @@ -100,9 +119,14 @@ 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 args = { + label: name, + translations: { en: nameEn.trim() || undefined }, + parentCategory: parentCategory?._id as Id<'categories'> | undefined, + fields: parentCategory ? picked : ownChoice, + }; + if (category) await update({ categoryId: category._id, ...args }); + else await create(args); toast.success(t('categories.saved')); onClose(); } catch (error) { @@ -112,47 +136,133 @@ function CategoryDialog({ } }; + const sizes = definitions.filter((field) => field.key === 'size').length; return ( !open && onClose()}> - + - {t(category ? 'categories.edit' : 'categories.new')} + + {t( + category ? 'categories.edit' : parentCategory ? 'categories.newSub' : 'categories.new' + )} + - + +
+
+ + setLabel(event.target.value)} + maxLength={60} + required + autoFocus + /> +
+
+ + setNameEn(event.target.value)} + maxLength={60} + /> +
+
+
- - setLabel(event.target.value)} - maxLength={60} - required - autoFocus - /> -

{t('categories.fieldsHint')}

- {name && ( -

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

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

+
+ +
+ {t('categories.fields')} +

{t('categories.fieldsHelp')}

+ {parentCategory && ( + + setPicked(value === 'own' ? inherited.map((f) => f._id) : undefined) + } + className="gap-2" + > +
+ + +
+
+ + +
+
+ )} + {(!parentCategory || picked) && ( +
+ {definitions.map((field) => ( + + ))} +
+ )} + {(!parentCategory || picked) && ( +

+ {sizes > 1 && `${t('categories.oneSize')} `} + {t('categories.manageFields')}

)} {fieldsChange && (

{t('categories.fieldsChange')}

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

{t('categories.nameEnHint')}

-
+ + + @@ -163,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')); @@ -179,122 +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 ?? '—'} - - {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/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 554e7909..5ff8ab90 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -67,6 +67,7 @@ import { placeFromLocation, type EventPlace } from '../../../shared/eventJsonLd' import { EVENT_TYPES, findEventType, + preselectedCategories, type EventType, type EventTypeId, } from '../../../lib/eventTypes'; @@ -868,9 +869,10 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { const type = EVENT_TYPES.find((candidate) => candidate.id === id); if (!type) return; const current = methods.getValues(); - const matching = (categories ?? []) - .filter((category) => type.categoryMatch?.test(category.label)) - .map((category) => category._id as string); + const matching = preselectedCategories( + type, + (categories ?? []).map((category) => ({ ...category, _id: category._id as string })) + ); reset({ ...current, // A start for the title; the organizer adds town or year in "When and where?" diff --git a/src/pages/organizer/events/components/EditEventCategories.test.tsx b/src/pages/organizer/events/components/EditEventCategories.test.tsx new file mode 100644 index 00000000..120c4230 --- /dev/null +++ b/src/pages/organizer/events/components/EditEventCategories.test.tsx @@ -0,0 +1,79 @@ +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'; + +const category = (id: string, label: string, parentCategory?: string) => + ({ _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 ( + + + + ); +} + +beforeEach(() => { + // jsdom has no ResizeObserver; the checkbox uses it + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + } + ); +}); + +describe('EditEventCategories', () => { + it('one row per main category; opened, its sub-categories', () => { + render(
); + 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.getByLabelText('Lastenräder')).not.toBeChecked(); + }); + + it('a main category with all sub-categories is stored as itself', () => { + render(); + 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.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([]); + }); + + 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 1d9b0bf1..00873d4d 100644 --- a/src/pages/organizer/events/components/EditEventCategories.tsx +++ b/src/pages/organizer/events/components/EditEventCategories.tsx @@ -3,17 +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 } from 'react'; +import { useEffect, useState } from 'react'; +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 { @@ -23,7 +156,6 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { formState: { errors }, } = useFormContext(); - const categories: string[] = watch('categories') || []; const services: string[] = watch('services') || []; useEffect(() => { @@ -31,15 +163,6 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { register('services'); }, [register]); - const toggleCategory = (catId: string) => { - const id = String(catId); - const current = categories.includes(id) - ? categories.filter((c: string) => c !== id) - : [...categories, id]; - - setValue('categories', current, { shouldValidate: true, shouldDirty: true, shouldTouch: true }); - }; - const toggleService = (svc: string) => { const current = services.includes(svc) ? services.filter((s: string) => s !== svc) @@ -49,25 +172,8 @@ export function EditEventCategories({ categoryList }: EventCategoriesProbs) { return ( -
- -
- {categoryList.map((cat) => { - const catId = String(cat._id); - return ( - toggleCategory(catId)} - > - {categoryName(cat)} - - ); - })} -
- {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 9e20e23a..96e1f134 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -45,10 +45,10 @@ 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 { 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,12 +409,14 @@ 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 required = REQUIRABLE_FIELDS.filter((field) => - features.requiredFields?.includes(field.key) - ).map((field) => categoryFieldText(field, 'label') ?? field.label); + 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 + .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 dd2e2c90..08933c53 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -8,9 +8,9 @@ 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 { 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'; @@ -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', @@ -120,11 +121,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} + + ) + )}
@@ -155,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/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/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 91462c3b..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; @@ -431,6 +449,7 @@ export function MyProductsPage() { sortBy, minPrice, maxPrice, + categories: categoryList, }) : []; 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 ec9928cf..8a9ec5ff 100644 --- a/src/pages/seller/products/components/MyProductBasicInfo.tsx +++ b/src/pages/seller/products/components/MyProductBasicInfo.tsx @@ -1,23 +1,17 @@ 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'; 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 { 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'; @@ -29,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'); @@ -55,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 ( @@ -105,25 +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 3639a6bb..b505c1ad 100644 --- a/src/shared/categoryFields.ts +++ b/src/shared/categoryFields.ts @@ -1,160 +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' - | '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 BIKE_FIELDS: 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, - }, - { 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' }, -]; - -const CLOTHING_FIELDS: CategoryField[] = [ - { - key: 'size', - text: 'clothingSize', - label: 'Größe', - placeholder: 'z. B. M oder 128', - maxLength: MAX_SIZE_LENGTH, - }, - { key: 'brand', text: 'brand', label: 'Marke' }, -]; - -const SHOE_FIELDS: CategoryField[] = [ - { - key: 'size', - text: 'shoeSize', - label: 'Größe (EU)', - placeholder: 'z. B. 38', - maxLength: MAX_SIZE_LENGTH, - }, - { key: 'brand', text: 'brand', label: 'Marke' }, -]; - -const SPORT_FIELDS: CategoryField[] = [ - { - key: 'size', - text: 'sportSize', - label: 'Größe / Länge', - placeholder: 'z. B. 160 cm', - maxLength: MAX_SIZE_LENGTH, - }, - { key: 'brand', text: 'brand', label: 'Marke' }, -]; - -const ELECTRONICS_FIELDS: CategoryField[] = [ - { key: 'brand', text: 'brand', label: 'Marke' }, - { key: 'model', text: 'model', label: 'Modell' }, -]; - -/** - * 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, - // Accessories and clothing for cyclists have no frame number - exclude: /zubehör|teile|bekleidung|helm|anhänger|schloss/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[] = (() => { - const byKey = new Map(); - for (const rule of FIELD_RULES) { - for (const field of rule.fields) if (!byKey.has(field.key)) byKey.set(field.key, field); - } - return [...byKey.values()]; -})(); - -export const REQUIRABLE_FIELD_KEYS = REQUIRABLE_FIELDS.map((field) => field.key); - -/** Fields for a single category label, without looking at parent categories. */ -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; +export function requirableFields(definitions: readonly CategoryField[] | undefined) { + return (definitions ?? []).filter( + (field, index, all) => all.findIndex((other) => other.key === field.key) === index + ); } -type CategoryLike = { _id: string; label: string; parentCategory?: string }; +type CategoryWithFields = { _id: string; fieldList?: CategoryField[] }; -/** - * Fields for a category. Sub-categories without their own set 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); - 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 ?? []; } /** @@ -174,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 new file mode 100644 index 00000000..1ede93dc --- /dev/null +++ b/src/shared/categoryTree.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import { + collapseSubcategories, + compactSelection, + expandCategories, + expandSelection, + groupCategories, + isCategoryAllowed, + isForItems, + 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']); + }); + + 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 new file mode 100644 index 00000000..b07fae9a --- /dev/null +++ b/src/shared/categoryTree.ts @@ -0,0 +1,145 @@ +/** + * 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)); +} + +/** 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 fb0755d7..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,82 +17,62 @@ import { resolveEventFeatures, } from './eventFeatures'; -const keys = (label: string) => getFieldsForLabel(label)?.map((field) => field.key); -const BIKE_KEYS = ['frameNumber', 'frameSize', 'wheelSize', 'brand']; - -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', - 'Einrad', - 'Laufrad', - ])('"%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); - } - ); - - test('cycling clothes count as clothing, sports shoes as shoes', () => { - expect(keys('Fahrradbekleidung')).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([]); +/** 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('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(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 692b85eb..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' }).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' }).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' }).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 0e64c86e..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' }).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 f83e5327..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' }).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(); +}