diff --git a/.env.selfhost.example b/.env.selfhost.example index a90c11e8..8b7ca1ef 100644 --- a/.env.selfhost.example +++ b/.env.selfhost.example @@ -11,7 +11,7 @@ POSTGRES_PASSWORD= ACME_EMAIL=admin@example.org # Release von BazarPro, siehe https://github.com/BazarPro/core/releases -BAZARPRO_VERSION=v2.3.0 +BAZARPRO_VERSION=v2.4.0 # single: ein Verein mit eigenen Basaren (Standard) # platform: mehrere Veranstalter wie auf bazarpro.de, mit Werbeseiten 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/migrations/0022_event_invitations.sql b/backend/migrations/0022_event_invitations.sql new file mode 100644 index 00000000..6375bd03 --- /dev/null +++ b/backend/migrations/0022_event_invitations.sql @@ -0,0 +1,15 @@ +-- The organizer invites someone by mail to a bazaar, as seller or helper. One row per mail +-- sent, which also counts them for the daily limit. Rows hold an address of someone who may +-- never answer, so they go soon after the bazaar (retention.rs). +CREATE TABLE event_invitations ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + created_at timestamptz NOT NULL DEFAULT now(), + event_id uuid NOT NULL REFERENCES events (id) ON DELETE CASCADE, + email text NOT NULL, + helper boolean NOT NULL, + invited_by uuid REFERENCES users (id) ON DELETE SET NULL, + token_hash bytea NOT NULL UNIQUE, + -- Used, taken back, or replaced by a newer invitation to the same address + closed_at timestamptz +); +CREATE INDEX event_invitations_event ON event_invitations (event_id, created_at); 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_invitations.rs b/backend/src/modules/event_invitations.rs new file mode 100644 index 00000000..eb34de14 --- /dev/null +++ b/backend/src/modules/event_invitations.rs @@ -0,0 +1,317 @@ +//! Invitations by mail: the organizer names an address, the person gets a link with the +//! bazaar's details and joins with their own account as seller or helper. +//! +//! The answer never tells whether an address has an account. Only the account with the +//! invited address can use a link, so a forwarded mail does not make someone a helper. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +use super::berlin_time::format_range; +use super::docs; +use super::event_roles::{self, Role}; +use super::events::{EventDetails, details}; +use super::instance::EMAIL_PATTERN; +use super::notifications::{self, Content, T}; +use crate::auth::users::normalize_email; +use crate::error::{AppError, AppResult}; +use crate::i18n::Locale; +use crate::mail::Detail; +use crate::realtime::Topic; +use crate::register; +use crate::rpc::{Ctx, Registry}; +use crate::shape::{Id, ms}; + +/// Per bazaar and 24 hours, also when taken back again: the mails go to strangers +pub const MAX_INVITATIONS_PER_DAY: i64 = 30; + +pub fn register(registry: &mut Registry) { + register!(registry, Mutation "eventInvitations.send" => send); + register!(registry, Mutation "eventInvitations.revoke" => revoke); + register!(registry, Query "eventInvitations.listOpen" => list_open); + register!(registry, Query "eventInvitations.getByToken" => get_by_token); +} + +fn token_hash(token: &str) -> Vec { + Sha256::digest(token.trim().as_bytes()).to_vec() +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SendArgs { + event_id: Id, + email: String, + helper: bool, +} + +#[derive(Serialize)] +struct Success { + success: bool, +} + +async fn send(ctx: &mut Ctx, args: SendArgs) -> AppResult { + let event_id = args.event_id.0; + let viewer = ctx.require_user()?; + if !event_roles::has_role_or_admin(ctx.conn(), event_id, viewer, Role::Organizer).await? { + return Err(AppError::forbidden("auth.forbidden")); + } + let event = docs::event(ctx.conn(), event_id) + .await? + .ok_or_else(|| AppError::not_found("notFound.event"))?; + if event.moderation.is_some() { + return Err(AppError::forbidden("event.blocked")); + } + if event.end_date < chrono::Utc::now() { + return Err(AppError::bad_request("join.past")); + } + let email = normalize_email(&args.email); + if !EMAIL_PATTERN.is_match(&email) { + return Err(AppError::bad_request("invitation.invalidEmail")); + } + let sent: i64 = sqlx::query_scalar( + "SELECT count(*) FROM event_invitations + WHERE event_id = $1 AND created_at > now() - interval '1 day'", + ) + .bind(event_id) + .fetch_one(ctx.conn()) + .await?; + if sent >= MAX_INVITATIONS_PER_DAY { + return Err(AppError::too_many_requests("invitation.limit")); + } + + sqlx::query( + "UPDATE event_invitations SET closed_at = now() + WHERE event_id = $1 AND email = $2 AND closed_at IS NULL", + ) + .bind(event_id) + .bind(&email) + .execute(ctx.conn()) + .await?; + let token = URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>()); + sqlx::query( + "INSERT INTO event_invitations (event_id, email, helper, invited_by, token_hash) + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(event_id) + .bind(&email) + .bind(args.helper) + .bind(viewer) + .bind(token_hash(&token)) + .execute(ctx.conn()) + .await?; + ctx.touch(Topic::Event(event_id)); + + let inviter = docs::user(ctx.conn(), viewer).await?; + let inviter_name = inviter + .as_ref() + .and_then(|user| user.name.clone()) + .unwrap_or_default(); + let locale: Locale = sqlx::query_scalar("SELECT locale FROM users WHERE id = $1") + .bind(viewer) + .fetch_optional(ctx.conn()) + .await? + .flatten() + .unwrap_or_default(); + let path = format!("/invite/{token}"); + let when = format_range(event.start_date, Some(event.end_date), locale); + let place = [ + Some(event.location.clone()).filter(|text| !text.is_empty()), + event.city.clone(), + ] + .into_iter() + .flatten() + .collect::>() + .join(", "); + let title = event.title.clone(); + notifications::notify_address(ctx, email, locale, |t: T| { + let values = [("event", title.as_str()), ("name", inviter_name.as_str())]; + let mut rows = vec![ + Detail { + label: t.t("reminder.bazaar", &[]), + value: title.clone(), + }, + Detail { + label: t.t("invitation.when", &[]), + value: when.clone(), + }, + ]; + if !place.is_empty() { + rows.push(Detail { + label: t.t("reminder.location", &[]), + value: place.clone(), + }); + } + let role = if args.helper { "helper" } else { "seller" }; + Content { + subject: t.t("invitation.subject", &values), + heading: t.t("invitation.heading", &values), + paragraphs: vec![ + t.t(&format!("invitation.{role}"), &values), + t.t("invitation.next", &[]), + ], + details: rows, + link: t.link("invitation.link", path.clone()), + footnote: Some(t.t("invitation.footnote", &[])), + category: None, + } + }) + .await?; + Ok(Success { success: true }) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RevokeArgs { + event_id: Id, + invitation_id: Id, +} + +async fn revoke(ctx: &mut Ctx, args: RevokeArgs) -> AppResult { + let viewer = ctx.require_user()?; + if !event_roles::has_role_or_admin(ctx.conn(), args.event_id.0, viewer, Role::Organizer).await? + { + return Err(AppError::forbidden("auth.forbidden")); + } + sqlx::query( + "UPDATE event_invitations SET closed_at = now() + WHERE id = $1 AND event_id = $2 AND closed_at IS NULL", + ) + .bind(args.invitation_id.0) + .bind(args.event_id.0) + .execute(ctx.conn()) + .await?; + ctx.touch(Topic::Event(args.event_id.0)); + Ok(Success { success: true }) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EventArgs { + event_id: Id, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct OpenInvitation { + #[serde(rename = "_id")] + id: Uuid, + email: String, + helper: bool, + #[serde(with = "ms")] + sent_at: chrono::DateTime, +} + +async fn list_open(ctx: &mut Ctx, args: EventArgs) -> AppResult> { + let viewer = ctx.require_user()?; + if !event_roles::has_role_or_admin(ctx.conn(), args.event_id.0, viewer, Role::Organizer).await? + { + return Err(AppError::forbidden("auth.forbidden")); + } + ctx.read(Topic::Event(args.event_id.0)); + let rows: Vec<(Uuid, String, bool, chrono::DateTime)> = sqlx::query_as( + "SELECT id, email, helper, created_at FROM event_invitations + WHERE event_id = $1 AND closed_at IS NULL ORDER BY created_at DESC", + ) + .bind(args.event_id.0) + .fetch_all(ctx.conn()) + .await?; + Ok(rows + .into_iter() + .map(|(id, email, helper, sent_at)| OpenInvitation { + id, + email, + helper, + sent_at, + }) + .collect()) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TokenArgs { + token: String, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct InvitationView { + /// Whoever holds the link got it at this address + email: String, + helper: bool, + event: EventDetails, +} + +/// What the invited person sees; the link alone opens it, without an account yet. Also for +/// bazaars that visitors cannot see otherwise. Nothing once used, taken back or over. +async fn get_by_token(ctx: &mut Ctx, args: TokenArgs) -> AppResult> { + let row: Option<(Uuid, String, bool)> = sqlx::query_as( + "SELECT event_id, email, helper FROM event_invitations + WHERE token_hash = $1 AND closed_at IS NULL", + ) + .bind(token_hash(&args.token)) + .fetch_optional(ctx.conn()) + .await?; + let Some((event_id, email, helper)) = row else { + return Ok(None); + }; + ctx.read(Topic::Event(event_id)); + let Some(event) = docs::event(ctx.conn(), event_id).await? else { + return Ok(None); + }; + if event.moderation.is_some() || event.end_date < chrono::Utc::now() { + return Ok(None); + } + Ok(Some(InvitationView { + email, + helper, + event: details(ctx, event, false).await?, + })) +} + +/// Whether the link fits this event and account; the answer is whether it makes a helper. +pub async fn check(ctx: &mut Ctx, event: Uuid, token: &str, user: Uuid) -> AppResult { + let row: Option<(String, bool)> = sqlx::query_as( + "SELECT email, helper FROM event_invitations + WHERE token_hash = $1 AND event_id = $2 AND closed_at IS NULL", + ) + .bind(token_hash(token)) + .bind(event) + .fetch_optional(ctx.conn()) + .await?; + let (email, helper) = row.ok_or_else(|| AppError::bad_request("invitation.invalid"))?; + let account = docs::user(ctx.conn(), user) + .await? + .and_then(|user| user.email); + if account.as_deref().map(normalize_email).as_deref() != Some(email.as_str()) { + return Err(AppError::forbidden("invitation.otherAccount")); + } + Ok(helper) +} + +/// After joining: the link is used up, and a helper invitation takes effect. +pub async fn redeem( + ctx: &mut Ctx, + event: Uuid, + token: &str, + user: Uuid, + helper: bool, +) -> AppResult<()> { + sqlx::query("UPDATE event_invitations SET closed_at = now() WHERE token_hash = $1") + .bind(token_hash(token)) + .execute(ctx.conn()) + .await?; + if helper && !event_roles::has_role(ctx.conn(), event, user, Role::Organizer).await? { + event_roles::add_role(ctx, event, user, Role::Coorganizer).await?; + } + ctx.touch(Topic::Event(event)); + Ok(()) +} + +/// Used by the retention job: addresses of people who may never have answered. +pub const CLEAN_UP_SQL: &str = "DELETE FROM event_invitations i USING events e + WHERE e.id = i.event_id AND (e.end_date < now() OR i.closed_at < now() - make_interval(days => $1))"; +/// Closed rows only count for the daily limit +pub const CLOSED_DAYS: i32 = 2; diff --git a/backend/src/modules/event_products.rs b/backend/src/modules/event_products.rs index f75fe12d..b6136b24 100644 --- a/backend/src/modules/event_products.rs +++ b/backend/src/modules/event_products.rs @@ -21,7 +21,7 @@ use super::docs::{self, EVENT_PRODUCT_COLUMNS, Event, EventProduct, Product, Use use super::event_roles::{ TEAM, assert_vendor_not_paid_out, has_any_role_or_admin, is_bystander, require_team, }; -use super::events::is_event_approved; +use super::events::{admitted_by_visibility, is_event_approved, is_live}; use super::features::discount_unavailable; use super::offers::{close_offers_for_event_product, reopen_closed_offers}; use super::sales::{self, SaleInfo}; @@ -425,12 +425,31 @@ struct ProductArgs { async fn get_event_ids_for_product(ctx: &mut Ctx, args: ProductArgs) -> AppResult> { ctx.read(Topic::Product(args.product_id.0)); - Ok(sqlx::query_scalar( + let ids: Vec = sqlx::query_scalar( "SELECT event_id FROM event_products WHERE product_id = $1 ORDER BY created_at, id", ) .bind(args.product_id.0) .fetch_all(ctx.conn()) - .await?) + .await?; + let mut visible = Vec::new(); + for id in ids { + if may_see_event(ctx, id).await? { + visible.push(id); + } + } + Ok(visible) +} + +async fn may_see_event(ctx: &mut Ctx, id: Uuid) -> sqlx::Result { + if let Some(user) = ctx.user { + ctx.read(Topic::User(user)); + } + ctx.read(Topic::Event(id)); + let Some(event) = docs::event(ctx.conn(), id).await? else { + return Ok(false); + }; + let viewer = ctx.user; + admitted_by_visibility(ctx.conn(), &event, viewer).await } #[skip_serializing_none] @@ -446,14 +465,21 @@ async fn get_event_locations_for_product( args: ProductArgs, ) -> AppResult> { ctx.read(Topic::Product(args.product_id.0)); - Ok(sqlx::query_as( + let rows: Vec = sqlx::query_as( "SELECT ep.event_id, l.label AS location_label FROM event_products ep LEFT JOIN event_location_categories l ON l.id = ep.location_category_id WHERE ep.product_id = $1 ORDER BY ep.created_at, ep.id", ) .bind(args.product_id.0) .fetch_all(ctx.conn()) - .await?) + .await?; + let mut visible = Vec::new(); + for row in rows { + if may_see_event(ctx, row.event_id).await? { + visible.push(row); + } + } + Ok(visible) } #[derive(Deserialize)] @@ -463,7 +489,9 @@ struct EventArgs { } async fn get_product_ids_for_event(ctx: &mut Ctx, args: EventArgs) -> AppResult> { - ctx.read(Topic::Event(args.event_id.0)); + if !may_see_event(ctx, args.event_id.0).await? { + return Ok(Vec::new()); + } Ok(sqlx::query_scalar( "SELECT product_id FROM event_products WHERE event_id = $1 ORDER BY created_at, id", ) @@ -614,6 +642,12 @@ async fn get_products_for_event(ctx: &mut Ctx, args: EventArgs) -> AppResult