From ad81b1f063617f04df53395368af8e004ca245db Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 22:05:04 +0100 Subject: [PATCH 01/10] feat(fees): fee groups with own fees for members, helpers and others in the backend (#302) Groups in features.feeGroups with own commission, intake fee, fee cap and item limit. Self-declared groups are checked at the intake before the first item can be accepted; helpers are in their group by role, the organizer puts others in by hand. Cash desk, settlement, payout, export and item limit use the seller's fees; a group change books the seller's sales anew. Fee lock: groups only get cheaper. Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0036_fee_groups.sql | 10 + backend/src/demo/extended.rs | 11 + backend/src/modules/docs.rs | 10 +- backend/src/modules/event_products.rs | 9 + backend/src/modules/event_roles.rs | 77 +++- backend/src/modules/event_seller.rs | 27 +- backend/src/modules/events.rs | 158 ++++++- backend/src/modules/features.rs | 154 +++++-- backend/src/modules/fee_groups.rs | 610 +++++++++++++++++++++++++ backend/src/modules/mod.rs | 2 + backend/src/modules/purchases.rs | 122 +++-- backend/src/modules/sales.rs | 27 +- backend/src/modules/seller_numbers.rs | 7 +- backend/src/modules/settlement.rs | 6 + backend/tests/api/events.rs | 2 +- backend/tests/api/fee_groups.rs | 539 ++++++++++++++++++++++ backend/tests/api/main.rs | 1 + 17 files changed, 1656 insertions(+), 116 deletions(-) create mode 100644 backend/migrations/0036_fee_groups.sql create mode 100644 backend/src/modules/fee_groups.rs create mode 100644 backend/tests/api/fee_groups.rs diff --git a/backend/migrations/0036_fee_groups.sql b/backend/migrations/0036_fee_groups.sql new file mode 100644 index 00000000..bc06b41b --- /dev/null +++ b/backend/migrations/0036_fee_groups.sql @@ -0,0 +1,10 @@ +-- Fee groups (features.feeGroups, #302): the group a seller is in, by their own choice +-- (self-declared) or put in by the team. Helpers are in their group by role and need no row. +-- fee_group_decided_at/by: when the team confirmed, assigned or took away the group; a +-- self-declared group without it is still to be checked at the intake. +-- fee_group_label: the group applied at the payout, so the settlement keeps it. +ALTER TABLE event_sellers + ADD COLUMN fee_group_id text, + ADD COLUMN fee_group_decided_at timestamptz, + ADD COLUMN fee_group_decided_by uuid REFERENCES users(id) ON DELETE SET NULL, + ADD COLUMN fee_group_label text; diff --git a/backend/src/demo/extended.rs b/backend/src/demo/extended.rs index 9acc69f8..56885dee 100644 --- a/backend/src/demo/extended.rs +++ b/backend/src/demo/extended.rs @@ -825,6 +825,11 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "privateSellersOnly": true, "fixedSellerData": true, "maxItemsPerSeller": 40, + // Helpers sell without commission and bring more (#302) + "feeGroups": [{ + "id": "helfer", "label": "Helferinnen und Helfer", "commission": 0, + "maxItemsPerSeller": 60, "assignment": "helpers", + }], }), }, true, @@ -1116,6 +1121,12 @@ async fn ski_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "photosOptional": true, "priceOnLabel": true, "intakeFee": 1, + // Club members pay less; the intake checks the card (#302) + "feeGroups": [{ + "id": "mitglieder", "label": "Vereinsmitglieder", "commission": 5, + "assignment": "selfDeclared", + "proofHint": "Mitgliedsausweis bei der Abgabe zeigen", + }], }), }, true, diff --git a/backend/src/modules/docs.rs b/backend/src/modules/docs.rs index 5c26a7bc..c404de17 100644 --- a/backend/src/modules/docs.rs +++ b/backend/src/modules/docs.rs @@ -539,6 +539,13 @@ pub struct EventSeller { pub intake_fee_items: Option, /// Fees above the cap given back at the payout (#301) pub fee_cap_credit: Option, + /// Fee group the seller chose or the team put them in (#302) + pub fee_group_id: Option, + /// When the team confirmed, assigned or took away the group + #[serde(with = "ms_opt")] + pub fee_group_decided_at: Option>, + /// The group applied at the payout + pub fee_group_label: Option, #[serde(with = "ms_opt")] pub private_seller_confirmed_at: Option>, pub seller_snapshot: Option, @@ -547,7 +554,8 @@ pub struct EventSeller { pub const EVENT_SELLER_COLUMNS: &str = "id, created_at, event_id, user_id, total_fee, commission_fee, sale_fee_fixed, sale_fee_percentage, payout_amount, payout_received, number, intake_fee, - intake_fee_items, fee_cap_credit, private_seller_confirmed_at, seller_snapshot"; + intake_fee_items, fee_cap_credit, fee_group_id, fee_group_decided_at, fee_group_label, + private_seller_confirmed_at, seller_snapshot"; pub async fn event_seller( conn: &mut PgConnection, diff --git a/backend/src/modules/event_products.rs b/backend/src/modules/event_products.rs index 84dacdee..26cdfa24 100644 --- a/backend/src/modules/event_products.rs +++ b/backend/src/modules/event_products.rs @@ -29,6 +29,7 @@ use super::event_roles::{ }; use super::events::{admitted_by_visibility, is_event_approved, is_live}; use super::features::discount_unavailable; +use super::fee_groups; use super::notifications::{self, Area, Content, T}; use super::offers::{close_offers_for_event_product, reopen_closed_offers}; use super::sales::{self, SaleInfo}; @@ -1027,6 +1028,10 @@ async fn update_product_status(ctx: &mut Ctx, args: StatusArgs) -> AppResult> = args .seen_product_ids .map(|ids| ids.into_iter().map(|id| id.0).collect()); diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index f41dc78d..453c677e 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -12,6 +12,7 @@ use super::access::is_platform_admin; use super::docs::{self, User}; use super::event_exclusions::{Exclusion, exclusions_of_event}; use super::features::label_mark; +use super::fee_groups::{self, Membership}; use super::labels::seller_sort_code; use super::sales::{self, IntakeFee}; use super::seller_records::{keeps_seller_record, with_snapshot}; @@ -435,6 +436,23 @@ pub struct VendorWithCalculations { pub details_recorded: Option, /// The organizer took the seller out of the bazaar pub excluded: Option, + /// The fee group whose fees apply (#302) + pub fee_group: Option, +} + +/// A seller's fee group as the team sees it. +#[skip_serializing_none] +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VendorFeeGroup { + pub id: Option, + pub label: String, + /// Self-declared and not checked yet: the intake has to confirm or take it away + pub pending: bool, + /// By the helper role, not chosen or assigned + pub by_role: bool, + /// The group the seller chose or was put in, when another one applies or none + pub chosen: Option, } /// Sellers of an event with their sales totals and payout state. No permission check. @@ -462,7 +480,11 @@ pub async fn load_vendors_with_calculations( .bind(event_id) .fetch_all(ctx.conn()) .await?; - let accepted = if event.resolved_features().intake_fee.is_some() { + let features = event.resolved_features(); + let groups = !features.fee_groups.is_empty(); + let accepted = if features.intake_fee.is_some() + || features.fee_groups.iter().any(|g| g.intake_fee.is_some()) + { sales::accepted_items_by_seller(ctx.conn(), event_id).await? } else { Default::default() @@ -501,22 +523,55 @@ pub async fn load_vendors_with_calculations( { user = with_snapshot(user, snapshot); } + let helper_permissions = helpers + .iter() + .find(|(user, _)| *user == vendor) + .map(|(_, stored)| permissions_of(stored.clone())); + let member = if groups { + Membership { + stored: seller.as_ref().and_then(|s| s.fee_group_id.clone()), + decided_at: seller.as_ref().and_then(|s| s.fee_group_decided_at), + helper: helper_permissions.is_some(), + } + } else { + Membership::default() + }; + let fees = member.fees(&event); + let paid = seller.as_ref().is_some_and(|seller| seller.payout_received); + let fee_group = match ( + &fees.group, + seller.as_ref().and_then(|s| s.fee_group_label.clone()), + ) { + // Paid out: the group as settled + (_, Some(label)) if paid => Some(VendorFeeGroup { + id: None, + label, + pending: false, + by_role: false, + chosen: None, + }), + _ if paid => None, + (Some(group), _) => Some(VendorFeeGroup { + id: Some(group.id.clone()), + label: group.label.clone(), + pending: member.pending(&event, &fees).is_some(), + by_role: member.stored.as_deref() != Some(group.id.as_str()), + chosen: member.stored.clone().filter(|chosen| *chosen != group.id), + }), + (None, _) => None, + }; let intake_fee = sales::intake_fee_of( - &event, + &fees, seller.as_ref(), accepted.get(&vendor).copied().unwrap_or(0), ); let fee_cap_credit = - sales::fee_cap_credit_of(&event, seller.as_ref(), commission, &intake_fee); + sales::fee_cap_credit_of(&fees, seller.as_ref(), commission, &intake_fee); let sort_code = if universal { seller_sort_code(ctx, vendor).await? } else { None }; - let helper_permissions = helpers - .iter() - .find(|(user, _)| *user == vendor) - .map(|(_, stored)| permissions_of(stored.clone())); vendors.push(VendorWithCalculations { user, total_revenue, @@ -525,7 +580,7 @@ pub async fn load_vendors_with_calculations( fee_cap_credit, payout: sales_payout - intake_fee.total + fee_cap_credit, received_directly, - paid: seller.as_ref().is_some_and(|seller| seller.payout_received), + paid, gross_revenue, total_discount: gross_revenue - total_revenue, is_helper: helper_permissions.is_some(), @@ -538,6 +593,7 @@ pub async fn load_vendors_with_calculations( seller_number: seller.and_then(|seller| seller.number), sort_code, excluded: exclusions.remove(&vendor), + fee_group, }); } Ok(vendors) @@ -703,6 +759,8 @@ async fn add_co_organizer_for_event(ctx: &mut Ctx, args: AddHelperArgs) -> AppRe add_role(ctx, event, user, Role::Coorganizer).await?; // Also when already a helper: appointing again sets the rights anew store_permissions(ctx, event, user, args.permissions.as_deref()).await?; + // Helpers may pay the fees of a helper group (#302) + fee_groups::after_role_change(ctx, event, user).await?; Ok(Success { success: true }) } @@ -752,6 +810,7 @@ async fn remove_co_organizer_for_event(ctx: &mut Ctx, args: EventUserArgs) -> Ap return Err(AppError::bad_request("seller.organizerRoleFixed")); } remove_role(ctx, event, user, Role::Coorganizer).await?; + fee_groups::after_role_change(ctx, event, user).await?; // Their devices may keep the keys of the sellers' ID codes super::offline::renew_check_in_keys(ctx, event).await?; Ok(Success { success: true }) @@ -777,6 +836,8 @@ async fn transfer_organizer(ctx: &mut Ctx, args: EventUserArgs) -> AppResult, /// The link of an invitation by mail: replaces the access code invitation: Option, + /// A fee group the seller says they belong to, checked at the intake (#302) + fee_group_id: Option, } /// The current user joins the event as seller and gets the next seller number. @@ -138,6 +141,7 @@ async fn join_event(ctx: &mut Ctx, args: JoinArgs) -> AppResult { return Err(anyhow::anyhow!("seller role without event_sellers row").into()); } let features = event.resolved_features(); + fee_groups::check_choice(&event, args.fee_group_id.as_deref())?; if features.private_sellers_only && args.private_seller != Some(true) { return Err(AppError::bad_request("join.privateRequired")); } @@ -162,14 +166,15 @@ async fn join_event(ctx: &mut Ctx, args: JoinArgs) -> AppResult { let number = next_seller_number(ctx, event.id).await?; let id: Uuid = sqlx::query_scalar( "INSERT INTO event_sellers (event_id, user_id, total_fee, commission_fee, payout_amount, - payout_received, number, private_seller_confirmed_at) - VALUES ($1, $2, 0, 0, 0, false, $3, CASE WHEN $4 THEN now() END) + payout_received, number, private_seller_confirmed_at, fee_group_id) + VALUES ($1, $2, 0, 0, 0, false, $3, CASE WHEN $4 THEN now() END, $5) RETURNING id", ) .bind(event.id) .bind(user) .bind(number) .bind(features.private_sellers_only) + .bind(&args.fee_group_id) .fetch_one(ctx.conn()) .await?; event_roles::add_role(ctx, event.id, user, Role::Seller).await?; @@ -409,15 +414,19 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult .fetch_one(ctx.conn()) .await?; let fee = intake_fee_for_seller(ctx.conn(), &event, vendor, row.as_ref()).await?; + let fees = fee_groups::seller_fees(ctx.conn(), &event, vendor).await?; // Fees above the cap go back to the seller with the payout - let credit = sales::fee_cap_credit_of(&event, row.as_ref(), commission, &fee); + let credit = sales::fee_cap_credit_of(&fees, row.as_ref(), commission, &fee); + // The group applied, kept with the settlement (#302) + let group = fees.group.map(|group| group.label); let payout = payout - fee.total + credit; let credit = (!credit.is_zero()).then_some(credit); match row { Some(row) => { sqlx::query( "UPDATE event_sellers SET commission_fee = $2, payout_amount = $3, intake_fee = $4, - intake_fee_items = $5, fee_cap_credit = $6, payout_received = true + intake_fee_items = $5, fee_cap_credit = $6, fee_group_label = $7, + payout_received = true WHERE id = $1", ) .bind(row.id) @@ -426,6 +435,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult .bind(fee.total) .bind(fee.items as i32) .bind(credit) + .bind(&group) .execute(ctx.conn()) .await?; } @@ -433,8 +443,9 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult let number = next_seller_number(ctx, event.id).await?; sqlx::query( "INSERT INTO event_sellers (event_id, user_id, total_fee, commission_fee, payout_amount, - intake_fee, intake_fee_items, fee_cap_credit, payout_received, number) - VALUES ($1, $2, 0, $3, $4, $5, $6, $7, true, $8)", + intake_fee, intake_fee_items, fee_cap_credit, fee_group_label, payout_received, + number) + VALUES ($1, $2, 0, $3, $4, $5, $6, $7, $8, true, $9)", ) .bind(event.id) .bind(vendor) @@ -443,6 +454,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult .bind(fee.total) .bind(fee.items as i32) .bind(credit) + .bind(&group) .bind(number) .execute(ctx.conn()) .await?; @@ -460,7 +472,8 @@ async fn unmark_vendor_payout_received(ctx: &mut Ctx, args: VendorArgs) -> AppRe require_staff_and_seller(ctx, event, vendor, "seller.undoPayoutStaffOnly").await?; sqlx::query( "UPDATE event_sellers SET payout_received = false, commission_fee = 0, payout_amount = 0, - intake_fee = NULL, intake_fee_items = NULL, fee_cap_credit = NULL + intake_fee = NULL, intake_fee_items = NULL, fee_cap_credit = NULL, + fee_group_label = NULL WHERE event_id = $1 AND user_id = $2 AND payout_received", ) .bind(event) diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index e47b5772..3d9276bd 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -24,7 +24,7 @@ use super::event_roles::{ self, Permission, Role, TEAM, has_any_role_or_admin, has_role_or_admin, is_bystander, load_vendors_with_calculations, require_permission, }; -use super::features::MAX_DISCOUNT_PERCENT; +use super::features::{self, FeeGroupAssignment, MAX_DISCOUNT_PERCENT}; use super::moderation::{LogEntry, log_action}; use super::notifications::{self, Area, Content, T}; use super::{retention, sales, seller_numbers}; @@ -772,6 +772,97 @@ struct FeaturesArgs { registration_open: Option, registration_starts_at: Option, registration_ends_at: Option, + /// Absent (older apps): the stored groups stay + fee_groups: Option>, +} + +/// One fee group as the form sends it (#302) +#[derive(Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FeeGroupArgs { + id: String, + label: String, + commission: f64, + intake_fee: Option, + max_fees_per_seller: Option, + max_items_per_seller: Option, + assignment: FeeGroupAssignment, + proof_hint: Option, +} + +/// At most this many fee groups per bazaar +const MAX_FEE_GROUPS: usize = 10; + +/// Checks the fee groups and stores them like the bazaar's own fees: cents, trimmed text. +fn sanitize_fee_groups(groups: Vec) -> AppResult { + if groups.len() > MAX_FEE_GROUPS { + return Err(AppError::bad_request("event.feeGroupsTooMany")); + } + let mut ids: Vec = Vec::new(); + let mut labels: Vec = Vec::new(); + let mut stored = Vec::new(); + for group in groups { + let id = group.id.trim().to_owned(); + let valid_id = !id.is_empty() + && id.len() <= 40 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if !valid_id || ids.contains(&id) { + return Err(invalid("feeGroups.id")); + } + let label = group.label.trim().to_owned(); + if label.is_empty() || label.chars().count() > 60 { + return Err(AppError::bad_request("event.feeGroupLabel")); + } + if labels + .iter() + .any(|other| other.to_lowercase() == label.to_lowercase()) + { + return Err(AppError::bad_request("event.feeGroupLabelTwice")); + } + if !group.commission.is_finite() || !(0.0..=100.0).contains(&group.commission) { + return Err(AppError::bad_request("event.feeGroupCommission")); + } + let proof_hint = group + .proof_hint + .map(|hint| hint.trim().to_owned()) + .filter(|hint| !hint.is_empty()); + if proof_hint + .as_ref() + .is_some_and(|hint| hint.chars().count() > 200) + { + return Err(AppError::bad_request("event.feeGroupProofHint")); + } + let mut entry = Map::new(); + entry.insert("id".into(), json!(id)); + entry.insert("label".into(), json!(label)); + entry.insert( + "commission".into(), + json!((group.commission * 100.0).round() / 100.0), + ); + if let Some(fee) = sanitize_intake_fee(group.intake_fee)? { + entry.insert("intakeFee".into(), json!(fee)); + } + if let Some(cap) = sanitize_fee_cap(group.max_fees_per_seller)? { + entry.insert("maxFeesPerSeller".into(), json!(cap)); + } + if let Some(limit) = sanitize_item_limit(group.max_items_per_seller)? { + entry.insert("maxItemsPerSeller".into(), json!(limit)); + } + entry.insert("assignment".into(), json!(group.assignment)); + if let Some(hint) = proof_hint { + entry.insert("proofHint".into(), json!(hint)); + } + ids.push(id); + labels.push(label); + stored.push(Value::Object(entry)); + } + Ok(if stored.is_empty() { + Value::Null + } else { + Value::Array(stored) + }) } fn sanitize_item_limit(limit: Option) -> AppResult> { @@ -1031,6 +1122,16 @@ fn sanitize_features( put("registrationOpen", json!(registration_open)); put("registrationStartsAt", json!(starts)); put("registrationEndsAt", json!(ends)); + put( + "feeGroups", + match features.fee_groups { + Some(groups) => sanitize_fee_groups(groups)?, + None => previous + .and_then(|p| p.get("feeGroups")) + .cloned() + .unwrap_or(Value::Null), + }, + ); Ok(Value::Object(stored)) } @@ -1151,6 +1252,56 @@ fn time_arg(ms: f64, field: &str) -> AppResult> { from_ms(ms).ok_or_else(|| invalid(field)) } +/// Fee groups once sellers registered: none may go and none may get dearer, like the fees +/// of the bazaar; while it runs they stay as they are. Name and hint may change. +fn check_fee_groups_lock( + old: &features::EventFeatures, + new: &features::EventFeatures, + running: bool, +) -> AppResult<()> { + let infinite = |value: Option| value.unwrap_or(Decimal::MAX); + for group in &old.fee_groups { + let Some(next) = new.fee_groups.iter().find(|next| next.id == group.id) else { + return Err(AppError::bad_request(if running { + "event.runningNoFees" + } else { + "event.feeGroupsOnlyLower" + })); + }; + let fees = |g: &features::FeeGroup, f: &features::EventFeatures| { + ( + g.commission, + g.intake_fee.unwrap_or_default(), + infinite(g.max_fees_per_seller.or(f.max_fees_per_seller)), + ) + }; + let (before, after) = (fees(group, old), fees(next, new)); + let items = |g: &features::FeeGroup, f: &features::EventFeatures| { + g.max_items_per_seller + .or(f.max_items_per_seller) + .unwrap_or(u32::MAX) + }; + if running { + if before != after || group.assignment != next.assignment { + return Err(AppError::bad_request("event.runningNoFees")); + } + } else if after.0 > before.0 + || after.1 > before.1 + || after.2 > before.2 + || group.assignment != next.assignment + { + return Err(AppError::bad_request("event.feeGroupsOnlyLower")); + } + if items(next, new) < items(group, old) { + return Err(AppError::bad_request("event.limitOnlyHigher")); + } + } + if running && new.fee_groups.len() != old.fee_groups.len() { + return Err(AppError::bad_request("event.runningNoFees")); + } + Ok(()) +} + fn money(value: f64, field: &str) -> AppResult { Decimal::from_f64(value) .map(|v| v.cents()) @@ -1423,6 +1574,11 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { if limit(Some(&features)) < limit(event.features.as_ref()) { return Err(AppError::bad_request("event.limitOnlyHigher")); } + check_fee_groups_lock( + &event.resolved_features(), + &features::resolve(Some(&features)), + running, + )?; } // The admin approves anyway: no request to themselves let making_public = !admin diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index 054961c4..c37fa3b4 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -39,6 +39,51 @@ struct Stored { registration_open: Option, registration_starts_at: Option, registration_ends_at: Option, + fee_groups: Option>, +} + +/// A fee group as stored in `features.feeGroups` (#302). +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredFeeGroup { + id: String, + label: String, + commission: f64, + intake_fee: Option, + max_fees_per_seller: Option, + max_items_per_seller: Option, + assignment: FeeGroupAssignment, + proof_hint: Option, +} + +/// How a seller gets into a fee group. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum FeeGroupAssignment { + /// The seller says so when joining; the team checks it at the intake + SelfDeclared, + /// Everyone with a helper role at the bazaar, and whom the team puts in by hand + Helpers, +} + +/// Sellers with own fees instead of the bazaar's, e.g. club members or helpers (#302). +/// Each group has its own fees, not a discount: "5 % instead of 10 %". +#[derive(Debug, Clone, PartialEq)] +pub struct FeeGroup { + pub id: String, + /// Chosen by the organizer, e.g. "Vereinsmitglieder" + pub label: String, + /// Percent of each sale + pub commission: Decimal, + /// € per accepted item; none: no intake fee + pub intake_fee: Option, + /// Own fee cap; none: the bazaar's + pub max_fees_per_seller: Option, + /// Own item limit per seller; none: the bazaar's + pub max_items_per_seller: Option, + pub assignment: FeeGroupAssignment, + /// Shown to sellers, e.g. "Mitgliedsausweis bei der Abgabe zeigen" + pub proof_hint: Option, } #[derive(Debug, Clone, PartialEq)] @@ -76,6 +121,8 @@ pub struct EventFeatures { /// Joining is possible from / until then; either may be missing pub registration_starts_at: Option>, pub registration_ends_at: Option>, + /// Sellers with own fees (#302); see `fee_groups` + pub fee_groups: Vec, } /// Events created before features existed keep their old behaviour: discounts on (up to @@ -122,6 +169,31 @@ pub fn resolve(features: Option<&Value>) -> EventFeatures { registration_open: stored.registration_open.unwrap_or(true), registration_starts_at: stored.registration_starts_at.and_then(from_ms), registration_ends_at: stored.registration_ends_at.and_then(from_ms), + fee_groups: stored + .fee_groups + .unwrap_or_default() + .into_iter() + .map(|group| FeeGroup { + id: group.id, + label: group.label, + commission: Decimal::from_f64_retain(group.commission) + .unwrap_or_default() + .max(Decimal::ZERO) + .round_dp(2), + intake_fee: group + .intake_fee + .and_then(Decimal::from_f64_retain) + .map(|fee| fee.max(Decimal::ZERO).cents()) + .filter(|fee| !fee.is_zero()), + max_fees_per_seller: group + .max_fees_per_seller + .and_then(Decimal::from_f64_retain) + .map(|cap| cap.max(Decimal::ZERO).cents()), + max_items_per_seller: group.max_items_per_seller.map(|n| n.max(0.0) as u32), + assignment: group.assignment, + proof_hint: group.proof_hint, + }) + .collect(), } } @@ -245,6 +317,49 @@ pub fn shows_price_on_label(event: &Event) -> bool { features.price_on_label && !features.discounts } +/// An event with these features, for tests +#[cfg(test)] +pub fn tests_event(features: Value) -> Event { + Event { + id: uuid::Uuid::nil(), + created_at: Utc::now(), + title: String::new(), + description: String::new(), + cover_image: None, + event_map_image: None, + location: String::new(), + street: None, + postal_code: None, + city: None, + country: None, + start_date: Utc::now(), + end_date: Utc::now(), + contact_info: String::new(), + categories: Vec::new(), + services: Vec::new(), + visibility: "public".into(), + is_approved: None, + approval_status: None, + approved_at: None, + approved_by: None, + rejected_at: None, + rejected_by: None, + rejection_reason: None, + access_code: None, + vendor_limit: None, + seller_count: None, + last_seller_number: None, + commission: Decimal::ZERO, + sale_fee_fixed: None, + sale_fee_percentage: None, + features: Some(features), + seller_logistics: None, + reminders_sent: None, + moderation: None, + organizer_id: uuid::Uuid::nil(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -309,44 +424,7 @@ mod tests { } fn event_with(features: Value) -> Event { - Event { - id: uuid::Uuid::nil(), - created_at: Utc::now(), - title: String::new(), - description: String::new(), - cover_image: None, - event_map_image: None, - location: String::new(), - street: None, - postal_code: None, - city: None, - country: None, - start_date: Utc::now(), - end_date: Utc::now(), - contact_info: String::new(), - categories: Vec::new(), - services: Vec::new(), - visibility: "public".into(), - is_approved: None, - approval_status: None, - approved_at: None, - approved_by: None, - rejected_at: None, - rejected_by: None, - rejection_reason: None, - access_code: None, - vendor_limit: None, - seller_count: None, - last_seller_number: None, - commission: Decimal::ZERO, - sale_fee_fixed: None, - sale_fee_percentage: None, - features: Some(features), - seller_logistics: None, - reminders_sent: None, - moderation: None, - organizer_id: uuid::Uuid::nil(), - } + super::tests_event(features) } #[test] diff --git a/backend/src/modules/fee_groups.rs b/backend/src/modules/fee_groups.rs new file mode 100644 index 00000000..7722611b --- /dev/null +++ b/backend/src/modules/fee_groups.rs @@ -0,0 +1,610 @@ +//! Fee groups (#302): sellers with own fees instead of the bazaar's, e.g. club members or +//! helpers. A seller is in at most one group at a time; who would be in several gets the +//! cheapest. Self-declared groups are checked by the team at the intake: until then no +//! item of the seller can be accepted, so nobody is settled with a group nobody checked. + +use std::cmp::Ordering; +use std::collections::HashMap; + +use chrono::{DateTime, Utc}; +use rust_decimal::Decimal; +use serde::{Deserialize, Serialize}; +use serde_with::skip_serializing_none; +use sqlx::PgConnection; +use uuid::Uuid; + +use super::docs::{self, Event}; +use super::event_roles::{self, Permission, Role, assert_vendor_not_paid_out, require_permission}; +use super::features::{FeeGroup, FeeGroupAssignment}; +use super::sales::{self, ACCEPTED_STATUSES}; +use crate::error::{AppError, AppResult}; +use crate::money::Cents; +use crate::realtime::Topic; +use crate::register; +use crate::rpc::{Ctx, Registry}; +use crate::shape::{Id, ms_opt}; + +pub fn register(registry: &mut Registry) { + register!(registry, Query "feeGroups.getMyFeeGroup" => get_my_fee_group); + register!(registry, Mutation "feeGroups.chooseFeeGroup" => choose_fee_group); + register!(registry, Mutation "feeGroups.confirmFeeGroup" => confirm_fee_group); + register!(registry, Mutation "feeGroups.removeFeeGroup" => remove_fee_group); + register!(registry, Mutation "feeGroups.assignFeeGroup" => assign_fee_group); +} + +/// The fees one seller pays at the bazaar: the bazaar's or those of their group. +#[derive(Debug, Clone, PartialEq)] +pub struct SellerFees { + /// The group whose fees apply; none: the bazaar's + pub group: Option, + /// Percent of each sale + pub commission: Decimal, + /// € per accepted item + pub intake_fee: Option, + /// All fees of the seller together at most + pub max_fees_per_seller: Option, + pub max_items_per_seller: Option, +} + +impl SellerFees { + /// The bazaar's own fees + pub fn of_event(event: &Event) -> Self { + let features = event.resolved_features(); + Self { + group: None, + commission: event.commission, + intake_fee: features.intake_fee.filter(|fee| *fee > Decimal::ZERO), + max_fees_per_seller: features.max_fees_per_seller, + max_items_per_seller: features.max_items_per_seller, + } + } + + /// The fees of a group: cap and item limit fall back to the bazaar's + pub fn of_group(event: &Event, group: &FeeGroup) -> Self { + let base = Self::of_event(event); + Self { + group: Some(group.clone()), + commission: group.commission, + intake_fee: group.intake_fee.filter(|fee| *fee > Decimal::ZERO), + max_fees_per_seller: group.max_fees_per_seller.or(base.max_fees_per_seller), + max_items_per_seller: group.max_items_per_seller.or(base.max_items_per_seller), + } + } + + /// The commission of a sale at `total`, in cents + pub fn commission_of(&self, total: Decimal) -> Option { + total + .checked_mul(self.commission) + .map(|c| (c / Decimal::ONE_HUNDRED).cents()) + } +} + +/// Which of two fee sets is cheaper for the seller: the lower commission, then the lower +/// intake fee, then the lower cap. The app sorts the same (cheaperFees in feeGroups.ts). +fn compare(a: &SellerFees, b: &SellerFees) -> Ordering { + let key = |f: &SellerFees| { + ( + f.commission, + f.intake_fee.unwrap_or_default(), + f.max_fees_per_seller.unwrap_or(Decimal::MAX), + ) + }; + key(a).cmp(&key(b)) +} + +/// The fees of a seller in the stored group `stored` (if it still exists) and, as helper, +/// in every helper group: the cheapest of them; the bazaar's without any. +pub fn fees_for(event: &Event, stored: Option<&str>, helper: bool) -> SellerFees { + let groups = event.resolved_features().fee_groups; + groups + .iter() + .filter(|group| { + Some(group.id.as_str()) == stored + || (helper && group.assignment == FeeGroupAssignment::Helpers) + }) + .map(|group| SellerFees::of_group(event, group)) + .min_by(compare) + .unwrap_or_else(|| SellerFees::of_event(event)) +} + +/// What the event needs to know of a seller for their group. +#[derive(Debug, Clone, Default)] +pub struct Membership { + pub stored: Option, + pub decided_at: Option>, + pub helper: bool, +} + +impl Membership { + fn from_row(row: Option<&docs::EventSeller>, helper: bool) -> Self { + Self { + stored: row.and_then(|row| row.fee_group_id.clone()), + decided_at: row.and_then(|row| row.fee_group_decided_at), + helper, + } + } + + pub fn fees(&self, event: &Event) -> SellerFees { + fees_for(event, self.stored.as_deref(), self.helper) + } + + /// A self-declared group the team has not checked yet, and it is the one that applies + pub fn pending<'a>(&self, event: &Event, fees: &'a SellerFees) -> Option<&'a FeeGroup> { + fees.group.as_ref().filter(|group| { + self.decided_at.is_none() + && group.assignment == FeeGroupAssignment::SelfDeclared + && self.stored.as_deref() == Some(group.id.as_str()) + && !event.resolved_features().fee_groups.is_empty() + }) + } +} + +async fn is_helper(conn: &mut PgConnection, event: Uuid, seller: Uuid) -> sqlx::Result { + event_roles::has_role(conn, event, seller, Role::Coorganizer).await +} + +/// The group of one seller. +pub async fn membership( + conn: &mut PgConnection, + event: &Event, + seller: Uuid, +) -> sqlx::Result { + if event.resolved_features().fee_groups.is_empty() { + return Ok(Membership::default()); + } + let row = docs::event_seller(&mut *conn, event.id, seller).await?; + let helper = is_helper(conn, event.id, seller).await?; + Ok(Membership::from_row(row.as_ref(), helper)) +} + +/// The fees one seller pays at the event. +pub async fn seller_fees( + conn: &mut PgConnection, + event: &Event, + seller: Uuid, +) -> sqlx::Result { + if event.resolved_features().fee_groups.is_empty() { + return Ok(SellerFees::of_event(event)); + } + Ok(membership(conn, event, seller).await?.fees(event)) +} + +/// The fees of every seller of the event, for the cash desk and the lists. Sellers without +/// a group pay the bazaar's. +pub struct FeeBook { + default: SellerFees, + by_seller: HashMap, +} + +impl FeeBook { + pub async fn load(conn: &mut PgConnection, event: &Event) -> sqlx::Result { + let default = SellerFees::of_event(event); + let mut by_seller = HashMap::new(); + if !event.resolved_features().fee_groups.is_empty() { + let rows: Vec<(Uuid, Option, bool)> = sqlx::query_as( + "SELECT u.user_id, s.fee_group_id, bool_or(u.helper) FROM ( + SELECT user_id, false AS helper FROM event_sellers + WHERE event_id = $1 AND fee_group_id IS NOT NULL + UNION ALL SELECT user_id, true FROM event_roles + WHERE event_id = $1 AND role = 'coorganizer' + ) u + LEFT JOIN event_sellers s ON s.event_id = $1 AND s.user_id = u.user_id + GROUP BY u.user_id, s.fee_group_id", + ) + .bind(event.id) + .fetch_all(conn) + .await?; + for (seller, stored, helper) in rows { + by_seller.insert(seller, fees_for(event, stored.as_deref(), helper)); + } + } + Ok(Self { default, by_seller }) + } + + pub fn get(&self, seller: Uuid) -> &SellerFees { + self.by_seller.get(&seller).unwrap_or(&self.default) + } +} + +/// Refuses the intake of a seller whose self-declared group the team has not checked: +/// confirming or taking it away comes first. +pub async fn assert_group_decided( + conn: &mut PgConnection, + event: &Event, + seller: Uuid, +) -> AppResult<()> { + let member = membership(conn, event, seller).await?; + let fees = member.fees(event); + if let Some(group) = member.pending(event, &fees) { + return Err(AppError::coded( + axum::http::StatusCode::BAD_REQUEST, + "feeGroup.unconfirmed", + &[("group", &group.label)], + )); + } + Ok(()) +} + +/// Books the seller's sales of the event anew with the fees that apply now, after their +/// group changed. Sales through the desk: commission of the price, the rest is paid out. +/// Direct sales: the desk took what it took, so what the seller paid too much comes back +/// with the payout and what is missing is owed (a negative payout of that sale); the cap +/// applies in booking order. Not for paid-out sellers: the settlement is final. +pub async fn reprice_seller_sales( + conn: &mut PgConnection, + event: &Event, + seller: Uuid, +) -> sqlx::Result<()> { + let fees = seller_fees(&mut *conn, event, seller).await?; + let rows: Vec<(Uuid, Decimal, Decimal, Decimal, bool)> = sqlx::query_as( + "SELECT id, total_amount, commission_amount, payout_amount, direct_sale FROM purchases + WHERE event_id = $1 AND seller_id = $2 ORDER BY created_at, id", + ) + .bind(event.id) + .bind(seller) + .fetch_all(&mut *conn) + .await?; + let mut paid_directly = Decimal::ZERO; + for (id, total, commission, payout, direct) in rows { + let full = fees.commission_of(total).unwrap_or(commission); + let (due, rest) = if direct { + let due = sales::capped_commission(full, paid_directly, fees.max_fees_per_seller); + paid_directly += due; + // What the desk took stays: commission + payout + (due, commission + payout - due) + } else { + (full, total - full) + }; + if due != commission { + sqlx::query( + "UPDATE purchases SET commission_amount = $2, payout_amount = $3 WHERE id = $1", + ) + .bind(id) + .bind(due) + .bind(rest) + .execute(&mut *conn) + .await?; + } + } + Ok(()) +} + +/// After a helper role came or went: the seller's group may be another now. +pub async fn after_role_change(ctx: &mut Ctx, event: Uuid, seller: Uuid) -> AppResult<()> { + let Some(event) = docs::event(ctx.conn(), event).await? else { + return Ok(()); + }; + let helper_groups = event + .resolved_features() + .fee_groups + .iter() + .any(|group| group.assignment == FeeGroupAssignment::Helpers); + let paid = docs::event_seller(ctx.conn(), event.id, seller) + .await? + .is_some_and(|row| row.payout_received); + if helper_groups && !paid { + sales::lock_seller_fees(ctx.conn(), event.id, seller).await?; + reprice_seller_sales(ctx.conn(), &event, seller).await?; + } + Ok(()) +} + +/// Whether the team took in an item of the seller already: then the seller can no longer +/// change their group themselves. +async fn has_accepted_items( + conn: &mut PgConnection, + event: Uuid, + seller: Uuid, +) -> sqlx::Result { + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT EXISTS (SELECT 1 FROM event_products ep JOIN products p ON p.id = ep.product_id + WHERE ep.event_id = $1 AND p.vendor_id = $2 AND ep.status IN {ACCEPTED_STATUSES})" + ))) + .bind(event) + .bind(seller) + .fetch_one(conn) + .await +} + +/// A group sellers may choose themselves; `None` (no group) is always fine. +pub fn check_choice(event: &Event, group: Option<&str>) -> AppResult<()> { + let Some(group) = group else { + return Ok(()); + }; + let choosable = event + .resolved_features() + .fee_groups + .iter() + .any(|g| g.id == group && g.assignment == FeeGroupAssignment::SelfDeclared); + if !choosable { + return Err(AppError::bad_request("feeGroup.unknown")); + } + Ok(()) +} + +async fn event_of(ctx: &mut Ctx, event: Uuid) -> AppResult { + docs::event(ctx.conn(), event) + .await? + .ok_or_else(|| AppError::not_found("notFound.event")) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct EventArgs { + event_id: Id, +} + +/// The seller's group as they see it. +#[skip_serializing_none] +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct MyFeeGroup { + /// The group the seller chose or was put in + chosen: Option, + /// The group whose fees apply: the chosen one or, as helper, a helper group + applied: Option, + /// The chosen group is still to be checked at the intake + pending: bool, + /// The team decided on the group: confirmed, put in or taken away + #[serde(with = "ms_opt")] + decided_at: Option>, + /// The seller can no longer change it (first item accepted, or the team decided) + locked: bool, +} + +async fn get_my_fee_group(ctx: &mut Ctx, args: EventArgs) -> AppResult> { + let Some(user) = ctx.user else { + return Ok(None); + }; + let event_id = args.event_id.0; + ctx.read(Topic::Event(event_id)); + ctx.read(Topic::User(user)); + let Some(event) = docs::event(ctx.conn(), event_id).await? else { + return Ok(None); + }; + if event.resolved_features().fee_groups.is_empty() + || !event_roles::has_role(ctx.conn(), event_id, user, Role::Seller).await? + { + return Ok(None); + } + let member = membership(ctx.conn(), &event, user).await?; + let fees = member.fees(&event); + let pending = member.pending(&event, &fees).is_some(); + let locked = member.decided_at.is_some() + || has_accepted_items(ctx.conn(), event_id, user).await? + || event.end_date < Utc::now(); + Ok(Some(MyFeeGroup { + applied: fees.group.map(|group| group.id), + chosen: member.stored, + pending, + decided_at: member.decided_at, + locked, + })) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ChooseArgs { + event_id: Id, + /// None: no group + group_id: Option, +} + +/// The seller chooses a self-declared group, or none, until the first item is accepted. +async fn choose_fee_group(ctx: &mut Ctx, args: ChooseArgs) -> AppResult<()> { + let user = ctx.require_user()?; + let event = event_of(ctx, args.event_id.0).await?; + if !event_roles::has_role(ctx.conn(), event.id, user, Role::Seller).await? { + return Err(AppError::bad_request("seller.notParticipant")); + } + if event.end_date < Utc::now() { + return Err(AppError::bad_request("join.past")); + } + check_choice(&event, args.group_id.as_deref())?; + let row = docs::event_seller(ctx.conn(), event.id, user).await?; + if row + .as_ref() + .is_some_and(|row| row.fee_group_decided_at.is_some()) + { + return Err(AppError::bad_request("feeGroup.decided")); + } + if has_accepted_items(ctx.conn(), event.id, user).await? { + return Err(AppError::bad_request("feeGroup.locked")); + } + sqlx::query("UPDATE event_sellers SET fee_group_id = $3 WHERE event_id = $1 AND user_id = $2") + .bind(event.id) + .bind(user) + .bind(args.group_id) + .execute(ctx.conn()) + .await?; + ctx.touch(Topic::Event(event.id)); + ctx.touch(Topic::User(user)); + Ok(()) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SellerArgs { + event_id: Id, + seller_id: Id, +} + +/// Stores the team's decision on the seller's group and books their sales anew. +async fn decide( + ctx: &mut Ctx, + event: &Event, + seller: Uuid, + by: Uuid, + group: Option>, +) -> AppResult<()> { + assert_vendor_not_paid_out(ctx.conn(), event.id, seller).await?; + if docs::event_seller(ctx.conn(), event.id, seller) + .await? + .is_none() + { + return Err(AppError::bad_request("seller.notSeller")); + } + sales::lock_seller_fees(ctx.conn(), event.id, seller).await?; + sqlx::query( + "UPDATE event_sellers SET fee_group_id = CASE WHEN $3 THEN $4 ELSE fee_group_id END, + fee_group_decided_at = now(), fee_group_decided_by = $5 + WHERE event_id = $1 AND user_id = $2", + ) + .bind(event.id) + .bind(seller) + .bind(group.is_some()) + .bind(group.flatten()) + .bind(by) + .execute(ctx.conn()) + .await?; + reprice_seller_sales(ctx.conn(), event, seller).await?; + ctx.touch(Topic::Event(event.id)); + ctx.touch(Topic::User(seller)); + Ok(()) +} + +/// The team saw the proof (e.g. the member card) at the intake. Helpers with the intake +/// right may do it. +async fn confirm_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { + let (event_id, seller) = (args.event_id.0, args.seller_id.0); + let by = require_permission(ctx, event_id, Permission::Intake).await?; + let event = event_of(ctx, event_id).await?; + let stored = docs::event_seller(ctx.conn(), event_id, seller) + .await? + .and_then(|row| row.fee_group_id); + let exists = event + .resolved_features() + .fee_groups + .iter() + .any(|group| Some(&group.id) == stored.as_ref()); + if !exists { + return Err(AppError::bad_request("feeGroup.none")); + } + decide(ctx, &event, seller, by, None).await +} + +/// The proof is missing: the seller pays the bazaar's fees (or a helper group's). +async fn remove_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { + let (event_id, seller) = (args.event_id.0, args.seller_id.0); + let by = require_permission(ctx, event_id, Permission::Intake).await?; + let event = event_of(ctx, event_id).await?; + decide(ctx, &event, seller, by, Some(None)).await +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AssignArgs { + event_id: Id, + seller_id: Id, + /// None: no group + group_id: Option, +} + +/// The organizer puts a seller in a group by hand, e.g. a helper without rights in the +/// helper group. Changes money, so organizers only. +async fn assign_fee_group(ctx: &mut Ctx, args: AssignArgs) -> AppResult<()> { + let (event_id, seller) = (args.event_id.0, args.seller_id.0); + let by = ctx.require_user()?; + if !event_roles::has_role_or_admin(ctx.conn(), event_id, by, Role::Organizer).await? { + return Err(AppError::forbidden("feeGroup.organizerOnly")); + } + let event = event_of(ctx, event_id).await?; + if let Some(group) = &args.group_id + && !event + .resolved_features() + .fee_groups + .iter() + .any(|g| &g.id == group) + { + return Err(AppError::bad_request("feeGroup.unknown")); + } + decide(ctx, &event, seller, by, Some(args.group_id)).await +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn event(features: serde_json::Value) -> Event { + let mut event: Event = crate::modules::features::tests_event(features); + event.commission = Decimal::new(10, 0); + event + } + + fn groups() -> serde_json::Value { + json!({ + "intakeFee": 1.0, + "maxFeesPerSeller": 20.0, + "maxItemsPerSeller": 20, + "feeGroups": [ + { "id": "members", "label": "Mitglieder", "commission": 5, + "assignment": "selfDeclared", "proofHint": "Ausweis zeigen" }, + { "id": "helpers", "label": "Helfer", "commission": 0, "intakeFee": 0.5, + "maxItemsPerSeller": 40, "assignment": "helpers" } + ] + }) + } + + #[test] + fn sellers_without_a_group_pay_the_bazaars_fees() { + let event = event(groups()); + let fees = fees_for(&event, None, false); + assert_eq!(fees.group, None); + assert_eq!(fees.commission, Decimal::new(10, 0)); + assert_eq!(fees.intake_fee, Some(Decimal::new(100, 2))); + // A group that is gone counts as none + assert_eq!(fees_for(&event, Some("gone"), false).group, None); + } + + #[test] + fn a_group_has_its_own_fees_and_falls_back_to_the_bazaars_cap_and_limit() { + let event = event(groups()); + let members = fees_for(&event, Some("members"), false); + assert_eq!(members.commission, Decimal::new(5, 0)); + // No intake fee in the group: none + assert_eq!(members.intake_fee, None); + assert_eq!(members.max_fees_per_seller, Some(Decimal::new(2000, 2))); + assert_eq!(members.max_items_per_seller, Some(20)); + let helpers = fees_for(&event, None, true); + assert_eq!(helpers.group.map(|g| g.id), Some("helpers".to_owned())); + assert_eq!(helpers.max_items_per_seller, Some(40)); + } + + #[test] + fn who_is_in_two_groups_gets_the_cheapest() { + let event = event(groups()); + let fees = fees_for(&event, Some("members"), true); + assert_eq!(fees.group.map(|g| g.id), Some("helpers".to_owned())); + } + + #[test] + fn only_an_unchecked_self_declaration_is_pending() { + let event = event(groups()); + let mut member = Membership { + stored: Some("members".to_owned()), + decided_at: None, + helper: false, + }; + let fees = member.fees(&event); + assert!(member.pending(&event, &fees).is_some()); + // As helper the helper group applies, nothing to check + member.helper = true; + let fees = member.fees(&event); + assert!(member.pending(&event, &fees).is_none()); + member.helper = false; + member.decided_at = Some(Utc::now()); + let fees = member.fees(&event); + assert!(member.pending(&event, &fees).is_none()); + } + + #[test] + fn commission_in_cents() { + let event = event(groups()); + let fees = fees_for(&event, Some("members"), false); + assert_eq!( + fees.commission_of(Decimal::new(1999, 2)), + Some(Decimal::new(100, 2)) + ); + } +} diff --git a/backend/src/modules/mod.rs b/backend/src/modules/mod.rs index 6ae460e5..a24c233e 100644 --- a/backend/src/modules/mod.rs +++ b/backend/src/modules/mod.rs @@ -17,6 +17,7 @@ pub mod event_seller; pub mod events; pub mod feature_flags; pub mod features; +pub mod fee_groups; pub mod instance; pub mod labels; pub mod messages; @@ -55,6 +56,7 @@ pub fn register_all() -> Registry { event_seller::register(&mut registry); events::register(&mut registry); feature_flags::register(&mut registry); + fee_groups::register(&mut registry); instance::register(&mut registry); labels::register(&mut registry); messages::register(&mut registry); diff --git a/backend/src/modules/purchases.rs b/backend/src/modules/purchases.rs index e76d3bb0..7d136d56 100644 --- a/backend/src/modules/purchases.rs +++ b/backend/src/modules/purchases.rs @@ -19,6 +19,7 @@ use super::event_roles::{ Permission, assert_vendor_not_paid_out, require_permission, require_team, }; use super::features::discounted_price; +use super::fee_groups::{self, FeeBook}; use super::instance::EMAIL_PATTERN; use super::notifications::{self, Area, Category, Content, T, format_euro}; use super::offers::{ @@ -229,13 +230,13 @@ async fn book( product, } = item; let total = price.total; - let commission = total - .checked_mul(event.commission) - .ok_or_else(|| AppError::bad_request("checkout.invalidPrice"))? - / Decimal::ONE_HUNDRED; - let mut commission = commission.cents(); + // The seller's fees: their group's or the bazaar's (#302) + let fees = fee_groups::seller_fees(ctx.conn(), &event, product.vendor_id).await?; + let mut commission = fees + .commission_of(total) + .ok_or_else(|| AppError::bad_request("checkout.invalidPrice"))?; // The seller pays the commission of a direct sale right away: only up to the fee cap - let cap = event.resolved_features().max_fees_per_seller; + let cap = fees.max_fees_per_seller; if direct && cap.is_some() { // Two desks selling for the same seller at once must not both take the rest sales::lock_seller_fees(ctx.conn(), event.id, product.vendor_id).await?; @@ -770,38 +771,56 @@ struct CheckoutItem { seller_id: Uuid, /// Direct sale with a fee cap: the commission the seller still pays at most (#301) fee_cap_left: Option, + /// The seller's commission in percent, when their fee group has its own (#302) + commission_percent: Option, } -/// Direct sale with a fee cap: what is left of the cap per seller, after the commissions -/// they paid at the desk. None for other events. -async fn fee_cap_left( - conn: &mut sqlx::PgConnection, - event: &Event, -) -> sqlx::Result)>> { - let features = event.resolved_features(); - let Some(cap) = features - .max_fees_per_seller - .filter(|_| features.direct_sale) - else { - return Ok(None); - }; - let paid: Vec<(Uuid, Decimal)> = sqlx::query_as( - "SELECT seller_id, sum(commission_amount) FROM purchases - WHERE event_id = $1 AND direct_sale GROUP BY seller_id", - ) - .bind(event.id) - .fetch_all(conn) - .await?; - let left = paid - .into_iter() - .map(|(seller, paid)| (seller, (cap - paid).max(Decimal::ZERO))) - .collect(); - Ok(Some((cap, left))) +/// What the desk needs of each seller's fees: the commission when it is not the bazaar's +/// (fee group, #302) and, at a direct sale with a fee cap, what is left of the cap after +/// the commissions they paid at the desk. +struct DeskFees { + book: FeeBook, + direct: bool, + paid: HashMap, + commission: Decimal, } -fn cap_left_of(caps: &Option<(Decimal, HashMap)>, seller: Uuid) -> Option { - caps.as_ref() - .map(|(cap, left)| left.get(&seller).copied().unwrap_or(*cap)) +impl DeskFees { + async fn load(conn: &mut sqlx::PgConnection, event: &Event) -> sqlx::Result { + let direct = event.resolved_features().direct_sale; + let book = FeeBook::load(&mut *conn, event).await?; + let paid: Vec<(Uuid, Decimal)> = if direct { + sqlx::query_as( + "SELECT seller_id, sum(commission_amount) FROM purchases + WHERE event_id = $1 AND direct_sale GROUP BY seller_id", + ) + .bind(event.id) + .fetch_all(conn) + .await? + } else { + Vec::new() + }; + Ok(Self { + book, + direct, + paid: paid.into_iter().collect(), + commission: event.commission, + }) + } + + fn cap_left(&self, seller: Uuid) -> Option { + let cap = self + .book + .get(seller) + .max_fees_per_seller + .filter(|_| self.direct)?; + let paid = self.paid.get(&seller).copied().unwrap_or_default(); + Some((cap - paid).max(Decimal::ZERO)) + } + + fn commission_percent(&self, seller: Uuid) -> Option { + Some(self.book.get(seller).commission).filter(|percent| *percent != self.commission) + } } fn nullable(value: &Option, serializer: S) -> Result { @@ -838,10 +857,8 @@ async fn get_checkout_item( .minimum_price .filter(|minimum| event.resolved_features().minimum_price && *minimum < list_price); let features = event.resolved_features(); - let fee_cap_left = match features - .max_fees_per_seller - .filter(|_| features.direct_sale) - { + let fees = fee_groups::seller_fees(ctx.conn(), &event, product.vendor_id).await?; + let fee_cap_left = match fees.max_fees_per_seller.filter(|_| features.direct_sale) { Some(cap) => { let paid = sales::direct_commission_paid(ctx.conn(), event.id, product.vendor_id).await?; @@ -849,6 +866,7 @@ async fn get_checkout_item( } None => None, }; + let commission_percent = Some(fees.commission).filter(|percent| *percent != event.commission); Ok(Some(CheckoutItem { event_product_id: relation.id, product_id: product.id, @@ -863,6 +881,7 @@ async fn get_checkout_item( internal_note: relation.internal_note, seller_id: product.vendor_id, fee_cap_left, + commission_percent, title: product.title, })) } @@ -923,7 +942,7 @@ async fn get_checkout_snapshot(ctx: &mut Ctx, args: EventIdArgs) -> AppResult AppResult AppResult { .await? .ok_or_else(|| AppError::not_found("notFound.product"))?; assert_vendor_not_paid_out(ctx.conn(), relation.event_id, product.vendor_id).await?; - if event.resolved_features().max_fees_per_seller.is_some() { + if fee_groups::seller_fees(ctx.conn(), &event, product.vendor_id) + .await? + .max_fees_per_seller + .is_some() + { sales::lock_seller_fees(ctx.conn(), event.id, product.vendor_id).await?; } let deleted: Option<(Option, bool)> = sqlx::query_as( @@ -1337,6 +1361,7 @@ struct SaleItem { sale: SaleInfo, } +#[skip_serializing_none] #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct SalesEvent { @@ -1347,7 +1372,10 @@ struct SalesEvent { start_date: DateTime, #[serde(with = "ms")] end_date: DateTime, + /// The seller's commission: their fee group's or the bazaar's commission_percent: Decimal, + /// The seller's fee group (#302) + fee_group: Option, } #[derive(Serialize)] @@ -1443,8 +1471,15 @@ async fn get_my_sales(ctx: &mut Ctx, _: NoArgs) -> AppResult> { } let revenue: Decimal = items.iter().map(|i| i.sale.total_amount).sum(); let commission: Decimal = items.iter().map(|i| i.sale.commission).sum(); + let fees = fee_groups::seller_fees(ctx.conn(), &event, user).await?; let fee_cap_credit = - sales::fee_cap_credit_of(&event, seller.as_ref(), commission, &intake_fee); + sales::fee_cap_credit_of(&fees, seller.as_ref(), commission, &intake_fee); + let paid = seller.as_ref().is_some_and(|s| s.payout_received); + let fee_group = if paid { + seller.as_ref().and_then(|s| s.fee_group_label.clone()) + } else { + fees.group.as_ref().map(|group| group.label.clone()) + }; let payout: Decimal = items.iter().map(|i| i.sale.payout).sum::() - intake_fee.total + fee_cap_credit; @@ -1454,7 +1489,8 @@ async fn get_my_sales(ctx: &mut Ctx, _: NoArgs) -> AppResult> { title: event.title.clone(), start_date: event.start_date, end_date: event.end_date, - commission_percent: event.commission, + commission_percent: fees.commission, + fee_group, }, paid: seller.as_ref().is_some_and(|s| s.payout_received), seller_number: seller.and_then(|s| s.number), diff --git a/backend/src/modules/sales.rs b/backend/src/modules/sales.rs index 76f7d86f..417a6bf7 100644 --- a/backend/src/modules/sales.rs +++ b/backend/src/modules/sales.rs @@ -10,6 +10,7 @@ use sqlx::PgConnection; use uuid::Uuid; use super::docs::{Event, EventSeller, Purchase}; +use super::fee_groups::{self, SellerFees}; use crate::error::{AppError, AppResult}; use crate::money::Cents; use crate::shape::ms; @@ -135,16 +136,17 @@ pub async fn accepted_items_by_seller( Ok(rows.into_iter().collect()) } -/// Intake fee of one seller, given the accepted items (see accepted_items_by_seller). +/// Intake fee of one seller, given the accepted items (see accepted_items_by_seller) and +/// the fees that apply to them (their group's or the bazaar's). pub fn intake_fee_of( - event: &Event, + fees: &SellerFees, seller: Option<&EventSeller>, accepted_items: i64, ) -> IntakeFee { if let Some(stored) = stored_fee(seller) { return stored; } - match event.resolved_features().intake_fee { + match fees.intake_fee { Some(per_item) if per_item > Decimal::ZERO => fee_for(per_item, accepted_items), _ => NO_FEE, } @@ -160,11 +162,8 @@ pub async fn intake_fee_for_seller( if let Some(stored) = stored_fee(seller) { return Ok(stored); } - let Some(per_item) = event - .resolved_features() - .intake_fee - .filter(|fee| *fee > Decimal::ZERO) - else { + let fees = fee_groups::seller_fees(&mut *conn, event, seller_id).await?; + let Some(per_item) = fees.intake_fee.filter(|fee| *fee > Decimal::ZERO) else { return Ok(NO_FEE); }; let items: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( @@ -194,7 +193,7 @@ pub fn capped_commission(commission: Decimal, paid: Decimal, cap: Option, commission: Decimal, intake_fee: &IntakeFee, @@ -202,10 +201,7 @@ pub fn fee_cap_credit_of( if let Some(seller) = seller.filter(|seller| seller.payout_received) { return seller.fee_cap_credit.unwrap_or(Decimal::ZERO); } - fee_cap_credit( - commission + intake_fee.total, - event.resolved_features().max_fees_per_seller, - ) + fee_cap_credit(commission + intake_fee.total, fees.max_fees_per_seller) } /// Commissions the seller paid at the desk for direct sales of the event so far. @@ -280,7 +276,8 @@ pub async fn recap_seller_direct_sales( event: &Event, seller_id: Uuid, ) -> sqlx::Result<()> { - let cap = event.resolved_features().max_fees_per_seller; + let fees = fee_groups::seller_fees(&mut *conn, event, seller_id).await?; + let cap = fees.max_fees_per_seller; if cap.is_none() { return Ok(()); } @@ -295,7 +292,7 @@ pub async fn recap_seller_direct_sales( let sales: Vec = rows .iter() .map(|(_, total, commission, payout)| DirectSale { - full: (total * event.commission / Decimal::ONE_HUNDRED).cents(), + full: fees.commission_of(*total).unwrap_or(*commission), commission: *commission, taken: commission + payout, }) diff --git a/backend/src/modules/seller_numbers.rs b/backend/src/modules/seller_numbers.rs index f15d149b..29f9083e 100644 --- a/backend/src/modules/seller_numbers.rs +++ b/backend/src/modules/seller_numbers.rs @@ -124,11 +124,14 @@ pub async fn assert_item_limit( vendor: Uuid, adding: i64, ) -> AppResult<()> { - let features = event.resolved_features(); if adding <= 0 { return Ok(()); } - if let Some(limit) = features.max_items_per_seller { + // A fee group may allow more items (#302) + let limit = super::fee_groups::seller_fees(ctx.conn(), event, vendor) + .await? + .max_items_per_seller; + if let Some(limit) = limit { let current: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( "SELECT count(*) FROM event_products ep JOIN products p ON p.id = ep.product_id WHERE ep.event_id = $1 AND p.vendor_id = $2 AND {TAKING_PLACE}" diff --git a/backend/src/modules/settlement.rs b/backend/src/modules/settlement.rs index dab9d8cc..12344a06 100644 --- a/backend/src/modules/settlement.rs +++ b/backend/src/modules/settlement.rs @@ -36,6 +36,8 @@ struct ExportEvent { commission: Decimal, /// Fee cap per seller (#301); with it the seller table has a column for it max_fees_per_seller: Option, + /// The bazaar has fee groups (#302); with it the seller table has a column for them + fee_groups: bool, } #[skip_serializing_none] @@ -76,6 +78,8 @@ struct ExportSeller { /// Negative when the seller owes the bazaar payout: Decimal, paid: bool, + /// The fee group applied (#302) + fee_group: Option, } #[derive(Serialize)] @@ -144,12 +148,14 @@ async fn get_export(ctx: &mut Ctx, args: EventArgs) -> AppResult { fee_cap_credit: vendor.fee_cap_credit, payout: vendor.payout, paid: vendor.paid, + fee_group: vendor.fee_group.map(|group| group.label), }) .collect(); sellers.sort_by_key(|seller| seller.seller_number.unwrap_or(i32::MAX)); Ok(Export { event: ExportEvent { max_fees_per_seller: event.resolved_features().max_fees_per_seller, + fee_groups: !event.resolved_features().fee_groups.is_empty(), location: event.place(), title: event.title, start_date: event.start_date, diff --git a/backend/tests/api/events.rs b/backend/tests/api/events.rs index b40fc772..80881515 100644 --- a/backend/tests/api/events.rs +++ b/backend/tests/api/events.rs @@ -41,7 +41,7 @@ async fn create(app: &TestApp, session: &str, args: Value) -> Uuid { } /// The arguments of editEvent from the current state of the event. -async fn edit_args(app: &TestApp, session: &str, id: Uuid) -> Value { +pub async fn edit_args(app: &TestApp, session: &str, id: Uuid) -> Value { let event = app .query("events.getEvent", json!({ "id": id }), Some(session)) .await diff --git a/backend/tests/api/fee_groups.rs b/backend/tests/api/fee_groups.rs new file mode 100644 index 00000000..422b403a --- /dev/null +++ b/backend/tests/api/fee_groups.rs @@ -0,0 +1,539 @@ +//! Fee groups (#302): own fees for club members, helpers and other groups. + +use crate::common; + +use axum::http::StatusCode; +use common::desk::Desk; +use common::fixtures::{self, EventSpec}; +use common::{Reply, TestApp}; +use serde_json::{Value, json}; +use sqlx::PgPool; +use uuid::Uuid; + +/// 10 % commission, 1 € per item; members 5 % without intake fee, helpers 0 % and up to +/// 40 items instead of 2. +fn groups() -> Value { + json!({ + "intakeFee": 1, + "maxItemsPerSeller": 2, + "photosOptional": true, + "feeGroups": [ + { "id": "members", "label": "Vereinsmitglieder", "commission": 5, + "assignment": "selfDeclared", "proofHint": "Ausweis zeigen" }, + { "id": "helpers", "label": "Helfer", "commission": 0, + "maxItemsPerSeller": 40, "assignment": "helpers" } + ] + }) +} + +struct Market { + app: TestApp, + db: PgPool, + event: Uuid, + organizer: String, +} + +impl Market { + async fn new(db: PgPool) -> Self { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let event = fixtures::event( + &db, + EventSpec { + start_hours: -1, + end_hours: 5, + commission: 10, + features: groups(), + ..EventSpec::new("Fahrradbörse", organizer) + }, + ) + .await; + Self { + organizer: fixtures::session(&db, organizer).await, + app, + db, + event, + } + } + + async fn join(&self, name: &str, group: Option<&str>) -> (Uuid, String) { + let user = fixtures::user(&self.db, name).await; + let session = fixtures::session(&self.db, user).await; + let joined = self + .app + .mutation( + "eventSeller.joinEvent", + json!({ "eventId": self.event, "feeGroupId": group }), + Some(&session), + ) + .await; + assert_eq!(joined.status, StatusCode::OK, "{}", joined.body); + (user, session) + } + + async fn announced(&self, seller: Uuid, title: &str, price: f64) -> (Uuid, Uuid) { + let product = fixtures::product(&self.db, seller, title, price).await; + let relation = fixtures::event_product(&self.db, self.event, product, "announced").await; + (product, relation) + } + + async fn accept(&self, relation: Uuid, session: &str) -> Reply { + self.app + .mutation( + "eventProducts.updateProductStatus", + json!({ "eventProductId": relation, "status": "available" }), + Some(session), + ) + .await + } + + async fn team(&self, name: &str, seller: Uuid, session: &str) -> Reply { + self.app + .mutation( + name, + json!({ "eventId": self.event, "sellerId": seller }), + Some(session), + ) + .await + } + + async fn vendor(&self, seller: Uuid) -> Value { + let vendors = self + .app + .query( + "eventRoles.getVendorsForEvent", + json!({ "eventId": self.event }), + Some(&self.organizer), + ) + .await; + assert_eq!(vendors.status, StatusCode::OK, "{}", vendors.body); + vendors.body["value"] + .as_array() + .unwrap() + .iter() + .find(|vendor| vendor["_id"] == json!(seller)) + .cloned() + .unwrap() + } + + async fn my_group(&self, session: &str) -> Value { + self.app + .query( + "feeGroups.getMyFeeGroup", + json!({ "eventId": self.event }), + Some(session), + ) + .await + .body["value"] + .clone() + } + + async fn sell(&self, relation: Uuid) { + let sold = self + .app + .mutation( + "purchases.sellProduct", + json!({ "eventProductId": relation }), + Some(&self.organizer), + ) + .await; + assert_eq!(sold.status, StatusCode::OK, "{}", sold.body); + } + + async fn commission(&self, product: Uuid) -> f64 { + sqlx::query_scalar("SELECT commission_amount::float8 FROM purchases WHERE product_id = $1") + .bind(product) + .fetch_one(&self.db) + .await + .unwrap() + } +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn a_self_declared_group_is_checked_before_the_first_item(db: PgPool) { + let m = Market::new(db.clone()).await; + let (seller, session) = m.join("Mitglied", Some("members")).await; + assert_eq!( + m.my_group(&session).await, + json!({ "chosen": "members", "applied": "members", "pending": true, "locked": false }) + ); + let (product, relation) = m.announced(seller, "Rennrad", 200.0).await; + + // The intake asks for the proof first, for one item and for all at once + let refused = m.accept(relation, &m.organizer).await; + assert_eq!( + refused.body["code"], "feeGroup.unconfirmed", + "{}", + refused.body + ); + let all = m + .app + .mutation( + "eventProducts.markAllVendorProductsAvailable", + json!({ "eventId": m.event, "vendorId": seller }), + Some(&m.organizer), + ) + .await; + assert_eq!(all.body["code"], "feeGroup.unconfirmed"); + let vendor = m.vendor(seller).await; + assert_eq!(vendor["feeGroup"]["label"], "Vereinsmitglieder"); + assert_eq!(vendor["feeGroup"]["pending"], true); + + // A helper with the intake right confirms + let helper = fixtures::user(&db, "Helferin").await; + fixtures::role(&db, m.event, helper, "seller").await; + fixtures::role(&db, m.event, helper, "coorganizer").await; + let helper_session = fixtures::session(&db, helper).await; + let confirmed = m + .team("feeGroups.confirmFeeGroup", seller, &helper_session) + .await; + assert_eq!(confirmed.status, StatusCode::OK, "{}", confirmed.body); + assert_eq!(m.vendor(seller).await["feeGroup"]["pending"], false); + let accepted = m.accept(relation, &helper_session).await; + assert_eq!(accepted.status, StatusCode::OK, "{}", accepted.body); + + // The seller can no longer change it + let changed = m + .app + .mutation( + "feeGroups.chooseFeeGroup", + json!({ "eventId": m.event, "groupId": null }), + Some(&session), + ) + .await; + assert_eq!(changed.body["code"], "feeGroup.decided"); + + // 5 % of 200 €, no intake fee + m.sell(relation).await; + assert_eq!(m.commission(product).await, 10.0); + let vendor = m.vendor(seller).await; + assert_eq!(vendor["intakeFee"]["total"], json!(0.0), "{vendor}"); + assert_eq!(vendor["payout"], json!(190.0)); + let sales = m + .app + .query("purchases.getMySales", json!({}), Some(&session)) + .await; + let event = &sales.body["value"][0]["event"]; + assert_eq!(event["commissionPercent"], json!(5.0), "{event}"); + assert_eq!(event["feeGroup"], "Vereinsmitglieder"); + + // The payout keeps the group + let paid = m + .app + .mutation( + "eventSeller.settleVendor", + json!({ "eventId": m.event, "vendorUserId": seller }), + Some(&m.organizer), + ) + .await; + assert_eq!(paid.status, StatusCode::OK, "{}", paid.body); + let label: Option = sqlx::query_scalar( + "SELECT fee_group_label FROM event_sellers WHERE event_id = $1 AND user_id = $2", + ) + .bind(m.event) + .bind(seller) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(label.as_deref(), Some("Vereinsmitglieder")); + let export = m + .app + .query( + "settlement.getExport", + json!({ "eventId": m.event }), + Some(&m.organizer), + ) + .await; + assert_eq!(export.body["value"]["event"]["feeGroups"], true); + assert_eq!( + export.body["value"]["sellers"][0]["feeGroup"], + "Vereinsmitglieder" + ); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn without_proof_the_bazaars_fees_apply(db: PgPool) { + let m = Market::new(db.clone()).await; + let (seller, session) = m.join("Kein Mitglied", Some("members")).await; + let (product, relation) = m.announced(seller, "Kinderrad", 50.0).await; + // Only the event team decides + let by_seller = m.team("feeGroups.removeFeeGroup", seller, &session).await; + assert_eq!(by_seller.status, StatusCode::FORBIDDEN); + let removed = m + .team("feeGroups.removeFeeGroup", seller, &m.organizer) + .await; + assert_eq!(removed.status, StatusCode::OK, "{}", removed.body); + assert_eq!(m.vendor(seller).await["feeGroup"], Value::Null); + let group = m.my_group(&session).await; + assert_eq!(group["chosen"], Value::Null, "{group}"); + assert_eq!(group["locked"], true); + // Choosing again is not possible after the team decided + let again = m + .app + .mutation( + "feeGroups.chooseFeeGroup", + json!({ "eventId": m.event, "groupId": "members" }), + Some(&session), + ) + .await; + assert_eq!(again.body["code"], "feeGroup.decided"); + assert_eq!( + m.accept(relation, &m.organizer).await.status, + StatusCode::OK + ); + m.sell(relation).await; + assert_eq!(m.commission(product).await, 5.0); + assert_eq!(m.vendor(seller).await["intakeFee"]["total"], json!(1.0)); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn sellers_choose_only_self_declared_groups_until_the_intake(db: PgPool) { + let m = Market::new(db.clone()).await; + let user = fixtures::user(&db, "Schlau").await; + let session = fixtures::session(&db, user).await; + let helpers = m + .app + .mutation( + "eventSeller.joinEvent", + json!({ "eventId": m.event, "feeGroupId": "helpers" }), + Some(&session), + ) + .await; + assert_eq!(helpers.body["code"], "feeGroup.unknown"); + + let (seller, session) = m.join("Später", None).await; + let choose = |group: Value| { + let (app, session) = (&m.app, session.clone()); + async move { + app.mutation( + "feeGroups.chooseFeeGroup", + json!({ "eventId": m.event, "groupId": group }), + Some(&session), + ) + .await + } + }; + assert_eq!(choose(json!("members")).await.status, StatusCode::OK); + assert_eq!(m.my_group(&session).await["pending"], true); + assert_eq!(choose(Value::Null).await.status, StatusCode::OK); + assert_eq!(m.my_group(&session).await["chosen"], Value::Null); + // Without a group nothing stops the intake; afterwards the choice is fixed + let (_, relation) = m.announced(seller, "Laufrad", 20.0).await; + assert_eq!( + m.accept(relation, &m.organizer).await.status, + StatusCode::OK + ); + assert_eq!( + choose(json!("members")).await.body["code"], + "feeGroup.locked" + ); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn helpers_are_in_their_group_while_they_have_the_role(db: PgPool) { + let desk = Desk::new(db.clone(), groups()).await; + fixtures::event_seller(&db, desk.event, desk.seller, 1, false).await; + let (product, relation) = desk.item("Mountainbike", 300.0).await; + desk.sell(json!({ "eventProductId": relation })).await; + assert_eq!(desk.purchase(product).await.unwrap().1, 30.0); + + // Made a helper after the sale: the sale is booked anew at 0 % + let made = desk + .app + .mutation( + "eventRoles.addCoOrganizerForEvent", + json!({ "eventId": desk.event, "userId": desk.seller, "permissions": [] }), + Some(&desk.team), + ) + .await; + assert_eq!(made.status, StatusCode::OK, "{}", made.body); + assert_eq!(desk.purchase(product).await.unwrap().1, 0.0); + let vendors = desk + .app + .query( + "eventRoles.getVendorsForEvent", + json!({ "eventId": desk.event }), + Some(&desk.team), + ) + .await; + let vendor = &vendors.body["value"][0]; + assert_eq!(vendor["feeGroup"]["label"], "Helfer", "{vendor}"); + assert_eq!(vendor["feeGroup"]["byRole"], true); + // No commission, and the helper group has no intake fee + assert_eq!(vendor["payout"], json!(300.0)); + + // Without the role again: the bazaar's fees + let removed = desk + .app + .mutation( + "eventRoles.removeCoOrganizerForEvent", + json!({ "eventId": desk.event, "userId": desk.seller }), + Some(&desk.team), + ) + .await; + assert_eq!(removed.status, StatusCode::OK, "{}", removed.body); + assert_eq!(desk.purchase(product).await.unwrap().1, 30.0); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_organizer_puts_sellers_in_a_group_by_hand(db: PgPool) { + let m = Market::new(db.clone()).await; + let (seller, session) = m.join("Kuchenbäckerin", None).await; + let assign = |group: Value, session: String| { + let app = &m.app; + async move { + app.mutation( + "feeGroups.assignFeeGroup", + json!({ "eventId": m.event, "sellerId": seller, "groupId": group }), + Some(&session), + ) + .await + } + }; + // Helpers may confirm at the intake, but not hand out groups + let helper = fixtures::user(&db, "Helfer").await; + fixtures::role(&db, m.event, helper, "seller").await; + fixtures::role(&db, m.event, helper, "coorganizer").await; + let helper = fixtures::session(&db, helper).await; + assert_eq!( + assign(json!("helpers"), helper).await.body["code"], + "feeGroup.organizerOnly" + ); + assert_eq!( + assign(json!("unknown"), m.organizer.clone()).await.body["code"], + "feeGroup.unknown" + ); + let assigned = assign(json!("helpers"), m.organizer.clone()).await; + assert_eq!(assigned.status, StatusCode::OK, "{}", assigned.body); + let group = &m.vendor(seller).await["feeGroup"]; + assert_eq!(group["label"], "Helfer", "{group}"); + assert_eq!(group["byRole"], false); + assert_eq!(group["pending"], false); + assert_eq!(m.my_group(&session).await["applied"], "helpers"); + + // The group's item limit: 40 instead of 2 + for n in 0..3 { + let product = fixtures::product(&db, seller, &format!("Rad {n}"), 10.0).await; + let added = m + .app + .mutation( + "eventProducts.addProductToEvent", + json!({ "eventId": m.event, "productId": product }), + Some(&session), + ) + .await; + assert_eq!(added.status, StatusCode::OK, "{}", added.body); + } +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn groups_are_checked_when_saved(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let session = fixtures::session(&db, organizer).await; + let id = fixtures::event(&db, EventSpec::new("Basar", organizer)).await; + let args = crate::events::edit_args(&app, &session, id).await; + let save = |groups: Value| { + let mut args = args.clone(); + args["features"] = json!({ "feeGroups": groups }); + let (app, session) = (&app, session.clone()); + async move { + app.mutation("events.editEvent", args, Some(&session)) + .await + .body + } + }; + let group = |label: &str, commission: f64| { + json!({ "id": label.trim().to_lowercase().replace(' ', "-") + "x", "label": label, "commission": commission, + "assignment": "selfDeclared" }) + }; + assert_eq!( + save(json!([group(" ", 5.0)])).await["code"], + "event.feeGroupLabel" + ); + assert_eq!( + save(json!([group("Mitglieder", 120.0)])).await["code"], + "event.feeGroupCommission" + ); + let mut twice = group("mitglieder", 5.0); + twice["id"] = json!("other"); + assert_eq!( + save(json!([group("Mitglieder", 5.0), twice])).await["code"], + "event.feeGroupLabelTwice" + ); + let mut fine = group("Mitglieder", 4.999); + fine["proofHint"] = json!(" Ausweis zeigen "); + fine["intakeFee"] = json!(0); + assert_eq!(save(json!([fine])).await["value"], Value::Null); + let event = app + .query("events.getEvent", json!({ "id": id }), Some(&session)) + .await + .body["value"] + .clone(); + assert_eq!( + event["features"]["feeGroups"], + json!([{ "id": "mitgliederx", "label": "Mitglieder", "commission": 5.0, + "assignment": "selfDeclared", "proofHint": "Ausweis zeigen" }]) + ); + // An older app leaves them out: they stay + let mut older = args.clone(); + older["features"] = json!({}); + let kept = app + .mutation("events.editEvent", older, Some(&session)) + .await; + assert_eq!(kept.body["value"], Value::Null, "{}", kept.body); + let event = app + .query("events.getEvent", json!({ "id": id }), Some(&session)) + .await + .body["value"] + .clone(); + assert_eq!(event["features"]["feeGroups"][0]["id"], "mitgliederx"); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn after_the_first_seller_groups_only_get_cheaper(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let session = fixtures::session(&db, organizer).await; + let members = |commission: f64| { + json!({ "id": "members", "label": "Mitglieder", "commission": commission, + "assignment": "selfDeclared" }) + }; + let id = fixtures::event( + &db, + EventSpec { + features: json!({ "feeGroups": [members(5.0)] }), + ..EventSpec::new("Basar", organizer) + }, + ) + .await; + fixtures::role(&db, id, fixtures::user(&db, "Seller").await, "seller").await; + let args = crate::events::edit_args(&app, &session, id).await; + let save = |groups: Value| { + let mut args = args.clone(); + args["features"] = json!({ "feeGroups": groups }); + let (app, session) = (&app, session.clone()); + async move { + app.mutation("events.editEvent", args, Some(&session)) + .await + .body + } + }; + assert_eq!( + save(json!([members(6.0)])).await["code"], + "event.feeGroupsOnlyLower" + ); + assert_eq!(save(json!([])).await["code"], "event.feeGroupsOnlyLower"); + let mut helpers = members(5.0); + helpers["assignment"] = json!("helpers"); + assert_eq!( + save(json!([helpers])).await["code"], + "event.feeGroupsOnlyLower" + ); + // Cheaper, renamed and a new group are fine + let mut cheaper = members(3.0); + cheaper["label"] = json!("Vereinsmitglieder"); + let new = json!({ "id": "kids", "label": "Schüler", "commission": 0, + "assignment": "selfDeclared" }); + assert_eq!(save(json!([cheaper, new])).await["value"], Value::Null); +} diff --git a/backend/tests/api/main.rs b/backend/tests/api/main.rs index 8d654612..12f2c0a8 100644 --- a/backend/tests/api/main.rs +++ b/backend/tests/api/main.rs @@ -14,6 +14,7 @@ mod event_invitations; mod event_roles; mod event_seller; mod events; +mod fee_groups; mod helper_permissions; mod import; mod infrastructure; From 252a9d09808e36b6b22b50c665414dd8b1082757 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 22:05:04 +0100 Subject: [PATCH 02/10] feat(fees): fee groups in the editor, conditions, registration, intake and seller list (#302) Co-Authored-By: Claude Opus 5.5 --- .../events/EventRegistrationDialog.tsx | 11 + src/components/events/FeeGroups.tsx | 194 ++++++++++ src/components/events/SellerConditions.tsx | 9 + src/components/sellers/FeeGroupBadge.tsx | 120 ++++++ src/components/sellers/FeeGroupCheck.tsx | 85 +++++ src/lib/api/types.ts | 78 ++++ src/lib/checkout.test.ts | 6 + src/lib/checkout.ts | 6 +- src/lib/sellerFees.test.ts | 46 ++- src/lib/sellerFees.ts | 50 +++ src/lib/settlementExport.test.ts | 12 + src/lib/settlementExport.ts | 42 +- src/locales/de/errors.json | 16 +- src/locales/de/events.json | 25 +- src/locales/de/organizer.json | 85 ++++- src/locales/de/sales.json | 3 +- src/locales/en/errors.json | 16 +- src/locales/en/events.json | 25 +- src/locales/en/organizer.json | 85 ++++- src/locales/en/sales.json | 3 +- src/pages/organizer/events/EditEventForm.tsx | 125 +++++- .../events/components/EditEventFeeGroups.tsx | 358 ++++++++++++++++++ .../events/components/EventPageSidebar.tsx | 12 +- .../components/wizard/WizardPreviews.tsx | 16 + .../components/wizard/WizardSummary.tsx | 10 + .../events/dashboard/CheckoutPage.tsx | 17 +- .../dashboard/ProductManagementPage.tsx | 34 +- .../events/dashboard/SellerManagementPage.tsx | 108 ++++-- .../components/EventSettingsSummary.tsx | 9 + .../components/InventoryConfirmDialog.tsx | 5 + .../dashboard/components/VendorSettlement.tsx | 7 +- src/pages/public/events/PublicEventPage.tsx | 6 +- src/pages/seller/sales/MySalesPage.tsx | 7 +- src/shared/eventFeatures.ts | 6 + src/shared/feeGroups.test.ts | 54 +++ src/shared/feeGroups.ts | 96 +++++ src/tests/auth/fee-groups.spec.ts | 86 +++++ src/tests/helpers/profile.ts | 4 +- 38 files changed, 1807 insertions(+), 70 deletions(-) create mode 100644 src/components/events/FeeGroups.tsx create mode 100644 src/components/sellers/FeeGroupBadge.tsx create mode 100644 src/components/sellers/FeeGroupCheck.tsx create mode 100644 src/pages/organizer/events/components/EditEventFeeGroups.tsx create mode 100644 src/shared/feeGroups.test.ts create mode 100644 src/shared/feeGroups.ts create mode 100644 src/tests/auth/fee-groups.spec.ts diff --git a/src/components/events/EventRegistrationDialog.tsx b/src/components/events/EventRegistrationDialog.tsx index edcedc45..99e5f541 100644 --- a/src/components/events/EventRegistrationDialog.tsx +++ b/src/components/events/EventRegistrationDialog.tsx @@ -21,6 +21,7 @@ import { useFeatureFlags } from '../../hooks/useFeatureFlags'; import { getUserFacingErrorMessage } from '../../lib/errors'; import { ValidateProfileInformation } from './ValidateProfileInformation'; import { SellerConditions } from './SellerConditions'; +import { FeeGroupChoice } from './FeeGroups'; import type { SellerConditionsEvent } from '../../lib/sellerFees'; import { useTranslation } from 'react-i18next'; @@ -56,6 +57,7 @@ export function EventRegistrationDialog({ const { t } = useTranslation('events'); const askPrivateSeller = resolveEventFeatures(conditions).privateSellersOnly; const [privateSeller, setPrivateSeller] = useState(false); + const [feeGroup, setFeeGroup] = useState(null); const [accessCode, setAccessCode] = useState(''); const [accessCodeValid, setAccessCodeValid] = useState(null); const [isJoining, setIsJoining] = useState(false); @@ -112,6 +114,7 @@ export function EventRegistrationDialog({ accessCode: needsCode ? accessCode : undefined, invitation, ...(askPrivateSeller ? { privateSeller } : {}), + ...(feeGroup ? { feeGroupId: feeGroup } : {}), }); toast.success(t('join.joined', { event: eventTitle })); onSuccess(); @@ -245,6 +248,14 @@ export function EventRegistrationDialog({ className="rounded-lg border bg-muted/30 p-4" /> )} + {(!needsCode || accessCodeValid) && !hasMissingProfileData && ( + + )} {(!needsCode || accessCodeValid) && !hasMissingProfileData && askPrivateSeller && (
+

{t('conditions.groupsTitle')}

+
    + {groups.map(({ group, fees, how }) => ( +
  • + + + {group.label}: {fees} + {how} + +
  • + ))} +
+
+ ); +} + +/** The groups a seller may say they belong to; `null`: none, the bazaar's fees. */ +export function FeeGroupChoice({ + event, + value, + onChange, + disabled, +}: { + event: SellerConditionsEvent; + value: string | null; + onChange: (value: string | null) => void; + disabled?: boolean; +}) { + const { t } = useTranslation('events'); + const choosable = describeFeeGroups(event).filter( + ({ group }) => group.assignment === 'selfDeclared' + ); + if (choosable.length === 0) return null; + const options = [ + { id: 'none', label: t('conditions.choiceNone'), detail: undefined }, + ...choosable.map(({ group, fees, how }) => ({ + id: group.id, + label: group.label, + detail: `${fees} · ${how}`, + })), + ]; + return ( +
+ {t('conditions.choiceTitle')} + onChange(next === 'none' ? null : next)} + disabled={disabled} + className="gap-2" + > + {options.map((option) => ( + + ))} + +

{t('conditions.choiceHint')}

+
+ ); +} + +/** + * A registered seller's own group in the conditions: which applies, whether the team + * still checks it, and changing it until the first item is accepted. + */ +export function MyFeeGroup({ + eventId, + event, +}: { + eventId: Id<'events'>; + event: SellerConditionsEvent; +}) { + const { t } = useTranslation('events'); + const groups = event.features?.feeGroups ?? []; + const mine = useQuery(api.feeGroups.getMyFeeGroup, groups.length > 0 ? { eventId } : 'skip'); + const choose = useMutation(api.feeGroups.chooseFeeGroup); + const [open, setOpen] = useState(false); + const [choice, setChoice] = useState(null); + const [saving, setSaving] = useState(false); + if (!mine) return null; + const applied = groups.find((group) => group.id === mine.applied); + const selfDeclared = groups.some((group) => group.assignment === 'selfDeclared'); + const Icon = mine.pending ? Clock : applied ? BadgeCheck : Users; + + const save = async () => { + setSaving(true); + try { + await choose({ eventId, groupId: choice }); + toast.success(t('conditions.myGroupSaved')); + setOpen(false); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } finally { + setSaving(false); + } + }; + + return ( +
+ +
+

+ {applied + ? t('conditions.myGroup', { group: applied.label }) + : t('conditions.myGroupNone')} +

+ {applied && ( +

+ {mine.pending ? t('conditions.myGroupPending') : t('conditions.myGroupConfirmed')} +

+ )} + {mine.locked && selfDeclared && ( +

{t('conditions.myGroupLocked')}

+ )} +
+ {!mine.locked && selfDeclared && ( + + )} + + + + {t('conditions.choiceDialogTitle')} + {t('conditions.choiceTitle')} + + +
+ + +
+
+
+
+ ); +} diff --git a/src/components/events/SellerConditions.tsx b/src/components/events/SellerConditions.tsx index ea5dc325..7347e0e4 100644 --- a/src/components/events/SellerConditions.tsx +++ b/src/components/events/SellerConditions.tsx @@ -1,6 +1,7 @@ import { Check, ClipboardList, Coins, X, type LucideIcon } from 'lucide-react'; import type { ReactNode } from 'react'; import { + describeFeeGroups, describeSellerFees, describeSellerRules, describeSellerSchedule, @@ -11,6 +12,8 @@ import { resolveEventFeatures } from '../../shared/eventFeatures'; import { useCategoryFieldDefinitions } from '../../hooks/useCategoryFields'; import { cn, formatPriceDE } from '../../lib/utils'; import { useTranslation } from 'react-i18next'; +import type { Id } from '../../lib/api/types'; +import { FeeGroupList, MyFeeGroup } from './FeeGroups'; /** * What sellers agree to at a bazaar: fees with a worked example, item limit, price @@ -23,11 +26,14 @@ export function SellerConditions({ className, id, compact = false, + eventId, }: { event: SellerConditionsEvent; className?: string; id?: string; compact?: boolean; + /** With it, a registered seller sees their fee group there (#302) */ + eventId?: Id<'events'>; }) { const { t } = useTranslation('events'); const { intakeFee, maxFeesPerSeller } = resolveEventFeatures(event); @@ -41,6 +47,7 @@ export function SellerConditions({ (rule) => !compact || rule.allowed ); const schedule = describeSellerSchedule(event); + const groups = describeFeeGroups(event); return (
@@ -50,6 +57,7 @@ export function SellerConditions({
+ {eventId && } {lines.length === 0 ? (
    @@ -61,6 +69,7 @@ export function SellerConditions({ ))}
)} + {example && !compact && (

{t('conditions.example')}

diff --git a/src/components/sellers/FeeGroupBadge.tsx b/src/components/sellers/FeeGroupBadge.tsx new file mode 100644 index 00000000..c6564016 --- /dev/null +++ b/src/components/sellers/FeeGroupBadge.tsx @@ -0,0 +1,120 @@ +import { useState } from 'react'; +import { BadgePercent } from 'lucide-react'; +import { toast } from 'sonner'; +import { useTranslation } from 'react-i18next'; +import type { Id, VendorWithCalculations } from '../../lib/api/types'; +import type { FeeGroup } from '../../shared/feeGroups'; +import { api } from '../../lib/api/functions'; +import { useMutation } from '../../lib/api/react'; +import { getUserFacingErrorMessage } from '../../lib/errors'; +import { cn } from '../../lib/utils'; +import { Button } from '../ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuLabel, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '../ui/dropdown-menu'; + +/** The seller's fee group next to their name; amber while the intake still checks it. */ +export function FeeGroupBadge({ group }: { group: VendorWithCalculations['feeGroup'] }) { + const { t } = useTranslation('organizer'); + if (!group) return null; + return ( + + + {group.label} + {group.pending && · {t('sellerFeeGroup.pending')}} + + ); +} + +/** + * The organizer puts a seller in a fee group by hand, e.g. a helper without rights in + * the helper group, or takes them out. Helper groups apply by role anyway. + */ +export function FeeGroupMenu({ + eventId, + vendor, + groups, + iconOnly, +}: { + eventId: Id<'events'>; + vendor: VendorWithCalculations; + groups: FeeGroup[]; + iconOnly?: boolean; +}) { + const { t } = useTranslation('organizer'); + const assign = useMutation(api.feeGroups.assignFeeGroup); + const [busy, setBusy] = useState(false); + if (groups.length === 0 || vendor.paid) return null; + const current = vendor.feeGroup?.byRole + ? (vendor.feeGroup.chosen ?? 'none') + : (vendor.feeGroup?.id ?? 'none'); + const label = t('sellerFeeGroup.assign'); + + const choose = async (value: string) => { + if (value === current) return; + setBusy(true); + try { + await assign({ eventId, sellerId: vendor._id, groupId: value === 'none' ? null : value }); + const group = groups.find((candidate) => candidate.id === value); + toast.success( + group + ? t('sellerFeeGroup.assigned', { name: vendor.name, group: group.label }) + : t('sellerFeeGroup.unassigned', { name: vendor.name }) + ); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } finally { + setBusy(false); + } + }; + + return ( + + + + + e.stopPropagation()}> + {t('sellerFeeGroup.title')} + + void choose(value)}> + {t('sellerFeeGroup.none')} + {groups.map((group) => ( + + {group.label} + + ))} + + {vendor.feeGroup?.byRole && ( +

+ {t('sellerFeeGroup.byRole', { group: vendor.feeGroup.label })} +

+ )} +
+
+ ); +} diff --git a/src/components/sellers/FeeGroupCheck.tsx b/src/components/sellers/FeeGroupCheck.tsx new file mode 100644 index 00000000..eaf6df65 --- /dev/null +++ b/src/components/sellers/FeeGroupCheck.tsx @@ -0,0 +1,85 @@ +import { useState } from 'react'; +import { BadgePercent, Check, X } from 'lucide-react'; +import { toast } from 'sonner'; +import { useTranslation } from 'react-i18next'; +import type { Id, VendorWithCalculations } from '../../lib/api/types'; +import type { FeeGroup } from '../../shared/feeGroups'; +import { api } from '../../lib/api/functions'; +import { useMutation } from '../../lib/api/react'; +import { getUserFacingErrorMessage } from '../../lib/errors'; +import { Button } from '../ui/button'; + +/** + * At the intake: the seller says they belong to a fee group (#302). The team checks the + * proof and confirms or removes the group; until then no item of the seller is accepted. + */ +export function FeeGroupCheck({ + eventId, + seller, + groups, +}: { + eventId: Id<'events'>; + seller: VendorWithCalculations; + groups: FeeGroup[]; +}) { + const { t } = useTranslation('organizer'); + const confirm = useMutation(api.feeGroups.confirmFeeGroup); + const remove = useMutation(api.feeGroups.removeFeeGroup); + const [busy, setBusy] = useState<'confirm' | 'remove' | null>(null); + const pending = seller.feeGroup?.pending ? seller.feeGroup : undefined; + if (!pending) return null; + const group = groups.find((candidate) => candidate.id === pending.id); + + const run = async (action: 'confirm' | 'remove') => { + setBusy(action); + try { + await (action === 'confirm' ? confirm : remove)({ eventId, sellerId: seller._id }); + toast.success( + t(action === 'confirm' ? 'feeGroupCheck.confirmed' : 'feeGroupCheck.removed', { + group: pending.label, + }) + ); + } catch (error) { + toast.error(getUserFacingErrorMessage(error)); + } finally { + setBusy(null); + } + }; + + return ( +
+
+ + {t('feeGroupCheck.title', { group: pending.label })} +
+

+ {group?.proofHint + ? t('feeGroupCheck.textWithProof', { proof: group.proofHint }) + : t('feeGroupCheck.text')} +

+
+ + +
+
+ ); +} diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index d74acec1..c3f86c7b 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -7,6 +7,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import type { CategoryField, DescribedAttribute } from '../../shared/categoryFields'; +import type { FeeGroup } from '../../shared/feeGroups'; import type { EventProductStatus, EventServices, HelperPermission } from '../../shared/constants'; export type TableName = @@ -118,6 +119,7 @@ export interface Docs { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -392,6 +394,7 @@ export type EventFeatures = { labelMark: 'universal' | 'none'; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly: boolean; fixedSellerData: boolean; directSale: boolean; @@ -469,6 +472,8 @@ export type SettlementExport = { commission: number; /** Fee cap per seller; with it the seller table has its column */ maxFeesPerSeller?: number | undefined; + /** The bazaar has fee groups; with it the seller table has a column for them */ + feeGroups?: boolean | undefined; }; sales: SettlementSale[]; sellers: SettlementSeller[]; @@ -504,6 +509,8 @@ export type SettlementSeller = { /** Negative when the seller owes the bazaar */ payout: number; paid: boolean; + /** The fee group applied (#302) */ + feeGroup?: string | undefined; }; export type SaleInfo = { @@ -591,6 +598,33 @@ export type VendorWithCalculations = { detailsRecorded?: boolean | undefined; /** The organizer took the seller out of the bazaar */ excluded?: Exclusion | undefined; + /** The fee group whose fees apply (#302) */ + feeGroup?: VendorFeeGroup | undefined; +}; + +/** A seller's fee group as the team sees it (#302) */ +export type VendorFeeGroup = { + /** Missing once paid out: then the group as settled */ + id?: string | undefined; + label: string; + /** Self-declared and not checked yet: the intake confirms or takes it away first */ + pending: boolean; + /** By the helper role, not chosen or put in */ + byRole: boolean; + /** The group the seller chose or was put in, when another one applies */ + chosen?: string | undefined; +}; + +/** The signed-in seller's fee group at a bazaar (#302) */ +export type MyFeeGroup = { + chosen?: string | undefined; + /** The group whose fees apply */ + applied?: string | undefined; + /** Still to be checked at the intake */ + pending: boolean; + decidedAt?: number | undefined; + /** The seller can no longer change it */ + locked: boolean; }; /** The organizer took a seller out of the bazaar (#252) */ @@ -1078,6 +1112,8 @@ export interface Api { accessCode?: string | undefined; privateSeller?: boolean | undefined; invitation?: string | undefined; + /** A self-declared fee group, checked at the intake (#302) */ + feeGroupId?: string | undefined; eventId: Id<'events'>; }, Id<'eventSeller'> @@ -1114,6 +1150,33 @@ export interface Api { null >; }; + feeGroups: { + getMyFeeGroup: FunctionReference<'query', { eventId: Id<'events'> }, MyFeeGroup | null>; + /** The seller chooses a self-declared group, or none, until the first item is accepted */ + chooseFeeGroup: FunctionReference< + 'mutation', + { eventId: Id<'events'>; groupId: string | null }, + null + >; + /** The team saw the proof at the intake */ + confirmFeeGroup: FunctionReference< + 'mutation', + { eventId: Id<'events'>; sellerId: Id<'users'> }, + null + >; + /** The proof is missing: the bazaar's fees apply */ + removeFeeGroup: FunctionReference< + 'mutation', + { eventId: Id<'events'>; sellerId: Id<'users'> }, + null + >; + /** The organizer puts a seller in a group by hand, or takes them out */ + assignFeeGroup: FunctionReference< + 'mutation', + { eventId: Id<'events'>; sellerId: Id<'users'>; groupId: string | null }, + null + >; + }; events: { getFeeLock: FunctionReference<'query', { eventId: Id<'events'> }, { locked: boolean } | null>; getMyEventDraft: FunctionReference< @@ -1165,6 +1228,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1239,6 +1303,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1315,6 +1380,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1391,6 +1457,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1477,6 +1544,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1556,6 +1624,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1630,6 +1699,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1691,6 +1761,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | null | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1750,6 +1821,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | null | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -1833,6 +1905,7 @@ export interface Api { labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; maxFeesPerSeller?: number | undefined; + feeGroups?: FeeGroup[] | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; directSale?: boolean | undefined; @@ -2594,6 +2667,8 @@ export interface Api { sellerId: Id<'users'>; /** Direct sale with a fee cap: the commission the seller still pays at most */ feeCapLeft?: number; + /** The seller's commission in percent, when their fee group has its own (#302) */ + commissionPercent?: number; } | null >; getCheckoutSnapshot: FunctionReference< @@ -2692,7 +2767,10 @@ export interface Api { title: string; startDate: number; endDate: number; + /** The seller's commission: their fee group's or the bazaar's */ commissionPercent: number; + /** The seller's fee group (#302) */ + feeGroup?: string | undefined; }; paid: boolean; sellerNumber: number | undefined; diff --git a/src/lib/checkout.test.ts b/src/lib/checkout.test.ts index e8d01ce9..06bc58da 100644 --- a/src/lib/checkout.test.ts +++ b/src/lib/checkout.test.ts @@ -239,4 +239,10 @@ describe('what the desk takes', () => { // Without a cap every item pays its commission expect(deskCommissions([{ price: 140 }, { price: 90 }], 10)).toEqual([14, 9]); }); + + it("takes the commission of the seller's fee group", () => { + expect(deskCommissions([{ price: 140, commissionPercent: 5 }, { price: 90 }], 10)).toEqual([ + 7, 9, + ]); + }); }); diff --git a/src/lib/checkout.ts b/src/lib/checkout.ts index e02d06c4..7b2668d0 100644 --- a/src/lib/checkout.ts +++ b/src/lib/checkout.ts @@ -182,6 +182,8 @@ export interface CommissionLine { sellerId?: string; /** What is left of the seller's fee cap before this cart; unset without a cap */ feeCapLeft?: number; + /** The seller's commission when their fee group has its own (#302) */ + commissionPercent?: number; } /** @@ -190,8 +192,8 @@ export interface CommissionLine { */ export function deskCommissions(lines: CommissionLine[], percent: number): number[] { const paid = new Map(); - return lines.map(({ price, sellerId, feeCapLeft }) => { - const commission = commissionOf(price, percent); + return lines.map(({ price, sellerId, feeCapLeft, commissionPercent }) => { + const commission = commissionOf(price, commissionPercent ?? percent); if (feeCapLeft === undefined || sellerId === undefined) return commission; const before = paid.get(sellerId) ?? 0; const capped = cappedCommission(commission, before, feeCapLeft); diff --git a/src/lib/sellerFees.test.ts b/src/lib/sellerFees.test.ts index f364e3bd..12fde8c3 100644 --- a/src/lib/sellerFees.test.ts +++ b/src/lib/sellerFees.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { describeSellerFees, describeSellerRules, describeSellerSchedule } from './sellerFees'; +import { + describeFeeGroups, + describeSellerFees, + describeSellerRules, + describeSellerSchedule, +} from './sellerFees'; describe('describeSellerFees', () => { it('explains commission and intake fee with an example', () => { @@ -131,3 +136,42 @@ describe('describeSellerSchedule', () => { expect(schedule.rows.map((row) => row.label)).toEqual(['Aufbau', 'Abbau']); }); }); + +describe('describeFeeGroups', () => { + it("names each group with its fees next to the bazaar's and how to get in", () => { + const groups = describeFeeGroups({ + commission: 10, + features: { + intakeFee: 1, + maxItemsPerSeller: 20, + feeGroups: [ + { + id: 'members', + label: 'Vereinsmitglieder', + commission: 5, + assignment: 'selfDeclared', + proofHint: 'Mitgliedsausweis zeigen', + }, + { + id: 'helpers', + label: 'Helfer', + commission: 10, + intakeFee: 0.5, + maxItemsPerSeller: 40, + assignment: 'helpers', + }, + ], + }, + }); + expect(groups.map(({ fees, how }) => ({ fees, how }))).toEqual([ + { + fees: '5 % Provision statt 10 % · keine Annahmegebühr', + how: 'Nachweis bei der Abgabe: Mitgliedsausweis zeigen', + }, + { + fees: '10 % Provision · 0,50 € pro Artikel · bis zu 40 Artikel', + how: 'Gilt für Helfer des Basars', + }, + ]); + }); +}); diff --git a/src/lib/sellerFees.ts b/src/lib/sellerFees.ts index 83e60882..74f5735b 100644 --- a/src/lib/sellerFees.ts +++ b/src/lib/sellerFees.ts @@ -1,5 +1,6 @@ import { formatPriceDE } from './utils'; import { feeCapCredit } from '../shared/feeCap'; +import { eventFees, groupFees, type FeeGroup } from '../shared/feeGroups'; import { resolveEventFeatures, type StoredEventFeatures } from '../shared/eventFeatures'; import { formatBerlinRange, formatBerlinTime } from '../shared/berlinTime'; import i18n, { currentLocale } from '../i18n'; @@ -124,6 +125,55 @@ export function describeSellerFees({ commission, intakeFee = 0, maxFeesPerSeller }; } +export interface FeeGroupTerms { + group: FeeGroup; + /** The group's fees in short, e.g. "5 % Provision statt 10 % · keine Annahmegebühr" */ + fees: string; + /** How one gets in: the proof to bring, or "for helpers" */ + how: string; +} + +/** + * The fee groups as sellers read them (#302): each with its own fees next to the bazaar's, + * so it is clear what changes ("5 % instead of 10 %"). + */ +export function describeFeeGroups(event: SellerConditionsEvent): FeeGroupTerms[] { + const groups = event.features?.feeGroups ?? []; + const base = eventFees(event); + return groups.map((group) => { + const fees = groupFees(event, group); + const parts = [ + fees.commission === base.commission + ? text('groupCommission', { percent: formatPercent(fees.commission) }) + : text('groupCommissionInstead', { + percent: formatPercent(fees.commission), + base: formatPercent(base.commission), + }), + fees.intakeFee + ? text('groupIntakeFee', { fee: formatPriceDE(fees.intakeFee) }) + : base.intakeFee + ? text('groupNoIntakeFee') + : undefined, + fees.maxFeesPerSeller !== undefined && fees.maxFeesPerSeller !== base.maxFeesPerSeller + ? text('groupCap', { fee: formatPriceDE(fees.maxFeesPerSeller) }) + : undefined, + fees.maxItemsPerSeller !== undefined && fees.maxItemsPerSeller !== base.maxItemsPerSeller + ? text('groupItems', { count: fees.maxItemsPerSeller }) + : undefined, + ]; + return { + group, + fees: parts.filter(Boolean).join(' · '), + how: + group.assignment === 'helpers' + ? text('groupHelpers') + : group.proofHint + ? text('groupProof', { hint: group.proofHint }) + : text('groupChecked'), + }; + }); +} + export interface SellerRule { text: string; /** false for something the bazaar does not offer */ diff --git a/src/lib/settlementExport.test.ts b/src/lib/settlementExport.test.ts index 2e2311e0..d1ef4f9f 100644 --- a/src/lib/settlementExport.test.ts +++ b/src/lib/settlementExport.test.ts @@ -103,6 +103,18 @@ describe('settlement export', () => { expect(columns(capped([seller({ feeCapCredit: 3 })]))).toBe(9); }); + it('names the fee group of each seller', () => { + const data = { + ...settlement([seller({ feeGroup: 'Vereinsmitglieder' }), seller({ sellerNumber: 8 })], []), + event: { ...settlement([], []).event, feeGroups: true }, + }; + const [header, first, second] = sellersCsv(data).split('\r\n'); + expect(header.split(';').at(-1)).toBe('Gebührengruppe'); + expect(first.split(';').at(-1)).toBe('Vereinsmitglieder'); + expect(second.split(';').at(-1)).toBe(''); + expect(sellerRows(data.sellers, false, 'name')[0][1]).toBe('Anna Rad (Vereinsmitglieder)'); + }); + it('writes two CSV tables that spreadsheets open', () => { const data = settlement([seller()], [sale({ title: 'Rad; "Cube"' })]); expect(sellersCsv(data).startsWith('\uFEFFNr.;Verkäufer;Anschrift;Umsatz (€)')).toBe(true); diff --git a/src/lib/settlementExport.ts b/src/lib/settlementExport.ts index d7b22a6e..f6bd12bc 100644 --- a/src/lib/settlementExport.ts +++ b/src/lib/settlementExport.ts @@ -39,8 +39,12 @@ function withCap(row: string[], cap: boolean, value: string): string[] { return cap ? [...row.slice(0, CAP_COLUMN), value, ...row.slice(CAP_COLUMN)] : row; } -export function sellerHeaders(cap = false): string[] { - return withCap( +/** The bazaar has fee groups (#302): the CSV gets a column, the PDF names it with the seller */ +export const hasGroupColumn = ({ event, sellers }: Pick) => + !!event.feeGroups || sellers.some((seller) => seller.feeGroup); + +export function sellerHeaders(cap = false, group = false): string[] { + const headers = withCap( [ text('number'), text('seller'), @@ -54,14 +58,24 @@ export function sellerHeaders(cap = false): string[] { cap, text('feeCap') ); + return group ? [...headers, text('feeGroup')] : headers; } -export function sellerRows(sellers: SettlementSeller[], cap = false): string[][] { - return sellers.map((seller) => - withCap( +/** + * `group`: "column" adds the fee group as last column, "name" after the seller's name + * (the PDF, whose columns are fixed). + */ +export function sellerRows( + sellers: SettlementSeller[], + cap = false, + group: 'column' | 'name' | false = false +): string[][] { + return sellers.map((seller) => { + const name = sellerName(seller); + const row = withCap( [ number(seller.sellerNumber), - sellerName(seller), + group === 'name' && seller.feeGroup ? `${name} (${seller.feeGroup})` : name, sellerAddress(seller), formatPriceDE(seller.revenue), formatPriceDE(seller.commission), @@ -71,8 +85,9 @@ export function sellerRows(sellers: SettlementSeller[], cap = false): string[][] ], cap, formatPriceDE(capCredit(seller)) - ) - ); + ); + return group === 'column' ? [...row, seller.feeGroup ?? ''] : row; + }); } function sellerTotals(sellers: SettlementSeller[], cap: boolean): string[] { @@ -179,7 +194,10 @@ export function buildSettlementPdf(settlement: SettlementExport): jsPDF { y = drawTable(doc, { columns: cap ? SELLER_COLUMNS_CAP : SELLER_COLUMNS, headers: sellerHeaders(cap), - rows: [...sellerRows(sellers, cap), sellerTotals(sellers, cap)], + rows: [ + ...sellerRows(sellers, cap, hasGroupColumn(settlement) && 'name'), + sellerTotals(sellers, cap), + ], y, margin: MARGIN, }); @@ -200,7 +218,11 @@ export function downloadSettlementPdf(settlement: SettlementExport) { export function sellersCsv(settlement: SettlementExport): string { const cap = hasCapColumn(settlement); - return toCsv([sellerHeaders(cap), ...sellerRows(settlement.sellers, cap)]); + const group = hasGroupColumn(settlement); + return toCsv([ + sellerHeaders(cap, group), + ...sellerRows(settlement.sellers, cap, group && 'column'), + ]); } export function salesCsv(settlement: SettlementExport): string { diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 9e9d6a7f..c55eabc6 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -90,7 +90,13 @@ "sellerNoteTooLong": "Der Hinweis für Verkäufer darf höchstens {{max}} Zeichen haben.", "settlementClosed": "Die Abwicklung dieses Basars ist abgeschlossen. Verkäufe und Rückgaben lassen sich nicht mehr ändern.", "startMissing": "Bitte auch den Beginn der {{label}} angeben.", - "registrationWindow": "Das Ende der Anmeldung muss nach ihrem Beginn liegen." + "registrationWindow": "Das Ende der Anmeldung muss nach ihrem Beginn liegen.", + "feeGroupsTooMany": "Ein Basar kann höchstens 10 Gebührengruppen haben.", + "feeGroupLabel": "Jede Gebührengruppe braucht einen Namen mit höchstens 60 Zeichen.", + "feeGroupLabelTwice": "Zwei Gebührengruppen haben denselben Namen.", + "feeGroupCommission": "Die Provision einer Gebührengruppe liegt zwischen 0 und 100 %.", + "feeGroupProofHint": "Der Hinweis zum Nachweis darf höchstens 200 Zeichen lang sein.", + "feeGroupsOnlyLower": "Seit sich Verkäufer angemeldet haben, können Gebührengruppen nur noch günstiger werden. Entfernen oder anders zuordnen geht nicht mehr." }, "feature": { "disabled": "Diese Aktion ist derzeit deaktiviert.", @@ -271,5 +277,13 @@ }, "categoryField": { "inUse": "Dieses Zusatzfeld wird noch von Kategorien verwendet. Entferne es dort zuerst." + }, + "feeGroup": { + "unconfirmed": "{{group}}: Bitte zuerst den Nachweis prüfen und die Gruppe bestätigen oder entfernen.", + "unknown": "Diese Gebührengruppe gibt es bei diesem Basar nicht.", + "decided": "Das Team hat deine Gruppe schon geprüft. Für eine Änderung sprich bitte das Team an.", + "locked": "Deine Artikel wurden schon angenommen. Für eine Änderung der Gruppe sprich bitte das Team an.", + "none": "Dieser Verkäufer hat keine Gebührengruppe angegeben.", + "organizerOnly": "Nur Veranstalter können Verkäufer einer Gebührengruppe zuordnen." } } diff --git a/src/locales/de/events.json b/src/locales/de/events.json index 306fefe8..4ee24932 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -124,7 +124,30 @@ "maxItemsTotal": "Höchstens {{max}} Artikel auf dem ganzen Basar", "placesLeft_one": "Höchstens {{max}} Artikel auf dem ganzen Basar, noch {{count}} Platz frei", "placesLeft_other": "Höchstens {{max}} Artikel auf dem ganzen Basar, noch {{count}} Plätze frei", - "marketFull": "Der Basar ist voll: Alle {{max}} Plätze für Artikel sind vergeben" + "marketFull": "Der Basar ist voll: Alle {{max}} Plätze für Artikel sind vergeben", + "groupsTitle": "Eigene Gebühren für", + "groupCommission": "{{percent}} % Provision", + "groupCommissionInstead": "{{percent}} % Provision statt {{base}} %", + "groupIntakeFee": "{{fee}} € pro Artikel", + "groupNoIntakeFee": "keine Annahmegebühr", + "groupCap": "höchstens {{fee}} € Gebühren", + "groupItems": "bis zu {{count}} Artikel", + "groupHelpers": "Gilt für Helfer des Basars", + "groupProof": "Nachweis bei der Abgabe: {{hint}}", + "groupChecked": "Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe", + "myGroup": "Deine Gruppe: {{group}}", + "myGroupPending": "Das Team prüft deine Angabe bei der Abgabe.", + "myGroupConfirmed": "Vom Team bestätigt.", + "myGroupNone": "Du zahlst die normalen Gebühren.", + "myGroupChange": "Ändern", + "myGroupChoose": "Gruppe angeben", + "myGroupLocked": "Für eine Änderung sprich bitte das Team an.", + "myGroupSaved": "Gespeichert", + "choiceTitle": "Gehörst du zu einer dieser Gruppen?", + "choiceNone": "Nein, ich zahle die normalen Gebühren", + "choiceHint": "Das Team prüft deine Angabe bei der Abgabe. Ohne Nachweis gelten die normalen Gebühren.", + "choiceDialogTitle": "Deine Gebührengruppe", + "choiceSave": "Speichern" }, "sidebar": { "details": "Basar-Details", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 4571444d..9b0fbbc7 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -340,7 +340,9 @@ "registrationClosed": "Geschlossen, nur mit Einladung", "untilTime": "bis {{time}} Uhr", "maxItemsTotal": "Höchstens {{count}} Artikel insgesamt", - "maxFees": "Höchstens {{amount}} € Gebühren pro Verkäufer" + "maxFees": "Höchstens {{amount}} € Gebühren pro Verkäufer", + "feeGroups_one": "Gebührengruppe: {{groups}}", + "feeGroups_other": "Gebührengruppen: {{groups}}" }, "sellers": { "sortSheets": "Sortierblätter", @@ -456,7 +458,8 @@ "returnedItems": "{{count}} unverkaufte Artikel zurückgegeben", "saving": "Wird gespeichert…", "done": "Erledigt, abschließen", - "feeCap": "Gebühren-Deckel" + "feeCap": "Gebühren-Deckel", + "commissionGroup": "Provision ({{percent}} %, {{group}})" }, "cash": { "title": "Abrechnung", @@ -798,7 +801,9 @@ "agreed": "Vereinbarter Preis", "agreedPrice": "Vereinbarter Preis", "commissionCapped": "Provision {{amount}} € · Deckel", - "capReached": "Gebühren-Deckel erreicht, keine Provision" + "capReached": "Gebühren-Deckel erreicht, keine Provision", + "sumMixed_one": "Provision ({{count}} Artikel)", + "sumMixed_other": "Provision ({{count}} Artikel)" } }, "proof": { @@ -884,7 +889,8 @@ "fileNameSellers": "Abrechnung-Verkaeufer", "fileNameSales": "Abrechnung-Verkaeufe", "direct": "direkt bezahlt", - "feeCap": "Gebühren-Deckel (€)" + "feeCap": "Gebühren-Deckel (€)", + "feeGroup": "Gebührengruppe" }, "wizard": { "back": "Zurück", @@ -971,7 +977,8 @@ }, "maxItemsTotal_one": "max. {{count}} Artikel insgesamt", "maxItemsTotal_other": "max. {{count}} Artikel insgesamt", - "maxFees": "höchstens {{fee}} € pro Verkäufer" + "maxFees": "höchstens {{fee}} € pro Verkäufer", + "feeGroup": "{{label}}: {{percent}} %" }, "fixErrors": "Bitte prüfe die markierten Angaben.", "guestCreate": "Konto anlegen und Basar erstellen", @@ -1051,7 +1058,8 @@ "mapEntrance": "Eingang", "maxItemsTotal": "{{count}} Plätze für Artikel insgesamt", "feeCap": "Höchstens {{fee}} Gebühren pro Verkäufer", - "feeCapExample": "Gebühren-Deckel {{fee}}" + "feeCapExample": "Gebühren-Deckel {{fee}}", + "feeGroup": "{{label}}: {{percent}} %" }, "short": { "type": "Art", @@ -1364,5 +1372,70 @@ "copyCode": "Code kopieren", "copyFailed": "Kopieren nicht möglich", "edit": "Ändern" + }, + "feeGroups": { + "title": "Gebührengruppen (optional)", + "hint": "Eigene Gebühren für eine Gruppe von Verkäufern, z. B. Vereinsmitglieder 5 % statt 10 % oder Helfer ohne Provision. Verkäufer sehen alle Gruppen in den Bedingungen. Wer zu mehreren Gruppen gehört, zahlt die günstigsten Gebühren.", + "empty": "Alle Verkäufer zahlen dieselben Gebühren. Mit einer Gruppe zahlen z. B. Vereinsmitglieder oder Helfer weniger.", + "unnamed": "Neue Gruppe", + "hasError": "Bitte prüfen", + "label": "Name der Gruppe", + "labelPlaceholder": "z. B. Vereinsmitglieder", + "assignmentLabel": "Wer gehört dazu?", + "assignment": { + "selfDeclared": "Verkäufer geben es bei der Anmeldung an", + "helpers": "Helfer des Basars", + "selfDeclaredShort": "Angabe bei der Anmeldung", + "helpersShort": "Helfer", + "selfDeclaredHint": "Verkäufer wählen die Gruppe bei der Anmeldung selbst. Bei der Abgabe prüft das Team den Nachweis und bestätigt die Gruppe oder entfernt sie. Vorher kann kein Artikel angenommen werden.", + "helpersHint": "Gilt automatisch für alle mit einer Helferrolle, solange sie sie haben. In der Verkäuferliste kannst du auch Helfer ohne Rechte zuordnen, z. B. Kuchenspender." + }, + "commission": "Provision", + "intakeFee": "Annahmegebühr", + "cap": "Gebühren-Deckel", + "capHint": "Leer: Es gilt der Deckel des Basars.", + "items": "Max. Artikel", + "itemsHint": "Leer: Es gilt die Grenze des Basars. Die Grenze für den ganzen Markt gilt für alle.", + "likeBazaar": "wie Basar ({{value}})", + "proofHint": "Nachweis (optional)", + "proofHintInfo": "Steht bei der Gruppe in den Bedingungen und bei der Abgabe, damit Verkäufer ihn mitbringen.", + "proofHintPlaceholder": "z. B. Mitgliedsausweis bei der Abgabe zeigen", + "fixed": "Verkäufer haben sich mit dieser Gruppe angemeldet: Sie bleibt und kann nur günstiger werden.", + "cheapest": "Wer zu mehreren Gruppen gehört, zahlt die günstigsten Gebühren.", + "remove": "Gruppe entfernen", + "add": "Gebührengruppe hinzufügen", + "summaryCommission": "{{percent}} % Provision", + "summaryIntakeFee": "{{fee}} € pro Artikel", + "summaryNoIntakeFee": "keine Annahmegebühr", + "summaryCap": "höchstens {{fee}} €", + "summaryItems_one": "{{count}} Artikel", + "summaryItems_other": "{{count}} Artikel", + "labelRequired": "Gib der Gruppe einen Namen.", + "labelTwice": "Diesen Namen hat schon eine andere Gruppe.", + "registeredMax": "Verkäufer haben sich mit dieser Gruppe angemeldet: höchstens {{value}}.", + "registeredMinItems": "Verkäufer haben sich mit dieser Gruppe angemeldet: mindestens {{min}} Artikel." + }, + "feeGroupCheck": { + "title": "Ermäßigt: {{group}} – Nachweis prüfen", + "text": "Der Verkäufer hat angegeben, zu dieser Gruppe zu gehören. Bestätige die Gruppe, wenn der Nachweis stimmt, sonst entferne sie: Dann gelten die normalen Gebühren. Vorher lassen sich keine Artikel annehmen.", + "textWithProof": "Nachweis: {{proof}}. Bestätige die Gruppe, wenn er stimmt, sonst entferne sie: Dann gelten die normalen Gebühren. Vorher lassen sich keine Artikel annehmen.", + "confirm": "Bestätigen", + "remove": "Entfernen", + "confirmed": "{{group}} bestätigt", + "removed": "{{group}} entfernt, es gelten die normalen Gebühren" + }, + "sellerFeeGroup": { + "title": "Gebührengruppe", + "pending": "prüfen", + "pendingHint": "Selbstauskunft: Bei der Abgabe Nachweis prüfen und bestätigen oder entfernen", + "assign": "Gebührengruppe zuordnen", + "none": "Keine Gruppe", + "assigned": "{{name}}: {{group}}", + "unassigned": "{{name}}: keine Gruppe", + "byRole": "{{group}} gilt durch die Helferrolle, solange sie besteht.", + "tab": "Gruppen", + "noneInGroups": "Noch niemand in einer Gebührengruppe.", + "pendingCount_one": "{{count}} Selbstauskunft ist noch nicht geprüft. Bei der Abgabe bestätigst oder entfernst du sie.", + "pendingCount_other": "{{count}} Selbstauskünfte sind noch nicht geprüft. Bei der Abgabe bestätigst oder entfernst du sie." } } diff --git a/src/locales/de/sales.json b/src/locales/de/sales.json index 1ffb1e60..28cf1bfb 100644 --- a/src/locales/de/sales.json +++ b/src/locales/de/sales.json @@ -39,7 +39,8 @@ "payFee": "Annahmegebühr beim Veranstalter bezahlen", "nothingSold": "Hier wurde nichts verkauft. Die Annahmegebühr fällt für jeden angenommenen Artikel an.", "youPay": "Du zahlst", - "feeCap": "Gebühren-Deckel" + "feeCap": "Gebühren-Deckel", + "bazaarFeeGroup": "Bazar-Gebühr ({{percent}} %, {{group}})" }, "invoice": { "title": "Privatrechnung", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 48cba175..47ad38df 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -90,7 +90,13 @@ "sellerNoteTooLong": "The note for sellers may have at most {{max}} characters.", "settlementClosed": "The settlement of this bazaar is closed. Sales and returns can no longer be changed.", "startMissing": "Please also give the start of the {{label}}.", - "registrationWindow": "Registration must end after it begins." + "registrationWindow": "Registration must end after it begins.", + "feeGroupsTooMany": "A bazaar can have at most 10 fee groups.", + "feeGroupLabel": "Every fee group needs a name of at most 60 characters.", + "feeGroupLabelTwice": "Two fee groups have the same name.", + "feeGroupCommission": "The commission of a fee group is between 0 and 100 %.", + "feeGroupProofHint": "The proof hint may be at most 200 characters long.", + "feeGroupsOnlyLower": "Since sellers have registered, fee groups can only get cheaper. They can no longer be removed or assigned differently." }, "feature": { "disabled": "This action is currently disabled.", @@ -271,5 +277,13 @@ }, "categoryField": { "inUse": "Categories still use this extra field. Remove it there first." + }, + "feeGroup": { + "unconfirmed": "{{group}}: Please check the proof first and confirm or remove the group.", + "unknown": "This fee group does not exist at this bazaar.", + "decided": "The team has already checked your group. Please talk to the team to change it.", + "locked": "Your items have already been accepted. Please talk to the team to change your group.", + "none": "This seller has not given a fee group.", + "organizerOnly": "Only organizers can put sellers in a fee group." } } diff --git a/src/locales/en/events.json b/src/locales/en/events.json index 6af4b824..071e7a09 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -124,7 +124,30 @@ "maxItemsTotal": "At most {{max}} items at the whole bazaar", "placesLeft_one": "At most {{max}} items at the whole bazaar, {{count}} place left", "placesLeft_other": "At most {{max}} items at the whole bazaar, {{count}} places left", - "marketFull": "The bazaar is full: all {{max}} places for items are taken" + "marketFull": "The bazaar is full: all {{max}} places for items are taken", + "groupsTitle": "Own fees for", + "groupCommission": "{{percent}} % commission", + "groupCommissionInstead": "{{percent}} % commission instead of {{base}} %", + "groupIntakeFee": "{{fee}} € per item", + "groupNoIntakeFee": "no intake fee", + "groupCap": "at most {{fee}} € in fees", + "groupItems": "up to {{count}} items", + "groupHelpers": "For helpers of the bazaar", + "groupProof": "Proof at the drop-off: {{hint}}", + "groupChecked": "You say so when registering, the team checks it at the drop-off", + "myGroup": "Your group: {{group}}", + "myGroupPending": "The team checks it at the drop-off.", + "myGroupConfirmed": "Confirmed by the team.", + "myGroupNone": "You pay the regular fees.", + "myGroupChange": "Change", + "myGroupChoose": "Choose group", + "myGroupLocked": "Please talk to the team to change it.", + "myGroupSaved": "Saved", + "choiceTitle": "Do you belong to one of these groups?", + "choiceNone": "No, I pay the regular fees", + "choiceHint": "The team checks it at the drop-off. Without proof the regular fees apply.", + "choiceDialogTitle": "Your fee group", + "choiceSave": "Save" }, "sidebar": { "details": "Bazaar details", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 96b84f57..0e61e786 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -340,7 +340,9 @@ "registrationClosed": "Closed, by invitation only", "untilTime": "until {{time}}", "maxItemsTotal": "At most {{count}} items in total", - "maxFees": "At most €{{amount}} of fees per seller" + "maxFees": "At most €{{amount}} of fees per seller", + "feeGroups_one": "Fee group: {{groups}}", + "feeGroups_other": "Fee groups: {{groups}}" }, "sellers": { "sortSheets": "Sorting sheets", @@ -456,7 +458,8 @@ "returnedItems": "{{count}} unsold items returned", "saving": "Saving…", "done": "Done, finish", - "feeCap": "Fee cap" + "feeCap": "Fee cap", + "commissionGroup": "Commission ({{percent}} %, {{group}})" }, "cash": { "title": "Settlement", @@ -798,7 +801,9 @@ "agreed": "Agreed price", "agreedPrice": "Agreed price", "commissionCapped": "Commission {{amount}} € · cap", - "capReached": "Fee cap reached, no commission" + "capReached": "Fee cap reached, no commission", + "sumMixed_one": "Commission ({{count}} item)", + "sumMixed_other": "Commission ({{count}} items)" } }, "proof": { @@ -884,7 +889,8 @@ "fileNameSellers": "Settlement-sellers", "fileNameSales": "Settlement-sales", "direct": "paid directly", - "feeCap": "Fee cap (€)" + "feeCap": "Fee cap (€)", + "feeGroup": "Fee group" }, "wizard": { "back": "Back", @@ -971,7 +977,8 @@ }, "maxItemsTotal_one": "max. {{count}} item in total", "maxItemsTotal_other": "max. {{count}} items in total", - "maxFees": "at most €{{fee}} per seller" + "maxFees": "at most €{{fee}} per seller", + "feeGroup": "{{label}}: {{percent}} %" }, "fixErrors": "Please check the marked details.", "guestCreate": "Sign up and create bazaar", @@ -1051,7 +1058,8 @@ "mapEntrance": "Entrance", "maxItemsTotal": "{{count}} places for items in total", "feeCap": "At most {{fee}} of fees per seller", - "feeCapExample": "Fee cap {{fee}}" + "feeCapExample": "Fee cap {{fee}}", + "feeGroup": "{{label}}: {{percent}} %" }, "short": { "type": "Kind", @@ -1364,5 +1372,70 @@ "copyCode": "Copy code", "copyFailed": "Copying failed", "edit": "Change" + }, + "feeGroups": { + "title": "Fee groups (optional)", + "hint": "Own fees for a group of sellers, e.g. club members 5 % instead of 10 % or helpers without commission. Sellers see all groups in the conditions. Who belongs to several groups pays the cheapest fees.", + "empty": "All sellers pay the same fees. With a group, e.g. club members or helpers pay less.", + "unnamed": "New group", + "hasError": "Please check", + "label": "Name of the group", + "labelPlaceholder": "e.g. Club members", + "assignmentLabel": "Who belongs to it?", + "assignment": { + "selfDeclared": "Sellers say so when registering", + "helpers": "Helpers of the bazaar", + "selfDeclaredShort": "Given at registration", + "helpersShort": "Helpers", + "selfDeclaredHint": "Sellers choose the group themselves when registering. At the drop-off the team checks the proof and confirms or removes the group. Until then no item can be accepted.", + "helpersHint": "Applies automatically to everyone with a helper role, as long as they have it. In the seller list you can also add helpers without rights, e.g. cake donors." + }, + "commission": "Commission", + "intakeFee": "Intake fee", + "cap": "Fee cap", + "capHint": "Empty: the bazaar's cap applies.", + "items": "Max. items", + "itemsHint": "Empty: the bazaar's limit applies. The limit for the whole market applies to everyone.", + "likeBazaar": "like bazaar ({{value}})", + "proofHint": "Proof (optional)", + "proofHintInfo": "Shown with the group in the conditions and at the drop-off, so sellers bring it.", + "proofHintPlaceholder": "e.g. Show your membership card at the drop-off", + "fixed": "Sellers registered with this group: it stays and can only get cheaper.", + "cheapest": "Who belongs to several groups pays the cheapest fees.", + "remove": "Remove group", + "add": "Add fee group", + "summaryCommission": "{{percent}} % commission", + "summaryIntakeFee": "{{fee}} € per item", + "summaryNoIntakeFee": "no intake fee", + "summaryCap": "at most {{fee}} €", + "summaryItems_one": "{{count}} item", + "summaryItems_other": "{{count}} items", + "labelRequired": "Give the group a name.", + "labelTwice": "Another group already has this name.", + "registeredMax": "Sellers registered with this group: at most {{value}}.", + "registeredMinItems": "Sellers registered with this group: at least {{min}} items." + }, + "feeGroupCheck": { + "title": "Reduced: {{group}} – check the proof", + "text": "The seller says they belong to this group. Confirm the group if the proof is right, otherwise remove it: then the regular fees apply. Until then no item can be accepted.", + "textWithProof": "Proof: {{proof}}. Confirm the group if it is right, otherwise remove it: then the regular fees apply. Until then no item can be accepted.", + "confirm": "Confirm", + "remove": "Remove", + "confirmed": "{{group}} confirmed", + "removed": "{{group}} removed, the regular fees apply" + }, + "sellerFeeGroup": { + "title": "Fee group", + "pending": "check", + "pendingHint": "Self-declared: check the proof at the drop-off and confirm or remove it", + "assign": "Assign fee group", + "none": "No group", + "assigned": "{{name}}: {{group}}", + "unassigned": "{{name}}: no group", + "byRole": "{{group}} applies through the helper role, as long as it lasts.", + "tab": "Groups", + "noneInGroups": "Nobody is in a fee group yet.", + "pendingCount_one": "{{count}} self-declaration is not checked yet. You confirm or remove it at the drop-off.", + "pendingCount_other": "{{count}} self-declarations are not checked yet. You confirm or remove them at the drop-off." } } diff --git a/src/locales/en/sales.json b/src/locales/en/sales.json index 29b81fff..274cffa1 100644 --- a/src/locales/en/sales.json +++ b/src/locales/en/sales.json @@ -39,7 +39,8 @@ "payFee": "Pay the intake fee to the organizer", "nothingSold": "Nothing was sold here. The intake fee applies to every accepted item.", "youPay": "You pay", - "feeCap": "Fee cap" + "feeCap": "Fee cap", + "bazaarFeeGroup": "Bazaar fee ({{percent}} %, {{group}})" }, "invoice": { "title": "Private invoice", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 29556aaa..4c5b848f 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -58,6 +58,8 @@ interface RegisteredTerms { maxItemsPerSeller?: number; /** Unset: no cap, the highest there is */ maxFeesPerSeller?: number; + /** Fee groups sellers registered with: they stay and only get cheaper (#302) */ + feeGroups: FeeGroup[]; } import { useTranslation } from 'react-i18next'; import { coverFile, coverForKind, DEFAULT_COVER } from '../../../lib/eventCovers'; @@ -83,6 +85,8 @@ import { SalePreview, } from './components/wizard/WizardPreviews'; import { WizardSummary } from './components/wizard/WizardSummary'; +import { EditEventFeeGroups } from './components/EditEventFeeGroups'; +import { MAX_FEE_GROUPS, type FeeGroup } from '../../../shared/feeGroups'; import { PageSkeleton } from '../../../components/ui/loading'; import { isEventRunning } from '../../../shared/eventPhase'; @@ -203,6 +207,56 @@ const buildEventSchema = ( .max(10_000, zodMessage('form.feeCapMax', 'organizer')) .optional() .or(z.nan()), + feeGroups: z + .array( + z.object({ + id: z.string(), + label: z + .string() + .trim() + .min(1, zodMessage('feeGroups.labelRequired', 'organizer')) + .max(60), + commission: z + .number(zodMessage('form.minPercent', 'organizer')) + .min(0, zodMessage('form.feeNegative', 'organizer')) + .max(100, zodMessage('form.maxPercent', 'organizer', { max: 100 })), + intakeFee: z + .number() + .min(0, zodMessage('form.feeNegative', 'organizer')) + .max(100, zodMessage('form.feeMax', 'organizer')) + .optional() + .or(z.nan()), + maxFeesPerSeller: z + .number() + .min(0, zodMessage('form.feeNegative', 'organizer')) + .max(10_000, zodMessage('form.feeCapMax', 'organizer')) + .optional() + .or(z.nan()), + maxItemsPerSeller: z + .number() + .int(zodMessage('form.wholeNumber', 'organizer')) + .min(1, zodMessage('form.minOne', 'organizer')) + .optional() + .or(z.nan()), + assignment: z.enum(['selfDeclared', 'helpers']), + proofHint: z.string().max(200), + }) + ) + .max(MAX_FEE_GROUPS) + .superRefine((groups, ctx) => { + const seen = new Set(); + groups.forEach((group, index) => { + const label = group.label.trim().toLowerCase(); + if (label && seen.has(label)) { + ctx.addIssue({ + code: 'custom', + message: i18n.t('feeGroups.labelTwice', { ns: 'organizer' }), + path: [index, 'label'], + }); + } + seen.add(label); + }); + }), }), sellerLogistics: z.object({ dropoffStart: z.string(), @@ -294,6 +348,49 @@ const buildEventSchema = ( path: ['features', 'maxItemsPerSeller'], }); } + // Fee groups sellers registered with stay (the form offers no removal) and only get + // cheaper; an empty cap or item limit falls back to the bazaar's + for (const before of terms.feeGroups) { + const index = data.features.feeGroups.findIndex((group) => group.id === before.id); + const now = data.features.feeGroups[index]; + if (!now) continue; + const path = (field: string) => ['features', 'feeGroups', index, field]; + const tooHigh = (field: string, value: number, max: number, text: string) => { + if (value > max) { + ctx.addIssue({ + code: 'custom', + message: i18n.t('feeGroups.registeredMax', { ns: 'organizer', value: text }), + path: path(field), + }); + } + }; + tooHigh('commission', now.commission, before.commission, `${before.commission} %`); + tooHigh( + 'intakeFee', + given(now.intakeFee) ?? 0, + before.intakeFee ?? 0, + `${formatPriceDE(before.intakeFee ?? 0)} €` + ); + const capBefore = before.maxFeesPerSeller ?? terms.maxFeesPerSeller; + if (capBefore !== undefined) { + tooHigh( + 'maxFeesPerSeller', + given(now.maxFeesPerSeller) ?? given(data.features.maxFeesPerSeller) ?? Infinity, + capBefore, + `${formatPriceDE(capBefore)} €` + ); + } + const itemsBefore = before.maxItemsPerSeller ?? terms.maxItemsPerSeller; + const items = + given(now.maxItemsPerSeller) ?? given(data.features.maxItemsPerSeller) ?? Infinity; + if (itemsBefore !== undefined && items < itemsBefore) { + ctx.addIssue({ + code: 'custom', + message: i18n.t('feeGroups.registeredMinItems', { ns: 'organizer', min: itemsBefore }), + path: path('maxItemsPerSeller'), + }); + } + } }); type EventFormData = z.infer>; @@ -338,6 +435,13 @@ function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormDat labelMark: features.labelMark, intakeFee: features.intakeFee, maxFeesPerSeller: features.maxFeesPerSeller, + feeGroups: (stored?.feeGroups ?? []).map((group) => ({ + ...group, + intakeFee: group.intakeFee ?? NaN, + maxFeesPerSeller: group.maxFeesPerSeller ?? NaN, + maxItemsPerSeller: group.maxItemsPerSeller ?? NaN, + proofHint: group.proofHint ?? '', + })), privateSellersOnly: features.privateSellersOnly, fixedSellerData: features.fixedSellerData, directSale: features.directSale, @@ -394,6 +498,17 @@ function featuresFromForm(features: FeatureFormData): FeaturesArgs { : undefined, // 0 is a cap as well: no fees at all maxFeesPerSeller: givenNumber(features.maxFeesPerSeller) ?? null, + // Always sent: an empty list removes the groups + feeGroups: features.feeGroups.map((group) => ({ + id: group.id, + label: group.label.trim(), + commission: group.commission, + intakeFee: (givenNumber(group.intakeFee) ?? 0) > 0 ? group.intakeFee : undefined, + maxFeesPerSeller: givenNumber(group.maxFeesPerSeller), + maxItemsPerSeller: givenNumber(group.maxItemsPerSeller), + assignment: group.assignment, + proofHint: group.proofHint.trim() || undefined, + })), privateSellersOnly: features.privateSellersOnly, fixedSellerData: features.fixedSellerData, directSale: features.directSale, @@ -481,7 +596,10 @@ const WIZARD_STEPS = [ fields: ['features.maxDiscountPercent', 'features.discountStartsAt'], }, { id: 'items', fields: ['categories', 'features.maxItemsPerSeller', 'features.maxItemsTotal'] }, - { id: 'fees', fields: ['commission', 'features.intakeFee', 'features.maxFeesPerSeller'] }, + { + id: 'fees', + fields: ['commission', 'features.intakeFee', 'features.maxFeesPerSeller', 'features.feeGroups'], + }, { id: 'registration', fields: ['visibility', 'accessCode', 'vendorLimit', 'features.registrationEndsAt'], @@ -588,6 +706,8 @@ function EventSection({ eventMapImageUrl?: string | null; isRunning: boolean; feeLock: FeeLock; + /** Ids of the fee groups sellers registered with */ + registeredFeeGroups?: string[]; }; }) { const feeLock = editing?.feeLock ?? null; @@ -645,6 +765,7 @@ function EventSection({ + ); case 'registration': @@ -751,6 +872,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { intakeFee: event.features?.intakeFee ?? 0, maxItemsPerSeller: event.features?.maxItemsPerSeller, maxFeesPerSeller: event.features?.maxFeesPerSeller, + feeGroups: event.features?.feeGroups ?? [], } : undefined; const eventSchema = useMemo( @@ -1317,6 +1439,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { eventMapImageUrl: event?.eventMapImageUrl, isRunning, feeLock, + registeredFeeGroups: registeredTerms.current?.feeGroups.map((g) => g.id), }} /> diff --git a/src/pages/organizer/events/components/EditEventFeeGroups.tsx b/src/pages/organizer/events/components/EditEventFeeGroups.tsx new file mode 100644 index 00000000..16da5422 --- /dev/null +++ b/src/pages/organizer/events/components/EditEventFeeGroups.tsx @@ -0,0 +1,358 @@ +import { useState, type ReactNode } from 'react'; +import { useFieldArray, useFormContext, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import { ChevronDown, Plus, Trash2, Users } from 'lucide-react'; +import { Button } from '../../../../components/ui/button'; +import { Input } from '../../../../components/ui/input'; +import { NativeSelect } from '../../../../components/ui/native-select'; +import { FieldError } from '../../../../components/ui/field-error'; +import { InfoTip, LabelWithInfo } from '../../../../components/ui/info-tip'; +import { cn, formatPriceDE } from '../../../../lib/utils'; +import type { FeeLock } from '../../../../lib/sellerFees'; +import { + MAX_FEE_GROUPS, + newFeeGroupId, + type FeeGroupAssignment, +} from '../../../../shared/feeGroups'; + +/** A fee group as the form holds it: empty numbers are NaN, the hint a string. */ +export interface FeeGroupForm { + id: string; + label: string; + commission: number; + intakeFee?: number; + maxFeesPerSeller?: number; + maxItemsPerSeller?: number; + assignment: FeeGroupAssignment; + proofHint: string; +} + +const given = (value: unknown): value is number => + typeof value === 'number' && Number.isFinite(value); + +/** A number field with its unit inside, like the bazaar's own fees. */ +function UnitInput({ + id, + unit, + readOnly, + ...props +}: React.ComponentProps & { unit?: string }) { + return ( +
+ + {unit && ( + + {unit} + + )} +
+ ); +} + +function Field({ + htmlFor, + label, + info, + error, + children, +}: { + htmlFor: string; + label: string; + info?: string; + error?: string; + children: ReactNode; +}) { + return ( +
+ + {label} + + {children} + {error && {error}} +
+ ); +} + +type GroupErrors = Partial>; + +/** + * Fee groups of the bazaar (#302): own fees for club members, helpers and others. Each + * group is a row with its fees in short; one opens to change it. Once sellers registered, + * a group that existed then cannot be removed and its fees only go down. + */ +export function EditEventFeeGroups({ + feeLock, + registeredIds = [], +}: { + feeLock: FeeLock; + /** Groups sellers registered with: they stay */ + registeredIds?: string[]; +}) { + const { t } = useTranslation('organizer'); + const { + control, + register, + formState: { errors }, + } = useFormContext(); + const { fields, append, remove } = useFieldArray({ control, name: 'features.feeGroups' }); + const groups = (useWatch({ control, name: 'features.feeGroups' }) ?? []) as FeeGroupForm[]; + const commission = useWatch({ control, name: 'commission' }) as number; + const eventCap = useWatch({ control, name: 'features.maxFeesPerSeller' }) as number | undefined; + const eventItems = useWatch({ control, name: 'features.maxItemsPerSeller' }) as + | number + | undefined; + const [open, setOpen] = useState(null); + const running = feeLock === 'running'; + const groupErrors = ( + errors.features as { feeGroups?: GroupErrors[] & { message?: string } } | undefined + )?.feeGroups; + + const add = () => { + const id = newFeeGroupId(); + append({ + id, + label: '', + commission: given(commission) ? commission : 0, + intakeFee: NaN, + maxFeesPerSeller: NaN, + maxItemsPerSeller: NaN, + assignment: 'selfDeclared', + proofHint: '', + } satisfies FeeGroupForm); + setOpen(id); + }; + + const summary = (group: FeeGroupForm) => + [ + t('feeGroups.summaryCommission', { percent: given(group.commission) ? group.commission : 0 }), + given(group.intakeFee) && group.intakeFee > 0 + ? t('feeGroups.summaryIntakeFee', { fee: formatPriceDE(group.intakeFee) }) + : t('feeGroups.summaryNoIntakeFee'), + given(group.maxFeesPerSeller) + ? t('feeGroups.summaryCap', { fee: formatPriceDE(group.maxFeesPerSeller) }) + : undefined, + given(group.maxItemsPerSeller) + ? t('feeGroups.summaryItems', { count: group.maxItemsPerSeller }) + : undefined, + t(`feeGroups.assignment.${group.assignment}Short`), + ] + .filter(Boolean) + .join(' · '); + + return ( +
+
+

{t('feeGroups.title')}

+ {t('feeGroups.hint')} +
+ {fields.length === 0 && ( +

{t('feeGroups.empty')}

+ )} + {fields.length > 0 && ( +
    + {fields.map((field, index) => { + const group = groups[index] ?? (field as unknown as FeeGroupForm); + const isOpen = open === group.id; + const error = groupErrors?.[index]; + const hasError = !!error && Object.keys(error).length > 0; + const fixed = !!feeLock && registeredIds.includes(group.id); + const prefix = `features.feeGroups.${index}`; + const domId = `fee-group-${index}`; + return ( +
  • + + {(isOpen || hasError) && ( +
    +
    + + + + + + + + + +
    +
    + + + + + + + + + + + + +
    + {group.assignment === 'selfDeclared' && ( + + + + )} +
    +

    + {fixed ? t('feeGroups.fixed') : t('feeGroups.cheapest')} +

    + +
    +
    + )} +
  • + ); + })} +
+ )} + {groupErrors?.message && {groupErrors.message}} + {!running && fields.length < MAX_FEE_GROUPS && ( + + )} +
+ ); +} diff --git a/src/pages/organizer/events/components/EventPageSidebar.tsx b/src/pages/organizer/events/components/EventPageSidebar.tsx index 716f1d40..a98ec66c 100644 --- a/src/pages/organizer/events/components/EventPageSidebar.tsx +++ b/src/pages/organizer/events/components/EventPageSidebar.tsx @@ -16,6 +16,7 @@ import type { SellerConditionsEvent } from '../../../../lib/sellerFees'; import { dateLocale } from '../../../../i18n/format'; import { toAbsoluteUrl } from '../../../../lib/seo'; import { useTranslation } from 'react-i18next'; +import type { Id } from '../../../../lib/api/types'; import type { TFunction } from 'i18next'; import { formatEventPlace } from '../../../../shared/eventJsonLd'; import { useNowPassing } from '../../../../hooks/useNowPassing'; @@ -50,6 +51,8 @@ interface EventPageSidebarProps { event: EventPageSidebarEvent; /** Shown to everyone thinking about selling here and to registered sellers */ conditions?: SellerConditionsEvent; + /** With it, a registered seller sees their fee group in the conditions */ + eventId?: Id<'events'>; } const dateOptions: Intl.DateTimeFormatOptions = { @@ -61,7 +64,7 @@ const timeOptions: Intl.DateTimeFormatOptions = { minute: '2-digit', }; -export function EventPageSidebar({ event, conditions }: EventPageSidebarProps) { +export function EventPageSidebar({ event, conditions, eventId }: EventPageSidebarProps) { const { t } = useTranslation('events'); const startDate = new Date(event.startDate); const endDate = new Date(event.endDate); @@ -257,7 +260,12 @@ export function EventPageSidebar({ event, conditions }: EventPageSidebarProps) {
{conditions && ( - + )} diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index cbdb0a90..84889003 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -94,6 +94,7 @@ interface WizardValues { labelMark?: LabelMark; intakeFee?: number; maxFeesPerSeller?: number; + feeGroups?: { id: string; label: string; commission: number }[]; privateSellersOnly?: boolean; fixedSellerData?: boolean; directSale?: boolean; @@ -565,6 +566,21 @@ export function FeesPreview({ type }: { type?: EventType }) { {t('wizard.preview.free')}

)} + {/* Own fees for groups of sellers (#302) */} + {(values.features?.feeGroups ?? []) + .filter((group) => group.label.trim()) + .map((group) => ( +

+ + {t('wizard.preview.feeGroup', { + label: group.label.trim(), + percent: given(group.commission) ?? 0, + })} +

+ ))}
{example && (
diff --git a/src/pages/organizer/events/components/wizard/WizardSummary.tsx b/src/pages/organizer/events/components/wizard/WizardSummary.tsx index b0b06509..a2ac1677 100644 --- a/src/pages/organizer/events/components/wizard/WizardSummary.tsx +++ b/src/pages/organizer/events/components/wizard/WizardSummary.tsx @@ -50,6 +50,7 @@ interface SummaryValues { maxItemsTotal?: number; maxFeesPerSeller?: number; intakeFee?: number; + feeGroups?: { id: string; label: string; commission: number }[]; registrationOpen?: boolean; }; sellerLogistics?: { @@ -164,6 +165,15 @@ export function WizardSummary({ onEdit }: { onEdit: (step: SummaryStep) => void maxFees !== undefined ? t('wizard.summary.maxFees', { fee: formatPriceDE(maxFees) }) : undefined, + // "Vereinsmitglieder: 5 %" + ...(features.feeGroups ?? []) + .filter((group) => group.label.trim()) + .map((group) => + t('wizard.summary.feeGroup', { + label: group.label.trim(), + percent: given(group.commission) ?? 0, + }) + ), ].filter(Boolean); const joining = [ diff --git a/src/pages/organizer/events/dashboard/CheckoutPage.tsx b/src/pages/organizer/events/dashboard/CheckoutPage.tsx index e83d5577..7931e5f2 100644 --- a/src/pages/organizer/events/dashboard/CheckoutPage.tsx +++ b/src/pages/organizer/events/dashboard/CheckoutPage.tsx @@ -74,6 +74,8 @@ export type ResolvedLine = /** Direct sale with a fee cap: the seller and what is left of their cap */ sellerId?: Id<'users'>; feeCapLeft?: number; + /** The seller's commission when their fee group has its own (#302) */ + commissionPercent?: number; /** For the offline queue: what the desk sold and why at this price */ productId: Id<'products'>; title: string; @@ -555,7 +557,17 @@ function CashDesk() {
{directSale - ? t('checkout.direct.sum', { count: cart.length, percent: commissionPercent }) + ? ready.some( + (line) => + line.commissionPercent !== undefined && + line.commissionPercent !== commissionPercent + ) + ? // Sellers of fee groups pay their own percentage + t('checkout.direct.sumMixed', { count: cart.length }) + : t('checkout.direct.sum', { + count: cart.length, + percent: commissionPercent, + }) : t('checkout.sum', { count: cart.length })} {formatPriceDE(taken)} € @@ -681,6 +693,7 @@ function CartLine({ productId: entry.productId, sellerId: item.sellerId, feeCapLeft: item.feeCapLeft, + commissionPercent: item.commissionPercent, invoice: { description: item.attributes.map((a) => `${a.label}: ${a.value}`).join(', '), image: item.image ?? undefined, @@ -777,7 +790,7 @@ function CartLine({ {directSale && ( )} diff --git a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx index bedfb2c0..d4940b35 100644 --- a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx @@ -71,6 +71,7 @@ import { type SellerPrintoutKind, } from '../../../../lib/sellerPrintout'; import { SellerIdCheck } from '../../../../components/sellers/SellerIdCheck'; +import { FeeGroupCheck } from '../../../../components/sellers/FeeGroupCheck'; import { useAssignMissingSellerNumbers } from '../../../../hooks/useAssignMissingSellerNumbers'; import { matchingVendors, productMatcher } from '../../../../lib/productSearch'; import { addToCachedCart } from '../../../../lib/checkout'; @@ -882,6 +883,12 @@ export function ProductManagementPage() { {selectedVendor.detailsRecorded === false && ( )} + {/* A self-declared fee group: confirm or remove it before the intake */} +
{selectedVendor.sortCode !== undefined && ( @@ -940,7 +947,11 @@ export function ProductManagementPage() {
+ {activeFilter === 'groups' && pendingGroups > 0 && ( +

+ {t('sellerFeeGroup.pendingCount', { count: pendingGroups })} +

+ )} + {/* Table only where it fits; the side menu takes room on tablets, too */}
@@ -264,9 +301,7 @@ export function SellerManagementPage() { {filteredVendors.length === 0 ? ( - {activeFilter === 'helpers' && !searchTerm - ? t('sellers.noHelpers') - : t('sellers.noneForFilter')} + {emptyText ?? t('sellers.noneForFilter')} ) : ( @@ -293,6 +328,7 @@ export function SellerManagementPage() { {v.managedByEventId && } {v.excluded && } + {v.isHelper && !isOwner && ( )} @@ -329,23 +365,33 @@ export function SellerManagementPage() { - {isOwner ? ( - - {t('sellers.owner')} - - ) : v.isHelper ? ( - - - {t('sellers.helpers')} + + {isOwner ? ( + + {t('sellers.owner')} - {canManageHelpers && ( - setHelperAction({ mode: 'edit', vendor: v })} - /> - )} - - ) : null} + ) : v.isHelper ? ( + + + {t('sellers.helpers')} + + {canManageHelpers && ( + setHelperAction({ mode: 'edit', vendor: v })} + /> + )} + + ) : null} + {canManageHelpers && ( + } + vendor={v} + groups={feeGroups} + iconOnly + /> + )} + @@ -361,9 +407,7 @@ export function SellerManagementPage() {
{filteredVendors.length === 0 ? (
- {activeFilter === 'helpers' && !searchTerm - ? t('sellers.noHelpers') - : t('sellers.none')} + {emptyText ?? t('sellers.none')}
) : ( filteredVendors.map((v) => { @@ -389,6 +433,7 @@ export function SellerManagementPage() { {v.managedByEventId && } {v.excluded && } + {isOwner && } {v.isHelper && !isOwner && ( @@ -415,10 +460,17 @@ export function SellerManagementPage() {
- {canManageHelpers && !isOwner && v.isHelper && ( -
- setHelperAction({ mode: 'edit', vendor: v })} + {canManageHelpers && ((!isOwner && v.isHelper) || feeGroups.length > 0) && ( +
+ {!isOwner && v.isHelper && ( + setHelperAction({ mode: 'edit', vendor: v })} + /> + )} + } + vendor={v} + groups={feeGroups} />
)} diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index 4894b6e2..2a8c01f5 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -189,6 +189,15 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { title={t('summary.maxFees', { amount: formatPriceDE(features.maxFeesPerSeller) })} /> )} + {(features.feeGroups?.length ?? 0) > 0 && ( + group.label).join(', '), + })} + /> + )} | undefined; onConfirm: (options?: { locationCategoryId?: Id<'eventLocationCategories'>; internalNote?: string; @@ -44,6 +47,7 @@ export function InventoryConfirmDialog({ locationCategories, initialNote, idCheck, + feeGroupCheck, onConfirm, isSubmitting, }: InventoryConfirmDialogProps) { @@ -127,6 +131,7 @@ export function InventoryConfirmDialog({ }} > {type === 'markAvailable' && idCheck && } + {type === 'markAvailable' && feeGroupCheck && } {showLocationSelect && (
- {t('settle.commission', { percent: commissionPercent })} + {vendor.feeGroup + ? t('settle.commissionGroup', { + percent: commissionPercent, + group: vendor.feeGroup.label, + }) + : t('settle.commission', { percent: commissionPercent })}
{vendor.commission > 0 ? '−' : ''} diff --git a/src/pages/public/events/PublicEventPage.tsx b/src/pages/public/events/PublicEventPage.tsx index 951e3c42..a9289a79 100644 --- a/src/pages/public/events/PublicEventPage.tsx +++ b/src/pages/public/events/PublicEventPage.tsx @@ -425,7 +425,11 @@ export function PublicEventLanding({ eventId, onNavigate }: PublicEventLandingPr )}
- +
- {t('mySales.bazaarFee', { percent: group.event.commissionPercent })} + {group.event.feeGroup + ? t('mySales.bazaarFeeGroup', { + percent: group.event.commissionPercent, + group: group.event.feeGroup, + }) + : t('mySales.bazaarFee', { percent: group.event.commissionPercent })}
{group.totals.commission > 0 ? '−' : ''} diff --git a/src/shared/eventFeatures.ts b/src/shared/eventFeatures.ts index 3ad17014..f26ccbdb 100644 --- a/src/shared/eventFeatures.ts +++ b/src/shared/eventFeatures.ts @@ -1,6 +1,7 @@ import type { LabelFormat, LabelMark } from './constants'; import type { ErrorCode } from './errorCodes'; import type { CategoryField } from './categoryFields'; +import type { FeeGroup } from './feeGroups'; /** * Per-event feature switches chosen by the organizer. Pure helpers only, so the * frontend can import this file as well. @@ -59,6 +60,11 @@ export interface EventFeatures { * together (src/shared/feeCap.ts); unset means no cap. */ maxFeesPerSeller?: number; + /** + * Sellers with own fees, e.g. club members or helpers (src/shared/feeGroups.ts, #302); + * unset means none. + */ + feeGroups?: FeeGroup[]; /** Sellers confirm when joining that they sell as private persons, not as traders. */ privateSellersOnly: boolean; /** diff --git a/src/shared/feeGroups.test.ts b/src/shared/feeGroups.test.ts new file mode 100644 index 00000000..2a197b1e --- /dev/null +++ b/src/shared/feeGroups.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest'; +import { appliedGroup, compareFees, groupFees, type FeeGroup } from './feeGroups'; + +// The same cases as the tests of backend/src/modules/fee_groups.rs +const members: FeeGroup = { + id: 'members', + label: 'Mitglieder', + commission: 5, + assignment: 'selfDeclared', + proofHint: 'Ausweis zeigen', +}; +const helpers: FeeGroup = { + id: 'helpers', + label: 'Helfer', + commission: 0, + intakeFee: 0.5, + maxItemsPerSeller: 40, + assignment: 'helpers', +}; +const event = { + commission: 10, + features: { + intakeFee: 1, + maxFeesPerSeller: 20, + maxItemsPerSeller: 20, + feeGroups: [members, helpers], + }, +}; + +describe('fee groups', () => { + it('have their own fees and fall back to the bazaar for cap and item limit', () => { + expect(groupFees(event, members)).toEqual({ + commission: 5, + intakeFee: undefined, + maxFeesPerSeller: 20, + maxItemsPerSeller: 20, + }); + expect(groupFees(event, helpers).maxItemsPerSeller).toBe(40); + }); + + it('give who is in two groups the cheapest', () => { + expect(appliedGroup(event, undefined, false)).toBeUndefined(); + expect(appliedGroup(event, 'gone', false)).toBeUndefined(); + expect(appliedGroup(event, 'members', false)).toBe(members); + expect(appliedGroup(event, undefined, true)).toBe(helpers); + expect(appliedGroup(event, 'members', true)).toBe(helpers); + }); + + it('compare by commission, then intake fee, then cap', () => { + expect(compareFees({ commission: 5 }, { commission: 6, intakeFee: 0 })).toBeLessThan(0); + expect(compareFees({ commission: 5, intakeFee: 1 }, { commission: 5 })).toBeGreaterThan(0); + expect(compareFees({ commission: 5, maxFeesPerSeller: 10 }, { commission: 5 })).toBeLessThan(0); + }); +}); diff --git a/src/shared/feeGroups.ts b/src/shared/feeGroups.ts new file mode 100644 index 00000000..57fe337b --- /dev/null +++ b/src/shared/feeGroups.ts @@ -0,0 +1,96 @@ +/** + * Fee groups (features.feeGroups, #302): sellers with own fees instead of the bazaar's, + * e.g. club members or helpers. Each group has its own fees ("5 % instead of 10 %"), not a + * discount. The backend has the same rules (backend/src/modules/fee_groups.rs). + */ + +/** How a seller gets into a group */ +export type FeeGroupAssignment = 'selfDeclared' | 'helpers'; + +export interface FeeGroup { + id: string; + /** Chosen by the organizer, e.g. "Vereinsmitglieder" or "Helfer" */ + label: string; + /** Percent of each sale for this group */ + commission: number; + /** € per accepted item; unset: no intake fee */ + intakeFee?: number; + /** Own fee cap; unset: the bazaar's */ + maxFeesPerSeller?: number; + /** Own item limit per seller; unset: the bazaar's */ + maxItemsPerSeller?: number; + /** + * `selfDeclared`: the seller says so when joining, the team checks it at the intake. + * `helpers`: everyone with a helper role, and whom the organizer puts in by hand. + */ + assignment: FeeGroupAssignment; + /** Shown to sellers, e.g. "Mitgliedsausweis bei der Abgabe zeigen" */ + proofHint?: string; +} + +export const MAX_FEE_GROUPS = 10; + +/** The fees one seller pays: the bazaar's or those of their group. */ +export interface GroupFees { + commission: number; + intakeFee?: number; + maxFeesPerSeller?: number; + maxItemsPerSeller?: number; +} + +interface FeesEvent { + commission: number; + features?: { + intakeFee?: number; + maxFeesPerSeller?: number; + maxItemsPerSeller?: number; + feeGroups?: FeeGroup[]; + }; +} + +export function eventFees(event: FeesEvent): GroupFees { + const features = event.features ?? {}; + return { + commission: event.commission, + intakeFee: features.intakeFee && features.intakeFee > 0 ? features.intakeFee : undefined, + maxFeesPerSeller: features.maxFeesPerSeller, + maxItemsPerSeller: features.maxItemsPerSeller, + }; +} + +/** The fees of a group; cap and item limit fall back to the bazaar's. */ +export function groupFees(event: FeesEvent, group: FeeGroup): GroupFees { + const base = eventFees(event); + return { + commission: group.commission, + intakeFee: group.intakeFee && group.intakeFee > 0 ? group.intakeFee : undefined, + maxFeesPerSeller: group.maxFeesPerSeller ?? base.maxFeesPerSeller, + maxItemsPerSeller: group.maxItemsPerSeller ?? base.maxItemsPerSeller, + }; +} + +/** Lower commission first, then lower intake fee, then lower cap (as the backend sorts). */ +export function compareFees(a: GroupFees, b: GroupFees): number { + return ( + a.commission - b.commission || + (a.intakeFee ?? 0) - (b.intakeFee ?? 0) || + (a.maxFeesPerSeller ?? Infinity) - (b.maxFeesPerSeller ?? Infinity) || + 0 + ); +} + +/** The group whose fees apply: the chosen one and, for helpers, the helper groups; the cheapest. */ +export function appliedGroup( + event: FeesEvent, + chosen: string | undefined, + helper: boolean +): FeeGroup | undefined { + return (event.features?.feeGroups ?? []) + .filter((group) => group.id === chosen || (helper && group.assignment === 'helpers')) + .sort((a, b) => compareFees(groupFees(event, a), groupFees(event, b)))[0]; +} + +/** A new id for a group: short, URL-safe, unique enough within one bazaar */ +export function newFeeGroupId(): string { + return `g${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; +} diff --git a/src/tests/auth/fee-groups.spec.ts b/src/tests/auth/fee-groups.spec.ts new file mode 100644 index 00000000..4705529d --- /dev/null +++ b/src/tests/auth/fee-groups.spec.ts @@ -0,0 +1,86 @@ +import { test, expect } from '@playwright/test'; +import { runBackend } from '../utils'; +import { + OTHER_BUYER, + ORGANIZER, + createShowcase, + expectToast, + login, + loginAs, +} from '../helpers/features'; + +/** + * Fee groups (#302): the organizer sets up a group, a seller says they belong to it when + * registering, and the intake checks it before the first item. + */ + +test.beforeAll(() => { + runBackend('featureFlags.set', { key: 'is_e2e_auth_skip_email', value: true }); +}); + +test.describe.configure({ timeout: 120_000 }); + +test('a self-declared fee group is chosen at registration and checked at the intake', async ({ + page, +}, testInfo) => { + const showcase = createShowcase(testInfo, 'FeeGroups'); + + // The showcase runs already: only the platform admin may still change its fees + await login(page, 'admin@bazarpro.de'); + await page.goto(`/events/view/${showcase.eventId}/settings`); + await page.getByRole('button', { name: 'Gebührengruppe hinzufügen' }).click(); + await page.getByLabel('Name der Gruppe').fill('Vereinsmitglieder'); + await page.getByLabel('Provision', { exact: true }).last().fill('5'); + await page.getByLabel('Nachweis (optional)').fill('Mitgliedsausweis zeigen'); + await page.getByRole('button', { name: 'Speichern' }).click(); + await expectToast(page, 'Basar gespeichert'); + + // The seller sees the group in the conditions and chooses it + const seller = await loginAs(page, OTHER_BUYER); + await seller.goto(`/public-events/${showcase.eventId}`); + await seller.getByRole('button', { name: 'Als Verkäufer anmelden' }).click(); + const dialog = seller.getByRole('dialog'); + // The demo buyer has neither phone nor address; nobody else registers them in parallel + const confirm = dialog.getByRole('button', { name: 'Anmelden bestätigen' }); + const phone = dialog.getByRole('textbox', { name: 'Telefonnummer' }); + await expect(confirm.or(phone)).toBeVisible(); + if (await phone.isVisible()) { + await phone.fill('0123456789'); + await dialog.getByRole('button', { name: 'Weiter' }).click(); + } + const street = dialog.getByRole('textbox', { name: 'Straße und Hausnummer' }); + await expect(confirm.or(street)).toBeVisible(); + if (await street.isVisible()) { + await street.fill('Musterstraße 1'); + await dialog.getByRole('textbox', { name: 'Postleitzahl' }).fill('89073'); + await dialog.getByRole('textbox', { name: 'Ort' }).fill('Ulm'); + await dialog.getByRole('button', { name: 'Adresse speichern' }).click(); + } + await expect(confirm).toBeVisible(); + await expect(dialog.getByTestId('fee-groups')).toContainText( + 'Vereinsmitglieder: 5 % Provision statt 10 %' + ); + await dialog.getByTestId('fee-group-choice').getByText('Vereinsmitglieder').click(); + await dialog.getByRole('button', { name: 'Anmelden bestätigen' }).click(); + await expect(seller.getByText(/^Anmeldung erfolgreich!/)).toBeVisible(); + await seller.goto(`/public-events/${showcase.eventId}`); + await expect(seller.getByTestId('my-fee-group')).toContainText('Deine Gruppe: Vereinsmitglieder'); + await expect(seller.getByTestId('my-fee-group')).toContainText('prüft deine Angabe'); + + // The organizer sees the unchecked self-declaration and confirms it at the intake + const organizer = await loginAs(page, ORGANIZER); + await organizer.goto(`/events/view/${showcase.eventId}/sellers`); + await organizer.getByRole('tab', { name: /Gruppen/ }).click(); + await expect(organizer.getByText('1 Selbstauskunft ist noch nicht geprüft')).toBeVisible(); + const row = organizer.getByRole('row', { name: /Vereinsmitglieder · prüfen/ }); + await row.click(); + const check = organizer.getByTestId('fee-group-check'); + await expect(check).toContainText('Ermäßigt: Vereinsmitglieder – Nachweis prüfen'); + await expect(check).toContainText('Mitgliedsausweis zeigen'); + await check.getByRole('button', { name: 'Bestätigen' }).click(); + await expectToast(organizer, 'Vereinsmitglieder bestätigt'); + await expect(check).toBeHidden(); + + await seller.reload(); + await expect(seller.getByTestId('my-fee-group')).toContainText('Vom Team bestätigt'); +}); diff --git a/src/tests/helpers/profile.ts b/src/tests/helpers/profile.ts index 98dba3d8..61639a37 100644 --- a/src/tests/helpers/profile.ts +++ b/src/tests/helpers/profile.ts @@ -24,7 +24,9 @@ export async function fillProfileForm(page: Page) { await street.fill('Musterstrasse 1', { timeout: 2000 }); await page.getByRole('textbox', { name: 'Postleitzahl' }).fill('12345', { timeout: 2000 }); await page.getByRole('textbox', { name: 'Ort' }).fill('de', { timeout: 2000 }); - await page.getByRole('textbox', { name: 'Land' }).fill('de', { timeout: 2000 }); + // The country is a select by now, which keeps its default + const country = page.getByRole('textbox', { name: 'Land' }); + if (await country.count()) await country.fill('de', { timeout: 2000 }); await page.getByRole('button', { name: /speichern/i }).click({ timeout: 2000 }); } } catch { From f121c18189f92849bff7fa7297e5c0f3326367ea Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 22:17:53 +0100 Subject: [PATCH 03/10] test(fees): fee group components, so branch coverage stays above 80 % (#302) Co-Authored-By: Claude Opus 5.5 --- src/components/events/FeeGroups.test.tsx | 126 +++++++++++++++ src/components/sellers/FeeGroupCheck.test.tsx | 148 ++++++++++++++++++ .../components/EditEventFeeGroups.test.tsx | 101 ++++++++++++ 3 files changed, 375 insertions(+) create mode 100644 src/components/events/FeeGroups.test.tsx create mode 100644 src/components/sellers/FeeGroupCheck.test.tsx create mode 100644 src/pages/organizer/events/components/EditEventFeeGroups.test.tsx diff --git a/src/components/events/FeeGroups.test.tsx b/src/components/events/FeeGroups.test.tsx new file mode 100644 index 00000000..b95b67fd --- /dev/null +++ b/src/components/events/FeeGroups.test.tsx @@ -0,0 +1,126 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { toast } from 'sonner'; +import { useMutation, useQuery } from '../../lib/api/react'; +import type { Id, MyFeeGroup as MyGroup } from '../../lib/api/types'; +import { describeFeeGroups, type SellerConditionsEvent } from '../../lib/sellerFees'; +import { FeeGroupChoice, FeeGroupList, MyFeeGroup } from './FeeGroups'; + +vi.mock('../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn() })); +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); + +const EVENT = 'evt1' as Id<'events'>; +const event: SellerConditionsEvent = { + commission: 10, + features: { + intakeFee: 1, + feeGroups: [ + { + id: 'members', + label: 'Vereinsmitglieder', + commission: 5, + assignment: 'selfDeclared', + proofHint: 'Ausweis zeigen', + }, + { id: 'helpers', label: 'Helfer', commission: 0, assignment: 'helpers' }, + ], + }, +}; +const choose = vi.fn(); +let mine: MyGroup | null | undefined; + +beforeEach(() => { + choose.mockReset().mockResolvedValue(null); + vi.mocked(useMutation).mockReturnValue(choose as unknown as ReturnType); + vi.mocked(useQuery).mockImplementation((() => mine) as unknown as typeof useQuery); + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + } + ); +}); + +describe('FeeGroupList', () => { + it('lists every group with its fees and how to get in', () => { + render(); + expect(screen.getByText('Eigene Gebühren für')).toBeInTheDocument(); + expect(screen.getByText('Nachweis bei der Abgabe: Ausweis zeigen')).toBeInTheDocument(); + expect(screen.getByText('Gilt für Helfer des Basars')).toBeInTheDocument(); + }); + + it('shows nothing without groups', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); +}); + +describe('FeeGroupChoice', () => { + it('offers only the self-declared groups and no group', () => { + const onChange = vi.fn(); + render(); + expect(screen.getByLabelText(/Nein, ich zahle die normalen Gebühren/)).toBeChecked(); + expect(screen.queryByLabelText(/Helfer/)).not.toBeInTheDocument(); + fireEvent.click(screen.getByLabelText(/Vereinsmitglieder/)); + expect(onChange).toHaveBeenCalledWith('members'); + }); + + it('goes back to no group', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByLabelText(/Nein, ich zahle/)); + expect(onChange).toHaveBeenCalledWith(null); + }); + + it('is not there without self-declared groups', () => { + const helpersOnly = { + ...event, + features: { feeGroups: [event.features!.feeGroups![1]] }, + }; + const { container } = render( + + ); + expect(container).toBeEmptyDOMElement(); + }); +}); + +describe('MyFeeGroup', () => { + it('shows a group still to be checked and changes it', async () => { + mine = { chosen: 'members', applied: 'members', pending: true, locked: false }; + render(); + expect(screen.getByText('Deine Gruppe: Vereinsmitglieder')).toBeInTheDocument(); + expect(screen.getByText('Das Team prüft deine Angabe bei der Abgabe.')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Ändern' })); + fireEvent.click(screen.getByLabelText(/Nein, ich zahle/)); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => expect(choose).toHaveBeenCalledWith({ eventId: EVENT, groupId: null })); + await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Gespeichert')); + }); + + it('reports when the choice is refused', async () => { + mine = { pending: false, locked: false }; + choose.mockRejectedValue(new Error('nope')); + render(); + expect(screen.getByText('Du zahlst die normalen Gebühren.')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Gruppe angeben' })); + fireEvent.click(screen.getByLabelText(/Vereinsmitglieder/)); + fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); + await waitFor(() => expect(toast.error).toHaveBeenCalled()); + }); + + it('only names the team once the group is fixed', () => { + mine = { chosen: 'members', applied: 'members', pending: false, locked: true, decidedAt: 1 }; + render(); + expect(screen.getByText('Vom Team bestätigt.')).toBeInTheDocument(); + expect(screen.getByText('Für eine Änderung sprich bitte das Team an.')).toBeInTheDocument(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + }); + + it('shows nothing to sellers outside the bazaar', () => { + mine = null; + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/src/components/sellers/FeeGroupCheck.test.tsx b/src/components/sellers/FeeGroupCheck.test.tsx new file mode 100644 index 00000000..60de77bc --- /dev/null +++ b/src/components/sellers/FeeGroupCheck.test.tsx @@ -0,0 +1,148 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { toast } from 'sonner'; +import { useMutation } from '../../lib/api/react'; +import { getFunctionName } from '../../lib/api/functions'; +import type { Id, VendorWithCalculations } from '../../lib/api/types'; +import type { FeeGroup } from '../../shared/feeGroups'; +import { FeeGroupCheck } from './FeeGroupCheck'; +import { FeeGroupBadge, FeeGroupMenu } from './FeeGroupBadge'; + +vi.mock('../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn() })); +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); + +const EVENT = 'evt1' as Id<'events'>; +const groups: FeeGroup[] = [ + { + id: 'members', + label: 'Vereinsmitglieder', + commission: 5, + assignment: 'selfDeclared', + proofHint: 'Ausweis zeigen', + }, + { id: 'helpers', label: 'Helfer', commission: 0, assignment: 'helpers' }, +]; +const vendor = (feeGroup?: VendorWithCalculations['feeGroup'], paid = false) => + ({ _id: 'u1', name: 'Anna', paid, feeGroup }) as unknown as VendorWithCalculations; +const calls: Record> = {}; + +beforeEach(() => { + for (const key of Object.keys(calls)) delete calls[key]; + vi.mocked(useMutation).mockImplementation(((fn: unknown) => { + const name = getFunctionName(fn); + calls[name] ??= vi.fn().mockResolvedValue(null); + return calls[name]; + }) as unknown as typeof useMutation); +}); + +const pending = { id: 'members', label: 'Vereinsmitglieder', pending: true, byRole: false }; + +describe('FeeGroupCheck', () => { + it('asks for the proof and confirms the group', async () => { + render(); + expect(screen.getByText('Ermäßigt: Vereinsmitglieder – Nachweis prüfen')).toBeInTheDocument(); + expect(screen.getByText(/Nachweis: Ausweis zeigen/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Bestätigen' })); + await waitFor(() => + expect(calls['feeGroups.confirmFeeGroup']).toHaveBeenCalledWith({ + eventId: EVENT, + sellerId: 'u1', + }) + ); + expect(toast.success).toHaveBeenCalledWith('Vereinsmitglieder bestätigt'); + }); + + it('removes the group without proof', async () => { + const noHint = { ...pending, id: 'other' }; + calls['feeGroups.removeFeeGroup'] = vi.fn().mockRejectedValue(new Error('x')); + render(); + expect(screen.getByText(/Der Verkäufer hat angegeben/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Entfernen' })); + await waitFor(() => expect(toast.error).toHaveBeenCalled()); + }); + + it('is not there for a checked group', () => { + const { container } = render( + + ); + expect(container).toBeEmptyDOMElement(); + }); +}); + +describe('FeeGroupBadge', () => { + it('names the group and whether it is still to be checked', () => { + const { rerender } = render(); + expect(screen.getByText('Vereinsmitglieder')).toBeInTheDocument(); + expect(screen.getByText('· prüfen')).toBeInTheDocument(); + rerender(); + expect(screen.queryByText('· prüfen')).not.toBeInTheDocument(); + rerender(); + expect(screen.queryByText('Vereinsmitglieder')).not.toBeInTheDocument(); + }); +}); + +describe('FeeGroupMenu', () => { + it('puts a seller in a group and takes them out', async () => { + render(); + const open = () => + fireEvent.pointerDown(screen.getByRole('button', { name: 'Gebührengruppe zuordnen' }), { + button: 0, + ctrlKey: false, + }); + open(); + fireEvent.click(await screen.findByRole('menuitemradio', { name: 'Helfer' })); + await waitFor(() => + expect(calls['feeGroups.assignFeeGroup']).toHaveBeenCalledWith({ + eventId: EVENT, + sellerId: 'u1', + groupId: 'helpers', + }) + ); + expect(toast.success).toHaveBeenCalledWith('Anna: Helfer'); + }); + + it('explains a group by role and takes the chosen one out', async () => { + render( + + ); + fireEvent.pointerDown(screen.getByRole('button', { name: 'Gebührengruppe zuordnen' }), { + button: 0, + ctrlKey: false, + }); + expect(await screen.findByText(/gilt durch die Helferrolle/)).toBeInTheDocument(); + expect(screen.getByRole('menuitemradio', { name: 'Vereinsmitglieder' })).toBeChecked(); + fireEvent.click(screen.getByRole('menuitemradio', { name: 'Keine Gruppe' })); + await waitFor(() => + expect(calls['feeGroups.assignFeeGroup']).toHaveBeenCalledWith({ + eventId: EVENT, + sellerId: 'u1', + groupId: null, + }) + ); + expect(toast.success).toHaveBeenCalledWith('Anna: keine Gruppe'); + }); + + it('is not offered for paid-out sellers or without groups', () => { + const { container, rerender } = render( + + ); + expect(container).toBeEmptyDOMElement(); + rerender(); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx b/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx new file mode 100644 index 00000000..f651c83f --- /dev/null +++ b/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx @@ -0,0 +1,101 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { FormProvider, useForm } from 'react-hook-form'; +import type { FeeLock } from '../../../../lib/sellerFees'; +import { EditEventFeeGroups, type FeeGroupForm } from './EditEventFeeGroups'; + +let current: FeeGroupForm[] = []; +const members: FeeGroupForm = { + id: 'members', + label: 'Vereinsmitglieder', + commission: 5, + intakeFee: 1, + maxFeesPerSeller: 15, + maxItemsPerSeller: 30, + assignment: 'selfDeclared', + proofHint: 'Ausweis zeigen', +}; + +// One object for every render: a new one each time would reset the form again and again +const LABEL_ERROR = { + features: { feeGroups: [{ label: { type: 'custom', message: 'Name fehlt' } }] }, +}; + +function Form({ + groups = [] as FeeGroupForm[], + feeLock = null as FeeLock, + registeredIds = [] as string[], + error = false, +}) { + const methods = useForm({ + defaultValues: { + commission: 10, + features: { maxFeesPerSeller: 20, maxItemsPerSeller: 20, feeGroups: groups }, + }, + errors: error ? LABEL_ERROR : undefined, + }); + current = methods.watch('features.feeGroups'); + return ( + + + + ); +} + +describe('EditEventFeeGroups', () => { + it("adds a group with the bazaar's commission and opens it", () => { + render(
); + expect(screen.getByText(/Alle Verkäufer zahlen dieselben Gebühren/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Gebührengruppe hinzufügen' })); + expect(screen.getByText('Neue Gruppe')).toBeInTheDocument(); + expect(screen.getByPlaceholderText('wie Basar (20,00 €)')).toBeInTheDocument(); + expect(screen.getByPlaceholderText('wie Basar (20)')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Name der Gruppe'), { target: { value: 'Helfer' } }); + fireEvent.change(screen.getByLabelText('Wer gehört dazu?'), { target: { value: 'helpers' } }); + expect(current[0]).toMatchObject({ label: 'Helfer', commission: 10, assignment: 'helpers' }); + // Helpers bring no proof + expect(screen.queryByLabelText('Nachweis (optional)')).not.toBeInTheDocument(); + }); + + it('shows a group in short and removes it', () => { + render(); + expect( + screen.getByText( + '5 % Provision · 1,00 € pro Artikel · höchstens 15,00 € · 30 Artikel · Angabe bei der Anmeldung' + ) + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Vereinsmitglieder/ })); + expect(screen.getByLabelText('Nachweis (optional)')).toHaveValue('Ausweis zeigen'); + fireEvent.click(screen.getByRole('button', { name: 'Gruppe entfernen' })); + expect(current).toEqual([]); + }); + + it('keeps a group sellers registered with', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: /Vereinsmitglieder/ })); + expect(screen.getByRole('button', { name: 'Gruppe entfernen' })).toBeDisabled(); + expect(screen.getByLabelText('Wer gehört dazu?')).toBeDisabled(); + expect( + screen.getByText(/Verkäufer haben sich mit dieser Gruppe angemeldet/) + ).toBeInTheDocument(); + }); + + it('is fixed while the bazaar runs and opens a group with an error', () => { + const noFees = { + ...members, + intakeFee: NaN, + maxFeesPerSeller: NaN, + maxItemsPerSeller: NaN, + label: '', + }; + render(); + expect( + screen.queryByRole('button', { name: 'Gebührengruppe hinzufügen' }) + ).not.toBeInTheDocument(); + expect(screen.getByText('Name fehlt')).toBeInTheDocument(); + expect( + screen.getByText('5 % Provision · keine Annahmegebühr · Angabe bei der Anmeldung') + ).toBeInTheDocument(); + expect(screen.getByLabelText('Provision')).toHaveAttribute('readonly'); + }); +}); From f0c471681eeace6f5d9e37df3eb18a2e4aa13d1e Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 18 Nov 2026 22:50:23 +0100 Subject: [PATCH 04/10] fix(fees): wizard drafts keep empty fee fields, autosave, only a group's advantages (#302) - A draft saved on the server turned empty number fields into null, which the form refused when continuing: they are left out now, and older drafts lose their nulls when restored - Every change of the wizard waits in this browser; "continue later" moved from the bottom bar to the header, so the bar is one row on phones - Conditions, preview, summary and the editor name only what a group changes against the bazaar, e.g. just "up to 40 items" - Fee group fields read better on phones: shorter labels and choices Co-Authored-By: Claude Opus 5.5 --- src/lib/eventDraft.test.ts | 22 ++++ src/lib/eventDraft.ts | 32 ++++- src/lib/sellerFees.test.ts | 46 ++++++- src/lib/sellerFees.ts | 114 ++++++++++++------ src/locales/de/events.json | 5 +- src/locales/de/organizer.json | 14 +-- src/locales/en/events.json | 5 +- src/locales/en/organizer.json | 12 +- src/pages/organizer/events/EditEventForm.tsx | 103 +++++++++++----- .../components/EditEventFeeGroups.test.tsx | 4 +- .../events/components/EditEventFeeGroups.tsx | 39 +++--- .../components/wizard/WizardPreviews.tsx | 6 +- .../components/wizard/WizardSummary.tsx | 6 +- 13 files changed, 291 insertions(+), 117 deletions(-) create mode 100644 src/lib/eventDraft.test.ts diff --git a/src/lib/eventDraft.test.ts b/src/lib/eventDraft.test.ts new file mode 100644 index 00000000..032b0abb --- /dev/null +++ b/src/lib/eventDraft.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { draftJson, withoutNulls } from './eventDraft'; + +describe('event drafts', () => { + it('leave out empty numbers, which JSON would turn into null', () => { + const values = { + commission: 10, + features: { maxFeesPerSeller: NaN, feeGroups: [{ id: 'g', intakeFee: NaN, commission: 5 }] }, + }; + expect(draftJson(values)).toEqual({ + commission: 10, + features: { feeGroups: [{ id: 'g', commission: 5 }] }, + }); + }); + + it('drop the nulls of older drafts, which no field accepts', () => { + expect( + withoutNulls({ intakeFee: null, feeGroups: [{ id: 'g', maxItemsPerSeller: null }], ok: 1 }) + ).toEqual({ feeGroups: [{ id: 'g' }], ok: 1 }); + expect(withoutNulls('text')).toBe('text'); + }); +}); diff --git a/src/lib/eventDraft.ts b/src/lib/eventDraft.ts index 54765f1b..cfe7ddbe 100644 --- a/src/lib/eventDraft.ts +++ b/src/lib/eventDraft.ts @@ -18,15 +18,39 @@ export interface EventDraft { step?: number; /** The guest finished the wizard: only then the sign-up creates the bazaar by itself */ submitted?: boolean; + /** The draft on the server it continues (its updatedAt), so saving it again asks nothing */ + continues?: number; savedAt: number; } +/** Empty number fields hold NaN, which JSON would turn into null: leave them out */ +const leaveOutNaN = (_key: string, value: unknown) => + typeof value === 'number' && Number.isNaN(value) ? undefined : value; + +/** The values as JSON keeps them, for the draft on the server: without empty numbers. */ +export function draftJson(value: T): T { + return JSON.parse(JSON.stringify(value, leaveOutNaN)) as T; +} + +/** + * A stored draft as the form takes it: drafts saved before empty numbers were left out + * hold null there, which no field accepts (e.g. the fees of a fee group). + */ +export function withoutNulls(value: T): T { + if (Array.isArray(value)) return value.map(withoutNulls) as T; + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value) + .filter(([, entry]) => entry !== null) + .map(([key, entry]) => [key, withoutNulls(entry)]) + ) as T; + } + return value; +} + export function saveEventDraft(draft: Omit, 'savedAt'>) { try { - // Empty number fields hold NaN, which JSON would turn into null: leave them out - const json = JSON.stringify({ ...draft, savedAt: Date.now() }, (_key, value: unknown) => - typeof value === 'number' && Number.isNaN(value) ? undefined : value - ); + const json = JSON.stringify({ ...draft, savedAt: Date.now() }, leaveOutNaN); localStorage.setItem(KEY, json); } catch { // Private mode or full storage: the draft is only lost on the way to the account diff --git a/src/lib/sellerFees.test.ts b/src/lib/sellerFees.test.ts index 12fde8c3..5cfd68b5 100644 --- a/src/lib/sellerFees.test.ts +++ b/src/lib/sellerFees.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { describeFeeGroups, + formGroupAdvantages, describeSellerFees, describeSellerRules, describeSellerSchedule, @@ -138,12 +139,13 @@ describe('describeSellerSchedule', () => { }); describe('describeFeeGroups', () => { - it("names each group with its fees next to the bazaar's and how to get in", () => { + it('names only what a group changes and how to get in', () => { const groups = describeFeeGroups({ commission: 10, features: { intakeFee: 1, maxItemsPerSeller: 20, + maxFeesPerSeller: 20, feeGroups: [ { id: 'members', @@ -152,6 +154,7 @@ describe('describeFeeGroups', () => { assignment: 'selfDeclared', proofHint: 'Mitgliedsausweis zeigen', }, + // Same commission: only the item limit and the intake fee count { id: 'helpers', label: 'Helfer', @@ -160,6 +163,21 @@ describe('describeFeeGroups', () => { maxItemsPerSeller: 40, assignment: 'helpers', }, + { + id: 'kids', + label: 'Schüler', + commission: 10, + intakeFee: 1, + assignment: 'selfDeclared', + }, + { + id: 'cap', + label: 'Profis', + commission: 10, + intakeFee: 1, + maxFeesPerSeller: 10, + assignment: 'selfDeclared', + }, ], }, }); @@ -169,9 +187,33 @@ describe('describeFeeGroups', () => { how: 'Nachweis bei der Abgabe: Mitgliedsausweis zeigen', }, { - fees: '10 % Provision · 0,50 € pro Artikel · bis zu 40 Artikel', + fees: '0,50 € pro Artikel statt 1,00 € · bis zu 40 Artikel', how: 'Gilt für Helfer des Basars', }, + { + fees: 'gleiche Gebühren wie alle', + how: 'Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe', + }, + { + fees: 'höchstens 10,00 € Gebühren', + how: 'Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe', + }, ]); }); + + it('reads the values of the event form, where empty numbers are NaN', () => { + expect( + formGroupAdvantages( + { commission: 10, features: { intakeFee: NaN, maxItemsPerSeller: 20 } }, + { + id: 'g', + label: 'Helfer', + commission: NaN, + intakeFee: 2, + maxItemsPerSeller: NaN, + assignment: 'helpers', + } + ) + ).toBe('0 % Provision statt 10 % · 2,00 € pro Artikel'); + }); }); diff --git a/src/lib/sellerFees.ts b/src/lib/sellerFees.ts index 74f5735b..bdfe1b25 100644 --- a/src/lib/sellerFees.ts +++ b/src/lib/sellerFees.ts @@ -134,44 +134,86 @@ export interface FeeGroupTerms { } /** - * The fee groups as sellers read them (#302): each with its own fees next to the bazaar's, - * so it is clear what changes ("5 % instead of 10 %"). + * What a group changes against the bazaar's fees, in short: only its advantages, e.g. + * "5 % Provision statt 10 %" or just "bis zu 40 Artikel" when the fees are the same. */ -export function describeFeeGroups(event: SellerConditionsEvent): FeeGroupTerms[] { - const groups = event.features?.feeGroups ?? []; +export function feeGroupAdvantages(event: SellerConditionsEvent, group: FeeGroup): string[] { const base = eventFees(event); - return groups.map((group) => { - const fees = groupFees(event, group); - const parts = [ - fees.commission === base.commission - ? text('groupCommission', { percent: formatPercent(fees.commission) }) - : text('groupCommissionInstead', { - percent: formatPercent(fees.commission), - base: formatPercent(base.commission), - }), - fees.intakeFee - ? text('groupIntakeFee', { fee: formatPriceDE(fees.intakeFee) }) - : base.intakeFee - ? text('groupNoIntakeFee') - : undefined, - fees.maxFeesPerSeller !== undefined && fees.maxFeesPerSeller !== base.maxFeesPerSeller - ? text('groupCap', { fee: formatPriceDE(fees.maxFeesPerSeller) }) - : undefined, - fees.maxItemsPerSeller !== undefined && fees.maxItemsPerSeller !== base.maxItemsPerSeller - ? text('groupItems', { count: fees.maxItemsPerSeller }) - : undefined, - ]; - return { - group, - fees: parts.filter(Boolean).join(' · '), - how: - group.assignment === 'helpers' - ? text('groupHelpers') - : group.proofHint - ? text('groupProof', { hint: group.proofHint }) - : text('groupChecked'), - }; - }); + const fees = groupFees(event, group); + const parts = [ + fees.commission !== base.commission + ? text('groupCommissionInstead', { + percent: formatPercent(fees.commission), + base: formatPercent(base.commission), + }) + : undefined, + fees.intakeFee !== base.intakeFee + ? fees.intakeFee + ? base.intakeFee + ? text('groupIntakeFeeInstead', { + fee: formatPriceDE(fees.intakeFee), + base: formatPriceDE(base.intakeFee), + }) + : text('groupIntakeFee', { fee: formatPriceDE(fees.intakeFee) }) + : text('groupNoIntakeFee') + : undefined, + fees.maxFeesPerSeller !== undefined && fees.maxFeesPerSeller !== base.maxFeesPerSeller + ? text('groupCap', { fee: formatPriceDE(fees.maxFeesPerSeller) }) + : undefined, + fees.maxItemsPerSeller !== undefined && fees.maxItemsPerSeller !== base.maxItemsPerSeller + ? text('groupItems', { count: fees.maxItemsPerSeller }) + : undefined, + ].filter((part): part is string => !!part); + // The same as everyone: say so rather than nothing + return parts.length > 0 ? parts : [text('groupSame')]; +} + +const givenNumber = (value: number | undefined) => + typeof value === 'number' && Number.isFinite(value) ? value : undefined; + +/** + * `feeGroupAdvantages` from the values of the event form, where empty numbers are NaN, + * e.g. "5 % Provision statt 10 % · bis zu 40 Artikel". + */ +export function formGroupAdvantages( + values: { + commission?: number; + features?: { intakeFee?: number; maxFeesPerSeller?: number; maxItemsPerSeller?: number }; + }, + group: FeeGroup +): string { + const features = values.features ?? {}; + return feeGroupAdvantages( + { + commission: givenNumber(values.commission) ?? 0, + features: { + intakeFee: givenNumber(features.intakeFee), + maxFeesPerSeller: givenNumber(features.maxFeesPerSeller), + maxItemsPerSeller: givenNumber(features.maxItemsPerSeller), + }, + }, + { + ...group, + commission: givenNumber(group.commission) ?? 0, + intakeFee: givenNumber(group.intakeFee), + maxFeesPerSeller: givenNumber(group.maxFeesPerSeller), + maxItemsPerSeller: givenNumber(group.maxItemsPerSeller), + } + ).join(' · '); +} + +/** The fee groups as sellers read them (#302): each with its advantages and how to get in. */ +export function describeFeeGroups(event: SellerConditionsEvent): FeeGroupTerms[] { + return (event.features?.feeGroups ?? []).map((group) => ({ + group, + fees: feeGroupAdvantages(event, group).join(' · '), + how: + group.assignment === 'helpers' + ? text('groupHelpers') + : group.proofHint + ? text('groupProof', { hint: group.proofHint }) + : text('groupChecked'), + })); } export interface SellerRule { diff --git a/src/locales/de/events.json b/src/locales/de/events.json index 4ee24932..3c825e74 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -126,7 +126,6 @@ "placesLeft_other": "Höchstens {{max}} Artikel auf dem ganzen Basar, noch {{count}} Plätze frei", "marketFull": "Der Basar ist voll: Alle {{max}} Plätze für Artikel sind vergeben", "groupsTitle": "Eigene Gebühren für", - "groupCommission": "{{percent}} % Provision", "groupCommissionInstead": "{{percent}} % Provision statt {{base}} %", "groupIntakeFee": "{{fee}} € pro Artikel", "groupNoIntakeFee": "keine Annahmegebühr", @@ -147,7 +146,9 @@ "choiceNone": "Nein, ich zahle die normalen Gebühren", "choiceHint": "Das Team prüft deine Angabe bei der Abgabe. Ohne Nachweis gelten die normalen Gebühren.", "choiceDialogTitle": "Deine Gebührengruppe", - "choiceSave": "Speichern" + "choiceSave": "Speichern", + "groupIntakeFeeInstead": "{{fee}} € pro Artikel statt {{base}} €", + "groupSame": "gleiche Gebühren wie alle" }, "sidebar": { "details": "Basar-Details", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 9b0fbbc7..f2f47115 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -978,7 +978,7 @@ "maxItemsTotal_one": "max. {{count}} Artikel insgesamt", "maxItemsTotal_other": "max. {{count}} Artikel insgesamt", "maxFees": "höchstens {{fee}} € pro Verkäufer", - "feeGroup": "{{label}}: {{percent}} %" + "feeGroup": "{{label}}: {{advantages}}" }, "fixErrors": "Bitte prüfe die markierten Angaben.", "guestCreate": "Konto anlegen und Basar erstellen", @@ -1059,7 +1059,7 @@ "maxItemsTotal": "{{count}} Plätze für Artikel insgesamt", "feeCap": "Höchstens {{fee}} Gebühren pro Verkäufer", "feeCapExample": "Gebühren-Deckel {{fee}}", - "feeGroup": "{{label}}: {{percent}} %" + "feeGroup": "{{label}}: {{advantages}}" }, "short": { "type": "Art", @@ -1383,7 +1383,7 @@ "labelPlaceholder": "z. B. Vereinsmitglieder", "assignmentLabel": "Wer gehört dazu?", "assignment": { - "selfDeclared": "Verkäufer geben es bei der Anmeldung an", + "selfDeclared": "Angabe bei der Anmeldung", "helpers": "Helfer des Basars", "selfDeclaredShort": "Angabe bei der Anmeldung", "helpersShort": "Helfer", @@ -1392,7 +1392,7 @@ }, "commission": "Provision", "intakeFee": "Annahmegebühr", - "cap": "Gebühren-Deckel", + "cap": "Deckel", "capHint": "Leer: Es gilt der Deckel des Basars.", "items": "Max. Artikel", "itemsHint": "Leer: Es gilt die Grenze des Basars. Die Grenze für den ganzen Markt gilt für alle.", @@ -1404,12 +1404,6 @@ "cheapest": "Wer zu mehreren Gruppen gehört, zahlt die günstigsten Gebühren.", "remove": "Gruppe entfernen", "add": "Gebührengruppe hinzufügen", - "summaryCommission": "{{percent}} % Provision", - "summaryIntakeFee": "{{fee}} € pro Artikel", - "summaryNoIntakeFee": "keine Annahmegebühr", - "summaryCap": "höchstens {{fee}} €", - "summaryItems_one": "{{count}} Artikel", - "summaryItems_other": "{{count}} Artikel", "labelRequired": "Gib der Gruppe einen Namen.", "labelTwice": "Diesen Namen hat schon eine andere Gruppe.", "registeredMax": "Verkäufer haben sich mit dieser Gruppe angemeldet: höchstens {{value}}.", diff --git a/src/locales/en/events.json b/src/locales/en/events.json index 071e7a09..00d6c3cb 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -126,7 +126,6 @@ "placesLeft_other": "At most {{max}} items at the whole bazaar, {{count}} places left", "marketFull": "The bazaar is full: all {{max}} places for items are taken", "groupsTitle": "Own fees for", - "groupCommission": "{{percent}} % commission", "groupCommissionInstead": "{{percent}} % commission instead of {{base}} %", "groupIntakeFee": "{{fee}} € per item", "groupNoIntakeFee": "no intake fee", @@ -147,7 +146,9 @@ "choiceNone": "No, I pay the regular fees", "choiceHint": "The team checks it at the drop-off. Without proof the regular fees apply.", "choiceDialogTitle": "Your fee group", - "choiceSave": "Save" + "choiceSave": "Save", + "groupIntakeFeeInstead": "{{fee}} € per item instead of {{base}} €", + "groupSame": "same fees as everyone" }, "sidebar": { "details": "Bazaar details", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 0e61e786..4260e8a3 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -978,7 +978,7 @@ "maxItemsTotal_one": "max. {{count}} item in total", "maxItemsTotal_other": "max. {{count}} items in total", "maxFees": "at most €{{fee}} per seller", - "feeGroup": "{{label}}: {{percent}} %" + "feeGroup": "{{label}}: {{advantages}}" }, "fixErrors": "Please check the marked details.", "guestCreate": "Sign up and create bazaar", @@ -1059,7 +1059,7 @@ "maxItemsTotal": "{{count}} places for items in total", "feeCap": "At most {{fee}} of fees per seller", "feeCapExample": "Fee cap {{fee}}", - "feeGroup": "{{label}}: {{percent}} %" + "feeGroup": "{{label}}: {{advantages}}" }, "short": { "type": "Kind", @@ -1383,7 +1383,7 @@ "labelPlaceholder": "e.g. Club members", "assignmentLabel": "Who belongs to it?", "assignment": { - "selfDeclared": "Sellers say so when registering", + "selfDeclared": "Given at registration", "helpers": "Helpers of the bazaar", "selfDeclaredShort": "Given at registration", "helpersShort": "Helpers", @@ -1404,12 +1404,6 @@ "cheapest": "Who belongs to several groups pays the cheapest fees.", "remove": "Remove group", "add": "Add fee group", - "summaryCommission": "{{percent}} % commission", - "summaryIntakeFee": "{{fee}} € per item", - "summaryNoIntakeFee": "no intake fee", - "summaryCap": "at most {{fee}} €", - "summaryItems_one": "{{count}} item", - "summaryItems_other": "{{count}} items", "labelRequired": "Give the group a name.", "labelTwice": "Another group already has this name.", "registeredMax": "Sellers registered with this group: at most {{value}}.", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 4c5b848f..984ba3a1 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -49,6 +49,8 @@ import { eventDraftTitle, loadEventDraft, saveEventDraft, + draftJson, + withoutNulls, } from '../../../lib/eventDraft'; /** Fees and item limit sellers registered with; they may only get better for sellers. */ @@ -615,11 +617,16 @@ function WizardHeader({ step, onGoTo, onCancel, + onContinueLater, + savingLater, disabled, }: { step: number; onGoTo: (step: number) => void; onCancel: () => void; + /** Signed in: keeps the bazaar in the account to finish later */ + onContinueLater?: () => void; + savingLater?: boolean; disabled: boolean; }) { const { t } = useTranslation('organizer'); @@ -635,10 +642,35 @@ function WizardHeader({ {t('wizard.progress', { step: step + 1, total: WIZARD_STEPS.length })} - +
+ {/* Up here, not in the bar at the bottom: on phones it would take a row of its own */} + {onContinueLater && ( + + )} + +
    {WIZARD_STEPS.map((candidate, index) => ( @@ -1026,6 +1058,8 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { // Creating goes through a wizard that explains each group of settings const [step, setStep] = useState(0); + const stepRef = useRef(step); + stepRef.current = step; // Every new step starts at the top: after it rendered, so a shorter step cannot stop // the scrolling half way (on phones the buttons sit far below the start) const shownStep = useRef(step); @@ -1077,6 +1111,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { } toast.error(t('wizard.fixErrors')); }; + const [continuedDraftAt, setContinuedDraftAt] = useState(); const keepDraft = (draftStep: number, submitted = false) => saveEventDraft({ values: draftValues(methods.getValues()), @@ -1084,6 +1119,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { eventType, step: draftStep, submitted, + continues: continuedDraftAt, }); // Signed in, a bazaar can wait on the server with gaps; it comes back on the start // page (DashboardPage) and when the wizard opens again @@ -1091,7 +1127,6 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { // There is only one saved draft: saving another bazaar over it asks first. That is the // case when the wizard did not continue it (e.g. started from the landing page) or it // changed elsewhere meanwhile. - const [continuedDraftAt, setContinuedDraftAt] = useState(); const [confirmReplace, setConfirmReplace] = useState(false); const replacesOtherDraft = !!serverDraft && serverDraft.updatedAt !== continuedDraftAt; const continueLater = async () => { @@ -1099,13 +1134,14 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { setSavingDraft(true); try { await saveServerDraft({ - draft: { + // As JSON keeps them: empty numbers (NaN) would come back as null + draft: draftJson({ values: draftValues(methods.getValues()), pendingLocationCategories, eventType, step, savedAt: Date.now(), - }, + }), }); clearEventDraft(); toast.success(t('form.draftSaved'), { description: t('form.draftSavedHint') }); @@ -1121,7 +1157,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { const fields = WIZARD_STEPS[step].fields; if (fields.length > 0 && !(await methods.trigger(fields as never))) return; } - if (isGuest) keepDraft(next); + if (next > 0) keepDraft(next); setStep(next); }; @@ -1191,7 +1227,8 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { const saved = serverDraft?.draft as Omit, 'savedAt'> | undefined; const continuesSaved = !!saved && !!serverDraft && (!local || serverDraft.updatedAt > local.savedAt); - if (continuesSaved) setContinuedDraftAt(serverDraft.updatedAt); + // A draft kept in this browser may continue the saved one as well + setContinuedDraftAt(continuesSaved ? serverDraft.updatedAt : local?.continues); const draft = continuesSaved ? { ...saved, savedAt: serverDraft.updatedAt } : local; if (!draft) { // The link of the confirmation mail may open in another browser than the wizard @@ -1204,7 +1241,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { ...current, ...draft.values, coverTemplate: draft.values.coverTemplate ?? undefined, - features: { ...current.features, ...draft.values.features }, + features: { ...current.features, ...withoutNulls(draft.values.features) }, }); setPendingLocationCategories(draft.pendingLocationCategories); setEventType(findEventType(draft.eventType)?.id); @@ -1216,6 +1253,26 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { } // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when auth and categories are known }, [isEditing, isAuthLoading, categories, isAuthenticated, serverDraft]); + // Every change waits in this browser (also for signed-in organizers), so a reload or a + // closed tab loses nothing; "continue later" keeps it in the account + const keepDraftRef = useRef(keepDraft); + keepDraftRef.current = keepDraft; + useEffect(() => { + if (isEditing) return; + let timer: ReturnType | undefined; + const subscription = methods.watch(() => { + if (!draftHandled.current) return; + clearTimeout(timer); + // Not on the first step: nothing is typed yet, and a discarded draft stays gone + timer = setTimeout(() => { + if (stepRef.current > 0) keepDraftRef.current(stepRef.current); + }, 600); + }); + return () => { + clearTimeout(timer); + subscription.unsubscribe(); + }; + }, [isEditing, methods]); // Next render: onSubmit then sees the restored storage locations useEffect(() => { if (!creatingDraft) return; @@ -1518,6 +1575,12 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { clearEventDraft(); navigate('/'); }} + onContinueLater={ + !isGuest && step > 0 + ? () => (replacesOtherDraft ? setConfirmReplace(true) : void continueLater()) + : undefined + } + savingLater={savingDraft} disabled={isSubmitting} />
    - {/* - Guests keep their draft in the browser anyway, until they sign up. On - phones the label needs its own row below back and next: an icon alone - does not say that the bazaar is kept for later - */} - {!isGuest && step > 0 && ( - - )} {step > 0 && ( + {badge ? ( + + ) : ( + + )} e.stopPropagation()}> {t('sellerFeeGroup.title')} diff --git a/src/components/sellers/FeeGroupCheck.test.tsx b/src/components/sellers/FeeGroupCheck.test.tsx index b83cf267..641c5998 100644 --- a/src/components/sellers/FeeGroupCheck.test.tsx +++ b/src/components/sellers/FeeGroupCheck.test.tsx @@ -145,4 +145,31 @@ describe('FeeGroupMenu', () => { rerender(); expect(container).toBeEmptyDOMElement(); }); + + it('as badge: the group opens the choice, "no group" too', async () => { + const { rerender } = render( + + ); + const chip = screen.getByRole('button', { name: 'Gebührengruppe zuordnen: Keine Gruppe' }); + expect(chip).toHaveTextContent('Keine Gruppe'); + fireEvent.pointerDown(chip, { button: 0, ctrlKey: false }); + fireEvent.click(await screen.findByRole('menuitemradio', { name: 'Vereinsmitglieder' })); + await waitFor(() => + expect(calls['feeGroups.assignFeeGroup']).toHaveBeenCalledWith({ + eventId: EVENT, + sellerId: 'u1', + groupId: 'members', + }) + ); + + rerender(); + expect( + screen.getByRole('button', { name: 'Gebührengruppe zuordnen: Vereinsmitglieder' }) + ).toHaveTextContent('Vereinsmitglieder· prüfen'); + + // Paid out: only the badge, nothing to choose + rerender(); + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + expect(screen.getByText('Vereinsmitglieder')).toBeInTheDocument(); + }); }); diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index c55eabc6..c637a384 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -91,7 +91,7 @@ "settlementClosed": "Die Abwicklung dieses Basars ist abgeschlossen. Verkäufe und Rückgaben lassen sich nicht mehr ändern.", "startMissing": "Bitte auch den Beginn der {{label}} angeben.", "registrationWindow": "Das Ende der Anmeldung muss nach ihrem Beginn liegen.", - "feeGroupsTooMany": "Ein Basar kann höchstens 10 Gebührengruppen haben.", + "feeGroupsTooMany": "Ein Basar kann höchstens 4 Gebührengruppen haben.", "feeGroupLabel": "Jede Gebührengruppe braucht einen Namen mit höchstens 60 Zeichen.", "feeGroupLabelTwice": "Zwei Gebührengruppen haben denselben Namen.", "feeGroupCommission": "Die Provision einer Gebührengruppe liegt zwischen 0 und 100 %.", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index f2f47115..f59e5aea 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -1375,7 +1375,7 @@ }, "feeGroups": { "title": "Gebührengruppen (optional)", - "hint": "Eigene Gebühren für eine Gruppe von Verkäufern, z. B. Vereinsmitglieder 5 % statt 10 % oder Helfer ohne Provision. Verkäufer sehen alle Gruppen in den Bedingungen. Wer zu mehreren Gruppen gehört, zahlt die günstigsten Gebühren.", + "hint": "Eigene Gebühren für eine Gruppe von Verkäufern, z. B. Vereinsmitglieder 5 % statt 10 % oder Helfer ohne Provision. Verkäufer sehen alle Gruppen in den Bedingungen. Bis zu 4 Gruppen, jeder Verkäufer ist in höchstens einer.", "empty": "Alle Verkäufer zahlen dieselben Gebühren. Mit einer Gruppe zahlen z. B. Vereinsmitglieder oder Helfer weniger.", "unnamed": "Neue Gruppe", "hasError": "Bitte prüfen", @@ -1401,7 +1401,6 @@ "proofHintInfo": "Steht bei der Gruppe in den Bedingungen und bei der Abgabe, damit Verkäufer ihn mitbringen.", "proofHintPlaceholder": "z. B. Mitgliedsausweis bei der Abgabe zeigen", "fixed": "Verkäufer haben sich mit dieser Gruppe angemeldet: Sie bleibt und kann nur günstiger werden.", - "cheapest": "Wer zu mehreren Gruppen gehört, zahlt die günstigsten Gebühren.", "remove": "Gruppe entfernen", "add": "Gebührengruppe hinzufügen", "labelRequired": "Gib der Gruppe einen Namen.", @@ -1427,9 +1426,10 @@ "assigned": "{{name}}: {{group}}", "unassigned": "{{name}}: keine Gruppe", "byRole": "{{group}} gilt durch die Helferrolle, solange sie besteht.", - "tab": "Gruppen", - "noneInGroups": "Noch niemand in einer Gebührengruppe.", "pendingCount_one": "{{count}} Selbstauskunft ist noch nicht geprüft. Bei der Abgabe bestätigst oder entfernst du sie.", - "pendingCount_other": "{{count}} Selbstauskünfte sind noch nicht geprüft. Bei der Abgabe bestätigst oder entfernst du sie." + "pendingCount_other": "{{count}} Selbstauskünfte sind noch nicht geprüft. Bei der Abgabe bestätigst oder entfernst du sie.", + "filter": "Nach Gebührengruppe filtern", + "allGroups": "Alle Gruppen", + "withPending": "{{group}} ({{count}} prüfen)" } } diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 47ad38df..362d64c2 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -91,7 +91,7 @@ "settlementClosed": "The settlement of this bazaar is closed. Sales and returns can no longer be changed.", "startMissing": "Please also give the start of the {{label}}.", "registrationWindow": "Registration must end after it begins.", - "feeGroupsTooMany": "A bazaar can have at most 10 fee groups.", + "feeGroupsTooMany": "A bazaar can have at most 4 fee groups.", "feeGroupLabel": "Every fee group needs a name of at most 60 characters.", "feeGroupLabelTwice": "Two fee groups have the same name.", "feeGroupCommission": "The commission of a fee group is between 0 and 100 %.", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 4260e8a3..bed64278 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -1375,7 +1375,7 @@ }, "feeGroups": { "title": "Fee groups (optional)", - "hint": "Own fees for a group of sellers, e.g. club members 5 % instead of 10 % or helpers without commission. Sellers see all groups in the conditions. Who belongs to several groups pays the cheapest fees.", + "hint": "Own fees for a group of sellers, e.g. club members 5 % instead of 10 % or helpers without commission. Sellers see all groups in the conditions. Up to 4 groups, each seller is in one at most.", "empty": "All sellers pay the same fees. With a group, e.g. club members or helpers pay less.", "unnamed": "New group", "hasError": "Please check", @@ -1401,7 +1401,6 @@ "proofHintInfo": "Shown with the group in the conditions and at the drop-off, so sellers bring it.", "proofHintPlaceholder": "e.g. Show your membership card at the drop-off", "fixed": "Sellers registered with this group: it stays and can only get cheaper.", - "cheapest": "Who belongs to several groups pays the cheapest fees.", "remove": "Remove group", "add": "Add fee group", "labelRequired": "Give the group a name.", @@ -1427,9 +1426,10 @@ "assigned": "{{name}}: {{group}}", "unassigned": "{{name}}: no group", "byRole": "{{group}} applies through the helper role, as long as it lasts.", - "tab": "Groups", - "noneInGroups": "Nobody is in a fee group yet.", "pendingCount_one": "{{count}} self-declaration is not checked yet. You confirm or remove it at the drop-off.", - "pendingCount_other": "{{count}} self-declarations are not checked yet. You confirm or remove them at the drop-off." + "pendingCount_other": "{{count}} self-declarations are not checked yet. You confirm or remove them at the drop-off.", + "filter": "Filter by fee group", + "allGroups": "All groups", + "withPending": "{{group}} ({{count}} to check)" } } diff --git a/src/pages/organizer/events/components/EditEventFeeGroups.tsx b/src/pages/organizer/events/components/EditEventFeeGroups.tsx index 86f15596..7968fe0d 100644 --- a/src/pages/organizer/events/components/EditEventFeeGroups.tsx +++ b/src/pages/organizer/events/components/EditEventFeeGroups.tsx @@ -331,7 +331,7 @@ export function EditEventFeeGroups({ )}

    - {fixed ? t('feeGroups.fixed') : t('feeGroups.cheapest')} + {fixed && t('feeGroups.fixed')}

    - {activeFilter === 'groups' && pendingGroups > 0 && ( + {pendingGroups > 0 && (

    {t('sellerFeeGroup.pendingCount', { count: pendingGroups })}

    diff --git a/src/shared/feeGroups.ts b/src/shared/feeGroups.ts index 57fe337b..ede6cf10 100644 --- a/src/shared/feeGroups.ts +++ b/src/shared/feeGroups.ts @@ -28,7 +28,7 @@ export interface FeeGroup { proofHint?: string; } -export const MAX_FEE_GROUPS = 10; +export const MAX_FEE_GROUPS = 4; /** The fees one seller pays: the bazaar's or those of their group. */ export interface GroupFees { diff --git a/src/tests/auth/fee-groups.spec.ts b/src/tests/auth/fee-groups.spec.ts index 4705529d..7aaf930a 100644 --- a/src/tests/auth/fee-groups.spec.ts +++ b/src/tests/auth/fee-groups.spec.ts @@ -70,7 +70,9 @@ test('a self-declared fee group is chosen at registration and checked at the int // The organizer sees the unchecked self-declaration and confirms it at the intake const organizer = await loginAs(page, ORGANIZER); await organizer.goto(`/events/view/${showcase.eventId}/sellers`); - await organizer.getByRole('tab', { name: /Gruppen/ }).click(); + await organizer + .getByRole('combobox', { name: 'Nach Gebührengruppe filtern' }) + .selectOption({ label: 'Vereinsmitglieder (1 prüfen)' }); await expect(organizer.getByText('1 Selbstauskunft ist noch nicht geprüft')).toBeVisible(); const row = organizer.getByRole('row', { name: /Vereinsmitglieder · prüfen/ }); await row.click(); @@ -83,4 +85,11 @@ test('a self-declared fee group is chosen at registration and checked at the int await seller.reload(); await expect(seller.getByTestId('my-fee-group')).toContainText('Vom Team bestätigt'); + + // The group's chip in the seller's header changes it, here back to no group + const chip = organizer.getByRole('button', { name: /^Gebührengruppe zuordnen/ }); + await expect(chip).toHaveText('Vereinsmitglieder'); + await chip.click(); + await organizer.getByRole('menuitemradio', { name: 'Keine Gruppe' }).click(); + await expect(chip).toHaveText('Keine Gruppe'); }); From 7b723a0349edf5c0ccc7f0606a4fa225a19533de Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Thu, 19 Nov 2026 10:35:28 +0100 Subject: [PATCH 07/10] feat(fees): manual fee groups, only one helper group (#302) - Add the "manual" assignment: only the organizer puts sellers in, sellers cannot choose or see it as a choice - Allow at most one helper group per bazaar, in the backend (event.feeGroupHelpersTwice) and in the editor - Show manual groups in the seller conditions as "Vergibt der Veranstalter" - Show assignment errors in the group editor --- backend/src/modules/events.rs | 8 +++ backend/src/modules/features.rs | 5 +- backend/tests/api/fee_groups.rs | 54 ++++++++++++++++++- src/lib/sellerFees.test.ts | 4 +- src/lib/sellerFees.ts | 8 +-- src/locales/de/errors.json | 1 + src/locales/de/events.json | 1 + src/locales/de/organizer.json | 8 ++- src/locales/en/errors.json | 1 + src/locales/en/events.json | 1 + src/locales/en/organizer.json | 8 ++- src/pages/organizer/events/EditEventForm.tsx | 11 +++- .../events/EditEventForm.wizard.test.tsx | 3 +- .../components/EditEventFeeGroups.test.tsx | 12 +++++ .../events/components/EditEventFeeGroups.tsx | 12 ++++- src/shared/feeGroups.test.ts | 19 ++++++- src/shared/feeGroups.ts | 11 +++- 17 files changed, 148 insertions(+), 19 deletions(-) diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index c0312190..8867550a 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -798,6 +798,14 @@ fn sanitize_fee_groups(groups: Vec) -> AppResult { if groups.len() > MAX_FEE_GROUPS { return Err(AppError::bad_request("event.feeGroupsTooMany")); } + // Helpers are in their group by role: two such groups would put them in both + let helper_groups = groups + .iter() + .filter(|group| group.assignment == FeeGroupAssignment::Helpers) + .count(); + if helper_groups > 1 { + return Err(AppError::bad_request("event.feeGroupHelpersTwice")); + } let mut ids: Vec = Vec::new(); let mut labels: Vec = Vec::new(); let mut stored = Vec::new(); diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index c37fa3b4..d337a68d 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -62,8 +62,11 @@ struct StoredFeeGroup { pub enum FeeGroupAssignment { /// The seller says so when joining; the team checks it at the intake SelfDeclared, - /// Everyone with a helper role at the bazaar, and whom the team puts in by hand + /// Everyone with a helper role at the bazaar, and whom the team puts in by hand. + /// At most one group per bazaar. Helpers, + /// Only whom the team puts in by hand; sellers can neither choose nor see it as choice + Manual, } /// Sellers with own fees instead of the bazaar's, e.g. club members or helpers (#302). diff --git a/backend/tests/api/fee_groups.rs b/backend/tests/api/fee_groups.rs index 3ee4df82..4c4b65f1 100644 --- a/backend/tests/api/fee_groups.rs +++ b/backend/tests/api/fee_groups.rs @@ -11,7 +11,7 @@ use sqlx::PgPool; use uuid::Uuid; /// 10 % commission, 1 € per item; members 5 % without intake fee, helpers 0 % and up to -/// 40 items instead of 2. +/// 40 items instead of 2, bakers (only by the team) 3 %. fn groups() -> Value { json!({ "intakeFee": 1, @@ -21,7 +21,9 @@ fn groups() -> Value { { "id": "members", "label": "Vereinsmitglieder", "commission": 5, "assignment": "selfDeclared", "proofHint": "Ausweis zeigen" }, { "id": "helpers", "label": "Helfer", "commission": 0, - "maxItemsPerSeller": 40, "assignment": "helpers" } + "maxItemsPerSeller": 40, "assignment": "helpers" }, + { "id": "bakers", "label": "Kuchenspender", "commission": 3, + "assignment": "manual" } ] }) } @@ -300,6 +302,16 @@ async fn sellers_choose_only_self_declared_groups_until_the_intake(db: PgPool) { ) .await; assert_eq!(helpers.body["code"], "feeGroup.unknown"); + // Groups only the team hands out cannot be chosen either + let bakers = m + .app + .mutation( + "eventSeller.joinEvent", + json!({ "eventId": m.event, "feeGroupId": "bakers" }), + Some(&session), + ) + .await; + assert_eq!(bakers.body["code"], "feeGroup.unknown"); let (seller, session) = m.join("Später", None).await; let choose = |group: Value| { @@ -329,6 +341,35 @@ async fn sellers_choose_only_self_declared_groups_until_the_intake(db: PgPool) { ); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn a_group_only_the_team_hands_out(db: PgPool) { + let m = Market::new(db.clone()).await; + let (seller, session) = m.join("Bäcker", None).await; + let chosen = m + .app + .mutation( + "feeGroups.chooseFeeGroup", + json!({ "eventId": m.event, "groupId": "bakers" }), + Some(&session), + ) + .await; + assert_eq!(chosen.body["code"], "feeGroup.unknown"); + let assigned = m + .app + .mutation( + "feeGroups.assignFeeGroup", + json!({ "eventId": m.event, "sellerId": seller, "groupId": "bakers" }), + Some(&m.organizer), + ) + .await; + assert_eq!(assigned.status, StatusCode::OK, "{}", assigned.body); + // Put in by the team: nothing left to check at the intake + let group = &m.vendor(seller).await["feeGroup"]; + assert_eq!(group["label"], "Kuchenspender", "{group}"); + assert_eq!(group["pending"], false); + assert_eq!(m.my_group(&session).await["applied"], "bakers"); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn helpers_are_in_their_group_while_they_have_the_role(db: PgPool) { let desk = Desk::new(db.clone(), groups()).await; @@ -455,6 +496,15 @@ async fn groups_are_checked_when_saved(db: PgPool) { save(json!([group("Mitglieder", 120.0)])).await["code"], "event.feeGroupCommission" ); + // Helpers are in their group by role: one such group only + let mut helpers = group("Helfer", 0.0); + helpers["assignment"] = json!("helpers"); + let mut more_helpers = group("Aufbauhelfer", 2.0); + more_helpers["assignment"] = json!("helpers"); + assert_eq!( + save(json!([helpers, more_helpers])).await["code"], + "event.feeGroupHelpersTwice" + ); // At most 4 groups per bazaar let five: Vec = ["A", "B", "C", "D", "E"] .iter() diff --git a/src/lib/sellerFees.test.ts b/src/lib/sellerFees.test.ts index 5cfd68b5..f9f7c288 100644 --- a/src/lib/sellerFees.test.ts +++ b/src/lib/sellerFees.test.ts @@ -176,7 +176,7 @@ describe('describeFeeGroups', () => { commission: 10, intakeFee: 1, maxFeesPerSeller: 10, - assignment: 'selfDeclared', + assignment: 'manual', }, ], }, @@ -196,7 +196,7 @@ describe('describeFeeGroups', () => { }, { fees: 'höchstens 10,00 € Gebühren', - how: 'Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe', + how: 'Vergibt der Veranstalter', }, ]); }); diff --git a/src/lib/sellerFees.ts b/src/lib/sellerFees.ts index bdfe1b25..61924d84 100644 --- a/src/lib/sellerFees.ts +++ b/src/lib/sellerFees.ts @@ -210,9 +210,11 @@ export function describeFeeGroups(event: SellerConditionsEvent): FeeGroupTerms[] how: group.assignment === 'helpers' ? text('groupHelpers') - : group.proofHint - ? text('groupProof', { hint: group.proofHint }) - : text('groupChecked'), + : group.assignment === 'manual' + ? text('groupManual') + : group.proofHint + ? text('groupProof', { hint: group.proofHint }) + : text('groupChecked'), })); } diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index c637a384..472aeb39 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -94,6 +94,7 @@ "feeGroupsTooMany": "Ein Basar kann höchstens 4 Gebührengruppen haben.", "feeGroupLabel": "Jede Gebührengruppe braucht einen Namen mit höchstens 60 Zeichen.", "feeGroupLabelTwice": "Zwei Gebührengruppen haben denselben Namen.", + "feeGroupHelpersTwice": "Nur eine Gebührengruppe kann für die Helfer des Basars gelten.", "feeGroupCommission": "Die Provision einer Gebührengruppe liegt zwischen 0 und 100 %.", "feeGroupProofHint": "Der Hinweis zum Nachweis darf höchstens 200 Zeichen lang sein.", "feeGroupsOnlyLower": "Seit sich Verkäufer angemeldet haben, können Gebührengruppen nur noch günstiger werden. Entfernen oder anders zuordnen geht nicht mehr." diff --git a/src/locales/de/events.json b/src/locales/de/events.json index 3c825e74..be7004f6 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -132,6 +132,7 @@ "groupCap": "höchstens {{fee}} € Gebühren", "groupItems": "bis zu {{count}} Artikel", "groupHelpers": "Gilt für Helfer des Basars", + "groupManual": "Vergibt der Veranstalter", "groupProof": "Nachweis bei der Abgabe: {{hint}}", "groupChecked": "Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe", "myGroup": "Deine Gruppe: {{group}}", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index f59e5aea..d9cea570 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -1388,7 +1388,10 @@ "selfDeclaredShort": "Angabe bei der Anmeldung", "helpersShort": "Helfer", "selfDeclaredHint": "Verkäufer wählen die Gruppe bei der Anmeldung selbst. Bei der Abgabe prüft das Team den Nachweis und bestätigt die Gruppe oder entfernt sie. Vorher kann kein Artikel angenommen werden.", - "helpersHint": "Gilt automatisch für alle mit einer Helferrolle, solange sie sie haben. In der Verkäuferliste kannst du auch Helfer ohne Rechte zuordnen, z. B. Kuchenspender." + "helpersHint": "Gilt automatisch für alle mit einer Helferrolle, solange sie sie haben. Du kannst auch Helfer ohne Rechte zuordnen. Nur eine Gruppe kann für die Helfer gelten.", + "manual": "Nur vom Veranstalter", + "manualShort": "vom Veranstalter vergeben", + "manualHint": "Verkäufer können die Gruppe nicht selbst wählen. Du ordnest sie in der Verkäuferliste oder beim Verkäufer zu, z. B. Kuchenspender oder Vorstand." }, "commission": "Provision", "intakeFee": "Annahmegebühr", @@ -1406,7 +1409,8 @@ "labelRequired": "Gib der Gruppe einen Namen.", "labelTwice": "Diesen Namen hat schon eine andere Gruppe.", "registeredMax": "Verkäufer haben sich mit dieser Gruppe angemeldet: höchstens {{value}}.", - "registeredMinItems": "Verkäufer haben sich mit dieser Gruppe angemeldet: mindestens {{min}} Artikel." + "registeredMinItems": "Verkäufer haben sich mit dieser Gruppe angemeldet: mindestens {{min}} Artikel.", + "helpersTwice": "Es gibt schon eine Gruppe für die Helfer des Basars." }, "feeGroupCheck": { "title": "Ermäßigt: {{group}} – Nachweis prüfen", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 362d64c2..221148af 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -94,6 +94,7 @@ "feeGroupsTooMany": "A bazaar can have at most 4 fee groups.", "feeGroupLabel": "Every fee group needs a name of at most 60 characters.", "feeGroupLabelTwice": "Two fee groups have the same name.", + "feeGroupHelpersTwice": "Only one fee group can apply to the helpers of the bazaar.", "feeGroupCommission": "The commission of a fee group is between 0 and 100 %.", "feeGroupProofHint": "The proof hint may be at most 200 characters long.", "feeGroupsOnlyLower": "Since sellers have registered, fee groups can only get cheaper. They can no longer be removed or assigned differently." diff --git a/src/locales/en/events.json b/src/locales/en/events.json index 00d6c3cb..3f7fb99f 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -132,6 +132,7 @@ "groupCap": "at most {{fee}} € in fees", "groupItems": "up to {{count}} items", "groupHelpers": "For helpers of the bazaar", + "groupManual": "Assigned by the organizer", "groupProof": "Proof at the drop-off: {{hint}}", "groupChecked": "You say so when registering, the team checks it at the drop-off", "myGroup": "Your group: {{group}}", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index bed64278..ccdcdd0f 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -1388,7 +1388,10 @@ "selfDeclaredShort": "Given at registration", "helpersShort": "Helpers", "selfDeclaredHint": "Sellers choose the group themselves when registering. At the drop-off the team checks the proof and confirms or removes the group. Until then no item can be accepted.", - "helpersHint": "Applies automatically to everyone with a helper role, as long as they have it. In the seller list you can also add helpers without rights, e.g. cake donors." + "helpersHint": "Applies automatically to everyone with a helper role, as long as they have it. You can also assign helpers without rights. Only one group can apply to helpers.", + "manual": "Organizer only", + "manualShort": "assigned by the organizer", + "manualHint": "Sellers cannot choose the group themselves. You assign it in the seller list or at the seller, e.g. cake donors or the board." }, "commission": "Commission", "intakeFee": "Intake fee", @@ -1406,7 +1409,8 @@ "labelRequired": "Give the group a name.", "labelTwice": "Another group already has this name.", "registeredMax": "Sellers registered with this group: at most {{value}}.", - "registeredMinItems": "Sellers registered with this group: at least {{min}} items." + "registeredMinItems": "Sellers registered with this group: at least {{min}} items.", + "helpersTwice": "There is already a group for the helpers of the bazaar." }, "feeGroupCheck": { "title": "Reduced: {{group}} – check the proof", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 984ba3a1..0675c30c 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -88,7 +88,7 @@ import { } from './components/wizard/WizardPreviews'; import { WizardSummary } from './components/wizard/WizardSummary'; import { EditEventFeeGroups } from './components/EditEventFeeGroups'; -import { MAX_FEE_GROUPS, type FeeGroup } from '../../../shared/feeGroups'; +import { MAX_FEE_GROUPS, extraHelperGroups, type FeeGroup } from '../../../shared/feeGroups'; import { PageSkeleton } from '../../../components/ui/loading'; import { isEventRunning } from '../../../shared/eventPhase'; @@ -240,7 +240,7 @@ const buildEventSchema = ( .min(1, zodMessage('form.minOne', 'organizer')) .optional() .or(z.nan()), - assignment: z.enum(['selfDeclared', 'helpers']), + assignment: z.enum(['selfDeclared', 'helpers', 'manual']), proofHint: z.string().max(200), }) ) @@ -258,6 +258,13 @@ const buildEventSchema = ( } seen.add(label); }); + for (const index of extraHelperGroups(groups)) { + ctx.addIssue({ + code: 'custom', + message: i18n.t('feeGroups.helpersTwice', { ns: 'organizer' }), + path: [index, 'assignment'], + }); + } }), }), sellerLogistics: z.object({ diff --git a/src/pages/organizer/events/EditEventForm.wizard.test.tsx b/src/pages/organizer/events/EditEventForm.wizard.test.tsx index 35a23957..fa3e2fb3 100644 --- a/src/pages/organizer/events/EditEventForm.wizard.test.tsx +++ b/src/pages/organizer/events/EditEventForm.wizard.test.tsx @@ -345,7 +345,8 @@ describe('event creation wizard', () => { // Back from the sign-up: the bazaar is created without another click auth.current = { isLoading: false, isAuthenticated: true }; renderWizard('/events/new?draft=1'); - await waitFor(() => expect(createEvent).toHaveBeenCalledTimes(1)); + // Restoring and checking the whole form takes a while on a busy CI runner + await waitFor(() => expect(createEvent).toHaveBeenCalledTimes(1), { timeout: 5_000 }); expect(createEvent.mock.calls[0][0]).toMatchObject({ title: 'Kinderbasar Kita', location: 'Münsterplatz', diff --git a/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx b/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx index 7bbb54f0..4f62e9e6 100644 --- a/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx +++ b/src/pages/organizer/events/components/EditEventFeeGroups.test.tsx @@ -57,6 +57,18 @@ describe('EditEventFeeGroups', () => { expect(screen.queryByLabelText('Nachweis (optional)')).not.toBeInTheDocument(); }); + it('offers the helpers only once and groups only the organizer hands out', () => { + render( + + ); + fireEvent.click(screen.getByRole('button', { name: 'Gebührengruppe hinzufügen' })); + const assignment = screen.getByLabelText('Wer gehört dazu?'); + expect(screen.getByRole('option', { name: 'Helfer des Basars' })).toBeDisabled(); + fireEvent.change(assignment, { target: { value: 'manual' } }); + expect(current[1]).toMatchObject({ assignment: 'manual' }); + expect(screen.getByText(/vom Veranstalter vergeben$/)).toBeInTheDocument(); + }); + it('shows a group in short and removes it', () => { render(); expect( diff --git a/src/pages/organizer/events/components/EditEventFeeGroups.tsx b/src/pages/organizer/events/components/EditEventFeeGroups.tsx index 7968fe0d..6b59bd61 100644 --- a/src/pages/organizer/events/components/EditEventFeeGroups.tsx +++ b/src/pages/organizer/events/components/EditEventFeeGroups.tsx @@ -233,6 +233,7 @@ export function EditEventFeeGroups({ htmlFor={`${domId}-assignment`} label={t('feeGroups.assignmentLabel')} info={t(`feeGroups.assignment.${group.assignment}Hint`)} + error={error?.assignment?.message} > {t('feeGroups.assignment.selfDeclared')} - + {/* Helpers are in their group by role: one such group per bazaar */} + +
diff --git a/src/shared/feeGroups.test.ts b/src/shared/feeGroups.test.ts index 2a197b1e..75bcf47d 100644 --- a/src/shared/feeGroups.test.ts +++ b/src/shared/feeGroups.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { appliedGroup, compareFees, groupFees, type FeeGroup } from './feeGroups'; +import { + appliedGroup, + compareFees, + extraHelperGroups, + groupFees, + type FeeGroup, +} from './feeGroups'; // The same cases as the tests of backend/src/modules/fee_groups.rs const members: FeeGroup = { @@ -51,4 +57,15 @@ describe('fee groups', () => { expect(compareFees({ commission: 5, intakeFee: 1 }, { commission: 5 })).toBeGreaterThan(0); expect(compareFees({ commission: 5, maxFeesPerSeller: 10 }, { commission: 5 })).toBeLessThan(0); }); + + it('allow one helper group only', () => { + expect(extraHelperGroups([{ assignment: 'helpers' }, { assignment: 'manual' }])).toEqual([]); + expect( + extraHelperGroups([ + { assignment: 'selfDeclared' }, + { assignment: 'helpers' }, + { assignment: 'helpers' }, + ]) + ).toEqual([2]); + }); }); diff --git a/src/shared/feeGroups.ts b/src/shared/feeGroups.ts index ede6cf10..66badbce 100644 --- a/src/shared/feeGroups.ts +++ b/src/shared/feeGroups.ts @@ -5,7 +5,7 @@ */ /** How a seller gets into a group */ -export type FeeGroupAssignment = 'selfDeclared' | 'helpers'; +export type FeeGroupAssignment = 'selfDeclared' | 'helpers' | 'manual'; export interface FeeGroup { id: string; @@ -21,7 +21,9 @@ export interface FeeGroup { maxItemsPerSeller?: number; /** * `selfDeclared`: the seller says so when joining, the team checks it at the intake. - * `helpers`: everyone with a helper role, and whom the organizer puts in by hand. + * `helpers`: everyone with a helper role, and whom the organizer puts in by hand. At + * most one such group per bazaar. + * `manual`: only whom the organizer puts in by hand. */ assignment: FeeGroupAssignment; /** Shown to sellers, e.g. "Mitgliedsausweis bei der Abgabe zeigen" */ @@ -90,6 +92,11 @@ export function appliedGroup( .sort((a, b) => compareFees(groupFees(event, a), groupFees(event, b)))[0]; } +/** Helpers are in their group by role: every helper group after the first is one too many. */ +export function extraHelperGroups(groups: Pick[]): number[] { + return groups.flatMap((group, index) => (group.assignment === 'helpers' ? [index] : [])).slice(1); +} + /** A new id for a group: short, URL-safe, unique enough within one bazaar */ export function newFeeGroupId(): string { return `g${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; From 8e8edfeda9d946611e9504887718822357a95ea2 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Fri, 20 Nov 2026 12:55:43 +0100 Subject: [PATCH 08/10] feat(fees): apply fee groups once checked, keep settled rates (#302) - Self-declared groups not yet checked by the team do not apply: bookings, item limit and settlement use the bazaar's fees until the team confirms the group - Removing a helper role or excluding a helper re-books their sales under the fees that now apply - Store the commission percent with each payout (migration 0037), so settled rates stay fixed when settings change; expose it as commissionPercent on vendors and in my sales - Direct sales: the payout holds the difference when the commission changed since the sale, negative if the seller owes it, positive if they get it back - Helpers at the intake may only decide groups still to be checked; organizer-assigned groups need an organizer --- .../0037_payout_commission_percent.sql | 4 + backend/src/modules/docs.rs | 13 +- backend/src/modules/event_exclusions.rs | 2 + backend/src/modules/event_invitations.rs | 2 + backend/src/modules/event_roles.rs | 16 +- backend/src/modules/event_seller.rs | 14 +- backend/src/modules/fee_groups.rs | 112 ++++++++---- backend/src/modules/purchases.rs | 18 +- backend/src/modules/seller_numbers.rs | 2 +- backend/tests/api/fee_groups.rs | 164 ++++++++++++++++++ src/components/events/FeeGroups.test.tsx | 6 +- src/lib/api/types.ts | 2 + src/locales/de/errors.json | 3 +- src/locales/de/events.json | 2 +- src/locales/de/organizer.json | 4 +- src/locales/en/errors.json | 3 +- src/locales/en/events.json | 2 +- src/locales/en/organizer.json | 4 +- .../dashboard/ProductManagementPage.tsx | 13 +- 19 files changed, 318 insertions(+), 68 deletions(-) create mode 100644 backend/migrations/0037_payout_commission_percent.sql diff --git a/backend/migrations/0037_payout_commission_percent.sql b/backend/migrations/0037_payout_commission_percent.sql new file mode 100644 index 00000000..fe3f387f --- /dev/null +++ b/backend/migrations/0037_payout_commission_percent.sql @@ -0,0 +1,4 @@ +-- The commission percent applied at the payout (#302), next to fee_group_label: so the +-- settlement keeps showing the rate it was booked with, even when the group or the bazaar's +-- commission changes later. NULL for payouts from before. +ALTER TABLE event_sellers ADD COLUMN commission_percent numeric; diff --git a/backend/src/modules/docs.rs b/backend/src/modules/docs.rs index c404de17..c9589c0f 100644 --- a/backend/src/modules/docs.rs +++ b/backend/src/modules/docs.rs @@ -546,6 +546,8 @@ pub struct EventSeller { pub fee_group_decided_at: Option>, /// The group applied at the payout pub fee_group_label: Option, + /// The commission percent applied at the payout + pub commission_percent: Option, #[serde(with = "ms_opt")] pub private_seller_confirmed_at: Option>, pub seller_snapshot: Option, @@ -555,7 +557,7 @@ pub const EVENT_SELLER_COLUMNS: &str = "id, created_at, event_id, user_id, total_fee, commission_fee, sale_fee_fixed, sale_fee_percentage, payout_amount, payout_received, number, intake_fee, intake_fee_items, fee_cap_credit, fee_group_id, fee_group_decided_at, fee_group_label, - private_seller_confirmed_at, seller_snapshot"; + commission_percent, private_seller_confirmed_at, seller_snapshot"; pub async fn event_seller( conn: &mut PgConnection, @@ -608,12 +610,13 @@ pub struct Purchase { } impl Purchase { - /// What came into the till for the sale. A direct sale whose commission was raised - /// after an undone sale (fee cap, #301) has a negative payout: the part the desk did not - /// take and the seller pays at the settlement. + /// What came into the till for the sale. At a direct sale the desk took the commission + /// as it was then; when it changed since (fee cap #301, fee group #302) the payout of + /// the sale holds the difference: negative what the seller still owes, positive what + /// they get back. Either way commission and payout together are what the desk took. pub fn taken(&self) -> Decimal { if self.direct_sale { - self.commission_amount + self.payout_amount.min(Decimal::ZERO) + self.commission_amount + self.payout_amount } else { desk_takes(false, self.total_amount, self.commission_amount) } diff --git a/backend/src/modules/event_exclusions.rs b/backend/src/modules/event_exclusions.rs index 2cb719c5..23822bd1 100644 --- a/backend/src/modules/event_exclusions.rs +++ b/backend/src/modules/event_exclusions.rs @@ -186,6 +186,8 @@ async fn exclude(ctx: &mut Ctx, args: ExcludeArgs) -> AppResult { let was_helper = event_roles::has_role(ctx.conn(), event.id, user, Role::Coorganizer).await?; if was_helper { event_roles::remove_role(ctx, event.id, user, Role::Coorganizer).await?; + // A helper group no longer applies: their sales are booked anew (#302) + super::fee_groups::after_role_change(ctx, event.id, user).await?; // Their devices may keep the keys of the sellers' ID codes super::offline::renew_check_in_keys(ctx, event.id).await?; } diff --git a/backend/src/modules/event_invitations.rs b/backend/src/modules/event_invitations.rs index c55ab032..ef71c403 100644 --- a/backend/src/modules/event_invitations.rs +++ b/backend/src/modules/event_invitations.rs @@ -317,6 +317,8 @@ pub async fn redeem( .await?; if helper && !event_roles::has_role(ctx.conn(), event, user, Role::Organizer).await? { event_roles::add_role(ctx, event, user, Role::Coorganizer).await?; + // Helpers may pay the fees of a helper group (#302) + super::fee_groups::after_role_change(ctx, event, user).await?; } ctx.touch(Topic::Event(event)); Ok(()) diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index 453c677e..f5008938 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -438,6 +438,9 @@ pub struct VendorWithCalculations { pub excluded: Option, /// The fee group whose fees apply (#302) pub fee_group: Option, + /// The seller's commission in percent: their group's or the bazaar's; once paid out the + /// one settled with + pub commission_percent: Decimal, } /// A seller's fee group as the team sees it. @@ -537,9 +540,17 @@ pub async fn load_vendors_with_calculations( Membership::default() }; let fees = member.fees(&event); + // A group still to be checked shows, marked pending, though its fees do not apply yet + let shown = member.claimed(&event); + let pending = member.pending(&event).is_some(); let paid = seller.as_ref().is_some_and(|seller| seller.payout_received); + let commission_percent = seller + .as_ref() + .filter(|_| paid) + .and_then(|seller| seller.commission_percent) + .unwrap_or(fees.commission); let fee_group = match ( - &fees.group, + &shown.group, seller.as_ref().and_then(|s| s.fee_group_label.clone()), ) { // Paid out: the group as settled @@ -554,7 +565,7 @@ pub async fn load_vendors_with_calculations( (Some(group), _) => Some(VendorFeeGroup { id: Some(group.id.clone()), label: group.label.clone(), - pending: member.pending(&event, &fees).is_some(), + pending, by_role: member.stored.as_deref() != Some(group.id.as_str()), chosen: member.stored.clone().filter(|chosen| *chosen != group.id), }), @@ -594,6 +605,7 @@ pub async fn load_vendors_with_calculations( sort_code, excluded: exclusions.remove(&vendor), fee_group, + commission_percent, }); } Ok(vendors) diff --git a/backend/src/modules/event_seller.rs b/backend/src/modules/event_seller.rs index d207e6a6..c7c460f3 100644 --- a/backend/src/modules/event_seller.rs +++ b/backend/src/modules/event_seller.rs @@ -418,7 +418,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult // Fees above the cap go back to the seller with the payout let credit = sales::fee_cap_credit_of(&fees, row.as_ref(), commission, &fee); // The group applied, kept with the settlement (#302) - let group = fees.group.map(|group| group.label); + let group = fees.group.as_ref().map(|group| group.label.clone()); let payout = payout - fee.total + credit; let credit = (!credit.is_zero()).then_some(credit); match row { @@ -426,7 +426,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult sqlx::query( "UPDATE event_sellers SET commission_fee = $2, payout_amount = $3, intake_fee = $4, intake_fee_items = $5, fee_cap_credit = $6, fee_group_label = $7, - payout_received = true + commission_percent = $8, payout_received = true WHERE id = $1", ) .bind(row.id) @@ -436,6 +436,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult .bind(fee.items as i32) .bind(credit) .bind(&group) + .bind(fees.commission) .execute(ctx.conn()) .await?; } @@ -443,9 +444,9 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult let number = next_seller_number(ctx, event.id).await?; sqlx::query( "INSERT INTO event_sellers (event_id, user_id, total_fee, commission_fee, payout_amount, - intake_fee, intake_fee_items, fee_cap_credit, fee_group_label, payout_received, - number) - VALUES ($1, $2, 0, $3, $4, $5, $6, $7, $8, true, $9)", + intake_fee, intake_fee_items, fee_cap_credit, fee_group_label, commission_percent, + payout_received, number) + VALUES ($1, $2, 0, $3, $4, $5, $6, $7, $8, $9, true, $10)", ) .bind(event.id) .bind(vendor) @@ -455,6 +456,7 @@ async fn record_payout(ctx: &mut Ctx, event_id: Uuid, vendor: Uuid) -> AppResult .bind(fee.items as i32) .bind(credit) .bind(&group) + .bind(fees.commission) .bind(number) .execute(ctx.conn()) .await?; @@ -473,7 +475,7 @@ async fn unmark_vendor_payout_received(ctx: &mut Ctx, args: VendorArgs) -> AppRe sqlx::query( "UPDATE event_sellers SET payout_received = false, commission_fee = 0, payout_amount = 0, intake_fee = NULL, intake_fee_items = NULL, fee_cap_credit = NULL, - fee_group_label = NULL + fee_group_label = NULL, commission_percent = NULL WHERE event_id = $1 AND user_id = $2 AND payout_received", ) .bind(event) diff --git a/backend/src/modules/fee_groups.rs b/backend/src/modules/fee_groups.rs index 7722611b..299612de 100644 --- a/backend/src/modules/fee_groups.rs +++ b/backend/src/modules/fee_groups.rs @@ -80,7 +80,9 @@ impl SellerFees { } /// Which of two fee sets is cheaper for the seller: the lower commission, then the lower -/// intake fee, then the lower cap. The app sorts the same (cheaperFees in feeGroups.ts). +/// intake fee, then the lower cap. The app sorts the same (compareFees in feeGroups.ts). +/// Deliberately not by the expected total: that would need the seller's items and could +/// switch the group with every sale. The editor tells organizers that commission decides. fn compare(a: &SellerFees, b: &SellerFees) -> Ordering { let key = |f: &SellerFees| { ( @@ -124,19 +126,31 @@ impl Membership { } } - pub fn fees(&self, event: &Event) -> SellerFees { + /// The fees as the seller claims them, counting a self-declared group nobody checked yet + pub fn claimed(&self, event: &Event) -> SellerFees { fees_for(event, self.stored.as_deref(), self.helper) } - /// A self-declared group the team has not checked yet, and it is the one that applies - pub fn pending<'a>(&self, event: &Event, fees: &'a SellerFees) -> Option<&'a FeeGroup> { - fees.group.as_ref().filter(|group| { + /// A self-declared group the team has not checked yet, and it would be the one that + /// applies + pub fn pending(&self, event: &Event) -> Option { + self.claimed(event).group.filter(|group| { self.decided_at.is_none() && group.assignment == FeeGroupAssignment::SelfDeclared && self.stored.as_deref() == Some(group.id.as_str()) - && !event.resolved_features().fee_groups.is_empty() }) } + + /// The fees that apply: an unchecked self-declaration does not count until the team + /// confirms it, so nobody is booked, limited or settled by a group nobody checked. That + /// matters for a helper who chose a group and loses the role after items were accepted. + pub fn fees(&self, event: &Event) -> SellerFees { + if self.pending(event).is_some() { + fees_for(event, None, self.helper) + } else { + self.claimed(event) + } + } } async fn is_helper(conn: &mut PgConnection, event: Uuid, seller: Uuid) -> sqlx::Result { @@ -169,6 +183,9 @@ pub async fn seller_fees( Ok(membership(conn, event, seller).await?.fees(event)) } +/// Seller, stored group, when the team decided on it, helper +type FeeBookRow = (Uuid, Option, Option>, bool); + /// The fees of every seller of the event, for the cash desk and the lists. Sellers without /// a group pay the bazaar's. pub struct FeeBook { @@ -181,21 +198,26 @@ impl FeeBook { let default = SellerFees::of_event(event); let mut by_seller = HashMap::new(); if !event.resolved_features().fee_groups.is_empty() { - let rows: Vec<(Uuid, Option, bool)> = sqlx::query_as( - "SELECT u.user_id, s.fee_group_id, bool_or(u.helper) FROM ( + let rows: Vec = sqlx::query_as( + "SELECT u.user_id, s.fee_group_id, s.fee_group_decided_at, bool_or(u.helper) FROM ( SELECT user_id, false AS helper FROM event_sellers WHERE event_id = $1 AND fee_group_id IS NOT NULL UNION ALL SELECT user_id, true FROM event_roles WHERE event_id = $1 AND role = 'coorganizer' ) u LEFT JOIN event_sellers s ON s.event_id = $1 AND s.user_id = u.user_id - GROUP BY u.user_id, s.fee_group_id", + GROUP BY u.user_id, s.fee_group_id, s.fee_group_decided_at", ) .bind(event.id) .fetch_all(conn) .await?; - for (seller, stored, helper) in rows { - by_seller.insert(seller, fees_for(event, stored.as_deref(), helper)); + for (seller, stored, decided_at, helper) in rows { + let member = Membership { + stored, + decided_at, + helper, + }; + by_seller.insert(seller, member.fees(event)); } } Ok(Self { default, by_seller }) @@ -214,8 +236,7 @@ pub async fn assert_group_decided( seller: Uuid, ) -> AppResult<()> { let member = membership(conn, event, seller).await?; - let fees = member.fees(event); - if let Some(group) = member.pending(event, &fees) { + if let Some(group) = member.pending(event) { return Err(AppError::coded( axum::http::StatusCode::BAD_REQUEST, "feeGroup.unconfirmed", @@ -368,13 +389,13 @@ async fn get_my_fee_group(ctx: &mut Ctx, args: EventArgs) -> AppResult AppResult { + let by = require_permission(ctx, event.id, Permission::Intake).await?; + let row = docs::event_seller(ctx.conn(), event.id, seller).await?; + let Some(stored) = row.as_ref().and_then(|row| row.fee_group_id.clone()) else { + // Nothing to confirm or take away, e.g. from a screen not up to date + return Err(AppError::bad_request("feeGroup.none")); + }; + let unchecked = row + .as_ref() + .is_some_and(|row| row.fee_group_decided_at.is_none()) + && event + .resolved_features() + .fee_groups + .iter() + .any(|g| g.id == stored && g.assignment == FeeGroupAssignment::SelfDeclared); + if !unchecked + && !event_roles::has_role_or_admin(ctx.conn(), event.id, by, Role::Organizer).await? + { + return Err(AppError::forbidden("feeGroup.decidedOrganizerOnly")); + } + Ok(by) +} + /// The team saw the proof (e.g. the member card) at the intake. Helpers with the intake -/// right may do it. +/// right may do it while the group is still to be checked. async fn confirm_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { - let (event_id, seller) = (args.event_id.0, args.seller_id.0); - let by = require_permission(ctx, event_id, Permission::Intake).await?; - let event = event_of(ctx, event_id).await?; - let stored = docs::event_seller(ctx.conn(), event_id, seller) + let event = event_of(ctx, args.event_id.0).await?; + let seller = args.seller_id.0; + let by = require_decider(ctx, &event, seller).await?; + let stored = docs::event_seller(ctx.conn(), event.id, seller) .await? .and_then(|row| row.fee_group_id); let exists = event @@ -485,9 +532,9 @@ async fn confirm_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { /// The proof is missing: the seller pays the bazaar's fees (or a helper group's). async fn remove_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { - let (event_id, seller) = (args.event_id.0, args.seller_id.0); - let by = require_permission(ctx, event_id, Permission::Intake).await?; - let event = event_of(ctx, event_id).await?; + let event = event_of(ctx, args.event_id.0).await?; + let seller = args.seller_id.0; + let by = require_decider(ctx, &event, seller).await?; decide(ctx, &event, seller, by, Some(None)).await } @@ -586,16 +633,21 @@ mod tests { decided_at: None, helper: false, }; - let fees = member.fees(&event); - assert!(member.pending(&event, &fees).is_some()); + assert!(member.pending(&event).is_some()); + // Until checked the bazaar's fees and item limit apply + assert_eq!(member.fees(&event), SellerFees::of_event(&event)); + assert_eq!(member.claimed(&event).commission, Decimal::new(5, 0)); // As helper the helper group applies, nothing to check member.helper = true; - let fees = member.fees(&event); - assert!(member.pending(&event, &fees).is_none()); + assert!(member.pending(&event).is_none()); + assert_eq!( + member.fees(&event).group.map(|g| g.id), + Some("helpers".to_owned()) + ); member.helper = false; member.decided_at = Some(Utc::now()); - let fees = member.fees(&event); - assert!(member.pending(&event, &fees).is_none()); + assert!(member.pending(&event).is_none()); + assert_eq!(member.fees(&event).commission, Decimal::new(5, 0)); } #[test] diff --git a/backend/src/modules/purchases.rs b/backend/src/modules/purchases.rs index 7d136d56..f0cfffa1 100644 --- a/backend/src/modules/purchases.rs +++ b/backend/src/modules/purchases.rs @@ -1475,10 +1475,20 @@ async fn get_my_sales(ctx: &mut Ctx, _: NoArgs) -> AppResult> { let fee_cap_credit = sales::fee_cap_credit_of(&fees, seller.as_ref(), commission, &intake_fee); let paid = seller.as_ref().is_some_and(|s| s.payout_received); - let fee_group = if paid { - seller.as_ref().and_then(|s| s.fee_group_label.clone()) + // Paid out: group and rate as settled, not as the settings are now + let (fee_group, commission_percent) = if paid { + ( + seller.as_ref().and_then(|s| s.fee_group_label.clone()), + seller + .as_ref() + .and_then(|s| s.commission_percent) + .unwrap_or(fees.commission), + ) } else { - fees.group.as_ref().map(|group| group.label.clone()) + ( + fees.group.as_ref().map(|group| group.label.clone()), + fees.commission, + ) }; let payout: Decimal = items.iter().map(|i| i.sale.payout).sum::() - intake_fee.total @@ -1489,7 +1499,7 @@ async fn get_my_sales(ctx: &mut Ctx, _: NoArgs) -> AppResult> { title: event.title.clone(), start_date: event.start_date, end_date: event.end_date, - commission_percent: fees.commission, + commission_percent, fee_group, }, paid: seller.as_ref().is_some_and(|s| s.payout_received), diff --git a/backend/src/modules/seller_numbers.rs b/backend/src/modules/seller_numbers.rs index 29f9083e..0d51e413 100644 --- a/backend/src/modules/seller_numbers.rs +++ b/backend/src/modules/seller_numbers.rs @@ -127,7 +127,7 @@ pub async fn assert_item_limit( if adding <= 0 { return Ok(()); } - // A fee group may allow more items (#302) + // A fee group may allow more items (#302); a self-declared one only once checked let limit = super::fee_groups::seller_fees(ctx.conn(), event, vendor) .await? .max_items_per_seller; diff --git a/backend/tests/api/fee_groups.rs b/backend/tests/api/fee_groups.rs index 4c4b65f1..fa774c9a 100644 --- a/backend/tests/api/fee_groups.rs +++ b/backend/tests/api/fee_groups.rs @@ -238,6 +238,24 @@ async fn a_self_declared_group_is_checked_before_the_first_item(db: PgPool) { .await .unwrap(); assert_eq!(label.as_deref(), Some("Vereinsmitglieder")); + // The rate as settled, even when the group changes afterwards + sqlx::query( + "UPDATE events SET features = jsonb_set(features, '{feeGroups,0,commission}', '7') + WHERE id = $1", + ) + .bind(m.event) + .execute(&db) + .await + .unwrap(); + assert_eq!(m.vendor(seller).await["commissionPercent"], json!(5.0)); + let sales = m + .app + .query("purchases.getMySales", json!({}), Some(&session)) + .await; + assert_eq!( + sales.body["value"][0]["event"]["commissionPercent"], + json!(5.0) + ); let export = m .app .query( @@ -594,3 +612,149 @@ async fn after_the_first_seller_groups_only_get_cheaper(db: PgPool) { "assignment": "selfDeclared" }); assert_eq!(save(json!([cheaper, new])).await["value"], Value::Null); } + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn an_unchecked_group_does_not_count_when_the_helper_role_goes(db: PgPool) { + let m = Market::new(db.clone()).await; + let (seller, _) = m.join("Helfendes Mitglied", Some("members")).await; + let made = m + .app + .mutation( + "eventRoles.addCoOrganizerForEvent", + json!({ "eventId": m.event, "userId": seller, "permissions": [] }), + Some(&m.organizer), + ) + .await; + assert_eq!(made.status, StatusCode::OK, "{}", made.body); + // As helper the helper group applies: nothing to check at the intake + let (product, relation) = m.announced(seller, "Tandem", 100.0).await; + let accepted = m.accept(relation, &m.organizer).await; + assert_eq!(accepted.status, StatusCode::OK, "{}", accepted.body); + m.sell(relation).await; + assert_eq!(m.commission(product).await, 0.0); + + // Without the role: the bazaar's 10 %, not the 5 % of the group nobody checked + let removed = m + .app + .mutation( + "eventRoles.removeCoOrganizerForEvent", + json!({ "eventId": m.event, "userId": seller }), + Some(&m.organizer), + ) + .await; + assert_eq!(removed.status, StatusCode::OK, "{}", removed.body); + assert_eq!(m.commission(product).await, 10.0); + let vendor = m.vendor(seller).await; + assert_eq!(vendor["feeGroup"]["pending"], true, "{vendor}"); + assert_eq!(vendor["commissionPercent"], json!(10.0)); + // Once the team saw the proof + let confirmed = m + .team("feeGroups.confirmFeeGroup", seller, &m.organizer) + .await; + assert_eq!(confirmed.status, StatusCode::OK, "{}", confirmed.body); + assert_eq!(m.commission(product).await, 5.0); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_intake_only_decides_on_groups_still_to_be_checked(db: PgPool) { + let m = Market::new(db.clone()).await; + let helper = fixtures::user(&db, "Helfer").await; + fixtures::role(&db, m.event, helper, "seller").await; + fixtures::role(&db, m.event, helper, "coorganizer").await; + let helper = fixtures::session(&db, helper).await; + + // Put in by the organizer: helpers cannot take it away or confirm it + let (baker, _) = m.join("Bäcker", None).await; + let assigned = m + .app + .mutation( + "feeGroups.assignFeeGroup", + json!({ "eventId": m.event, "sellerId": baker, "groupId": "bakers" }), + Some(&m.organizer), + ) + .await; + assert_eq!(assigned.status, StatusCode::OK, "{}", assigned.body); + for action in ["feeGroups.removeFeeGroup", "feeGroups.confirmFeeGroup"] { + let refused = m.team(action, baker, &helper).await; + assert_eq!(refused.status, StatusCode::FORBIDDEN, "{}", refused.body); + assert_eq!(refused.body["code"], "feeGroup.decidedOrganizerOnly"); + } + assert_eq!(m.vendor(baker).await["feeGroup"]["label"], "Kuchenspender"); + // The organizer may + let removed = m + .team("feeGroups.removeFeeGroup", baker, &m.organizer) + .await; + assert_eq!(removed.status, StatusCode::OK, "{}", removed.body); + + // Without a group there is nothing to take away, and the seller may still choose one + let (seller, session) = m.join("Ohne", None).await; + let none = m.team("feeGroups.removeFeeGroup", seller, &helper).await; + assert_eq!(none.body["code"], "feeGroup.none", "{}", none.body); + let chosen = m + .app + .mutation( + "feeGroups.chooseFeeGroup", + json!({ "eventId": m.event, "groupId": "members" }), + Some(&session), + ) + .await; + assert_eq!(chosen.status, StatusCode::OK, "{}", chosen.body); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn excluding_a_helper_books_their_sales_anew(db: PgPool) { + let desk = Desk::new(db.clone(), groups()).await; + fixtures::event_seller(&db, desk.event, desk.seller, 1, false).await; + fixtures::role(&db, desk.event, desk.seller, "coorganizer").await; + let (product, relation) = desk.item("Lastenrad", 300.0).await; + desk.sell(json!({ "eventProductId": relation })).await; + assert_eq!(desk.purchase(product).await.unwrap().1, 0.0); + let excluded = desk + .app + .mutation( + "eventExclusions.exclude", + json!({ "eventId": desk.event, "userId": desk.seller }), + Some(&desk.team), + ) + .await; + assert_eq!(excluded.status, StatusCode::OK, "{}", excluded.body); + assert_eq!(desk.purchase(product).await.unwrap().1, 30.0); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn a_cheaper_group_gives_back_what_the_desk_took_for_a_direct_sale(db: PgPool) { + let mut features = groups(); + features["directSale"] = json!(true); + let desk = Desk::new(db.clone(), features).await; + fixtures::event_seller(&db, desk.event, desk.seller, 1, false).await; + let (product, relation) = desk.item("Faltrad", 100.0).await; + let sold = desk + .cart(json!([{ "eventProductId": relation }]), None) + .await; + assert_eq!(sold.status, StatusCode::OK, "{}", sold.body); + assert_eq!(sold.body["value"]["taken"], json!(10.0)); + // Made a helper: 0 %, the 10 € the desk took come back with the payout + let made = desk + .app + .mutation( + "eventRoles.addCoOrganizerForEvent", + json!({ "eventId": desk.event, "userId": desk.seller, "permissions": [] }), + Some(&desk.team), + ) + .await; + assert_eq!(made.status, StatusCode::OK, "{}", made.body); + let (_, commission, payout, _, _) = desk.purchase(product).await.unwrap(); + assert_eq!((commission, payout), (0.0, 10.0)); + let vendors = desk + .app + .query( + "eventRoles.getVendorsForEvent", + json!({ "eventId": desk.event }), + Some(&desk.team), + ) + .await; + let vendor = &vendors.body["value"][0]; + // 100 € sales − 0 € commission − 90 € kept from the buyer = 10 € payout + assert_eq!(vendor["receivedDirectly"], json!(90.0), "{vendor}"); + assert_eq!(vendor["payout"], json!(10.0)); +} diff --git a/src/components/events/FeeGroups.test.tsx b/src/components/events/FeeGroups.test.tsx index b95b67fd..396a3f61 100644 --- a/src/components/events/FeeGroups.test.tsx +++ b/src/components/events/FeeGroups.test.tsx @@ -91,7 +91,11 @@ describe('MyFeeGroup', () => { mine = { chosen: 'members', applied: 'members', pending: true, locked: false }; render(); expect(screen.getByText('Deine Gruppe: Vereinsmitglieder')).toBeInTheDocument(); - expect(screen.getByText('Das Team prüft deine Angabe bei der Abgabe.')).toBeInTheDocument(); + expect( + screen.getByText( + /Das Team prüft deine Angabe bei der Abgabe\. Bis dahin gelten die normalen Gebühren/ + ) + ).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Ändern' })); fireEvent.click(screen.getByLabelText(/Nein, ich zahle/)); fireEvent.click(screen.getByRole('button', { name: 'Speichern' })); diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index c3f86c7b..02e4bfa1 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -600,6 +600,8 @@ export type VendorWithCalculations = { excluded?: Exclusion | undefined; /** The fee group whose fees apply (#302) */ feeGroup?: VendorFeeGroup | undefined; + /** The seller's commission in percent: their group's or the bazaar's; once paid out the one settled with */ + commissionPercent: number; }; /** A seller's fee group as the team sees it (#302) */ diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 472aeb39..e6b204b5 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -285,6 +285,7 @@ "decided": "Das Team hat deine Gruppe schon geprüft. Für eine Änderung sprich bitte das Team an.", "locked": "Deine Artikel wurden schon angenommen. Für eine Änderung der Gruppe sprich bitte das Team an.", "none": "Dieser Verkäufer hat keine Gebührengruppe angegeben.", - "organizerOnly": "Nur Veranstalter können Verkäufer einer Gebührengruppe zuordnen." + "organizerOnly": "Nur Veranstalter können Verkäufer einer Gebührengruppe zuordnen.", + "decidedOrganizerOnly": "Diese Gruppe wurde schon geprüft oder zugeordnet. Ändern können sie nur Veranstalter." } } diff --git a/src/locales/de/events.json b/src/locales/de/events.json index be7004f6..922435d2 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -136,7 +136,7 @@ "groupProof": "Nachweis bei der Abgabe: {{hint}}", "groupChecked": "Gibst du bei der Anmeldung an, das Team prüft es bei der Abgabe", "myGroup": "Deine Gruppe: {{group}}", - "myGroupPending": "Das Team prüft deine Angabe bei der Abgabe.", + "myGroupPending": "Das Team prüft deine Angabe bei der Abgabe. Bis dahin gelten die normalen Gebühren und das normale Artikellimit.", "myGroupConfirmed": "Vom Team bestätigt.", "myGroupNone": "Du zahlst die normalen Gebühren.", "myGroupChange": "Ändern", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index d9cea570..7f5d872e 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -1375,7 +1375,7 @@ }, "feeGroups": { "title": "Gebührengruppen (optional)", - "hint": "Eigene Gebühren für eine Gruppe von Verkäufern, z. B. Vereinsmitglieder 5 % statt 10 % oder Helfer ohne Provision. Verkäufer sehen alle Gruppen in den Bedingungen. Bis zu 4 Gruppen, jeder Verkäufer ist in höchstens einer.", + "hint": "Eigene Gebühren für eine Gruppe von Verkäufern, z. B. Vereinsmitglieder 5 % statt 10 % oder Helfer ohne Provision. Verkäufer sehen alle Gruppen in den Bedingungen. Bis zu 4 Gruppen, jeder Verkäufer ist in höchstens einer. Wer zu zwei Gruppen gehört (z. B. Helfer und Mitglied), bekommt die mit der niedrigeren Provision, bei gleicher Provision die mit der niedrigeren Annahmegebühr. Eine hohe Annahmegebühr macht eine Gruppe also nicht teurer als eine mit mehr Provision.", "empty": "Alle Verkäufer zahlen dieselben Gebühren. Mit einer Gruppe zahlen z. B. Vereinsmitglieder oder Helfer weniger.", "unnamed": "Neue Gruppe", "hasError": "Bitte prüfen", @@ -1387,7 +1387,7 @@ "helpers": "Helfer des Basars", "selfDeclaredShort": "Angabe bei der Anmeldung", "helpersShort": "Helfer", - "selfDeclaredHint": "Verkäufer wählen die Gruppe bei der Anmeldung selbst. Bei der Abgabe prüft das Team den Nachweis und bestätigt die Gruppe oder entfernt sie. Vorher kann kein Artikel angenommen werden.", + "selfDeclaredHint": "Verkäufer wählen die Gruppe bei der Anmeldung selbst. Bei der Abgabe prüft das Team den Nachweis und bestätigt die Gruppe oder entfernt sie. Vorher kann kein Artikel angenommen werden. Bis dahin gelten die normalen Gebühren und das normale Artikellimit.", "helpersHint": "Gilt automatisch für alle mit einer Helferrolle, solange sie sie haben. Du kannst auch Helfer ohne Rechte zuordnen. Nur eine Gruppe kann für die Helfer gelten.", "manual": "Nur vom Veranstalter", "manualShort": "vom Veranstalter vergeben", diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 221148af..cd2c0a4f 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -285,6 +285,7 @@ "decided": "The team has already checked your group. Please talk to the team to change it.", "locked": "Your items have already been accepted. Please talk to the team to change your group.", "none": "This seller has not given a fee group.", - "organizerOnly": "Only organizers can put sellers in a fee group." + "organizerOnly": "Only organizers can put sellers in a fee group.", + "decidedOrganizerOnly": "This group has already been checked or was assigned. Only organizers can change it." } } diff --git a/src/locales/en/events.json b/src/locales/en/events.json index 3f7fb99f..dcb8a10b 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -136,7 +136,7 @@ "groupProof": "Proof at the drop-off: {{hint}}", "groupChecked": "You say so when registering, the team checks it at the drop-off", "myGroup": "Your group: {{group}}", - "myGroupPending": "The team checks it at the drop-off.", + "myGroupPending": "The team checks it at the drop-off. Until then the normal fees and item limit apply.", "myGroupConfirmed": "Confirmed by the team.", "myGroupNone": "You pay the regular fees.", "myGroupChange": "Change", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index ccdcdd0f..31d80106 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -1375,7 +1375,7 @@ }, "feeGroups": { "title": "Fee groups (optional)", - "hint": "Own fees for a group of sellers, e.g. club members 5 % instead of 10 % or helpers without commission. Sellers see all groups in the conditions. Up to 4 groups, each seller is in one at most.", + "hint": "Own fees for a group of sellers, e.g. club members 5 % instead of 10 % or helpers without commission. Sellers see all groups in the conditions. Up to 4 groups, each seller is in one at most. Who belongs to two groups (e.g. helper and member) gets the one with the lower commission, at equal commission the one with the lower intake fee. So a high intake fee does not make a group count as dearer than one with more commission.", "empty": "All sellers pay the same fees. With a group, e.g. club members or helpers pay less.", "unnamed": "New group", "hasError": "Please check", @@ -1387,7 +1387,7 @@ "helpers": "Helpers of the bazaar", "selfDeclaredShort": "Given at registration", "helpersShort": "Helpers", - "selfDeclaredHint": "Sellers choose the group themselves when registering. At the drop-off the team checks the proof and confirms or removes the group. Until then no item can be accepted.", + "selfDeclaredHint": "Sellers choose the group themselves when registering. At the drop-off the team checks the proof and confirms or removes the group. Until then no item can be accepted. Until then the normal fees and item limit apply.", "helpersHint": "Applies automatically to everyone with a helper role, as long as they have it. You can also assign helpers without rights. Only one group can apply to helpers.", "manual": "Organizer only", "manualShort": "assigned by the organizer", diff --git a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx index 5a15113b..b0381512 100644 --- a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx @@ -978,17 +978,8 @@ export function ProductManagementPage() { {sellerMode === 'payout' && can('payout') && ( - selectedVendor.feeGroup?.id - ? g.id === selectedVendor.feeGroup.id - : g.label === selectedVendor.feeGroup?.label - )?.commission ?? - event?.commission ?? - 0 - } + // The seller's fee group may have its own commission (#302); paid out: as settled + commissionPercent={selectedVendor.commissionPercent} itemsToReturn={vendorProducts.filter((p) => p.status === 'available')} soldCount={stats.sold} returnedCount={stats.returned} From 74cc3b8f36b628fc4c7166124dc7d1721ca82d99 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Fri, 20 Nov 2026 13:28:57 +0100 Subject: [PATCH 09/10] fix(wizard): the autosave keeps a guest's submitted draft (#302) A change still waiting for the 600 ms autosave could save the draft again after 'Konto anlegen und Basar erstellen', without the submitted mark, so the bazaar was not created after the sign-up. Made the wizard test fail on busy CI runners. Co-Authored-By: Claude Opus 5.5 --- src/pages/organizer/events/EditEventForm.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 0675c30c..a7ca8b48 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -1174,8 +1174,11 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { navigate(`/login?redirect=${encodeURIComponent('/events/new')}`); }; - // Last step without an account: keep the bazaar and create it right after the sign-up + // Last step without an account: keep the bazaar and create it right after the sign-up. + // A change still waiting for the autosave must not save it again without that mark. + const guestSubmitted = useRef(false); const onGuestSubmit = () => { + guestSubmitted.current = true; keepDraft(step, true); navigate(`/register?redirect=${encodeURIComponent(CREATE_DRAFT_PATH)}`); }; @@ -1272,7 +1275,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { clearTimeout(timer); // Not on the first step: nothing is typed yet, and a discarded draft stays gone timer = setTimeout(() => { - if (stepRef.current > 0) keepDraftRef.current(stepRef.current); + if (stepRef.current > 0) keepDraftRef.current(stepRef.current, guestSubmitted.current); }, 600); }); return () => { From 53b31e285f4e643bef501c43f92ec442d838fc9c Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Fri, 20 Nov 2026 13:44:57 +0100 Subject: [PATCH 10/10] feat(fees): choose the fee group in the seller's menu (#302) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the fee group chip in the seller header and the icon buttons in the seller list with a "Gebührengruppe zuordnen" submenu in the seller's "…" menu - Show the header badge as display only; the submenu is organizer-only and hidden once the seller is paid out - Remove the per-row helper permission button from the seller list; the helper edit stays in the "…" menu - Update the component tests and the fee group e2e spec for the new menu path --- src/components/sellers/FeeGroupBadge.tsx | 113 ++++++------------ src/components/sellers/FeeGroupCheck.test.tsx | 88 +++++--------- .../dashboard/ProductManagementPage.tsx | 33 ++--- .../events/dashboard/SellerManagementPage.tsx | 76 ++---------- src/tests/auth/fee-groups.spec.ts | 12 +- 5 files changed, 101 insertions(+), 221 deletions(-) diff --git a/src/components/sellers/FeeGroupBadge.tsx b/src/components/sellers/FeeGroupBadge.tsx index 5b6fc2e0..eed7bcea 100644 --- a/src/components/sellers/FeeGroupBadge.tsx +++ b/src/components/sellers/FeeGroupBadge.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { BadgePercent, ChevronDown } from 'lucide-react'; +import { BadgePercent } from 'lucide-react'; import { toast } from 'sonner'; import { useTranslation } from 'react-i18next'; import type { Id, VendorWithCalculations } from '../../lib/api/types'; @@ -8,15 +8,15 @@ import { api } from '../../lib/api/functions'; import { useMutation } from '../../lib/api/react'; import { getUserFacingErrorMessage } from '../../lib/errors'; import { cn } from '../../lib/utils'; -import { Button } from '../ui/button'; import { - DropdownMenu, - DropdownMenuContent, DropdownMenuLabel, + DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, - DropdownMenuTrigger, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, } from '../ui/dropdown-menu'; /** The seller's fee group next to their name; amber while the intake still checks it. */ @@ -36,11 +36,9 @@ export function FeeGroupBadge({ group }: { group: VendorWithCalculations['feeGro function badgeClass(group: VendorWithCalculations['feeGroup']) { return cn( 'inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-xs font-medium', - !group - ? 'border-dashed text-muted-foreground' - : group.pending - ? 'border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300' - : 'border-primary/20 bg-primary/5 text-primary' + group?.pending + ? 'border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-300' + : 'border-primary/20 bg-primary/5 text-primary' ); } @@ -58,31 +56,24 @@ function BadgeContent({ group }: { group: NonNullable; vendor: VendorWithCalculations; groups: FeeGroup[]; - iconOnly?: boolean; - badge?: boolean; }) { const { t } = useTranslation('organizer'); const assign = useMutation(api.feeGroups.assignFeeGroup); const [busy, setBusy] = useState(false); - if (groups.length === 0) return null; - // Paid out: the group is settled, it only shows - if (vendor.paid) return badge ? : null; + if (groups.length === 0 || vendor.paid) return null; const current = vendor.feeGroup?.byRole ? (vendor.feeGroup.chosen ?? 'none') : (vendor.feeGroup?.id ?? 'none'); - const label = t('sellerFeeGroup.assign'); const choose = async (value: string) => { if (value === current) return; @@ -103,62 +94,30 @@ export function FeeGroupMenu({ }; return ( - - - {badge ? ( - - ) : ( - - )} - - e.stopPropagation()}> - {t('sellerFeeGroup.title')} - - void choose(value)}> - {t('sellerFeeGroup.none')} - {groups.map((group) => ( - - {group.label} - - ))} - - {vendor.feeGroup?.byRole && ( -

- {t('sellerFeeGroup.byRole', { group: vendor.feeGroup.label })} -

- )} -
-
+ + + + {t('sellerFeeGroup.assign')} + + + + {t('sellerFeeGroup.title')} + + void choose(value)}> + {t('sellerFeeGroup.none')} + {groups.map((group) => ( + + {group.label} + + ))} + + {vendor.feeGroup?.byRole && ( +

+ {t('sellerFeeGroup.byRole', { group: vendor.feeGroup.label })} +

+ )} +
+
+
); } diff --git a/src/components/sellers/FeeGroupCheck.test.tsx b/src/components/sellers/FeeGroupCheck.test.tsx index 641c5998..90d63a23 100644 --- a/src/components/sellers/FeeGroupCheck.test.tsx +++ b/src/components/sellers/FeeGroupCheck.test.tsx @@ -6,7 +6,8 @@ import { getFunctionName } from '../../lib/api/functions'; import type { Id, VendorWithCalculations } from '../../lib/api/types'; import type { FeeGroup } from '../../shared/feeGroups'; import { FeeGroupCheck } from './FeeGroupCheck'; -import { FeeGroupBadge, FeeGroupMenu } from './FeeGroupBadge'; +import { FeeGroupBadge, FeeGroupSubMenu } from './FeeGroupBadge'; +import { DropdownMenu, DropdownMenuContent } from '../ui/dropdown-menu'; vi.mock('../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn() })); vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); @@ -85,15 +86,26 @@ describe('FeeGroupBadge', () => { }); }); -describe('FeeGroupMenu', () => { +/** The submenu sits in the seller's open "…" menu. */ +function renderSubMenu(v: VendorWithCalculations, g: FeeGroup[] = groups) { + return render( + + + + + + ); +} + +const openSubMenu = () => + fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Gebührengruppe zuordnen' }), { + key: 'ArrowRight', + }); + +describe('FeeGroupSubMenu', () => { it('puts a seller in a group and takes them out', async () => { - render(); - const open = () => - fireEvent.pointerDown(screen.getByRole('button', { name: 'Gebührengruppe zuordnen' }), { - button: 0, - ctrlKey: false, - }); - open(); + renderSubMenu(vendor()); + openSubMenu(); fireEvent.click(await screen.findByRole('menuitemradio', { name: 'Helfer' })); await waitFor(() => expect(calls['feeGroups.assignFeeGroup']).toHaveBeenCalledWith({ @@ -106,24 +118,10 @@ describe('FeeGroupMenu', () => { }); it('explains a group by role and takes the chosen one out', async () => { - render( - + renderSubMenu( + vendor({ id: 'helpers', label: 'Helfer', pending: false, byRole: true, chosen: 'members' }) ); - fireEvent.pointerDown(screen.getByRole('button', { name: 'Gebührengruppe zuordnen' }), { - button: 0, - ctrlKey: false, - }); + openSubMenu(); expect(await screen.findByText(/gilt durch die Helferrolle/)).toBeInTheDocument(); expect(screen.getByRole('menuitemradio', { name: 'Vereinsmitglieder' })).toBeChecked(); fireEvent.click(screen.getByRole('menuitemradio', { name: 'Keine Gruppe' })); @@ -138,38 +136,10 @@ describe('FeeGroupMenu', () => { }); it('is not offered for paid-out sellers or without groups', () => { - const { container, rerender } = render( - - ); - expect(container).toBeEmptyDOMElement(); - rerender(); - expect(container).toBeEmptyDOMElement(); - }); - - it('as badge: the group opens the choice, "no group" too', async () => { - const { rerender } = render( - - ); - const chip = screen.getByRole('button', { name: 'Gebührengruppe zuordnen: Keine Gruppe' }); - expect(chip).toHaveTextContent('Keine Gruppe'); - fireEvent.pointerDown(chip, { button: 0, ctrlKey: false }); - fireEvent.click(await screen.findByRole('menuitemradio', { name: 'Vereinsmitglieder' })); - await waitFor(() => - expect(calls['feeGroups.assignFeeGroup']).toHaveBeenCalledWith({ - eventId: EVENT, - sellerId: 'u1', - groupId: 'members', - }) - ); - - rerender(); - expect( - screen.getByRole('button', { name: 'Gebührengruppe zuordnen: Vereinsmitglieder' }) - ).toHaveTextContent('Vereinsmitglieder· prüfen'); - - // Paid out: only the badge, nothing to choose - rerender(); - expect(screen.queryByRole('button')).not.toBeInTheDocument(); - expect(screen.getByText('Vereinsmitglieder')).toBeInTheDocument(); + const { unmount } = renderSubMenu(vendor(pending, true)); + expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + unmount(); + renderSubMenu(vendor(), []); + expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); }); }); diff --git a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx index b0381512..3fa21de4 100644 --- a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx @@ -72,7 +72,7 @@ import { } from '../../../../lib/sellerPrintout'; import { SellerIdCheck } from '../../../../components/sellers/SellerIdCheck'; import { FeeGroupCheck } from '../../../../components/sellers/FeeGroupCheck'; -import { FeeGroupBadge, FeeGroupMenu } from '../../../../components/sellers/FeeGroupBadge'; +import { FeeGroupBadge, FeeGroupSubMenu } from '../../../../components/sellers/FeeGroupBadge'; import { useAssignMissingSellerNumbers } from '../../../../hooks/useAssignMissingSellerNumbers'; import { matchingVendors, productMatcher } from '../../../../lib/productSearch'; import { addToCachedCart } from '../../../../lib/checkout'; @@ -227,6 +227,12 @@ export function ProductManagementPage() { !selectedVendor.managedByEventId && event?.organizerId !== selectedVendor._id; const [helperAction, setHelperAction] = useState(null); + // The fee group by hand: organizer only, chosen in the "…" menu like the helper rights + const canChooseFeeGroup = + canLead && + !!selectedVendor && + !selectedVendor.paid && + (event?.features?.feeGroups?.length ?? 0) > 0; const stats = useMemo(() => { const announced = vendorProducts.filter((p) => p.status === 'announced').length; @@ -664,17 +670,7 @@ export function ProductManagementPage() { {selectedVendor.managedByEventId && } {selectedVendor.excluded && } - {/* The group opens its own choice: the header stays one row */} - {canLead ? ( - - ) : ( - - )} +
- - {canManageHelpers && ((!isOwner && v.isHelper) || feeGroups.length > 0) && ( -
- {!isOwner && v.isHelper && ( - setHelperAction({ mode: 'edit', vendor: v })} - /> - )} - } - vendor={v} - groups={feeGroups} - /> -
- )}
); }) @@ -567,25 +533,3 @@ function PaidBadge({ paid }: { paid?: boolean }) { ); } - -/** Changes what the helper may do; the dialog also takes the helper role back. */ -function EditPermissionsButton({ onClick, iconOnly }: { onClick: () => void; iconOnly?: boolean }) { - const { t } = useTranslation('organizer'); - const label = t('sellers.editPermissions'); - return ( - - ); -} diff --git a/src/tests/auth/fee-groups.spec.ts b/src/tests/auth/fee-groups.spec.ts index 7aaf930a..a0ddf8bd 100644 --- a/src/tests/auth/fee-groups.spec.ts +++ b/src/tests/auth/fee-groups.spec.ts @@ -86,10 +86,12 @@ test('a self-declared fee group is chosen at registration and checked at the int await seller.reload(); await expect(seller.getByTestId('my-fee-group')).toContainText('Vom Team bestätigt'); - // The group's chip in the seller's header changes it, here back to no group - const chip = organizer.getByRole('button', { name: /^Gebührengruppe zuordnen/ }); - await expect(chip).toHaveText('Vereinsmitglieder'); - await chip.click(); + // The seller's "…" menu changes the group, here back to no group + const badge = organizer.getByTitle('Gebührengruppe', { exact: true }); + await expect(badge).toHaveText('Vereinsmitglieder'); + await organizer.getByRole('button', { name: /^Weitere Aktionen für / }).click(); + await organizer.getByRole('menuitem', { name: 'Gebührengruppe zuordnen' }).click(); await organizer.getByRole('menuitemradio', { name: 'Keine Gruppe' }).click(); - await expect(chip).toHaveText('Keine Gruppe'); + await expectToast(organizer, /: keine Gruppe$/); + await expect(badge).toBeHidden(); });