diff --git a/backend/migrations/0017_user_sort_code.sql b/backend/migrations/0017_user_sort_code.sql new file mode 100644 index 00000000..d1b07f00 --- /dev/null +++ b/backend/migrations/0017_user_sort_code.sql @@ -0,0 +1,4 @@ +-- A number that stays with a seller across all bazaars. Universal labels print it as a +-- digit, symbols and colors (src/shared/sortCode.ts), so they can be reused. Numbers are +-- not given out again, also after an account is deleted. +ALTER TABLE users ADD COLUMN sort_code integer GENERATED BY DEFAULT AS IDENTITY UNIQUE; diff --git a/backend/migrations/0018_user_country_code.sql b/backend/migrations/0018_user_country_code.sql new file mode 100644 index 00000000..5e138199 --- /dev/null +++ b/backend/migrations/0018_user_country_code.sql @@ -0,0 +1,13 @@ +-- Profile countries were free text; now they are ISO 3166-1 alpha-2 codes like those of events. +-- Other values stay as they are and keep being shown as typed. Snapshots of sellers keep what +-- was true when they were taken. +UPDATE users SET country = CASE + WHEN lower(trim(country)) IN ('de', 'd', 'deu', 'ger', 'brd', 'deutschland', 'germany') THEN 'DE' + -- translate: lower() leaves Ö alone in databases with the C locale + WHEN translate(lower(trim(country)), 'Ö', 'ö') IN ('at', 'a', 'aut', 'österreich', 'oesterreich', 'austria') THEN 'AT' + WHEN lower(trim(country)) IN ('ch', 'che', 'schweiz', 'switzerland', 'suisse', 'svizzera') THEN 'CH' + WHEN lower(trim(country)) IN ('li', 'lie', 'liechtenstein') THEN 'LI' + WHEN lower(trim(country)) IN ('lu', 'lux', 'luxemburg', 'luxembourg') THEN 'LU' + ELSE country + END +WHERE country IS NOT NULL; diff --git a/backend/migrations/0020_sort_code_for_sellers.sql b/backend/migrations/0020_sort_code_for_sellers.sql new file mode 100644 index 00000000..bfebe015 --- /dev/null +++ b/backend/migrations/0020_sort_code_for_sellers.sql @@ -0,0 +1,32 @@ +-- Sorting codes are for sellers. A buyer without items must not use up one of the codes +-- that need no extra letter, so a code is given with the first item or bazaar. Codes are +-- never given out again, not even after an account is deleted: printed labels may still +-- carry them. +ALTER TABLE users ALTER COLUMN sort_code DROP IDENTITY; +ALTER TABLE users ALTER COLUMN sort_code DROP NOT NULL; +UPDATE users SET sort_code = NULL; + +CREATE SEQUENCE users_sort_code_seq OWNED BY users.sort_code; + +WITH sellers AS ( + SELECT id FROM users u + WHERE EXISTS (SELECT 1 FROM products p WHERE p.vendor_id = u.id) + OR EXISTS (SELECT 1 FROM event_sellers s WHERE s.user_id = u.id) + ORDER BY created_at, id +), numbered AS ( + SELECT id, nextval('users_sort_code_seq')::integer AS code FROM sellers +) +UPDATE users u SET sort_code = n.code FROM numbered n WHERE n.id = u.id; + +CREATE FUNCTION give_sort_code() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE users SET sort_code = nextval('users_sort_code_seq') + WHERE id = (to_jsonb(NEW) ->> TG_ARGV[0])::uuid AND sort_code IS NULL; + RETURN NULL; +END; +$$; + +CREATE TRIGGER products_give_sort_code AFTER INSERT OR UPDATE OF vendor_id ON products + FOR EACH ROW EXECUTE FUNCTION give_sort_code('vendor_id'); +CREATE TRIGGER event_sellers_give_sort_code AFTER INSERT ON event_sellers + FOR EACH ROW EXECUTE FUNCTION give_sort_code('user_id'); diff --git a/backend/migrations/0021_random_sort_codes.sql b/backend/migrations/0021_random_sort_codes.sql new file mode 100644 index 00000000..dd74eebe --- /dev/null +++ b/backend/migrations/0021_random_sort_codes.sql @@ -0,0 +1,46 @@ +-- A code must not tell when an account was made, and a new bazaar must not start at 00 00: +-- codes are drawn at random. A code without a letter is drawn while one is easy to find, +-- then one with the next letter (see src/shared/sortCode.ts). Codes stay unique and are +-- never given out again. No labels were printed with the numbers before. +CREATE FUNCTION assign_sort_code(seller uuid) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE + patterns CONSTANT integer := 100000; + tries_per_letter CONSTANT integer := 20; + letter integer := 0; + candidate integer; +BEGIN + LOOP + FOR try IN 1..tries_per_letter LOOP + candidate := letter * patterns + floor(random() * patterns)::integer; + BEGIN + UPDATE users SET sort_code = candidate WHERE id = seller AND sort_code IS NULL; + RETURN; + EXCEPTION WHEN unique_violation THEN + NULL; -- Taken: draw again + END; + END LOOP; + letter := letter + 1; + END LOOP; +END; +$$; + +CREATE OR REPLACE FUNCTION give_sort_code() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + PERFORM assign_sort_code((to_jsonb(NEW) ->> TG_ARGV[0])::uuid); + RETURN NULL; +END; +$$; + +DO $$ +DECLARE + seller uuid; +BEGIN + CREATE TEMP TABLE sellers ON COMMIT DROP AS SELECT id FROM users WHERE sort_code IS NOT NULL; + UPDATE users SET sort_code = NULL; + FOR seller IN SELECT id FROM sellers LOOP + PERFORM assign_sort_code(seller); + END LOOP; +END; +$$; + +DROP SEQUENCE users_sort_code_seq; diff --git a/backend/src/demo/catalog.rs b/backend/src/demo/catalog.rs index 670a1bee..7e379f81 100644 --- a/backend/src/demo/catalog.rs +++ b/backend/src/demo/catalog.rs @@ -211,17 +211,17 @@ pub fn city(locale: Locale, index: usize) -> City { City { zip: "89073", name: "Ulm", - country: "Deutschland", + country: "DE", }, City { zip: "89231", name: "Neu-Ulm", - country: "Deutschland", + country: "DE", }, City { zip: "89077", name: "Ulm", - country: "Deutschland", + country: "DE", }, ]; const EN: [City; 3] = [ diff --git a/backend/src/demo/core.rs b/backend/src/demo/core.rs index d96fefcd..1f66e96b 100644 --- a/backend/src/demo/core.rs +++ b/backend/src/demo/core.rs @@ -653,7 +653,7 @@ pub async fn insert_users(seeder: &Seeder, ctx: &mut Ctx) -> AppResult { single: bool, } +/// Address of the venue. Empty parts in English: the address form knows no British towns, +/// those demos keep it all in the location, as older events do. +struct Venue { + street: Text, + postal_code: Text, + city: Text, + country: &'static str, +} + struct EventPlan { organizer: Uuid, title: Text, description: Text, location: Text, + address: Option, contact: &'static str, services: &'static [&'static str], visibility: &'static str, @@ -239,6 +249,14 @@ impl Demo<'_> { "commission": plan.commission, "features": plan.features, }); + if let Some(venue) = &plan.address { + args["address"] = json!({ + "street": self.text(venue.street), + "postalCode": self.text(venue.postal_code), + "city": self.text(venue.city), + "country": venue.country, + }); + } if let Some(cover) = self.seeder.image(plan.cover) { args["coverImage"] = json!(cover); } @@ -659,9 +677,15 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Second-hand bazaar for children's clothes, toys, books and prams. Run by the parents' council, 15 % go to the nursery. With a cake buffet!\n\nDrop-off the day before, unsold items can be picked up from 3 pm.", ), location: t( - "Kita Sonnenschein, Turnraum, Lindenstraße 4, Ulm", + "Kita Sonnenschein, Turnraum", "Sunshine Nursery, gym, 4 Linden Street, Oxford", ), + address: Some(Venue { + street: t("Lindenstraße 4", ""), + postal_code: t("89073", ""), + city: t("Ulm", ""), + country: "DE", + }), contact: "elternbeirat@example.org", services: &["Imbiss", "Getränke"], visibility: "public", @@ -678,6 +702,7 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "minimumPrice": true, "questions": true, "labelFormat": "small", + "labelMark": "universal", "intakeFee": 0.5, "privateSellersOnly": true, "fixedSellerData": true, @@ -948,9 +973,15 @@ async fn ski_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Used skis, snowboards, boots, helmets and winter clothing. Our instructors help you choose, and the waxing service is on site.\n\nSellers register with the access code from the club newsletter.", ), location: t( - "Mehrzweckhalle Blaustein, Am Sportplatz 2", + "Mehrzweckhalle Blaustein", "Blue Valley sports hall, 2 Sports Ground Road", ), + address: Some(Venue { + street: t("Am Sportplatz 2", ""), + postal_code: t("89134", ""), + city: t("Blaustein", ""), + country: "DE", + }), contact: "skibasar@example.org", services: &["Parkplatz", "Skiservice", "Getränke"], visibility: "public", @@ -1096,9 +1127,15 @@ async fn flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Flea market in the courtyard of the community centre: household goods, furniture, electronics, bikes and clothes. Coffee and waffles from the neighbourhood café.", ), location: t( - "Stadtteiltreff Südstadt, Gartenweg 12", + "Stadtteiltreff Südstadt", "Southside community centre, 12 Garden Lane", ), + address: Some(Venue { + street: t("Gartenweg 12", ""), + postal_code: t("89077", ""), + city: t("Ulm", ""), + country: "DE", + }), contact: "suedstadt@example.org", services: &["Gastronomie"], visibility: "public", @@ -1114,6 +1151,8 @@ async fn flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "priceOffers": true, "minimumPrice": true, "questions": true, + // Only the QR code: sellers bring the labels of their last flea market + "labelMark": "none", }), }, true, @@ -1290,6 +1329,12 @@ async fn book_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Second-hand books for a good cause: novels, non-fiction and children's books. Proceeds go to reading programmes.", ), location: t("Stadtbibliothek, Foyer", "City library, foyer"), + address: Some(Venue { + street: t("Kirchstraße 12", "Kirchstraße 12"), + postal_code: t("6900", "6900"), + city: t("Bregenz", "Bregenz"), + country: "AT", + }), contact: "bibliothek@example.org", services: &["Getränke"], visibility: "public", @@ -1354,6 +1399,7 @@ async fn other_events(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<() title, description, location, + address: None, contact: "kontakt@example.org", services: &[], visibility: "public", @@ -1431,7 +1477,7 @@ async fn other_events(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<() vendor_limit: Some(3), visibility: "logged-in", categories: &[Cat::Clothing, Cat::Shoes], - features: json!({ "discounts": false, "labelFormat": "small" }), + features: json!({ "discounts": false, "labelFormat": "small", "labelMark": "universal" }), ..plan( sabine, t("Kleiderbasar Gemeindehaus", "Parish Hall Clothes Sale"), diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index 819e5d80..52b8ffc7 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -10,6 +10,8 @@ use uuid::Uuid; use super::access::is_platform_admin; use super::docs::{self, User}; +use super::features::label_mark; +use super::labels::seller_sort_code; use super::sales::{self, IntakeFee}; use super::seller_records::{keeps_seller_record, with_snapshot}; use crate::error::{AppError, AppResult}; @@ -257,6 +259,8 @@ pub struct VendorWithCalculations { pub is_helper: bool, /// Seller number of this event; missing for sellers from before numbers existed pub seller_number: Option, + /// The seller's lasting code, on bazaars with universal labels + pub sort_code: Option, /// Bazaars with fixedSellerData: name and address are recorded (first item accepted). /// Before, the team checks them against the ID card and the seller may still correct them. pub details_recorded: Option, @@ -304,6 +308,7 @@ pub async fn load_vendors_with_calculations( let users = docs::users(ctx.conn(), &vendor_ids).await?; let over = event.end_date < Utc::now(); let keeps_record = keeps_seller_record(&event); + let universal = label_mark(&event) == "universal"; for vendor in vendor_ids { let Some(mut user) = users.iter().find(|user| user.id == vendor).cloned() else { continue; @@ -328,6 +333,11 @@ pub async fn load_vendors_with_calculations( seller.as_ref(), accepted.get(&vendor).copied().unwrap_or(0), ); + let sort_code = if universal { + seller_sort_code(ctx, vendor).await? + } else { + None + }; vendors.push(VendorWithCalculations { user, total_revenue, @@ -344,6 +354,7 @@ pub async fn load_vendors_with_calculations( .is_some_and(|seller| seller.seller_snapshot.is_some()) }), seller_number: seller.and_then(|seller| seller.number), + sort_code, }); } Ok(vendors) diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index c8566e16..3104b5b1 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -48,6 +48,7 @@ const SERVICES: [&str; 5] = [ ]; const VISIBILITIES: [&str; 3] = ["public", "logged-in", "approved"]; const LABEL_FORMATS: [&str; 2] = ["standard", "small"]; +const LABEL_MARKS: [&str; 2] = ["universal", "none"]; /// What viewers outside the team see instead of the access code const HIDDEN_ACCESS_CODE: &str = "••••"; @@ -672,6 +673,7 @@ struct FeaturesArgs { max_items_per_seller: Option, label_format: Option, price_on_label: Option, + label_mark: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -717,6 +719,11 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes { return Err(invalid("labelFormat")); } + if let Some(mark) = &features.label_mark + && !LABEL_MARKS.contains(&mark.as_str()) + { + return Err(invalid("labelMark")); + } let previous_bool = |key: &str| previous.and_then(|p| p.get(key)).and_then(Value::as_bool); let required_fields: Option> = match features.required_fields { Some(fields) => fields, @@ -795,6 +802,18 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes "priceOnLabel", json!(features.price_on_label.unwrap_or(false)), ); + put( + "labelMark", + json!( + features + .label_mark + .or_else(|| previous + .and_then(|p| p.get("labelMark")) + .and_then(Value::as_str) + .map(str::to_owned)) + .unwrap_or_else(|| "number".to_owned()) + ), + ); put( "intakeFee", json!(sanitize_intake_fee(features.intake_fee)?), @@ -1600,7 +1619,7 @@ mod tests { intake_fee: Some(0.555), ..FeaturesArgs::default() }, - Some(&json!({ "fixedSellerData": true })), + Some(&json!({ "fixedSellerData": true, "labelMark": "universal" })), ) .unwrap(); assert_eq!(stored["discounts"], false); @@ -1609,6 +1628,7 @@ mod tests { assert_eq!(stored["intakeFee"], 0.56); // Not sent by an older client: kept assert_eq!(stored["fixedSellerData"], true); + assert_eq!(stored["labelMark"], "universal"); assert_eq!(stored["labelFormat"], "standard"); } diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index 820c833a..18895b3e 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -28,6 +28,7 @@ struct Stored { max_items_per_seller: Option, label_format: Option, price_on_label: Option, + label_mark: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -47,6 +48,8 @@ pub struct EventFeatures { pub max_items_per_seller: Option, pub label_format: String, pub price_on_label: bool, + /// What tells the sellers' items apart on labels: see `label_mark` + pub label_mark: String, /// Fixed fee in € per accepted item, kept from the payout pub intake_fee: Option, pub private_sellers_only: bool, @@ -76,6 +79,11 @@ pub fn resolve(features: Option<&Value>) -> EventFeatures { max_items_per_seller: stored.max_items_per_seller.map(|n| n.max(0.0) as u32), label_format: stored.label_format.unwrap_or_else(|| "standard".to_owned()), price_on_label: stored.price_on_label.unwrap_or(false), + // Older bazaars may have stored the seller number, which labels no longer show + label_mark: match stored.label_mark.as_deref() { + Some("none") => "none".to_owned(), + _ => "universal".to_owned(), + }, intake_fee: stored .intake_fee .and_then(Decimal::from_f64_retain) @@ -89,6 +97,51 @@ impl Event { pub fn resolved_features(&self) -> EventFeatures { resolve(self.features.as_ref()) } + + /// "Turnhalle Nord, Hauptstr. 5, 89073 Ulm" (formatEventPlace in the app). + pub fn place(&self) -> String { + format_place( + &self.location, + self.street.as_deref(), + self.postal_code.as_deref(), + self.city.as_deref(), + ) + } +} + +/// Whether `part` stands in `text` as whole words: "Ulm" is not in "Ulmer Halle". +fn contains_words(text: &str, part: &str) -> bool { + let text = text.to_lowercase(); + let part = part.to_lowercase(); + text.match_indices(&part).any(|(start, _)| { + let before = text[..start].chars().next_back(); + let after = text[start + part.len()..].chars().next(); + !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric) + }) +} + +fn format_place( + location: &str, + street: Option<&str>, + postal_code: Option<&str>, + city: Option<&str>, +) -> String { + let location = location.trim(); + let town = [postal_code, city] + .into_iter() + .flatten() + .map(str::trim) + .filter(|part| !part.is_empty()) + .collect::>() + .join(" "); + let mut parts = vec![location.to_owned()]; + for part in [street.unwrap_or_default().trim(), town.as_str()] { + if !part.is_empty() && !contains_words(location, part) { + parts.push(part.to_owned()); + } + } + parts.retain(|part| !part.is_empty()); + parts.join(", ") } /// Whether questions on items of this event can be asked right now. @@ -129,6 +182,12 @@ pub fn are_offers_open(status: &str, event: &Event, now: DateTime) -> bool status == "available" && event.start_date <= now && now <= event.end_date } +/// The seller's mark on the labels of this bazaar: `universal` (the seller's lasting sorting +/// code) or `none`. +pub fn label_mark(event: &Event) -> String { + event.resolved_features().label_mark +} + /// Labels show the price only without discounts: a discount would make it wrong. pub fn shows_price_on_label(event: &Event) -> bool { let features = event.resolved_features(); @@ -147,6 +206,7 @@ mod tests { assert_eq!(features.max_discount_percent, 50); assert!(!features.price_offers && !features.questions && !features.fixed_seller_data); assert_eq!(features.label_format, "standard"); + assert_eq!(features.label_mark, "universal"); } #[test] @@ -165,6 +225,37 @@ mod tests { ); } + #[test] + fn the_place_names_venue_and_address_once() { + assert_eq!( + format_place( + "Turnhalle Nord", + Some("Hauptstr. 5"), + Some("89073"), + Some("Ulm") + ), + "Turnhalle Nord, Hauptstr. 5, 89073 Ulm" + ); + assert_eq!( + format_place( + "Halle, Hauptstr. 5, 89073 Ulm", + Some("hauptstr. 5"), + Some("89073"), + Some("Ulm") + ), + "Halle, Hauptstr. 5, 89073 Ulm" + ); + // Only whole words count as already there + assert_eq!( + format_place("Ulmer Stadthalle", None, None, Some("Ulm")), + "Ulmer Stadthalle, Ulm" + ); + assert_eq!( + format_place("Halle, Hauptstr. 50", Some("Hauptstr. 5"), None, None), + "Halle, Hauptstr. 50, Hauptstr. 5" + ); + } + #[test] fn discounted_prices() { assert_eq!( diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index 199aba40..05a6cf7e 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use super::docs::{self, Event}; use super::event_products::{find_active_listing, relation}; use super::event_roles::{TEAM, has_any_role_or_admin}; -use super::features::shows_price_on_label; +use super::features::{label_mark, shows_price_on_label}; use crate::error::{AppError, AppResult}; use crate::realtime::Topic; use crate::register; @@ -18,9 +18,14 @@ use crate::shape::Id; /// More labels at once would be a huge PDF; nobody prints that many in one go. const MAX_LABELS: usize = 500; +/// Sorting codes with the same rest differ by the letter only: src/shared/sortCode.ts +const SORT_PATTERNS: i32 = 100_000; pub fn register(registry: &mut Registry) { register!(registry, Query "labels.getLabelData" => get_label_data); + register!(registry, Query "labels.getSortMarkClashes" => get_sort_mark_clashes); + register!(registry, Query "labels.getMyBasketLabel" => get_my_basket_label); + register!(registry, Query "labels.getEventLabelIds" => get_event_label_ids); } #[derive(Deserialize)] @@ -36,7 +41,8 @@ struct LabelArgs { struct Label { product_id: Uuid, title: String, - seller_number: Option, + /// The seller's lasting code for sorting back; none on QR-only labels + sort_code: Option, size: Option, price: Option, } @@ -47,7 +53,7 @@ struct Labels { labels: Vec